Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 15 Online
OpenStudy (anonymous):

Hey, how would I write a program, that, for example, took all even numbers in the list [1,2,5,6,8] and, say added each of their doubles to the list? This is what I got but it's not right I don't think: sia = [1,2,5,6,8] for all x in sia: if x%2==0: sia.append(2x) else: pass thanks for helping...

OpenStudy (anonymous):

Your logic is wrong, it will get stuck in infinite loop.When you multiply any number with 2 and add to the same list, it will also be processed in the for loop. And any number multiplied by 2 i even. So your adding even number to list and also checking if even number exists in the for .

OpenStudy (anonymous):

So how could I fix the logic? And actually when I execute the script it doesn't do anything...-_-

OpenStudy (anonymous):

this will work for your logic . for syntax doesn't have all in it >>> sia = [1,2,5,6,8] >>> b= [] >>> for x in sia : if x % 2 == 0 : b.append(2*x) >>> b [4, 12, 16]

OpenStudy (anonymous):

How would I do it n times?

OpenStudy (anonymous):

Don't iterate over all the elements of the list. Instead iterate only over the indices. for i in range(0,len(sia))

OpenStudy (anonymous):

What's an indice? (sorry)

OpenStudy (anonymous):

Index is the position of an element in the list. (Just like array indices in languages like C, Java) Index numbering starts from 0. Here, your list is sia = [1,2,5,6,8]. sia[0]=1 sia[1]=2 ... sia[4]=8 You can iterate over the indices from 0 till the initial length of sia (ie len(sia)) so that even while you append the doubles to the list, you don't end up in an infinite loop (as stated by Jagan)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!