Aji Peatama - 1 year ago 53

Python Question

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?

Answer Source

but i can not use external code

Then you can write some code that does exactly what `izip_longest`

does with the zero padding when the new entry is lengthier than the previous result.

The sums are performed in a *list comprehension* where the values and indices from the input list are gotten by applying `enumerate`

on the entry in the comprehension. Values from the accumulated list are indexed and added to new values at the same index:

```
tot = []
while True:
a = input('Input : ')
n = range (1,a+1,1)
x, y = len(tot), len(n)
if y > x:
tot[x:y] = [0]*(y-x) # pad the tot list with zeros
tot[:y] = [tot[i]+v for i, v in enumerate(n)]
print tot
```

Output:

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