Saturday 28 January 2017

Fibonacci Series

Lets generate fibonacci series using generators in python

The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The next number is found by adding up the two numbers before it.

  • The 2 is found by adding the two numbers before it (1+1)
  • The 3 is found by adding the two numbers before it (1+2),
  • And the 5 is (2+3),
  • and so on!


num = int(input())

#method to generate fibonacci sequence
def fibo(n):
    a,b = 0,1
    for i in range(n):
        yield a
        a,b = b,a+b
#print the numbers
for i in fibo(num):
    print(i)

Diamond Pattern


How to print diamond pattern.
For printing pattern like this,

  1. We need to take care of spaces,
  2. print the required number of spaces.

lets checkout the program in python
//take number of rows input from user
num = int(input())
for i in range(0,num):
#loop for printing the spaces as required first half of diamond
    for j in range(1,num-i):
        print(' ',end='')
    print((2*i+1)*'*')
#print other half of diamond
for i in range(1,num):
    print(' '*i,end='')
    print((2*(num-i-1)+1)*'*')



#If you have any doubt and want to do in any other language.You can simply post a comment here.