'How to use revised array again in loop python
The below code is about, dividing the even elements of list by 2 till if reaches 1 if the element is odd then remove the element .
I just now started this program. What doubt I have means I need to use the revised array again in the loop. But it showing error.
Input:
4
32 60 8 200
Needed Output:
16 30 4 100
8 15 2 50
4 1 25
1
n=int(input())
l=list(map(int,input().split()))
leg=len(l)
rv=[]
for i in range(0,leg):
if l[i]%2==0:
rv.append(l[i]//2)
l=rv
error:
Traceback (most recent call last):
File "HelloWorld.py", line 7, in <module>
if l[i]%2==0:
IndexError: list index out of range
In my above code what i am trying to do means i append the even elements of list 'l' to 'rv' and i need to use 'rv' for the loop instead of 'l' but it showing error why??
Solution 1:[1]
I think this code calculates what you want correctly. However, it breaks if not all the numbers are divisible by two.
n = int(input('set lenght of input'))
l = []
for k in range(n):
l.append(int(input()))
running = True
while(running):
print(l)
for i in l[len(l)-n:len(l)]:
if(i % 2 == 0):
z = int(i / 2)
l.append(z)
if z == 1: running = False
l = l[n+1:]
print(l)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RiveN |
