使用Python递归拆分数字范围

-2 投票
1 回答
1719 浏览
提问于 2025-04-17 04:06

我想在Python里写一个递归函数。我写了一个,但它运行得不太对。

我有一组从1到1000的数字,我想把它分成两部分:1到500和501到1000。然后我想继续这样分,直到每部分只剩下20个数字。

这是我尝试的代码:

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)

1 个回答

4

试试这样做,其中 seq 是一个包含数字范围的列表:

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

撰写回答