· 8 years ago · Apr 03, 2018, 10:20 AM
1http://www.vitskill.com/search/label/Inlab
2
3files read,write,append:
4
5class py:
6a=10
7def __init__(self):
8print "welcome"
9def fun(self):
10f=open('temp.txt','w')
11self.m=raw_input("enter text:")
12f.write(self.m)
13f.close()
14def read(self):
15f=open('temp.txt','r')
16self.m=f.read()
17print self.m
18f.close()
19def app(self):
20f=open('temp.txt','a')
21self.s=raw_input("text:")
22f.write('\n'+self.s)
23f.close()
24ob=py()
25ob.fun()
26i=int(input("0:close, 1:enter text into file"))
27if i==1:
28ob.app()
29ob.read()
30else:
31ob.read()
32
33---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
34
35print "*****TELEPHONE DIRECTORY***"
36list1=[]
37list2=[]
38dict1={}
39temp=100
40n=input("Enter the number of contacts : ")
41for i in range(0,n):
42name1=raw_input("Enter your name: ")
43num=input("Enter your phone number: ")
44list1.extend([name1])
45list2.extend([num])
46dict1=dict(zip(list1,list2))#to convert two list into dictionary
47print dict1
48print """
491:Add a contact
502:Search a contact
513:Delete a contact
524:Update a contact
535:View directory
546:Exit"""
55choice=input("Enter your choice")
56def add(dict1):
57name3=raw_input("Enter the new name you want to add: ")
58num3=input("Enter the number: ")
59dict1[name3]=num3
60print dict1
61def search(dict1,n,list1,temp):
62name2=raw_input("Enter the name whose number is to be found: ")
63for i in range(0,n):
64if list1[i]==name2:
65temp=i
66if temp!=100:
67print "Number is : ",list2[temp]
68def delete(dict1):
69name4=raw_input("Enter the name you want to delete: ")
70del dict1[name4]
71print dict1
72def update(dict1,n,list1):
73name5=raw_input("Enter the name which you want to update: ")
74for i in range(0,n):
75if list1[i]==name5:
76temp=i
77if temp!=100:
78num5=input("Enter the new number")
79dict1[name5]=num5
80print dict1
81def view(dict1):
82print dict1
83if (choice==1):
84add(dict1)
85elif (choice==2):
86search(dict1,n,list1,temp)
87elif (choice==3):
88delete(dict1)
89elif (choice==4):
90update(dict1,n,list1)
91else:
92view(dict1)
93
94--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
95
96Library books binary search:-
97
98def bsearch(n_list,num):
99low = 0
100high = len(n_list) - 1
101while low!=high-1:
102mid = (low+high)//2
103if n_list[mid] == num:
104return 'Found'
105elif n_list[mid] > num:
106high = mid
107elif n_list[mid] < num:
108low = mid
109else:
110if n_list[low] == num or n_list[high]==num:
111return 'Found'
112else:
113return 'Not Found'
114n_list = []
115n = int(input())
116for i in range(n):
117temp_list = []
118for j in range(5):
119if j == 3:
120accession_num = int(input())
121n_list.append(accession_num)
122else:
123temp_list.append(input().rstrip())
124num_search = int(input())
125n_list.sort()
126print(bsearch(n_list,num_search))
127
128------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
129
130In FFCS students portal, the Register number, name, age, gender, address, phone number, hobby, blood group are stored.:-
131
132def read_print():
133ffcs = open('ffcs.csv')
134for i in ffcs.readlines():
135print(i,end='')
136ffcs.close()
137
138def append_new():
139temp = []
140ffcs = open('ffcs.csv','a')
141for i in range(8):
142input_text = input().rstrip()
143temp.append(input_text)
144temp = ','.join(temp)
145ffcs.write('\n')
146ffcs.write(temp)
147ffcs.close()
148read_print()
149
150def check_append():
151temp = []
152flag = True
153ffcs = open('ffcs.csv','r+')
154for i in range(8):
155input_text = input().rstrip()
156if i == 0 and input_text in ffcs.read():
157flag = False
158temp.append(input_text)
159temp = ','.join(temp)
160if flag == True:
161ffcs.write('\n')
162ffcs.write(temp)
163ffcs.close()
164if flag == True:
165read_print()
166
167def football_kerala():
168count = 0
169ffcs = open('ffcs.csv')
170for i in ffcs.readlines():
171if 'Kerala' in i and 'Football' in i:
172temp = i.split(',')
173if temp[3] == 'M':
174count+=1
175ffcs.close()
176print(count,sep='')
177
178def tamil_b_grp():
179ffcs = open('ffcs.csv')
180for i in ffcs.readlines():
181if 'A+' in i and 'Tamilnadu' in i:
182temp = i.split(',')
183if temp[3] == 'F':
184data = i.split(',')
185print(data[1],data[-3],sep=' ')
186ffcs.close()
187
188read_print()
189append_new()
190check_append()
191football_kerala()
192tamil_b_grp()
193
194---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
195
196Given ‘n’ integers, write an algorithm and the subsequent Python code to print all numbers that are sum-equivalent to the first number.
197
198def sum_digit(number):
199total = 0
200count = 0
201temp = number
202while number:
203total += number%10
204number = number//10
205count += 1
206return temp,count,total
207n = int(input())
208sum_list = []
209for i in range(n):
210number = int(input())
211sum_list.append(sum_digit(number))
212count = 0
213for i in range(1,n):
214if sum_list[0][1] == sum_list[i][1] and sum_list[0][2] == sum_list[i][2]:
215if count == 0:
216print(sum_list[0][0])
217print(sum_list[i][0])
218count += 1
219if count == 0:
220print('No sum-equivalent')
221
222----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
223
224A team of experts formed by Govt. of India conducted a survey on colleges in India. Let us assume that the survey was conducted in ‘n’ number of institutes.
225
226number_institutes = int(input())
227facility_scores = []
228academics_scores = []
229infra_scores = []
230total_scores = []
231flag = True
232for i in range(number_institutes):
233facility_s = int(input())
234acad_s = int(input())
235infra_s = int(input())
236if facility_s >= 0 and facility_s = 0 and acad_s = 0 and infra_s facility_scores.append(facility_s)
237academics_scores.append(acad_s)
238infra_scores.append(infra_s)
239total_scores.append(facility_s + acad_s + infra_s)
240else:
241flag = False
242if flag == True:
243total_scores.sort(reverse=True)
244print(total_scores)
245else:
246print('Invalid Input')
247
248-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
249
250Government of India has appointed two separate teams with three members each for investigating a case.
251
252from pprint import pprint
253group1, group2 = {},{}
254for i in range(6):
255name = input().rstrip()
256experience = int(input())
257if i < 3:
258group1[experience] = name
259else:
260group2[experience] = name
261final_group = {}
262for i in group1.keys():
263final_group[i] = group1[i]
264for i in group2.keys():
265final_group[i] = group2[i]
266for i in sorted(final_group.keys()):
267del final_group[i]
268break
269chairman = max(final_group.keys())
270new_mem = input()
271if new_mem in final_group.values():
272print('Exist')
273else:
274print('Does not Exist')
275pprint(final_group)
276print(final_group[chairman])
277
278-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
279
280regular expression:
281import re
282n=input("enter:")
283if re.match('^[a-zA-z]+@+[a-zA-Z]+.+[a-z]{2,4}$',n):
284print("matched")
285else:
286print("nope")
287
288---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
289
290Write a Python program to read first n lines of a file.
291Sample Solution:-
292Python Code:
293def file_read_from_head(fname, nlines):
294from itertools import islice
295with open(fname) as f:
296for line in islice(f, nlines):
297print(line)
298file_read_from_head('test.txt',2)
299Write a Python program to append text to a file and display the text.
300Sample Solution:-
301Python Code:
302def file_read(fname):
303from itertools import islice
304with open(fname, "w") as myfile:
305myfile.write("Python Exercises\n")
306myfile.write("Java Exercises")
307txt = open(fname)
308print(txt.read())
309file_read('abc.txt')
310Write a Python program to read last n lines of a file.
311Sample Solution:-
312Python Code:
313import sys
314import os
315def file_read_from_tail(fname,lines):
316bufsize = 8192
317fsize = os.stat(fname).st_size
318iter = 0
319with open(fname) as f:
320if bufsize > fsize:
321bufsize = fsize-1
322data = []
323while True:
324iter +=1
325f.seek(fsize-bufsize*iter)
326data.extend(f.readlines())
327if len(data) >= lines or f.tell() == 0:
328print(''.join(data[-lines:]))
329break
330
331file_read_from_tail('test.txt',2)
332Write a Python program to read a file line by line and store it into a list.
333Sample Solution:-
334Python Code:
335def file_read(fname):
336with open(fname) as f:
337#Content_list is the list that contains the read lines.
338content_list = f.readlines()
339print(content_list)
340
341file_read(\'test.txt\')
342Write a Python program to read a file line by line store it into a variable.
343Sample Solution:-
344Python Code:
345def file_read(fname):
346with open (fname, "r") as myfile:
347data=myfile.readlines()
348print(data)
349file_read('test.txt')
350Write a Python program to read a file line by line store it into an array.
351Sample Solution:-
352Python Code:
353
354def file_read(fname):
355content_array = []
356with open(fname) as f:
357#Content_list is the list that contains the read lines.
358for line in f:
359content_array.append(line)
360print(content_array)
361
362file_read('test.txt')
363Write a python program to find the longest words.
364Sample Solution:-
365Python Code:
366def longest_word(filename):
367with open(filename, 'r') as infile:
368words = infile.read().split()
369max_len = len(max(words, key=len))
370return [word for word in words if len(word) == max_len]
371
372print(longest_word('test.txt'))
373Write a Python program to count the number of lines in a text file.
374
375Sample Solution:-
376Python Code:
377def file_lengthy(fname):
378with open(fname) as f:
379for i, l in enumerate(f):
380pass
381return i + 1
382print("Number of lines in the file: ",file_lengthy("test.txt"))
383Write a Python program to count the frequency of words in a file.
384Sample Solution:-
385Python Code:
386from collections import Counter
387def word_count(fname):
388with open(fname) as f:
389return Counter(f.read().split())
390
391print("Number of words in the file :",word_count("test.txt"))
392
393Write a Python program to get the file size of a plain file.
394Sample Solution:-
395Python Code:
396def file_size(fname):
397import os
398statinfo = os.stat(fname)
399return statinfo.st_size
400
401print("File size in bytes of a plain file: ",file_size("test.txt"))
402Write a Python program to write a list content to a file.
403Sample Solution:-
404Python Code:
405color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
406with open('abc.txt', "w") as myfile:
407for c in color:
408myfile.write("%s\n" % c)
409
410content = open('abc.txt')
411print(content.read())
412Write a Python program to copy the contents of a file to another file .
413Sample Solution:-
414Python Code:
415from shutil import copyfile
416copyfile('test.py', 'abc.py')
417Write a Python program to combine each line from first file with the corresponding line in second file.
418Sample Solution:-
419Python Code:
420with open('abc.txt') as fh1, open('test.txt') as fh2:
421for line1, line2 in zip(fh1, fh2):
422# line1 from abc.txt, line2 from test.txtg
423print(line1+line2)
424Write a Python program to read a random line from a file.
425Sample Solution:-
426Python Code:
427import random
428def random_line(fname):
429lines = open(fname).read().splitlines()
430return random.choice(lines)
431print(random_line('test.txt'))
432Write a Python program to remove newline characters from a file.
433
434def remove_newlines(fname):
435flist = open(fname).readlines()
436return [s.rstrip('\n') for s in flist]
437
438print(remove_newlines("test.txt"))
439
440Sample Solution:-
441Python Code:
442
443from tkinter import *
444
445master = Tk()
446Label(master, text="REG NO").grid(row=0)
447Label(master, text="FIRST Name").grid(row=1)
448Label(master, text="Last Name").grid(row=2)
449Label(master, text="CGPA ").grid(row=3)
450Label(master, text="YEAR").grid(row=4)
451e1 = Entry(master)
452e2 = Entry(master)
453e3 = Entry(master)
454e4 = Entry(master)
455e5 = Entry(master)
456e1.grid(row=0, column=1)
457e2.grid(row=1, column=1)
458e3.grid(row=2, column=1)
459e4.grid(row=3, column=1)
460e5.grid(row=4, column=1)
461
462Button(master, text='SUBMIT', command=show_entry_fields).grid(row=6, column=1, sticky=W, pady=4)
463Button(master, text='RETRIEVE', command=retrieve).grid(row=7, column=1, sticky=W, pady=4)
464
465mainloop( )
466
467FORM DB
468
469from tkinter import *
470import sqlite3
471
472def show_entry_fields():
473connection=sqlite3.connect("reg.db")
474cursor=connection.cursorA()
475cursor.execute("""DROP TABLE student;""")
476sql_c="""
477CREATE TABLE student (
478regno VARCHAR(20),
479fname VARCHAR(20),
480lname VARCHAR(20),
481cgpa number,
482year number);"""
483cursor.execute(sql_c)
484f="""INSERT INTO student(regno,fname,lname,cgpa,year)VALUES ("{a}","{b}","{c}","{d}","{e}");"""
485sql_c=f.format(a=e1.get(),b=e2.get(),c=e3.get(),d=e4.get(),e=e5.get())
486cursor.execute(sql_c)
487cursor.execute("SELECT * FROM student")
488print("fetchall:")
489result=cursor.fetchall()
490for r in result:
491print(r)
492def retrieve():
493m1=Tk()
494a=e1.get()
495b=e2.get()
496c=e3.get()
497d=e4.get()
498e=e5.get()
499Label(m1,text=a).grid(row=0)
500Label(m1,text=b).grid(row=1)
501Label(m1,text=c).grid(row=2)
502Label(m1,text=d).grid(row=3)
503Label(m1,text=e).grid(row=4)
504mainloop( )
505master = Tk()
506Label(master, text="REG NO").grid(row=0)
507Label(master, text="FIRST Name").grid(row=1)
508Label(master, text="Last Name").grid(row=2)
509Label(master, text="CGPA ").grid(row=3)
510Label(master, text="YEAR").grid(row=4)
511e1 = Entry(master)
512e2 = Entry(master)
513e3 = Entry(master)
514e4 = Entry(master)
515e5 = Entry(master)
516e1.grid(row=0, column=1)
517e2.grid(row=1, column=1)
518e3.grid(row=2, column=1)
519e4.grid(row=3, column=1)
520e5.grid(row=4, column=1)
521
522Button(master, text='SUBMIT', command=show_entry_fields).grid(row=6, column=1, sticky=W, pady=4)
523Button(master, text='RETRIEVE', command=retrieve).grid(row=7, column=1, sticky=W, pady=4)
524
525mainloop( )
526
527-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
528
529class py:
530 a=10
531 def __init__(self):
532 print "welcome"
533 def fun(self):
534 f=open('temp.txt','w')
535 self.m=raw_input("enter text:")
536 f.write(self.m)
537 f.close()
538 def read(self):
539 f=open('temp.txt','r')
540 self.m=f.read()
541 print self.m
542 f.close()
543 def app(self):
544 f=open('temp.txt','a')
545 self.s=raw_input("text:")
546 f.write('\n'+self.s)
547 f.close()
548ob=py()
549ob.fun()
550i=int(input("0:close, 1:enter text into file"))
551if i==1:
552 ob.app()
553 ob.read()
554else:
555 ob.read()
556------------------------------------------------------------------------------------------------------
557(Tkinter Form example)
558
559from tkinter import Tk, N, S, W, E, BOTH, Text, Frame,Label, Button,Checkbutton, IntVar,Entry
560
561
562class Example(Frame):
563
564 def __init__(self, parent):
565 Frame.__init__(self, parent)
566 self.parent = parent
567 self.initUI()
568
569 def initUI(self):
570 self.parent.title("Windows")
571
572
573 Label(text="Contact List").grid(row=0,column=0,columnspan=2)
574 Text(width=30,height=15).grid(row=1,rowspan=9, column=0,columnspan=2,padx=20)
575 Button(text="Display Contact").grid(row=10, column=0,columnspan=2,pady=10)
576 Label(text="Last Name:").grid(row=11, column=0,pady=10)
577 Entry().grid(row=11,column=1)
578 Button(text="Search").grid(row=12,column=0,columnspan=2)
579
580
581
582 Label(text="New Contact").grid(row=0,column=2,columnspan=2)
583 Label(text="First Name:").grid(row=1,column=2,sticky=E)
584 Entry().grid(row=1,column=3)
585 Label(text="Last Name:").grid(row=2,column=2,sticky=E)
586 Entry().grid(row=2,column=3)
587 Label(text="Phone #:").grid(row=3,column=2,sticky=E)
588 Entry().grid(row=3,column=3)
589 friend_check = IntVar()
590 Checkbutton(variable=friend_check, command = self.friend_box, text = "Friend").grid(row=4,column=3,sticky=W)
591 #Label(text="Friend").grid(row=4,column=3,padx=20,sticky=W)
592 Label(text="Email:").grid(row=5,column=2,sticky=E)
593 Entry().grid(row=5,column=3)
594 Label(text="Birthday:").grid(row=6,column=2,sticky=E)
595 Entry().grid(row=6,column=3)
596 Button(text="Add Contact").grid(row=7,column=3,sticky=E)
597
598 def friend_box(self):
599 if friend_check.get() == 1:
600 print ('1')
601 else:
602 print ('0')
603
604
605def main():
606
607 root = Tk()
608 root.geometry("600x450+900+300")
609 root.resizable(0,0)
610 app = Example(root)
611 root.mainloop()
612
613
614if __name__ == '__main__':
615 main()
616--------------------------------------------------------------------------------------------------------------------------------
617A Student in a class is appreciated based on the following factors:
618Number of 'S' grade in the subjects learnt >= 3
619Percentage of Attendance >= 90
620Participation in sports activity in a semester >= 2
621Appreciation is given as follows:
622(i) 'Excellent' if all three conditions are met
623(ii)'Very Good' if conditions (i) and (ii) are met
624(iii)'Good' if conditions (i) and (iii) are met
625Given the Number of 'S' grades, Attendance and Participation in sports activity in a semester, write an algorithm and the subsequent 'C' program to output the appreciation for the student.
626Input Format:
627First line contains the number of 'S' grade
628Next line contains the percentage of Attendance of the student
629Next line contains the number participation in sports activity by the student in the current semester
630Output Format:
631
632Print the Appreciation for the student
633
634Program:
635#include
636
637void main()
638{
639int s_grade, attendance, sports;
640scanf("%d%d%d", &s_grade, &attendance, &sports);
641if (s_grade >= 3 && attendance >= 90 && sports >= 2)
642printf("Excellent");
643else if (s_grade >= 3 && attendance >= 90)
644printf("Very good");
645else if (s_grade >= 3 && sports >= 2)
646printf("Good");
647}
648
649Algorithm:
650Step1. get the number of s grades, attendance in the subjects and the number of sports activities that the person participated in.
651Step2. if the inputs satisfy the all the criteria then display excellent.
652Step3. if the inputs satisfy criteria i,ii then display very good.
653Step4. if the inputs satisfy criteria i,iii then display good.
654Step5. End
655at November 01, 2017 No comments: Links to this post
656Email This
657BlogThis!
658Share to Twitter
659Share to Facebook
660Share to Pinterest
661
662Labels: C programming, Inlab
663Inlab 10
664INLAB 10
665A barcode scanner for Universal Product Codes (UPCs) verifies the 12-digit code scanned by comparing the code’s last digit (called as check digit) to its own computation of the check digit from the first 11 digits as follows:
666Calculate the sum of the digits in the odd-numbered positions (the first, third, …, eleventh digits) and multiply this sum by 3.
667Calculate the sum of the digits in the even-numbered positions (the second, fourth, …, tenth digits) and add this to the previous result, to get dig_Sum.
668If the last digit of the result from step 2 is 0, then the check digit is 0. Otherwise, check digit is obtained by subtracting last digit of dig_Sum from 10 (10 - last digit of dig_Sum).
669Develop an algorithm and write a C program to read the barcode, if the number of digits is not 12 then print “Cannot be processed†and terminate program. Otherwise calculate the check digit, and compare it to the last barcode digit.
670If the digits match, output the barcode with the message “Validatedâ€. If not, output the barcode with the message “Error in barcode.†For example the barcode code 079400804501, the result from step 2 is 79 (0 + 9+ 0 + 8 + 4 + 0) * 3 + (7 + 4+ 0 + 0 + 5). Since the last digit is 9, check digit is 10 -9 = 1 and this matches the last digit of USD therefore print ‘Validated’.
671Input format
672Barcode
673Output
674If number of digits is not 12, then print “Cannot be processedâ€
675If check digit matches the last digit of USD then print the message “Validatedâ€
676If not, output the barcode with the message “Error in barcode.â€
677
678Program:
679#include
680#include
681int main()
682{
683char UGC[13];
684scanf("%s",&UGC);
685if(strlen(UGC) ==12)
686{
687int sum = 0;
688for(int i = 0;i<11;i+=2)
689sum += (UGC[i] - '0');
690sum *= 3;
691for(int i = 1;i<11;i+=2)
692sum += (UGC[i] - '0');
693if ((UGC[11] == '0') && ((sum%10)==0))
694printf("Validated");
695else if ((UGC[11]-'0') == (10-(sum%10)))
696printf("Validated");
697else
698printf("Error in barcode");
699}
700else
701printf("Cannot be processed");
702return 0;
703}
704
705at October 29, 2017 No comments: Links to this post
706Email This
707BlogThis!
708Share to Twitter
709Share to Facebook
710Share to Pinterest
711
712Labels: C programming, Inlab
713INLAB 8
714In FFCS students portal, the Register number, name, age, gender, address, phone number, hobby, blood group are stored. Assume that the details are present in a file named as 'ffcs.csv' and each field of a record are separated by a ‘,’. Write an algorithm to achieve the following and implement it using functions in Python:
715a) Read and print the content of the file
716b) Get a new record with the fields mentioned in order and append the file
717c) Get a new record with the fields mentioned in order and append to file if the record is new and do nothing otherwise. Register number shall be used for checking if a record is new.
718d) Find the number of male football players from Kerala
719e) List the name and phone numbers of girls from Tamilnadu having A+ blood group
720Write functions for the purpose of items (a) to (e) and call those functions defined in the order from (a) to (e).
721
722Input Format
723For items (b) and (c), read a record from the user.
724Details of each student are given in the order - Register number, name, age, gender, address, phone number, hobby, blood group
725No input is given for other items
726
727Output Format
728Output of item (a) – print the content of the file with each field of record separated by a comma.
729
730Print content of file after doing operations (b) and (c), with each field of a record separated by a comma.
731
732Program:
733def read_print():
734ffcs = open('ffcs.csv')
735for i in ffcs.readlines():
736print(i,end='')
737ffcs.close()
738
739def append_new():
740temp = []
741ffcs = open('ffcs.csv','a')
742for i in range(8):
743input_text = input().rstrip()
744temp.append(input_text)
745temp = ','.join(temp)
746ffcs.write('\n')
747ffcs.write(temp)
748ffcs.close()
749read_print()
750
751def check_append():
752temp = []
753flag = True
754ffcs = open('ffcs.csv','r+')
755for i in range(8):
756input_text = input().rstrip()
757if i == 0 and input_text in ffcs.read():
758flag = False
759temp.append(input_text)
760temp = ','.join(temp)
761if flag == True:
762ffcs.write('\n')
763ffcs.write(temp)
764ffcs.close()
765if flag == True:
766read_print()
767
768def football_kerala():
769count = 0
770ffcs = open('ffcs.csv')
771for i in ffcs.readlines():
772if 'Kerala' in i and 'Football' in i:
773temp = i.split(',')
774if temp[3] == 'M':
775count+=1
776ffcs.close()
777print(count,sep='')
778
779def tamil_b_grp():
780ffcs = open('ffcs.csv')
781for i in ffcs.readlines():
782if 'A+' in i and 'Tamilnadu' in i:
783temp = i.split(',')
784if temp[3] == 'F':
785data = i.split(',')
786print(data[1],data[-3],sep=' ')
787ffcs.close()
788
789read_print()
790append_new()
791check_append()
792football_kerala()
793tamil_b_grp()
794
795Algorithm:
796Step1. define the function read_print() which reads the contents of the file and display the contents
797Step2. get the required data from the user and then append the data into ffcs.csv using the append_new
798Step3. append data that is not present in the file using check_append function
799Step4. define the function football_kerala that display people from Kerala who play Football and use the function to count and display the number people
800Step5. define tamil_b_grp that displays the name and number of students whose blood group is A+ and are from Tamilnadu
801Step6. call all the functions in the respective order.
802Step7.End
803
804at October 10, 2017 10 comments: Links to this post
805Email This
806BlogThis!
807Share to Twitter
808Share to Facebook
809Share to Pinterest
810
811Labels: Inlab, Python
812Inlab 7
813In a small village library, books are lended to the members for a period of one week. Details such as name of the book, author, date of purchase, accession number and availability status are stored for each book. Given the details of the 'n' books sorted by the accession number of book and an accession number to search, develop an algorithm and write the Python code to perform binary search in the given data. Print 'Found' or 'Not Found' appropriately.
814Input Format
815First line contains the number of books in the library, n
816Next n*5 lines contains the details of the book in the following order:
817name of the book
818author of the book
819date of purchase of the book
820accession number of the book
821availability status of the book
822Next line contains the accession number of book to be searched 'n'
823Output Format
824Print Found or Not Found
825
826Program:
827def bsearch(n_list,num):
828low = 0
829high = len(n_list) - 1
830while low!=high-1:
831mid = (low+high)//2
832if n_list[mid] == num:
833return 'Found'
834elif n_list[mid] > num:
835high = mid
836elif n_list[mid] < num:
837low = mid
838else:
839if n_list[low] == num or n_list[high]==num:
840return 'Found'
841else:
842return 'Not Found'
843n_list = []
844n = int(input())
845for i in range(n):
846temp_list = []
847for j in range(5):
848if j == 3:
849accession_num = int(input())
850n_list.append(accession_num)
851else:
852temp_list.append(input().rstrip())
853num_search = int(input())
854n_list.sort()
855print(bsearch(n_list,num_search))
856
857Algorithm:
858Step1. define bsearch function with two parameters n_list and num
859Step1.1 assign low as 0,high as the length of the list minus one and mid as one
860Step1.2 repeat till low is not equal to mid
861Step1.2.1 check if the num entered is equal to the middle element in the list if so then print found else if the middle element is greater than num then assign high as mid else if the middle element is less than num then assign low as mid
862Step1.3 if the function has not returned None till now then print Not Found and return None
863Step2. get the number of books.
864Step3. get the details of the book and assign these details to the dictionary n_list with accession number as the key and all the other things as the value
865Step4. get the accession number of the number that needs to be searched.
866Step5. call the bsearch function to perform binary search and to check whether the accession number is found or not
867Step6. End
868
869at October 04, 2017 2 comments: Links to this post
870Email This
871BlogThis!
872Share to Twitter
873Share to Facebook
874Share to Pinterest
875
876Labels: Inlab, Python
877INLAB 6
878INLAB 6
879
880Q.Given ‘n’ integers, write an algorithm and the subsequent Python code to print all numbers that are sum-equivalent to the first number. Two numbers ‘m’ and ‘n’ are said to be sum-equivalent if ‘m’ and ‘n’ have the same number of digits and the sum of the digits in ‘m’ and ‘n’ are equal. 12381 is sum-equivalent to 10545. Here both the numbers are five digit numbers. Sum of the digits in 12381 is 1+2+3+8+1=15. Similarly the sum of the digits in 10545 is 15.
881Write a function to check whether two numbers are sum-equivalent or not. If none of the numbers are sum-equivalent then print ‘No sum-equivalent’.
882Input Format
883First line contains the number of elements, n
884Next ‘n’ line contains the numbers
885Output Format
886Print first number in the first line
887Next few lines contain the numbers that are sum-equivalent to first number.
888If the none of the numbers are sum-equivalent , then Print “No sum-equivalentâ€
889
890Input:
891the number of elements n
892the n numbers
893Processing:
894def sum_digit(number):
895total = 0
896count = 0
897temp = number
898while number:
899total += number%10
900number = number//10
901count += 1
902return temp,count,total
903n = int(input())
904sum_list = []
905for i in range(n):
906number = int(input())
907sum_list.append(sum_digit(number))
908count = 0
909
910Output:
911the numbers that are the sum equivalents of the first number if none then display no sum equivalent
912
913Program:
914def sum_digit(number):
915total = 0
916count = 0
917temp = number
918while number:
919total += number%10
920number = number//10
921count += 1
922return temp,count,total
923n = int(input())
924sum_list = []
925for i in range(n):
926number = int(input())
927sum_list.append(sum_digit(number))
928count = 0
929for i in range(1,n):
930if sum_list[0][1] == sum_list[i][1] and sum_list[0][2] == sum_list[i][2]:
931if count == 0:
932print(sum_list[0][0])
933print(sum_list[i][0])
934count += 1
935if count == 0:
936print('No sum-equivalent')
937
938Algorithm:
939Step1. Define a function sum_digit with parameter as number as follows
940Step1.1 assign total, count as 0 and temp as number
941Step1.2 repeat till the number is not equal to zero
942Step1.2.1 assign total as the sum of total and the remainder obtained when number is divided by 10
943Step1.2.2 assign number as the number obtained when number is divided by 10 and the decimal places are removed.
944Step1.2.3 increment count by 1
945Step1.3 return the tuple temp,count,total
946Step2. Get n
947Step3. Assign sum_list as an empty list
948Step4. Repeat till i is less than n
949Step4.1 get the number and call the function sum_digit with the actual parameter as number and the returned value should be appended in sum_list
950Step5. Print the first number in sum_list
951Step6. Assign count as 0
952Step7. Repeat till i is less than where i goes from 1 to n
953Step7.1 if the number of digits in the ith element and the total of the ith element match with the number of digits in the 0th element and the total of the 0th element then display the ith number
954Step7.2 increment count by 1
955Step8. If count is equal to zero then display no sum-equivalent
956Step9. End
957at September 30, 2017 2 comments: Links to this post
958Email This
959BlogThis!
960Share to Twitter
961Share to Facebook
962Share to Pinterest
963
964Labels: Inlab, Python
965INLAB 4
966INLAB 4
967Q.A team of experts formed by Govt. of India conducted a survey on colleges in India. Let us assume that the survey was conducted in ‘n’ number of institutes. The experts were asked to rank the institutes based on three different metrics. The metrics are facilities, academics and infrastructure. Maximum score in each category is as follows.
968Facilities = 25
969Academics = 50
970Infrastructure = 25
971At the end of the survey the scores of the individual metrics are added up to get the total score and the institutes are ranked based on the total score. The institute that scores the highest score is ranked 1st. Next highest score is given the rank 2 and so on. Write a program to read the scores of the three metrics for each institute, store the scores in a list. Make a list of individual score list for 10 institutes. Print only the Total score in the sorted (Descending) order. Use insertion sort for arranging the data in descending order.
972number_institutes = int(input())
973facility_scores = []
974academics_scores = []
975infra_scores = []
976total_scores = []
977flag = True
978for i in range(number_institutes):
979facility_s = int(input())
980acad_s = int(input())
981infra_s = int(input())
982if facility_s >= 0 and facility_s = 0 and acad_s = 0 and infra_s facility_scores.append(facility_s)
983academics_scores.append(acad_s)
984infra_scores.append(infra_s)
985total_scores.append(facility_s + acad_s + infra_s)
986else:
987flag = False
988if flag == True:
989total_scores.sort(reverse=True)
990print(total_scores)
991else:
992print('Invalid Input')
993
994Comment:
995The teacher told us not to program code for insertion sort and rather use the sort function
996
997Algorithm
998Step1. Get the number of institutes
999Step2. Repeat until i is less than number of institutes
1000Step2.1 Get Facilities scores
1001Step2.2 Get Academics scores
1002Step2.3 Get Infrastructure scores
1003Step3. Insert the scores in separate lists according to the category
1004Step4. Process the list of total scores
1005Step5. Sort the list of total scores using insertion sort
1006Step6. Reverse the above list and print it.
1007at September 17, 2017 No comments: Links to this post
1008Email This
1009BlogThis!
1010Share to Twitter
1011Share to Facebook
1012Share to Pinterest
1013
1014Labels: Inlab
1015INLAB 5
1016INLAB 5
1017Q.Government of India has appointed two separate teams with three members each for investigating a case. After forming the two teams with three members each, as a cost-cutting measure, the government decides to merge the two teams in to a single team with five members, by eliminating the member with the least experience among all the six members from the two teams. Use dictionaries to store the two teams and form a new team by concatenating the two teams. The chairperson of the new team is the person with the maximum experience. Design an algorithm and write the subsequent Python code to store the members of the two teams as dictionaries, print the new (concatenated) dictionary with the names in an increasing order of experience, to check whether a given name is present in the new dictionary or not and to print the name of the chairperson of the new team.
1018Note: Assume that there is only one person with least experience in the two dictionaries.
1019Input format:
1020Enter the details of the first team
1021Name of the first member
1022Experience (in years) of the first member
1023...
1024....
1025Name of the third member
1026Experience (in years) of the third member
1027Enter the details of the second team:
1028Name of the first member
1029Experience of the first member
1030....
1031....
1032Name of the third member
1033Experience of the third member
1034Enter the name to be checked in the new team
1035Output format:
1036Exists or Does not Exist
1037New team with experience as key value
1038Name of the person who is having maximum experience
1039[Hint: use pprint function for printing dictionary in sorted order.]
1040Syntax for pprint:
1041include 'from pprint import pprint'
1042from pprint import pprint
1043group1, group2 = {},{}
1044for i in range(6):
1045name = input().rstrip()
1046experience = int(input())
1047if i < 3:
1048group1[experience] = name
1049else:
1050group2[experience] = name
1051final_group = {}
1052for i in group1.keys():
1053final_group[i] = group1[i]
1054for i in group2.keys():
1055final_group[i] = group2[i]
1056for i in sorted(final_group.keys()):
1057del final_group[i]
1058break
1059chairman = max(final_group.keys())
1060new_mem = input()
1061if new_mem in final_group.values():
1062print('Exist')
1063else:
1064print('Does not Exist')
1065pprint(final_group)
1066print(final_group[chairman])
1067
1068Algorithm:
1069Step1. Initialize group1 and group2 as empty dictionaries.
1070Step2. Initialize i as 0 and repeat till is less than 6
1071Step2.1 get the name and the number of years of experience from the user
1072Step2.2 if i is less than 3 then let group1 key be the experience and name be the value of the key else let group2 key be the experience and name be the value of the key
1073Step3. Initialize final_group as an empty dictionary
1074Step4. Reinitialize i as the first key in group1 and repeat till i doesn’t complete all the keys in group1
1075Step4.1 let the value of key i of final_group be the same as the value obtained by accessing the key i of group1
1076Step5. Reinitialize i as the first key in group2 and repeat till i doesn’t complete all the keys in group2
1077Step5.2 let the value of key i of final_group be the same as the value obtained by accessing the key i of group2
1078Step6. Reinitialize i to be the first key of the sorted list of keys in the final_group and repeat till i doesn’t complete all the keys in the final_group
1079Step6.1 delete the first key and value pair in the final_group dictionary and break out from the loop
1080Step7. Assign chairman as the maximum value of key in final_group
1081Step8. Get the member that has to be searched
1082Step9. If the member is in the final_group display Exist else display Does not Exist
1083Step10. Print the final_group dictionary in sorted order.
1084Step11. Display the name of the chairman.
1085at September 17, 2017 No comments: Links to this post
1086Email This
1087BlogThis!
1088Share to Twitter
1089Share to Facebook
1090Share to Pinterest
1091
1092Labels: Inlab, Python
1093INLAB 3
1094INLAB 3
1095‘pneumonoultramicroscopicsilicovolcanoconiosis’ is the longest word in a dictionary with 45 letters. Given the value of ‘i' and the value of ‘k' write an algorithm and the subsequent Python code to output the five letters of the above longest string which are in the positions that are the first five multiples of 2*i+k. If a multiple is greater than the length of the string, then continue the counting from the beginning of the string. For example, if the value of i = 5 and k = 2 then the output letters are ‘r’, ‘c’, ‘n’, ‘e’, and ‘i'. The longest string is stored in a variable named as 's' in the precode, to be used for coding.
1096Input Format
1097First line contains the value of ‘i'
1098Second line contains the value of ‘k'
1099Output Format
1100Letters in the position that are the first five multiples of 2*i + k, one letter in one line
1101
1102Input:
1103the numbers i and k
1104
1105Processing:
1106s = 'pneumonoultramicroscopicsilicovolcanoconiosis'
1107multiple = ((2*i) + k)
1108for j in range(5):
1109multiple = multiple%45
1110multiple += ((2*i) + k)
1111
1112Output:
1113The letters at the positions of the five multiples in the string
1114
1115Program:
1116s = 'pneumonoultramicroscopicsilicovolcanoconiosis'
1117i = int(input())
1118k = int(input())
1119multiple = ((2*i) + k)
1120for j in range(5):
1121multiple = multiple%45
1122print(s[multiple-1])
1123multiple += ((2*i) + k)