【问题标题】:Sum from random list in pythonpython中随机列表的总和
【发布时间】:2018-01-30 17:50:23
【问题描述】:

我创建了一个包含 60 个数字的随机列表,我不知道列表中包含的数字。我被要求从列表中找到总和为零的三个数字的任意组合。我能做些什么? 这是我的代码:

import random
import itertools
result = []

for x in range (-30, 30):
   num = random.randint(-30, 30)
   while num in result:
     num = random.randint(-30, 30)
     result.append(num)
        result = [seq for i in range(len(result), 0, -1) for seq in itertools.combinations(result, i) if sum(seq) == 0]
print result

【问题讨论】:

  • 到目前为止你的尝试是什么?
  • 请包含您已经尝试过的代码。 (列表是如何制作的,您已经尝试让它们添加什么。)
  • 我的总和代码不在这里,因为它不起作用!
  • 发布不起作用的代码有点像stackoverflow。我们可以查看它并告诉您您做错了什么。
  • 请注意format your question,以便代码显示为代码。

标签: python list random sum zero


【解决方案1】:

出于演示的目的,我将为result 定义一个特定的示例值,我们可以用它来测试并看看会发生什么。

result = [1, 2, -2, -3, 4]

您可以使用itertools.combinations 列出三个数字的所有组合。

import itertools

>>> list(itertools.combinations(result, 3))
[(1, 2, -2),
 (1, 2, -3),
 (1, 2, 4),
 (1, -2, -3),
 (1, -2, 4),
 (1, -3, 4),
 (2, -2, -3),
 (2, -2, 4),
 (2, -3, 4),
 (-2, -3, 4)]

您可以使用filterlambda c: sum(c) == 0 作为谓词来选择总和为零的组合。

>> list(filter(lambda c: sum(c) == 0, itertools.combinations(result, 3)))
[(1, 2, -3)]

【讨论】:

  • 我不知道列表中的数字!我该怎么办?
  • 什么意思?为什么你需要了解他们?
  • 您使用数字 1、2、-2 等。我不知道我列表中的数字
  • 我将result 定义为一组特定的数字,目的是向您展示发生的情况。但该代码适用于任何一组数字,而不仅仅是示例。
  • 我刚刚在上面添加了我的代码,我该怎么做才能从我创建的列表中获得任何组合,总和为零?
【解决方案2】:

itertools中有一个函数combinations,可以用来生成组合。

import random
import itertools
# Generate a random list of 30 numbers
mylist = random.sample(range(-50,50), 30)

combins = itertools.combinations(mylist, 3)
interested = list(filter(lambda combin: sum(combin) == 0, combins))
print(interested)

请注意,filter()itertools.combinations() 的结果是可迭代的,需要 list() 将可迭代转换为列表。

lambda 表达式lambda combin: sum(combin) == 0 用于保留combins 和为零的组合

itertools.combinations(): https://docs.python.org/3.6/library/itertools.html#itertools.combinations

filter(): https://docs.python.org/3.6/library/functions.html?highlight=filter#filter

【讨论】:

  • :) 该列表是随机生成的,因此如果足够幸运,列表interested 可能为空。然后重新运行脚本。
猜你喜欢
  • 2022-08-08
  • 1970-01-01
  • 2016-03-01
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 2012-02-21
相关资源
最近更新 更多