Generating Fibonacci series in Python - python-3.x

I want to simple generate the fibonacci series in Python. But somehow i don't see the correct series. For example if i input 3 then the correct answer should come with the series : 1 1 2 3
Below is my code.Can someone please point out what is wrong with this :
def genfibonacci(no):
if no <= 1:
return no
else:
sum = genfibonacci(no - 1) + genfibonacci(no - 2)
print (sum)
return(sum)
number = int(input())
genfibonacci(number)
Thanks in advance.

Part of your problem is printing while you calculate (apart from if no <= 1)
If we remove the print, and just show what you get as a result this will help:
def genfibonacci(no):
if no <= 1:
sum = no
else:
sum = genfibonacci(no-1) + genfibonacci(no-2)
return sum
>>> [genfibonacci(i) for i in range(4)]
[0, 1, 1, 2]
>>> [genfibonacci(i) for i in range(5)]
[0, 1, 1, 2, 3]
This range starts at 0, so you can remove that if you want.
Since genfibonacci for say 4 will call 32 and 2, which in turn will call 2 and 1, the print statement you have will happen for the same number more than once.
And not at all for the no <= 1.

There are so many ways to calculate fibonacci sesries in python..
Example 1: Using looping technique
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)
Example 2: Using recursion
def fibR(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
print fibR(5)
Example 3: Using generators
a,b = 0,1
def fibI():
global a,b
while True:
a,b = b, a+b
yield a
f=fibI()
f.next()
f.next()
f.next()
f.next()
print f.next()
Example 4: Using memoization
def memoize(fn, arg):
memo = {}
if arg not in memo:
memo[arg] = fn(arg)
return memo[arg]
fib() as written in example 1.
fibm = memoize(fib,5)
print fibm
Example 5: Using memoization as decorator
class Memoize:
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, arg):
if arg not in self.memo:
self.memo[arg] = self.fn(arg)
return self.memo[arg]
#Memoize
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)

Here the Simplest Fibonacci Series represnted:
#Fibonacci series in Short Code
#initilize the base list
ls2=[0,1]
#user input: How many wants to print
c=int(input('Enter required numbers:'))
#fibonacci Function to add last two elements of list
ls2.extend((ls2[i-1]+ls2[i-2]) for i in range(2,c))
#This will print recuired numbers of list
print(ls2[0:c])
If you Want Create Function Then:
#Fibonacci series in Short Code
#initilize the base list
ls2=[0,1]
#user input: How many wants to print
c=int(input('Enter required numbers:'))
#fibonacci Function to add last two elements of list
def fibonacci(c):
ls2.extend((ls2[i-1]+ls2[i-2]) for i in range(2,c))
#This will print required numbers of list
print(ls2[0:c])
fibonacci(c)

Fibonacci using Recursive Function in Python:
def fibonacci(n, fib1=0, fib2=1):
if n<=1:
print(fib1)
return
else:
print(fib1)
fib = fib1 + fib2
fib1 = fib2
fib2 = fib
fibonacci(n - 1, fib1, fib2)
number = int(input())
fibonacci(number)

There are different methods you can use but I use the method of recursion because here you have to code less
def fib(n):
if n<=1:
return n
else:
return fib(n-1)+fib(n-2)
n = int(input())
for i in range(n):
print(fib(i),sep=' ',end=' ')

Related

Sum function not working when trying to add numbers in lists using python

I am trying to create a program that takes only even numbers from a range of numbers from 1 to 100 and add all of the even numbers. I am a beginner and I have been trying to get this working since yesterday, and nothing I have tried works. This is my first post, so sorry if the format is wrong but here is my code.
for i in range(1, 100):
if i % 2 == 0:
x = [I]
y = sum(x)
print(y)
The problems with your code has multiple issues that - 1)if you want to get all even numbers from 1 to 100, your range should be (1, 101); 2) the way you build list is wrong (syntax); 3) the sum expect an iterable (list).
There are a few ways to accomplish this sum from 1 to 100 (inclusive), here it will start with yours, and try to show List Comprenshion and Generator Expression way:
lst = [] # to store the build-up list
tot = 0 # to store the answer
for i in range(1, 101):
if i % 2 == 0: # it's a even number
lst.append(i) # store it into lst
tot = sum(lst) # 2550
Generator expression:
all_evens_sum = sum(x for x in range(1, 101) if x % 2 == 0) # 2550
Or List Comprehension:
lst = [x for x in range(1, 101) if x % 2 == 0] # even nums
total = sum(lst) # 2550
I am a beginner too but it looks I can help you some.
for i in range(1, 100):
if(i % 2 == 0):
sum += i
print(sum) // do what you want

Twin Primes Python Program

I need to write a Python program that determines whether a given integer input is is a twin prime number or not. If the input number is a twin prime, the program must output true. Otherwise, it must output false.
Please may someone guide me with how this program should be written in Python?
This is what I have done so far. I am stuck at the is_twin_prime function part.
def is_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
def is_twin_prime(x):
if is_prime(x) = True:
N = int(input())
for i in range(N):
p = int(input())
if is_twin_prime(p):
print("true")
else:
print("false")
Based on the assumption, that you are trying to determine if N & p are twin primes of one another, I found several issues with your code as follows:
the is_twin_prime function has no False return
the is_prime function always starts with 2 and iteratively checks for prime, this is very inefficient.
To provide an answer, I started with the following factoids about twin_primes:
both numbers must be prime
abs(n-p) == 2
n and p must each have a units digit in [0, 2, 3, 5, 7, 8]
To make the function testing for twin primes as efficient as possible, I eliminated any numbers not meeting the last two cases first, and only if necessary did I generate a list of primes. Also, when generating the primes, I only did it once for the largest number since, once I have the list or the largest both numbers must be in the list.
To make searching for primes more efficient I employed itertools, although this could be done with slightly less efficiency without it's use.
import itertools
def erat2():
D = { }
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q*q] = q
yield q
else:
x = p + q
while x in D or not (x&1):
x += p
D[x] = p
def generatePrimes(given_number):
"""
Returns the prime number <= given_number using
an adaptive sieve of estraothenes approach
"""
return list(itertools.islice(erat2(), given_number))
def is_twinPrime(n, p):
accepted_digits = [0, 2, 3, 5, 7, 8]
if abs(n-p) != 2:
return False
elif n%10 not in accepted_digits and p%10 not in accepted_digits:
return False
else:
primes = generatePrimes(max(n, p))
if n in primes and p in primes:
return True
return False
N = int(input("Enter first number"))
P = int(input(Enter second number"))
print(istwinPrime(N, P)

My two approaches to solve Fibonacci Last Digit Problem on Python

I am a newbie here. If I do something wrongly, please show me tolerance.
I tried to solve this problem:
Problem_Picture_1
Problem_Picture_2
My first solution didn't work:
# Uses python3
import sys
# Uses python3
def get_fibonacci_last_digit(n):
fib = [0, 1]
if n <= 1:
return n
for i in range(2, n):
current = (fib[i-1] + fib[i-2]) % 10
fib.append(current)
return fib[-1]
n = int(input())
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
print(get_fibonacci_last_digit(n))
But my second solution worked:
# Uses python3
def calc_fib(n):
fib = [0, 1]
if n <= 1:
return n
for i in range(2, n+1):
current = (fib[i-1] + fib[i-2]) % 10
fib.append(current)
return fib[-1]
n = int(input())
print(calc_fib(n))
What is the difference between these two approaches? Why didn't work my first solution? Please explain to me.
Edit:
When I worked my first approach, It's still running. It couldn't return a number
When I worked my first approach, It could return a number
The range(A, B) object iterates from A (inclusive) to B (exclusive). Eg.- range(2, 5) will return (2, 3, 4).
PS - Please use proper indentation while posting a question

Python generator only returning first instance of yield

This code should produce all prime numbers in order when 'next' is called, but it only produces 2, the first prime number of the list. The list works properly to produce prime numbers.
def genPrime():
x = 1
primeList = [2]
while True:
x += 1
tempList = []
for i in range(len(primeList)):
tempList.append(x % primeList[i])
if min(tempList) > 0:
next = primeList[-1]
yield next
primeList.append(x)
prime = genPrime()
print(prime.__next__())
That's exactly what a generator is supposed to do. .__next__() only returns the next item, just as the name says.
Try:
print(prime.__next__())
print(prime.__next__())
print(prime.__next__())
You will see that you get them one by one.
Further, it is important that .__next__() is not meant to be called directly. The correct way is:
print(next(prime))
print(next(prime))
print(next(prime))
If you want them all, do:
for p in prime:
print(p)
Further, while not part of the answer, I give you a couple of programming tips:
for i in range(len(primeList)):
tempList.append(x % primeList[i])
has an unnecessary indirection. Just do
for prime in primeList:
tempList.append(x % prime)
Also, the entire tempList is unnecessary.
Just use a for-else construct:
def genPrime():
x = 1
primeList = []
while True:
x += 1
for prime in primeList:
if x % prime == 0:
break
else:
yield x
primeList.append(x)

Using Recursive Functions in Python to find Factors of a Given Number

Have tried searching for this, but can't find exactly what I'm looking for.
I want to make a function that will recursively find the factors of a number; for example, the factors of 12 are 1, 2, 3, 4, 6 & 12.
I can write this fairly simply using a for loop with an if statement:
#a function to find the factors of a given number
def print_factors(x):
print ("The factors of %s are:" % number)
for i in range(1, x + 1):
if number % i == 0: #if the number divided by i is zero, then i is a factor of that number
print (i)
number = int(input("Enter a number: "))
print (print_factors(number))
However, when I try to change it to a recursive function, I am getting just a loop of the "The factors of x are:" statement. This is what I currently have:
#uses recursive function to print all the letters of an integer
def print_factors(x): #function to print factors of the number with the argument n
print ("The factors of %s are:" % number)
while print_factors(x) != 0: #to break the recursion loop
for i in range(1,x + 1):
if x % i == 0:
print (i)
number = int(input("Enter a number: "))
print_factors(number)
The error must be coming in either when I am calling the function again, or to do with the while loop (as far as I understand, you need a while loop in a recursive function, in order to break it?)
There are quite many problems with your recursive approach. In fact its not recursive at all.
1) Your function doesn't return anything but your while loop has a comparision while print_factors(x) != 0:
2) Even if your function was returning a value, it would never get to the point of evaluating it and comparing due to the way you have coded.
You are constantly calling your function with the same parameter over and over which is why you are getting a loop of print statements.
In a recursive approach, you define a problem in terms of a simpler version of itself.
And you need a base case to break out of recursive function, not a while loop.
Here is a very naive recursive approach.
def factors(x,i):
if i==0:
return
if x%i == 0:
print(i)
return factors (x,i-1) #simpler version of the problem
factors(12,12)
I think we do using below method:
def findfactor(n):
factorizeDict
def factorize(acc, x):
if(n%x == 0 and n/x >= x):
if(n/x > x):
acc += [x, n//x]
return factorize(acc, x+1)
else:
acc += [x]
return acc
elif(n%x != 0):
return factorize(acc, x+1)
else:
return acc
return factorize(list(), 1)
def factors(x,i=None) :
if i is None :
print('the factors of %s are : ' %x)
print(x,end=' ')
i = int(x/2)
if i == 0 :
return
if x % i == 0 :
print(i,end=' ')
return factors(x,i-1)
num1 = int(input('enter number : '))
print(factors(num1))
Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutations, variable reassignments, and other side effects. That said, here's how I'd write factors -
def factors(n, m = 2):
if m >= n:
return
if n % m == 0:
yield m
yield from factors(n, m + 1)
print(list(factors(10))) # [2,5]
print(list(factors(24))) # [2,3,4,6,8,12]
print(list(factors(99))) # [3,9,11,33]
And here's prime_factors -
def prime_factors(n, m = 2):
if m > n:
return
elif n % m == 0:
yield m
yield from prime_factors(n // m, m)
else:
yield from prime_factors(n, m + 1)
print(list(prime_factors(10))) # [2,5]
print(list(prime_factors(24))) # [2,2,2,3]
print(list(prime_factors(99))) # [3,3,11]
def fact (n , a = 2):
if n <= a :
return n
elif n % a != 0 :
return fact(n , a + 1 )
elif n % a == 0:
return str(a) + f" * {str(fact(n / a , a ))}"
Here is another way. The 'x' is the number you want to find the factors of. The 'c = 1' is used as a counter, using it we'll divide your number by 1, then by 2, all the way up to and including your nubmer, and if the modular returns a 0, then we know that number is a factor, so we print it out.
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)

Resources