L=[]
def Prime(N):
a=0
for i in range(2,N):
if N%i==0:
a+=1
if a>0:
return False
else:
return True
def PrimesList(N):
if N==2:
L.append(2)
elif Prime(N):
L.append(N)
return PrimesList(N-1)
else:
return PrimesList(N-1)
L.reverse()
print L
If I use it one time, it gives the correct answer. But L is being saved in global environment. How can I bring it inside loop when using recursion? The question might be basic for most of you but I am new to Python. I am supposed to print the prime numbers till N.
I would do it as a second parameter, using None to avoid this common issue:
def PrimesList(N, L=None):
if L is None:
L = []
...
Then just include L in the recursive call and make sure you return L from the end of he recursion.
To print the first N prime numbers you can just print the first N-1 prime numbers and add next prime. However to compute next prime the list of numbers is also useful so in addition to print it just return the list:
def printFirstPrimes(N):
if N == 1:
result = [2]
else:
result = printFirstPrimes(N-1)
# ... compute next prime here ...
result.append(next_prime)
print result
return result
Note that this is not the best approach with Python, deep recursion is not very efficient and tail call optimization is not implemented in the reference implementation CPython.
Related
I wrote a function filter_primes that is supposed to (aptly) filter out prime numbers from a given list and output a new list of just the primes. When I run this example I get>>> [9].
My brain is boggled. Can someone point me in the right direction?
n = 2
def is_prime(num):
global n
if num%n != 0 and n<num:
n = n + 1
is_prime(num)
elif n == num:
return True
else:
return False
def filter_primes(list1):
list2 = []
for i in list1:
if is_prime(i):
list2.append(i)
print(list2)
filter_primes([7, 9, 3, 9, 10, 11, 27])
The problem is in your is_prime function. Since you are doing it recursively, you want to separate it into:
Handle the base cases:
You find an n that evenly divides num, then num isn't prime
You end up with an n bigger than num, then num is prime
Otherwise, call your function recursively with n+1 and return that value.
One way to get around using the global n (which then gets overwritten each time a new larger is used), is to have is_prime have a default starting value for n)
For example,
def is_prime(num, n=2):
if n >= num: # This could be made into sqrt(num) if you're trying to optimize this
return True
if num % n == 0:
return False
return is_prime(num, n+1)
The way I tackled this was to open the code up in an IDE (IntelliJ), and then step through the code line by line using an intergrated debugger. This will help you visualize what is going on. Else try printing out variables inside the function.
You first problem is that you are using global n. This works perfectly fine for the first number 7, but this number doesn't get reset for the second number 9. Thus what is happening is that is_prime(9) is only testing against division of 8 (which is why it returns true)
This could potentually be done in a loop rather than using recursion, but since you are using recursion, n (as internal state) can be handled by passing this as a function parameter with a default. This will reset n for each top level call for n.
Also as you are recursively calling is_prime(), you need return is_prime() to ensure the boolean returned from the top of the stack gets returned when you unwind back to the bottom of the stack for the original caller.
Your code accidently worked for is_prime(9) because your logic was only testing for 8, thus could return without recusion.
Here is working code:
def is_prime(num, n=2):
if num % n != 0 and n < num:
n = n + 1
return is_prime(num, n)
elif n == num:
return True
else:
return False
def filter_primes(list1):
list2 = []
for i in list1:
if is_prime(i):
list2.append(i)
return list2
print( filter_primes([7, 9, 3, 9, 10, 11, 27]) )
$ primes.py
[7, 3, 11]
Also you might find it intresting to do a little reading up on prime number search algorithms.
A few simple optimizations:
Except for 2, all prime numbers are odd (so you can return False instantly)
Sieve of Eratosthenes extends this further
Technically you only need to search upto sqrt(num)
Read up on memoization (aka dynamic programming), as you can cache results from previous function calls
Add python type hints and write documention for your functions (your future self will thank you when you return the code in a month)
Consider a new usecase:
generate the entire sequence of prime numbers (you will start to notice performance issues here)
Add a timer, or use a profiler inside your IDE. Compare how fast the code runs, especially for large numbers. Do these suggested optimizations speed things up?
I'm trying to convert below code to recursive function but seems i'm quite confusing how could i write below in recursive function. could help me to give some thoughts?
Basically, what I'm generating below is the sum of the first n odd numbers.
def sum_odd_n(n):
total=0
j=2*n-1
i=1
if i>j:
return 1
else:
total =((j+1)/2)**2
i+=2
return total
> >>> sum_odd_n(5)
> 25.0
> >>> sum_odd_n(4)
> 16.0
> >>> sum_odd_n(1)
> 1.0
This smells somewhat like homework so I'm going to offer some advice instead of a solution.
Recursion is about expressing a problem in terms of itself.
Suppose you know the sum of the odd numbers from N to N - 2.
Can you write the total sum in terms of this sum and the function itself (or a related helper function)?
Recursive functions have at least one base case and at least one recursive call. Here are some hints:
def f(n):
# Base case - for which
# n do we already know the answer
# and can return it without
# more function calls? (Clearly,
# this must also terminate any
# recursive sequence.)
if n == ???:
return ???
# Otherwise, lets say we know the answer
# to f(n - 1) and assign it to
# the variable, 'rest'
rest = f(n - 1)
# What do we need to do with 'rest'
# to return the complete result
return rest + ???
Fill out the question marks and you'll have the answer.
Try:
def sum_of_odd(n):
if n>0:
x=(n*2)-1
return x+sum_of_odd(n-1)
else:
return 0
The answer of this:
sum_of_odd(5)
will be:
25
Try :
def sum_odd_n(n):
if n>0:
if n==1:
return 1
else:
return 2*n-1 + sum_odd_n(n-1)
I am supposed to write two functions that do the exact same thing but their implementation is different.
The function takes as input a list of positive integers and a positive integer n, and returns True if two of the numbers in list equal to n. Otherwise, it returns False.
The first function is supposed to use a nested a loop, which I was able to get.
The second functions is not supposed to use a nested loop. However, you are supposed to sort the list out and then solve the problem.
Here is what I have for the second function.
def pairs2(lst, n):
lst.sort()
if len(lst) == 2:
if lst[0] + lst[1] == n:
return True
else:
return False
elif len(lst) >= 3:
for i in range(len(lst) - 1):
if lst[0] + lst[i + 1] == n:
return True
lst.remove(lst[0])
pairs2(lst, n)
The function works until the last two lines are implemented. After that, it doesn't return anything. What is wrong with my function?
Also, are they any other alternatives to that I do not use recursion? I just came up with using recursion since it was the first idea that I got.
A recursive algorithm that eliminates the largest number at each recursive step:
def pairs2(lst, n, s=False):
if len(lst) < 2: return False
if not s: lst = sorted(lst)
for item in lst:
if item + lst[-1] > n:
return pairs2(lst[:-1], n, True)
if item + lst[-1] == n:
print item, lst[-1]
return True
return False
The s parameter indicates whether the list is already sorted or not.
def pairs2(lst, n):
[pair for pair in itertools.combinations(lst,2) if sum(pair) == n]
Instead of using recursion, you could use the brute-force approach to find the pairs using the itertools.combinations.
Read more about itertools: https://docs.python.org/2/library/itertools.html
I am trying to write a recursive function that prints from 0 to n, but I have no idea how to do it. I accidentally made one that prints from n to 0 though:
def countdown(n):
print(n)
if n == 0:
return 0
return countdown(n - 1)
I don't know if that helps or not, maybe I can change something in the code to make it go from 0 to n?
You're about 99% there.
Think of your base case and your recursive step - when you hit 0, what do you want to do? When you're still working your way down from n, what do you want to happen?
If you reverse the order in which you print the value, you'll reach your desired result.
def countdown(n):
if n != 0:
countdown(n-1)
print(n)
The reason this works is that recursive calls go on the call stack. As you push calls onto the stack, while your end case isn't met, you'll keep adding more calls until you reach your base case of n == 0, and then you'll exclusively start printing the values.
The other calls will then fall through to the print statement, as their execution has returned to the line after the conditional.
So, the call stack looks something like this:
countdown(5)
countdown(4)
countdown(3)
countdown(2)
countdown(1)
countdown(0)
print(0)
print(1)
print(2)
print(3)
print(4)
print(5)
You almost got it! here's a fixed, simplified version:
def countup(n):
if n >= 0:
countup(n - 1)
print(n)
Notice that:
You don't have to return anything from a recursive function that only prints values
For printing in ascending order, the print statement must be placed after the recursive call
The recursion exits when n < 0, given that we're only printing, there's nothing left to be done afterwards and it's ok to return None (Python's default return value)
UPDATE
It seems that writing a tail recursive solution is all the rage around here :) oh well, here's my shot at it, a simplified and tail-recursive version of #AndyHayden's idea - using the tail call optimization decorator recipe:
#tail_call_optimized
def countup(N, n=0):
print(n)
if n < N:
countup(N, n + 1)
Either way, it works as expected:
countup(5)
=> 0
1
2
3
4
5
You can replace the 0 and the n, and the + with a - to make your recursive countdown function to a recursive countup:
def countup(N, n=0):
print(n)
if n == N:
return
return countup(N, n + 1)
And call it as follows:
countup(3)
#JFSebastian points out this algorithm has the benefit of being O(1) rather than O(n), as discussed in this excellent article about the difference between a linear and iterative recursion, if used with the #tail_call_optimized decorator.
You can do this
def fun(num,n):
if num<n:
print(num)
fun(num+1,n)
n=int(input())
print(fun(0,n+1))
you can try this method as well:
def recursion_print(n):
if n==0:
print(n)
else:
recursion_print(n-1)
print(n)
recursion_print(9)
It should be best answer from my side.I hope u like this
def countdown(n):
if n >0: #this condition if n is greater than 0 untill run the program.
countdown(n-1) #this is recursion (calling itself).
print(n) #print the numbers.
countdown(10) #function arguments.
I am new to programming, and was trying to solve this problem on Project Euler using basic Python.
Essentially, I tried to use recursion based on the largest value chosen at every stage, and using a list to maintain possible options for future choices.
The code is short and is given below:
def func(n,l):
if n<0:
return 0
if l==[1] or n==0:
return 1
else:
j=0
while l != []:
j=j+func(n-l[0],l)
del l[0]
return j
print func(200,[200,100,50,20,10,5,2,1])
For instance, if we have
func(5,[5,2,1])
the recursion splits it into
func(0,[5,2,1]) + func(3,[2,1]) + func(4,[1])
But the code never seems to go through. Either it says that there is a list-index-out-of-range error, or a maximum-recursion-depth error (even for very small toy instances). I am unable to find the mistake. Any help will be much appreciated.
In Python lists are passed into functions by reference, but not by value. The simplest fix for your program is changing recursive call to func(n - l[0], l[:]). In this way list will be passed by value.
One thing you're failing to take into account is that the following:
j=j+func(n-l[0],l)
doesn't make a copy of l.
Therefore all recursive invocations of func operate on the same list. When the innermost invocation deletes the last element of l and returns, its caller will attempt to del l[0] and will get an IndexError.
At each recursion, make the following 2 decisions:
Take the first coin (say f) from available coin types, then check if we can made (n-f) from those coins. This results in a sub-problem func(n - f, l)
Ignore the first coin type, and check if we can make n from the remaining coin types. This results in a sub-problem func(n, l[1:])
The total number of combinations should be the sum of the two sub-problems. So the code goes:
def func(n, l):
if n == 0:
return 1
if n < 0 or len(l) == 0:
return 0
if l == [1] or n == 0:
return 1
return func(n - l[0], l) + func(n, l[1:])
Each recursion a copy of l is made by l[1:]. This can be omitted by pop element before next recursion and restore with append afterwards.
def func(n, l):
if n == 0:
return 1
if n < 0 or len(l) == 0:
return 0
if l == [1] or n == 0:
return 1
full = func(n - l[-1], l)
last = l.pop()
partial = func(n, l)
l.append(last)
return full + partial