How would I use a function with two variables python? [closed] - python

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

Related

Python won't accept large numbers? [closed]

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))

random.randint() works when printing but not when assigning to a value [closed]

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.

Computing directly nth Fibonacci term without finding previous terms using binet's formula. (in O(1) time) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
from math import sqrt
n = int(input())
phi = (1 + sqrt(5))/2
fib_n = round((phi**n))
print(fib_n)
The above-mentioned code is not correct, it gives some nearer value to fib_n.
from math import sqrt
n = int(input())
phi = (1 + sqrt(5))/2
fib_n = round((phi**n)/sqrt(5))
print(fib_n)
This code works absolutely perfect after dividing by sqrt(5) in the 6th line.
My doubts are:
What is the significance of dividing by sqrt(5) and why only sqrt(5) and not any other number?
Can I solve the same thing using the floor or ceiling (or any other) and without dividing by root(5)?
Any help/guidance/resources are heavily appreciated!
This is the wrong formula.
The formula should be:
from math import sqrt
n = int(input())
phi1 = (1 + sqrt(5))/2
phi2 = (1 - sqrt(5))/2
fib_n = (pow(phi1, n) - pow(phi2, n)) / sqrt(5)
print(fib_n)
The sqrt(5) comes out of the proof: Proof
Basically, the sqrt(5) comes from solving the partial fractions
Side note: pow(phi, n) is usually more efficient than phi ** n and it can also compute mods. pow(phi, n, m) gives (phi ** n) % m

Python script- need help understanding this while loop [closed]

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.

Using a while loop to calculate the factorial of numbers between 0 and 10 in Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a simple program to calculate the factorial of a user inputted value, however, I want to write a program to output the values of the factorials of each number from 0 to 10. (inclusive)
my program:
def factorial(n):
f = 1
while (n > 0):
f = f * n
n = n - 1
return f
Thank you!
This question is probably destined for oblivion, but it costs nothing to answer.
#your function
def factorial(n):
f = 1
while (n > 0):
f = f * n
n = n - 1
return f
#a new function that loop the first one
def factorial_loop(n):
#in Python 2.x, you should use xrange() instead of range()
for i in range(n+1):
print(factorial(i))
factorial_loop(10)
You need to iterate your factorial recursive function from 1 to 10 and put the index as your argument.
I urge you to try to do this and code it, in order for you to improve your coding skills.
Hope it helps.

Categories