[英]python - print the sum of items in list whose total is the largest and is odd
It's a simple problem I have been trying to solve. 这是我一直试图解决的一个简单问题。 First of all I take input with a list of positive integers.
首先,我输入一个正整数列表。 I want to choose items from them in such a way that their total is maximum possible and their sum is odd.
我想从他们中选择项目,使他们的总数最大可能,他们的总和是奇数。 If no combination is possible I want to print
-1
. 如果没有可能的组合,我想打印
-1
。 I have written the code and it is not working properly. 我编写了代码,但它无法正常工作。
l = sorted(list(map(int, input().split())))
if sum(l)%2 == 1:
print(sum(l))
else:
m = 0
for x in range(len(l)):
a = l
a.pop(x)
if sum(a)%2 == 1 and sum(a) > m:
m = sum(a)
For example, for the input 2 3 4 5
, it's printing 9
where it should print 11
. 例如,对于输入
2 3 4 5
,它打印9
应打印11
。
Any help would be appreciated. 任何帮助,将不胜感激。
So, from the list of numbers, you want to get the largest possible sum which is odd. 因此,从数字列表中,您希望获得最大可能的总和,这是奇数。 This is actually rather simple and can be solved pretty easily.
这实际上非常简单,可以很容易地解决。 What you need to do is take the sum of all numbers as that is the maximum sum that you could possibly get from those numbers.
您需要做的是获取所有数字的总和,因为这是您可以从这些数字中获得的最大总和。 Now, we have two options:
现在,我们有两个选择:
In code, this could look like this: 在代码中,这可能如下所示:
def largestOddSum(numbers):
s = sum(numbers)
if s % 2 == 1:
return s
for x in sorted(numbers):
if x % 2 == 1:
return s - x
return -1
Used like this: 像这样使用:
>>> largestOddSum([2, 3, 4, 5])
11
In a easy way : sum all and subtract the minimum odd number if first sum is even : 一个简单的方法:加上所有并减去最小奇数,如果第一个和是偶数:
if sum(l)%2 == 1:
print(sum(l))
else:
print(sum(l) - [i for i in sorted(l) if i%2==1][0])
I think the best way to tackle this is by remembering that: 我认为解决这个问题的最佳方法是记住:
even + even = even
odd + even = odd
odd + odd = even
With this in mind, you can always include all even numbers. 考虑到这一点,您始终可以包含所有偶数。 You can also always include all odd numbers, as long as the number of odd numbers is not even.
您也可以始终包含所有奇数,只要奇数的数量不均匀即可。 If the number of odds IS even, just leave the smallest out.
如果赔率是偶数,那么就把最小的赔率留下来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.