Python prime number list -


i trying figure out why these 2 snippets should same work, somehow not.

i want find prime numbers between 1-100. , know work:

# create empty list first. # if number qualifies prime number append, if not break.  pnumber1 = [] x in range(2, 101):     in range(2, x):         if x % == 0:             break     else:         pnumber1.append(x) print(pnumber1) 

so trying play in way, create list of numbers 1-100, , remove number not prime number. what's left should prime number list. have:

# note: code should exclude '2', prime number, i'll worry later.  pnumber1b = list(range(3, 101)) x in pnumber1b:     in range(2, x):         if x % == 0:             pnumber1b.remove(x)     else:         break print(pnumber1b) 

somehow, won't work, return every number 3-100. means pumber1b.remove(x) did not work.

ok, if try way:

  pnumber1b = list(range(3, 101))     x in pnumber1b:         in range(2, x):             if x % == 0:                 pnumber1b.remove(x)             else:                 break print(pnumber1b) 

to change indent level, still return: list.remove(x): x not in list

of course not work : take example of i=2,x=6 , 6 not prime ergo remove it.

on next iteration of i, i=3 come across x=6 1 again , try remove again! getting error : list.remove(x): x not in list .

and of course important note: cannot change list iterating over! when remove item x list next iteration invalid , list corrupted!

try adding if asks if x still in pnumber1b:

pnumber1b = list(range(3, 101)) pnumber1a = list(range(3, 101)) x in pnumber1b:         in range(2, x):                 if x % == 0:                     if x in pnumber1a:                         pnumber1a.remove(x)                         break                     else:                         continue  print(pnumber1a) 

or add break after remove command since there no need continue running on number x.

pnumber1b = list(range(3, 101)) pnumber1a = list(range(3, 101)) x in pnumber1b:         in range(2, x):                 if x % == 0:                     pnumber1a.remove(x)                     break print(pnumber1a) 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -