I would like to write a recursive function in Python开发者_如何学Go. I have written one but it doesn't work correctly.
I have a range of numbers from 1 to 1000 and I want cut it into two parts 1 to 500 and 501 to 1000. Then I want to do this recursively until there are only 20 numbers in each part.
Here is my attempt:
mw = range(1,1000)
def cuter(mw):
if len(mw)<20:
return False
else:
cut=int(len(mw)/2)
number.append(mw[0])
number.append(cut)
number.append(mw[-1])
return cuter(mw)
cuter(mw)
Try something like this, where seq
is a list with the range of numbers:
def cutter(seq):
n = len(seq)
if n <= 20:
# here the recursion stops, do your stuff with the sequence
return
a = cutter(seq[:n/2])
b = cutter(seq[n/2:])
# combine the answer from both subsequences
return
精彩评论