python生成器中的TypeError

定义一个生成器函数权限,该功能接受一个数字列表和一个非负整数n。实现该函数,以便它使用lst元素生成长度恰好为n的所有排列。假设lst的元素是唯一的,并且n

ttt = Tk()
ttt.title("Tic Tac Toe")
w = Canvas(ttt,width = 902,height = 902)
w.configure (bg =  "white")
w.pack()

m = [[0,0],[0,0]]

def drawx(event):
    x,y = event.x,event.y
    w.create_line(49,49,249,fill = "black")
    w.create_line(49,fill = "black")

def drawo(event):
    x2,y2 = event.x,event.y
    x0 = x2 - 100
    y0 = y2 - 100
    x1 = x2 + 100
    y1 = y2 + 100
    return w.create_oval(x0,y0,x1,y1)

w.create_line(0,300,901,fill = "black") 
w.create_line(0,601,fill = "black")
w.create_line(300,fill = "black")
w.create_line(601,fill = "black")
diaoqichao 回答:python生成器中的TypeError

问题所在

yield from lst 

这里将产生列表的每个元素,该元素是int的,不能在循环中使用

for p in perms(lst,n-1)

正确且可行的解决方案:

def perms(lst,n):
"""
>>> g1 = perms([1,2,3],2)
>>> print(list(g1))
[[1,2],[1,[2,1],[3,2]]
"""

if n == 0:
    yield []
elif n == 1:
    for elem in lst:
        yield [elem]
else:
    for p in perms(lst,n-1):
        for e in lst:
            if e not in p:
                yield p + [e]
,

首次调用for p in perms(lst,n-1):for p in perms([1,2-1)相同时,由于您的perms([1,2-1)yield from lst不会返回列表,而是返回整数。 yield from lst仅返回可迭代元素。 因此,for p in perms(lst,n-1):首次调用时与for p in 1:相同,这当然会引发错误。

本文链接:https://www.f2er.com/2792106.html

大家都在问