You are on page 1of 15

Python Programs

Unit 2 and 3
Lists and Files

By:
Arsal ul Haque 1MS14EC020
Keerti Vardhan 1MS14EC048
Unit 2

Lists
2) Design amd implement a python program to find the number 4 in a given list.

def list_count_4(nums):
count = 0
for num in nums:
if num == 4:
count = count + 1

return count

print(list_count_4([1, 4, 6, 7, 4]))
print(list_count_4([1, 4, 6, 4, 7, 4]))
3) Python program to generate and print list except first 5 elements,
where the values are square of a number between 1 and 30.

def printValues():
l = list()
for i in range(1,31):
l.append(i**2)
print(l[5:])

printValues()

4) Implement a python function that takes two list and returns true if they have at least one
element in common.

def common_data(list1, list2):


result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))
5) implement a pythin program to find a list of words that are no
longer than n feom a given list of words.
def long_words(n, str):
word_len = []
txt = str.split(" ")
for x in txt:
if len(x) > n:
word_len.append(x)
return word_len
print(long_words(3, "The quick brown fox jumps over the lazy dog"))

6)
Implement a python program to count no. of vowels present in a given
list of strings using ‘in’ and ‘not in’ operators
string=input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or
i=='E' or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)

10)
Python program to remove duplicates from a list.
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)

12)
Python function that takes a list and returns a new list with unique
elements of the first list.
def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x

print(unique_list([1,2,3,3,3,3,4,5]))

14) Python program to check wheather a list contains a sublist.


def is_Sublist(l, s):
sub_set = False
if s == []:
sub_set = True
elif s == l:
sub_set = True
elif len(s) > len(l):
sub_set = False

else:
for i in range(len(l)):
if l[i] == s[0]:
n = 1
while (n < len(s)) and (l[i+n] == s[n]):
n += 1

if n == len(s):
sub_set = True

return sub_set

a = [2,4,3,5,7]
b = [4,3]
c = [3,7]
print(is_Sublist(a, b))
print(is_Sublist(a, c))
22)
Program that reads details of student in comma separated values from
keyboard and split & typecast the input based comma delimiter and
store it in list before displaying it.
string = input(“Enter the student details separated by commas”)
list = string.split(“,”)
print(list)
while(i<=(len(list)-3))
name=list[i]
usn=list[i+1]
sem=list[i+2]
i+3
print(name)
print(usn)
print(sem)
Unit 3
Files
1)
Design and implement program to create and read contents of file
that resembles a phonebook. Sort it alphabetically.
f= open("phonebook.txt","w+")
f.write("fghk 9874563210\n")
f.write("wxyz 2365987410\n")
f.write("abcd 9865320147\n")
f.close()
f=open("phonebook.txt","r")
contents=f.read()
f.close()
f=open("phonebook.txt","r")
words=f.readlines()
f.close()
words.sort()
print (words)

2) Implement a program to crate and read a file, store it in a list


of lists, with inner list containing product name, net weight and
unit price of the product, by name shopper_list.txt that contains
name weight and priceof products in a supermarket.
f= open("shopper_list.txt","r")
list1=[]
list2=[]
list3=[]
#words=[]
#words=f.split()
for line in f:
for i in line.split():
if(len(list1)!=3):
list1.append(i)
else:
list2.append(i)
print (list1)
print (list2)
list3=[list1,list2]
print(list3)

3) Implement a program to read a file and count occurences of each letter


in a line.

import collections
import pprint
file_input = input('File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
5) Program that reads a file and displays how many time a leeter ‘c’ has
occurred.

f= open("original_text.txt","r")
count=0
for line in f:
if 'c' in line:
count=count+1
print(count)
6)
Python program to count no of lines in a file.
fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f:
for line in f:
num_lines += 1
print("Number of lines:")
print(num_lines)

10) A python program that reads a file and write outs anew file with
the lines in reversed order. (The first line becomes the last)
f = open("shopper_list.txt", "rb")
s = f.readlines()
f.close()
f = open("newtext.txt", "wb")
f.writelines(s[::-1])
f.close()
print (f)
12) Python program to read a file line by line and store into a
list. Find the longest word.
f = open("shopper_list.txt", "r")
list=[]
list = f.read().split('\n')
print(list)
f.close()
f = open("shopper_list.txt", "r")
w=[]
for lines in f:
for words in lines.split():
w.append(words)
#print(w)
longest=""
for i in w:
if (len(longest)<len(i)):
longest=i
print(longest)
f.close()
14) Program that reads a file and print only those line that
contains a substring snake.
f= open("find.txt","r")
for line in f:
if 'snake' in line:
print(line)

18)
Python program to count frequency of words in a file.
from collections import Counter
def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())
print("Number of words in the file :",word_count("find.txt"))

You might also like