當我在代碼中引入產量時,它在 python 中不起作用 (when i introduced yield in code it doesn't work in python)


問題描述

當我在代碼中引入產量時,它在 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_star007qouify)

參考文件

  1. when i introduced yield in code it doesn't work in python (CC BY‑SA 2.5/3.0/4.0)

#yield-return #yield #python-3.x






相關問題

Bagaimana saya bisa membuat `menunggu ...` bekerja dengan `yield return` (yaitu di dalam metode iterator)? (How can I make `await …` work with `yield return` (i.e. inside an iterator method)?)

收益回報使用 (yield return usage)

無法將“<>d__6”類型的對象轉換為“System.Object[]”類型 (Unable to cast object of type '<>d__6' to type 'System.Object[]')

使用 yield return 時 GetEnumerator() 方法會發生什麼? (What happens to GetEnumerator() method when yield return is used?)

抓取回調函數 (Scrapy callback function)

我可以在 VB.NET 中為 IEnumerable 函數實現收益返回嗎? (Can I implement yield return for IEnumerable functions in VB.NET?)

使用具有代碼訪問安全性的 C# 迭代器方法時出現問題 (Problem using C# iterator methods with code access security)

如何使用收益返回和遞歸獲得每個字母組合? (How do I get every combination of letters using yield return and recursion?)

是否可以使用 'yield' 來生成 'Iterator' 而不是 Scala 中的列表? (Is it possible to use 'yield' to generate 'Iterator' instead of a list in Scala?)

yield return 除了 IEnumerable 之外還有其他用途嗎? (Does yield return have any uses other than for IEnumerable?)

這個函數可以用更有效的方式編寫嗎? (Can this function be written in more efficient way?)

當我在代碼中引入產量時,它在 python 中不起作用 (when i introduced yield in code it doesn't work in python)







留言討論