New factorial function without 0 - python

So, the standard factorial function in python is defined as:
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x-1)
Since n! := n * (n-1) * ... * 1, we can write n! as (n+1)! / (n+1). Thus 0! = 1 and we wouldn't need that if x == 0. I tried to write that in python to but I didn't work. Can you guys help me?

Since this is a recursive function (return x * factorial(x-1)) you must have an end condition (if x == 0:).
It is true that n! == (n+1)! / (n+1) and you could change your recursive call to :
def factorial(x):
return factorial(x+1) / (x+1)
But that again would have no end condition -> endless recursion (you will calling the next (n+1)! and than the (n+2)! and so on forever (or until you'll get an exception)).
BTW, you can have the condition stop your execution at 1:
if x == 1:
return 1

You wouldn't want to use recursive function for things that are not limited, hence I suggest doing a little bit importing from the standard library
from functools import reduce
import operator
def fact(x):
if not isinstance(x, int) or x <= 0:
raise Exception("math error")
else:
return reduce(operator.mul, range(1, x + 1), 1)
print(fact("string"))
print(fact(-5))
print(fact(0))
print(fact(5))
Just realized that there is no need for a hustle like that:
def fact2(x):
if not isinstance(x, int) or x <= 0:
Exception("math error")
else:
y = 1
while x > 1:
y *= x
x -= 1
return y

Related

Sum of Prime using Recursion in Python

The problem given is to determine whether two numbers m and n are prime or not, and if they are, give the sum of all prime numbers from m to n. I have already made a code for the first part:
def isPrime(n, i):
if n <= i:
return True if (n == 2) else False
if n % i == 0:
return False
if i * i > n:
return True
return isPrime(n, i + 1)
However, I don't know how to do the second part of the code. A clue that our professor gave to us was to call the first function in the second part of the code, like this:
def sumOfPrime(m, n):
**enter code here**
isPrime(m, 2)
isPrime(n, 2)
I've no idea how to know all the prime numbers from m to n. Also, we are only allowed to use recursion for this problem.
I assume your professor wants you to just test all numbers between m and n for primality, then add those that pass together.
def sumOfPrime(m, n):
if isPrime(m, 2) and isPrime(n, 2):
return sum(i for i in range(m, n + 1) if isPrime(i, 2))
Here is a fully recursive version:
def sumOfPrime(m,n):
if isPrime(n,2) and isPrime(m,2):
return sumOfPrimes(m,n)
def sumOfPrimes(m, n):
if m > n:
return 0
return (m if isPrime(m,2) else 0) + sumOfPrimes(m+1,n)
If only one function, maybe better with a nestet function:
def sumOfPrime(m,n):
def helper(m,n):
if m > n:
return 0
return (m if isPrime(m,2) else 0) + sumOfPrimes(m+1,n)
if isPrime(n,2) and isPrime(m,2):
return helper(m,n)
assert sumOfPrime(2,5) == 2 +3 + 5

python, power function using one loop

I tried to solve a problem, writing a power by function that does the same job as the operator ** (by python for example)
after I solve it, I got another assignment:
I'm allowed to use only one loop and only one if\else.
I would love for some insight
I'm a beginer and have no clue how to go further.
my code was:
...
def power(x, y):
s = x
if y > 0:
for i in range (1, y):
s = s * x
elif (y < 0):
for i in range (y, -1):
s = s * x
s = 1 / s
else:
s = 1
return s
print(power(3, 5))
print(power(3, -5))
print(power(3, 0))
Are you allowed to use the abs function?
from typing import Union
def power(x: Union[float, int], y: int) -> Union[float, int]:
s: Union[float, int] = 1
for _ in range(abs(y)):
s *= x
if y < 0:
s = 1 / s
return s
assert power(3, 5) == 243
assert 0.0040 < power(3, -5) < 0.0042
assert power(3, 0) == 1
A way I would do it is creating a function that accepts a number and an exponent.
Then I would create a list with exp amount of that number. Multiply everything in the list together to get the result:
def power(num, exp):
prod = 1
powers = [num] * exp
for n in powers:
prod *= n
return prod

create recursive power of 2 '*' in python

In pyschools, I am stuck in the power of 2 recursive function
>>> createStars(0) # 2 to power of 0 = 1
'*'
>>> createStars(1) # 2 to power of 1 = 2
'**'
>>> createStars(2) # 2 to power of 2 = 4
'****'
>>> createStars(3) # 2 to power of 3 = 8
'********'
What I am trying to do is as following:
def createStars(x):
if x == 0:
return '*'
else:
return '*' * x + createStars(x-1)
However, this seems to be a summation of 'x' not power of 2.
Meaning, this will break when the x is higher than 2
I know how to do the power of 2 recursively but no idea where to change to make createStars() work.
def power(x, n):
if n == 0:
return 1
else:
return x * power(x, n-1)
PS. I know it is easy to use non-recursive method to solve it.
But would like to seek advice how to do it in recursive way.
Thanks.
def createStars(x):
if x == 0:
return '*'
else:
return createStars(x-1) * 2
(Each step back in the recursion doubles the number of stars in the output string).
You're very close!
I would suggest comparing the two pieces of code you gave us. (I'm going to rename it a bit to make the analogy more clear):
def createStars(n):
if n == 0:
return '*'
else:
return '*' * n + createStars(n-1)
def power(x, n):
if n == 0:
return 1
else:
return x * power(x, n-1)
They have almost exactly the same structure. In particular, the last line of each has a slightly different structure.
In the (working) power, you multiply the result for n-1 by x. So, when computing the power(2, 6), you increase power(2, 5) by 2. (i.e. you multiply 32 by 2 to get 64).
In the (not working) createStars, you're not multiplying the result for the n-1 case by anything; you're just adding stuff to the start of it. What if you change it to make the structures match?
Also, you should check what the result is for createStars(1).

Generalized project euler #4

I tried some basic optimizations, to cut down on the number of operations for the general euler problem #4:
def is_palindrome(num):
return str(num) == str(num)[::-1]
def fn(n):
max_palindrome = 1
for x in range(n,1,-1):
for y in range(n,x-1,-1):
if is_palindrome(x*y) and x*y > max_palindrome:
max_palindrome = x*y
elif x * y < max_palindrome:
break
return max_palindrome
print fn(999)
Can I/how do I optimize this further? (assume it's the general solution, for factors of at most n rather than at most 999).
Some small optimizations: you can break out early of the x-loop and reduce the number of calls to is_palindrome by swapping the checks around a bit (untested):
def fn(n):
max_palindrome = 1
for x in range(n,1,-1):
if x * n <= max_palindrome: # nothing bigger possible for remaining x
break
for y in range(n,x-1,-1):
if x * y <= max_palindrome: #nothing bigger possible for current x
break
if is_palindrome(x*y):
max_palindrome = x*y
return max_palindrome

Simple program to find squre root using recursion

Hi I'm new to Python and I wrote a simple program to find the square root of a given number.
n = int(input("ENTER YOUR NUMBER: "))
g = n/2
t = 0.0001
def findRoot(x):
if ((x * x > n - t) and (x * x <= n + t)):
return x
else:
x = (x + n / x) / 2
findRoot(x)
r = findRoot(g)
print("ROOT OF {} IS {}".format(n, r))
t is the maximum error.
I know it's easy to use a while loop but I can't figure out what's wrong with this code. I debugged the code and after returning the value x (line 7), line 10 runs again resulting a "None" value.
Console output for any n, n > 0 (except 4) is ROOT OF (Given Number) IS None
Any idea how to correct the code?
You need to return something inside your else block. This should work:
def findRoot(x):
if ((x*x > n - t) and (x*x <= n + t)):
return x
else:
x = (x + n/x)/2
return findRoot(x)
An alternative as suggested by Alexander in the comment below is to remove the else altogether, because the code contained within will only ever be reached if we have not already returned inside the if block. So this is equivalent:
def findRoot(x):
if ((x*x > n - t) and (x*x <= n + t)):
return x
x = (x + n/x)/2
return findRoot(x)

Categories