这是非常糟糕且混乱的地方,我是新手,请帮助我。
基本上,我试图从列表中找到两个数字,这些数字加起来等于目标数字。
我用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))
答案 0 :(得分:6)
对于列表中的每个数字,您都可以查找他的补码(将数字加到上一个将得出所需的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")
答案 1 :(得分:1)
您可以像下面这样用列表理解功能在同一行中完成此操作:
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)]
答案 2 :(得分:1)
执行此操作的最简单的常规方法是遍历列表,并针对每个项目遍历列表的其余部分以查看其是否合计为目标值。缺点是它是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
当然,您应该将此函数创建为返回结果的函数,而不仅仅是打印结果。这样就无需使用“完成”变量。
答案 3 :(得分:1)
列表理解将在这里很好地工作。试试这个:
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的对。
答案 4 :(得分:1)
如果您尝试使用长列表包含重复的值来查找多个整数的答案,建议您使用Frozenset。 “已选中”的答案只会得到第一个答案,然后停止。
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)然后,frozenset会取出所有重复的对。
%timeit adds_to_target(numbers, target_number)
# 312 ms ± 8.86 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
答案 5 :(得分:0)
如果您想要一种无需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)
答案 6 :(得分:0)
这很简单:)
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
答案 7 :(得分:0)
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)
答案 8 :(得分:-1)
n 是所需的总和,L 是列表。基本上,您进入循环内部,然后从 no 到列表末尾迭代下一个循环。如果列表中的 L[i],L[j] 索引加起来为 n 并且如果 L[i]!=L[j] 打印它。
numbers=[1,2,3,4,9,8,5,10,20,30,6]
def two_no_summer(n,L):
for i in range(0,len(L)):
for j in range(i,len(L)):
if (L[i]+L[j]==n) & (L[i]!=L[j]):
print(L[i],L[j])