how can n=1 be the parameter of a function - python

I was doing an online course for python and on the functions part of the course, they made two functions (one for determining prime numbers and one printing them)
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def primes(n=1):
while(True):
if isprime(n): yield n
n += 1
for n in primes():
if n > 100: break
print(n)
what i don't understand is the parameter of the function primes. Why is it n=1. I'm new to programming in general as you could probably tell and I'm not very knowledgeable on functions and generators. Any help would be greatly appreciated.

It's a default value. If a parameter is passed to the function it will behave "normally", otherwise it will use the default.
def my_print(num=1):
print num
my_print()
>> 1
my_print(7)
>> 7

Keyword argument in the function call means a match by name, and in the
function header it specifies a default for an optional argument.

Related

Number of recursive function calls

I'm a total beginner at Python and I was wondering how to get the number of recursive function calls ?
is it 2^n (if n is the argument given)
The amount of calls completely depends on the algorithm. Sometimes it is 2**n, but other times it could be n! or a quadratic, or anything else.
To work out how many it is, you can you use my method. This might get shunned by some other users, but using a global counter is a quick and easy way to count the amount of function calls.
function_calls = 0
def fibonacci_recursive(n):
global function_calls
function_calls += 1
if n == 0:
return 1
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
ans = fibonacci_recursive(20)
print("There were",function_calls,"function calls.")

recursive function to sum of first odd numbers python

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)

exponential sum using recursion.python

I need to write a function using recursion that accepts the following variables:
n: int
x: real
and returns the exponential sum function:
I can't use loops at all, only recursion.
I started by writing two recursive functions for sum and factorial but when I tried to combine the two of them I got the error message:
TypeError: 'int' object is not iterable
I don't quite understand what it means because I didn't use loops, only recursion. Here is my code:
def sum_exp(n):
if n == 0:
return 0
return n + sum(n - 1)
def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
def exp_n_x(n, x):
if n == 0:
return 1
else:
return sum_exp(x*(1/factorial(n)))
print(exp_n_x(10, 10))
I would love to get some help with this. Thanks a lot in advance.
you've made a typo in:
def sum_exp(n):
if n == 0:
return 0
return n + sum(n - 1)
^^^
where you use the global function sum() which takes an iterable and returns the sum of its elements. Thus:
>>> sum(42)
TypeError: 'int' object is not iterable
whereas
>>> sum([42])
42
so your fix is straightforward:
def sum_exp(n):
if n == 0:
return 0
return n + sum_exp(n - 1)
N.B.: This answer is only meant to fix your issue with the TypeError, and get you going to the next error you'll hit, which is an infinite recursion. As an advice you should double check your stop condition and recursion step.

Variable Scope Issue in Python

I am new to Python and I have been working with it for a bit, but I am stuck on a problem. Here is my code:
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2,ctr)
else:
collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
For any number I put in for num, let's say 9 for instance, and 0 for ctr, ctr always comes out as 1. Am I using the ctr variable wrong?
EDIT:
I am trying to print out how many times the function is recursed. So ctr would be a counter for each recursion.
The variable ctr in your example will always be 1 because of the order of the recursive call stack. As one value of ctr is returned, then the call stack will start returning the previous values of ctr. Basically, at the very last recursive call, the highest value of ctr will be returned. But since the method call at the bottom of the call stack returns the very last value aka the value that will be stored in test, test will always be 1. Let's say I input parameters into collatz that would result in five total calls of the method. The call stack would look like this coming down,
collatz returns ctr --> 5
collatz returns ctr --> 4
collatz returns ctr --> 3
collatz returns ctr --> 2
collatz returns ctr --> 1 //what matters because ctr is being returned with every method call
As you can see, no matter how many times collatz is called, 1 will always be returned because the call at the bottom of the call stack has ctr equaling 1.
The solution can be a lot of things, but it really depends on the purpose of what you're trying to accomplish which isn't clearly stated in your question.
EDIT: If you want ctr to end up being the number of times a recursive call is made, then just assign ctr to the value of the method call. It should look like this,
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
ctr = collatz(num/2,ctr)
else:
ttr = collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
I changed your recursive calls to set the value received back from the recursive calls into ctr. The way you wrote it, you were discarding the values you got back from recursing.
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
ctr=collatz(num/2,ctr)
else:
ctr=collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
An example:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
Function parameters in Python are passed by value, not by reference. If you pass a number to a function, the function receives a copy of that number. If the function modifies its parameter, that change will not be visible outside the function:
def foo(y):
y += 1
print("y=", y) # prints 11
x = 10
foo(x)
print("x=", x) # Still 10
In your case, the most direct fix is to make ctr into a global variable. Its very ugly because you need to reset the global back to 0 if you want to call the collatz function again but I'm showing this alternative just to show that your logic is correct except for the pass-by-reference bit. (Note that the collatz function doesn't return anything now, the answer is in the global variable).
ctr = 0
def collatz(num):
global ctr
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2)
else:
collatz(num*3+1)
ctr = 0
collatz(9)
print(ctr)
Since Python doesn't have tail-call-optimization, your current recursive code will crash with a stack overflow if the collatz sequence is longer than 1000 steps (this is Pythons default stack limit). You can avoid this problem by using a loop instead of recursion. This also lets use get rid of that troublesome global variable. The final result is a bit more idiomatic Python, in my opinion:
def collats(num):
ctr = 0
while num != 1:
ctr += 1
if num % 2 == 0:
num = num/2
else:
num = 3*num + 1
return ctr
print(collatz(9))
If you want to stick with using recursive functions, its usually cleaner to avoid using mutable assignment like you are trying to do. Instead of functions being "subroutines" that modify state, make them into something closer to mathematical functions, which receive a value and return a result that depends only on the inputs. It can be much easier to reason about recursion if you do this. I will leave this as an exercise but the typical "skeleton" of a recursive function is to have an if statement that checks for the base case and the recursive cases:
def collatz(n):
if n == 1:
return 0
else if n % 2 == 0:
# tip: something involving collatz(n/2)
return #???
else:
# tip: something involving collatz(3*n+1)
return #???
The variable will return the final number of the collatz sequence starting from whatever number you put in. The collatz conjecture says this will always be 1

python recursive function that prints from 0 to n?

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.

Categories

Resources