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