GE8151 Python Programming - Unit I Question Bank With Sample Code
GE8151 Python Programming - Unit I Question Bank With Sample Code
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
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.
The project implementation now needs to be monitored by the group to ensure their
recommendations are followed. Monitoring includes checking:
Bubble Sort
Selection Sort
Insertion Sort
Merge Sort
Heap Sort
Quick Sort
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.
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.
Output:
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
Think:
Execute
1. Code it up
2. Test your solution against your examples
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
PART-B
Explain the algorithm GCD and find LCM
Pseudocode
while n ≠ 0 do
r ← m mod n
m←n
n←r
return m
Sample Output:
-8
Sample Output:
2
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
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
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
Output
111 is not a prime number
3 times 37 is 111
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.
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
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.
i) 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.
Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
start = 11
end = 25
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
def factorial(n):
# 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
print(insert(list, n))
Output:
[1, 2, 3, 4]
num = 50
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
output
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.
14
Program Development Cycle
• Development cycle of a program includes:
Analyse/Define the Problem
Task Analysis
Developing Algorithm
Documentation
Implementation
PART-C
What is pseudo code? Explain how it can be designed and write
benefits and limitations.
1
PSEUDOCODE
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.
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.
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
Logical Steps
Effective Communication
Disadvantages of Flowchart
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
output
# importing reduce()
def Average(lst):
# Driver Code
average = Average(lst)
Output:
Average of the list = 35.75
# Using mean()
# importing mean()
def Average(lst):
return mean(lst)
# Driver Code
average = Average(lst)
Output:
Average of the list = 35.75
def cal_average(num):
sum_num = 0
for t in num:
sum_num = sum_num + t
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.
if n == 1:
return