Click here to Skip to main content
16,016,962 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
6,4,12,9,45,23,2,43,56,17,20,11,7
Using the numbers above how would I search for the two consecutive values that add up to the smallest and the largest value? In this case, the two values that have the smallest sum are 6 & 4 for a total of 10 and values 43 & 56 with a sum of 99. how would I locate the two values for each and then print out the values and their sum?

What I have tried:

I know I could make a list of all the pairs. Then use min() and max() with a key function that calculates the sums but I'm not entirely sure on how to code that or even begin to code it.
Posted
Updated 20-Sep-22 18:12pm
Comments
Bob@work 20-Sep-22 18:37pm    
You can create the list, sort it and then add the first two items and last two list items to get the min and max. The answers will be 6 (2+4), and 101 (45+56).

Something like:

nums = [6,4,12,9,45,23,2,43,56,17,20,11,7]
print(nums)
nums.sort()
print(nums)
print(nums[0]+nums[1])
print(nums[len(nums)-1]+nums[len(nums)-2])

1 solution

Working out how to do it is a big part of the task: the idea is to get you thinking about how you go from a specification to a working design.

So start by thinking about how you would do it manually if you were looking for the "lowest pair" only.
You would add each pair is turn, comparing that sum with the "smallest so far". When you'd summed and compared them all, you would have the smallest pair.
So if the data was
3,4,2,1,5
Then the sums would be:
3,4,2,1,5
 + 
 7         smallest becomes 7
   +
   6       smallest becomes 6
     +
     3     smallest becomes 3
       +
       6   smallest remains 3
And the smallest sum is 3, the pair the generated it was 2 + 1Easy, right?
Now think about how you would code that: you'd need a "smallestSum" variable, and a pair of "smallestInput" variables.
You'd want a loop, and inside the loop you would add the current pair, and compare the sum to smallestSum if the new sum is smaller, you'd store it in smallestSum and change the smallestInput values as well.
After the loop ended, you'd have the minimum.

So write the code to do that, and you are halfway finished. I'll leave the rest to you!
 
Share this answer
 
Comments
CPallini 21-Sep-22 2:26am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900