I'm learning python and had an excercise where I had a list of integers and had to keep one on two numbers, then 2 on 3, then 3 on 4... And see at the end what was left. Ex : [1,2,3,4,5,6,7,8,9] --> [1,3,5,7,9] --> [1,3,7,9] --> [1,3,7]
My first try, just to see the output (beware, shockingly dirty code) :
n=input()
list2=list(range(1,int(n)))
list1=[]
step=2
while list1 != list2 :
countSteps=1
position=0
list1=list2
list2=[]
lenlist1=len(list1)
while position < lenlist1 :
while countSteps != step and position < lenlist1 :
list2.append(list1[position])
countSteps+=1
position+=1
position+=1
countSteps = 1
step+=1
print(list2)
The "idea" there was to use two lists and add 1/2/3... on 2/3/4... numbers from one to the other. It seems to me (maybe I'm wrong) that memory wise it was a bad choice, so I came up with the following :
n=input()
list1=list(range(1,int(n)))
lenCached=0
step=1
while lenCached!=len(list1) :
lenCached = len(list1)
position = step
while position < len(list1):
list1.pop(position)
position+=step
step+=1
print(list1)
I'm happy with how this last one looks but performance is horrible. When I run the first one with range(1,1000000), it takes 10s while the second one takes ages (several minutes). Why and is there something I can do about it ?
(if reading this you thought of a better way to achieve the initial goal I would of course be interested in hearing it!)