Home > Software engineering >  Python Sum of recent program
Python Sum of recent program

Time:11-21

I need help working on a python program that does the following(A list is required):

Can someone please help me! Would be much appreciated!

CodePudding user response:

Append each input to a list, and use a [-3:] slice to get the last 3 elements.

>>> nums = []
>>> while True:
...     nums.append(int(input("Enter a number: ")))
...     print(f"Your last 3 inputs sum to {sum(nums[-3:])}")
...
Enter a number: 1
Your last 3 inputs sum to 1
Enter a number: 2
Your last 3 inputs sum to 3
Enter a number: 3
Your last 3 inputs sum to 6
Enter a number: 4
Your last 3 inputs sum to 9
Enter a number: 0
Your last 3 inputs sum to 7
Enter a number: 0
Your last 3 inputs sum to 4
Enter a number: 0
Your last 3 inputs sum to 0
Enter a number: 5
Your last 3 inputs sum to 5
Enter a number: 5
Your last 3 inputs sum to 10

CodePudding user response:

You could use a collections.deque:

from collections import deque

last3 = deque(maxlen=3)
while True:
    num = int(input('Enter a number: '))
    last3.append(num)
    print(f'Your last 3 inputs sum to {sum(last3)}')

Enter a number: 1
Your last 3 inputs sum to 1
Enter a number: 2
Your last 3 inputs sum to 3
Enter a number: 3
Your last 3 inputs sum to 6
Enter a number: 4
Your last 3 inputs sum to 9
Enter a number: 0
Your last 3 inputs sum to 7
Enter a number: 0
Your last 3 inputs sum to 4
Enter a number: 0
Your last 3 inputs sum to 0
Enter a number: 5
Your last 3 inputs sum to 5
Enter a number: 5
Your last 3 inputs sum to 10

Without using a deque:

last3 = [int(input('Enter a number: '))]
while True:
    print(f'Your last 3 inputs sum to {sum(last3)}')
    last3.append(int(input('Enter a number: ')))
    del last3[:-3]
  • Related