gpt4 book ai didi

Python 列表和屈服

转载 作者:太空宇宙 更新时间:2023-11-04 01:39:30 25 4
gpt4 key购买 nike

我对 Project Euler 问题 24 有以下(正确的)解决方案。我对 Python 比较陌生,并且在 Python 的几个要点上感到困惑。

先上代码:

# A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
# If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
# The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210
# What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

permutations = []

def getLexicographicPermutationsOf(digits, state):
if len(digits) == 0:
permutations.append(str(state))

for i in range(len(digits)):
state.append(digits[i])
rest = digits[:i] + digits[i+1:]
getLexicographicPermutationsOf(rest, state)
state.pop()

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
getLexicographicPermutationsOf(digits, [])
print(permutations[999999])

我的第一个问题是关于 yield 语句的使用。我的第一个设计不是在顶部定义排列列表,而是替换 permutations.append符合 yield state .然后我会将方法的返回值分配给一个变量。我检查了一下,返回值是一个生成器,正如预期的那样。但是,遍历其内容表明没有生成任何值。我在这里遗漏了什么吗?

我的第二个查询是关于最后一行 - 从列表中打印一个值。当我运行它时,它输出的值就好像它是一个列表,而它应该是一个字符串。事实上,替换 print(permutations[999999])print(type(permutations[999999]))结果 < class str> .那么为什么它被打印成一个列表(用方括号,用逗号分隔)?

最佳答案

当您递归调用 getLexicographicPermutationsOf 时,您也需要从那里产生结果。

for result in getLexicographicPermutationsOf(rest, state):
yield result

permutations.append(str(state)) 创建 state 的字符串表示,这是一个列表。这解释了为什么它在打印时看起来像一个列表。

关于Python 列表和屈服,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6598726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com