I am trying to code a problem in python. It is to divide an integer number successively by 10 till the quotient < 10 i.e. no longer divisible by 10. here is my code - I am stuck, please help!
def recurDiv(N):
'''
N: a non-negative integer
'''
# Your code here
Q=N/10
R=N%10
if Q<=10:
return Q
else:
Q=recurDiv(N/10)*(N/10)**-1
R=N%10
return Q
You should work on clarifying your questions in the future but I think you're looking for this:
def recurDiv(N):
N/=10
R=N%10
if N<10:
return N
else:
return recurDiv(N)
But if you don't absolutely have to do it recursively you can get the same result with this:
def thing(N):
print(str(N)[0])
though you might want put something in to raise an error if N is not an integer or float.
Related
I was doing a programming challenge question where you need to found out if a given number (n) is equal to 3 raised to some exponent(x)
9 is True since 3^x -> 3^3 = 9
10 is False since no x for 3^x is equal to 10
my problem occurred when 243 was entered into my code, which returned a result of 4.999 repeating.
my solution was to simply add a round function, in which I arbitrarily decided on 5 decimal places, this solved the problem.
now another problem occurred when the input was 531440, this returns an x value of 11.999998287222695 which, according to the challenge, was false, but with my code returned a true since I rounded to the fifth decimal place. I then changed my round to 10 decimal places and this fixed the code.
I was wondering if there was a way to implement my solution without having to round, as I'm sure if I plugged in enough numbers eventually another one would need to round past >10 decimal places and cause my code to fail. Please see the code below.
import math as math
def isPowerOfThree(n):
print(math.log(n,3)) #this line prints the unrounded log result
print(round((math.log(n,3)),10)) #this line prints the rounded result
return n>0 and round((math.log(n,3)),10).is_integer()
n = 243
print(isPowerOfThree(n))
The 'trick' allowing to avoid problems with chosen precision is to round to an integer and then check if this exponent gives the required result. The code below implements this approach:
import math
def isPowerOfThree(N):
if 3**round(math.log(N,3)) == N:
return True
return False
N = 531440 # 243
print(isPowerOfThree(N)) # gives False
Another approach will be to check all powers of 3 against the target number:
def isPowerOfThree(N):
x = 1
while True:
n = 3**x
if n == N:
return True
elif n > N:
return False
x += 1
And here an approach detecting directly without the need to run multiple loop runs if a number is not a power of 3:
def isPowerOfThree(N):
while True:
N , r = divmod(N, 3)
if r != 0:
return False
if N == 1:
return True
P.S. the two last approaches provide code to what Karl Knechtel mentioned in his comment to the question.
Recently, I was trying to create an algorithm for finding a square root of a number. I am kind of new to python programming. This is my implementation:
def findSquareRt(num):
n = 8 #Initial Guess
while True:
if n**2 < num:
if not num/n == n:
temp = n
n = num/n
if (int((temp+n)/2))**2 == num:
return ((temp+n)/2)
else:
n = (temp+n)/2
But when i run the above code it just doesn't produce any output. Maybe it is the looping condition which is causing this, but i cant figure that out.
Your code has a lot of issues, one of them being that you will get an infinite loop if n**2 > num.
A simpler way of doing this would be something like this:
def findSquareRt(num):
return num**0.5
Thank you for responding to the question, From responses there were two problems:
first problem:
if n**2 < num:
this condition is always returning False on second or some other future iterations, and is redundant so this should be removed in order to get a solution.
second problem:
if (int((temp+n)/2))**2 == num:
The integer conversion of the expression ((temp+n)/2) is returning floor value of the float numbers, which effects the precision of the output hence the program stuck infinitely in the loop waiting for the condition to be True. Hence needed to be changed.
Final Solution:
def findSquareRt(num):
n = 8 #Initial Guess
while True:
if not num/n == n:
temp = n
n = num/n
if (((temp+n)/2))**2 == num:
return ((temp+n)/2)
else:
n = (temp+n)/2
else:
return n
I just started to study Python. I must use Python3.7.
Could someone show me a working factorial code?
i tried some i found here but i always get this error:
=================== RESTART: C:\programozás\pytutorial.py ===================
Code:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Your code is working, even though you could simply use the math library:
import math
print(math.factorial(5))
The problem does not come from your script, so maybe you should try to reinstall your python, and avoid paths with special characters as Adam Toth pointed out.
Update: to get the input and return a factorial as asked in comments
import math
print(math.factorial(int(input(">>"))))
The problem is most likely caused because you have a special character in the path to the .py file. So should use a folder like C:\programming, or anything without a special character, like 'á'.
It's very important to do like this, even if it does not solve your current problem, it can prevent many more in the future.
Ps.: Jó kiszúrni magyar programozót is :)
I see a related (older) thread here about this error
For the logic:
We have to consider:
Negative numbers
Zero
Positive numbers
So one way to write it will be:
def factorial(n):
if n < 0:
result = "Factorial doesn't exist for negative numbers"
elif n == 0:
result = 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result
You can try the concept of recursion as well.
To get the factorial of a number "num":
print(factorial(num))
Make sure you indent the code properly, indentation is important in python.
Hope it helps!
Python Code of Factorial Using Recursive Function:
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
factorial(5)
Note: The First Condition will only meet when the input is 0 or 1 and in else block n will be recursively multiplying n * n - 1.
I had an overflow error with this program here!, I realized the mistake of that program. I cannot use range or xrange when it came to really long integers. I tried running the program in Python 3 and it works. My code works but then responds after several times. Hence in order to optimize my code, I started thinking of strategies for the optimizing the code.
My problem statement is A number is called lucky if the sum of its digits, as well as the sum of the squares of its digits is a prime number. How many numbers between A and B are lucky?.
I started with this:
squarelist=[0,1,4,9,16,25,36,49,64,81]
def isEven(self, n):
return
def isPrime(n):
return
def main():
t=long(raw_input().rstrip())
count = []
for i in xrange(t):
counts = 0
a,b = raw_input().rstrip().split()
if a=='1':
a='2'
tempa, tempb= map(int, a), map(int,b)
for i in range(len(b),a,-1):
tempsum[i]+=squarelist[tempb[i]]
What I am trying to achieve is since I know the series is ordered, only the last number changes. I can save the sum of squares of the earlier numbers in the list and just keep changing the last number. This does not calculate the sum everytime and check if the sum of squares is prime. I am unable to fix the sum to some value and then keep changing the last number.How to go forward from here?
My sample inputs are provided below.
87517 52088
72232 13553
19219 17901
39863 30628
94978 75750
79208 13282
77561 61794
I didn't get what you want to achieve with your code at all. This is my solution to the question as I understand it: For all natural numbers n in a range X so that a < X < b for some natural numbers a, b with a < b, how many numbers n have the property that the sum of its digits and the sum of the square of its digits in decimal writing are both prime?
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
def sum_digits_squared(n):
s = 0
while n:
s += (n % 10) ** 2
n /= 10
return s
def is_prime(n):
return all(n % i for i in xrange(2, n))
def is_lucky(n):
return is_prime(sum_digits(n)) and is_prime(sum_digits_squared(n))
def all_lucky_numbers(a, b):
return [n for n in xrange(a, b) if is_lucky(n)]
if __name__ == "__main__":
sample_inputs = ((87517, 52088),
(72232, 13553),
(19219, 17901),
(39863, 30628),
(94978, 75750),
(79208, 13282),
(77561, 61794))
for b, a in sample_inputs:
lucky_number_count = len(all_lucky_numbers(a, b))
print("There are {} lucky numbers between {} and {}").format(lucky_number_count, a, b)
A few notes:
The is_prime is the most naive implementation possible. It's still totally fast enough for the sample input. There are many better implementations possible (and just one google away). The most obvious improvement would be skipping every even number except for 2. That alone would cut calculation time in half.
In Python 3 (and I really recommend using it), remember to use //= to force the result of the division to be an integer, and use range instead of xrange. Also, an easy way to speed up is_prime is Python 3's #functools.lru_cache.
If you want to save some lines, calculate the sum of digits by casting them to str and back to int like that:
def sum_digits(n):
return sum(int(d) for d in str(a))
It's not as mathy, though.
I am writing a program that gives me an overflow error. I realized that the cause of that was due to my input which could do inputs till 2147483646. I figured this using the sys.maxint. Anything beyond that gave me an overflow error. How I can take in inputs for large values? For value, 2147483646 my system hangs. How to deal with such an error. The statement of the problem here is given, A number is called lucky if the sum of its digits, as well as the sum of the squares of its digits is a prime number. How many numbers between A and B are lucky?
I am attaching the sample code here.
class luckynumbers():
#required numbers are only 0-9, their values can be stored in a lookup table
def __init__(self):
self.squarelist=[0,1,4,9,16,25,36,49,64,81]
def isEven(self, n):
if n%2 ==0:
return True
else:
return False
def isPrime(self,n):
return_val=True
if n==2:
return_val= True
if not self.isEven(n):
for i in xrange(2,n/2):
if n%i ==0:
return_val=False
break
else:
return_val= False
return return_val
def sumofDigits(self,n):
return sum(map(int, n))
def generateSquares(self, n):
return map(lambda x: self.squarelist[x], map(int,n))
def satisfy(self,n):
return self.isPrime(self.sumofDigits(n)) and self.isPrime(sum(self.generateSquares(n)))
def main():
luckyno=luckynumbers()
t=int(raw_input().rstrip())
count = []
for i in xrange(t):
counts = 0
a,b = map(int, raw_input().rstrip().split())
if a==1:
a=2
for j in xrange(a,b+1,1):
if luckyno.satisfy(str(j)):
counts+=1
count.append(counts)
for i in count:
print i
if __name__=='__main__':
main()
I am still looking at long integers document in python. But haven't figured a way yet. I have tried to use optimization as far as I can think of. Anything more, I will really grateful.
The xrange() function is limited to ints (not longs). The code works as expected if you replace the xrange() call where OverflowError occurs with just a range() call.