100% found this document useful (1 vote)
302 views

GE8151 Python Programming - Unit I Question Bank With Sample Code

Question bank for UNIT-I Problem solving and Python programming (GE8151) -2017 Regulations (B.E. and B.Tech. courses - Civil, CSE, ECE, EEE, Mechanical, Information Technology of Anna University affiliated institutions
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
302 views

GE8151 Python Programming - Unit I Question Bank With Sample Code

Question bank for UNIT-I Problem solving and Python programming (GE8151) -2017 Regulations (B.E. and B.Tech. courses - Civil, CSE, ECE, EEE, Mechanical, Information Technology of Anna University affiliated institutions
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT 1- ALGORITHMIC PROBLEM SOLVING


SYLLABUS
Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation
(pseudo code, flow chart, programming language), algorithmic problem solving, simple strategies
for developing algorithms (iteration, recursion). Illustrative problems: find minimum in a list,
insert a card in a list of sorted cards, guess an integer number in a range, Towers of Hanoi.
PART-A
Q.No Questions
Point out any 5 programming language
Java, Python, C, C++,C-Sharp
1
Define an algorithm
An algorithm is a finite sequence of well-defined, computer-implementable instructions,
2 typically to solve a class of problems or to perform a computation. Algorithms
are unambiguous specifications for performing calculation, data processing, automated
reasoning, and other tasks.
Distinguish between pseudo code and flowchart.
Pseudocode is linear (i.e. a sequence of lines with instructions), a flowchart is not. Flowcharts are
3 a higher abstraction level, used before writing pseudocode or for
documentation. Flowcharts have, in my opinion, two strong advantages over pseudocode:
Firstly, they are graphical.
Define control flow statement with an eg:
A program's control flow is the order in which the program's code executes. The control
4 flow of a Python program is regulated by conditional statements, loops, and function calls. ...
Raising and handling exceptions also affects control flow;
Control flow example
if x < 0: print "x is negative"
elif x % 2: print "x is positive and odd"
else: print "x is even and non-negative"

Describe recursion.
A recursive function is a function defined in terms of itself via self-referential expressions.
5 This means that the function will continue to call itself and repeat its behavior until some
condition is met to return a result.
def factorial(x):
if x==1:
return 1
else:
return x*factorial(x-1)

f=factorial(5)
print ("factorial of 5 is ",f)
The result is
factorial of 5 is 120

Discover the concept of towers of Hanoi.


Tower of Hanoi consists of three pegs or towers with n disks placed one over the other. The
6 objective of the puzzle is to move the stack to another peg following these simple rules. Only
one disk can be moved at a time. No disk can be placed on top of the smaller disk.

Explain list
The most commonly used data structure in Python is List. Python list is a container like an
7 array that holds an ordered sequence of objects. The object can be anything from a string to a
number or the data of any available type.

Explain Iteration
An iteration statement, which allows a code block to be repeated a certain number of times.
8 Repeated execution of a set of statements is called iteration. Iteration is the repetition of a
process in order to generate a sequence of outcomes. The sequence will approach some end point
or end value. Each repetition of the process is a single iteration, and the outcome of each iteration
is then the starting point of the next iteration.
Define simple computational problem
The process of computational problem solving involves understanding the problem,
9 designing a solution, and writing the solution (code).
Computational thinking is an approach to solving problems using concepts and ideas from
computer science, and expressing solutions to those problems so that they can be run on a
computer.

Assess problem solving method.


The problem solving methodology using a computer is a process that evolves on the
10 following steps:
1. Formulate the problem;
2. Formalize the problem;
3. Develop an algorithm that solves the problem;
4. Program the algorithm (i.e., encode the algorithm as a valid program of a programming
language available on the computer);

Evaluate the Outcome

The project implementation now needs to be monitored by the group to ensure their
recommendations are followed. Monitoring includes checking:

 Milestones are met

 Costs are contained

 Necessary work is completed


What is meant by sorting ? mention its types
Sorting is the process of placing elements from a collection in some kind of order.
11 For example, a list of words could be sorted alphabetically or by length.

 Bubble Sort
 Selection Sort
 Insertion Sort
 Merge Sort
 Heap Sort
 Quick Sort

Develop algorithm for Celsius to Fahrenheit and vice versa


# Python Program to convert temperature in celsius to fahrenheit
12
Program to Convert Celsius To Fahrenheit

In the following program we are taking the input from user, user enters the temperature
in Celsius and the program converts the entered value into Fahrenheit using the
conversion formula we have seen above.

celsius = float(input("Enter temperature in celsius: "))


fahrenheit = (celsius * 9/5) + 32
print('%.2f Celsius is: %0.2f Fahrenheit' %(celsius, fahrenheit))
Output:

Program to Convert Fahrenheit to Celsius

In the following program user enters the temperature in Fahrenheit and the program
converts the entered value into Celsius using the Fahrenheit to Celsius conversion
formula.

fahrenheit = float(input("Enter temperature in fahrenheit: "))


celsius = (fahrenheit - 32) * 5/9
print('%.2f Fahrenheit is: %0.2f Celsius' %(fahrenheit, celsius))

Output:

Define programming language


A programming language is a formal language, which comprises a set of instructions that
13 produce various kinds of output. Programming languages are used in
computer programming to implement algorithms.
Identify the function types
There are two basic types of functions: built-in functions and user defined functions. The built-
14 in functions are part of the Python language; for instance dir() , len() , or abs() . The user
defined functions are functions created with the def keyword.
Examine a simple program to print the integer number from 1 to 50
# Sum of natural numbers up to 50
15
num = 50

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
Discuss building blocks of algorithm

16 An algorithm is made up of three basic building blocks: sequencing, selection, and iteration.

Sequencing: An algorithm is a step-by-step process, and the order of those steps are crucial to

ensuring the correctness of an algorithm.


Selection: Algorithms can use selection to determine a different set of steps to execute based
on a Boolean expression.
Iteration: Algorithms often use repetition to execute steps a certain number of times or until a
certain condition is met.

Discover the steps of simple strategies for developing algorithms.

17 Approach the problem in stages:

Think:

i) Analyze the problem


ii) Restate the problem
iii) Write out examples of input and output
iv) Break the problem into its component parts
v) Outline a solution in psuedo-code
vi) Step through your example data with your psuedo-code

Execute

1. Code it up
2. Test your solution against your examples

Differentiate user defined function and predefined function


User-Defined function
18
 In Python, a user-defined function's declaration begins with the keyword def and
followed by the function name.
 The function may take arguments(s) as input within the opening and closing
parentheses, just after the function name followed by a colon.
 After defining the function name and arguments(s) a block of program statement(s)
start at the next line and these statement(s) must be indented.

Python Built-in Function.


The Python interpreter has a number of functions that are always available for use.
These functions are called built-in functions. For example, print() function prints the given
object to the standard output device (screen) or to the text stream file.
Analyze the notations used in algorithmic problem solving
We usually present algorithms in the form of some pseudo-code, which is normally a mixture
19 of English statements, some mathematical notations, and selected keywords from a
programming language.
Algorithms may also be represented by diagrams. One popular diagrammatic method is the
flowchart, which consists of terminator boxes, process boxes, and decision boxes, with flows
of logic indicated by arrows.

Describe some example for recursion function


Recursive Functions in Python
20
A recursive function is a function defined in terms of itself via self-referential expressions.
This means that the function will continue to call itself and repeat its behavior until some
condition is met to return a result.

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

PART-B
Explain the algorithm GCD and find LCM

1 Euclid’s algorithm is based on repeated


application of equality gcd(m,n) = gcd(n, m mod n)
until the second number becomes 0, which makes
the problem trivial.
Example:
gcd(60,24) = gcd(24,12) = gcd(12,0) =
12

Pseudocode
while n ≠ 0 do
r ← m mod n
m←n
n←r
return m

Discuss with suitable examples


i)Find minimum in a list
2
def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))

Sample Output:
-8

ii)Find Maximum in a list


def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))

Sample Output:
2

i)Summarize advantage and disadvantage of flow chart

3
Advantages and Disadvantages of Flowchart
Flowchart Meaning
It is said that a single picture is worth thousands words and flowchart works basically on
that concept only as it illustrates solution of complex problems through diagrams and thus
helps an individual to understand the concept better, however sometimes it may complicate
the solution which in turn will make it even more difficult for an individual to understand
the solution of the problem
Advantages of Flowchart
 Short and Simple
The biggest advantage of using flowchart is that it is short as well as simple
 Logical Steps
It helps them understand the solution of the problem logically.
 Effective Communication
It is one of the effective ways of communicating because flowchart can be made on
1 or 2 pages only as opposed to other methods of communication like written
communication which may take many pages, hence if one wants to save time and
communicate effectively than flowcharts can be a good option for them.

Disadvantages of Flowchart

 Not suitable where Solution is long


When the solution of the problem is short than it is a good method but if the
solution is longer than this may not be the ideal method.

 Complicate Things
One does not understand the solution even when the solution is right due to the
wrong presentation through flowcharts.
 Difficult to Alter
Another limitation is that flowcharts are difficult to alter because if there is one
mistake than one has to alter the whole flowchart

ii)Summarize the symbol used in flow chart

i)
Symbol Description Symbol Description

START /
PROCESS
STOP

DECISION INPUT

CONNECTO
OUTPUT
RS

STORAGE
Describe Build an algorithm for the following
i) Prime number or not
4 # Program to check if a number is prime or not

num = 111

# To take input from the user


#num = int(input("Enter a number: "))

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")

Output
111 is not a prime number
3 times 37 is 111

ii) Odd or even


# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

output
Enter a number: 7
7
7 is Odd
Explain the rules for pseudo code and uses of keywords
RULES FOR PSEUDOCODE
5 1. Write only one stmt per line
Each stmt in your pseudocode should express just one action for the computer.
If the task list is properly drawn, then in most cases each task will correspond to
one line of pseudocode.

Eg: TASK LIST:


Read name, hourly rate, hours worked, deduction rate

Perform calculations
gross = hourlyRate * hoursWorked
deduction = grossPay * deductionRate
net pay = grossPay – deduction
Write name, gross, deduction, net pay
PSEUDOCODE:
READ name, hourlyRate, hoursWorked, deductionRate
grossPay = hourlyRate * hoursWorked
deduction = grossPay * deductionRate
netPay = grossPay – deduction
WRITE name, grossPay, deduction, netPay
2. Capitalize initial keyword
In the example above, READ and WRITE are in caps. There are just a few
keywords we will use:
READ, WRITE, IF, ELSE, ENDIF, WHILE, ENDWHILE, REPEAT, UNTIL
3. Indent to show hierarchy
We will use a particular indentation pattern in each of the design structures:
SEQUENCE: keep statements that are “stacked” in sequence all starting in the
same column.
SELECTION: indent the statements that fall inside the selection structure, but not
the keywords that form the selection
LOOPING: indent the statements that fall inside the loop, but not the keywords
that form the loop
Eg: In the example above, employees whose grossPay is less than 100 do not
have any deduction.
Task List:
Read name, hourly rate, hours worked, deduction rate
Compute gross, deduction, net pay
Is gross >= 100?
YES: calculate deduction
NO: no deduction
Write name, gross, deduction, net pay
Pseudocode:
READ name, hourlyRate, hoursWorked
grossPay = hourlyRate * hoursWorked
IF grossPay >= 100
deduction = grossPay * deductionRate
ELSE
deduction = 0
ENDIF
netPay = grossPay – deduction
WRITE name, grossPay, deduction, netPay
4. End multiline structures
See how the IF/ELSE/ENDIF is constructed above. The ENDIF (or END
whatever) always is in line with the IF (or whatever starts the structure).
5. Keep stmts language independent
Resist the urge to write in whatever language you are most comfortable with. In
the long run, you will save time! There may be special features available in the
language you plan to eventually write the program in; if you are SURE it will be
written in that language, then you can use the features. If not, then avoid using
the special features

Pseudocode uses Keywords (Reserved Words) to control the structure of a solution.


Reserved words are written in capitals. Structural elements come in pairs, eg for every
BEGIN there is an END, for every IF there is an ENDIF, etc. Indenting is used to show
structure in the algorithm.

Explain the following programming language


i). Machine language
6 ii). Assembly language
iii). High level language

i) Machine language
Machine code is a computer program written in machine language instructions that can
be executed directly by a computer's central processing unit (CPU). Each instruction
causes the CPU to perform a very specific task, such as a load, a store, a jump, or
an ALU operation on one or more units of data in CPU registers or memory.
ii) Assembly language
Assembly language (or assembler language), is any low-level programming language in
which there is a very strong correspondence between the instructions in the language and
the architecture's machine code instructions. Assembly code is converted into executable
machine code by an assembler. Assembly language instructions usually consist of
an opcode mnemonic followed by a list of data, arguments. These are translated by
an assembler into machine language instructions that can be loaded into memory and
executed.
iii) High level language
High-level programming languages mean that languages of writing computer
instructions in a way that is easily understandable and close to human language.
High-level languages are created by developers so that programmers don’t need to
know highly difficult low level/machine language. Programmers can easily learn
high-level languages as it is very close to human language.

Neat sketch explain the following building blocks of alg.


i). Statements
7 ii). Control Flow

i) Statements

A computer program statement is an instruction for the computer program to perform


an action. There are many different types of statements that can be given in a
computer program in order to direct the actions the program performs. In computer
programming, a statement is a syntactic unit of an imperative programming language that
expresses some action to be carried out. A program written in such a language is formed
by a sequence of one or more statements. A statement may have internal components
(e.g., expressions).

ii) Control flow

Control Flow Statements

Without control flow statements, the interpreter executes these statements in the order
they appear in the file from left to right, top to bottom. You can use control flow
statements in your programs to conditionally execute statements, to repeatedly execute a
block of statements, and to otherwise change the normal, sequential flow of control.

Describe State and function in Building Block and examples.

8 Building blocks of algorithms (statements, state, control flow, functions)

Algorithms can be constructed from basic building blocks namely, sequence,


selection and iteration.
Statements:
Statement is a single action in a computer.
In a computer statements might include some of the following actions
 input data-information given to the program
 process data-perform operation on a given input
 output data-processed result
State:
Transition from one process to another process under specified condition with
in a time is called state.
Control flow:
The process of executing the individual statements in a given order is called
control flow.
The control can be executed in three ways
1. sequence
2. selection
3. iteration
Sequence:
All the instructions are executed one after another is called sequence execution
.Selection:
A selection statement causes the program control to be transferred to a specific
part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed,
otherwise it will execute the other part of the program.
Iteration:
In some programs, certain set of statements are executed again and again based
upon conditional test. i.e. executed more than one time. This type of execution
is called looping or iteration.
Functions:
 Function is a sub program which consists of block of code(set of
instructions) that performs a particular task.
 For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.
Benefits of Using Functions
 Reduction in line of code
 code reuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability

Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop

sub function add()


Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return

Draw a flow chart print all prime number between to intervals


# Python program to print all
9 # prime number in an interval

start = 11
end = 25

for val in range(start, end + 1):

# If num is divisible by any number


# between 2 and val, it is not prime
if val > 1:
for n in range(2, val):
if (val % n) == 0:
break
else:
print(val)
Output:
11
13
17
19
23

i). Describe pseudo code for Fibonacci sequence using


ii). Draw a flow chart for factorial given number (3*3)
10

# Function for nth Fibonacci number

def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==1:
return 0
# Second Fibonacci number is 1
elif n==2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)

# Driver Program

print(Fibonacci(9))
Output:
21

i) Draw a flowchart for factorial of given


Number
# Python 3 program to find
# factorial of given number

def factorial(n):

# single line to find factorial


return 1 if (n==1 or n==0) else n * factorial(n - 1)

# Driver Code
num = 5
print ("Factorial of",num,"is",
factorial(num))
Output:
Factorial of 5 is 120
i). Describe the program to insert an element in a sorted list
ii). Draw the flow chart sum of n numbers
11

# Python3 program to insert


# an element into sorted list

# Function to insert element


def insert(list, n):

# Searching for the position


for i in range(len(list)):
if list[i] > n:
index = i
break

# Inserting n in the list


list = list[:i] + [n] + list[i:]
return list
# Driver function
list = [1, 2, 4]
n=3

print(insert(list, n))
Output:
[1, 2, 3, 4]

i) Draw the flowchart to find the sum of series


1+2+3+4+….+100

# Sum of natural numbers up to num

num = 50

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero

while(num > 0):


sum += num
num -= 1
print("The sum is", sum)

output

The sum is 1275


>>>

i). Summarize the difference between algorithm, flow chart and


pseudo code
12
ALGORITHM
• An algorithm is defined as a finite sequence of explicit instructions,
which when provided with a set of input values produces an output and
then terminates.
• To be an algorithm, the steps must be unambiguous and after a finite
number of steps, the solution of the problem is achieved.
FLOWCHART
• A flowchart is a pictorial representation of an algorithm in which the steps are drawn in
the form of different shapes of boxes and the logical flow is indicated by
interconnecting arrows.
• The boxes represent operations and the arrows represent the sequence in which the
operations are implemented.
PSEUDOCODE
• Pseudo code is a generic way of describing an algorithm without
using any specific programming language-related notations.
• It is an outline of a program, written in a form, which can easily be
converted into real programming statements.

(i). Explain algorithmic problem solving technique in detail.

13 Algorithms are the solutions to computational problems. They define a method that uses
the input to a problem in order to produce the correct output. A computational problem
can have many solutions. Efficient algorithms can solve the computational problems
more effectively.

To harness the power of computers we use programming. Programming is the


art of developing a solution to a computational problem, in the form of a set of
instructions that a computer can execute. These instructions are what we call code, and the
language in which they are written a programming language.
The abstract method that such code describes is what we call an algorithm. The aim of
algorithmic problem solving is thus to, given a computational problem, devise an
algorithm that solves it. One does not necessarily need to complete the full programming
process (i.e. write code that implements the algorithm
in a programming language) to enjoy solving algorithmic problems. However, it often
provides more insight and trains you at finding simpler algorithms to problems.
Explain program life cycle

14
 Program Development Cycle
• Development cycle of a program includes:
 Analyse/Define the Problem
 Task Analysis

 Developing Algorithm

 Testing the Algorithm for Accuracy

 Coding the Solution

 Test and Debug the Program

 Documentation

 Implementation

 Maintenance and Enhancement

PART-C
What is pseudo code? Explain how it can be designed and write
benefits and limitations.
1
PSEUDOCODE

 Pseudo code is a generic way of describing an algorithm without


using any specific programming language-related notations.
 It is an outline of a program, written in a form, which can easily be
converted into real programming statements.

Pseudocode is a kind of structured english for describing algorithms. It allows the


designer to focus on the logic of the algorithm without being distracted by details of
language syntax. At the same time, the pseudocode needs to be complete. It describe the
entire logic of the algorithm so that implementation becomes a rote mechanical task of
translating line by line into source code.

In general the vocabulary used in the pseudocode should be the vocabulary of the problem
domain, not of the implementation domain. The pseudocode is a narrative for someone
who knows the requirements (problem domain) and is trying to learn how the solution is
organized.

Advantages and benefits of pseudo code:


Programming can be a complex process when the requirements of the program are
complex in nature. The pseudo code provides a simple method of developing the program
logic as it uses every language to prepare a brief set of instructions in the order in which
they appear. In the completed program it allows the programmer programmers to focus on
the steps required to solve a problem rather than on how to use the computer language.
Some of the most significant benefits of the Pseudo code are:

 Since it is a language-independent it can be used by most programmers it allows


the developer to express the design in plain and natural language.
 It is easier to develop a program from a pseudo code as compared to the flow
chart. Programmers do not have to think about syntax, we simply have to
concentrate on the underline logic. The focus is on the steps to solve a problem
rather than how to use the computer language.
 Often it is easy to translate pseudocode into a programming language, a step
which can be accomplished by less experienced
 The uses of words and phrases in pseudo code, which are in the lines of basic
computer operations simplify the translation from the pseudo code algorithm to
the specific programming language.
 Unlike flow charts, pseudo code is at and does not tend to run over many pages.
Its simple structure and readability make it easier to modify.
 The pseudocode allows programmers to work in different computer languages to
talk to others they can be reviewed by groups easier than the real code.

Disadvantages/limitation of Pseudo Code:

Although the pseudo code is a very simple mechanism to specify problem-solving logic, it
has some of the limitations that are listed below:

 The main disadvantages are that it does not provide a visual representation of the
programming logic.
 There are no accepted standards for writing the pseudo code. Programmers use
their own styles of writing pseudo code.
 The pseudo code cannot be compiled nor executed and there is no real formative
of a syntax of rules. It is simply one step, an important one, in producing the final
code.

Explain guidelines for preparing flowcharts, benefits and limitation of


flowcharts and preparing flow chart for quadratic equation
2
Advantages and Disadvantages of Flowchart

Flowchart Meaning

It is said that a single picture is worth thousands words and flowchart works basically on
that concept only as it illustrates solution of complex problems through diagrams and
thus helps an individual to understand the concept better, however sometimes it may
complicate the solution which in turn will make it even more difficult for an individual to
understand the solution of the problem

Advantages of Flowchart

Short and Simple


The biggest advantage of using flowchart is that it is short as well as simple

Logical Steps

It helps them understand the solution of the problem logically.

Effective Communication

It is one of the effective ways of communicating because flowchart can be made on 1 or


2 pages only as opposed to other methods of communication like written
communication which may take many pages, hence if one wants to save time and
communicate effectively than flowcharts can be a good option for them.

Disadvantages of Flowchart

Not suitable where Solution is long

When the solution of the problem is short than it is a good method but if the solution is
longer than this may not be the ideal method.

Complicate Things

One does not understand the solution even when the solution is right due to the wrong
presentation through flowcharts.

Difficult to Alter

Another limitation is that flowcharts are difficult to alter because if there is one mistake
than one has to alter the whole flowchart
Describe the algorithm for finding sum and average of n numbers.

3
# Sum of natural numbers up to num

num = 50

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero

while(num > 0):


sum += num
num -= 1
print("The sum is", sum)

output

The sum is 1275


>>>

# Python program to get average of a list

# Using reduce() and lambda

# importing reduce()

from functools import reduce

def Average(lst):

return reduce(lambda a, b: a + b, lst) / len(lst)

# Driver Code

lst = [15, 9, 55, 41, 35, 20, 62, 49]

average = Average(lst)

# Printing average of the list

print("Average of the list =", round(average, 2))

Output:
Average of the list = 35.75

# Python program to get average of a list

# Using mean()

# importing mean()

from statistics import mean

def Average(lst):

return mean(lst)
# Driver Code

lst = [15, 9, 55, 41, 35, 20, 62, 49]

average = Average(lst)

# Printing average of the list

print("Average of the list =", round(average, 2))

Output:
Average of the list = 35.75

def cal_average(num):

sum_num = 0

for t in num:

sum_num = sum_num + t

Also state the properties of a good algorithm


Describe the algorithm of towers of Hanoi problem.

4
Tower of Hanoi Problem

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The
objective of the puzzle is to move the entire stack to another rod, obeying the following
simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.

# Recursive Python function to solve tower of hanoi


def TowerOfHanoi(n , from_rod, to_rod, aux_rod):

if n == 1:

print "Move disk 1 from rod",from_rod,"to rod",to_rod

return

TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)

print "Move disk",n,"from rod",from_rod,"to rod",to_rod

TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)

You might also like