CBSE COMPUTER SCIENCE
Ir al canal en Telegram
QUESTION BANK, REFERENCE BOOK, LAB MANUAL , WORKSHEET ETC., PYTHON TEXT BOOK AND REFERENCE BOOKS, 01. ASK QUESTIONS AT https://t.me/joinchat/FJ1noGs-64I0OWI1
Mostrar más549
Suscriptores
Sin datos24 horas
Sin datos7 días
Sin datos30 días
Archivo de publicaciones
#List Operation Test : SET-1
A=[10,'35','BCD',39.25]
B=['AZL','99',79.25,39,25]
C=['LMN',79.25,76,'JKM',39]
#Membership Operator [in / not in]
I=input('Enter any value : ')
if I in A:
print(I,'is exist in this list')
else:
print(I,'not exist in this list')
if I not in A:
print(I,'Not exist...')
else:
print(I,'Exist...')
# Repetition (Replication) [ * ]
print('Replication of A \n',A*2)
# Concatenation (Appending) [ + ]
print('Concatenation of A and B :\n',A+B)
#Slicing [::]
print(A[:3:2])
print(A[:-3:-2])
print(A[::-2])
print(A[-1:5:3])
print(A[5:-1:-2])
print(A[:-1:-1])
'''
#OUTPUT
Enter any value : 10
10 not exist in this list
10 Not exist...
Replication of A
[10, '35', 'BCD', 39.25, 10, '35', 'BCD', 39.25]
Concatenation of A and B :
[10, '35', 'BCD', 39.25, 'AZL', '99', 79.25, 39, 25]
[10, 'BCD']
[39.25]
[39.25, '35']
[39.25]
[]
[]'''
#List Operation Test : SET-2
A=[10,'35','BCD',39.25]
B=['AZL','99',79.25,39,25]
C=['LMN',79.25,76,'JKM',39]
#Membership Operator [in / not in]
I=input('Enter any value : ')
if I in B:
print(I,'is exist in this list')
else:
print(I,'not exist in this list')
if I not in B:
print(I,'Not exist...')
else:
print(I,'Exist...')
# Repetition (Replication) [ * ]
print('Replication of B \n',B*2)
# Concatenation (Appending) [ + ]
print('Concatenation of B and C :\n',B+C)
#Slicing [::]
print(B[:3:2])
print(B[:-3:-2])
print(B[::-2])
print(B[-1:5:3])
print(B[5:-1:-2])
print(B[:-1:-1])
'''
#OUTPUT
Enter any value : 10
10 not exist in this list
10 Not exist...
Replication of B
['AZL', '99', 79.25, 39, 25, 'AZL', '99', 79.25, 39, 25]
Concatenation of B and C :
['AZL', '99', 79.25, 39, 25, 'LMN', 79.25, 76, 'JKM', 39]
['AZL', 79.25]
[25]
[25, 79.25, 'AZL']
[25]
[]
[]'''
#List Operation Test : SET-2
A=[10,'35','BCD',39.25]
B=['AZL','99',79.25,39,25]
C=['LMN',79.25,76,'JKM',39]
#Membership Operator [in / not in]
I=input('Enter any value : ')
if I in C:
print(I,'is exist in this list')
else:
print(I,'not exist in this list')
if I not in C:
print(I,'Not exist...')
else:
print(I,'Exist...')
# Repetition (Replication) [ * ]
print('Replication of C \n',C*2)
# Concatenation (Appending) [ + ]
print('Concatenation of B and C :\n',C+A)
#Slicing [::]
print(C[:3:2])
print(C[:-3:-2])
print(C[::-2])
print(C[-1:5:3])
print(C[5:-1:-2])
print(C[:-1:-1])
'''
#OUTPUT
Enter any value : 10
10 not exist in this list
10 Not exist...
Replication of C
['LMN', 79.25, 76, 'JKM', 39, 'LMN', 79.25, 76, 'JKM', 39]
Concatenation of B and C :
['LMN', 79.25, 76, 'JKM', 39, 10, '35', 'BCD', 39.25]
['LMN', 76]
[39]
[39, 76, 'LMN']
[39]
[]
[]'''
Answers:
1. Files
2. open()
3. read ('r'), write ('w'), append ('a')
4. writelines()
5. close()
6. getcwd()
7. rename()
8. remove()
9. binary
10. with
11. (beginning)
12. dump(), load()
13. end of file (EOF)
14. read(n)
15. flush()
16. CSV
17. seek()
18. dump()
19. load()
20. import csv
21. join()
22. line_num
23. readlines()
24. writelines()
25. flush()
26. read
27. file mode
28. text, binary
29. file handle
30. r+
31. w+ or a+
32. close()
33. readlines()
34. writelines()
35. flush()
1. _____ in Python are interpreted as a sequence or stream of bytes stored on some storage media.
2. The _____ function creates a file object used to call other support methods associated with it.
3. Files in Python can be opened in one of the three modes - _____, _____ and _____.
4. The _____ method writes a list of strings to a file.
5. The _____ method of a file object flushes any unwritten information and closes the file object.
6. The name of the current working directory can be determined using _____ method.
7. The_____ method is used to rename the file or folder.
8. The _____ method is used to remove/delete a file.
9. A _____ file is a series of 1's and 0's, treated as raw data and read byte-by-byte.
10. The _____ statement automatically closes the file after the processing on the file gets over.
11. The read() function reads data from the _____ of a file.
12. The pickle module produces two main methods called _____ and ____ for writing and reading operations.
13. The readlines() returns a list of lines from the file till _____.
14. The _____ method reads 'n' characters from the file.
15. _____ function is used to force transfer of data from buffer to file.
16. _____ format is a text format accessible to all applications across several platforms.
17. _____ method is used for random access of data in a CSV file.
18. _____ method of pickle module is used to write an object into binary file.
19. _____ method of pickle module is used to read data from a binary file.
20. _____ statement is given for importing csv module into your program.
21. _____ is a string method that joins all values of each row with comma separator in CSV.
22. _____ object contains the number of the current line in a CSV file.
23. To end all the file contents in the form of a list, _____ method may be used.
24. To read all the file contents, _____ method is used.
25. To force Python to write the contents of file buffer on to storage file, _____ method may be used.
26. The default file-open mode is _____ mode.
27. A _____ governs the type of operations (e.g., read/write/append) possible in the opened file.
28. The two types of data files can be _____ files and _____ files.
29. The other name for file object is _____.
30. The _____ file mode will open a file for read and write purpose.
31. The _____ file mode will open a file for write and read purpose.
32. To close an open file, _____ method is used.
33. To read all the file contents in form of a list, ______ method is used.
34. To write a list in a file, _____ method may be used.
35. To force Python to write the contents of file buffer on to storage file, _____ method may be used.
Answers:
1. b
2. b
3. a
4. d
5. a
6. b
7. a
8. c
9. d
10. d
11. c
12. c
13. d
14. c
15. a
16. b
17. a
18. b
19. b
20. c
21. a
22. b
23. d
24. d
25. c
26. c
27. b, d
28. a, c
29. c
30. d
31. b
32. d
33. a
34. a
35. a
36. a
37. b
38. a
39. b
40. b
(a) file position is set to the start of file
(b) file position is set to the end of file
(c) file position remains unchanged
(d) results in an error
24. Which of the following modes will refer to binary data?
(a) r
(b) w
(c) +
(d) b
25. Every record in a CSV file is stored in reader object in the form of a list using which method?
(a) writer()
(b) append()
(c) reader()
(d) list()
26. Information stored on a storage device with a specific name is called a _____.
(a) array
(b) dictionary
(c) file
(d) tuple
27. Which of the following format of files can be created programmatically through Python to some data?
(a) Data files
(b) Text files
(c) Video files
(d) Binary files
28. To open a file c:\ss.txt for appending data, we use
(a) file = open("c:\\ss.txt", "a")
(b) file = open("c:\\ss.txt", "rw")
(c) file = open(r"c\ss.txt", "a")
(d) file = open(file = "c:\ss.txt", "w")
(e) file = open(file = "c\\ss.txt", "w")
(f) file = open("c\ res.txt")
29. To read the next line of the file from a file object infi, we use
(a) infi.read(all)
(b) infi.read()
(c) infi.readline()
(d) infi.readlines()
30. To read the remaining lines of the file from a file object infi, we use
(a) infi.read(all)
(b) infi.read()
(c) infi.readline()
(d) infi.readlines()
31. The readlines() method returns
(a) str
(b) a list of lines
(c) a list of single characters
(d) a list of integers
32. Which of the following mode will refer to binary data?
(a) r
(b) w
(c) +
(d) b
33. In file handling, what does this term means "r, a"?
(a) read, append
(b) append, read
(c) all of the mentioned
(d) none of these
34. Which function is used to read all the characters?
(a) read()
(b) read characters()
(c) readall()
(d) readchar()
35. Which function is used to read single line from file?
(a) readline()
(b) readlines()
(c) readstatement( )
(d) readfulline()
36. Which function is used to write all the characters?
(a) write()
(b) writecharacters()
(c) writeall()
(d) writechar()
37. Which function is used to write a list of strings in a file?
(a) writeline()
(b) writelines()
(c) writestatement()
(d) writefullline()
38. Which of the following is modes of both writing and reading in binary format in file?
(a) wb+
(b) w
(c) wb
(d) w+
39. Which of the following is not a valid mode to open a file?
(a) ab
(b) rw
(c) r+
(d) w+
40. What is the difference between r+ and w+ modes?
(a) No difference.
(b) In r+ mode, the pointer is initially placed at the beginning of the file and for w+, the pointer is placed at the end.
(c) In w+ mode, the pointer is initially placed at the beginning of the file and for r+, the pointer is placed at the end.
(d) Depends on the operating system.
1. To open a file c:\test.txt for reading, we should give the statement:
(a) filel = open("c:\ test.txt", "r")
(b) file1 = open("c:\\ test.txt", "r")
(c) file = open(file = "c:\ test.txt", "r")
(d) file1 = open(file = "c:\\s test.txt", "r")
2. To open a file c:\ test.txt for writing, we should use the statement:
(a) fobj = open("c:\test.txt", "w")
(b) fobj = open("c:\\ test.txt", "w")
(c) fobj = open(file = "c:\ test.txt", "w")
(d) fobj = open(file = "c:\\ test.txt", "w")
3. To open a file c:\ test.txt for appending data, we can give the statement:
(a) fobj = open("c:\\ test.txt", "a")
(b) fobj = open("c:\\ test.txt", "rw")
(c) fobj = open(file = "c:\test.txt", "w")
(d) fobj = open(file = "c:\\ test.txt", "w")
4. Which of the following statements is/are true?
(a) When you open a file for reading, if the file does not exist, an error occurs.
(b) When you open a file for writing, if the file does not exist, a new file is created.
(c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file.
(d) All of the above.
5. To read two characters from a file object from, the command should be:
(a) fobj.read(2)
(b) fobj.read()
(c) fobj.readline()
(d) fobj.readlines()
6. To read the entire contents of the file as a string from a file object fobj, the command should be:
(a) fobj.read(2)
(b) fobj.read()
(c) fobj.readline()
(d) fobj.readlines()
7. What will be the output of the following snippet?
f = None
for i in range (5):
with open ("data.txt", "W") as f:
if i > 2:
break
print (f.closed)
(a) True
(b) False
(c) None
(d) Error
8. To read the next line of the file from a file object fobj, we use:
(a) fobj.read(2)
(b) fobj.read()
(c) fobj.readline()
(d) fobj.readlines()
9. To read the remaining lines of the file from a file object fobj, we use:
(a) fobj.read(2)
(b) fobj.read()
(c) fobj.readline()
(d) fobj.readlines
10. The readlines() method returns:
(a) String
(b) A list of integers
(c) A list of single characters
(d) A list of lines
11. Which module is required to use the built-in function dump( )?
(a) math
(b) flush
(c) pickle
(d) unpickle
12. Which of the following functions is used to write data in the binary mode?
(a) write
(b) output
(c) dump
(d) send
13. Which is/are the basic I/O (input-output) stream(s) in file?
(a) Standard Input
(b) Standard Output
(c) Standard Errors
(d) All of the above
14. Which of the following is the correct syntax of file.writelines()?
(a) file.writelines(sequence)
(b) fobj.writelines()
(c) fobj.writelines(sequence)
(d) fobj.writeline()
15. In file handling, what do the terms "r" and "a" stand for?
(a) read, append
(b) append, read
(iii) write, append
(d) None of the above
16. Which of the following is not a valid mode to open a file?
(a) ab
(b) rw
(c) r+
(d) w+
17. Which statement is used to change the file position to an offset value from the start?
(a) fp.seek(offset, 0)
(b) fp.seek(offset, 1)
(c) fp.seek(offset, 2)
(d) None of the above
18. The difference between r+ and w+ modes is expressed as?
(a) No difference
(b) In r+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the end for w+
(c) In w+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the end for r+
(d) Depends on the operating system
19. What does CSV stand for?
(a) Cursor Separated Variables
(b) Comma Separated Values
(c) Cursor Separated Values
(d) Cursor Separated Version
20. Which module is used for working with CSV files in Python?
(a) random
(b) statistics
(c) csv
(d) math
21. Which of the following modes is used for both writing and reading from a binary file?
(a) wb+
(b) w
(c) wb
(d) w+
22. Which statement is used to retrieve the current position within the file?
(a) fp.seek()
(b) fp.tell()
(c) fp.loc
(d) fp.pos
23. What happens if no arguments are passed to the seek() method?
found = False
position = -1
while start <= end:
if Lst[mid] == num:
found = True
position = mid
print('Number %d found at position %d'%(num, position+1))
break
if num > Lst[mid]:
start = mid + 1
mid = (start + end) // 2
else:
end = mid - 1
mid = (start + end) // 2
if found==False:
print('Number %d not found' %num)
# DRIVER CODE
def main():
print ("SEARCH MENU")
print ("1. LINEAR SERACH")
print ("2. BINARY SEARCH")
print ("3. EXIT")
choice=int(input("Enter your Choice [ 1 - 3 ]: "))
arr = [12, 34, 54, 2, 3]
n = len(arr)
if choice==1:
print("The List contains : ",arr)
num=int(input("Enter number to be searched: "))
index = Linear_Search(arr,num)
if choice==2:
arr = [2, 3,12,34,54] #Sorted Array
print("The List contains : ",arr)
num=int(input("Enter number to be searched: "))
result = binary_Search(arr,num)
main()
#Driver Code
def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()
24. Write a program to implement a queue using a list data structure.
Download
# Function to check Queue is empty or not
def isEmpty(qLst):
if len(qLst)==0:
return 1
else:
return 0
# Function to add elements in Queue
def Enqueue(qLst,val):
qLst.append(val)
if len(qLst)==1:
front=rear=0
else:
rear=len(qLst)-1
# Function to Delete elements in Queue
def Dqueue(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
val = qLst.pop(0)
if len(qLst)==0:
front=rear=None
return val
# Function to Display top element of Queue
def Peek(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
front=0
return qLst[front]
# Function to Display elements of Queue
def Display(qLst):
if isEmpty(qLst):
print("No Item to Dispay in Queue....")
else:
tp = len(qLst)-1
print("[FRONT]",end=' ')
front = 0
i = front
rear = len(qLst)-1
while(i<=rear):
print(qLst[i],'<-',end=' ')
i += 1
print()
# Driver function
def main():
qList = []
front = rear = 0
while True:
print()
print("##### QUEUE OPERATION #####")
print("1. ENQUEUE ")
print("2. DEQUEUE ")
print("3. PEEK ")
print("4. DISPLAY ")
print("0. EXIT ")
choice = int(input("Enter Your Choice: "))
if choice == 1:
ele = int(input("Enter element to insert"))
Enqueue(qList,ele)
elif choice == 2:
val = Dqueue(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("\n Deleted Element was : ",val)
elif choice==3:
val = Peek(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("Item at Front: ",val)
elif choice==4:
Display(qList)
elif choice==0:
print("Good Luck......")
break
main()
25. Write a python program to implement searching methods based on user choice using a list data-structure. (linear & binary)
Download
#Linear Search Function Definition
def Linear_Search( lst, srchItem):
found= False
for i in range(len(lst)):
if lst[i] == srchItem:
found = True
print(srchItem, ' was found in the list at index ', i)
break
if found == False:
print(srchItem, ' was not found in the list!')
#Binary Search Definition
def binary_Search(Lst,num):
start = 0
end = len(Lst) - 1
mid = (start + end) // 2
# We took found as False that is, initially
# we are considering that the given number
# is not present in the list unless proven
s1 = float(input("Enter side1 of triangle: "))
s2 = float(input("Enter side2 of triangle: "))
area = Area.triangle(s1,s2)
print("The Area of TriRectangle is:",area)
s = float(input("Enter side of square: "))
area =Area.square(s)
print("The Area of square is:",area)
num1 = float(input("\nEnter First number :"))
num2 = float(input("\nEnter second number :"))
print("\nThe Sum is : ",Calculator.sum(num1,num2))
print("\nThe Multiplication is : ",Calculator.mult(num1,num2))
print("\nThe sub is : ",Calculator.sub(num1,num2))
print("\nThe Division is : ",Calculator.div(num1,num2))
main()
21. Write a python program to implement sorting techniques based on user choice using a list data-structure. (bubble/insertion)
Download
#BUBBLE SORT FUNCTION
def Bubble_Sort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp
#INSERTION SORT FUNCTION
def Insertion_Sort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
# DRIVER CODE
def main():
print ("SORT MENU")
print ("1. BUBBLE SORT")
print ("2. INSERTION SORT")
print ("3. EXIT")
choice=int(input("Enter your Choice [ 1 - 3 ]: "))
nlist = [14,46,43,27,57,41,45,21,70]
if choice==1:
print("Before Sorting: ",nlist)
Bubble_Sort(nlist)
print("After Bubble Sort: ",nlist)
elif choice==2:
print("Before Sorting: ",nlist)
Insertion_Sort(nlist)
print("After Insertion Sort: ",nlist)
else:
print("Quitting.....!")
main()
22. Take a sample of ten phishing e-mails (or any text file) and find the most commonly occurring word(s).
Download
def Read_Email_File():
import collections
fin = open('email.txt','r')
a= fin.read()
d={ }
L=a.lower().split()
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count
n = int(input("How many most common words to print: "))
print("\nOK. The {} most common words are as follows\n".format(n))
word_counter = collections.Counter(d)
for word, count in word_counter.most_common(n):
print(word, ": ", count)
fin.close()
#Driver Code
def main():
Read_Email_File()
main()
23. Write a python program to implement a stack using a list data-structure.
Download
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be update: "))
Modify(r)
else:
break
main()
16. Remove all the lines that contain the character `a' in a file and write it to another file
Download
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())
17. Write a program to perform read and write operation onto a student.csv file having fields as roll number, name, stream and percentage.
Download
import csv
with open('Student_Details.csv','w',newline='') as csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details file..")
choice=input("Want add more record(y/n).....")
with open('Student_Details.csv','r',newline='') as fileobject:
readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)
18. Program to search the record of a particular student from CSV file on the basis of inputted name.
Download
import csv
#input Roll number you want to search
number = input('Enter number to find: ')
found=0
#read csv, and split on "," the line
with open('Student_Details.csv') as f:
csv_file = csv.reader(f, delimiter=",")
#loop through csv list
for row in csv_file:
#if current rows index value (here 0) is equal to input, print that row
if number ==row[0]:
print (row)
found=1
else:
found=0
if found==1:
pass
else:
print("Record Not found")
19. Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
Download
import random
import random
def roll_dice():
print (random.randint(1, 6))
print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.""")
flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
20. Write a program to create a library in python and import it in a program.
Download
#Let's create a package named Mypackage, using the following steps:
#• Create a new folder named NewApp in D drive (D:\NewApp)
#• Inside NewApp, create a subfolder with the name 'Mypackage'.
#• Create an empty __init__.py file in the Mypackage folder
#• Create modules Area.py and Calculator.py in Mypackage folder with following code
# Area.py Module
import math
def rectangle(s1,s2):
area = s1*s2
return area
def circle(r):
area= math.pi*r*r
return area
def square(s1):
area = s1*s1
return area
def triangle(s1,s2):
area=0.5*s1*s2
return area
# Calculator.py Module
def sum(n1,n2):
s = n1 + n2
return s
def sub(n1,n2):
r = n1 - n2
return r
def mult(n1,n2):
m = n1*n1
return m
def div(n1,n2):
d=n1/n2
return d
# main() function
from Mypackage import Area
from Mypackage import Calculator
def main():
r = float(input("Enter Radius: "))
area =Area.circle(r)
print("The Area of Circle is:",area)
s1 = float(input("Enter side1 of rectangle: "))
s2 = float(input("Enter side2 of rectangle: "))
area = Area.rectangle(s1,s2)
print("The Area of Rectangle is:",area)
def Writerecord(sroll,sname):
with open ('StudentRecord1.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)
def SearchRecord(roll):
with open ('StudentRecord1.dat','rb') as Myfile:
while True:
try:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
except EOFError:
print("Record not find..............")
print("Try Again..............")
break
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Search Records (By Roll No)')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r=int(input("Enter a Rollno to be Search: "))
SearchRecord(r)
else:
break
main()
15. Create a binary file with roll number, name and marks. Input a roll number and update details.
Download
def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)
def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")
newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0
if found==0:
print("Record not found")
with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)
num = int(input("Enter how many number :"))
for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
mylst.append(n) #Adding number to list
sum = lstSum(myl
st,len(mylst))
print("Sum of List items ",mylst, " is :",sum)
9. Write a recursive code to compute the nth Fibonacci number.
Download
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return(fibonacci(n-2) + fibonacci(n-1))
nterms = int(input("Please enter the Range Number: "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i),end=' ')
10.Read a text file line by line and display each word separated by a #.
Download
filein = open("Mydoc.txt",'r')
line =" "
while line:
line = filein.readline()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()
'''
#-------------OR------------------
filein = open("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()
'''
11. Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase characters and other than character and digit in the file.
Download
filein = open("Mydoc1.txt",'r')
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if ch.isupper():
count_up +=1
if ch.islower():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
count_digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
count_other += 1
print("Digits",count_digit)
print("Vowels: ",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)
filein.close()
12. Write a Python code to find the size of the file in bytes, the number of lines, number of words and no. of character.
Download
import os
lines = 0
words = 0
letters = 0
filesize = 0
for line in open("Mydoc.txt"):
lines += 1
letters += len(line)
# get the size of file
filesize = os.path.getsize("Mydoc.txt")
# A flag that signals the location outside the word.
pos = 'out'
for letter in line:
if letter != ' ' and pos == 'out':
words += 1
pos = 'in'
elif letter == ' ':
pos = 'out'
print("Size of File is",filesize,'bytes')
print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)
13. Write a program that accepts a filename of a text file and reports the file's longest line.
Download
def get_longest_line(filename):
large_line = ''
large_line_len = 0
with open(filename, 'r') as f:
for line in f:
if len(line) > large_line_len:
large_line_len = len(line)
large_line = line
return large_line
filename = input('Enter text file Name: ')
print (get_longest_line(filename+".txt"))
14. Create a binary file with the name and roll number. Search for a given roll number and display the name, if not found display appropriate message.
Download
import pickle
Write a Program to show whether entered numbers are prime or not in the given range.
Download
lower=int(input("Enter lowest number as lower bound to check : "))
upper=int(input("Enter highest number as upper bound to check: "))
c=0
for i in range(lower, upper+1):
if (i == 1):
continue
# flag variable to tell if i is prime or not
flag = 1
for j in range(2, i // 2 + 1):
if (i % j == 0):
flag = 0
break
# flag = 1 means i is prime
# and flag = 0 means i is not prime
if (flag == 1):
print(i, end = " ")
2. Input a string and determine whether it is a palindrome or not.
Download
string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(string,'is not a palindrome.')
3. Find the largest/smallest number in a list/tuple
Download
# creating empty list
list1 = []
# asking number of elements to put in list
num = int(input("Enter number of elements in list: "))
# iterating till num to append elements in list
for i in range(1, num + 1):
ele= int(input("Enter elements: "))
list1.append(ele)
# print maximum element
print("Largest element is:", max(list1))
# print minimum element
print("Smallest element is:", min(list1))
4. WAP to input any two tuples and swap their values.
Download
t1 = tuple()
n = int (input("Total no of values in First tuple: "))
for i in range(n):
a = input("Enter Elements : ")
t1 = t1 + (a,)
t2 = tuple()
m = int (input("Total no of values in Second tuple: "))
for i in range(m):
a = input("Enter Elements : ")
t2 = t2 + (a,)
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
t1,t2 = t2, t1
print("After Swapping: ")
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
5. WAP to store students’ details like admission number, roll number, name and percentage in a dictionary and display information on the basis of admission number.
Download
record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i = i + 1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")
6. Write a program with a user-defined function with string as a parameter which replaces all vowels in the string with ‘*’.
Download
def strep(str):
# convert string into list
str_lst =list(str)
# Iterate list
for i in range(len(str_lst)):
# Each Character Check with Vowels
if str_lst[i] in 'aeiouAEIOU':
# Replace ith position vowel with'*'
str_lst[i]='*'
#to join the characters into a new string.
new_str = "".join(str_lst)
return new_str
def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
7. Recursively find the factorial of a natural number.
Download
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def main():
n = int(input("Enter any number: "))
print("The factorial of given number is: ",factorial(n))
main()
8. Write a recursive code to find the sum of all elements of a list.
Download
def lstSum(lst,n):
if n==0:
return 0
else:
return lst[n-1]+lstSum(lst,n-1)
mylst = [] # Empty List
#Loop to input in list
Class XI Computer Science Notes
Basics of Computer Organization
Types of Software
Boolean Logic
Number System
Problem Solving
Getting Started with Python
Basics of Python programming
Data Types
Debugging
Flow of Control
Strings
List
Tuples
Dictionary
Python Modules
Society, Law and Ethics 1
Society, Law and Ethics 2
Class XI Informatics Practices Notes
Computer System
Computer Memory
Software
Getting Started with Python
Basics of Python Programming
Data Types and Debugging
Control Statements
Lists
Dictionary
DBMS
SQL
Emerging Trends
Class XII Computer Science Notes
Revision of the basics of python
Function
File Handling
Data Structure
Network and Network Types
Network Protocols
Web Services
Database Concepts
SQL
Interface Python with SQL database
Class XII Informatics Practices Notes
Python Pandas
Data Visualization
SQL Functions
Database query using sql group by, Operations on relation
Computer Network
Internet and WWW
Website Concepts
Web Browsers
Societal Impacts 1
Societal Impacts 2
Important Data Structure MCQ for Class 12
1. ___________________ is a way to represent data in memory.
a) Data Handling
b) Data Structure
c) Data Dumping
d) Data Collection
2. Python built-in data structures are
a) integer,float,string
b) list,tuple,dictionary,sets
c) math,pyplot
d) All of the above
3. Data structure can be of two type’s namely___________
a) Simple and Compound
b) Simple and Nested
c) Sequential and random
d) All of the above
4. Array or linear list comes under the category of______
a) Simple Data Structure
b) Compound Data Structure
c) random
d) None of these
5. Compound Data structure can be ______ & _______
a) Sequential and random
b) Simple & Nested
c) Linear & Non Linear
d) Simple and Linear
6. The examples of Linear Data Structures are
a) Stacks, Queues, Linked list
b) int, float, complex
c) Operators, tokens, punctuators
d) All of the above
7. Stacks follows____________ order
a) FIFO (First In First Out )
b) LIFO (Last In First Out)
c) Random
d) All of the above
8. Queue follows____________ order
a) FIFO (First In First Out )
b) LIFO (Last In First Out)
c) Random
d) None of the above
9. Main Operations in Stacks are called
a) Insertion and deletion
b) append and insertion
c) Push and Pop
d) append and deletion
10. Main Operations in Queue are called
a) Insertion and deletion
b) append and insertion
c) Push and Pop
d) append and deletion
11. In Stack Insertion and deletion of an element is done at single end called ________
a) Start
b) Last
c) Top
d) Bottom
12. In stack we cannot insert an element in between the elements that are already inserted.
a) True
b) False
13. The process of visiting each element in any Data structure is termed as ____________
a) Visiting
b) Searching
c) Traversing
d) Movement
14. While implementing Stack using list when we want to delete element we must use pop function as__________
a) list.pop(pos)
b) list.pop(0)
c) list.pop()
d) list.push()
15. Arranging elements of a data structure in increasing or decreasing order is known as_________
a) Searching
b) Arrangement
c) Sorting
d) Indexing
16. Searching of any element in a data structure can be done in 2 ways _________ and ________
a) Sequential and random
b) linear and non linear
c) linear and binary
d) sequential and binary
17. _________ is an example of nonlinear data structure
a) Stack
b) Queue
c) Sorting
d) Tree
18. In a stack, if a user tries to remove an element from empty stack it is called _________
a) Underflow
b) Empty
c) Overflow
d) Garbage Collection
19. What is the value of the postfix expression 6 3 2 4 + – *
a) 1
b) 40
c) 74
d) -18
20. If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a time, in what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
21. Which of the following data structure is linear type?
a) Stack
b) Array
c) Queue
d) All of the above
22. The postfix form of the expression (A+ B)*(C*D- E)*F / G is?
a) AB + CDE * – * F *G /
b) AB+ CD*E – FG /**
c) AB + CD* E – F **G /
d) AB + CD* E – *F *G /
23. The postfix form of A*B+C/D is?
a) *AB/CD+
b) AB*CD/+
c) A*BC+/D
d) ABCD+/*
24. Which of the following statement(s) about stack data structure is/are NOT correct?
a) Stack data structure can be implemented using linked list
b) New node can only be added at the top of the stack
c) Stack is the FIFO data structure
d) The last node at the bottom of the stack has a NULL link
