質問

I am not understanding why the below code is falling into an infinite loop when the 'start' argument of totalArea is 0. I have been watching the code run in Python Tutor, and j executes through value of Stop -1, but then resets to 0 without moving onto value of Stop.

import math
def totalArea(start, stop, step):
    def f(x):
        return 10*math.e**(math.log(0.5)/5.27 * x)

    area = 0.0
    j = start

    while j <= len(range(start, stop)):

        for j in range(start, stop):
            area += float(step) * f(j)

    print area

totalArea(0, 11, 1)
役に立ちましたか?

解決

while j <= len(range(start, stop)):
    for j in range(start, stop):

Every time the for loop ends, j = 10

len(range(start, stop)) is 11

So j <= len(range(start, stop)) forever

The while loop seems entirely superfluous. Try removing it entirely:

def totalArea(start, stop, step):
    def f(x):
        return 10*math.e**(math.log(0.5)/5.27 * x)

    area = 0.0
    j = start

    for j in range(start, stop):
        area += float(step) * f(j)

    print area

他のヒント

Within the outer (while) loop, len(range(start,stop) is a constant (11). Within the inner (for) loop, j takes on the values 0 to 10 (per the help for range:

Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]

)

Why not take out the outer while loop?

Let's say start=0 and stop=11. Then len(range(start,stop)) is 11, the length of [0,1,2,3,4,5,6,7,8,9,10]. Inside the while loop, j iterates over the values 0 through 10. As you can see, j never exceeds 11, so the while loop never terminates.

The range function returns a list that doesn't include the end value:

>> range(5)
[0, 1, 2, 3, 4]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top