Python generator only returning first instance of yield - python-3.x

This code should produce all prime numbers in order when 'next' is called, but it only produces 2, the first prime number of the list. The list works properly to produce prime numbers.
def genPrime():
x = 1
primeList = [2]
while True:
x += 1
tempList = []
for i in range(len(primeList)):
tempList.append(x % primeList[i])
if min(tempList) > 0:
next = primeList[-1]
yield next
primeList.append(x)
prime = genPrime()
print(prime.__next__())

That's exactly what a generator is supposed to do. .__next__() only returns the next item, just as the name says.
Try:
print(prime.__next__())
print(prime.__next__())
print(prime.__next__())
You will see that you get them one by one.
Further, it is important that .__next__() is not meant to be called directly. The correct way is:
print(next(prime))
print(next(prime))
print(next(prime))
If you want them all, do:
for p in prime:
print(p)
Further, while not part of the answer, I give you a couple of programming tips:
for i in range(len(primeList)):
tempList.append(x % primeList[i])
has an unnecessary indirection. Just do
for prime in primeList:
tempList.append(x % prime)
Also, the entire tempList is unnecessary.
Just use a for-else construct:
def genPrime():
x = 1
primeList = []
while True:
x += 1
for prime in primeList:
if x % prime == 0:
break
else:
yield x
primeList.append(x)

Related

Twin Primes Python Program

I need to write a Python program that determines whether a given integer input is is a twin prime number or not. If the input number is a twin prime, the program must output true. Otherwise, it must output false.
Please may someone guide me with how this program should be written in Python?
This is what I have done so far. I am stuck at the is_twin_prime function part.
def is_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
def is_twin_prime(x):
if is_prime(x) = True:
N = int(input())
for i in range(N):
p = int(input())
if is_twin_prime(p):
print("true")
else:
print("false")
Based on the assumption, that you are trying to determine if N & p are twin primes of one another, I found several issues with your code as follows:
the is_twin_prime function has no False return
the is_prime function always starts with 2 and iteratively checks for prime, this is very inefficient.
To provide an answer, I started with the following factoids about twin_primes:
both numbers must be prime
abs(n-p) == 2
n and p must each have a units digit in [0, 2, 3, 5, 7, 8]
To make the function testing for twin primes as efficient as possible, I eliminated any numbers not meeting the last two cases first, and only if necessary did I generate a list of primes. Also, when generating the primes, I only did it once for the largest number since, once I have the list or the largest both numbers must be in the list.
To make searching for primes more efficient I employed itertools, although this could be done with slightly less efficiency without it's use.
import itertools
def erat2():
D = { }
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q*q] = q
yield q
else:
x = p + q
while x in D or not (x&1):
x += p
D[x] = p
def generatePrimes(given_number):
"""
Returns the prime number <= given_number using
an adaptive sieve of estraothenes approach
"""
return list(itertools.islice(erat2(), given_number))
def is_twinPrime(n, p):
accepted_digits = [0, 2, 3, 5, 7, 8]
if abs(n-p) != 2:
return False
elif n%10 not in accepted_digits and p%10 not in accepted_digits:
return False
else:
primes = generatePrimes(max(n, p))
if n in primes and p in primes:
return True
return False
N = int(input("Enter first number"))
P = int(input(Enter second number"))
print(istwinPrime(N, P)

Dynamic Programming Primitive calculator code optimization

I am currently doing coursera course on algorithms. I have successfully completed this assignment. All test cases passed. My code looks messy and I want to know if there is any thing availiable in Python which can help run my code faster. Thanks
The problem statement is as follows: You are given a primitive calculator that can perform the following three operations with
the current number 𝑥: multiply 𝑥 by 2, multiply 𝑥 by 3, or add 1 to 𝑥. Your goal is given a
positive integer 𝑛, find the minimum number of operations needed to obtain the number 𝑛
starting from the number 1.
# Uses python3
import sys
def optimal_sequence(m):
a=[0,0]
for i in range(2,m+1):
if i%3==0 and i%2==0:
a.append(min(a[i//2],a[i//3],a[i-1])+1)
elif i%3==0:
a.append(min(a[i//3],a[i-1])+1)
elif i%2==0:
a.append(min(a[i//2],a[i-1])+1)
else:
a.append((a[i-1])+1)
return backtrack(a,m)
def backtrack(a,m):
result=[]
result.append(m)
current = m
for i in range(a[-1],0,-1):
if current%3==0 and a[current//3]==(i-1):
current=current//3
result.append(current)
elif current%2==0 and a[current//2]==(i-1):
current = current//2
result.append(current)
elif a[current-1]==(i-1):
current = current-1
result.append(current)
return result
n = int(input())
if n == 1:
print(0)
print(1)
sys.exit(0)
a= (optimal_sequence(n))
print(len(a)-1)
for x in reversed(a):
print(x,end=" ")
I would use a breadth first search for number 1 starting from number n. Keep track of the numbers that were visited, so that the search backtracks on already visited numbers. For visited numbers remember which is the number you "came from" to reach it, i.e. the next number in the shortest path to n.
In my tests this code runs faster than yours:
from collections import deque
def findOperations(n):
# Perform a BFS
successor = {} # map number to next number in shortest path
queue = deque() # queue with number pairs (curr, next)
queue.append((n,None)) # start at n
while True:
curr, succ = queue.popleft()
if not curr in successor:
successor[curr] = succ
if curr == 1:
break
if curr%3 == 0: queue.append((curr//3, curr))
if curr%2 == 0: queue.append((curr//2, curr))
queue.append((curr-1, curr))
# Create list from successor chain
result = []
i = 1
while i:
result.append(i)
i = successor[i]
return result
Call this function with argument n:
findOperations(n)
It returns a list.

Using Recursive Functions in Python to find Factors of a Given Number

Have tried searching for this, but can't find exactly what I'm looking for.
I want to make a function that will recursively find the factors of a number; for example, the factors of 12 are 1, 2, 3, 4, 6 & 12.
I can write this fairly simply using a for loop with an if statement:
#a function to find the factors of a given number
def print_factors(x):
print ("The factors of %s are:" % number)
for i in range(1, x + 1):
if number % i == 0: #if the number divided by i is zero, then i is a factor of that number
print (i)
number = int(input("Enter a number: "))
print (print_factors(number))
However, when I try to change it to a recursive function, I am getting just a loop of the "The factors of x are:" statement. This is what I currently have:
#uses recursive function to print all the letters of an integer
def print_factors(x): #function to print factors of the number with the argument n
print ("The factors of %s are:" % number)
while print_factors(x) != 0: #to break the recursion loop
for i in range(1,x + 1):
if x % i == 0:
print (i)
number = int(input("Enter a number: "))
print_factors(number)
The error must be coming in either when I am calling the function again, or to do with the while loop (as far as I understand, you need a while loop in a recursive function, in order to break it?)
There are quite many problems with your recursive approach. In fact its not recursive at all.
1) Your function doesn't return anything but your while loop has a comparision while print_factors(x) != 0:
2) Even if your function was returning a value, it would never get to the point of evaluating it and comparing due to the way you have coded.
You are constantly calling your function with the same parameter over and over which is why you are getting a loop of print statements.
In a recursive approach, you define a problem in terms of a simpler version of itself.
And you need a base case to break out of recursive function, not a while loop.
Here is a very naive recursive approach.
def factors(x,i):
if i==0:
return
if x%i == 0:
print(i)
return factors (x,i-1) #simpler version of the problem
factors(12,12)
I think we do using below method:
def findfactor(n):
factorizeDict
def factorize(acc, x):
if(n%x == 0 and n/x >= x):
if(n/x > x):
acc += [x, n//x]
return factorize(acc, x+1)
else:
acc += [x]
return acc
elif(n%x != 0):
return factorize(acc, x+1)
else:
return acc
return factorize(list(), 1)
def factors(x,i=None) :
if i is None :
print('the factors of %s are : ' %x)
print(x,end=' ')
i = int(x/2)
if i == 0 :
return
if x % i == 0 :
print(i,end=' ')
return factors(x,i-1)
num1 = int(input('enter number : '))
print(factors(num1))
Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutations, variable reassignments, and other side effects. That said, here's how I'd write factors -
def factors(n, m = 2):
if m >= n:
return
if n % m == 0:
yield m
yield from factors(n, m + 1)
print(list(factors(10))) # [2,5]
print(list(factors(24))) # [2,3,4,6,8,12]
print(list(factors(99))) # [3,9,11,33]
And here's prime_factors -
def prime_factors(n, m = 2):
if m > n:
return
elif n % m == 0:
yield m
yield from prime_factors(n // m, m)
else:
yield from prime_factors(n, m + 1)
print(list(prime_factors(10))) # [2,5]
print(list(prime_factors(24))) # [2,2,2,3]
print(list(prime_factors(99))) # [3,3,11]
def fact (n , a = 2):
if n <= a :
return n
elif n % a != 0 :
return fact(n , a + 1 )
elif n % a == 0:
return str(a) + f" * {str(fact(n / a , a ))}"
Here is another way. The 'x' is the number you want to find the factors of. The 'c = 1' is used as a counter, using it we'll divide your number by 1, then by 2, all the way up to and including your nubmer, and if the modular returns a 0, then we know that number is a factor, so we print it out.
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)

Prime Factor Program Always Returning 3

Diving into coding for the first time and I'm trying to tackle the third Project Euler problem (finding the largest prime factor of 600851475143) and I want to write a function that simply returns the prime factors before I determine the largest one.
I cobbled together some shoddily written Python code below. It finds the factor of any number just fine but for some reason, the prime factor function always returns 3. Is there something I'm missing? Here's the code:
def factorize(j):
factors = []
print("Finding factors...")
for i in range(1, j+1):
if j % i == 0:
factors.append(i)
print("Done!")
print(factors)
return factors
def prime(n):
primes = []
for factor in n:
for p in range(1, factor+1):
for i in range (2, p):
if p % i == 0:
break
else:
primes.append(p)
print(primes)
return primes
print("Number to factor: ")
num = int(input())
num = factorize(num)
print("Now to find the primes...")
prime(num)
Thanks again for your help!
You put a return statement deep inside the nested loops of prime, so none of those loops completes an iteration.

Having trouble printing the final list when appending to a list

def eratos(n):
numbers = []
prime = [True for i in range(n+1)]
p=2
while(p <= n):
if (prime[p] == True):
for i in range(p * 2, n+1, p):
prime[i] = False
p+=1
lis =[]
# Print all prime numbers
for p in range(2, n):
if prime[p]:
numbers.append(p)
print(numbers)
if __name__:
n = 12
eratos(n)
This will print
whereas I'd only like the last list [2,3,5,7,11].
I understand the for loop I have will check if there is a prime number in my set range then add it into my list then repeat and check for the next number. If possible I'd like for it to check all numbers in the range and then append all of them at the same time, or append one at a time but only return the final list.
That's because the print statement is in the for loop. Simply move it outside:
for p in range(2, n):
if prime[p]:
numbers.append(p)
print(numbers) # outside for loop
Now the numbers list will be printed after the for loop is done. A final remark: why do you construct lis? You never seem to use it.
You can also improve the readability (and a bit of efficiency) with:
def eratos(n):
prime = [True] * (n+1)
for p in range(2,n+1):
if prime[p]:
for i in range(2*p,n+1,p):
prime[i] = False
# Print all prime numbers
numbers = [p for for p in range(2,n) if prime[p]]
print(numbers)

Resources