Sunteți pe pagina 1din 49

Page 1

PagePage 11 MAHENDRA INSTITUTE OF TECHNOLOGY

Mallasamudram (west),Namakkal. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LABORATORY MANUAL

GE8161PROBLEM SOLVING AND

PYTHON PROGRAMMING

LABORATORY

 NAME :……………………………………………………………. YEAR :…………………………………………………………… SEM :……………………………………………………………. DEPT :……………………………………………………………

PREPARED BY

Mr.B.MOHANRAJ,

AP/CSE,

.

Mr.B.Mohanraj AP CSE MIT

Page 2

PagePage 22

LIST OF EXPERIMENTS:

1.Compute the GCD of two numbers.

2. Find the square root of a number (Newtons method)

3. Exponentiation (power of a number)

4. Find the maximum of a list of numbers

5. Linear search and Binary search

6. Selection sort, Insertion sort

7. Merge sort

8. First n prime numbers

9. Multiply matrices

10. Programs that take command line arguments (word count)

11. Find the most frequent words in a text read from a file

12. Simulate elliptical orbits in Pygame

13.Simulate bouncing ball in Pygame

Mr.B.Mohanraj AP CSE MIT

Page 3

PagePage 33

 GE 8161 – PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY CONTENTS Sl.No. Name of the Experiment Sign 1 Compute the GCD of two numbers. 2 Find the square root of a number (Newton’s method) 3 Exponentiation (power of a number) 4 Find the maximum of a list of numbers 5(a) Linear search 5(b) Binary search 6(a) Selection sort 6(b) Insertion sort 7 Merge sort 8 First n prime numbers 9 Multiply matrices 10 Programs that take command line arguments (word count) 11 Find the most frequent words in a text read from a file 12 Simulate elliptical orbits in Pygame 13 Simulate bouncing ball in Pygame

Mr.B.Mohanraj AP CSE MIT

Page 4

PagePage 44

Ex. No. :01 Date:

GCD OF TWO NUMBERS

Aim:

To write a Python program to find GCD of two numbers.

Algorithm:

1. Define a function named computeGCD()

2. Find the smallest among the two inputs x and y

3. Perform the following step till smaller+1

Check if ((x % i == 0) and (y % i == 0)), then assign GCD=i

4. Print the value of gcd

Program:

def computeGCD(x, y):

if x > y:

smaller = y

else:

smaller = x for i in range(1, smaller+1):

if((x % i == 0) and (y % i == 0)):

gcd = i return gcd num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: "))

print("The GCD. of", num1,"and", num2,"is", computeGCD(num1, num2))

Mr.B.Mohanraj AP CSE MIT

Page 5

PagePage 55

Sample output :

Enter first number: 54 Enter second number: 24

The GCD of 54 and 24 is 6

Result:

Thus the Python program to compute GCD of two numbers is executed successfully and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 6

PagePage 66

 Ex. No. :02 Date: SQUARE ROOT OF A NUMBER Aim: To write a Python Program to find the square root of a number by Newton’s Method. Algorithm: 1. Define a function named newtonSqrt(). 2. Initialize approx as 0.5*n and better as 0.5*(approx.+n/approx.) 3. Use a while loop with a condition better!=approx to perform the following, i. Set approx.=better ii. Better=0.5*(approx.+n/approx.) 4. Print the value of approx Program: def newtonSqrt(n): approx = 0.5 * n better = 0.5 * (approx + n/approx) while better != approx : approx = better better = 0.5 * (approx + n/approx) return approx num1 = int(input("Enter number: ")) print("The square root is" ,newtonSqrt(num1))

Mr.B.Mohanraj AP CSE MIT

Page 7

PagePage 77

Output:

Enter number: 81

The square root is 9.0

Result:

Thus the Python program for finding the square root of a given number by Newton’s

Method is executed successfully and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 8

PagePage 88

Ex. No. : 03 Date:

EXPONENTIATION OF A NUMBER

Aim:

To write a Python program to find the exponentiation of a number.

Algorithm:

1. Define a function named power()

2. Read the values of base and exp

3. Use ‘if’ to check if exp is equal to 1 or not i. if exp is equal to 1, then

return base

ii.if exp is not equal to 1, then return (base*power(base,exp-1))

4. Print the result

Program:

def power(base,exp):

if(exp==1):

return(base)

if(exp!=1):

return(base*power(base,exp-1))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value: "))

print("Result:",power(base,exp) )

Mr.B.Mohanraj AP CSE MIT

Page 9

PagePage 99

Output:

Enter base: 7 Enter exponential value: 2

Result:49

Result:

Thus the Python program to find the exponentiation of a number is executed successfully and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 10

PagePage 1010

 Ex. No. : 04 Date: FINDING MAXIMUM FROM A LIST OF NUMBERS Aim: To write a Python Program to find the maximum from a list of numbers. Algorithm: 1. Create an empty list named l 2. Read the value of n 3. Read the elements of the list until n 4. Assign l as maxno 5. If l[i]>maxno then set maxno=l[i] 6. Increment i by 1 7. Repeat steps 5-6 until imaxno: maxno=l[i] print("The maximum number is %d" %maxno)

Mr.B.Mohanraj AP CSE MIT

Page 11

PagePage 1111

Output:1

enter the upper limit 3

enter the numbers 12

enter the numbers 25

enter the numbers 45

The maximum number is 45

Output 2:

enter the upper limit 3

enter the numbers 15

enter the numbers 25

enter the numbers 0

The maximum number is 25

Result:

Thus a Python Program to find the maximum from the given list of numbers is successfully executed and the output is verified.

Mr.B.Mohanraj AP CSE MIT

 Page 12 PagePage 1212 Ex. No. : 5(a) Date: LINEAR SEARCH Aim: To write a Python Program to perform Linear Search Algorithm: 1. Read n elements into the list 2. Read the element to be searched 3. If alist[pos]==item, then print the position of the item 4. Else increment the position and repeat step 3 until pos reaches the length of the list Program: def search(alist,item): pos=0 found=False stop=False while positem: stop=True else: pos=pos+1 return found a=[] n=int(input("enter upper limit")) for i in range(0,n): e=int(input("enter the elements")) a.append(e) x=int(input("enter element to search")) search(a,x)

Mr.B.Mohanraj AP CSE MIT

Page 13

PagePage 1313

Output:

Enter upper limit 5 Enter the elements 6 Enter the elements 45 Enter the elements 2 Enter the elements 61 Enter the elements 26 Enter element to search 6 Element found in position 1

Result:

Thus the Python Program to perform linear search is executed successfully and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 14

PagePage 1414

 EX. No. : 5(b) Date: BINARY SEARCH Aim: To write a Python Program to perform binary search. Algorithm: 1.Read the search element 2.Find the middle element in the sorted list 3.Compare the search element with the middle element i. if both are matching, print element found ii. else then check if the search element is smaller or larger than the middle element 4.If the search element is smaller than the middle element, then repeat steps 2 and 3 for the left sublist of the middle element 5.If the search element is larger than the middle element, then repeat steps 2 and 3 for the right sublist of the middle element 6.Repeat the process until the search element if found in the list 7.If element is not found, loop terminates

Mr.B.Mohanraj AP CSE MIT

Page 15

PagePage 1515

Program:

def binary_sort(sortedlist,n,x):

start = 0 end = n - 1 while(start <= end):

mid = (start + end)/2 if (x == sortedlist[mid]):

return mid elif(x < sortedlist[mid]):

end = mid - 1 else:

start = mid + 1

return -1

n = input("Enter the size of the list: ")

sortedlist = [] for i in range(n):

sortedlist.append(input("Enter %dth element: "%i))

x = input("Enter the number to search: ")

position = binary_sort(sortedlist, n, x) if(position != -1):

print("Entered number %d is present at position: %d"%(x,position))

else:

print("Entered number %d is not present in the list"%x)

Mr.B.Mohanraj AP CSE MIT

Page 16

PagePage 1616

Output:

Enter the size of the list: 5

Enter 0th element: 34

Enter 1th element: 24

Enter 2th element: 14

Enter 3th element: 06

Enter 4th element: 02

Enter the number to search: 14

Entered number 14 is present at position: 2

Result:

Thus the Python Program to perform binary search is executed successfully and the output is verified

Mr.B.Mohanraj AP CSE MIT

Page 17

PagePage 1717

 Ex. No. : 6(a) Date: SELECTION SORT Aim: To write a Python Program to perform selection sort. Algorithm: 1. Create a function named selectionsort 2. Initialise pos=0 3. If alist[location]>alist[pos] then perform the following till i+1, 4. Set pos=location 5. Swap alist[i] and alist[pos] 6. Print the sorted list Program: def selectionSort(alist): for i in range(len(alist)-1,0,-1): pos=0 for location in range(1,i+1): if alist[location]>alist[pos]: pos= location temp = alist[i] alist[i] = alist[pos] alist[pos] = temp alist = [54,26,93,17,77,31,44,55,20] selectionSort(alist) print(alist)

Mr.B.Mohanraj AP CSE MIT

Page 18

PagePage 1818

Output:

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Result:

Thus the Python Program to output is verified.

perform selection sort is successfully executed and the

Mr.B.Mohanraj AP CSE MIT

Page 19

PagePage 1919

 Ex. No. : 6(b) Date: INSERTION SORT Aim: To write a Python Program to perform insertion sort. Algorithm: 1. Create a function named insertionsort 2. Initialise currentvalue=alist[index] and position=index 3. while position>0 and alist[position-1]>currentvalue, perform the following till len(alist) 4. alist[position]=alist[position-1] 5. position = position-1 6. alist[position]=currentvalue 7. Print the sorted list Program: def insertsort(sample): print("intial sample:", sample) for i in range(1, len(sample)): print(sample) j=i while(j!=0 and sample[j] < sample[j-1]): sample[j-1], sample[j] = sample[j], sample[j-1] j=j-1 print("sorted list:",sample) sample1 = [12,300,-90,-100-1000,1,4] insertsort(sample1)

Mr.B.Mohanraj AP CSE MIT

Page 20

PagePage 2020

Output:

('intial sample:', [12, 300, -90, -1100, 1, 4])

[12, 300, -90, -1100, 1, 4]

[12, 300, -90, -1100, 1, 4]

[-90, 12, 300, -1100, 1, 4]

[-1100, -90, 12, 300, 1, 4]

[-1100, -90, 1, 12, 300, 4]

('sorted list:', [-1100, -90, 1, 4, 12, 300]

Result:

Thus the Python program to perform insertion sort is successfully executed and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 21

PagePage 2121

Ex. No. : 7 Date:

MERGE SORT

Aim:

To write a Python Program to perform Merge sort.

Algorithm:

1. Create a function named mergesort

2. Find the mid of the list

3. Assign lefthalf = alist[:mid] and righthalf = alist[mid:]

4. Initialise i=j=k=0

5. while i < len(lefthalf) and j < len(righthalf), perform the following if lefthalf[i] < righthalf[j]:

alist[k]=lefthalf[i]

Increment i else alist[k]=righthalf[j] Increment j Increment k

6. while i < len(lefthalf),perform the following

alist[k]=lefthalf[i]

Increment i

Increment k

7. while j < len(righthalf), perform the following alist[k]=righthalf[j] Increment j Increment k

8. Print the sorted list

Mr.B.Mohanraj AP CSE MIT

Page 22

PagePage 2222

Program:

def merge(left,right):

result = [] i,j = 0, 0 while i<len(left) and j<len(right):

if left[i] <= right[j]:

result.append(left[i])

i+=1

else:

result.append(right[j])

j+=1

result += left[i:]

result += right[j:]

return result def mergesort(lst):

if(len(lst) <= 1):

return lst mid = int(len(lst)/2) left = mergesort(lst[:mid]) right = mergesort(lst[mid:]) return merge(left,right) arr = [1,2,-1,0,9,65,7,3,4,1,2] print(mergesort(arr))

Mr.B.Mohanraj AP CSE MIT

Page 23

PagePage 2323

Output:

[-1, 0, 1, 1, 2, 2, 3, 4, 7, 9, 65]

Result:

Thus the Python program to perform merge sort is successfully executed and the output is

verifie

Mr.B.Mohanraj AP CSE MIT

Page 24

PagePage 2424

Ex. No. : 8 Date:

FIRST N PRIME NUMBERS

Aim:

To write a Python program to find first n prime numbers.

Algorithm:

1. Read the value of n

2. for num in range(0,n + 1), perform the following

3. if num%i is 0 then break

else print the value of num

4. Repeat step 3 for i in range(2,num)

Program:

n=int(input("Enter the upper iimit;"))

print("Prime number are")

for num in range(0,n+1):

# prime number are greater than 1 if num>1:

for i in range(2,num):

if (num%i)==0:

else:

break

print(num)

Mr.B.Mohanraj AP CSE MIT

Page 25

PagePage 2525 Output:
Enter the upper limit:100
Prime numbers are
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Result:
Thus the Python Program to find the first n prime numbers is executed successfully and
the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 26

PagePage 2626

Ex. No. : 9 Date:

MATRIX MULTIPLICATION

Aim:

To write a Python program to multiply matrices. Algorithm:

1. Define two matrices X and Y

2. Create a resultant matrix named result

3. for i in range(len(X)):

i. for j in range(len(Y)):

a) for k in range(len(Y))

b) result[i][j] += X[i][k] * Y[k][j]

4. for r in result, print the value of r

`Program:

X = [[12,7,3], [4 ,5,6],[7 ,8,9]]

Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]]

result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]]

for i in range(len(X)):

for j in range(len(Y)):

for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

Mr.B.Mohanraj AP CSE MIT

Page 27

PagePage 2727

Output:

[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]

Result:

Thus the Python program to multiply matrices is executed successfully and the output is

verified.

Mr.B.Mohanraj AP CSE MIT

Page 28

PagePage 2828

 Ex. No. :10 Date: COMMAND LINE ARGUMENTS(WORD COUNT) Aim: To write a Python program for command line arguments. Algorithm: 1. Add arguments to find the words and lines 2. Add the filename as argument 3. Parse the arguments to get the values 4. Format and print the words and lines Program: parser=argparse.ArgumentParser() parser.add_argument('--words','-w',action='store_true') parser.add_argument('--lines','-l',action='store_true') parser.add_argument('filename') args=parser.parse_args() if args.words: print("words {}".format(print_words(args.filename)) elif args.lines: print("lines {}".format(print_lines(args.filename)) else: print ("words {}".format(print_words(args.filename)) print("lines {}".format(print_lines(args.filename))

Mr.B.Mohanraj AP CSE MIT

Page 29

PagePage 2929

Output:

python main.py i input.txt words 23 lines 1

Result:

Thus the Python program for command line arguments is executed successfully and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 30

PagePage 3030

 Ex. No. : 11 Date: FINDING MOST FREQUENT WORDS IN A TEXT READ FROM A FILE Aim: To write a Python program to find the most frequent words in a text read from a file. Algorithm: 1. Read the filename 2. Open the file in read mode 3. Read each line from the file to count the lowers and words 4. Read each line from the file to replace the punctuations 5. Split each line into words and count them 6. Print the words and counts Program: def main(): filename=raw_input("enter the file").strip() infile=open(filename,"r") wordcounts={} for line in infile: processLine(line.lower(),wordcounts) pairs=list(wordcounts.items()) items=[[x,y] for (y,x) in pairs] items.sort() for i in range(len(items)-1,len(items)-11,-1): print(items[i]+"\t"+str(items[i])) def processLine(line,wordcounts): line=replacePunctuations(line) words=line.split() for word in words: if word in wordcounts: wordcounts[word]+=1 else: wordcounts[word]=1 def replacePunctuations(line): for ch in line: if ch in "~@#\$%^&*()_-+=<>?/.,:;!{}[]''": line=line.replace(ch," ") return line main()

Mr.B.Mohanraj AP CSE MIT

Page 31

PagePage 3131 Output:
Enter a filename:a.txt
Hi
1
How
1
Are
1
You
1
Result:
Thus the Python program to find the most frequent words in a text read from a file is
executed successfully and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 32

PagePage 3232

 Ex. No. : 12 Date: SIMULATE ELLIPTICAL ORBITS IN PYGAME Aim: To write a Python program to simulate elliptical orbits in Pygame. Algorithm: 1. Import the required packages 2. Set up the colours for the elliptical orbits 3. Define the parameters to simulate elliptical orbits 4. Display the created orbits Program: import math import random import pygame class Particle (): def init (self, x, y, colour=0x000000): self.x = x self.y = y self.vx = 0 self.vy = 0 self.colour = colour def apply_gravity (self, target): dsqd = (self.x - target.x) ** 2 + (self.y - target.y) ** 2 #g = G*m/dsqd * normalized (self - target) if dsqd == 0: return self.vx += -1 / dsqd * (self.x - target.x) / dsqd ** 0.5 self.vy += -1 / dsqd * (self.y - target.y) / dsqd ** 0.5 def update (self): self.x += self.vx self.y += self.vy pygame.init() window = pygame.display.set_mode ((600, 400)) main_surface = pygame.Surface ((600, 400)) colours = [0x000000, 0x111111, 0x222222, 0x333333, 0x444444, 0x555555, 0x666666, 0x777777, 0x888888, 0x999999, 0xaaaaaa, 0xbbbbbb] + [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x888888, 0xFFFFFF, 0x808000, 0x008080, 0x800080, 0x800000] #colours = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x888888,

Mr.B.Mohanraj AP CSE MIT

Page 33

PagePage 3333

0xFFFFFF, 0x808000, 0x008080, 0x800080, 0x800000] particles = [Particle (200, 100, colours [i]) for i in range (20)] earth = Particle (200, 200) for i, p in enumerate (particles):

p.vx = i / 100 while (True):

# main_surface.fill(0x000000) pygame.draw.circle (main_surface, 0x00FF00, (earth.x, earth.y), 5, 2)

for p in particles:

p.apply_gravity (earth) p.update () pygame.draw.circle (main_surface, p.colour, (int (p.x), int (p.y)), 5, 2) window.blit(main_surface, (0, 0)) pygame.display.flip()

Mr.B.Mohanraj AP CSE MIT

Page 34

PagePage 3434

Output: Result:

Thus the Python Program to simulate elliptical orbits using Pygame is executed successfully and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 35

PagePage 3535

 Ex. No. : 13 Date: SIMULATE BOUNCING BALL USING PYGAME Aim: To write a Python program to bouncing ball in Pygame. Algorithm: 1. Import the required packages 2. Define the required variables 3. Define the screen space to display the bouncing balls in that space Program: import sys import pygame pygame.init() size = width, height = 320, 240 speed = [2, 2] black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load('C:\\Users\\admin\\Desktop//ball.jpg') ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed = -speed if ballrect.top < 0 or ballrect.bottom > height: speed = -speed screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip()

Mr.B.Mohanraj AP CSE MIT

Page 36

PagePage 3636

Output: Result:

Thus the Python Program to simulate bouncing ball using Pygame is executed successfully and the output is verified.

Mr.B.Mohanraj AP CSE MIT

Page 37

PagePage 3737

VIVAVOCE QUESTIONS:

1. What it the syntax of print function?

2. What is the usage of input function?

3. Define a variable.

4. What is type conversion?

5. Mention the data types in Python

6. What are the attributes of the complex datatype?

7. Mention a few escape sequences.

8. Define an expression

9. What is the usage of ** operator in Python?

10. Give the syntax of if else statement.

11. Give the syntax of for statement.

12. How is range function used in for?

13. Give the syntax of while statement.

14. What are multi way if statements?

15. How is random numbers generated?

16. Define a function.

17. Give the syntax of function.

18. What are the types of arguments in function.?

19. What is a recursive function?

20. What are anonymous functions?

21. What are default arguments?

22. What are variable length arguments?

23. What are keyword arguments?

24. Mention the use of map().

25. Mention the use of filter().

26. Mention the use of reduce().

27. Define a string.

28. How is string slicing done?

29. What is the usage of repetition operator?

30. How is string concatenation done using + operator>

31. Mention some string methods

32. How is length of a string found?

33. How is a string converted to its upper case?

34. `Differentiate isalpha() and isdigit().

35. What is the use of split()?

36. Define a file.

37. Give the syntax for opening a file.

38. Give the syntax for closing a file.

39. How is reading of file done?

40. How is writing of file done?

41. What is a list?

42. Lists are mutable-Justify.

43. How is a list created?

44. How can a list be sorted?

45. How are elements appended to the list?

46. How is insert() used in list?

Mr.B.Mohanraj AP CSE MIT

Page 38

PagePage 3838

47. What is the usage of pop() in list?

48. Define a tuple.

49. Are tuples mutable or immutable?

50. Mention the use of return statement.

51. What is a Boolean function?

52. How is main function defined?

53. What is a dictionary?

54. How are tuples created?

55. How is a dictionary created?

56. How to print the keys of a dictionary?

57. How to print the values of a dictionary?

58. How is del statement used?

59. Can tuple elements be deleted?

60. What is Python interpreter?

61. Why is Python called an interpreted language?

62. Mention some features of Python

63. What is Python IDLE?

64. Mention some rules for naming an identifier in Python.

65. Give points about Python Numbers.

66. What is bool datatype?

67. Give examples of mathematical functions.

68. What is string formatting operator?

69. Mention about membership operators inPython.

70. How is expression evaluated in Python?

71. What are the loop control statements in Python?

72. What is the use of break statement?

73. What is the use of continue statement?

74. What is the use of pass statement?

75. What is assert statement?

76. Differentiate fruitful function s and void functions.

77. What are required arguments ?

78. Differentiate pass by value and pass by reference.

79. Mention few advantages of function.

80. How is lambda function used?

81. What is a local variable?

82. What are global variables?

83. What are Python decorators?

84. Are strings mutable or immutable?

85. What is join()?

86. What is replace() method?

87. What is list comprehension?

88. Define multidimensional list.

89. How to create lists using range()?

90. What is swapcase() method?

91. What is linear search?

92. How is binary search done?

Mr.B.Mohanraj AP CSE MIT

Page 39

PagePage 3939

93. How is merge sort performed?

94. What is sorting?

95. How is insertion sort done?

96. How is selection sort done?

97. What are command line arguments?

98. Name some built in functions with dictionary.

99. What is an exception?

100. How is exception handled in python?

Mr.B.Mohanraj AP CSE MIT

Page 40

1. What do you know about python?

Python is a high-level programming language

Python is

interpreted

interactive

object-oriented scripting language

2. What makes Python differ from other programming languages?

In python English keywords are used frequently whereas punctuation is used

in other languages, and it has fewer syntactical constructions than other

languages.

3. Python is interpreted and interactive. How?

Python is processed at runtime by the interpreter. It does not need

compilation before execution. It is interactive as one can actually sit at a

Python prompt.

4. What is the use of Python?

It is used in GIS programming and as a scripting language (for ArcGIS, and Quantum GIS). Python is true general purpose language.

5. What is a board standard library of python?

A board standard library: Python’s bulk of the library is cross-platform compatible on Windows, UNIX, and Macintosh. It is portable.

Mr.B.Mohanraj AP CSE MIT

Page 41

6. What makes python portable?

Python can run on a wide variety of h-platforms and has the same interface for every platform.

7. How does it manage the memory?

A combination of a cycle-detecting garbage collector and reference counting and dynamic typing is used for memory management. Its memory is managed by its private heap space. All objects and data structures are placed in a private heap. The programmer is not allowed to access the heap but interpreter takes care of this private heap.

8. What is pickling and unpickling?

Pickle is a module which accepts any Python object. Converts this object into

a string and dumps it into a file by using dump function, this is called pickling.

While retrieving its original objects from the stored string is called

unpickling.

9. How are arguments passed?

In Python everything is an object and its variables hold references to the objects. The references values are assigned according to the functions; as a result the value of the references cannot be changed. However, mutable objects can do so.

10. What is python namespace?

It is like any box where a name of variable is mapped to the object being placed. To get corresponding object the box is searched every time when the variable is searched out.

Mr.B.Mohanraj AP CSE MIT

Page 42

11. What is PYTHONSTARTUP environment variable?

A variable which contains the path of an initialization file which contains Python source code, is executed whenever the interpreter is started and is named as .pythonrc.py in Unix and contains commands that modify PYTHONPATH or load utilities.

12. Is python a case sensitive language?

Yes!.

13. What are the supported data types in Python?

There are Immutable and mutable types of Pythons built in types.

Immutable:

Strings

Tuples

Numbers

Mutable:

List

Sets

Dictionaries

14. What are tuples in Python?

Mr.B.Mohanraj AP CSE MIT

Page 43

 A tuple is any other sequence data type which is similar to the list and consists of a number of values separated by commas, enclosed within parentheses.

15. What is the difference between tuples and lists in Python?

List is belongs to mutable type while tuple belongs to immutable types. Tuple can be hashed for e.g. as a key for dictionaries.

Brackets ( [ ] ) are used for enclosing list while parentheses ( ( ) ) are used to enclose tuples.

Elements and size of lists can be changed, while tuples be update and can be

16. What are python dictionaries?

It is kind of hash table type. Working process is just like associative arrays or

Perl hashes and consist of key-value pairs. A dictionary key can be of any

Python type, but are numbers or strings usually. On the other hand, values

can be any arbitrary Python object.

17. What is pass in Python?

Pass means, no-operation Python statement. It is used when a one does not want any command or code to execute but is required syntactically. The pass statement is a null operation; nothing will happens when it gets executed. It is useful in those places where the code will eventually go, but nothing has been written yet

18. What is the output of print str * 2 if str = ‘Hello!’?

It will print string two times. Output would be Hello!Hello!.

Mr.B.Mohanraj AP CSE MIT

Page 44

19. How will you convert an object to a string in python?

str(x) − object x is converted to a string representation.

20. How will you convert a string to a set in python?

set(s) − s is converted to a set.

21. What is the purpose of is operator?

is − Evaluates to true if the variables on both sides of the operator are pointing to the same object and false otherwise. y is x, here is results in 1 if id(y) equals id(x).

22. How can you get a random number in python?

random() − it returns a random float r, such that 0 <= r and r <1.

23. How will you check in a string that it contains all digits?

isdigit() − it returns true if string contains only digits else false.

24. How will you merge elements in a sequence?

join(seq) − concatenates the string representations of elements in seq sequence with separator string, into a string.

25. How will you reverse a list?

list.reverse() − reverses list objects.

Mr.B.Mohanraj AP CSE MIT

Page 45

26. What is the output of print tuple [1:3] if tuple = ( ‘ahjd’, 786 , 2.23, ‘sean’,

70.2 )?

It will print elements starting from 2nd to3rd. Output is (786, 2.23).

27. What is PYTHONHOME environment variable?

It is an alternative module search path, embedded usually in the PYTHONSTARTUP or PYTHONPATH directories making switching

module libraries easy.

28. What are python regular expressions?

It is a special sequence of characters that helps in matching or finding sets of

strings or other strings held in a pattern using a specialized syntax. These are

used widely in the world of UNIX.

29. What is the difference between Xrange and range?

Range returns the list and the same memory is used no matter what the range size is.

Xrange returns the xrange object

30. What is module and package in Python?

Mr.B.Mohanraj AP CSE MIT

Page 46

Module is the way program is structured. Each program file is a module, in which other modules like objects and attributes can be imported. The folder

of program is a package of modules like in other programming languages. A

package can have subfolders or modules.

31. What do you know about unittest?

A unit testing framework of python is called unittest. It supports automation

testing, sharing of setups, aggregation of tests into collections, shutdown code for tests, etc.

32. Given a function that does not return any value, when executed in shell

what value is thrown by it by default?

NoneType object is thrown back by python shell.

33. Which core datatype is used for the storage of values in terms of key and

value?

Dictionary stores values in terms of values and keys.

34. What is the order of precedence in python?

Parentheses, exponential, division, multiplication, addition and subtraction.

35. What is the maximum possible length of an identifier?

Identifiers can be of any length.

36. Why are local variable names beginning with an underscore discouraged?

Mr.B.Mohanraj AP CSE MIT

Page 47

Leading underscores are used to indicate variables as Python has no concept of private variables that must not be accessed from outside the class.

37. What is the output of the following?

print(”’

”’.isspace())

True, a newline character is considered as space.

38. How many except statements can a try-except block have?

More than zero, there has to be at least one except statement.

39. Which module in the python standard library is used for parsing options

received from the command line?getopt is used for parsing options received from the command line.

40. What is returned by math.ceil() function?

The ceil function returns the smallest integer >= to the number itself.

41. Is the function abs() same as math.fabs()?

Mr.B.Mohanraj AP CSE MIT

Page 48

The return type of function abs() is determined by the type of value which is passed to it whereas math.fabs() always returns a float and does not work with complex numbers

42. What does os.name contain?

It contains operating system dependent module name imported such as

‘posix’, ‘java’ etc.

43. What List nd Dict comprehensions are?

Syntax constructions based on existing iterable to ease the creation of a

Dictionary or List.

44. Define iterators.

To iterate a group of “containers” or “elements”.

45. Define generators.

A generator is simply a function that returns an object on which you can call

next until it raises a StopIteration exception, such that for every call it returns some value, signaling that all values have been generated.

46. Define slicing.

A process of selecting a range of items from sequence types like tuple, strings,

list etc. is called as slicing.

Mr.B.Mohanraj AP CSE MIT

Page 49

47. What is the output of print list + nlist * 2 if list = [ 'ajhd', 786 , 2.97, 'sean',

70.2 ] and nlist = [123, 'sean']?

It will print concatenated lists. Output would be ['ajhd', 786, 2.97, 'sean', 70.200000000000003, 123, 'sean'].

48. How will you get all the keys from the dictionary?

dictionary.keys() function does the work here, all the keys from the dictionary object can be retrieved by using it.

print dict.keys()

# Prints all the keys

49. How will you convert an object to a regular expression in python?

repr(x) − object x is converted to an expression string.

50. What is the purpose of // operator?

// represents floor division which corresponds to the division of operands

where the result is the quotient such that after the decimal point are removed.

Mr.B.Mohanraj AP CSE MIT