python - 大于数字的唯一总和
问题描述
因此,我正在尝试编写一个代码,该代码采用 1 到 10 之间的数字列表并找到大于或等于 10 的总和,然后从列表中删除这些数字。这就是转折点:首先您需要检查列表中是否有任何 10、总和为 10 的任何一对数字,然后是任何 3 个数字,依此类推,直到 5。此外,数字总和越低越好。因此,在对夫妇求和时,您需要去掉大多数数字。到目前为止,我设法做到了这对夫妇:
n = input("How many numbers in the list? \n")
throw = []
for i in range(int(n)):
throw.append(random.randint(1, 10))
throw.sort()
increments = 0
print(throw)
increments += throw.count(10)
throw = list(filter(lambda i: i != 10, throw))
high = len(throw)-1
low = 0
acceptable_couples = []
get_rid = []
while low < high:
sums = throw[high] + throw[low]
if sums >= 10:
increments += 1
get_rid.append(throw[high])
get_rid.append(throw[low])
acceptable_couples.append((throw[high], throw[low]))
high -= 1
low += 1
else:
low += 1
for i in get_rid:
throw.remove(i)
我也做了 3 对,并正在考虑对 4 和 5 应用相同的方法:
while len(throw) >= 3:
z = 0
x = list(itertools.combinations(throw, 3))
for couple in x:
if sum(couple) >= 10:
z += 1
i = list(couple)
increments += 1
for j in couple:
throw.remove(j)
break
else:
continue
if z == 0:
break
我希望找到一种不那么混乱的方法来做到这一点。这行得通,但是对于大量数字,似乎有很多无用的计算。有任何想法吗?
解决方案
不确定我是否正确理解了您的问题。我的解释是,你有一组介于 1 和 10 之间的数字,你需要从这个集合中找到最长的子集,总和为 10 或更大,然后从原始集合中删除这些数字,直到你找不到任何具有多个数字的更多集合。
如果这是正确的解释,则以下内容应该有效:
import random
n = int(input("How many numbers in the list? \n"))
throw = [random.randint(1, 10) for _ in range(n)]
print(throw)
throw.sort()
list_of_solved_sets = []
sets_found = True
while sets_found:
_sum = 0
solved_set = []
solved_indexes = []
for index, element in enumerate(throw):
_sum += element
solved_set.append(element)
solved_indexes.append(index)
if _sum >= 10:
break
if len(solved_set) <= 1:
sets_found = False
else:
list_of_solved_sets.append(solved_set)
for index in reversed(solved_indexes):
del throw[index]
print('List of solved sets:')
for i, solved_set in enumerate(list_of_solved_sets):
print(f' {i+1}: {solved_set}')
请注意,您需要以throw
相反的顺序从列表中删除索引!
推荐阅读
- scala - 如何根据同一数据框中另一列的值替换数据框中的值?
- hyperledger-fabric - Chaincode 没有正确创建状态?
- linux - 如何从 buildbot ShellCommand 启动守护进程
- mysql - 基于mysql条目的shell脚本中的文件复制
- android - 升级 react-native 版本后出现错误
- html - 如何在css中为具有绝对位置的兄弟div元素的margin-left设置动态数字
- android-source - 构建 AOSP 扩展 ROM 时出现杰克错误
- react-native - React-Native:如何找到 ph://uri 的文件信息?
- python - 从 pandas DataFrame 中通过多个部分字符串匹配选择列
- php - 如何更改 getter 属性参数并显示不同的结果?