我正在尝试编写一段代码,它将获取一个介于1和10之间的数字列表,并找出总和大于或等于10的数字,然后从列表中删除这些数字。这里的关键是:首先需要检查列表中是否有任何10,以及是否有总和为10的任意两个数字,然后是任意三个数字,以此类推直到五个数字。此外,被加起来的数字越低,就越好。因此,在对夫妻进行求和时,需要尽可能少地摆脱数字。到目前为止,我已经成功实现了夫妻之和的计算。
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)
我也做了三个一组,想用同样的方法来处理四个和五个:
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
我希望找到一个更简单的方法来完成这个操作。虽然这个方法是可行的,但对于大量数字而言,它似乎会进行很多无用的计算。 有什么想法吗?