My recursive function doesn't seem to be working - it’s supposed to take parameters a and b and return
a^b.
Here it is:
def power(a, b):
If b == 0:
return
return a * power(a, b-1)
power(2, 3)
Base case return statement is null. You should return 1 (since a^0 = 1 for a != 0).
if b == 0:
return 1
You might want to handle the case for a = 0 separately though, since 0^0 is mathematically undefined:
if a == 0:
if b > 0:
return 0
else
# raise an exception here?
def power(a, b):
if b == 0:
return 1;
return a * power(a, b - 1);
Related
I just started working with recursive functions and I have to create a function that receives an integer and returns a new number that contains only the even digits. For example if it receives 23456, it should return 246. This is what I've tried:
def newInt(n):
dig = n % 10
if dig % 2 == 1:
return newInt(n//10)
elif dig % 2 == 0:
return str(n) + newInt(n//10)
print(newInt(32))
But I'm getting the following error:
RecursionError: maximum recursion depth exceeded in __instancecheck__
Any hints on what should I do to fix it?
You need a base case. There's also no need to convert any of the integers to strings. Here is a working version of newInt() that resolves both of these issues:
def newInt(n):
if not n:
return 0
dig = n % 10
if dig % 2 == 1:
return newInt(n // 10)
else:
return 10 * newInt(n // 10) + dig
Your issue is that you have no condition to stop recursion - every call to newInt results in another call. One way to stop would be to check if n is less than 10 and then just return n if it is even. For example:
def newInt(n):
if n < 10:
return n if n % 2 == 0 else 0
dig = n % 10
if dig % 2 == 1:
return newInt(n//10)
elif dig % 2 == 0:
return newInt(n//10) * 10 + dig
Note I have modified your function to return an integer rather than a string.
Here is a variant with divmod. Uncomment the print to see how it works:
def newInt(n):
d,r = divmod(n,10)
# print(n,d,r)
if d == 0:
return 0 if r%2 else r
if r % 2:
return newInt(d)
else:
return 10*newInt(d)+r
print(newInt(212033450))
Output: 22040
You don't even need to break out dig for each loop:
def newInt(n):
if n:
if n & 1:
return newInt(n // 10)
else:
return 10 * newInt(n // 10) + (n % 10)
return 0
This is a rewrite of #mozway's algortihm using Python 3.10 match..case syntax -
def newInt(n):
match divmod(n, 10):
case (0, r) if r & 1:
return 0
case (0, r):
return r
case (d, r) if r & 1:
return newInt(d)
case (d, r):
return 10 * newInt(d) + r
print(newInt(67120593306737201))
6200620
Note r & 1 is more efficient for testing if a number is even or odd. r % 2 performs division whereas & simply checks the first bit.
I need help for defining the fibanocci 2 function. The fibanocci 2 function is decribed as :
fib2(n) = {0 if n <= 0, 1 if n = 1, 2 if n = 2, ( fib2( n - 1) * fib2( n - 2)) - fib2( n - 3) else}
We need to define this function iterative.
I tried my best but i couldn't write a working code.
def fib2(n: int) -> int:
if n <= 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
else:
n = ((n - 1) * (n - 2) - (n - 3)
return n
a = fib2(7)
print (a)
assert (fib2(7) == 37)
the output from this fib2 function is 26 but it should be 37.
Thank you in advance
For the iterative version you have to use a for loop.
And just add the 3 previous numbers to get the next one.
Here is a piece of code:
def fib3(n):
a = 0
b = 1
c = 0
for n in range(n):
newc = a+b+c
a = b
b = c
c = newc
return newc
print(fib3(7))
assert (fib3(7) == 37)
You can not change the value of a parameter.
Please try to return directly :
Return ((fb2(n-1)×fb2(n-2))-fb2(n-3))
So it will work as a recursive function.
def fibo(n):
current = 0
previous_1 = 1
previous_2 = 0
for i in range(1,n):
current = previous_1 + previous_2
previous_2 = previous_1
previous_1 = current
return current
To do it iteratively, the best way is to write it on paper to understand how it works.
Mathematically fibo is Fn = Fn-1 + Fn-2 . Therefore, you can create variables called previous_1 and previous_2 which represents the elements of Fn and you simply update them on each run.
Fn is current
class Solution(object):
def getSum(self, a, b):
if (a == 0):
return b
if (b == 0):
return a;
while(b != 0):
_a = a ^ b
_b = (a & b) << 1
a = _a
b = _b
return a
But when one of a, b < 0 or both, how the script should be like?
+ operator internally makes a call to __add__(). So, you may directly call a.__add__(b) to get sum. Below is the modified code:
>>> class Solution(object):
... def getSum(self, a, b):
... return a.__add__(b)
...
>>> s = Solution()
>>> s.getSum(1, 2)
3
OR, you may use operator.add(a, b) as:
>>> import operator
>>> operator.add(1, 2)
3
I enjoy solving other people's problems.
class Solution(object):
def getSum(self, a, b):
return sum([a, b])
Edit: If you are in for some fantasy. You can do operator overloading.
class CrappyInt(int):
def __init__(self, num):
self.num = num
def __eq__(self, a):
return self.__add__(a)
m = CrappyInt(3)
n = CrappyInt(4)
print m == n
# 7
This maybe a little hard for you now. But it is fun.
You can also use operator package
import operator
class Solution(object):
def getSum(self, a, b):
return operator.add(a, b)
And if you want to hassle with binary bitwise operations. Here is first method:
def complex_add_1(x, y):
while y != 0:
b = x & y
x = x ^ y
y = b << 1
return x
And here is the another one with recursion:
def complex_add_2(x, y):
if y == 0:
return x
else:
return complex_add_2(x ^ y, (x & y) << 1)
Edit: methods with bitwise operations are working only in Python 3
My old highschool program that I found on my usb stick. Yes it's crude but it works.
def s(a,b):
a = bin(a)[2:]
b = bin(b)[2:]
c_in = 0
value = ''
if not len(a) == len(b):
to_fill = abs(len(a) - len(b))
if len(a) > len(b):
b = b.zfill(len(a))
else:
a = a.zfill(len(b))
for i,j in zip(reversed(a),reversed(b)):
i_xor_j = int(i) ^ int(j)
i_and_j = int(i) and int(j)
s = int(c_in) ^ int(i_xor_j)
c_in_and_i_xor_j = int(c_in) and int(i_xor_j)
c_in = int(i_and_j) or int(c_in_and_i_xor_j)
value += str(int(s))
value += str(int(c_in))
return int(value[::-1],2)
print(s(5,9))
#>> 14
Or I would have see if I could cheat with sum.
This was kinda fun :) I'm not sure if this is what you're after, but these all should work so long as you're using integers
def subtract(a, b):
if a < 0:
return negative(add(negative(a), b))
if b < 0:
return add(a, negative(b))
if a < b:
return negative(subtract(b, a))
if b == 0:
return a
return subtract(a^b, (~a & b) << 1)
def negative(a):
if a == 0: return 0
a = ~a
b = 1
while b > 0:
a, b = a^b, (a&b) << 1
return a
def add(a, b):
if a < 0:
return negative(subtract(negative(a), b))
if b < 0:
return subtract(a, negative(b))
if b == 0:
return a
return add(a^b, (a & b) << 1)
def multiply(a, b):
if a == 0 or b == 0:
return 0
if b < 0:
a = negative(a)
b = negative(b)
A = 0
while b > 0:
A = add(A, a)
b = subtract(b, 1)
return A
def div(a, b):
if b == 0:
raise ZeroDivisionError
if a == 0:
return 0
if b < 0:
a = negative(a)
b = negative(b)
A = 0
if a < 0:
while a < 0:
a = add(a, b)
A = subtract(A, 1)
else:
while b < a :
a = subtract(a, b)
A = add(A, 1)
return A
def mod(a, b):
return subtract(a, multiply(div(a, b),b))
negation by two's compliment is used to get a function where a and b are both greater than 0 and the correct operation (addition or subtraction) is selected. further with subtraction, care is taken to not yield a negative result. This is done because the recursive definitions of add and subtract hate crossing 0. Also in this case the recursive add and subtract do the exact same thing as your loop.
Here is my code:
def lcm(a, b):
if b == 0:
return a
return a * b / lcm(a, b)
print lcm(5,3)
This is what I could manage so far, any idea on how to find the LCM (least common multiple) of two numbers using recursive and one function?
We have lcm(a, b) * gcd(a, b) = a * b. So we can write the following equation:
lcm(a, b) = a; if a % b == 0
lcm(a, b) ; if a % b != 0
= a * b / gcd(a, b)
= a * b / gcd(b, a % b)
= a * b / (b * (a % b) / lcm(b, a % b))
= a / (a % b) * lcm(b, a % b)
And translate to Python, we have:
def lcm(a, b):
t = a % b
if t == 0: return a
return a * lcm(b, t) / t
Edit: I didn't read the recursive / one function bit in your question cause I'm dumb. Incorporated now.
The lcm isn't a * b / lcm(a, b), it's a * b / gcd(a, b) (greatest common divisor).
So the cleanest way to do this is:
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(x, y):
return x * y / gcd(x, y)
If you are limited to recursion only (e.g. for an exam) then this doesn't have to be efficient, so you might as well just recursively count up until you find the lowest number that both x and y divide into:
def lcm(x, y, counter=1):
if (counter%x == 0 and counter%y == 0):
return counter
return lcm(x, y, counter+1)
That just increases counter until counter%x == 0 and counter%y == 0 is true, which is the LCM. Don't try it on large numbers though, you'll just get a stack overflow.
As stated in the other answers here lcm = a*b / gcd(a, b)but then you will need to define another function gcd(a, b) for it.
Since you needed only 1 function with recursion, maybe this piece of code will do.
N.B. : This function has one extra parameter c which should be always passed as 1 while calling it outside the function only :
def lcm(a, b, c):
d = c
m = min(a, b)
while m > 1 :
if a%m == 0 and b%m == 0 :
d*=m
return lcm(int(a/m), int(b/m), d)
else:
m-= 1
d*= a*b
return d
Using the mathematical relationship that the product of two numbers is equal to the product of the Greatest Common Divisor and the Least Common Multiplier of those two numbers: A * B = GCD(A,B) * LCM(A,B)
def gcd(a,b):
if a % b == 0: return b
return gcd(b, a % b)
def lcm(a, b):
return ((a*b) // gcd(a,b))
The first function is recursive and it's used to find the Greatest Common Divisor, it has cost O(log(n)).
This should do:
# Python Program to find the L.C.M. of two input number
# define a function
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
# choose the greater number
if x > y:
greater = x
else:
greater = y
while True:
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
I created my own easy programme.
def lcm(greater,a,b):
# while(True):
if (greater % a == 0 and greater % b == 0):
lcm1 = greater
return lcm1
else:
lcm1=lcm(greater + 1,a,b)
return lcm1
a=int(input(" Enter 1st number :"))
b=int(input(" Enter 2nd number :"))
if(a>b):
greater=a
else:
greater=b
print(lcm(greater,a,b))
I must write a function that computes the logarithm of a number x relative to a base b (rounded down if the answer is not an integer). I wrote this function but it's not working
def myLog(x, b):
result = 1
if b > x :
result -= 1
return result
elif x == b :
return result
else :
result += 1
b *= result
return myLog(x,b)
Why are you multiplying the base by result and changing the base? When you determine that the base fits into the input number, you should be dividing the number by the base. Since the division means the final number is 1 more, you add 1 to the result of the recursive call.
def myLog(x, b):
result = 1
if b > x:
result -= 1
return result
elif x == b:
return result
else:
x /= b
return 1 + myLog(x, b)
Example: myLog(32, 2):
32/2 = 16, add 1 to answer
16/2 = 8, add 1 to answer
...
answer = 5
Some of the code is unnecessary though, and I would further edit it to be this:
def myLog(x, b):
if b > x:
return 0
elif x == b:
return 1
else:
x /= b
return 1 + myLog(x, b)