Cia1 - Key - Ge3151 PSPP - Set1
Cia1 - Key - Ge3151 PSPP - Set1
Artificial Intelligence & Data Science and Electronics and Communication Engineering
GE3151 - Problem Solving and Python Programming
(Regulations 2021)
Date : 21-12-2022
Time: 180 Minutes Maximum: 100 Marks
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function
EX: Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
The keywords are some predefined and reserved words in python that have special meanings. Keywords
are used to define the syntax of the coding. The keyword cannot be used as an identifier, function, and
variable name. All the keywords in python are written in lower case except True and False. There are 33
keywords in Python 3.7
5.Write an algorithm to accept two numbers, compute the sum and print the result.
Algorithm:
1. start.
2. initialize two variables a,b as int.
3. input a,b, value from the user.
4. add a and b,store the value in sum variable.
5. print sum.
6. stop.
8.Give the python code to find the minimum among the list of 10 numbers.
ls1 = []
n= int (input (" no of elements”))
for i in range (n):
n =int (input ("Enter a number:"))
ls1.append(n)
print (ls1)
min = ls1[0]
for i in range (len (ls1)):
if ls1[i] < min:
min = ls1[i]
print ("The smallest element is ", min)
9. Outline the logic to swap the contents of two identifiers without using third variable.
x = 5.4
y = 10.3
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
# Swap code
x = x + y # x = 15.7, y = 10.3
y = x - y # x = 15.7, y = 5.4
x = x - y # x = 10.3, y = 5.4
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
• Iteration
• Recursion
Iteration
Iteration is a process wherein a set of instructions or structures are repeated in a sequence, a specified
number of times or until a condition is met. Once a problem is clear then the logic of the solution could
be implemented using an iteration where it could run multiple times to achieve a specific outcome.
Step 1: Start
Step 2: Get a number from the user and store it in variable given_number
Step 3: Initialize variables start and storage with 1.
Step 4: Repeat Until start is less than or equal to the given_number
Step 5: Multiply start with storage and store the result in variable storage
Step 6: Increase the value of start with 1 and go to step 4
Step 7: Display the value of storage as the factorial of the given number.
Recursion
Recursion is a technique in which a function calls itself repeatedly until a concluding situation
. happen. A function which utilizes this technique is called a a recursive function.
Step 1: Start
Step 2: Get a number from the user and store it in variable given_number.
Step 5: Stop
Factorial(given_number)
Step1:Start
Step2: Check whether given_number is equal to 1. If true the return 1 otherwise goto Step3
Step3: Multiply the given_number with function call Finding_Factorial passing argument number-1 and
store the result in variable Factorial.
Step5: Stop
ii) Write an algorithm to insert a card into a list of sorted cards.
Algorithm:
Step 1: Start
Step 2: Read n
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 10: If i<n, then goto step 10.1, 10.2 lse goto st 11
12 A) Discuss in detail the various built in data types available in python with suitable examples.
Data types are the classification or categorization of data items. It represents the kind of value that tells
what operations can be performed on a particular data.
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value can be
integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.
• Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fraction or decimal). In Python there is no limit to how long an integer value can be.
• Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
• Complex Numbers – Complex number is represented by complex class. It is specified as (real
part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences allows to
store multiple values in an organized and efficient fashion. There are several sequence types in Python
–
• String
• List
• Tuple
1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or
more characters put in a single quote, double-quote or triple quote. In python there is no character data
type, a character is a string of length one. It is represented by str class.
2) List
Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.
3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple
and list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented
by tuple class.
Boolean
Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are
truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in
Boolean context as well and determined to be true or false. It is denoted by the class bool
Set
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements.
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-
value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.
12 B) Sketch the structures of interpreter and compiler. Detail the difference between them.
Explain how python works in interactive and script mode with examples
A high-level language is one that is understandable by us, humans. This is called source code.
However, a computer does not understand high-level language. It only understands the program written
To convert source code into machine code, we use either a compiler or an interpreter.
Both compilers and interpreters are used to convert a program written in a high-level language into
machine code understood by computers. However, there are differences between how an interpreter and a
compiler works.
Interpreter Vs Compiler
Interpreter Compiler
Interpreters usually take less amount of Compilers usually take a large amount of
time to analyze the source code. However, time to analyze the source code. However,
the overall execution time is comparatively the overall execution time is comparatively
slower than compilers. faster than interpreters.
13.A) Outline the Towers of Hanoi Problem with relevant diagrams. Suggest a solution to the Towers of Hanoi
problem with algorithm, flow chart and pseudo code.
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.
Step 1: Start
Step 8: Stop
START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
STOP
13 b) Write an Algorithm, Pseudo code and draw flowchart for finding the GCD of given number.
Algorithm:
Step 1: Start
Step 2: Read n
Pseudocode:
BEGIN READ n
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
Flowchart:
14. a) Explain in detail about Building Blocks of Algorithm.
Algorithms can be constructed from basic building blocks namely, sequence, selection and iteration.
Statements:
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.
Example:
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.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
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.
Example
Functions:
v Function is a sub program which consists of block of code(set of instructions) that performs a particular
task.
v For complex problems, the problem is been divided into smaller and simpler tasks during algorithm
design.
Example:
14.b) Describe the algorithm for finding sum and average of n numbers. Also state the properties of a
good algorithm.
Algorithm for finding sum and average of N numbers Step 1: start
sum = sum + I
Erledigt
Properties of Algorithms
Should be written in simple English
Each and every instruction should be precise and unambiguous.
Instructions in an algorithm should not be repeated infinitely.
Algorithm should conclude after a finite number of steps.
Should have an end point
Derived results should be obtained only after the algorithm terminates.
Arithmetic operators
Comparison Operator
Assignment operator
Logical operator
Bitwise operator
Membership operator
Identity operator
15.b) i) Show how a tuple can be assigned and state its importance.
Tuple is used for heterogeneous data types and list is used for homogeneous data types.
• Since tuple are immutable, iterating through tuple is faster than with list.
• Tuples that contain immutable elements can be used as key for dictionary.
• Implementing data that doesn‘t change as a tuple remains write-protected.
my_tuple=(‗p‘,‘y‘,‘t‘,‘h‘,‘o‘,‘n‘)
ii) Write a python code to circulate the values of n variables.
def rotate(L,y=1):
if (len(L)==0):
return L
y=y%len(L)
return L[y:]+L[:y]
print(rotate([1,2,3,4])
PART C
16.a) What is pseudo code? Explain how it can be designed with control flow examples and write
benefits and limitations.
PSEUDOCODE
Definition:
Advantages
• It can be done easily in any word processor.
• It can be easily modified as compared to flowchart.
• Its implementation is very useful in structured design elements.
• It can be written easily.
• It can be read and understood easily.
• Converting a pseudocode to programming language is very easy compared with converting a flowchart to
programming language.
Disadvantage
• It is not visual.
• We do not get a picture of the design.
• There is no standardized style or format.
• For a beginner, it is more difficult to follow the logic or write pseudocode as compared to flowchart.
Examples Pseudocode
Problem 1: Calculate sum and average for n numbers.
BEGIN
INITIALIZE sum=0, i=1
READ n
FOR i <=n, then
COMPUTE sum = sum +i
CALCULATE i=i+1
END FOR
COMPUTE avg = sum/n
PRINT sum, avg
END
Problem 2: Calculate area of circle
BEGIN
READ radius, r
INITIALIZE pi=3.14
CALCULATE Area=pi * r *r
PRINT Area
END
16.b) Write an Algorithm, Pseudo code and draw flowchart for Insert a card in a sorted cards
problem.
ALGORITHM:
Step 1: Start
Step 2: Get a list of sorted cards from the user and store it in variable
aList_of_sorted_Cards.
Step 3: Get a new card from the user and store it in variable aNewCard.
Step 5: Find the size of the list, aList_of_sorted_Cards, and store it variable
List_Size.
Step 6: Assign Last_Index with value List_Size -1.
Step 7: Check if Last_Index is greater than zero. If True the goto Step 7.
Step 8: Asssign variable aNewCard with the element in the list ,aList_of_sorted_Cards,in the position
Last_Index.
Step 9: Assign variable Previous_Card with the element in the list,aList_of_sorted_Cards,in the
position Last_Index-1.
Step 10: If aNewCard is less than Previous_Card then swap both these values in the list,
aList_of_sorted_Cards,
Step 11: Decrease the Last_Index value with one and goto Step 6.
GET aList_of_sorted_Cards
GET aNewCard
aNewCard=aList_of_sorted_Cards[Last_Index]
Previous_Card= aList_of_sorted_Cards[Last_Index-1]
Last_Index=Last_Index - 1
END WHILE
DISPLAY aList_ofSorted_cards
FLOWCHART: