我需要編寫一個帶有兩個函數的Python腳本。一個功能是將(p)的後代孩子還給Take(p)並返回(p)的祖先。recurDescents(p)和recurAncestors(p)
我做了一個腳本,返回(p)的子項。
parent = [("Homer","Bart"),("Homer","Lisa"),("Abe","Homer"),("Bart","Jim"),("Jim","Kim"),("Lisa","Lora")]
def child(p): #definition of child function()
result = []
for x in parent:
if x[0] == p:
print(x[1])
result.append(x[1])
return result
def grandChild (p):
result = []
children = child(p)
for x in children:
for y in parent:
if x == y[0]:
result.append(y(1))
return result
p = "Homer"
children = child(p) # my caller question
print(p, " has child ", children)
我只是不知道該怎麼做。
你return語句縮進錯誤。把它們放在for循環之外。 –