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.
Related
I was doing an assignment question.
Write a program, divisible_by_11(num), to return the divisibility of num
by 11. i.e. divisible_by_11(num) should return True is num is divisible by 11,
or False otherwise. Implement this function recursively and using the following algorithm.
Note: a number is divisible by 11 if the difference between the sum of odd digits
and the sum of even digits is divisible by 11. Note that 0 is divisible by 11.
def divisible_by_11(num):
def helper(num,i):
if num==0:
return 0
elif i%2:
return helper(num//10,i+1)-num%10
Question is about replacing the above line with return -num%10+ helper(num//10,i+1)
elif i%2==0:
return num%10+helper(num//10,i+1)
return helper(num,0)%11==0
this code works, however if I wrote return -num%10+ helper(num//10,i+1) instead of return helper(num//10,i+1)-num%10, my code would fail. Can anyone tell me what's happening?
The issue with the alternate form is due to order of operations. The unary-minus operator binds more tightly than the mod operator. That is, the expression -num%10 is interpreted as (-num) % 10, and the modulus of a negative number is not the same thing as its last digit.
There are a few ways you could fix it. The easiest would probably be to add your own parentheses so that the mod happens first: return -(num%10) + helper(num//10,i+1) should work as expected.
Unrelated to that issue, I'm very skeptical that your assignment allows you to do %11 in the final return, since that operation is all you would need to solve the whole problem without the rest!
Instead, I suspect it wants you to use recursion for that part too (and maybe not for adding up the digits). Instead of return helper(num,0)%11==0, try:
while num > 10:
num = helper(num, 0)
return num == 0
We just started learning python this year in school, and so far we are only doing basic stuff with tkinter canvas (drawing houses, flowers etc.) and our teacher kinda sucks so I had to learn everything I know by now myself.
I've been thinking about this idea of writing a function to find the digital sum of a number (without recursion preferably) so I came up with this:
def sum(n):
total=0
for letter in str(n):
total+=int(letter)
return total
But then, I had an idea about using recursion to find the "absolute dig. sum of a number", for instance 99=9+9=18 =>1+8=9
and I came up with this
total=0
def suma(n):
global total
def part_sum(n):
global total
total_part=0
for letter in str(n):
total_part+=int(letter)
total=total_part
if total<10:
print(total)
else:
part_sum(total)
part_sum(n)
which basically makes a sum of n, checks if it is lower than n, if it is not it runs it again (basic recursion), but it uses a bunch of variables and global variables (which are for some reason bad as I've heard) and I am well aware it could be done much more efficiently using classes and objects, but I've only watched couple of vidoes on that so I'm not very good at it.
Could someone please edit my code and paste it here with some notes to help me understand it?
Recursion is often overused. I believe you can write suma() much more clearly without it. Build on what you have already created.
def sum(n):
total=0
for letter in str(n):
total+=int(letter)
return total
def suma(n):
while n >= 10:
n = sum(n)
return n
Here's my solution
def rec_dig_sum(n):
total = str(sum(map(int, str(n))))
while len(total)>1:
total = str(sum(map(int, total)))
return int(total)
You can think of map as taking map(function, [input1, input2, input3]) and returning [function(input1), function(input2), function(input3)]
Instead of saving a variable and updating it with each iteration of a loop (the normal way to do this):
def iterative_sum(num):
while num >= 10:
num = int(sum(map(int, str(num))))
return num
Send it as an argument to a new function call:
def recursive_sum(num):
if num >= 10:
return recursive_sum(sum(map(int, str(num))))
return num
You can also make a recursive function to do the initial summation, and use that in the function that keeps doing so until it's only one digit:
def rc(n, c=0):
if n:
return rc(n//10, c+n%10)
return c
def rs(n):
if n >= 10:
return rs(rc(n))
return n
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.
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 must find if a number is even or not. It needs to follow this template. I can get it to find if a number is even or not recursively
The key is that you need to return a boolean value:
def isEven(num):
if (num <= 0):
return (num == 0)
return isEven(num-2)
For larger numbers though this quickly exceeds the default maximum recursion depth for Python. That can be remedied by calling sys.setrecursionlimit(n) where n is the number of recursive calls you want to allow. n in turn is limited by the platform you are on.
Try this, it works for integer values with 0 <= n <= sys.getrecursionlimit()-2:
def even(n):
return True if n == 0 else odd(n - 1)
def odd(n):
return False if n == 0 else even(n - 1)
It's a nice example of a pair of mutually recursive functions. Not the most efficient way to find the answer, of course - but nevertheless interesting from an academic point of view.
This template will help. You need to fill in the commented lines. The one you have in the question won't work - you aren't passing anything into isEven. This will only work if n >= 0, otherwise it will crash your program. Easy enough to fix if you ever need to deal with negative numbers.
def isEven(n):
if n == 0:
# Number is even
elif n == 1:
# Number is odd
else:
# Call the function again, but with a different n
Taking up wim's challenge to find a "different" way to do this: The prototypical recursive pattern is foo(cdr(x)), with a base case for the empty list… so let's write it around that:
def isEven(num):
def isEvenLength(l):
if not l:
return True
return not isEvenLength(l[1:])
return isEvenLength(range(num))
A really dumb use case for recursion, but here is my version anyway
import random
def isEven(num):
if random.random() < 0.5:
# let's learn about recursion!
return isEven(num)
else:
# let's be sane!
return num % 2 == 0
disclaimer: if you submitted this you'd probably tick off the teacher and come across as a smartypants.