Python 中项目欧拉 37 的循环列表

2 投票
1 回答
1109 浏览
提问于 2025-04-18 00:18

我在做 Project Euler 37 的题目。

我需要循环一个列表。

输入是:2345 # 在函数内部转换成列表

期望的输出是:[[3,4,5,2],[4,5,2,3],[5,2,3,4],[2,3,4,5]]

这是我为此写的函数:

def circulate(n):           #2345
    lst=list(str(n))          #[2,3,4,5]
    res=[]
    for i in range(len(lst)):
        temp=lst.pop(0)
        lst.append(temp)
        print lst             #print expected list 
        res.append(lst)       #but doesn't append as expected
    return res
print circulate(2345)

我的输出是:

['3', '4', '5', '2']
['4', '5', '2', '3']
['5', '2', '3', '4']
['2', '3', '4', '5']
[['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5']]

这个函数每次都能正确打印出列表,但没有像我预期的那样添加内容。

我哪里做错了?

1 个回答

3

你需要把你的列表的副本添加到res中:

res.append(lst[:])

你之前添加的是正在被修改的列表的引用;所有的引用都会反映出对这个对象所做的改变。

你可能想看看collections.deque();这个双端列表对象支持高效的旋转操作,并且有一个.rotate()的方法:

from collections import deque

def circulate(n):
    lst = deque(str(n))
    res = []
    for i in range(len(lst)):
        lst.rotate(1)
        res.append(list(lst))
    return res

撰写回答