gpt4 book ai didi

python不能返回变量但可以打印

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:14 24 4
gpt4 key购买 nike

所以我遇到了一个奇怪的问题。

def findFourPlus(itemCount, seq, goal):
goalDifference = float("inf")
closestPartial = []
hello = subset_sum(itemCount, seq, goal, goalDifference, closestPartial, partial=[])
return hello #doesn't return value from subset_sum()

def subset_sum(itemCount, seq, goal, goalDifference, closestPartial, partial):
s = sum(partial)

# check if the partial sum is equals to target
if(len(partial) == itemCount):
if s == goal:
print("FOUND YAA")
return partial #right now doesn't return anything. I intend for it to break out of this function as soon as it finds one pair of solution.


else:
if( abs(goal - s) < goalDifference):
#print(abs(goal-s), goalDifference, closestPartial)
goalDifference = abs(goal - s)
closestPartial[:] = partial
#print(abs(goal-s), goalDifference, closestPartial)
return closestPartial

for i in range(len(seq)):
n = seq[i]
remaining = seq[i+1:]
print(subset_sum(itemCount, remaining, goal, goalDifference, closestPartial, partial + [n]))

在 subset_sum() 函数中,我可以打印出 partial 变量,它会返回给我正确的值

>>> findFourPlus(3, [1,2,3,4,5,6,7,8,9,10], 20)
FOUND YAA
[1, 9, 10]
FOUND YAA
[2, 8, 10]
FOUND YAA
[3, 7, 10]
FOUND YAA
[3, 8, 9]
FOUND YAA
[4, 6, 10]
FOUND YAA
[4, 7, 9]
FOUND YAA
[5, 6, 9]
FOUND YAA
[5, 7, 8]

但是,如果我将 print(partial) 行更改为 return partial,它仍然会打印出 FOUNDYAA 行,因为它已打印,但不会返回部分

>>> findFourPlus(3, [1,2,3,4,5,6,7,8,9,10], 20)
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA

在编写 findFourPlus 和 subset_sum 之前,我编写了其他函数,当我尝试返回某些内容时,这些函数运行良好。我在这里做错了什么?

编辑:我在这里似乎让读者感到困惑。我最终要做的是通过调用 findFourPlus() 函数将整数集(列表)存储在一个变量中。假设我想看看列表 [1,2,3,4,5] 中的任意两个加起来是否等于 5,我会调用 findFourPlus(2, [1,2,3,4 ,5], 5),它有望返回给我 [1, 4]。有了它,我可以通过调用将答案 [1,4] 存储到一个变量中,比如答案

answer = findFourPlus(2, [1,2,3,4,5], 5) // if I call answer, it'll return to me [1,4]

一个例子:

>>> a = findFourPlus(2, [1,2,3,4,5], 6) # prints out everything, which is good for test cases
[1, 2]
[1, 3]
[1, 4]
FOUND YAA
[1, 5]
None
[2, 3]
FOUND YAA
[2, 4]
[2, 5]
None
[3, 4]
[3, 5]
None
[4, 5]
None
None
>>> a # doesn't return anything when called
>>>

打印都是为了确保我的逻辑是正确的。很抱歉造成混淆,但希望这能澄清问题!

最佳答案

当你执行一个函数时,它不会自动将它的返回值转储到输出中,所以在你的 for 循环中,

for i in range(len(seq)):
n = seq[i]
remaining = seq[i+1:]
print(subset_sum(itemCount, remaining, goal, goalDifference, closestPartial, partial + [n]))

关于python不能返回变量但可以打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25980180/

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