I'm trying to write a generator function for printing prime numbers as follows
def getPrimes(n):prime=Truei=2while(i<n):for a in range(2,i):if(i%a==0):prime=Falsebreakif(prime): yield i
However I'm not getting the desired results
p=getPrimes(100) should give me a generator function that will iterate primes from 2 through 100 but the result I'm getting is [2,3]. What am I doing wrong?
Answer
Sieve of Eratosthenes: Most efficient prime generator algorithm
Taken from here:
Simple Prime Generator in Python - an answer by Eli Bendersky.
It marks off all the multiples of 2, 3, 5, 7 and 11. The rest are all prime numbers.
def genprimes(limit): # derived from # Code by David Eppstein, UC Irvine, 28 Feb 2002D = {} # http://code.activestate.com/recipes/117119/q = 2while q <= limit:if q not in D:yield qD[q * q] = [q]else:for p in D[q]:D.setdefault(p + q, []).append(p)del D[q]q += 1p = genprimes(100)
prms = [i for i in p]print prms
I know that this error message (ValueError: too many values to unpack (expected 4)) appears when more variables are set to values than a function returns. scipy.stats.linregress returns 5 values accord…
For example, in Django 1.8:class A(models.Model):x = models.BooleanField(default=True)class B(models.Model):y = models.ManyToManyField(A)class C(models.Model):z = models.ForeignKey(A)In this scenario, …
I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and…
I am attempting to create a program using multiple processes and I would like to cleanly terminate all the spawned processes if errors occur. below Ive wrote out some pseudo type code for what I think …
Are there any limitations declared anywhere (PEPs or elsewhere) about how broad a scope the Linux wheels uploaded to PyPI should have? Specifically: is it considered acceptable practice to upload li…
Given two lists of dictionaries, new one and old one. Dictionaries represent the same objects in both lists.
I need to find differences and produce new list of dictionaries where will be objects from n…
Im developing an app on the Google App Engine and have run into a problem. I want to add a cookie to each user session so that I will be able to differentiate amongst the current users. I want them all…
So, I learned how to make cute little animations in matplotlib. For example, this:import numpy as np
import matplotlib
import matplotlib.pyplot as pltplt.ion()fig = plt.figure()
ax = fig.add_subplot(…
Where is python intrepreter located in virtual environment ?
I am making a GUI project and I stuck while finding the python interpreter in my virtual environment.
I am working on a program that has a virtual keyboard I created using Tkinter. The pages that have the keyboard enabled have entry widgets where the users need to input data. I am using pyautogui as …