Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python operation data List in loop

I want to solve my programming problem, the problem goes like so:

input: 3 #if i input as first input example 3, output is [1, 2, 3]
[1, 2, 3] 
input: 2  #2nd input example 2 output is [1, 2] + [1, 2, 3] = [2, 4, 6]
[2, 4, 3]
input: 6 #3rd input [2, 4, 6] + [1, 2, 3, 4, 5, 6] = [3, 6, 6, 4, 5, 6]
[3, 6, 6, 4, 5, 6]

My code:

while True:
    a = input('Input : ')
    n = range (1,a+1,1)

    print n 

Outputs:

 Input : 3
 [1, 2, 3]
 Input : 2
 [1, 2]
 Input : 6
 [1, 2, 3, 4, 5, 6]

How can I solve this problem?

like image 318
Aji Pratama Avatar asked May 09 '26 16:05

Aji Pratama


1 Answers

Building on your existing code, I would use itertools.izip_longest (Python 2, for 3 use zip.longest):

>>> import itertools
>>> nxt = []
>>> while True:
    a = input('Input : ')
    n = range(1, a+1, 1) # could change to range(1, a+1)
    nxt = map(sum, itertools.izip_longest(n, nxt, fillvalue=0))

    print nxt

Which yields:

Input : 3
[1, 2, 3]
Input : 2
[2, 4, 3]
Input : 6
[3, 6, 6, 4, 5, 6]
like image 64
Idos Avatar answered May 12 '26 05:05

Idos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!