Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to find the largest prime factor of a number. Below is my code in Python. When I input 600851475143, it doesn't give me an output. Is this code wrong?
def prime(n):
list = []
only_primes = []
for i in range(2,int(n)):
if n%i==0:
list.append(i)
for number in list:
if isprime(number)==True:
only_primes.append(number)
print(max(only_primes))
def isprime(k):
for z in range(2,int(k**1/2)+1):
if k%z==0:
return False
return True
print(prime(600851475143))
There are a couple things wrong here.
Most notably, the indentation on your 2nd for loop is off which is causing that loop to be ran every single iteration of the first for loop. It should be at the same indentation as the first so it can run strictly after.
Your algorithm is still far too slow to compute the largest prime factor of the number 600,851,475,143. It will only run in a feasible amount of time for numbers in the millions range. If you would like to run computations for numbers of that size, you will have to use a more advanced technique.
You are missing parentheses for the exponent in isprime's for loop.
In the case that your input number happens to be prime, your code will crash due to the only_primes list being empty.
Here is a fixed version:
def prime(n):
list = []
only_primes = []
for i in range(2, int(n)):
if n % i == 0:
list.append(i)
for number in list:
if isprime(number):
only_primes.append(number)
if len(only_primes) > 0:
return max(only_primes)
return n
def isprime(k):
for z in range(2, int(k**(1/2) + 1)):
if k % z == 0:
return False
return True
print(prime(1001))
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to make a minesweeper game as a practice project but I have ran into an error when generating the random coordinates for the bombs. Basically, when I run the random.randint() function, it gives me an error when I try to assign it, but not when I print it out.
import random
def assignBombs(grid, k):
m = len(grid) - 1
n = len(grid[1]) - 1
while k > 0:
i = random.randint(0, m)
j = random.randint(0, n)
if grid[i][j].bomb == False:
grid[i][j].bomb == True
n -= 1
return grid
grid = initialize(5, 5)
grid = assignBombs(grid, 4)
The initialize function will make a 5x5 grid of Cells, a class which has the boolean self.bomb. Please let me know if I need to provide this.
Anyway, this will give me the following error when running:
ValueError: empty range for randrange() (0, 0, 0)
However, if I replace the while loop in the function with a simple print statement:
def assignBombs(grid, k):
m = len(grid) - 1
n = len(grid[1]) - 1
print(m, n, random.randint(0, n), random.randint(0, m))
This will print out just fine:
4 4 3 4
Where m and n are the max row and column indices. Any help is appreciated!
You do not change k inside the loop, so it won't stop looping, decreasing n and eventually making it 0.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
I am practicing list comprehensions and nested list comprehensions. As part of my practice I am writing out equivalent for loops. This for loop I cannot get right, and I believe it's because I'm trying to assign a value rather than a variable in a function call. The error I receive is:
File "<stdin>", line 4
SyntaxError: can't assign to function call
The code I have written for this loop is:
import math
def squared_primes():
list = []
for x in range(1,1000000):
for q in range(2,math.sqrt(x)+1):
if all(x % q != 0):
list.append(x**2)
print(list)
This function is trying to create a list of perfect squares whose roots are prime numbers in the range 1 to 1000000.
Can someone help me understand where exactly the syntax of my loop breaks down? Also, can I possibly do this as a nested list comprehension? Clearly my list comprehension is breaking down because I can't get my for loop syntax right...
SOLUTION: Thanks to user #Evan, I was able to fix the variable and syntax problems, and took some cues about how to fix the all() statement from this thread.
This code will properly return a list of the squared primes from 1,1000:
def squared_primes():
list1 = []
for x in range(1,1000):
if all(x%q !=0 for q in range(2,int(math.sqrt(x)+1))):
list1.append(x**2)
print(list1)
This code will properly return a list of the squared primes from
1,1000:
Except that it returns 1 as the first element of the list and 1's square root isn't a prime. Let's fix that glitch and rewrite the code as a proper function:
from math import sqrt
def squared_primes(maximum):
primes = []
for number in range(2, maximum):
if all(number % divisor != 0 for divisor in range(2, int(sqrt(number)) + 1)):
primes.append(number ** 2)
return primes
print(squared_primes(1000))
BTW, this is not a list comprehension:
all(x % q !=0 for q in range(2, int(math.sqrt(x) + 1)))
it's a generator! If you wanted a list comprehension you would have done:
all([x % q !=0 for q in range(2, int(math.sqrt(x) + 1))])
but stick with the generator as it fails composites with less effort.
Your code will start to bog down when we ask for a list of the squares up to 1000000 (a million) or more. That's when we'll want a more efficient sieve-based algorithm like:
def squared_primes(maximum):
sieve = [True] * maximum
if maximum > 0:
sieve[0] = False # zero is not a prime
if maximum > 1:
sieve[1] = False # one is not a prime
for index in range(2, int(maximum ** 0.5) + 1):
if sieve[index]:
prime = index
for multiple in range(prime + prime, maximum, prime):
sieve[multiple] = False
return [index * index for index in range(maximum) if sieve[index]]
At around a million, this code will return results about 20x faster than your division-based solution.
And #Evan's glorious comprehension, since it lacks your math.sqrt() optimization, will be orders of magnitude slower than either (I'm still waiting for it to finish for one million) and starts the list with two incorrect results. We can put it on a par time-wise with your revised code by doing:
from math import sqrt
def squared_primes(maximum):
return [number ** 2 for number in range(2, maximum) if all(number % divisor for divisor in range(2, int(sqrt(number)) + 1))]
print(squared_primes(1000))
And this is a list comprehension. But again, the wrong approach so go back and look at the sieve-based implementation.
This is pretty concise. List comprehensions are glorious.
def squared_primes(maximum):
return( [ x**2 for x in range(0,maximum) if all( x % i for i in range(2, x) ) ] )
print(squared_primes(1000000))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My gf is studying CS and needs help understanding how this script runs and why?
What value does mystery(9870) return?
def mystery(n):
m = " "
while n > 0:
m += str(n % 10)
n //= 10
return m
The possible answers are-
"789"
"0789"
"7890"
"987"
"9870"
We just need to know how the code runs?
Can anyone help?
This is the proper indentation you need to use.
def mystery(n):
m = ""
while n > 0:
m += str(n % 10)
n //= 10
return m
When you call the function:
mystery(9870)
' 0789'
The function takes a parameter and checks if it is greater than 0. While the condition is satisfied, it divides the number by 10 and converts the remainder into a string and appends it to an empty string m. n //= 10 will remove the last digit of the number and stores the remaining in n. And the while loop checks if n is greater than 0 again. Etc.. The whole thing continues until n is a single digit number at which point, n//=10 will return 0 and the condition of while loop will not satisfy.
Basically, it reverses the digits of the number you pass as parameter.
Hope this explanation helps.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I was curious if anyone could fix my code, this is for project Euler Question 3 (What is the largest prime factor of the number 600851475143 ?), as of now, I am sticking to a program that will find all the prime factors in 100, but am getting an error message for divide by 0, in my head the code seems to work, but it isn't. Unless absolutely necessary, I'd like to keep the while loops. Thanks.
def isPrime(A):
x = 2
while x < A:
if A % x == 0:
return False
x += 1
return A
def isInt(x):
if x == int(x):
return True
return False
A = int(input("Number? "))
counter = 2
while counter <= A:
if isInt(A/isPrime(counter)) == True:
print(counter)
counter += 1
print ("Done")
It seems the key issue is that isPrime() sometimes returns a boolean, and other times returns the input (an integer). You should avoid having functions that do too many things at once - a function called isPrime() should just indicate whether the input is prime or not (i.e. always return a boolean). Some other suggestions inline:
def isPrime(n): # n is a common variable name to use for "some number"
x = 2
while x < n:
if n % x == 0:
return False
x += 1 # this isn't an ideal way to detect primes, can you think of any improvements?
return True
def isInt(n): # use consistent variables - you used A above and x here, which is confusing
return n == int(n) # you can just return the boolean result directly
input = int(input("Number? ")) # use meaningful variable names when possible
counter = 2
while counter <= input:
# I *think* this is what you were trying to do:
# if counter is prime and input/counter is an integer.
# If not you may need to play with this conditional a bit
# also no need to say ' == True' here
if isPrime(counter) and isInt(input/counter):
print(counter)
counter += 1
print ("Done")
This should run (whether it works or not, I leave to you!), but it's still not as efficient as it could be. As you get into harder Project Euler problems you'll need to start paying careful attention to efficiency and optimizations. I'll let you dig into this further, but here's two hints to get you started:
Incrementing by one every time is wasteful - if you know something is not divisible by 2 you also know it's not divisible by 4, 8, 16, and so on, yet your code will do those checks.
In general finding primes is expensive, and it's a very repetitive operation - can you re-use any work done to find one prime when finding the next one?
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have tried to creat a code,that given number n,it will print F[n] (wereas F the function i created in order to calculate the fibonacci number) .But apparently there is something wrong because no matter the input,the result is always 1.Heres is the code:
def fib(n):
a=1
b=1
x=1
for i in range(n):
a=b
b=x+b
x=a
return a
n=input()
print fib(n)
Python is a whitespace sensitive language. The scope of a block of code in Python is determined by the level of indentation so:
def fib(n):
a=1
b=1
x=1
for i in range(n):
a=b
b=x+b
x=a
return a # <--- the first time you run through the loop you return
return a is in the for loop as it is indented at the same level as the rest of the for loop. So the first time you run through the loop you reach the return statement which leaves the function at that point in time. This is most likely not what you want. You need to take the return outside the for loop, like so:
def fib(n):
a=1
b=1
x=1
for i in range(n):
a=b
b=x+b
x=a
return a # <--- now no longer in the loop.
Now the loop will run through all of range(n) and you can return your result after that.