This code doesnt work for some reason but im not sure why
def rev(n):
if not n:
return 0
return rev(int(n/10))*10 + n%10
rev(512)
152
but when i save it in a specific variable and pass it through the function, it works.
why does this happen? anyone can help me with it?
def rev(n,r=0):
if not n:
return r
r = r*10 + n%10
return rev(int(n/10),r)
rev(512)
215
If you must use recursion to solve this problem, a possible way is to recursively compute the sum between each digit of n, multiplied by 10 to the power of n's order of magnitude at each recursion.
from math import log10
def rev(n):
if not n:
return 0
return int(n%10)*10**int(log10(n)) + rev(n//10)
As a side note, if you don't have to use recursion there are much simpler ways of doing this with str processing.
def rev(n,r=0):
if not n:
return r
r = r*10 + n%10
return rev(int(n/10),r)
#the above code can reverse the number digit by digit,bringing it forward;
def rev(n):
if not n:
return 0
return rev(int(n/10))*10 + n%10
#this code will do some other thing;
#once try for few examples;
#preferable 1234;
#you can get the differences of bith the algo
Related
I tried to solve this Kata problem
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
But the problem is my code gives the correct answers right for the first time around but when
it is run for 2nd time onward it gives wrong answers only. I think it has to do sth with how my code is recursive. Please help me figure it out.
for example when i run count_bits(24) it gives the output 2 which is correct but when i run the same function again it would give 4 and then 6 and so on . I dont know what's wrong with this
My code.
dec_num = []
def count_bits(n):
def DecimalToBinary(n):
if n >= 1:
DecimalToBinary(n // 2)
dec_num.append( n % 2)
return dec_num
dec = DecimalToBinary(n)
return dec.count(1)
There is no need to create a list of digits if all you need is their sum. When possible, avoid creating mutable state in a recursive solution:
def count_bits(n):
if n > 0:
return n % 2 + count_bits(n // 2)
else:
return 0
That's a pretty natural translation of the obvious algorithm:
The sum of the bits in a number is the last bit plus the sum of the bits in the rest of the number.
Sometimes it's convenient to accumulate a result, which is best done by adding an accumulator argument. In some languages, that can limit stack usage, although not in Python which doesn't condense tail calls. All the same, some might find this more readable:
def count_bits(n, accum = 0):
if n > 0:
return count_bits(n // 2, accum + n % 2)
else:
return accum
In Python, a generator is a more natural control structure:
def each_bit(n):
while n > 0:
yield n % 2
n //= 2
def count_bits(n):
return sum(each_bit(n))
Of course, there are lots more ways to solve this problem.
That is because dec_num is outside the method, so it's reused at every call, put it inside
def count_bits(n):
dec_num = []
def DecimalToBinary(n):
if n >= 1:
DecimalToBinary(n // 2)
dec_num.append(n % 2)
return dec_num
dec = DecimalToBinary(n)
return dec.count(1)
I have the following exercise:
'''FIBONACCI
Compute the n'th Fibonacci number fib(n), defined recursively:
fib(0) == 0, fib(1) == 1, fib(n) = fib(n - 1) + fib(n - 2)
Input:
A single line containing an integer n, 0 <= n <= 10.000
Output:
A single line with the integer fib(n).
Example:
Input: 10
Output: 55
'''
My raw attempt so to speak:
def fib(n):
if n <= 1:
return n
if n >= 2:
return fib(n-1) + fib(n-2)
n = int(input()) # Read integer n from standard input
print(fib(n))
However this code can only handle up to around n = 500 before reaching maximum recursion depth. To increase that number and create code that can handle up to 10 000, I have tried two things: 1) To increase maximum recursion depth and 2) To use memoization in the form of a decorator. Now the code can handle up to about n = 2000:
import sys
from functools import lru_cache
sys.setrecursionlimit(10000)
#lru_cache(maxsize=None)
def fib(n):
if n <= 1:
return n
if n >= 2:
return fib(n-1) + fib(n-2)
n = int(input()) # Read integer n from standard input
print(fib(n))
With n > 2000 I get an memory error (stack overflow). How do I fix this? What more can I do? Is it even possible with my recursive function or do I have to change it in some way to make it work? Any help is appreciated!
A simple implementation of the nth Fibonacci number. There is no need to use recursion.
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
fa, fb = 0, 1
for i in range(2, n + 1):
fa, fb = fb, fa + fb
return fb
(Note: this is not the fastest. It is O(n). An O(log n) solution is available -- e.g. here, see their method 5.)
With a recursive implementation, you will almost end up with trouble when trying to go to such great depths. Like #alaniwi stated, you can always implement it in a non-recursive method. Here's a O(n) time solution with a O(1) space complexity. (Note: Theoretically you can even get a O(log n) solution.)
from collections import deque
def fib(n):
past = deque([1], maxlen=2)
for _ in range(n): past.appendleft(sum(past))
return past[0]
Because the fibonacci function only requires the last two values of f, we can store only those and bubble upwards.
In the task they give a recursive definition of the fibonacci sequence but nothing is said about a recursive implementation.
This is an iterative implementation of the recursive definition:
def fib(n):
if n == 0:
return 0
f1, f2 = 0, 1
for i in range(1, n + 1):
f1, f2 = f2, f1 + f2
return f2
So here is the 2 python codes of Fibonacci series using recursive function. I wanted to know the difference between these code and why code(1) is not working, and code(2) works without any error?
This is not working and shows error of maximum recursion limit:
def f(n):
return f(n-1) + f(n-2)
n=8
f(n)
whereas this works:
def f(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return f(n-1) + f(n-2)
f(4)
Your first code has no way of stopping. It does not have the base cases for n == 0 or n == 1, so it will continue infinitely downwards with negative numbers.
If you add:
if n <= 1:
return 0
you're golden. (allthough it is a very inefficient implementation of fibonacci).
Why is it inefficient, well because each subtree are calculated many times over. f(8) calls f(7) and f(6), but f(7) also call f(6), so you get an exponential recursive tree. Your running time will be O(2^n). This is really bad, normally you will not be able to calculate fib for n even as low as 50.
You can do better if you include memoization:
from functools import lru_cache
#lru_cache(maxsize=None)
def fib2(n):
if n <= 1:
return n
else:
return fib2(n-1) + fib2(n-2)
This will remember if you have called f(n) before and return the answer you did last time. The issue now is that you need to remember previous called numbers, so while your running time has decreased to O(n), your space requirement is now O(n) too.
You can improve on this again, by abandoning recursive functions all together and go
def fib3(n):
if n == 0:
return 0
f1 = 0
f2 = 1
for i in range(n-1):
f1,f2 = f2, f1+f2
return f2
This is better, since you are only remembering two numbers at any time.
This question already has answers here:
Check if a number is a perfect square
(25 answers)
Closed 9 days ago.
I wrote a function that returns whether a number input is a square or not
def is_square(n):
if n<1:
return False
else:
for i in range(int(n/2)+1):
if (i*i)==n:
return True
else:
return False
I am confident that this code works. But when I did the test cases, example:test.expect( is_square( 4)), it says that the value is not what was expected.
Your function doesn't actually work, as it will immediatley return False on the first non-square-root found. Instead you will want to modify your code to be:
def is_square(n):
if n<1:
return False
else:
for i in range(int(n/2)+1):
if (i*i)==n:
return True
return False
such that it only returns false once all possible square roots have been checked. You may also want to look into math.sqrt() and float.is_integer(). Using these methods your function would become this:
from math import sqrt
def is_square(n):
return sqrt(n).is_integer()
Keep in mind that this method will not work with very large numbers, but your method will be very slow with them, so you will have to choose which to use.
To stick to integer-based algorithms, you might look at implementation of binary search for finding square root:
def is_square(n):
if n < 0:
return False
if n == 0:
return True
x, y = 1, n
while x + 1 < y:
mid = (x+y)//2
if mid**2 < n:
x = mid
else:
y = mid
return n == x**2 or n == (x+1)**2
The main idea of Python philosophy is to write simple code. To check if a number is an perfect square:
def is_square(n):
return n**0.5 == int(n**0.5)
When power to a float you can find the root of a number.
In Python 3.8+, use this:
def is_square(n):
root = math.isqrt(n)
return n == root * root
You can simply use simpy module
import it as,
from sympy.ntheory.primetest import is_square
and you can check for a number like this:
is_square(number)
It will return a boolean value
I think the best take, using only "built-in" integer arithmetic, is:
def issquare(n): return math.isqrt(n)**2==n
(Squares x**2 are a priori more efficiently computed than products x*x...)
According to my timings, this is (at least up to ~ 10^8) faster than sympy.numtheory.primetest.is_square.
(I use a different name to make it easier to compare the two.)
The latter is first using some modular checks that should speed it up considerably, but it has so much conversion and testing overhead (int, as_int, squares become n-th powers with n=2, integers are converted from "small" to multiprecision integers and back, ...) that all the advantage is lost. After a lot of tests, it roughly does the above, using ntheory.nthroot, which is again an overkill: designed for any n-th root, the square root is just one special case, and noting is optimized for this case. Some subroutines there even do very weird floating point arithmetics including multiplication with 1.0000000001 and similar horrors... I once got the following horrible error message: (The original output has the full path "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\" instead of each "..." below...)
File "...\sympy\ntheory\primetest.py", line 112, in is_square
return integer_nthroot(n, 2)[1]
File "...\sympy\core\power.py", line 86, in integer_nthroot
return _integer_nthroot_python(y, n)
File "...\sympy\core\power.py", line 94, in _integer_nthroot_python
x, rem = mpmath_sqrtrem(y)
File "...\mpmath\libmp\libintmath.py", line 284, in sqrtrem_python
y = isqrt_small_python(x)
File "...\mpmath\libmp\libintmath.py", line 217, in isqrt_small_python
r = int(x**0.5 * 1.00000000000001) + 1
KeyboardInterrupt
This gives a good idea of the abyss into which sympy's is_square hopelessly drowns...
Documentation: see is_square in Sympy's Ntheory Class Reference
P.S.: FWIW, regarding other answers suggesting to use round() etc, let me just mention here that ceil(sqrt(n))**2 < n (!!), for example when n is the 26th and 27th primorial -- not extremely large numbers! So, clearly, use of math.sqrt is not adequate.
def myfunct(num):
for i in range(0,num):
if i*i==num:
return 'square'
else:
return 'not square'
Easiest working solution, but not for large numbers.
def squaretest(num):
sqlist=[]
i=1
while i**2 <= num:
sqlist.append(i**2)
i+=1
return num in sqlist
Assuming that n >= 0:
def is_square(n):
tmp = int(n ** 0.5)
return n == tmp * tmp
print(is_square(81), is_square(67108864 ** 2 + 1)) # True False
Another approach:
def SQRT(x):
import math
if math.sqrt(x) == int(math.sqrt(x)):
return True
else:
return False
def is_square(n):
if n < 0:
return False
return round(n ** 0.5) ** 2 == n
To check if a number is a square, you could use code like this:
import math
number = 16
if math.sqrt(number).is_interger:
print "Square"
else:
print "Not square"
import math imports the math module.
if math.sqrt(number).is_interger: checks to see if the square root of number is a whole number. If so, it will print Square. Otherwise, it will print Not square.
Since math.sqrt() returns a float, we can cast that to a string, split it from "." and check if the part on the right(the decimal) is 0.
import math
def is_square(n):
x= str(math.sqrt(n)).split(".")[1] #getting the floating part as a string.
return True if(x=="0") else False
How do I go about computing a factorial of an integer in Python?
The easiest way is to use math.factorial (available in Python 2.6 and above):
import math
math.factorial(1000)
If you want/have to write it yourself, you can use an iterative approach:
def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact
or a recursive approach:
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
Note that the factorial function is only defined for positive integers, so you should also check that n >= 0 and that isinstance(n, int). If it's not, raise a ValueError or a TypeError respectively. math.factorial will take care of this for you.
On Python 2.6 and up, try:
import math
math.factorial(n)
Existing solution
The shortest and probably the fastest solution is:
from math import factorial
print factorial(1000)
Building your own
You can also build your own solution. Generally you have two approaches. The one that suits me best is:
from itertools import imap
def factorial(x):
return reduce(long.__mul__, imap(long, xrange(1, x + 1)))
print factorial(1000)
(it works also for bigger numbers, when the result becomes long)
The second way of achieving the same is:
def factorial(x):
result = 1
for i in xrange(2, x + 1):
result *= i
return result
print factorial(1000)
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
For performance reasons, please do not use recursion. It would be disastrous.
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
Check running results
cProfile.run('fact(126000)')
4 function calls in 5.164 seconds
Using the stack is convenient (like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.
If the stack is high, it means that the computer stores a lot of information about function calls.
The method only takes up constant memory (like iteration).
Or using a 'for' loop
def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
Check running results
cProfile.run('fact(126000)')
4 function calls in 4.708 seconds
Or using the built-in function math
def fact(n):
return math.factorial(n)
Check running results
cProfile.run('fact(126000)')
5 function calls in 0.272 seconds
If you are using Python 2.5 or older, try
from operator import mul
def factorial(n):
return reduce(mul, range(1, n+1))
For newer versions of Python, there is factorial in the math module as given in other answers here.
def fact(n):
f = 1
for i in range(1, n + 1):
f *= i
return f
Another way to do it is to use np.prod shown below:
def factorial(n):
if n == 0:
return 1
else:
return np.prod(np.arange(1,n+1))
Non-recursive solution, no imports:
def factorial(x):
return eval(' * '.join(map(str, range(1, x + 1))))
You can also make it in one line recursively if you like it. It is just a matter of personal choice. Here we are using inline if else in Python, which is similar to the ternary operator in Java:
Expression1 ? Expression2 : Expression3
One line function call approach:
def factorial(n): return 1 if n == 0 else n * factorial(n-1)
One line lambda function approach:
(although it is not recommended to assign lambda functions directly to a name, as it is considered a bad practice and may bring inconsistency to your code. It's always good to know. See PEP8.)
factorial = lambda n: 1 if n == 0 else n * factorial(n-1)