Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

SRM TRP ENGINEERING COLLEGE

CONTINUOUS INTERNAL ASSESSMENT – I KEY


(CIA - I), DECEMBER 2022

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

PART A (10 *2 = 20 MARKS)

1.List out the symbols used in drawing flowchart

2. Define Recursion with Example.

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.

3. Distinguish between Algorithm and Program.

Algorithm – It is a well-defined, systematic logical approach that comes with a step-by-step


procedure for computers to solve any given program.
Program – It refers to the code (written by programmers) for any program that follows the
basic rules of the concerned programming language.
4. What are Keywords? Give example.

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

False await else import pass

None break except in raise

True class finally is return


and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

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.

6.How the Comments line will be used in Python Program?


comments in Python begin with a hash mark ( # ) and whitespace character and continue to the end of the
line. ... Because comments do not execute, when you run a program you will not see any indication of the
comment there. Comments are in the source code for humans to read, not for computers to execute.

7.Name the four types of scalar objects in python


Scalar data types: integers, floats, None and bool.

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)

10. State the reasons to divide programs into functions.


A function can be called multiple times to provide reusability and modularity to the Python program. The
Function helps to programmer to break the program into the smaller part.
PART B - (3 x 10 = 30 marks)
11a) I ) Identify the simple strategies for developing an algorithm.
Developing an algorithm is a very important step in problem-solving. There are different types of
strategies that could be used to develop an algorithm to solve a problem. Two of the most frequently used
strategies are:

• 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.

Example: Find the factorial of a number.

An algorithm using Iteration:

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.

Example: Finding the factorial of a number using Recursion

An algorithm using Recursion:

Step 1: Start

Step 2: Get a number from the user and store it in variable given_number.

Step 3: Call the subroutine Finding_Factorial by passing the argument given_number.

Step 4: Display the returned value as Factorial

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.

Step4: Return the 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 3:Initialize i=0

Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5

Step4.1: Read a[i]

Step 4.2: i=i+1 goto step 4

Step 5: Read item

Step 6: Calculate i=n-1

Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8

Step 7.1: a[i+1]=a[i]

Step 7.2: i=i-1 goto step 7

Step 8: Compute a[i+1]=item

Step 9: Compute n=n+1

Step 10: If i<n, then goto step 10.1, 10.2 lse goto st 11

Step10.1: Print a[i]

Step10.2: i=i+1 goto step 10

Step 11: Stop

11 B) Explain in detail the different types of programming languages.


Programming language:
It is a formal computer language which is designed to communicate instructions or commands
or orders to a machine, particularly a computer. Programming languages can be used to create
program to control the behaviour of the machine.
Different types of programming languages:
A. Compiled Languages:
A compiled language is a programming language in which we use a compiler to compile
and execute our code. the compilers are generally translators that generate machine level
code from our written source code.
Example:
• C
• C++
• C#
• ALGOL
• Cobol
• Fortran
• Java
• Visual Basic
• Smalltalk
B. Interpreted Languages:
An interpreted language is a programming language in which without compiling a
program into machine-language instructions we can execute instructions directly and
freely. The interpreter executes the program line by line.Interpreted a language gives
many additional flexibility over compiled implementations like, platform independence,
dynamic scoping, dynamic typing etc.
Example:
• Python
• Ruby
• Perl
• Pascal
• Lisp
• BASIC
• APL
C. Scripting Languages:
Scripting languages are programming languages that control an application. Scripts which
can be executed independently over any other application. They are widely used in the
application that they control and are used in automation.
Example:
• PHP
• VBScript
• Windows PowerShell
• F-Script
• BeanShell
• AutoIt
• R
• Game Maker Language
D. Markup Languages:
A markup language is an artificial language that used for annotating a document so that it
is syntactically distinguishable from the text, the text that define how the text is to be
displayed.
Example:
• HTML
• XML
• XHTML
• SGML
• Curl
E. Procedural Languages:
Procedural (imperative) programming implies specifying the steps that the programs
should take to reach to an intended state. A procedure is nothing but a set of instructions
that can be referenced through a procedure call. this help in the reuse of code. This type of
programming makes the programs structured and easily traceable for program flow.
Example:
• HyperTalk
• Go
• PL/C
• PL/I
• MATLAB
• Curl
• Mathematica
• MATLAB
F. Functional Languages:
Functional programming languages define every computation as a mathematical
evaluation. They focus on the application of functions.Some of the functional
programming languages are pure functional language but many so-called functional
languages are impure, containing imperative features, they are not pure function
languages.
Example:
• Pure Functional
• Agda
• SAC
• SASL
• Cuneiform
• Curry
• Futhark
• Haskell

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

in 0's and 1's in binary, called the machine code.

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

Scans the entire program and translates it as


Translates program one statement at a time.
a whole into machine code.

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.

Generates Object Code which further


No Object Code is generated, hence are
requires linking, hence requires more
memory efficient.
memory.

Programming languages like JavaScript, Programming languages like C, C++, Java


Python, Ruby use interpreters. use compilers.
Working of Compiler and Interpreter

Interactive and Script mode with examples


There are two modes through which we can create and run Python scripts: interactive mode and script mode. The interactive
mode involves running your codes directly on the Python shell which can be accessed from the terminal of the operating
system. In the script mode, you have to create a file, give it a name with a .py the extension then runs your code. The
interactive mode is suitable when running a few lines of code. The script mode is recommended when you need to create
large applications.

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 2: Let the three towers be the source, dest, aux.

Step 3: Read the number of disks, n from the user.

Step 4: Move n-1 disks from source to aux.

Step 5: Move nth disk from source to dest.

Step 6: Move n-1 disks from aux to dest.

Step 7: Repeat Steps 3 to 5, by decrementing n by 1.

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

Step 3:Initialize i=0

Step 4: If i<n, then goto

step 4.1, 4.2 else goto

step 5 Step4.1: Read a[i]

Step 4.2: i=i+1 goto step 4

Step 5: Compute min=a[0]


Step 6: Initialize i=1

Step 7: If i<n, then go to step 8 else goto step 10

Step 8: If a[i]<min, then goto

step 8.1,8.2 else goto 8.2

Step 8.1: min=a[i]

Step 8.2: i=i+1 goto 7

Step 9: Print min

Step 10: Stop

Pseudocode:

BEGIN READ n

FOR i=0 to n, then

READ a[i]

INCREMENT i

END FOR

COMPUTE min=a[0]

FOR i=1 to n, then

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:

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.

Example:

Add two numbers:


Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop

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

Write an algorithm to print all natural numbers up to n


Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop

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.

Benefits of Using Functions

v Reduction in line of code


v code reuse
v Better readability
v Information hiding
v Easy to debug and test
v 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

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

Step 2: read the value of N Step 3: initialize sum as 0


Step 3: until I less than or equal to N Repeat

sum = sum + I

Erledigt

Step 4: print sum Step 5: stop

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.

Qualities of a good algorithm


The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser is the time
required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space. The lesser is the
memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some of
these may provide more accurate results than others, and such algorithms may be suitable.
Example
Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop

15. a) Explain in detail about the various operators in python.

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:

· “Pseudo” means initiation or false.


· “Code” means the set of statements or instructions written in a programming language.
· Pseudocode is also called as “Program Design Language [PDL]”.
· Pseudocode is a Programming Analysis Tool, which is commonly used for planning he program
logic.
· Pseudocode is written in normal English and cannot be understood by the computer.
· Set of instructions that mimic programming language instructions
· An informal high-level description of the operating principle of a computer program. It uses the
structural conventions of a programming language, but is intended for human reading rather than machine
reading.

Rules for writing Pseudocode


1. Write one statement per line
2. Capitalize initial keywords (READ, WRITE, IF, WHILE, UNTIL).
3. Indent to show hierarchy.
4. End multiline structure.
5. Keep statements language.

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 4: Append the new card, aNewCard, to the list, aList_of_sorted_Cards.

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.

Step 12: Dispaly the list, aList_of_sorted_Cards

Step 13: Stop


PSEUDOCODE:

GET aList_of_sorted_Cards

GET aNewCard

APPEND aNewCard to aList_of_sorted_Cards

COMPUTE List_Size = Length(aList_of_sorted_Cards)

ASSIGN Last_Index= List_Size-1

WHILE Last_Index >=0

aNewCard=aList_of_sorted_Cards[Last_Index]
Previous_Card= aList_of_sorted_Cards[Last_Index-1]

IF aNewCard < Previous_Card


//Swap the two cards
aList_of_sorted_Cards[Last_Index] = Previous_Card
aList_of_sorted_Cards[Last_Index-1] = aNewCard

Last_Index=Last_Index - 1

END WHILE
DISPLAY aList_ofSorted_cards

FLOWCHART:

You might also like