开发者

Splitting a range of numbers up recursively with Python

开发者 https://www.devze.com 2023-04-12 02:29 出处:网络
I would like to write a recursive function in Python开发者_如何学Go. I have written one but it doesn\'t work correctly.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消