Programming with Python Examples

Examples

I will start a series of posts with some examples to develop with the Python programming language.

 

The idea is to assimilate concepts of language through research to solve problems.

The first problem to solve will be:

 

Python example 1

Print on screen the first 20 numbers of the Fibonacci sequence.

The Fibonacci sequence is made up of a function in which each element is the sum of the two previous numbers

The sequence begins with 0,1,1,2 …

 

Solution:

The sequence can be expressed with a recursive function

fibon (n) = fibon (n-1) + fibon (n-2)

 

# Example python 1
# Fibonacci sequence of the first 20 numbers
# fibon(n) = fibon(n-1)+fibon(n-2)
def fibon(n):
   if n<=2:
      return n
   return fibon(n-1)+fibon(n-2)

if __name__ == "__main__":
   cad=""
   for i in range(20):
      cad= cad+" "+str(fibon(i))

   print "Fibonacci sequence "+cad

 

Python 2 example

Print the factorial of the numbers from 1 to 10 on the screen

 

The factorial of a number is calculated as the product of all the numbers before it.

The factorial of 0 is 1

Factorial pe of 3 = 3 * 2 * 1

 

You will have to make two versions, one with a loop and the other with a recursive function.

 

# Example python 2
# recursive version
#    Factorial of the numbers from 1 to 10
#    factorial(n) = factorial(n-1)*n
#
def factorial(n):
   if n==0: 
      return 1 
   if n==1: 
      return 1 
   return factorial(n-1)*n

if __name__ == "__main__":
   for i in range(10):
     print "Factorial " + str(i) + " " + str(factorial(i))

 

# Example python 2
# Factorial of the numbers from 1 to 10
# with loops

if __name__ == "__main__":
   for i in range(10):
      f=1
      for n in range(1,i):
         f=f*n

      print "Factorial " + str(i) + " " + str(f)

 

Leave a Reply

Your email address will not be published. Required fields are marked *