This question already has answers here:
Python "OverflowError" [duplicate]
(8 answers)
Closed 7 years ago.
While I was trying to find the largest prime factor of a number using the code below attached , I encountered OverflowError: Python int too large to covert to C long
def prime_factors(n):
i = 2
if prime(n)==1:
return n
while n>0 and i<n:
if n % i ==0:
n = n/i
div = i
prime_factors(n)
else:
i+=1
return div
def prime(n):
for i in xrange(2,n):
if n%i ==0:
return 0
return 1
num = int(raw_input())
print prime_factors(num)
Can anyone please help find a solution to this ?
P.S: I am a beginner in Python.
range() creates a list in memory, which will raise an error if n is too large. You should use xrange() instead, which will create a lazy-evaluated generator object.
Related
This question already has answers here:
Python Sets vs Lists
(10 answers)
Complexity of *in* operator in Python
(3 answers)
Closed 1 year ago.
I was solving a hackerrank challenge.(in Python 3)
At one point I needed to sort a list and work with it.
(2 <= len(array) <= 10^5)
The list is containing unique integers.
I used arr.sort(), but I was getting "Time limit exceeded" message
Then I found if I use set(arr), it runs fast and passes all test cases.
here's is my function for more clarification
def pairs(k, ar):
ar.sort()
c=0
for i in ar:
if i+k in ar:
c+=1
return c
This gets me "Time limit exceeded"
def pairs(k, ar):
ar=set(ar)
c=0
for i in ar:
if i+k in ar:
c+=1
return c
This one with set() runs faster.
Why is this set() is faster than sort().
Don't they use same sorting algorithm?
This question already has answers here:
Python:How to make the sum of the values of a while loop store into a variable?
(4 answers)
Closed 4 months ago.
Hello (beginner here),
I am trying to write a script that prints the sum of every even numbers in the range [0; 100].
However, I am getting a "TypeError: 'int' object is not iterable".
This is my code:
for i in range(0, 101):
total = 0
if i % 2 == 0:
total = sum(i)
print(total)
My error message:
Traceback (most recent call last):
File "", line 4, in
TypeError: 'int' object is not iterable
I've searched this website and Google to understand what I'm doing wrong, but I cant seem to grasp an answer to my specific code.
Any help would be greatly appreciated.
The problem is with the sum function it is not used in that manner. If you give 1 argument then it should be a list then you can use .append() function but in your use-case you can simply use + i.e., addition.
total = 0
for i in range(0, 101):
if i % 2 == 0:
total += i
print(total)
The sum() function can only sum up an iterable (list, dict, etc.). In your loop, your variable i is seen as a solid number, not a list. If you want to sum up every even number, you need to add i to a list:
list1 = []
for i in range(0, 101):
if i % 2 == 0:
list1.append(i)
total = sum(list1)
print(total)
Here is a better version, if you do not want the output after every single addition:
print(sum([i for i in range(0,101, 2)]))
the answer to your question using sum function can simply be
for i in range(0, 101, 2):
total = 0
total = sum(i, total)
print(total)
Learn more about Python loops here!
Learn Python fundamentals here!
This question already has answers here:
Nested Function in Python
(7 answers)
Closed 4 years ago.
Not a complicate question but I couldn't find an explicit answer around.
For example, if I want to find out the number of prime numbers in a list of numbers:
def count_prime(lst):
"""lst is a list of integers"""
def isPrime(n):
return all(n % div != 0 for div in range(2, int(n**0.5) + 1)) if n > 1 else False
result = 0
for num in lst:
if isPrime(num):
result += 1
return result
This looks very simple, but I put isPrime(n) inside of the main function.
How does it compare to:
def isPrime(n):
return all(n % div != 0 for div in range(2, int(n**0.5) + 1)) if n > 1 else False
def count_prime(lst):
"""lst is a list of integers"""
result = 0
for num in lst:
if isPrime(num):
result += 1
return result
My question is: Does it make any difference? Which one is preferred?
I think both approaches are valid. isPrime is very small, so it can be embedded easily. If you want to reuse the function, it makes sense to define it globally.
This question already has answers here:
How do I compare version numbers in Python?
(16 answers)
Closed 5 years ago.
I am trying to compare android version numbers in my code. If any version is less than 4.1 I want that version number.
Should I use comparison on strings directly as below?
Examples:
"4.0.3" < "4.1" # should return.
"5.0" < "4.1" # should not return.
Try this
def compare_versions_greater_than(v1, v2):
for i, j in zip(map(int, v1.split(".")), map(int, v2.split("."))):
if i == j:
continue
return i > j
return len(v1.split(".")) > len(v2.split("."))
a = "2.0.3"
b = "2.1"
print(compare_versions_greater_than(a, b))
print(compare_versions_greater_than(b, a))
Output
False
True
You can transform the version string to float. And then compare them.
def version2float(version):
main, *tail = version.split('.')
temp = ''.join(tail)
return float('.'.join([main, temp]))
This question already has answers here:
Sum of the integers from 1 to n
(11 answers)
Closed 5 years ago.
I have written the following code for an exercise I was given, nonetheless, when I try to submit it, I get an incorrect answer for my code.
So this is my code:
def problem(n):
my_sum = 0
while my_sum < n:
my_sum = n
my_sum = my_sum + n
print (my_sum)
What they have asked me to code is the following: Write a function problem(n): that adds up the numbers 1 through n and
prints out the result. You should use either a 'while' loop or a 'for' loop.
Be sure that you check your answer on several numbers n.
You can try this:
def problem(n):
print sum(xrange(1, n+1))
If you are not allowed to use the built in sum function, you can try this:
def problem(n):
counter = 0
for i in range(1, n+1):
counter += i
print counter
The top example uses a for loop in what is called list comprehension, which is a shorter way of utilizing the regular for loop.
Your solution will iterate through the while loop only once and when my_sum becomes >= to n it will stop.
What you need is:
for x in range(1, n+1):
my_sum += x
This will do the job. n+1 is done because the right boundary of range() is non-inclusive.