I have to write code to manually input n number and code should find that n member of sequence.n should be natural number. Formula for that sequence is
f(n)=(f(n-1))²-1
First member is 2 second 3 third 8 and every next is one less than square of number before. The code should print that n member of sequence which is inputted.
For example
In:3
Out:8
In:4
Out:63
I wrote code but it don't work
n = int(input("'input n:"))
def f(n):
if n < 0:
print('Undefined')
else:
return (f(n - 1) ** 2) - 1
print(f(n))
In recursion, you need to return a definite value for the stop index.
Here you just have to write in your code that the first value of the sequence is 2:
def f(n):
if n < 0:
raise ValueError('Undefined') # better to raise to make sure to abort
elif n == 0:
return 2
else:
return (f(n - 1) ** 2) - 1
That is enough for f(1) to return 3 and f(2) to return 8...
Related
I'm new to python and I'm am having problems building a recursive function that checks if a given number is a Fibonacci number.
This is my code.
def isFib(n):
if n <= 1:
return n
else:
return (n - 1) + (n - 2)
if isFib(n) == 1 or isFib(n) == isFib(n - 1) + isFib(n - 2):
return True
It should print True in both cases, but instead it print True and False, and I can't find what's wrong
print(all([isFib(i) for i in [1,2,3,5,8,13,21,34,55]]))
print(all([not isFib(2*i) for i in [1,2,3,5,8,13,21,34,55]]))
The first part of your function is an if statement. If True, it returns a value - if False, it also returns a value. So, the second part of your function cannot possible execute, and the function isn't recursive (since you don't call the function again in either return statement).
More generally, what you're doing will never work. The logic seems to be: "a Fibonacci number is the sum of the previous Fibonacci number and the number before that, so I can reverse that logic by computing n - 1 and n - 2 and if they are Fibonacci numbers, then so is n" - or something like that.
But that doesn't work: 5 is a Fibonacci number, but (5-1) is not, so the logic breaks right there. If you were thinking only the sum needed to be a Fibonacci number: 13 is a Fibonacci number, but (13-1) + (13-2) = 23 and that's not a Fibonacci number either.
An easy way to solve this would be to just generate a Fibonacci sequence and return True as soon as the number you're checking comes up:
def is_fib(n, seq=None):
if seq is None:
seq = [0, 1]
# n is Fibonacci if the last number in the sequence is
# or if the last number has not yet past n, then compute the next and try again
return n == seq[-1] or (seq[-1] < n and is_fib(n, seq + [seq[-2] + seq[-1]]))
print([is_fib(i) for i in [1,2,3,5,8,13,21,34,55]])
print(is_fib(23))
I am trying to solve a problem where recursion is a must. The tasks is: Write a function that takes in an integer n and returns the highest integer in the corresponding Collatz sequence.
My solution is this:
collatz = []
def max_collatz(num):
collatz.append(num)
if num == 1:
return max(collatz)
else:
return max_collatz(num / 2) if num%2 == 0 else max_collatz((3 * num) + 1)
However, I need to find a way to solve it without using a list outside of the function. I really couldn't find a solution, is there any?
It's either the current number or the largest in the rest of the sequence.
def max_collatz(n):
if n == 1:
return 1
elif n % 2:
return max_collatz(3 * n + 1)
else:
return max(n, max_collatz(n // 2))
I've got a question- how do I write a function sum_even_factorials that finds the sum of the factorials of the even numbers that are less than or equal to n.
Eg:
sum_even_factorials(1)=
1
sum_even_factorials (3)=
3
sum_even_factorials (6)=
747
This is my current code:
Is there a logical error in the current code?
Is there a logical error in the current code?
To begin with, function sum_even_factorial doesn't return a value in every execution flow:
if cond1:
return val1
elif cond2:
return val2
else: # this part is missing in your code
return val3
In addition, note that when you call this function, you are not doing anything with the value that it returns:
sum_even_factorial(6)
Finally, although parts of your code are not visible in your question, I tend to guess that you cannot recursively compute the factorials of even numbers the way you did it, because the factorial of an even number n depends on the factorial of the odd number n - 1.
I think the code needs a loop. I'd write it like so:
def factorial(n):
if n == 0 or n == 1:
return 1;
else:
return n * factorial(n-1)
def sum_even_factorial(n):
current_sum = 0
while n >= 0:
if n % 2 == 0:
current_sum += factorial(n)
n -= 1
return current_sum
print(sum_even_factorial(6))
If you return tuples from the function, you can do it with one single function. See the comments in the code on how it works ...
def factorial_with_sum(n):
if n < 2:
return 1, 0 # first item of the tuple is the factorial, second item is the sum
else:
f, s = factorial_with_sum(n - 1) # calc factorial and sum for n - 1
f = f * n # factorial = n * factorial (n - 1)
if n % 2 == 0:
s = s + f # if n is even, add the current factorial to the sum
return f, s
fact, sum = factorial_with_sum(6)
print(fact)
print(sum)
You can also do it iteratively with a simple for loop as follows
def factorial_with_sum_iterative(n):
s = 0 # initialize sum
f = 1 # and factorial
for i in range(2, n + 1): # iterate from 2 to n
f = f * i # calculate factorial for current i
if i % 2 == 0:
s = s + f # if current i is even, add it to sum
return f, s
I need a function that takes n and returns 2n - 1 . It sounds simple enough, but the function has to be recursive. So far I have just 2n:
def required_steps(n):
if n == 0:
return 1
return 2 * req_steps(n-1)
The exercise states: "You can assume that the parameter n is always a positive integer and greater than 0"
2**n -1 is also 1+2+4+...+2n-1 which can made into a single recursive function (without the second one to subtract 1 from the power of 2).
Hint: 1+2*(1+2*(...))
Solution below, don't look if you want to try the hint first.
This works if n is guaranteed to be greater than zero (as was actually promised in the problem statement):
def required_steps(n):
if n == 1: # changed because we need one less going down
return 1
return 1 + 2 * required_steps(n-1)
A more robust version would handle zero and negative values too:
def required_steps(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 0
return 1 + 2 * required_steps(n-1)
(Adding a check for non-integers is left as an exercise.)
To solve a problem with a recursive approach you would have to find out how you can define the function with a given input in terms of the same function with a different input. In this case, since f(n) = 2 * f(n - 1) + 1, you can do:
def required_steps(n):
return n and 2 * required_steps(n - 1) + 1
so that:
for i in range(5):
print(required_steps(i))
outputs:
0
1
3
7
15
You can extract the really recursive part to another function
def f(n):
return required_steps(n) - 1
Or you can set a flag and define just when to subtract
def required_steps(n, sub=True):
if n == 0: return 1
return 2 * required_steps(n-1, False) - sub
>>> print(required_steps(10))
1023
Using an additional parameter for the result, r -
def required_steps (n = 0, r = 1):
if n == 0:
return r - 1
else:
return required_steps(n - 1, r * 2)
for x in range(6):
print(f"f({x}) = {required_steps(x)}")
# f(0) = 0
# f(1) = 1
# f(2) = 3
# f(3) = 7
# f(4) = 15
# f(5) = 31
You can also write it using bitwise left shift, << -
def required_steps (n = 0, r = 1):
if n == 0:
return r - 1
else:
return required_steps(n - 1, r << 1)
The output is the same
Have a placeholder to remember original value of n and then for the very first step i.e. n == N, return 2^n-1
n = 10
# constant to hold initial value of n
N = n
def required_steps(n, N):
if n == 0:
return 1
elif n == N:
return 2 * required_steps(n-1, N) - 1
return 2 * required_steps(n-1, N)
required_steps(n, N)
One way to get the offset of "-1" is to apply it in the return from the first function call using an argument with a default value, then explicitly set the offset argument to zero during the recursive calls.
def required_steps(n, offset = -1):
if n == 0:
return 1
return offset + 2 * required_steps(n-1,0)
On top of all the awesome answers given earlier, below will show its implementation with inner functions.
def outer(n):
k=n
def p(n):
if n==1:
return 2
if n==k:
return 2*p(n-1)-1
return 2*p(n-1)
return p(n)
n=5
print(outer(n))
Basically, it is assigning a global value of n to k and recursing through it with appropriate comparisons.
Forgive me, I'm new, but I want to build a recursive function that takes a natural number and returns the product of all the natural numbers from 1 up to the given number. So factorial(5) should return 120 (5·4·3·2·1 = 120). However, I think I am just stuck. Here is what I have so far:
def factorial(x):
"""returns the product of all natural numbers from 1 up to the given number
natural number -> natural number"""
if x <= 0:
return 1
else:
return x*(x-1)
Would the best route be to implement a counter?
First the statement in else needs to return a value, and because it's a factorial it should be x times the factorial of one less than x.
return x * factorial(x - 1)
The base case cannot be zero, firstly because the factorial of any number less than zero is undefined and any number times zero is zero, which makes the whole function pointless.
You should instead use the base case of:
if x <= 1:
return 1
So your function is:
def factorial(x):
if x <= 1:
return 1
else:
return x * factorial(x - 1)
def factorial(x):
"""returns the product of all natural numbers from 1 up to the given number
natural number -> natural number"""
if x <= 0:
return 1
else:
return x*(factorial(x-1))
You also need to recursively call the function again.