Home > Enterprise >  How I end a loop for not sum first and last number as a pair?
How I end a loop for not sum first and last number as a pair?

Time:11-16

I've got everything working correctly except this one problem - with the third output it says the max pair sum is 13 due to taking sum of the first and last number. It should be 11 (as 9 2 or 4 7). I can't figure it out how I fix this problem - ending the loop with the first and last position.

Thank you for all advice.

def _sum(num_list): 
    maxSum = -9999999
    for i in range(len(num_list)): 
        for j in range(i-1, i 1):
            if not num_list[i] == num_list[j]:
                maxSum = max(maxSum, num_list[i]   num_list[j])
    return maxSum        

print(_sum([1, 8, 7, 3, 5, 2])) 
# correct answer: 15
print(_sum([1, 2, 45, 4, 5, 6, 7, 3, 2]))
# correct answer: 49
print(_sum([9, 2, 3, 4, 7, 1, 2, 3, 4]))
# correct answer: 11

I have tried write some if conditions into for j loop but it ended up with many errors. I'm truly out of ideas and I can't even imagine how it could be right.

CodePudding user response:

in your solution, for first element value of j is [-1, 0] beacuse of this it is taking 4 and adding with 0th index element and making their sum as max value. you need to fix it by starting from index 1. A simple way to do that is below

def _sum(num_list): 
    maxSum = -9999999
    for i in range(1, len(num_list)): 
        for j in range(i-1, i 1):
            if not num_list[i] == num_list[j]:
                maxSum = max(maxSum, num_list[i]   num_list[j])
    return maxSum  

CodePudding user response:

You can use itertools.pairwise for this.

Your code considers every possible pairing of elements from the given array. pairwise only considers consecutive pairs:

from itertools import pairwise

def _sum(num_list):
    return sum(max(pairwise(num_list), key=lambda item: item[0] item[1]))

Output as requested

  • Related