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
. 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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.