这非常糟糕和混乱,我对此很陌生,请帮助我。
基本上,我试图从列表中找到两个数字加起来等于目标数字。
我设置了一个带有
lst = [2, 4, 6, 10]
和目标值 target = 8
的示例。本例中的答案是 (2, 6)
和 (6, 2)
。
下面是我的代码,但它又长又难看,我确信有更好的方法来做到这一点。您能看看我可以如何改进下面的代码吗?
from itertools import product, permutations
numbers = [2, 4, 6, 10]
target_number = 8
two_nums = (list(permutations(numbers, 2)))
print(two_nums)
result1 = (two_nums[0][0] + two_nums[0][1])
result2 = (two_nums[1][0] + two_nums[1][1])
result3 = (two_nums[2][0] + two_nums[2][1])
result4 = (two_nums[3][0] + two_nums[3][1])
result5 = (two_nums[4][0] + two_nums[4][1])
result6 = (two_nums[5][0] + two_nums[5][1])
result7 = (two_nums[6][0] + two_nums[6][1])
result8 = (two_nums[7][0] + two_nums[7][1])
result9 = (two_nums[8][0] + two_nums[8][1])
result10 = (two_nums[9][0] + two_nums[9][1])
my_list = (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10)
print (my_list)
for i in my_list:
if i == 8:
print ("Here it is:" + str(i))
对于列表中的每个数字,您可以查找其补数(与前一个数字相加时将得到所需的
target
总和)。如果存在,则获取该对并退出,否则继续。
这看起来像下面这样:
numbers = [2, 4, 6, 10]
target_number = 8
for i, number in enumerate(numbers[:-1]): # note 1
complementary = target_number - number
if complementary in numbers[i+1:]: # note 2
print("Solution Found: {} and {}".format(number, complementary))
break
else: # note 3
print("No solutions exist")
产生:
Solution Found: 2 and 6
备注:
numbers[i+1:]
。之前的数字已经核对过。切片的一个积极的副作用是,例如列表中存在一个 4
,但不会给出目标值 8
的一对。else
循环中对 for
的误解和经常令人困惑的使用。仅当循环不是由 else
突然结束时,break
才会触发。如果您可以接受例如
4
- 4
解决方案,即使列表中有 单个 4
,您也可以进行如下修改:
numbers = [2, 4, 6, 10]
target_number = 8
for i, number in enumerate(numbers):
complementary = target_number - number
if complementary in numbers[i:]:
print("Solution Found: {} and {}".format(number, complementary))
break
else:
print("No solutions exist")
列表理解在这里效果很好。试试这个:
from itertools import permutations
numbers = [2, 4, 6, 10]
target_number = 8
solutions = [pair for pair in permutations(numbers, 2) if sum(pair) == 8]
print('Solutions:', solutions)
基本上,这个列表理解会查看
permutations(numbers, 2)
返回的所有对,但只保留总和等于 8 的对。
执行此操作的最简单的通用方法是迭代列表,并针对每个项目迭代列表的其余部分以查看它是否等于目标值。这样做的缺点是它是一个 O(n^2) 操作。我不知道是否有更有效的解决方案。我不能 100% 确定我的语法是否正确,但它应该如下所示:
done = False
for i, val in enumerate(numbers):
if val >= target_number:
continue
for j, val2 in enumerate(numbers, i+1):
if val + val2 == target_number:
print ("Here it is: " + str(i) + "," + str(j))
done = True
break
if done:
break
当然,您应该将其创建为返回结果的函数,而不仅仅是打印它。这将消除对“完成”变量的需要。
如果您试图找到具有重复值的长列表的多个整数的答案,我建议使用 freezeset。 “选中”的答案只会得到第一个答案,然后停止。
import numpy as np
numbers = np.random.randint(0, 100, 1000)
target = 17
def adds_to_target(base_list, target):
return_list = []
for i in range(len(base_list)):
return_list.extend([list((base_list[i], b)) for b in base_list if (base_list[i] + b)==target])
return set(map(frozenset, return_list))
# sample output
{frozenset({7, 10}),
frozenset({4, 13}),
frozenset({8, 9}),
frozenset({5, 12}),
frozenset({2, 15}),
frozenset({3, 14}),
frozenset({0, 17}),
frozenset({1, 16}),
frozenset({6, 11})}
1) 在第一个 for 循环中,包含两个总和等于目标值的整数的列表被添加到“return_list”,即创建一个列表列表。
2)然后 freezeset 取出所有重复对。
%timeit adds_to_target(numbers, target_number)
# 312 ms ± 8.86 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
您可以使用列表理解在一行中完成此操作,如下所示:
from itertools import permutations
numbers = [2, 4, 6, 10]
target_number = 8
two_nums = (list(permutations(numbers, 2)))
result=[i for i in two_nums if i[0]+i[1] == target_number]
[(2,6) , (6,2)]
如果您想要一种无需 itertools 即可有效完成此操作的方法 -
numbers = [1,3,4,5,6,2,3,4,1]
target = 5
number_dict = {}
pairs = []
for num in numbers:
number_dict[num] = number_dict.get(num, 0) + 1
complement = target - num
if complement in number_dict.keys():
pairs.append((num, complement))
number_dict.pop(num)
number_dict.pop(complement)
就是这么简单:)
def func(array, target):
flag = 0;
for x in array:
for y in array:
if (target-x) == y and x != y:
print(x,y)
flag = 1
break
if flag ==1:
break
import pandas as pd
Filename = "D:\\python interview\\test.txt"
wordcount_dict = dict()
#input("Enter Filename:")
list_ = [1,2,4,6,8]
num = 10
for number in list_:
num_add = number
for number_ in list_:
if number_ + num_add == num and number_ != num_add :
print(number_ , num_add)
l = [2, 4, 6, 10]
t = 8
for i in range(len(l)):
for j in range(i, len(l)):
if l[i]+l[j] == t and (l[i] != l[j]):
print(l[i], l[j])
print(l[j], l[i])