【问题标题】:Returns a boolean value for whether any two distinct numbers in an array add up to an interger返回一个布尔值,判断数组中任意两个不同的数字加起来是否为整数
【发布时间】:2021-04-11 12:54:11
【问题描述】:

我正在练习 Python,我想编写一个函数,它接受一个整数数组 x 和一个整数 y,并返回一个布尔值,用于判断 x 中的任何两个不同的数字加起来是否等于 y,例如:

add_check([1, 1, 2], 2) # Returns True
add_check([1, 1, 2], 3) # Returns True

add_check([2, 3], 4) # Returns False

这是我不完整的解决方案:

def add_check(x: list, y: int):

    # create a dict object and add all the element in the list to the list 
    dictionary = {}
    for i in range(len(x)):
        dictionary.update({x[i]: i})
        #print(dictionary)

    for i in range(len(x)):
        second_num = y - x[i]
        if second_num in dictionary.values():
            second_index = x.index(second_num)
            if i != second_index:
                print(True)
    else:
        print(False)

但是当我运行add_check([1, 1, 2], 2) 时,它会返回True False。 我现在有点迷茫,谁能帮忙,非常感谢。

【问题讨论】:

  • 打印不等于返回。只有 return 会停止函数并将其值提供给调用者。

标签: python python-3.x dictionary arraylist


【解决方案1】:

print 语句只显示一个信息,但代码继续,for/else 结构像这样工作

如果循环中没有使用break 语句,则将执行else 语句

所以你需要在打印True后使用break

def add_check(x: list, y: int):
    dictionary = {}
    for i in range(len(x)):
        dictionary.update({x[i]: i})

    for i in range(len(x)):
        second_num = y - x[i]
        if second_num in dictionary.values():
            second_index = x.index(second_num)
            if i != second_index:
                print(True)
                break
    else:
        print(False)

改进和修复

  • 您可以使用return 而不是print,这样可以停止代码,让调用者完成工作而不是方法会更好

  • dictionary.values() 包含索引,而不是来自x 的值,因此它可能会产生误导,一个值可以是一个索引然后在x 中找不到并引发类似add_check([2, 3], 4) 示例的错误

因此,您可以检查总和的缺失值是否是字典中的键,如果是,则验证它的最后位置(存储在dictionary)不是当前索引

def add_check(x: list, y: int):
    dictionary = {value: i for i, value in enumerate(x)}
    for i, value in enumerate(x):
        second_index = dictionary.get(y - value)
        if second_index and i != second_index:
            return True
    return False

print(add_check([1, 1, 2], 2))  # True
print(add_check([1, 2, 2], 4))  # True
print(add_check([1, 1, 2], 3))  # True
print(add_check([2, 3], 4))     # False

【讨论】:

  • 只是一个快速的后续问题,为什么我们使用if second_index and i != second_index: 而不是if i != second_index:
【解决方案2】:

您的代码混淆了值和索引。例如[11, 3, 4, 7],元素的索引分别为0, 1, 2, 3,但值为[11, 3, 4, 7]

您的目标是将 值相加。我建议完全不使用索引进行编码:使用 for value in x 而不是 for i in range(len(x)) ,既可以避免这种混乱,也可以使用更多 Pythonic 代码。

【讨论】:

    猜你喜欢
    • 2018-12-20
    • 2013-11-05
    • 1970-01-01
    • 2020-07-24
    • 2017-07-09
    • 2020-08-30
    • 2013-09-29
    • 2012-11-14
    相关资源
    最近更新 更多