[Tutor] Question regarding Python loops
Peter Otten
__peter__ at web.de
Thu Apr 10 10:37:54 CEST 2014
Conner Crowe wrote:
> To whom this may concern:
>
> I am struggling on two questions:
> Problem 2.
> Suppose you are given a function leave(minute) which returns the number of
> students that leave an exam during its mth minute. Write a function
> already_left(t) that returns the number of students that left at or before
> minute t of the exam.
>
> Example code:
> # To simplify testing, you may wish to define a stand-in function for
> # leave that behaves predictably
> # Here's one possible stand-in:
> def leave(minute):
> if minute > 0:
> return minute
> return 0
>
> def already_left(t):
> # Your code goes here
>
> Example usage:
> print already_left(1)
> print already_left(4)
>
> Example output:
> 1
> 10
>
> So far for this i have:
> def leave(minute):
> if minute > 0:
> return minute
> elif minute=0:
> return 0
> def already_left(i):
> for i in range(0,t):
> leave(i)
Hint: You are throwing away the result of the leave() call. But what you
want is to add up the results of all calls to leave() in the loop.
Once you have that total you need already_left() to return it so that
> print already_left(8)
> print already_left(4)
will print it instead of None (the default when you do not explicitly return
anything from a function).
> Problem 3.
How would you solve that with pen and paper?
More information about the Tutor
mailing list