Example of a function
Table of contentsEx. NoName of the ExercisePage Number1Compute the GCD of two numbers.22Find the square root of a number (Newton‘s method)63Exponentiation (power of a number)74Find the maximum of a list of numbers85Linear search and Binary search96Selection sort, Insertion sort107Merge sort128First n prime numbers89Multiply matrices1310Programs that take command line arguments (word count)1511Find the most frequent words in a text read from a file1612Simulate elliptical orbits in Pygame-13Simulate bouncing ball using Pygame-14References20Ex. No 1. Compute the GCD of two numbersAimThe aim of this exercise is to compute the GCD of two numbers using recursion in Python.Concepts InvolvedPython Function:Function is a group of related statements that perform a specific task.Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.Furthermore, it avoids repetition and makes code reusable.Syntax of Functiondef function_name(parameters):"""docstring"""statement(s)Above shown is a function definition which consists of following components.Keyword def marks the start of function header.A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.Parameters (arguments) through which we pass values to a function. They are optional.A colon (:) to mark the end of function header.Optional documentation string (docstring) to describe what the function does.One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).An optional return statement to return a value from the function.Example of a functiondef greet(name):"""This function greets tothe person passed in asparameter"""print("Hello, " + name + ". Good morning!")Function CallOnce we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.>>> greet('Paul')Hello, Paul. Good morning!DocstringThe first string after the function header is called the docstring and is short for documentation string. It is used to explain in brief, what a function does.Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as __doc__ attribute of the function.For example:>>> print(greet.__doc__)This function greets tothe person passed into thename parameterThe return statementThe return statement is used to exit a function and go back to the place from where it was called.Syntax of returnreturn [expression_list]This statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.For example:>>> print(greet("May"))Hello, May. Good morning!NoneHere, None is the returned value.How Function works in Python?Types of FunctionsBasically, we can divide functions into the following two types:Built-in functions - Functions that are built into Python.User-defined functions - Functions defined by the users themselves.Exercise: Compute the GCD of two numbersProblem Description:1. Take two numbers from the user.2. Pass the two numbers as arguments to a recursive function.3. When the second number becomes 0, return the first number.4. Else recursively call the function with the arguments as the second number and the remainder when the first number is divided by the second number.5. Return the first number which is the GCD of the two numbers.6. Print the GCD.7. ExitProgram/Source Code:def gcd(a,b): if(b==0): return a else: return gcd(b,a%b)a=int(input("Enter first number:"))b=int(input("Enter second number:"))GCD=gcd(a,b)print("GCD is: ")print(GCD)Output:Enter first number: 5Enter second number: 15GCD is:5Ex. No 2. Find the square root of a number (Newton‘s method)AimThe aim of this exercise is to find the square root of a number (Newton’s method) in Python.Concepts InvolvedLoops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it.For example, one way of computing square roots is Newton’s method. Suppose that you want to know the square root of n. If you start with almost any approximation, you can compute a better approximation with the following formula:better = 1/2 * (approx + n/approx)Program/Source Codedef newtonSqrt(n): approx = 0.5 * n better = 0.5 * (approx + n/approx) while better != approx: approx = better better = 0.5 * (approx + n/approx) return approxprint(newtonSqrt(49))Output7.0Ex. No 3. Exponentiation (power of a number)AimThe aim of this exercise is to find the power of a number using recursion.Concepts InvolvedPython Function:Function is a group of related statements that perform a specific task.Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.Furthermore, it avoids repetition and makes code reusable.Syntax of Functiondef function_name(parameters):"""docstring"""statement(s)Problem DescriptionThe program takes a base and a power and finds the power of the base using recursion.Take the base and exponential value from the user.Pass the numbers as arguments to a recursive function to find the power of the number.Give the base condition that if the exponential power is equals to 1, return the base number.If the exponential power is not equal to 1, return the base number multiplied with the power function called recursively with the arguments as the base and power minus 1.Print the final result.ExitProgram/Source Codedef power(base,exp): if(exp==1): return(base) if(exp!=1): return(base*power(base,exp-1))base=int(input("Enter base: "))exp=int(input("Enter exponential value: "))print("Result:",power(base,exp))Output:Enter base: 2Enter exponential value: 5Result: 32Ex. No 4, 8: Find the maximum of a list of numbers and find first N prime numberAimThe aim of this exercise it to find the maximum of a list numbers.Concepts Involved1. Take in the number of elements and store it in a variable.2. Take in the elements of the list one by one.3. Sort the list in ascending order.4. Print the last element of the list.5. Exit.Program/Source Codea=[]n=int(input("Enter number of elements:"))for i in range(1,n+1): b=int(input("Enter element:")) a.append(b)a.sort()print("Largest element is:",a[n-1])Output:Enter number of elements:3Enter element:23Enter element:567Enter element:3Largest element is: 567Problem: Write a Python program to find first N prime numbers.Ex. No 5. Linear search and Binary searchAimThe aim of this exercise is to implement linear and binary search in Python.Concepts InvolvedBinary Search: Binary search algorithm is used to find a number in a sorted list. so, the pre condition for binary search is that the list should be sorted. If the number is found then its index is returned.Linear Search: The linear search is used to find an item in a list. The items do not have to be in order. To search for an item, start at the beginning of the list and continue searching until either the end of the list is reached or the item is found.Problem: Write a Python Program to implement linear search and binary search.Ex. No 6. Selection Sort and Insertion SortAimThe aim of this exercise is to implement selection sort and insertion sort in Python.Concepts InvolvedSelection Sort: The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, a selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location. As with a bubble sort, after the first pass, the largest item is in the correct place. After the second pass, the next largest is in place. This process continues and requires n?1 passes to sort n items, since the final item must be in place after the (n?1) st pass.On each pass, the largest remaining item is selected and then placed in its proper location. The first pass places 93, the second pass places 77, the third places 55, and so on.Insertion Sort:It always maintains a sorted sublist in the lower positions of the list. Each new item is then “inserted” back into the previous sublist such that the sorted sublist is one item larger.The shaded items represent the ordered sublists as the algorithm makes each pass.Problem: Write a Python Program to implement Selection Sort and Insertion Sort.Ex. No 7. Merge SortAimThe aim of this exercise is to implement merge sort in Python.Concepts InvolvedMerge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke a merge sort on both halves. Once the two halves are sorted, the fundamental operation, called a merge, is performed. Merging is the process of taking two smaller sorted lists and combining them together into a single, sorted, new list.Ex. No 9. Multiply MatricesAimThe aim of this exercise to perform matrix multiplication in PythonConcepts InvolvedPython – for loopPython – ListIn Python we can implement a matrix as nested list (list inside a list).We can treat each element as a row of the matrix.For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0].Multiplication of two matrices X and Y is defined only if the number of columns in X is equal to the number of rows Y.If X is a n x m matrix and Y is a m x l matrix then, XY is defined and has the dimension n x l (but YX is not defined).Program/Source Code:# Program to multiply two matrices using nested loops# 3x3 matrixX = [[12,7,3], [4 ,5,6], [7 ,8,9]]# 3x4 matrixY = [[5,8,1,2], [6,7,3,0], [4,5,9,1]]# result is 3x4result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]]# iterate through rows of Xfor i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j]for r in result: print(r)Output:[114, 160, 60, 27][74, 97, 73, 14][119, 157, 112, 23]Ex. No 10. Programs that take command line arguments (word count)AimThe aim of this exercise is to write a program to take command line arguments (word count) in Python.Concepts InvolvedPython provides a getopt module that helps you parse command-line options and arguments.$ python test.py arg1 arg2 arg3The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purposes ?sys.argv is the list of command-line arguments.len(sys.argv) is the number of command-line arguments.Here sys.argv[0] is the program ie. script name.ExampleConsider the following script test.py ?#!/usr/bin/pythonimport sysprint 'Number of arguments:', len(sys.argv), 'arguments.'print 'Argument List:', str(sys.argv)Now run above script as follows ?$ python test.py arg1 arg2 arg3This produce following result ?Number of arguments: 4 arguments.Argument List: ['test.py', 'arg1', 'arg2', 'arg3']NOTE: As mentioned above, first argument is always script name and it is also being counted in number of arguments.Problem: Write a Python Program to take command line arguments (Word count)Ex.No 11:Find the most frequent words in a text read from a fileAimThe aim of this exercise is to find the most frequent words in a text read from a file.Concepts InvolvedPython provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.The open FunctionBefore you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.Syntaxfile object = open(file_name [, access_mode][, buffering])Here are parameter details:file_name: The file_name argument is a string value that contains the name of the file that you want to access.access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).Here is a list of the different modes of opening a file ?ModesDescriptionrOpens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.rbOpens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.r+Opens a file for both reading and writing. The file pointer placed at the beginning of the file.rb+Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.wOpens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.wbOpens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.w+Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.wb+Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.aOpens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.abOpens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.a+Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.ab+Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.The file Object AttributesOnce a file is opened and you have one file object, you can get various information related to that file.Here is a list of all attributes related to file object:AttributeDescriptionfile.closedReturns true if file is closed, false otherwise.file.modeReturns access mode with which file was opened.file.nameReturns name of the file.file.softspaceReturns false if space explicitly required with print, true otherwise.Example#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")print "Name of the file: ", fo.nameprint "Closed or not : ", fo.closedprint "Opening mode : ", fo.modeprint "Softspace flag : ", fo.softspaceThis produces the following result ?Name of the file: foo.txtClosed or not : FalseOpening mode : wbThe close() MethodThe close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.SyntaxfileObject.close();Example#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")print "Name of the file: ", fo.name# Close opend filefo.close()This produces the following result ?Name of the file: foo.txtReading and Writing FilesThe file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.The write() MethodThe write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.The write() method does not add a newline character ('\n') to the end of the string ?SyntaxfileObject.write(string);Here, passed parameter is the content to be written into the opened file.Example#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")fo.write( "Python is a great language.\nYeah its great!!\n");# Close opend filefo.close()The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.Python is a great language.Yeah its great!!The read() MethodThe read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.SyntaxfileObject.read([count]);Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.ExampleLet's take a file foo.txt, which we created above.#!/usr/bin/python# Open a filefo = open("foo.txt", "r+")str = fo.read(10);print "Read String is : ", str# Close opend filefo.close()This produces the following result ?Read String is : Python isReferences: 12 & 13 : Simulate Elliptical Orbits and Bouncing Ball in PygameAimThe aim of this exercise is to simulate elliptical orbits and bouncing ball in Pygame in Python Interpreter.Concepts Involved ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- find inverse of a function calculator
- derivative of a function at a point
- period of a function sin
- period of a function equation
- period of a function calc
- differential of a function calculator
- transformation of a function calculator
- a example of a letter
- example of a profile on a person
- example of structure function relationship
- range of a function on a graph
- function of a function math