I am currently working on some beginner python challenges, I just finished a gaussian addition challenge. I was able to get the output that the challenge was looking for, but it seems like I over complicated things.
The challenge is as follows:
Write a program that passes a list of numbers to a function.
- The function should use a while loop to keep popping the first and last numbers from the list and calculate the sum of those two numbers.
- The function should print out the current numbers that are being added, and print their partial sum.
- The function should keep track of how many partial sums there are.
- The function should then print out how many partial sums there were.
- The function should perform Gauss’ multiplication, and report the final answer.
- Prove that your function works, by passing in the range 1-100, and verifying that you get 5050. gauss_addition(list(range(1,101)))
- Your function should work for any set of consecutive numbers, as long as that set has an even length.
- Bonus: Modify your function so that it works for any set of consecutive numbers, whether that set has an even or odd length.
My function is as follows:
def gauss(numbers): for number in numbers: while len(numbers) > 0: num1 = numbers.pop(0) print(num1) num2 = numbers.pop(-1) print(num2) calc = num1 + num2 print(str(num1) + " + " + str(num2) + " = " + str(calc)) print("Final answer is: " + str(num1 * calc)) gauss(list(range(1,101)))
Can someone explain how I can simplify this function without the use of python modules? I understand how the function that I wrote is working, but I also want to know if there is an easier, “more condensed” way of achieving this.
I should specify that I only know the basics of python…
Advertisement
Answer
Using list to approach this problem seems to be too expensive, for the reason of repeatedly pop will be costly as cited in early notes.
So instead of it, you can consider using collections module deque which will allow you to do the operations (pop) in both end efficiently.
Note – it will work well if the list is even-sized, but that’s part of requirements already.
So the solution will be like this:
# from collections import deque dq = deque(range(1, 101)) # create a list (dq list) total = 0 count = 0 while dq: x, y = dq.popleft(), dq.pop() print(x, y, x+y, end='t') count += 1 # how many partial sum? print(count) total += (x+y) print(f' final total: {total} ')
Outputs: (partial – it’s too long)
1 100 101 1 2 99 101 2 3 98 101 3 4 97 101 4 5 96 101 5 ........... ........... 48 53 101 48 49 52 101 49 50 51 101 50 final total: 5050