I'm having a very odd problem. I wrote a method that determines the degree of a formula describing a set of numbers, when given the said set. The method is fairly simple, I've added in a couple of lines for debugging purposes:
def getdeg(numlist, cnt): #get the degree of the equation describing numlist
count = cnt #initial run should be with cnt as 0
templist = []
for i in range(len(numlist) - 1): #exclude the last item (which doesn't have an item after it)
templist.append(numlist[i+1] - numlist[i]) #append the val of index i+1 minus index i
count += 1
print(templist)
if not allEqual(templist):
print("Not all equal, iterating again")
getdeg(templist, count)
else:
print(count)
return count
def allEqual(numlist):
if len(numlist) == 1:
return True
for i in range(len(numlist) -1):
if not (numlist[i] == numlist[i+1]):
return False
return True
Now, I'm running this on a set of numbers I KNOW to be described by a 3rd-degree equation, like so:
x = getdeg([2, 8, 9, 11, 20], 0)
print(x)
Fairly simple, yes? Except when you run this, it prints out the following:
[6, 1, 2, 9]
Not all equal, iterating again
[-5, 1, 7]
Not all equal, iterating again
[6, 6]
3
None
Everything is looking good, right up until that "None." What is it doing there? I would assume that the else
conditional isn't being executed, but it's printing out 3 just fine, so it obviously is. That also means that the program "knows" what the value of count
is, but it's not returning it right. Could someone enlighten me as to what on earth is going on?
if not allEqual(templist):
print("Not all equal, iterating again")
getdeg(templist, count)
Remember, when a method recursively calls itself, you still need to explicitly return
the value if you want a value to be returned.
if not allEqual(templist):
print("Not all equal, iterating again")
return getdeg(templist, count)
您还需要在if子句中返回一个值。
return getdeg(templist, count)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.