python - 使用 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 的单独数字。我将如何更改此代码?谢谢!
解决方案
您应该在没有正在测试的元素的情况下遍历数组:
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)
推荐阅读
- java - 如何防止使用静态分析工具在代码中使用指定的类/方法?
- c# - 从运行 C# Windows 应用程序的 Docker 容器访问主机文件夹路径
- javascript - 空() div + 变量
- angular - Angular Material 单元测试 - 找不到 MatHarness 元素
- embedded - 如何决定何时在浮点数上使用定点算法?
- javascript - HTTP POST 请求适用于 Postman,但不适用于我的 Web 应用程序的 JavaScript 提取
- angular - 使用 ng-packagr 制作 Angular mono-repo 库
- python - 无法在 KIVY Python 中打印取自 kivy.uix.textinput.TextInput 的文本
- javascript - 选择具有相同属性 data-img_key="bull3" 的所有行
- excel - 无法在 Excel 中断开链接 - VBA