問題描述
當我在代碼中引入產量時,它在 python 中不起作用 (when i introduced yield in code it doesn't work in python)
在下面的代碼中,在 permute 函數的 if 部分。如果我嘗試使用 yield 它不起作用但是如果我使用 print 它可以工作嗎?有人可以代碼有什麼問題嗎?提前致謝!
def permute(li,l,r):
if l==r:
ele = ''.join(li)
print(ele)
yield ele
else:
for i in range(l,r+1):
#print(i)
li[i],li[l]=li[l],li[i]
permute(li,l+1,r)
li[i],li[l]=li[l],li[i]
class Solution:
def find_permutation(self, S):
# Code here
s = list(S)
f = []
for i in permute(s,0,len(s)‑1):
print(i)
f.append(i)
return f
if name == 'main':
t=int(input())
for i in range(t):
S=input()
ob = Solution()
ans = ob.find_permutation(S)
for i in ans:
print(i,end=" ")
print()
</code></pre>
參考解法
方法 1:
When performing a recursive call of a function that yields results you need to use yield from
before your recursive call. Otherwise the data yielded by your recursive calls will be ignored:
def permute(li,l,r):
if l==r:
ele = ''.join(li)
yield ele
else:
for i in range(l,r+1):
li[i],li[l]=li[l],li[i]
yield from permute(li,l+1,r) # change here
li[i],li[l]=li[l],li[i]
(by morning_star007、qouify)
參考文件