Question Paper Code : 170000TB

B.E./B.Tech. DEGREE EXAMINATION, DECEMBER 2017 First Semester GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING (Common to ALL Branches) (Regulations 2017) Answer Key

PART A

1. Define an algorithm.

Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for completing a task.

2. Describe recursion.

A function that calls itself is recursive; the process of executing it is called recursion.

For example, we can write a function that prints a string n times:

def print_n(s, n): if n <= 0: return print(s) print_n(s, n-1)

3. List out the uses of default arguments in python.

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

The following example gives an idea on default arguments, it prints default age if it is not passed:

def printinfo(name, age = 19): print ("Name :", name) print ("Age :", age) printinfo("Arun", 20) printinfo("Babu")

4. Give the various data types in Python.

Int, Float, String, Boolean, Complex, List, Tuple, Set, Dictionary.

5. Differentiate global variable from local variable.

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. 6. What is slicing?

A segment of a string is called a slice. Selecting a slice is similar to selecting a character.

Example:

>>> s = 'Monty Python' >>> s[0:5] 'Monty' >>> s[6:12] 'Python'

7. Compare list and tuple.

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.

8. What will be the output? >>>m = [[x, x + 1, x + 2] for x in range (0, 3)]

No output.

m = [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

9. What is the output when following code is executed? >>>list1 = [1, 3] >>>list2 = list1 >>>list1[0] = 4 >>>print(list2)

[4, 3]

10. Define read() and write() operations in a file.

The read(size) method is used to read in size number of data. If size parameter is not specified, it reads and returns up to the end of the file.

>>> f = open("rec.txt",'') >>> f.read(3) # read the first 3 data 'Wel'

The write method puts data into the file:

>>> line1 = "This here's the wattle,\n" >>> fout.write(line1) 24

2 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PART B

11. (a) (i) Build an algorithm to check the given number is prime number or not. (7)

Step 1: Start Step 2: Declare variables n, i, flag. Step 3: Initialize variables flag←1 i←2 Step 4: Read n from user. Step 5: Repeat the steps until i<(n/2) 5.1 If remainder of n÷i equals 0 flag←0 Go to step 6 5.2 i←i+1 Step 6: If flag=0 Display n is not prime else Display n is prime Step 7: Stop

11. (a) (ii) Draw a flow chart to find the factorial of a given number. (6)

11. (b) (i) Explain in detail about the basic organization of a computer. (8)

Components of computer hardware: 2 marks The computer system hardware comprises of three main components:

1. Input/Output (I/O) Unit, 2. Central Processing Unit (CPU), and 3. Memory Unit.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 3

2 marks Input/Output Unit - The user interacts with the computer via the I/O unit. The Input unit accepts data from the user and the Output unit provides the processed data i.e. the information to the user. The Input unit converts the data that it accepts from the user, into a form that is understandable by the computer. Similarly, the Output unit provides the output in a form that is understandable by the user. The input is provided to the computer using input devices like keyboard, trackball and mouse. Some of the commonly used output devices are monitor and printer. 2 marks Central Processing Unit - CPU controls, coordinates and supervises the operations of the computer. It is responsible for processing of the input data. CPU consists of Arithmetic Logic Unit (ALU) and Control Unit (CU).

• ALU performs all the arithmetic and logic operations on the input data. • CU controls the overall operations of the computer i.e. it checks the sequence of execution of instructions, and, controls and coordinates the overall functioning of the units of computer.

Additionally, CPU also has a set of registers for temporary storage of data, instructions, addresses and intermediate results of calculation. 2 marks Memory Unit - Memory unit stores the data, instructions, intermediate results and output, temporarily, during the processing of data. This memory is also called the main memory or primary memory of the computer. The input data that is to be processed is brought into the main memory before processing. The instructions required for processing of data and any intermediate results are also stored in the main memory. The output is stored in memory before being transferred to the output device. CPU can work with the information stored in the main memory. Another kind of storage unit is also referred to as the secondary memory of the computer. The data, the programs and the output are stored permanently in the storage unit of the computer. Magnetic disks, optical disks and magnetic tapes are examples of secondary memory. - 2 marks

11. (b) (ii) Summarize the difference between algorithm, flow chart and pseudo code. (5) 1 mark Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for completing a task. 1 mark A flowchart is a diagrammatic representation of the logic for solving a task. The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form.

4 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

1 mark Pseudo code consists of short, readable and formally-styled English language used for explaining an algorithm. A pseudo code is easily translated into a programming language. Generally, programmers prefer to write pseudo code instead of flowcharts. 2 marks An algorithm can be represented using a pseudo code. Pseudo code is a readable, formally styled English like language representation of the algorithm. Pseudo code use structured constructs of the programming language for representation. The user does not require the knowledge of a programming language to write or understand a pseudo code.

12. (a) (i) Write a program to find whether the given year is leap year or not. (8) 7 marks Program: year = int(input("Enter the year : ")) if year % 400 == 0: print(year, "is a leap year") elif year % 4 == 0 and year % 100 != 0: print(year, "is a leap year") else: print(year, "is not a leap year") 1 mark Output:

Enter the year : 2012 2012 is a leap year

Enter the year : 2013 2013 is not a leap year

12. (a) (ii) Write a program to print the digit at first and hundredth place of a number. (5) 4 marks Program: n = int(input("Enter the number : ")) print("The digit at first place :", n % 10) print("The digits at hundred place :", n % 100) 1 mark Output:

Enter the number : 786 The digit at first place : 6 The digits at hundred place : 86

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 5

12. (b) What are the different looping statements available in python? Explain with suitable examples. (13) 3 marks Iteration:

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration. while statement: 1 mark Syntax:

while(test-condition): body of the loop statement-x 1 mark Flowchart:

3 marks Example:

n = 4 while n > 0: print(n) n = n - 1 print('Blastoff!')

The flow of execution for a while statement:

1. Determine whether the condition is true or false. 2. If false, exit the while statement and continue execution at the next statement. 3. If the condition is true, run the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top.

The body of the loop should change the value of one or more variables so that the condition becomes false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.

6 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai for Statement:

A for statement is also called a loop because the flow of execution runs through the body and then loops back to the top.

The syntax of a for statement has a header that ends with a colon and an indented body. The body can contain any number of statements. 1 mark Syntax:

for variable in sequence: body of the loop statement-x 1 mark Flowchart:

3 marks Example:

for i in range(4): print('Hello!')

You should see something like this:

Hello! Hello! Hello! Hello!

This is the simplest use of the for statement. In this case, it runs the body four times.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 7

13. (a) (i) Explain the different types of functions with examples. (8) 1 marks Types of Functions:

There are two types of functions:

•Built-in functions •User-defined functions 1 mark Function Definition:

A function definition specifies the name of a new function and the sequence of statements that run when the function is called. 1 mark Syntax

def function_name(parameters): """docstring""" statement(s) 1 mark Example

def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print("I sleep all night and I work all day.") 1 mark def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics. The empty parentheses after the name indicate that this function doesn’t take any arguments.

The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces. The body can contain any number of statements.

The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string. 1 mark Function Calling

The syntax for calling the new function is the same as for built-in functions:

>>> print_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day. 2 marks Built-in Functions:

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.

8 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai abs() dict() help() min() setattr() all() dir() hex() next() slice() any() divmod() id() object() sorted() () enumerate() input() oct() staticmethod() bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float() iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round() delattr() hash() memoryview() set()

13. (a) (ii) Write a program to generate the Fibonacci series. (5) 4 marks Program: n = int(input("Enter the number of terms : ")) a = -1 b = 1 print("The fibonacci series is :") for i in range(1, n + 1): = a + b print(c, end = "\t") a = b b = c 1 mark Output:

Enter the number of terms : 7 The fibonacci series is : 0 1 1 2 3 5 8

13. (b) (i) Explain about parameters and arguments. (8)

The following are the four types of arguments and their rules.

• Required arguments • Keyword arguments • Default arguments • Variable-length arguments

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 9

2 marks Required Arguments

Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

Example:

def printme(s): print(s) printme() 2 marks Keyword Arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

Example:

def printinfo(name, age): print ("Name :", name) print ("Age :", age) printinfo(age = 19, name = "Arun")

Output:

Name : Arun Age : 19 2 marks Default Arguments

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed:

def printinfo(name, age = 19): print ("Name :", name) print ("Age :", age) printinfo("Arun", 20) printinfo("Babu")

Output:

Name : Arun Age : 20 Name : Babu Age : 19

10 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

2 marks Variable-length Arguments

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Following is a simple example:

def printargs(*vartuple): print("Arguments are :") for i in vartuple: print(i) printargs(10, 20) printargs(10, 20, 30)

Output:

Arguments are : 10 20 Arguments are : 10 20 30

13. (b) (ii) Illustrate a python program to find GCD of two numbers. (5) 4 marks Program: n1 = int(input("Enter the first number : ")) n2 = int(input("Enter the second number : ")) while n1 != n2: if n1 > n2: n1 = n1 - n2 if n2 > n1: n2 = n2 - n1 print("The GCD is :", n1) 1 mark Output:

Enter the first number : 10 Enter the second number : 5 The GCD is : 5

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 11

14. (a) (i) Discuss the python list methods with examples. (8) append()

Append adds a new element to the end of a list:

>>> t = ['a', 'b', 'c'] >>> t.append('d') >>> t ['a', 'b', 'c', 'd'] extend()

extend takes a list as an argument and appends all of the elements:

>>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> t1 ['a', 'b', 'c', 'd', 'e']

This example leaves t2 unmodified. sort()

sort arranges the elements of the list from low to high:

>>> t = ['d', 'c', 'e', 'b', 'a'] >>> t.sort() >>> t ['a', 'b', 'c', 'd', 'e'] pop()

There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:

>>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> t ['a', 'c'] >>> x 'b'

pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.

12 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai remove()

If you know the element you want to remove (but not the index), you can use remove:

>>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> t ['a', 'c']

The return value from remove is None.

14. (a) (ii) Write a python program to concatenate two lists. (5) 4 marks Program: a = [] b = [] c = [] n1 = int(input("Enter number of elements for list 1 : ")) for i in range(n1): a.append(int(input("Enter the element : "))) n2 = int(input("Enter number of elements for list 2 : ")) for i in range(n2): b.append(int(input("Enter the element : "))) c = a + b print("The merged list is :", c) 1 mark Output:

Enter number of elements for list 1 : 3 Enter the element : 10 Enter the element : 20 Enter the element : 30 Enter number of elements for list 2 : 2 Enter the element : 5 Enter the element : 15 The merged list is : [10, 20, 30, 5, 15]

14. (b) Illustrate the ways of creating tuple and tuple assignment with suitable programs. (13) 6 marks Tuple Creation:

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.

Syntactically, a tuple is a comma-separated list of values:

>>> t = 'a', 'b', 'c', 'd', 'e'

Although it is not necessary, it is common to enclose tuples in parentheses:

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 13

>>> t = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, you have to include a final comma:

>>> t1 = 'a', >>> type(t1) 7 marks Tuple Assignment:

It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. For example, to swap a and b:

>>> temp = a >>> a = b >>> b = temp

This solution is cumbersome; tuple assignment is more elegant:

>>> a, b = b, a

The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.

The number of variables on the left and the number of values on the right have to be the same:

>>> a, b = 1, 2, 3 ValueError: too many values to unpack (expected 2)

More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split an email address into a user name and a domain, you could write:

>>> addr = '[email protected]' >>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned to uname, the second to domain:

>>> uname 'monty' >>> domain 'python.org'

14 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

15. (a) Write a program to find the one’s complement of binary number using file. (13) numbers.txt

00010100 12 marks Program: f = open("numbers.txt", "r") s = f.read() comp = "" for bit in s: if bit == "1": comp = comp + "0" else: comp = comp + "1" print("One's complement of the number is :", comp) 1 mark Output:

One's compOne's complement of the number is : 11101011

15. (b) Describe in detail about errors and exceptions handling. (13) 2 marks An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.

If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. 2 marks Syntax:

Here is simple syntax of try....except...else blocks:

try: You do your operations here...... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block...... else: If there is no exception then execute this block.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 15

2 marks Here are few important points about the above-mentioned syntax:

• A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. • You can also provide a generic except clause, which handles any exception. • After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. • The else-block is a good place for code that does not need the try: block's protection. 7 marks Example:

This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all:

try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print ("Error: can\'t find file or read data") else: print ("Written content in the file successfully.") fh.close()

This produces the following result:

Written content in the file successfully.

16 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

PART C

16. (a) Design a simple arithmetic calculator (using functions). (15) 14 marks Program: def add(a, b): return a + b def sub(a, b): return a - b def mul(a, b): return a * b def div(a, b): return a / b n1 = int(input("Enter the first number : ")) n2 = int(input("Enter the second number : ")) print("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division") choice = int(input("Enter your choice : ")) if choice == 1: print(add(n1, n2)) elif choice == 2: print(sub(n1, n2)) elif choice == 3: print(mul(n1, n2)) elif choice == 4: print(div(n1, n2)) else: print("Invalid choice") 1 mark Output:

Enter the first number : 10 Enter the second number : 5 1.Addition 2.Subtraction 3.Multiplication 4.Division Enter your choice : 3 50

16. Write a program to read a file and display the vowels in it. (15) input.txt:

Welcome to REC CSE Thandalam

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 17

14 marks Program: f = open("input.txt", "r") s = f.read() for char in s: if char in 'aeiouAEIOU': print(char) 1 mark Output: e o e o E E a a a

18 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Question Paper Code : 1700TA

B.E./B.Tech. DEGREE EXAMINATION, MARCH 2018 First Semester GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING (Common to ALL Branches) (Regulations 2017)

PART A

1. Define pseudo code. Why is pseudo code required? 1 mark Pseudo code consists of short, readable and formally-styled English language used for explaining an algorithm. 1 mark A pseudo code is easily translated into a programming language. Generally, programmers prefer to write pseudo code instead of flowcharts.

2. Draw a flowchart to print the largest of three numbers.

3. What do you mean by expression in Python? Give an example. 1 mark An expression is a combination of values, variables, and operators. 1 mark A value all by itself is considered an expression, and so is a variable, so the following is a legal expression:

>>> a = 10 >>> a + 20 30

4. Compare the break and continue statements in Python? 1 mark The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop. 1 mark The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 19

5. What is a function in Python? How will you define a function? 1 mark A function is a named sequence of statements that performs a computation. 1 mark A function definition specifies the name of a new function and the sequence of statements that run when the function is called.

Syntax:

def function_name(parameters): """docstring""" statement(s)

6. What is a string slice? Give an example. 1 mark A segment of a string is called a slice. Selecting a slice is similar to selecting a character. 1 mark Example:

>>> s = 'Monty Python' >>> s[0:5] 'Monty' >>> s[6:12] 'Python'

7. How to traverse a tuple? Give an example. 1 mark The most common way to traverse the elements of a tuple is with a for loop. – 1 mark 1 mark Example:

cheeses = ('Cheddar', 'Edam', 'Gouda') for cheese in cheeses: print(cheese)

8. How tuples are different from lists?

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.

9. List the purpose of tell() and seek() methods? 1 mark The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file. 1 mark The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.

20 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

10. Write a short note on any two Python's predefined error types. 1 mark ZeroDivisonError - Raised when division or modulo by zero takes place for all numeric types. 1 mark IndexError - Raised when an index is not found in a sequence.

PART B

11. (a) (i) Define computer. Explain the five characteristics of a computer. (8) 3 marks The term computer is derived from the word compute. The word compute means to calculate. A computer is an electronic machine that accepts data from the user, processes the data by performing calculations and operations on it, and generates the desired output results. Computer performs both simple and complex operations, with speed and accuracy. 1 mark Speed - The computer can process data very fast, at the rate of millions of instructions per second. 1 mark Accuracy - Computer provides a high degree of accuracy. For example, the computer can accurately give the result of division of any two numbers up to 10 decimal places. 1 mark Diligence - When used for a longer period of time, the computer does not get tired or fatigued. It can perform long and complex calculations with the same speed and accuracy from the start till the end. 1 mark Storage Capability - Large volumes of data and information can be stored in the computer and also retrieved whenever required. A limited amount of data can be stored, temporarily, in the primary memory. Secondary storage devices like floppy disk and compact disk can store a large amount of data permanently. 1 mark Versatility - Computer is versatile in nature. It can perform different types of tasks with the same ease.

11. (a) (ii) What is an algorithm? Write an algorithm to compute the sum of odd and even numbers up to N. (5) 2 marks Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for completing a task. 3 marks Step 1 : Start. Step 2 : Input N. Step 3 : sume = 0. Step 4 : sumo = 0. Step 5 : ctr = 1. Step 6: while (ctr <= N). if (ctr mod 2 = 0) sume = sume + ctr else sumo = sumo + ctr. ctr = ctr + 1 Step 7 : Print "Sum of even number is", sume.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 21

Step 8 : Print "Sum of odd number is", sumo. Step 9 : End.

11. (b) Draw the block diagram to illustrate the basic organization of computer system and explain the functions of the various units. (13) 2 marks Block diagram:

2 marks Components of computer hardware:

The computer system hardware comprises of three main components: 1. Input/Output (I/O) Unit, 2. Central Processing Unit (CPU), and 3. Memory Unit. 3 marks Input/Output Unit - The user interacts with the computer via the I/O unit. The Input unit accepts data from the user and the Output unit provides the processed data i.e. the information to the user. The Input unit converts the data that it accepts from the user, into a form that is understandable by the computer. Similarly, the Output unit provides the output in a form that is understandable by the user. The input is provided to the computer using input devices like keyboard, trackball and mouse. Some of the commonly used output devices are monitor and printer. 3 marks Central Processing Unit - CPU controls, coordinates and supervises the operations of the computer. It is responsible for processing of the input data. CPU consists of Arithmetic Logic Unit (ALU) and Control Unit (CU). • ALU performs all the arithmetic and logic operations on the input data. • CU controls the overall operations of the computer i.e. it checks the sequence of execution of instructions, and, controls and coordinates the overall functioning of the units of computer. Additionally, CPU also has a set of registers for temporary storage of data, instructions, addresses and intermediate results of calculation. 3 marks Memory Unit - Memory unit stores the data, instructions, intermediate results and output, temporarily, during the processing of data. This memory is also called the main memory or primary memory of the computer. The input data that is to be processed is brought into the main memory before processing. The instructions required for processing of data and any intermediate results are also stored in the main memory. The output is stored in memory before being transferred to the output device. CPU can work with the information stored in the main memory. Another kind of storage unit is also referred to as the secondary memory of the computer. The data, the programs and the output are stored permanently in the storage unit of the computer. Magnetic disks, optical disks and magnetic tapes are examples of secondary memory.

22 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

12. (a) (i) Explain the "if-elif-else" statement in Python with an example program. (8) 2 marks Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional. 2 marks Syntax:

if(test-condition-1): statement-1 elif(test-condition-2): statement-2 ...... elif(test-condition-n): statement-n else: default-statement statement-x 2 marks Flowchart:

2 marks

Example:

if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x and y are equal')

elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 23

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs.

12. (a) (ii) Illustrate the various arithmetic operators used in Python with suitable examples. (5)

Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example + Addition Adds values on either side of the operator. a + b = 30 Subtracts right hand operand from left hand a - b = -10 - Subtraction operand. b - a = 10 * Multiplication Multiplies values on either side of the operator. a * b = 200 Divides left hand operand by right hand operand. a / b = 0.5 / Division b / a = 2.0 Divides left hand operand by right hand operand a % b = 10 % Modulus and returns remainder. b % a = 0 Performs exponential (power) calculation on a**2 =100 ** Exponent operators. b ** 3 = 8000 Floor Division - The division of operands where the result is the quotient in which the digits after a // b = 0 the decimal point are removed. But if one of the // b // a = 2 operands is negative, the result is floored, i.e.,

rounded away from zero (towards negative infinity).

12. (b) Define Iteration. Explain the “while” and “for” loops in Python with syntax, flow diagram and example. (13) 3 marks Iteration:

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration. while statement: 1 mark Syntax:

while(test-condition): body of the loop statement-x

24 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

1 mark Flowchart:

3 marks Example:

n = 4 while n > 0: print(n) n = n - 1 print('Blastoff!')

The flow of execution for a while statement:

4. Determine whether the condition is true or false. 5. If false, exit the while statement and continue execution at the next statement. 6. If the condition is true, run the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top.

The body of the loop should change the value of one or more variables so that the condition becomes false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop. for Statement:

A for statement is also called a loop because the flow of execution runs through the body and then loops back to the top.

The syntax of a for statement has a header that ends with a colon and an indented body. The body can contain any number of statements. 1 mark Syntax:

for variable in sequence: body of the loop statement-x

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 25

1 mark Flowchart:

3 marks Example:

for i in range(4): print('Hello!')

You should see something like this:

Hello! Hello! Hello! Hello!

This is the simplest use of the for statement. In this case, it runs the body four times.

13. (a) (i) Explain the recursive function in Python with suitable example. (8)

It is legal for one function to call another; it is also legal for a function to call itself.

A function that calls itself is recursive; the process of executing it is called recursion.

If you looked up the definition of the factorial function, denoted with the symbol !, you might get something like this:

0! = 1 n! = n(n-1)!

This definition says that the factorial of 0 is 1, and the factorial of any other value, n, is n multiplied by the factorial of n-1.

So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together, 3! equals 3 times 2 times 1 times 1, which is 6.

26 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

If you can write a recursive definition of something, you can write a Python program to evaluate it. The first step is to decide what the parameters should be. In this case it should be clear that factorial takes an integer:

def factorial(n):

If the argument happens to be 0, all we have to do is return 1:

def factorial(n): if n == 0: return 1

Otherwise, and this is the interesting part, we have to make a recursive call to find the factorial of n-1 and then multiply it by n:

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

The flow of execution for this program is similar to the flow of countdown in “Recursion”. If we call factorial with the value 3:

Since 3 is not 0, we take the second branch and calculate the factorial of n-1...

Since 2 is not 0, we take the second branch and calculate the factorial of n-1...

Since 1 is not 0, we take the second branch and calculate the factorial of n-1...

Since 0 equals 0, we take the first branch and return 1 without making any more recursive calls.

The return value, 1, is multiplied by n, which is 1, and the result is returned.

The return value, 1, is multiplied by n, which is 2, and the result is returned.

The return value (2) is multiplied by n, which is 3, and the result, 6, becomes the return value of the function call that started the whole process.

Figure shows what the stack diagram looks like for this sequence of function calls.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 27

Figure. Stack diagram.

The return values are shown being passed back up the stack. In each frame, the return value is the value of result, which is the product of n and recurse.

In the last frame, the local variables recurse and result do not exist, because the branch that creates them does not run.

13. (a) (ii) Write a Python program to compute nCr using recursive function. (5) 4 marks Program: def factorial(n): if n == 0: return 1 else: return(n * factorial(n - 1)) n = int(input("Enter the value for n : ")) r = int(input("Enter the value for r : ")) if n >= r: ncr = factorial(n) / (factorial(n - r) * factorial(r)) print("The NCR value is :", ncr) else: print("Calculating NCR value is not possible") 1 mark Output:

Enter the value for n : 7 Enter the value for r : 5 The NCR value is : 21.0

Enter the value for n : 5 Enter the value for r : 7 Calculating NCR value is not possible

28 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

13. (b) What do you mean by string in Python? Explain any six string methods with examples. (13) 1 mark String:

A string is a sequence, which means it is an ordered collection of other values. 2 marks str.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased.

Example: s = "python programming" print(s.capitalize())

Output: Python programming 2 marks str.count()

Return the number of non-overlapping occurrences of substring sub in the range [start, end].

Example: s = "python programming" print(s.count("a")) Output: 1 2 marks str.find()

Return the lowest index in the string where substring sub is found within the slice s[start:end].

Example: s = "python programming" print(s.find("on")) print(s.find("va")) Output: 4 -1 2 marks str.index()

Like find(), but raise ValueError when the substring is not found.

Example: s = "python programming" print(s.index("on")) print(s.index("va")) Output: 4 ValueError: substring not found

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 29

2 marks str.lower()

Return a copy of the string with all the cased characters converted to lowercase.

Example: s = "python programming" p = "PSPP" t = "CSE Lab" print(s.lower()) print(p.lower()) print(t.lower()) Output: python programming pspp cse lab 2 marks str.upper()

Return a copy of the string with all the cased characters converted to uppercase.

Example: s = "python programming" p = "PSPP" print(s.upper()) print(p.upper()) Output: PYTHON PROGRAMMING PSPP

14. (a) (i) Briefly discuss about various list methods with suitable examples. (8) append()

Append adds a new element to the end of a list:

>>> t = ['a', 'b', 'c'] >>> t.append('d') >>> t ['a', 'b', 'c', 'd'] extend()

extend takes a list as an argument and appends all of the elements:

>>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> t1 ['a', 'b', 'c', 'd', 'e']

This example leaves t2 unmodified.

30 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai sort()

sort arranges the elements of the list from low to high:

>>> t = ['d', 'c', 'e', 'b', 'a'] >>> t.sort() >>> t ['a', 'b', 'c', 'd', 'e'] pop()

There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:

>>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> t ['a', 'c'] >>> x 'b'

pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element. remove()

If you know the element you want to remove (but not the index), you can use remove:

>>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> t ['a', 'c']

The return value from remove is None.

14. (a) (ii) What do you mean by a Python dictionary? What is a key-value pair with reference to dictionary? How to create a dictionary in Python? (5) 1 mark A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type. 2 marks A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item. 2 marks The function dict creates a new dictionary with no items.

>>> eng2sp = dict() >>> eng2sp {}

The squiggly brackets, {}, represent an empty dictionary.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 31

You can create a new dictionary with three items:

>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

14. (b) Write a Python program to search an element from a list using Binary Search algorithm and print the location of the element. (13) 12 marks Program: def BinarySearch(a, key): first = 0 last = len(a) - 1 while first <= last: mid = (first + last) // 2 if a[mid] == key: return mid elif a[mid] < key: first = mid + 1 else: last = mid - 1 return -1 n = int(input("Enter the limit : ")) print("Enter the elements in sorted order : ") a = [] for i in range(n): a.append(int(input())) key = int(input("Enter the element to search : ")) pos = BinarySearch(a, key) if pos != -1: print("Element found at location", pos) else: print("Element not found.") 1 mark Output:

Enter the limit : 5 Enter the elements in sorted order : 10 20 30 40 50 Enter the element to search : 30 Element found at location 2

Enter the limit : 5 Enter the elements in sorted order : 10 20 30 40 50 32 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

Enter the element to search : 55 Element not found.

15. (a) (i) Explain the file writing and reading operations in Python with suitable examples. (8) 2 marks Writing into a file

In order to write into a file in Python, we need to open it in write 'w', or append 'a' mode.

Writing a string or sequence of bytes (for binary files) is done using write() method. This method returns the number of characters written to the file. 2 marks f = open("rec.txt",'w') f.write("Welcome to\n") f.write("REC CSE\n") f.write("Thandalam\n")

This program will create a new file named 'rec.txt' if it does not exist. If it does exist, it is overwritten.

We must include the newline characters ourselves to distinguish different lines. 2 marks Reading from a file

To read a file in Python, we must open the file in reading mode.

There are various methods available for this purpose. We can use the read(size) method to read in size number of data. If size parameter is not specified, it reads and returns up to the end of the file. 2 marks >>> f = open("rec.txt",'r') >>> f.read(3) # read the first 3 data 'Wel' >>> f.read(4) # read the next 4 data 'come' >>> f.read() # read in the rest till end of file ' to \nREC CSE\nThandalam\n' >>> f.read() # further reading returns empty sting ''

We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get empty string on further reading.

Alternately, we can use readline() method to read individual lines of a file. This method reads a file till the newline, including the newline character.

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading method return empty values when end of file (EOF) is reached.

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 33

15. (a) (ii) Write a Python program to read the contents from the file named “input.dat” and writes it into the file named “output.dat”. (5) input.dat GE17151 Problem Solving and Python Programming 4 marks Program: file1 = open("input.dat", "r") file2 = open("output.dat", "w") for line in file1: file2.write(line) file1.close() file2.close() 1 mark output.dat

GE17151 Problem Solving and Python Programming

15. (b) Elaborate the usage of command line arguments in Python with proper examples. (13) 4 marks They sys module in Python is one of many available modules of library code.

sys.argv is the list of command line arguments passed to the Python program. argv represents all the items that come along via the command line input, it's basically an array holding the command line arguments of our program. The counting starts at zero (0) not one (1).

To use it, you will first have to import it (import sys). The first argument, sys.argv[0], is always the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual command line argument: 3 marks import sys name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments) print("Program name =", name) print("Total arguments =", count)

To run it, simply type:

C:\PSPP>python CLA.py GE17151 PSPP Program name = C:\PSPP\CLA.py Total arguments = 2 3 marks This is an example on how to read the argument from the command line:

import sys for i in sys.argv: print("Argument :", i)

34 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai

To run it, simply type:

C:\PSPP>python CLA.py

Argument : CLA.py

C:\PSPP>python CLA.py GE17151 PSPP

Argument : C:\PSPP\CLA.py Argument : GE17151 Argument : PSPP 3 marks len(sys.argv), checks how many arguments that have been entered.

len(sys.argv) != 2 just checks whether you entered at least two elements or not.

import sys if len(sys.argv) != 2: print("Usage: python example.py") sys.exit(1)

PART C

16. (a) Develop a Python code to complete the following task: Given a list, A, of size N with distinct elements, sort the list in ascending order using the Bubble Sort algorithm. Once sorted, print the following 2 lines as an output: Line 1: First Element: firstElement where firstElement is the first element in the sorted array. Line 2: Last Element: lastElement where lastElement is the last element in the sorted array. (15) 14 marks Program: def BubbleSort(a): for i in range(0, len(a) - 1): for j in range(0, len(a) - 1 - i): if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] n = int(input()) a = [] for i in range(n): a.append(int(input())) BubbleSort(a) print("First Element:", a[0]) print("last Element:", a[n-1]) 1 mark Output: 5 30 40 50 20 10

B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai 35

First Element: 10 last Element: 50

16. Develop a Python code to complete the following task: You are given a positive integer N. Your task is to print a palindromic triangle of size N. For example, a palindromic triangle of size 5 is: 1 121 12321 1234321 123454321 (15) 14 marks Program: n = int(input()) for i in range(1, n + 1): for j in range(1, i + 1): print(j, end = "") for j in range(i - 1, 0, -1): print(j, end = "") print()

1 mark Output:

5 1 121 12321 1234321 123454321

36 B.BHUVANESWARAN | AP (SG) | CSE | Rajalakshmi Engineering College | Chennai