0% found this document useful (0 votes)
8 views17 pages

Problem Sheet 8 Ws

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

Problem Sheet 8 Ws

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

PSG College of Technology, Coimbatore

M. Sc Applied Mathematics – II Semester


23SA27 - Python Programming Lab
Problem Sheet – 8
M S DARSINI
23PA03

1. File Display
Assume a file containing a series of integers is named numbers.txt and exists on the
computer’s
disk. Write a program that displays all of the numbers in the file.
Code:
f=open("Z:\\num1.txt","r")
print(f.read())
OUTPUT:

2. File Head Display


Write a program that asks the user for the name of a file. The program should display only
the first five lines of the file’s contents. If the file contains less than five lines, it should
display the file’s entire contents.
Code:

s=str(input("Enter the file name as path:"))


f=open(f'{s}',"r")
for i in range(0,5):
print(f.read())

OUTPUT:

3. Line Numbers
Write a program that asks the user for the name of a file. The program should display the
contents of the file with each line preceded with a line number followed by a colon. The
line numbering should start at 1.
s=str(input("Enter the file name as path:"))
f=open(f'{s}',"r")
i=1
for j in f:
print(i,":",j)
i=i+1

OUTPUT:

4. High Score
Assume that a file named scores.txt exists on the computer’s disk. It contains a series of
records, each with two fields – a name, followed by a score (an integer between 1 and 100).
Write a program that displays the name and score of the record with the highest score, as
well as the number of records in the file. (Hint: Use a variable and an “if” statement to
keep track of the highest score found as you read through the records, and a variable to
keep count of the number of records.)

file=open("C:/py file/scores.txt",'r')
i=0
high=1
name=''
for line in file:
n,s=line.strip().split()
if int(s)>high:
high=int(s)
name=n
i=i+1
print('the name and score of the record with highest score:')
print('Name:',name)
print('Score:',high)
print('\nNumber of records:',i)

OUTPUT:

5. Sum of Numbers
Assume a file containing a series of integers is named numbers.txt and exists on the
computer’s
disk. Write a program that reads all of the numbers stored in the file and calculates
their total.
f=open("C:/py file/numbers.txt","r")
sum=0
for i in f:
sum=sum+int(i)
print("total:",sum)

OUTPUT:

6. Average of Numbers
Assume a file containing a series of integers is named numbers.txt and exists on the
computer’s disk. Write a program that calculates the average of all the numbers stored in
the file.

f=open("C:/py file/numbers.txt","r")
sum=0
j=0
for i in f:
sum=sum+int(i)
j=j+1
avg=int(sum/j)
print("avg:",avg)

OUTPUT:

7. Word List File Writer


Write a program that asks the user how many words they would like to write to a file, and
then asks the user to enter that many words, one at a time. The words should be written
to a file.

f=open("C:/py file/words.txt","w")
n=int(input("Enter the no.of words:"))
for i in range(n):
x=str(input())
f.write(x)
f.close
f=open("C:/py file/words.txt","r")
print("The content of file:")
print(f.read())
OUTPUT:

8. Word List File Reader


This exercise assumes you have completed the Programming Exercise 7, Word List File
Writer. Write another program that reads the words from the file and displays the following
data:
• The number of words in the file.
• The longest word in the file.
• The average length of all of the words in the file.
f=open("C:/py file/words.txt","r")
count=0
min_len=0
length=0
content=f.read()
w=content.split(" ")
for i in w:
count=count+1
length=length+len(i)
if min_len<len(i):
min_len=len(i)
long=i
avg=(length-count-1)/count
print("Total no.of.words:",count)
print("The longest word in file:",long)
print("The average length of all words in file:",avg)
OUTPUT:
9. Golf Scores
The Springfork Amateur Golf Club has a tournament every weekend. The club president
has asked you to write two programs:
a. A program that will read each player’s name and golf score as keyboard input, then
save these as records in a file named golf.txt. (Each record will have a field for the
player’s name and a field for the player’s score.)
b. A program that reads the records from the golf.txt file and displays them.
f=open("C:/py file/words.txt","w")
n=int(input("Enter the no.of players:"))
for i in range(n):
name=str(input("Enter the name:"))
score=str(input("Enter the score:"))
f.write( name+"--"+score+"\n")
f.close
f=open("C:/py file/words.txt","r")
print(f.read())

OUTPUT:

10. You are given a file called class_scores.txt, where each line of the file contains a oneword
username and a test score separated by spaces, like below:.
GWashington 83
JAdams 86
Write code that scans through the file, adds 5 points to each test score, and outputs the
usernames
and new test scores to a new file, scores2.txt.

f1=open('C:/py file/class_scores.txt',"r")
f2=open('C:/py file/scores2.txt',"w")
for line in f1:
n,s=line.strip().split()
score=int(s)
score+=5
f2.write(n+" "+str(score)+'\n')
f1.close()
f2.close()
f1=open('C:/py file/class_scores.txt',"r")
print("Contents of class_scores.txt :")
for line in f1:
n,s=line.strip().split()
print(n,s)
f2=open('C:/py file/scores2.txt',"r")
print("\nContents of scores2.txt : ")
for line in f2:
n,s=line.strip().split()
print(n,s)

OUTPUT:

11. You are given a file called grades.txt, where each line of the file contains a one-word
student
username and three test scores separated by spaces, like below:.
GWashington 83 77 54
JAdams 86 69 90
Write code that scans through the file and determines how many students passed all three
tests.

print("contents in file:")
f=open("C:/py file/grades.txt","r")
print(f.read())
f.close()
f=open("C:/py file/grades.txt","r")
print("student passed all the 3 exams:")
count=0
for i in f:
n,s1,s2,s3=i.strip().split()
if int(s1)>55 and int(s2)>55 and int(s3)>55:
count=count+1
print(n)
print("no.of students passed:",count)

OUTPUT:
12. You are given a file called logfile.txt that lists log-on and log-off times for users of a
system. A typical line of the file looks like this:
Van Rossum, 14:22, 14:37
Each line has three entries separated by commas: a username, a log-on time, and a log-off
time. Times are given in 24-hour format. You may assume that all log-ons and log-offs occur
within a single workday.
Write a program that scans through the file and prints out all users who were online for at
least an hour.

f=open("C:/py file/logfile.txt","r")
print("users are in online for atleast one hr:")

for i in f:
n,t1,t2=i.strip().split(',')
h=float(t2)-float(t1)
if (h>=1.00):
print(n)

OUTPUT:

13. You are given a file called students.txt. A typical line in the file looks like:
walter melon [email protected] 555-3141
There is a name, an email address, and a phone number, each separated by tabs. Write a
program that reads through the file line-by-line, and for each line, capitalizes the first letter
of the first and last name and adds the area code 301 to the phone number. Your program
should write this to a new file called students2.txt. Here is what the first line of the new
file should look like:
Walter Melon [email protected] 301-555-3141

f=open("C:/py file/students.txt","r")
fi=open("C:/py file/students2.txt","w")
for i in f:
fn,ln,mail,code=i.strip().split()
x=str(301)+"-"+code
fi.write(fn.title()+"\t"+ln.title()+"\t"+mail+"\t"+x+"\t"+"\n")
fi=open("C:/py file/students2.txt","r")
print(fi.read())
OUTPUT:

14. You are given a file namelist.txt that contains a bunch of names. Some of the names are
a first name and a last name separated by spaces, like George Washington, while others have
a middle name, like John Quincy Adams. There are no names consisting of just one word or
more than three words. Write a program that asks the user to enter initials, like GW or JQA,
and prints all the names that match those initials. Note that initials like JA should match both
John Adams and John Quincy Adams.

f=open("C:/py file/namelist.txt","r")
s=str(input("Enter the initials:"))
s=s.upper()
for i in f:
n=i.strip().split()
if len(s)==2:
if len(n)==3 and n[0][0]==s[0] and n[2][0]==s[1]:
print(*n,sep=' ')
if len(n)==2 and n[0][0]==s[0] and n[1][0]==s[1]:
print(*n,sep=' ')
if len(s)==3 and n[0][0]==s[0] and n[1][0]==s[1] and n[2][0]==s[2]:
print(*n,sep=' ')

OUTPUT:

15. You are given a file namelist.txt that contains a bunch of names. Print out all the names
in the list in which the vowels a, e, i, o, and u appear in order (with repeats possible). The
first
vowel in the name must be a and after the first u, it is okay for there to be other vowels. An
example is Ace Elvin Coulson.

f=open("C:/py file/namelist.txt","r")
print("the names in which the vowels in order ")
for i in f:
s=i.strip().lower()
j=s.find('a')
if j!=-1:
j=s.find('e',j+1)
if j!=-1:
j=s.find('i',j+1)
if j!=-1:
j=s.find('o',j+1)
if j!=-1:
j=s.find('u',j+1)
if j!=-1:
print(i.strip())
OUTPUT:

16. You are given a file called baseball.txt. A typical line of the file starts like below.
Ichiro Suzuki SEA 162 680 74 ...[more stats]
Each entry is separated by a tab, \t. The first entry is the player’s name and the second is
their team. Following that are 16 statistics. Home runs are the seventh stat and stolen bases
are the eleventh. Print out all the players who have at least 20 home runs and at least 20
stolen bases.
f=open("Z:\\baseball.txt","r")
print("The players are:")
for i in f:
s=i.strip().split()
if int(s[7])>20 and int(s[11])>20:
print(s[0],s[1],s[2],s[7],s[11],sep="\t")

OUTPUT:

17. Wordplay – Use the file wordlist.txt for this problem. Find the following:
(a) All words ending in ime

f=open("Z:\wordslist.txt","r")
j=0:
for i in f:
s=i.strip()
j=j+1
if ((len(s)-3)==s.find("ime") and len(s)>2):
print(s)
f.seek(0)

OUTPUT:

(b) All words whose second, third, and fourth letters are ave

f=open("Z:\wordslist.txt","r")
for i in f:
s=i.strip()
if (s.find("ave")==1):
print(s)
f.seek(0)

OUTPUT:
(c) How many words contain at least one of the letters r, s, t, l, n, e

f=open("Z:\wordslist.txt","r")
k=0
for i in f:
s=i.strip()
if 'r' in s or 's' in s or 't' in s or 'l' in s or 'n' in s or 'e' in s:
k=k+1
print("count of words:",k)

OUTPUT:

(d) The percentage of words that contain at least one of the letters r, s, t, l, n, e

f=open("Z:\wordslist.txt","r")
k=0
j=0
for i in f:
s=i.strip()
j=j+1
if 'r' in s or 's' in s or 't' in s or 'l' in s or 'n' in s or 'e' in s:
k=k+1
print("count of words:",k*100/j)

OUTPUT:

(e) All words with no vowels

l=['a','e','i','o','u']
f=open("C:/py file/wordlist.txt","r")
for i in f:
g=0
s=i.strip()
for m in range(0,5):
if (l[m] in s):
g=g+1
if g==0:
print("word without vowel:",s)
f.seek(0)

OUTPUT:

(f) All words that contain every vowel

l=['a','e','i','o','u']
f=open("C:/py file/wordlist.txt","r")
for i in f:
g=0
s=i.strip().lower()
for m in range(0,5):
if (l[m] in s):
g=g+1
if g==5:
print("word with every vowel:",s)
f.seek(0)

OUTPUT:

(g) Whether there are more ten-letter words or seven-letter words

f = open("C:/py file/wordlist.txt", "r")


seven= 0
ten= 0

for i in f:
s = i.strip().split()
for j in s:
if len(j) >= 7:
seven+= 1
if len(j) >= 10:
ten += 1
f.close()

if seven > ten:


print("More seven-letter words")
else:
print("More ten-letter words")

OUTPUT:

(h) The longest word in the list

f = open("C:/py file/wordlist.txt", "r")


m=0
for i in f:
s=i.strip()
if len(s)>m:
m=len(s)
f.seek(0)
print("longest word is:",s)

OUTPUT:
(i) All palindromes

f = open("C:/py file/wordlist.txt", "r")


for i in f:
s=i.strip().lower()
if s==s[::-1]:
print("Palindrome:",s)
f.seek(0)

OUTPUT:

(j) All words that are words in reverse, like rat and tar.

f = open("C:/py file/wordlist.txt", "r")


for i in f:
s=i.strip().lower()
print("reverse:",s,"---",s[::-1])
f.seek(0)

OUTPUT:

(k) Same as above, but only print one word out of each pair.

f = open("C:/py file/wordlist.txt", "r")


for i in f:
s=i.strip().lower()
print(s)
f.seek(0)

OUTPUT:

(l) All words that contain double letters next each other like aardvark or book, excluding
words that end in lly

f = open("C:/py file/wordlist.txt", "r")


for i in f:
g=0
s=i.strip().lower()
for j in range(0,len(s)-1):
if s[j]==s[j+1]:
g=1
if g==1:
print(s)
f.seek(0)

OUTPUT:

(m) All words that contain a q that isn’t followed by a u

f = open("C:/py file/wordlist.txt", "r")


for i in f:
g=0
s=i.strip().lower()

for j in range(0,len(s)-1):
if 'q' in s[j] and 'u' not in s[j+1] :
g=1
if g==1:
print(s)
f.seek(0)

OUTPUT:

(n) All words that contain zu anywhere in the word

f = open("C:/py file/wordlist.txt", "r")


for i in f:
g=0
s=i.strip().lower()
for j in range(0,len(s)-1):
if 'z' in s[j] and 'u' in s[j+1]:
g=1
if g==1:
print("words that contain zu:",s)
f.seek(0)

OUTPUT:

(o) All words that contain ab in multiple places, like habitable

f = open("C:/py file/wordlist.txt", "r")


for i in f:
g=0
s=i.strip().lower()
for j in range(0,len(s)-1):
if 'a' in s[j] and 'b' in s[j+1]:
g=1
if g==1:
print("words that contain zu:",s)
f.seek(0)

OUTPUT:

(p) All words with four or more vowels in a row


.
l=['a','e','i','o','u']
f = open("C:/py file/wordlist.txt", "r")
for i in f:
s=i.strip().lower()
for j in range(0,len(s)-3):
if s[j] in l and s[j+1] in l and s[j+2] in l and s[j+3] in l:
print(s)
f.seek(0)

OUTPUT:

(q) All words that contain both a z and a w

f = open("C:/py file/wordlist.txt", "r")


for i in f:
s=i.strip().lower()
if s.find("az")!=-1 and s.find("aw")!=-1:
print(s)
f.seek(0)

OUTPUT:

(r) All words whose first letter is a, third letter is e and fifth letter is i

f = open("C:/py file/wordlist.txt", "r")


for i in f:
s=i.strip().lower()
if s[0]=='a' and s[2]=='e' and s[4]=='i':
print(s)
f.seek(0)

OUTPUT:
(s) All two-letter words

f = open("C:/py file/wordlist.txt", "r")


for i in f:
s=i.strip().lower()
if len(s)==2:
print(s)
f.seek(0)

OUTPUT:

(t) All four-letter words that start and end with the same letter

f = open("C:/py file/wordlist.txt", "r")


for i in f:
s=i.strip().lower()
if len(s)==4 and s[0]==s[3]:
print(s)
f.seek(0)

OUTPUT:

(u) All words that contain at least nine vowels.

l=['a','e','i','o','u']
f = open("C:/py file/wordlist.txt", "r")
for i in f:
g=0
s=i.strip().lower()
for j in range(0,len(s)):
if s[j] in l:
g=g+1
if g>=9:
print(s)
f.seek(0)

OUTPUT:

(v) All words that contain each of the letters a, b, c, d, e, and f in any order. There may be
other letters in the word. Two examples are backfield and feedback.

l=['a','b','c','d','e','f']
f = open("C:/py file/wordlist.txt", "r")
for i in f:
g=0
s=i.strip().lower()
for j in range(0,len(s)):
if s[j] in l:
g=g+1
if g==6:
print(s)
f.seek(0)

OUTPUT:

(w) All words whose first four and last four letters are the same
l=['a','b','c','d','e','f']
f = open("C:/py file/wordlist.txt", "r")
for i in f:
g=0
s=i.strip().lower()
if s[0:4]==s[4:]:
print(s)
f.seek(0)
OUTPUT:

(x) All words of the form abcd*dcba, where * is arbitrarily long sequence of letters.

l=['a','b','c','d','e','f']
f = open("C:/py file/wordlist.txt", "r")
for i in f:
g=0
s=i.strip().lower()
if s[0:4]==s[::-1][:4]:
print(s)
f.seek(0)

OUTPUT:

(y) All groups of 5 words, like pat pet pit pot put, where each word is 3 letters, all words
share
the same first and last letters, and the middle letter runs through all 5 vowels.

(z) The word that has the most i’s.


f=open("C:/py file/wordlist.txt", "r")
mi=0
for i in f:
g=0
s=i.strip()
j=s.find('i')
while j!=1:
g=g+1
j=s.find('i',j+1)
if g>mi:
mi=g
print("there are most i's in this word:",s)

OUTPUT:

You might also like