I wrote a piece of code to print n prime numbers:
class PrimeGen:
def __init__(self):
self.current = 2
def genPrime(self, num):
for i in range(num):
while 1:
for j in range(2, self.current/2 + 1):
if self.current % j == 0:
self.current = self.current + 1
break
else:
break
print self.current,
self.current = self.current + 1
if __name__ == '__main__':
p = PrimeGen()
p.genPrime(5)
The code works fine. I get 2 3 5 7 11 as output. I tried to make the class iterable. Code below. But the output is 0 1 2 3 4. I could not quite figure out where I am going wrong. Any help is appreciated. Thanks
class PrimeIter:
def __init__(self):
self.current = 1
def next(self):
self.current = self.current + 1
while 1:
for i in range(2, self.current/2 + 1):
if self.current % i == 0:
self.current = self.current + 1
break # Break current for loop
else:
break # Break the while loop and return
return self.current
def __iter__(self):
return self
if __name__ == '__main__':
p = PrimeIter()
for p in range (5):
print p,
You're using this code to print out the values:
for p in range (5):
print p,
If you look at that, it's printing the values of the range. You probably want to print things from the prime iterator. itertools has some functions that may help:
for prime in itertools.islice(p, 5):
print prime,
Additionally, you may want to consider using a generator:
def primes():
current = 1
while True:
current += 1
while True:
for i in xrange(2, current // 2 + 1):
if current % i == 0:
current += 1
break
else:
break
yield current
Your problem is that you are reusing the variable p in your test code:
if __name__ == '__main__':
p = PrimeIter() # first declaration of p
for p in range (5): # second declaration of p
print p, # uses second declaration of p
I'd recommend using itertools.islice to get the first 5 elements of an iterator:
if __name__ == '__main__':
p = PrimeIter()
for x in itertools.islice(p, 5):
print x,
Iterator for generating prime numbers upto some maximum m:
class PrimeIter:
def ___init__(self, m):
self.max = m
def __iter__(self):
self.n = 1
return self
def __next__(self):
if self.n < self.max:
self.n += 1
i = 2
while i < (self.n//2+1):
if self.n % i == 0:
self.n = self.n+1
if self.n > self.max:
raise StopIteration
i = 1
i += 1
else:
return self.n
else:
raise StopIteration
p = PrimeIter (100)
for i in p:
print(i, end=' ')
Related
class Stack:
def __init__(self):
self.stack=[]
self.top = None
def empty(self):
return not self.stack
def push(self, item):
self.stack.append(item)
self.top = item
def pop(self):
if self.empty():
a = self.stack.pop()
return a
else:
print("Empty stack")
def printall(self):
print(self.stack)
def clear(self):
self.stack = []
self.top = None
ysj = Stack()
jy = []
list = input().split()
leng = len(list)
num = 0
for i in range(0, leng):
if list[i] == '+' or list[i] == '-':
while ysj.top is not None:
jy.append(ysj.pop())
num = num - 1
ysj.push(list[i])
num = num + 1
elif list[i] == '/' or list[i] == '*':
while ysj.top == '/' or ysj.top == '*':
jy.append(ysj.pop())
num = num - 1
ysj.push(list[i])
num = num + 1
else:
jy.append(int(list[i]))
for i in range(1, num + 1):
jy.append(ysj.pop())
for i in range(0, len(jy)):
print(jy[i], end=" ")
I'm trying to convert the equation from infix form to postfix form using Stack class.
This code works when I type in
1 + 2 * 3
but doesn't work well when I type in
1 * 2 + 3 or 1 * 2 * 3 or 1 + 2 + 3
I think there's something wrong with my while loop but I can't figure out what part is wrong. Please help me.
You forgot to insert None to top when the list gets empty, and you are trying to remove a item when the list is empty:
class Stack:
def __init__(self):
self.stack=[]
self.top = None
def empty(self):
return not self.stack
def push(self, item):
self.stack.append(item)
self.top = item
def pop(self):
if not self.empty(): # remove item only if the stack is not empty
a = self.stack.pop()
# after removing a item, check if the stack is empty
if self.empty(): # if it is, set the top as None
self.top = None
return a
else:
print("Empty stack")
When I write this code:
n = int(input('num: '))
for i in range(2, n):
if n%i == 0:
a = i
print(a)
It works without a problem.
But this creates a problem. It says
local variable a referenced before assignment
def largestDivisor(n):
for i in range(2, n):
if n%i == 0:
a = i
return a
How can I fix it?
If you call like largestDivisor(2) you won't go in the for so not in the if and you'll never define a, define it at the beginning :
def largestDivisor(n):
a = 1
for i in range(2, n):
if n % i == 0:
a = i
return a
def largestDivisor(n):
a = 1
for i in range(2,n):
if n%i==0:
a=i
return a
If the condition "n % i == 0" is never True the variable "a" will not exist, therefore you must initialize it before the loop.
def largestDivisor(n):
a = 1
for i in range(2, n):
if n%i == 0:
a = i
return a
I have this problem from codewars.com: First n Primes numbers.
While I have no problem defining class Primes() and Primes.first(n1), I need to find the last prime numbers under the form: Primes.first(n1).last(n2). And I don't know how to define last(n2) without getting an error.
import math
class Primes():
def first(self):
primes = []
count = 1
prime = True
while len(primes) != self:
for i in range(2, int(math.sqrt(count)) + 1):
if count % i == 0:
prime = False
break
if prime:
primes.append(count)
prime = True
count += 1
return primes
def last(self):
pass
If i try Primes.first(5).last(3) i get: AttributeError: 'list' object has no attribute 'last'.
... first returns a list.last() is trying to call a function named last on a list. A list does not have a function called last.
I think you want this.
class Primes(list):
def first(self, amount):
count = 1
while len(self) < amount:
prime = True
for i in range(2, int(math.sqrt(count)) + 1):
if count % i == 0:
prime = False
break
if prime:
self.append(count)
count += 1
return self # Note: self is Primes object which has a last method.
def last(self, amount):
...
return self
p = Primes()
p.first(5)
p.last(3)
# same as p = Primes().first(5).last(3) because it returns self
# Primes now inherits from list, so it works like a list but has a last method
I've fixed the tabbing in your code.
From the looks of it you don't need a last method at all. If you just want to get the last 5 values use [-5:].
# Your old way edited
class Primes():
#staticmethod
def first(amount):
primes = []
count = 1
while len(primes) < amount:
prime = True
for i in range(2, int(math.sqrt(count)) + 1):
if count % i == 0:
prime = False
break
if prime:
primes.append(count)
count += 1
return primes
p = Primes.first(20)
print(p)
print(p[-5:]) # This will give you the last 5
I am trying to perform dynamic programming for approximate pattern matching in this code.Once the matrix is created,I am trying to trace back to my answer using the function trace.But when I run the program,the trace function is not returning any result and the program isn't getting terminated.
class Structure :
def __init__(self):
self.vertical =[]
self.horizontal =[]
self.diagnol=[]
def merge(self, s):
for i in s.vertical :
self.vertical.append(i)
for i in s.horizontal :
self.horizontal.append(i)
for i in s.diagonal:
self.diagonal.append(i)
def __str__(self):
return "horizontal \n"+str(self.horizontal) +"\n vertical \n"+str(self.vertical)+"\n diagonal"+str(self.diagonal)
def posList(pattern, text): #determine the positions in the matrix
retList = list()
textList = [x for x in text.strip()]
for i, char1 in enumerate(pattern):
textPos = [j for j, char2 in enumerate(textList) if char1==char2]
for j in textPos:
retList.append((i+1,j+1))
return retList
def trace(M,text,pattern,k) :
positions=posList(pattern,text)
struct = Structure()
for i in range(0,2):
for j in range(0,7):
while M[i,j]<=k and M[2,j]!=0:
if M[i,j] == M[i,j-1]+1:
struct.horizontal.append(j)
j -= 1
elif M[i,j] == M[i-1,j]+1:
struct.vertical.append(i)
i -= 1
elif (i+1,j+1)in positions and M[i,j]==M[i-1,j-1] :
struct.diagonal.append((i,j))
i -= 1
j -= 1
elif (i+1,j+1) not in positions and M[i,j]==M[i-1,j-1]+1 and M[i,j]==M[i-1,j]+1:
struct.vertical.append(i)
i-=1
print "error"
elif (i+1,j+1) not in positions and M[i,j]==M[i-1,j-1]+1 and M[i,j]==M[i,j-1]+1:
struct.horizontal.append(j)
j-=1
elif M[i,j]==M[i-1,j]+1 and M[i,j]==M[i,j-1]+1:
struct.vertical.append(i)
elif M[i,j]==M[i-1,j]+1 and M[i,j]==M[i,j-1]+1 and M[i,j]==M[i-1,j-1]+1:
struct.vertical.append(i)
i-=1
else :
pass
return struct
text='ACAGCAG'
pattern='GC'
n = len(pattern)
m = len(text)
text1=list(text)
pattern1=list(pattern)
M = [[0 0 0 0 0 0 0 0],[1 1 1 1 0 1 1 0],[2 2 1 2 1 0 1 1]]
#perform traceback
s= trace(M,text,pattern,1)
print s
s = trace(M, w, seq, max, 0, n-1)
print str(s)
print seq
result=real_string(s)
print "".join(result)
Can anyone suggest me where I maybe going wrong in the function ?
my prime function is working fine for numbers greater than 3,i have accounted for that in loop folowing afterward,question is to find 10001st prime
but i am getting wrong answer that is a prime number but not the 10001st,should be 104743
def pr(n):
for i in range(2,int(n**(0.5))+1):
if n%i==0:
return False
break
else:
return True
num = 3
count = 2
while count < 10001:
num += 1
x = pr(num)
if x == True:
count += 1
print num
try;
def pr(n):
if n%2 == 0:
return False
for i in range(3,int(n**(0.5))+1,2):
if n%i==0:
return False
return True
def pgen(): # Sieve of Eratosthenes generator
yield 2
np_f, q = {}, 3
while True:
f = np_f.pop(q, None)
if f:
np = q + f
while np in np_f:
np += f
np_f[np] = f
else:
yield q
np_f[q*q] = q+q
q += 2
>>> p = pgen()
>>> [next(p) for i in xrange(10001)][-1]
104743