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.
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 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))
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 2 years ago.
Improve this question
I'm supposed to calculate an approximation for the absolute value of any integer x. I need to write a function abs_approx(x, N) that calculates the N first terms of the sum and returns f(x). I am to use the function to compute the approximation for N=1,2,3,4.
The function is:
This is my following program, but I get that the absolute value of 1 is 0.3009465364104349. Which is completely wrong. Anyone see what I'm doing wrong?
from math import pi, cos
def abs_approx(x,N):
N=4
sum=0
for n in range(0,N+1):
num=cos((2*n-1)*x)
denom=(2*n-1)**2
sum+=num/denom
f=pi/2-4/pi*(sum)
return f
print(abs_approx(1,1))
print: 0.3009465364104349
Did you mean to loop from 1 to N?
from math import pi, cos
def abs_approx(x, N):
sigma = 0
for n in range(1, N + 1):
num = cos((2*n-1)*x)
denom = (2*n-1)**2
sigma += num/denom
f = (pi/2) - (4/pi*(sigma))
return f
print(abs_approx(1, 4))
Output:
0.988880798353344
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 2 years ago.
Improve this question
Is there a way to use FOR loop in python such that checking conditions on range values can be altered.
Basically convert this code into python using FOR loop(not using while loop or if-break).
for(int i = 1;i*i<=n;++i)
{
#code statements
}
You could check the highest value of i beforehand by taking the square root of n.
n = 10
for i in range(1, int(n**0.5) + 1):
print(i, i**2)
1 1
2 4
3 9
Does filter work for you?
n = 100
for i in filter(lambda x: x**2 <= n, range(1, n)):
print(i, i**2)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to programming and I am trying to write a program that takes a positive integer n from input, and then outputs all factorizations of n.
For example if n=10 the program would output
1 times 10 equals 10
2 times 5 equals 10
5 times 2 equals 10
10 times 1 equals 10
I believe the easiest way to do it is to use an if statement nested within for loops. Can anybody provide me with any guidance to help create this? So far I have...
n = int(input())
a = 0
b = n
for a in range(0, n):
if a * b !=n:
continue
if a * b ==n:
print (a+ "times" +b+ "equals" +n)
a=a+1
b=n-1
But for some reason it isn't working. I think I have the right general idea but my code is obviously incorrect.
There are a few issues with your code, but also with your logic. You are increasing a twice (with for and addition), b becomes n-1 the first time through the loop and stays that way, but even if it didn't (eg b = b - 1), it wouldn't work, because if you are increasing a and decreasing b simultaneously, you won't find the correct values unless they happen to match by chance.
Other than that, it's unnecessary to check for a * b != n, you need to call str on the integers to add them to strings and the 0 in your range call is redundant.
whncode's answer is an elegant solution (except for a couple of errors I tried to correct), but to use your logic, you might do this:
for a in range(1, n+1):
for b in range(1, n+1):
if a * b == n:
print str(a) + " times " + str(b) + " equals " + str(n)
n = 10
for divisor in range(n, 0, -1): # reverse range
if (n%divisor == 0): # if modulo is 0
print("%d times %d equals %d", (n/divisor, divisor, n)