gpt4 book ai didi

python - 用可迭代的东西替换函数

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:17 26 4
gpt4 key购买 nike

简而言之。我该如何编写除此之外的其他内容:for another in combinationOfK(K-1, L[i+1:]): 我的函数 combinationOfK(...) 不可迭代。

我正在尝试理解 here 中的代码,解决方案。 问题 26:生成从列表的 N 个元素中选择的 K 个不同对象的组合
我知道 yield 的作用。但我试图编写没有 yield 语句的代码。代码 with yield statement 是这样的。

def combination(K, L):
if K<=0:
yield []
return
for i in range(len(L)):
thisone = L[i:i+1]
for another in combination(K-1, L[i+1:]):
yield thisone + another

The question, yield-keyword-explained让我想到我可以取代 yield。他们提供的收据对我不起作用,是:

When you see a function with yield statements, apply this easy trick to understand what will happen:

  1. Insert a line result = [] at the start of the function.
  2. Replace each yield expr with result.append(expr).
  3. Insert a line return result at the bottom of the function.
  4. Yay - no more yield statements! Read and figure out code.
  5. Revert function to original definition.

使用它来获取代码而不产生 yield 给我这个。代码不工作(函数不可迭代)。 我必须编写什么才能让这段代码在没有 yield 的情况下运行?

def combinationOfK(K,L):
result = []
if K <= 0:
result.append([])
return
for i in range(len(L)):
thisone = L[i:i+1]
for another in combinationOfK(K-1, L[i+1:]): # the error
result.append(thisone + another)
return result

我正在使用这段代码来测试功能,

the_list = ['a','b','c','d','e']
print list(combinationOfK(2, the_list))

引发错误 TypeError: 'NoneType' object is not iterable

最佳答案

问题是您的原始代码使用了 return以一种不寻常的方式。

def combination(K, L):
if K<=0:
yield []
return # <--- hmmm

大多数时候你不会看到return在发电机中,因为您并不经常需要它。通常,生成器只是在最后“掉线”;解释器到达生成器的末尾而没有遇到 return语句,然后它知道抛出 StopIteration .

这种情况下,代码编写者插入了一个return声明“加快”进程。当K <= 0 ,没有更多的工作要做,所以生成器可以抛出 StopIteration -- 但没有 return声明,它将进入 for循环,产生不正确的结果。在我看来,更清晰的方法应该是这样的:

def combination(K, L):
if K<=0:
yield []
else:
for i in range(len(L)):
thisone = L[i:i+1]
for another in combination(K-1, L[i+1:]):
yield thisone + another

现在转换按预期进行:

def combination2(K, L):
result = []
if K <= 0:
result.append([])
else:
for i in range(len(L)):
thisone = L[i:i + 1]
for another in combination2(K - 1, L[i + 1:]):
result.append(thisone + another)
return result

关于python - 用可迭代的东西替换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11616080/

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