首页 > 解决方案 > 使用 for in 循环解决简单的 Python 挑战

问题描述

"""
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

"""
numbers = [7, 15, 17]
k = 14

def add_to_k(numbers_list,k_value):
    truth = False
    for i in numbers_list:
        for l in numbers_list:
            added = i + l
            if added == k_value:
                num1 = i
                num2 = l
                truth = True
    if truth == True:
        print("Two numbers in the list added together is 17. " + str(num1) + " " + str(num2))
    else:
        print("Sorry, none give " + str(k_value))
add_to_k(numbers,k)

按照上面评论中的提示,我尝试了这个挑战。但是,我意识到它会将列表的第一个数字添加两次,尽管我想找到两个加起来为 k 的单独数字。我将如何更改此代码?谢谢!

标签: python

解决方案


您应该在没有正在测试的元素的情况下遍历数组:

numbers = [7, 7, 17]
k = 14

def add_to_k(numbers_list,k_value):
    truth = False
    for i in numbers_list:
        y = numbers_list[:]  # fastest way to copy
        y.remove(i)
        for l in y:
            added = i + l
            if added == k_value:
                num1 = i
                num2 = l
                truth = True
    if truth == True:
        print("Two numbers in the list added together is "+str(k_value)+ ":  " + str(num1) + "," + str(num2))
    else:
        print("Sorry, none give " + str(k_value))
add_to_k(numbers,k)

输出:

 Two numbers in the list added together is 14:  7,7

或者,如果想要另一种选择:

import itertools as it
numbers = [12, 7, 17]
k = 19

def add_to_k(numbers_list,k_value):
    results = {i:sum(i) for i in list(it.combinations(numbers_list, 2))}
    if any(val==k_value for val in results.values()):
        print(f'Two numbers in the list added together is {k_value}:{list(results.keys())[list(results.values()).index(k_value)] }')
    else:
        print(f'Sorry, none give {k_value}')
    
add_to_k(numbers,k)

输出

Two numbers in the list added together is 19:(12, 7)

推荐阅读