I am trying to use Fibonacci series and get Cubes of the series. My Fibonacci function is giving an output but I want that output to be in a List form.
Following is my code
cube = lambda x : x ** 3
def fibonacci(n):
a = 0
b = 1
count = 0
if n < 0:
print("Incorrect input")
elif n == 0:
return a
elif n == 1:
return b
else:
while count < n:
print(a)
c = a + b
a = b
b = c
count += 1
if __name__ == "__main__":
n = int(input())
print(list(map(cube,fibonacci(n))))
I am getting the following output with error:
6
0
1
1
2
3
5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-58624b7f0dd2> in <module>
1 if __name__ == "__main__":
2 n = int(input())
----> 3 print(list(map(cube,fibonacci(n))))
TypeError: 'NoneType' object is not iterable
I am very new to coding. Please help!
If you'd your Fibonacci function to return a list, change it as follows:
def fibonacci(n):
a = 0
b = 1
count = 0
res = []
if n < 0:
print("Incorrect input")
elif n == 0:
return [a]
elif n == 1:
return [b]
else:
while count < n:
res.append(a)
c = a + b
a = b
b = c
count += 1
return res
You can then run:
n = 5
print(list(map(cube,fibonacci(n))))
Which results in:
[0, 1, 1, 8, 27]
While you could build a list right away as shown here, this task can be solved more efficiently using generators.
The idea is that with the generator you do the computation when actually required and you do not (need to) store potentially large intermediate objects.
Also, note how swapping is done in Python and why name = lambda ... is an anti-pattern in Python.
def fibonacci(n):
a = 0
b = 1
count = 0
if n < 0:
print("Incorrect input")
return
elif n == 0:
yield a
elif n == 1:
yield b
else:
while count < n:
yield a
a, b = b, a + b
count += 1
def cube(x):
return x ** 3
n = 8
print(list(fibonacci(n)))
# [0, 1, 1, 2, 3, 5, 8, 13]
print(list(map(cube, fibonacci(n))))
# [0, 1, 1, 8, 27, 125, 512, 2197]
Related
I want to generate list of primes of the format x2+1 but I am not getting any output.
My code:
def LPrime(n):
for i in range(1,n):
x = i**2+1;
for j in range(2,x):
if x % j != 0:
print(x,i)
Please tell me what am I doing wrong.
The expected output should be something like
2,1
5,2
and so on
Also I am not able to execute it properly, I am using Ubuntu 22.04
There is no output when I try to
If if x % j == 0: you have a divisor. and j will not be 1 or x. So you should mark p as False (there is no prime). else, it is a prime; print it.
def LPrime(n):
for i in range(0, n):
x = i**2+1
p = True
for j in range(2, x):
if x % j == 0:
p = False
if p:
print(f"Prime = {x},\t i = {i}")
Don't forget to call it
>>> LPrime(4)
Prime = 1, i = 0
Prime = 2, i = 1
Prime = 5, i = 2
If you want n primes, use a while loop:
def LPrime(n):
count = 0
i = 0
while count < n:
x = i**2+1
p = True
for j in range(2, x):
if x % j == 0:
p = False
if p:
print(f"Prime = {x},\t i = {i}")
count += 1
i += 1
>>> LPrime(4)
Prime = 1, i = 0
Prime = 2, i = 1
Prime = 5, i = 2
Prime = 17, i = 4
For example this is array = [1,2,3,4,3,2,1]
i want computer to choose i=4 and sum both left of the four and right of the four and then compare if they are equal to each other, program prints i value to the screen.
Now i write it in here and it works as long as the i value is 0 but if i want to make this search for i>0 then i gets complicated.
this is my main program:
# importing "array" for array creations
import array as arr
# Function to find sum
# of array exlcuding the
# range which has [a, b]
def sumexcludingrange(li, a, b): # I FOUND THIS FUNCTION ONLINE BUT ALSO DIDN`T WORK EITHER.
sum = 0
add = True
# loop in li
for no in li:
# if no != a then add
if no != a and add == True:
sum = sum + no
# mark when a and b are found
elif no == a:
add = False
elif no == b:
add = True
# print sum
return sum
#lis = [1, 2, 4, 5, 6]
#a = 2
#b = 5
#sumexcludingrange(arr, 0, i-1)
def my(arr):
for i in range(len(arr)):
if i == 0: #this works when array is like [1,0,0,1] and i equals zero
sum_left = arr[0]
sum_right = sum(arr) - arr[0]
while sum_left == sum_right:
print(i)
break
elif i > 0 : # i 1 2 3 4 5 6 7 8 9..
#sumleft and sumright are not right.. what is the issue here?
sum_left = sumexcludingrange(arr, 0, i-1) #result is 16, sumexcludingrange function didn`t
#work.
print (sum_left)
#print(i)
sum_right == sum(arr) - sum_left
#print(sum_right)
#break
while sum_left == sum_right:
print(sum_left)
print(sum_right)
print("they are equal now")
break
else:
print("index cannot be a negative number.")
something = arr.array('i', [1,2,3,4,3,2,1]) # len(arr) = 7
my(something)
After seeing that i need another function to compare two sides of the array, i created a new file and write it in here and somehow it outputs this:
1
13
13
2
10
10
#array[i] array[i+1] .. + array[length-1]
array = [1,2,3,4,5,6,7] # 7 element so length=7,
for i in range(len(array)):
if i > 0 :
ln = len(array) + 1
sum_right = sum(array[i+1:ln])
sum_left = sum(array) - sum_right
print(i)
print(sum_right)
print(sum_right)
the way i think is this:
# array[i] i>0 i={1,2,3,4..}
sum_total = sum(arr) = array[0] + ..+ array[i-1] + array[i] + array[i+1] + ... + array[length-1]
sum_right = array[i+1] + .. + array[length-1]
sum_left = sum_total - sum_right
Is there a better way to accomplish that?
If I understand your question correctly, the solution could be something like this:
array = [1,2,3,4,5,6,7]
a1 = array[:4] # first 4 numbers
a2 = array[-4:] # last 4 numbers
total = sum(array)
diff = total-sum(a2)
I am trying to write a python function which will give me back the first value of a number k which will function 2 >= function 1
function 1(p) => 1 + 1/1! + 1/2! + 1/p!
function 2(k) => (1 + 1/k)^k
So I input use 2 for example in function 1. It would take estimate e at 2.5 but it would take k being 6 for it to get close which is 2.522.
I want to return the 6.
I get this far but I am not sure where to go from there.
for x in range(p):
factorial(x):
if x == 0:
return 0
else:
return x * factorial(x-1)
result = 1 + 1/factorial(p)
I think you need two separate functions, and no loops are needed.
def factorial(x):
if x in {0, 1}:
return 1 # This needs to be 1, otherwise you multiply everything by 0
else:
return x * factorial(x-1)
def summ(p):
if p == 0:
return 1
elif p == 1:
return 2
else:
return 1/factorial(p) + summ(p-1)
Regarding the rest of the question, I think this will help
def f2(k):
return 1 if k == 0 else (1 + 1/k)**k
max_iter = 10 # TODO: increase
k = 0
delta = 0.000001
while max_iter > 0:
f1_result = summ(k)
f2_result = f2(k)
check = f1_result <= f2_result
print("k={}: {:6.8f} <= {:6.8f} == {}".format(k, f1_result, f2_result, check))
k += 1
max_iter -= 1
# if check:
# break
# TODO: Check if difference is within acceptable delta value
Output
k=0: 1.00000000 <= 1.00000000 == True
k=1: 2.00000000 <= 2.00000000 == True
k=2: 2.50000000 <= 2.25000000 == False
k=3: 2.66666667 <= 2.37037037 == False
k=4: 2.70833333 <= 2.44140625 == False
k=5: 2.71666667 <= 2.48832000 == False
k=6: 2.71805556 <= 2.52162637 == False
k=7: 2.71825397 <= 2.54649970 == False
k=8: 2.71827877 <= 2.56578451 == False
k=9: 2.71828153 <= 2.58117479 == False
From larger numbers, this check still fails at k=996 and throws a recursion error.
k=996: 2.71828183 <= 2.71691848 == False
Traceback (most recent call last):
File "python", line 22, in <module>
File "python", line 13, in summ
File "python", line 5, in factorial
File "python", line 5, in factorial
File "python", line 5, in factorial
[Previous line repeated 992 more times]
RecursionError: maximum recursion depth exceeded
Therefore, it would help if you wrote a factorial function using a loop rather than recursion.
Edit
I think I understand what you are trying to get now
in1 = int(input("value 1:"))
v1 = summ(in1)
v2 = 0
max_iter = 50 # Recursion execution limit
while f2(v2) <= v1 and max_iter > 0:
v2 += 1
max_iter -= 1
print(v2)
Output
value 1: <enter 2>
6
i have written this code which finds factors of a number .after thinking and trying so much i could not get the sum of the numbers I get in output.I wish to get the sum of these numbers as output recursively.here's my code:
def p(n,c):
s = 0
if c >= n:
return n
if n % c == 0:
s += c
print(s,end=',')
return p(n,c+1)
n = int(input('enter no:'))
c = 1
print(p(n,c))
Given the comments, it appears that this might be what you want:
sum([n for n in xrange(1,24) if 24 % n == 0])
To make it a bit more generic:
def sum_of_factors(x):
return sum([n for n in xrange(1,x) if x % n == 0])
EDIT: here's a recursive version:
def sum_of_factors(x, y=1):
if (y >= x):
return 0
if (x % y == 0):
return y + sum_of_factors(x, y + 1)
return sum_of_factors(x, y + 1)
>>> sum_of_factors(24)
36
Is this the output you are looking for?
Use global variable,
s = 0
def p(n,c):
global s
if c >= n:
return n
if n % c == 0:
s += c
print(s,end=',')
return p(n,c+1)
n = int(input('enter no:'))
c = 1
print(p(n,c))
Output
enter no:1,3,6,10,16,24,36,24
The Collatz conjecture
what i am trying to do:
Write a function called collatz_sequence that takes a starting integer and returns the sequence of integers, including the starting point, for that number. Return the sequence in the form of a list. Create your function so that if the user inputs any integer less than 1, it returns the empty list [].
background on collatz conjecture:
Take any natural number n. If n is even, divide it by 2 to get n / 2, if n is odd multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.
What I have so far:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x= x/2
else:
x= 3*x+1
return seq
When I run this with a number less than 1 i get the empty set which is right. But when i run it with a number above 1 I only get that number i.e. collatz_sequence(6) returns [6]. I need this to return the whole sequence of numbers so 6 should return 6,3,10,5,16,8,4,2,1 in a list.
You forgot to append the x values to the seq list:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x + 1
seq.append(x) # Added line
return seq
Verification:
~/tmp$ python collatz.py
[6, 3, 10, 5, 16, 8, 4, 2, 1]
def collatz_sequence(x):
seq = [x]
while seq[-1] > 1:
if x % 2 == 0:
seq.append(x/2)
else:
seq.append(3*x+1)
x = seq[-1]
return seq
Here's some code that produces what you're looking for. The check for 1 is built into while statement, and it iteratively appends to the list seq.
>>> collatz_sequence(6)
[6, 3, 10, 5, 16, 8, 4, 2, 1]
Note, this is going to be very slow for large lists of numbers. A cache won't solve the speed issue, and you won't be able to use this in a brute-force solution of the project euler problem, it will take forever (as it does every calculation, every single iteration.)
Here's another way of doing it:
while True:
x=int(input('ENTER NO.:'))
print ('----------------')
while x>0:
if x%2==0:
x = x/2
elif x>1:
x = 3*x + 1
else:
break
print (x)
This will ask the user for a number again and again to be put in it until he quits
def collatz(x):
while x !=1:
print(int(x))
if x%2 == 0:
x = x/2
else:
x = 3*x+1
this is what i propose..
seq = []
x = (int(input("Add number:")))
if (x != 1):
print ("Number can't be 1")
while x > 1:
if x % 2 == 0:
x=x/2
else:
x = 3 * x + 1
seq.append (x)
print seq
This gives all the steps of a single number. It has worked with a 50-digit number in 0,3 second.
collatz = []
def collatz_sequence(x):
while x != 1:
if x % 2 == 0:
x /= 2
else:
x = (3*x + 1)/2
collatz.append(int(x))
print(collatz)
collatz_sequence()
Recursion:
def collatz(n):
if n == 1: return [n]
elif n % 2 == 0: return [n] + collatz(int(n/2))
else: return [n] + collatz(n*3+1)
print(collatz(27))
steps=0
c0 = int(input("enter the value of c0="))
while c0>1:
if c0 % 2 ==0 :
c0 = c0/2
print(int(c0))
steps +=1
else:
c0 = (3 * c0) + 1
print(int(c0))
steps +=1
print("steps= ", steps)
import numpy as np
from matplotlib.pyplot import step, xlim, ylim, show
def collatz_sequence(N):
seq = [N]
m = 0
maxN = 0
while seq[-1] > 1:
if N % 2 == 0:
k = N//2
seq.append(N//2)
if k > maxN:
maxN = k
else:
k = 3*N+1
seq.append(3*N+1)
if k > maxN:
maxN = k
N = seq[-1]
m = m + 1
print(seq)
x = np.arange(0, m+1)
y = np.array(seq)
xlim(0, m+1)
ylim(0, maxN*1.1)
step(x, y)
show()
def collatz_exec():
print('Enter an Integer')
N = int(input())
collatz_sequence(N)
This is how you can use it:
>>> from collatz_sequence import *
>>> collatz_exec()
Enter an Integer
21
[21, 64, 32, 16, 8, 4, 2, 1]
And a plot that shows the sequence:
seq = []
def collatz_sequence(x):
global seq
seq.append(x)
if x == 1:
return
if (x % 2) == 0:
collatz_sequence(x / 2)
else:
collatz_sequence((x * 3) + 1)
collatz_sequence(217)
print seq
def collataz(number):
while number > 1:
if number % 2 == 0 :
number = number //2
print(number)
elif number % 2 ==1 :
number = 3 * number + 1
print(number)
if number == 1 :
break
print('enter any number...!')
number=int(input())
collataz(number)