gpt4 book ai didi

python - 递归 - Python - 为什么 print(Foo) 显示的内容与 print(FunctionReturningFoo()) 不同

转载 作者:行者123 更新时间:2023-12-01 01:14:34 25 4
gpt4 key购买 nike

为什么 print(foo) 显示的内容与 print(functionreturningthesame()) 不同

查看输出,打印函数中的数组显示正确答案,但打印函数的返回结果却没有。我可能对递归迭代感到困惑......

def AreNotOpposite(a,b):
if a == "NORTH" and b == "SOUTH":
return False
if a == "SOUTH" and b == "NORTH":
return False
if a == "WEST" and b == "EAST":
return False
if a == "EAST" and b == "WEST":
return False
return True

def canBeBetter(arr):
for i in range(len(arr)-1):
if not AreNotOpposite(arr[i],arr[i+1]):
return True
return False

def dirReduc(arr):
re = []
avoid = -1
for i in range(len(arr)):
if avoid == i:
continue
if i+1 == len(arr):
re.append(arr[i])
elif AreNotOpposite(arr[i],arr[i+1]):
re.append(arr[i])
else: #do not append neither the nextone
avoid = i+1
if canBeBetter(re): #can reduce more?
dirReduc(re)
else:
print(re)
return re

print (dirReduc(['NORTH', 'WEST', 'EAST','SOUTH', 'NORTH','SOUTH','EAST','NORTH']))

输出:

['EAST', 'NORTH']
None

最佳答案

您需要返回递归调用的结果(否则您的函数将到达逻辑末尾并简单地返回None):

if canBeBetter(re):  #can reduce more?
return dirReduc(re)
else:
print(re)
return re

关于python - 递归 - Python - 为什么 print(Foo) 显示的内容与 print(FunctionReturningFoo()) 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54480578/

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