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
So the question reads: Design a function that accepts an integer argument and returnβs the sum of all integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function will return the sum of 1,2,3,4β¦β¦.50. Use recursion to calculate the sum.
im having lots of trouble as you can tell by my code
def main():
numbers= int(input('Enter a number to add the sums: ')
mysum = sum_num(numbers,1)
def sum_num(numbers,mysum):
start=1
end=numbers
if start>end:
return 0
else:
return my_sum
main()
def sumup(n):
# this one is your emergency break. you return 1 if n gets below
# a certain threshold, otherwise you'll end up with an infinite
# loop
if n <= 1:
return n
# here is the recursion step, we return (n + "the sum to n+1")
else:
return n + sumup(n-1)
print(sumup(50))
Golfing a bit:
def sumup(n):
return (n + sumup(n - 1) if n > 1 else n) if isinstance(n, int) else None
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 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 1 year ago.
Improve this question
Good day, I want to write a python code to recursively calculate the entries of the Fibonacci sequence using a function. This function should take in as input an integer number which should denote the limit after which the recursion should stop.
This is what I have:
def fib2(n: int) -> int:
if n<2:
return n
return fib2(n - 2) + fib2(n - 1) # recursive case
If I call this function, say fib(4) I only get '4' returned, whereas I expect a set of calls, namely the recursion calls. Where is the mistake?
Edit: Thanks for the tips. I'm just at the beginning of learning Python and realized after the fact that the code indeed worked out. So I'm getting the right output. The reason I was confused was that I was expecting to obtain the whole series of outputs leading to the final expression. Now I know that this would be possible using a for-loop, for example.
I think f(1) = 0 so you need to make it
def fib2(n: int) -> int:
if n==1:
return 0
elif n==2:
return 1
return fib2(n - 2) + fib2(n - 1) # recursive case
I think you have a mistake in actually implementing the Fibonacci algorithm.
Actually, the problem is in implementing the Fibonacci algorithm.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
According to Wikipedia Fibonacci number.
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
F(0) = 0, F(1) = 1
and
F(n) = F(n - 1) + F(n - 2) [where n > 1]
Sample Code
def fib(n: int) -> int:
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
Output
print(fib(4))
# 3
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Write a function lowest_integer() which takes 2 input arguments:
a function f representing an increasing function π(π₯),
a number fmin,
and returns an integer nmin such that ππππ>0 is the smallest
integer that satisfies π(ππππ)>ππππ.
To test the function we use code like this where we define f(n) then
print(lowest_integer(f, fmin)) and get the expected output:
def f(n):
return 2*n
print(lowest_integer(f, 10))
## 6
def f(n):
return n**2 + 6*n - 3
print(lowest_integer(f, 500))
## 20
My attempt at the code:
def lowest_integer(f, fmin):
f = fmin
nmin = n + 1
return nmin
I'm having trouble figuring out how to define the function f(n) within the lowest_integer() function
You can loop through the integers starting at 1, until you find one that satisfies your condition, in that case, return it:
def lowest_integer(f, fmin):
nmin = 1
while True:
if f(nmin) > fmin:
return nmin
nmin += 1
def f(n):
return 2*n
print(lowest_integer(f, 10))
def f(n):
return n**2 + 6*n - 3
print(lowest_integer(f, 500))
Output:
6
20
This approach, of course, is a naive one, and will be slow if the function f is slow and fmin is very big, but in general it does good.
A faster approach would be using a library like sympy or something, that have functions that use more sophisticated methods and techniques that are suited to these kinds of problems.
def f(n):
return 2*n
def lowest_integer(f, fmin):
for findmin in range(fmin):
if f(findmin) > fmin:
return findmin
return -1
print(lowest_integer(f, 10))
You can do it like that :
def lowest_integer(f, fmin):
nmin=1
while f(nmin)<=fmin :
nmin += 1
return nmin
You begin with nmin = 1 and you add 1 to nmin while f(nmin)<=fmin. To do that, you can use a while loop.
By doing f(nmin), you call the function f and calculate its value for the entry nmin.
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 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.