Python 3.x while循环和逻辑问题的返回语句

Python 3.x while循环和逻辑问题的返回语句,python-3.x,while-loop,return,Python 3.x,While Loop,Return,我很不好意思问这个问题,但我似乎无法返回函数的正确结果。基本上,我可以对函数进行编程,以处理解决方案或无解决方案,但不能同时处理两者 def sum_pair(l, t): l.sort() s = 0 # start index e = len(l) - 1 # last index while s < e: if (l[s] + l[e] == t): a, b = l[s], l[e]

我很不好意思问这个问题,但我似乎无法返回函数的正确结果。基本上,我可以对函数进行编程,以处理解决方案或无解决方案,但不能同时处理两者

def sum_pair(l, t):
    l.sort()
    s = 0 # start index
    e = len(l) - 1 # last index

    while s < e:
        if (l[s] + l[e] == t):
            a, b = l[s], l[e]
            return a, b
        elif (l[s] + l[e] < t):
            s = + 1
        else:
            e -= 1
    return a,b # return (0,0) !no result or return (n,n) if result

l1 = [4, 3, 5, 7, 8]
target = 20 # No solution
print(sum_pair(l1, target))
定义和对(l,t): l、 排序() s=0#开始索引 e=len(l)-1#最后一个索引 而s 基本上,如果没有解,我会尝试返回(0,0),但是如果它们和目标值相加,我需要返回(n,n)。如果可能的话,我想避免使用条件逻辑

我猜我有一个范围问题

提前感谢所有人

  • 这个问题不需要a和b
  • s=+1
    中有一个打字错误,它将是
    s+=1
  • 定义和对(l,t): l、 排序() s=0#开始索引 e=len(l)-1#最后一个索引 而s
    这对我来说很好。

    以下是我如何编辑您的代码:

    def sum_pair(l, t):
        l.sort()
        s = 0 # start index
        e = len(l) - 1 # last index
    
        a, b = 0, 0 # set default return value
        while s < e:
            if (l[s] + l[e] == t):
                a, b = l[s], l[e]
                break
            elif (l[s] + l[e] < t):
                s += 1 # you typoed this line
            else:
                e -= 1
        return a, b
    l1 = [4, 3, 5, 7, 8]
    target = 10 # No solution
    print(sum_pair(l1, target))
    
    定义和对(l,t): l、 排序() s=0#开始索引 e=len(l)-1#最后一个索引 a、 b=0,0#设置默认返回值 而s
    我不太确定如果有多个答案该怎么办。通过这种方式,它接受
    a

    的最小值对。我不明白您实际遇到了什么问题。如果没有找到解决方案,为什么不能
    返回(0,0)
    ?你为什么有
    a
    b
    呢。在while循环2之前声明并定义
    a=0和b=0
    s+=1
    not
    s=+1
    @khelwood如果我将目标更改为12,例如(有一个解决方案),它仍然返回(0,0),那么您的实际问题是函数没有找到解决方案吗?如果你修正了
    s=+1
    打字错误怎么办?@khelwood不会改变逻辑。如果我删除了最终返回并得到了一个解决方案,那么它将正确地从If语句返回。但避免无限时间(没有解决方案)的唯一方法是获得该回报。但我不能用解决方案让它那样工作。谢谢你,我经历了一些非常奇怪的事情。我的函数不断产生一个具有相同逻辑的无限循环,但我将它移到了另一个文件,它成功了?谢谢,我遇到了一些非常奇怪的事情。我的函数不断产生一个具有相同逻辑的无限循环,但我将它移到了另一个文件中,它成功了。