简体   繁体   中英

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 . 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:

  1. The sum is odd: In that case, we're already done. The largest possible sum is also odd, so we have our result.
  2. The sum is even: In that case, we have the largest possible sum but we are not odd. In order to fix that we need to remove the smallest odd number from the sum. So we look at the sorted list of numbers and pick the first odd number from it. By removing an odd number from an even sum, we get an odd number again, and since we picked the smallest possible number, we know our new sum is the largest odd sum. So that's the result.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM