Chapter 8: Working with functions

Program 8.1, Page number: 120

In [1]:
def printMessage():                                #Function to Print Message
        print("Programming is Fun.\n")             #Print Statement


def main():                                        #Main() function
        printMessage()


if  __name__ =='__main__':                         #Setting Top-level conditional script
     main()
Programming is Fun.

Program 8.2, Page number: 121

In [2]:
def printMessage():                                #Function to Print Message
        print("Programming is Fun.\n")             #Print Statement


def main():                                        #Main() function
        printMessage()                             #First Function call
        printMessage()                             #Second Function Call

if  __name__ =='__main__':                         #Setting Top-level conditional script
     main()
Programming is Fun.

Programming is Fun.

Program 8.3, Page number: 122

In [3]:
def printMessage():                                #Function to Print Message
        print("Programming is Fun.\n")             #Print Statement


def main():               
     for i in range (1,6):                         #Main() function
        printMessage()


if  __name__ =='__main__':                         #Setting Top-level script environment
     main()
Programming is Fun.

Programming is Fun.

Programming is Fun.

Programming is Fun.

Programming is Fun.

Program 8.4, Page number: 123

In [4]:
def calculateTriangularNumber(n):                 #Function to calculate triangular number
        triangularNumber=0                        #Variable Dclaration
                          
        for i in range (1,n+1):                   #Calculation/Iteration
             triangularNumber+=i
     
        print("Triangular Number {0} is {1}".format(n,triangularNumber))


def main():
        calculateTriangularNumber(10)              #Function call-1
        calculateTriangularNumber(20)              #Function call-2
        calculateTriangularNumber(50)              #Function call-3
 

if __name__=='__main__':                            #Setting top level conditional script
      main()
Triangular Number 10 is 55
Triangular Number 20 is 210
Triangular Number 50 is 1275

Program 8.5, Page number: 125

In [5]:
import sys                                                 

def gcd(u,v):                                                   #Function to calculate gcd
        sys.stdout.write("gcd of {0} and {1} is: ".format(u,v))
        while(v!=0):
            temp=u%v
            u=v
            v=temp
        sys.stdout.write("{0}\n".format(u))



def main():                                                     #Main() function
   gcd(150,35)                                                  
   gcd(1026,405)
   gcd(83,240)

if __name__=='__main__':                                        #Setting Top level conditional script 
   main()
gcd of 150 and 35 is: 5
gcd of 1026 and 405 is: 27
gcd of 83 and 240 is: 1

Program 8.6, Page number: 127

In [6]:
import sys                                                 

def gcd(u,v):                                                   #Function to calculate gcd

        while(v!=0):
            temp=u%v
            u=v
            v=temp
        return u

def main():                                                     #Main() function
   result= gcd(150,35)                                                  
   print("the gcd of 150 and 35 is: {0}".format(result))
   result=gcd(1026,405)
   print("the gcd of 1026 and 405 is: {0}".format(result))  
   result= gcd(83,240)
   print("the gcd of 83 and 240 is: {0}".format(result))

if __name__=='__main__':                                        #Top level conditional script 
   main()
the gcd of 150 and 35 is: 5
the gcd of 1026 and 405 is: 27
the gcd of 83 and 240 is: 1

Program 8.7, Page number: 129

In [7]:
def absoluteValue(x):                              #Function to calculate & return absolute values
        if(x<0):
           x=-x
        return x

def main():                                         #Main() Function
    
        f1=-15.5
        f2=20.0
        f3=-5.0
        il=-716
        result=absoluteValue(f1)
        print("result= {0:.2f}".format(result))
        print("f1={0:.2f}".format(f1))

        result=absoluteValue(f2)+absoluteValue(f3)
        print("result= {0:.2f}".format(result))

        result=absoluteValue(float(il))
        print("result= {0:.2f}".format(result))
                
        result=absoluteValue(il)
        print("resut= {0:.2f}".format(result))

        print("{0:.2f}".format(absoluteValue((-6.0)/4)))


 
if __name__=='__main__':                                    #Setting Top level conditional script
    main()
result= 15.50
f1=-15.50
result= 25.00
result= 716.00
resut= 716.00
1.50

Program 8.8, Page number: 132

In [8]:
def absoluteValue(x):        
        if(x<0):
           x=-x
        return x

def squareRoot(x):
        epsilon=0.0001
        guess=1.0
        while(absoluteValue(guess*guess-x)>=epsilon):
                guess=(x/guess+guess)/2.0
        return guess

def main():
        print("squareRoot (2.0) = {0}".format(squareRoot (2.0)));
        print("squareRoot (144.0) = {0}".format(squareRoot (144.0)));
        print("squareRoot (17.5) = {0}".format(squareRoot (17.5)));

if __name__=='__main__':
        main()
squareRoot (2.0) = 1.41421568627
squareRoot (144.0) = 12.0000000124
squareRoot (17.5) = 4.18330153622

Program 8.9, Page number: 138

In [1]:
def minimum(values):
        minValue=values[0]                                   #Variable Declaration
        for i in range (1,10):                               #Calculation
                if(values[i]<minValue):
                        minValue=values[i]

        return minValue
                   
def main():
        scores=[]                                            #Variable Declaration
        print("Enter 10 scores:")
        for i in range (0,10):
            scores.append(5)                                 #score=5 for all cases
            #scores.append(input())              

        minScore=minimum(scores)                             #Function call & assignment
        print("\nMinimum score is {0}\n".format(minScore))   #Result

if __name__=='__main__':
        main()
Enter 10 scores:

Minimum score is 5

Program 8.10, Page number: 141

In [10]:
def minimum(values,numberOfElements):        
        minValue=values[0]                                    #Variable Declaration
        for i in range(1,numberOfElements):                   #Iteration/Calculations
                if(values[i]<minValue):
                        minValue=values[i]
        
        return minValue

def main():
        #List/Variable Delcaration
        array1 = [ 157, -28, -37, 26, 10 ]                       
        array2 = [ 12, 45, 1, 10, 5, 3, 22 ]
        
        #Result
        print("array1 minimum: {0}".format(minimum (array1, 5)));
        print("array2 minimum: {0}".format(minimum (array2, 7)));

if __name__=='__main__':
        main()
array1 minimum: -37
array2 minimum: 1

Program 8.11, Page number: 142

In [11]:
import sys

def multiplyBy2(array,n):
        for i in range (0,n):                                     #Iteration/Calculation
                array[i]*=2

def main():

        #List/Variable Declaration
        floatVals=[1.2, -3.7, 6.2, 8.55]      
        multiplyBy2(floatVals,4)

        for i in range (0,4):
                sys.stdout.write("{0:.2f} ".format(floatVals[i]))  #Result
        print("\n")

if __name__=='__main__':
        main()
2.40 -7.40 12.40 17.10 

Program 8.12, Page number: 145

In [12]:
import sys

def sort(a,n):

        for i in range (0,n-1):                          #Calculations
                for j in range (i+1,n):
                        if(a[i]>a[j]):                   #Conditional swapping
                                temp=a[i]
                                a[i]=a[j]
                                a[j]=temp

def  main():

        #List/Variable Declaration 
        array= [ 34, -5, 6, 0, 12, 100, 56, 22,\
                      44, -3, -9, 12, 17, 22, 6, 11 ]
        
        print("The array before the sort:\n");
        for i in range (0,16):
                sys.stdout.write("{0} ".format(array[i]))
        
        sort (array, 16);                                #Function Call
        
        print("\n\n\nThe array after the sort:\n")
        for i in range (0,16):
                sys.stdout.write("{0} ".format(array[i]))
        print("\n")


if  __name__=='__main__':
        main()
The array before the sort:

34 -5 6 0 12 100 56 22 44 -3 -9 12 17 22 6 11 


The array after the sort:

-9 -5 -3 0 6 6 11 12 12 17 22 22 34 44 56 100 

Program 8.13, Page number: 147

In [13]:
import sys

def main():

        #List/Variable Declaration
        sampleMatrix =[ [ 7, 16, 55, 13, 12 ],
                        [ 12, 10, 52, 0, 7 ],
                        [ -2, 1, 2, 4, 9 ]   ]


        print("Original matrix:\n")
        displayMatrix(sampleMatrix)                     #Function call-1

        scalarMultiply(sampleMatrix, 2)                 #Function Call-2
        print("\nMultiplied by 2:\n")
        
        displayMatrix(sampleMatrix);                    #Function call-3
        scalarMultiply(sampleMatrix, -1)                #Function call-4
        
        print("\nThen multiplied by -1:\n")
        displayMatrix(sampleMatrix)                     #Function call-5


def scalarMultiply(matrix,scalar):
        for row in range(0,3):                                 #Calculation
                for column in range(0,5):
                        matrix[row][column]*=scalar          


def displayMatrix(matrix):
        for row in range(0,3):                                 #Result
                for column in range(0,5):
                        sys.stdout.write("{0:7}".format(matrix[row][column]))
                sys.stdout.write("\n")


if __name__=='__main__':
        main()
Original matrix:

      7     16     55     13     12
     12     10     52      0      7
     -2      1      2      4      9

Multiplied by 2:

     14     32    110     26     24
     24     20    104      0     14
     -4      2      4      8     18

Then multiplied by -1:

    -14    -32   -110    -26    -24
    -24    -20   -104      0    -14
      4     -2     -4     -8    -18

Program 8.13A, Page number: 150

In [14]:
import sys

def main():

        #List/Variable Declaration
        sampleMatrix =[ [ 7, 16, 55, 13, 12 ],
                        [ 12, 10, 52, 0, 7 ],
                        [ -2, 1, 2, 4, 9 ]   ]


        print("Original matrix:\n")
        displayMatrix(3,5,sampleMatrix)                     #Function call-1

        scalarMultiply(3,5,sampleMatrix, 2)                 #Function Call-2
        print("\nMultiplied by 2:\n")
        
        displayMatrix(3,5,sampleMatrix);                    #Function call-3
        scalarMultiply(3,5,sampleMatrix, -1)                #Function call-4
        
        print("\nThen multiplied by -1:\n")
        displayMatrix(3,5,sampleMatrix)                     #Function call-5


def scalarMultiply(nRows,nCols,matrix,scalar):
        for row in range(0,nRows):                                 #Calculation
                for column in range(0,nCols):
                        matrix[row][column]*=scalar          


def displayMatrix(nRows,nCols,matrix):
        for row in range(0,nRows):                                 #Result
                for column in range(0,nCols):
                        sys.stdout.write("{0:7}".format(matrix[row][column]))
                sys.stdout.write("\n")


if __name__=='__main__':
        main()
Original matrix:

      7     16     55     13     12
     12     10     52      0      7
     -2      1      2      4      9

Multiplied by 2:

     14     32    110     26     24
     24     20    104      0     14
     -4      2      4      8     18

Then multiplied by -1:

    -14    -32   -110    -26    -24
    -24    -20   -104      0    -14
      4     -2     -4     -8    -18

Program 8.14, Page number: 153

In [15]:
import sys

def getNumberAndBase():
        
        #Global Reference
        global digit
        global numberToConvert
        global base
       
        #Variable Declaration
        digit=0
        numberToConvert=420                                     #numberToConvert=input("Number to be converted ?")
        base=8                                                  #base=input("Base?")
        if(base<2 or base>16):
                print("Bad base - must be between 2 and 16\n");
                base = 10;

def convertNumber():
        
        #Global Reference
        global numberToConvert
        global base
        global convertedNumber
        global digit
        convertedNumber=[0]*64                                      #List declaration
        
        while(numberToConvert!=0):
                convertedNumber[digit]=numberToConvert%base         #Calculations
                digit=digit+1
                numberToConvert/=base


def displayConvertedNumber():

        #Global reference 
        global baseDigits
        global digit 

        #List/Variable Declaration
        baseDigits=[ '0', '1', '2', '3', '4', '5', '6', '7',\
                          '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]
        sys.stdout.write("Converted number = ")
       
        digit=digit-1

        for i in range(digit,-1,-1):
                nextDigit = convertedNumber[i];
                sys.stdout.write("{0}".format(baseDigits[nextDigit]));  #Result

        sys.stdout.write("\n")



def main():
        getNumberAndBase()                               #Function call-1
        convertNumber()                                  #Function call-2
        displayConvertedNumber()                         #Function call-3


if __name__=='__main__':
        main()
Converted number = 644

Program 8.15, Page number: 157

In [16]:
def auto_static():
        global staticVar               #Global reference
        autoVar=1                      #variable Declaration
        print("automatic = {0}, static = {1}\n".format(autoVar,staticVar)); #Result
     
        #Calculation       
        autoVar+=1
        staticVar+=1

def main():
        global staticVar
        staticVar=1                    #Variable Declaration
        for i in range(0,5):
                auto_static()

if __name__=='__main__':
        main()
automatic = 1, static = 1

automatic = 1, static = 2

automatic = 1, static = 3

automatic = 1, static = 4

automatic = 1, static = 5

Program 8.16, Page number: 159

In [17]:
def factorial(n):
        if( n == 0 ):                            #Calculation
                result = 1
        else:
                result = n * factorial (n - 1)
        return result;

def main():
        for j in range (0,11):
                print("{0:3}! = {1}\n".format(j,factorial (j)))


if __name__=='__main__':
        main()
  0! = 1

  1! = 1

  2! = 2

  3! = 6

  4! = 24

  5! = 120

  6! = 720

  7! = 5040

  8! = 40320

  9! = 362880

 10! = 3628800