Hi,
In this post i attached my lecture 5 which describes chapter 8,9. Here i am going to post practice questions for chapter 9 and tutorials for chapter 8 and 9.
here, you can find the lecture slides,
In this post i attached my lecture 5 which describes chapter 8,9. Here i am going to post practice questions for chapter 9 and tutorials for chapter 8 and 9.
here, you can find the lecture slides,
Programming exercises
you can find these exercise questions at the end of the chapter 9 in this book.
1. InitialsWrite a program that gets a string containing a person’s first, middle, and last names, and then display their first, middle, and last initials. For example, if the user enters John William Smith the program should display J. W. S.
answer :-
firstName = input("Enter the first name : ")
middleName = input("Enter the middle name :")
lastName = input("Enter the last name : ")
print("disply the first , middle and last initials...")
print(firstName[0],".",middleName[0],".",lastName[0],sep="")
2. Sum of Digits in a String
Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the string. For example, if the user enters 2514, the method should return 12, which is the sum of 2, 5, 1, and 4.
Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the string. For example, if the user enters 2514, the method should return 12, which is the sum of 2, 5, 1, and 4.
answer :-
numbers = input("Enter the series single-digit numbers : ")
total = 0
for i in numbers:
convertNumber = int(i)
total += convertNumber
print("total :",total)
3. Date Printer
Write a program that reads a string from the user containing a date in the form mm/dd/yyyy. It should print the date in the form March 12, 2012.
Write a program that reads a string from the user containing a date in the form mm/dd/yyyy. It should print the date in the form March 12, 2012.
answer :-
def main():
monthList = ["January" , "february" , "March" , "April" , "May" ,\
"June" , "July" ,"August" , "September" , \
"October" , "November" , "December" ]
print("assign months into the list...")
print(monthList)
print("get the date from the user in the form (mm/dd/yyyy)")
date = input("Enter the date(mm/dd/yyyy) : ")
monthNumber , dateNumber , year, yearLength = date_split(date)
while monthNumber >= 13 or dateNumber>= 32 or \
monthNumber <= 0 or dateNumber<= 0 or yearLength != 4:
warning()
date = input("Enter the date(mm/dd/yyyy) : ")
monthNumber , dateNumber , year, yearLength = date_split(date)
print("print the date in the form: ",end="")
month = monthList[monthNumber - 1]
print(month,",",dateNumber,",",year,sep="")
def date_split(date):
dateSplit = date.split("/")
print("dateSplit = ",end="")
print(dateSplit)
monthNumber = int(dateSplit[0])
dateNumber = int(dateSplit[1])
year = int(dateSplit[2])
yearLength = len(dateSplit[2])
return monthNumber , dateNumber ,year,yearLength
def warning():
print("you gave the wrong inputs.....")
print("give the month number between 1 -12")
print("give the day number between 1 -31")
print("year must be 4 digits")
main()
4. Morse Code Converter
Morse code is a code where each letter of the English alphabet, each digit, and various punctuation characters are represented by a series of dots and dashes. Table 9-5 shows part of the code.
Write a program that asks the user to enter a string, and then converts that string to Morse code.
Morse code is a code where each letter of the English alphabet, each digit, and various punctuation characters are represented by a series of dots and dashes. Table 9-5 shows part of the code.
Write a program that asks the user to enter a string, and then converts that string to Morse code.
Table 9-5 Morse code
Character Code Character Code
space space 6 – . . . .
comma – – . . – – 7 – – . . . .
period . – . – . – 8 – – – . .
question mark . . – – . . 9 – – – – .
0 – – – – – A . –
1 . – – – – B – . . .
Character Code Character Code
space space 6 – . . . .
comma – – . . – – 7 – – . . . .
period . – . – . – 8 – – – . .
question mark . . – – . . 9 – – – – .
0 – – – – – A . –
1 . – – – – B – . . .
....................................................
answer :-
def main():
file_variable = open("morsecode.txt" , "r")
listOFlist = []
for line in file_variable:
line = line.rstrip('\n')
mylist = line.split()
listOFlist.append(mylist)
character = input("Enter the character : ")
morseCode = findOfCode(character,listOFlist)
if morseCode == "":
print(" chracter not found ")
else:
print("Morse Code for the character:"+"("+character+")","is",morseCode)
def findOfCode(character,listOFlist):
for i in range(len(listOFlist)):
for j in range(len(listOFlist[i])):
if(listOFlist[i][j] == character):
return listOFlist[i][j+1]
return ""
main()
5. Alphabetic Telephone Number Translator
Many companies use telephone numbers like 555-GET-FOOD so the number is easier for their customers to remember. On a standard telephone, the alphabetic letters are mapped to numbers in the following fashion:
A, B, and C = 2
D, E, and F = 3
G, H, and I = 4
J, K, and L = 5
M, N, and O = 6
P, Q, R, and S = 7
T, U, and V = 8
W, X, Y, and Z = 9
Write a program that asks the user to enter a 10-character telephone number in the format XXX-XXX-XXXX. The application should display the telephone number with any alphabetic characters that appeared in the original translated to their numeric equivalent. For example, if the user enters 555-GET-FOOD the application should display 555-438-3663.
Many companies use telephone numbers like 555-GET-FOOD so the number is easier for their customers to remember. On a standard telephone, the alphabetic letters are mapped to numbers in the following fashion:
A, B, and C = 2
D, E, and F = 3
G, H, and I = 4
J, K, and L = 5
M, N, and O = 6
P, Q, R, and S = 7
T, U, and V = 8
W, X, Y, and Z = 9
Write a program that asks the user to enter a 10-character telephone number in the format XXX-XXX-XXXX. The application should display the telephone number with any alphabetic characters that appeared in the original translated to their numeric equivalent. For example, if the user enters 555-GET-FOOD the application should display 555-438-3663.
answer :-
def main():
alphaList = [["A","B","C"],\
["D","E","F"],\
["G","H","I"],\
["J","K","L"],\
["M","N","O"],\
["P","Q","R","S"],\
["T","U","V"],\
["W","X","Y","Z"]]
numList = ["2","3","4","5","6","7","8","9","1"]
print("get the 10 character tp number",\
"from the user in the form (XXX-XXXX-XXXX)")
tpNumber = input("Enter the 10-character tp number(XXX-XXXX-XXXX) : ")
tpSplit = tpNumber.split("-")
listLength1,listLength2,listLength3 = tpList(tpSplit)
while listLength1 != 3 or listLength2 != 3 or \
listLength3 != 4 :
print("you gave the wrong format of telephone number...")
print("format should be XXX-XXX-XXXX")
tpNumber = input("Enter the 10-character tp number(XXX-XXXX-XXXX) : ")
tpSplit = tpNumber.split("-")
listLength1,listLength2,listLength3 = tpList(tpSplit)
print("user entered format : ",end="")
print(tpSplit[0].upper(),"-",tpSplit[1].upper(),\
"-",tpSplit[2].upper(),sep="")
print("numeric format : ",end="")
for element in tpSplit[0]:
elementUpper = element.upper()
result = convert_tp(elementUpper,numList,alphaList)
print(result,end="")
print("-",end="")
for element in tpSplit[1]:
elementUpper = element.upper()
result = convert_tp(elementUpper,numList,alphaList)
print(result,end="")
print("-",end="")
for element in tpSplit[2]:
elementUpper = element.upper()
result = convert_tp(elementUpper,numList,alphaList)
print(result,end="")
def tpList(anyList):
anyList1 = len(anyList[0])
anyList2 = len(anyList[1])
anyList3 = len(anyList[2])
return anyList1,anyList2,anyList3
def convert_tp(element,numList,alphaList):
if element in numList:
return element
else:
for row in range(len(alphaList)):
for coloumn in range(len(alphaList[row])):
if element == alphaList[row][coloumn]:
return numList[row]
main()
6. Average Number of Words
If you have downloaded the source code from this book’s companion Web site, you will find a file named text.txt in the Chapter 09 folder. The text that is in the file is stored as one sentence per line. Write a program that reads the file’s contents and calculates the average number of words per sentence.
If you have downloaded the source code from this book’s companion Web site, you will find a file named text.txt in the Chapter 09 folder. The text that is in the file is stored as one sentence per line. Write a program that reads the file’s contents and calculates the average number of words per sentence.
answer :-
def main():
file_variable = open("text.txt" , "r")
textList = []
for line in file_variable:
line = line.strip().rstrip("/n")
mylist = line.split()
textList.append(mylist)
print("finding number of lines in text.txt file")
totalLine = findLine(textList)
print("number of line : ",totalLine)
print("finding number of words in text.txt file")
totalWords = findWords(textList)
print("number of words : ",totalWords)
print("finding average words per line in text.txt file")
wordsPerLine = averageWords(totalWords , totalLine)
print("average words per line : ",wordsPerLine)
def findLine(anyList):
count = 0
for rachRow in anyList:
count+= 1
return count
def findWords(anyList):
total = 0
for row in range(len(anyList)):
count = 0
for coloumn in range(len(anyList[row])):
count += 1
total += count
return total
def averageWords(words , lines):
wordsPerLine = round(words /lines)
return wordsPerLine
main()
7. Character AnalysisIf you have downloaded the source code from this book’s companion Web site, you will find a file named text.txt in the Chapter 09 folder. Write a program that reads the file’s contents and determines the following:
• The number of uppercase letters in the file
• The number of lowercase letters in the file
• The number of digits in the file
• The number of whitespace characters in the file
• The number of uppercase letters in the file
• The number of lowercase letters in the file
• The number of digits in the file
• The number of whitespace characters in the file
answer :-
def main():
file_variable = open("text.txt" , "r")
textList = []
for line in file_variable:
line = line.rstrip("/n")
mylist = line
textList.append(mylist)
print("finding number of uppercase Letters in text.txt file")
totalUpCaLetters = countUpperCase(textList)
print("number of uppercase Letters : ",totalUpCaLetters)
print()
print("finding number of lowercase letters in text.txt file")
totalLoCaLetters = countLowerCase(textList)
print("number of Lower case Letters : ",totalLoCaLetters)
print()
print("finding number of digits in text.txt file")
totalDigits = countDigits(textList)
print("number of digits : ",totalDigits)
print()
print("finding number of whitespaces in text.txt file")
totalWhiteSpaces = countWhiteSpace(textList)
print("number of whitespaces : ",totalWhiteSpaces)
def countUpperCase(anyList):
count = 0
for row in range(len(anyList)):
for i in range(len(anyList[row])):
if anyList[row][i].isupper():
count+= 1
return count
def countLowerCase(anyList):
count = 0
for row in range(len(anyList)):
for i in range(len(anyList[row])):
if anyList[row][i].islower():
count+= 1
return count
def countDigits(anyList):
count = 0
for row in range(len(anyList)):
for i in range(len(anyList[row])):
if anyList[row][i].isdigit():
count+= 1
return count
def countWhiteSpace(anyList):
count = 0
for row in range(len(anyList)):
for i in range(len(anyList[row])):
if anyList[row][i].isspace():
count+= 1
return count
main()
8. Sentence Capitalizer
Write a program with a function that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized. For instance, if the argument is “hello. my name is Joe. what is your name?” the function should return the string “Hello. My name is Joe. What is your name?” The program should let the user enter a
string and then pass it to the function. The modified string should be displayed.
Write a program with a function that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized. For instance, if the argument is “hello. my name is Joe. what is your name?” the function should return the string “Hello. My name is Joe. What is your name?” The program should let the user enter a
string and then pass it to the function. The modified string should be displayed.
answer :-
getSentence = input("Enter the sentence : ")
i = 0
while i < len(getSentence):
if i == 0:
print(getSentence[i].upper(),end="")
elif getSentence[i] == '.':
print(". ",end="")
print(getSentence[i + 2].upper(),end="")
i += 2
else:
print(getSentence[i],end="")
i += 1
9. Vowels and ConsonantsWrite a program with a function that accepts a string as an argument and returns the number of vowels that the string contains. The application should have another function that accepts a string as an argument and returns the number of consonants that the string contains. The application should let the user enter a string and should display the number of vowels and the number of consonants it contains.
answer :-
def main():
getString = input("Enter the string : ")
print("counting number of vowel letters in given string....")
totalVowels = vowelCount(getString)
print("number if vowel letters :",totalVowels)
print()
print("counting number of consonants letters in given string....")
totalconsonants = consoCount(getString)
print("number if vowel letters :",totalconsonants)
def vowelCount(string):
count = 0
string1 = string.upper()
for ch in string1:
if ch == "A" or ch == "E" or ch == "I" or \
ch == "O" or ch == "U":
count += 1
return count
def consoCount(string):
count = 0
for ch in string:
if ch.isalpha():
count += 1
totalConsonants = count - vowelCount(string)
return totalConsonants
main()
10. Most Frequent Character
Write a program that lets the user enter a string and displays the character that appears most frequently in the string.
Write a program that lets the user enter a string and displays the character that appears most frequently in the string.
answer :-
(Not a good solution. good one will be updated)
def main():
string = input("Enter the string : ")
charList = []
occurList = []
for ch in string:
count = 0
for i in range(len(string)):
if ch == string[i]:
count += 1
if ch in charList:
charList
occurList
else:
charList.append(ch)
occurList.append(count)
print("character list : ",charList)
print("corresponding occurance list :",occurList)
print()
mostfreChar = maxOccur(occurList,charList)
if mostfreChar == " ":
print(" most frequent character : space ")
else:
print(" most frequent character :", mostfreChar)
def maxOccur(list1,list2):
largest = 0
for i in range(len(list1)):
find_lar = int(list1[i])
if(largest <= find_lar):
largest = find_lar
for i in range(len(list1)):
find_position = int(list1[i])
if(find_position == largest):
return list2[i]
main()
11. Word Separator
Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string “StopAndSmellTheRoses.” would be converted to “Stop and smell the roses.”
Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string “StopAndSmellTheRoses.” would be converted to “Stop and smell the roses.”
answer :-
getSentence = input("Enter the sentence without space : ")
uppLists = []
stringList = []
print("sentence before separate: ",getSentence)
for i in range(len(getSentence)):
if getSentence[i].isupper():
uppLists.append(i)
uppLists.append(len(getSentence))
i = 0
while i < len(uppLists) - 1:
startLimit = int(uppLists[i])
endLimit = int(uppLists[i + 1])
stringList.append(getSentence[startLimit : endLimit])
i += 1
print("sentence after separated: ",end = "")
for i in range(len(stringList)):
if i == 0:
print(stringList[i]+' ',end="")
else:
print(stringList[i].lower() + " ",end="")
12. Pig Latin
Write a program that accepts a sentence as input and converts each word to “Pig Latin.” In one version, to convert a word to Pig Latin you remove the first letter and place that letter at the end of the word. Then you append the string “ay” to the word. Here is an example:
English: I SLEPT MOST OF THE NIGHT
Pig Latin: IAY LEPTSAY OSTMAY FOAY HETAY IGHTNAY
Write a program that accepts a sentence as input and converts each word to “Pig Latin.” In one version, to convert a word to Pig Latin you remove the first letter and place that letter at the end of the word. Then you append the string “ay” to the word. Here is an example:
English: I SLEPT MOST OF THE NIGHT
Pig Latin: IAY LEPTSAY OSTMAY FOAY HETAY IGHTNAY
answer :-
getSentence = input("Enter the string : ")
lists = getSentence.split()
print("English :",getSentence)
print("Pig Latin : ",end="")
for i in lists:
newString = i[1:len(i)] +\
i[0]+"AY"
print(newString.upper(),end=" ")
From the tutorials,
Task 1
Create a single text file in IDLE named serverConnections.txt. This file stores a list
of host names and the number of connections for each server for a particular month of
the year, one line per server. For example, the serverConnections.txt might look like
the following (you may extend this file or create a completely new one consisting at
least of 10 lines of data). According to this file www.melbourne.edu.au had 1245
while www.athens.org.gr had 6754 connections for a particular month that the file
refers to.
www.melbourne.edu.au 1245
www.famagusta.com 457
www.athens.org.gr 6754
www.istanbul.com.tr 2980
….
Task 2
Write a menu driven Python program with the following functionality:
• When run, the program first opens the serverConnections.txt file for
reading, reads the contents line by line and creates a list of lists (say
serverConnectionsList), each small list in the big one being a list of
two elements, corresponding to a server name and the number of
connections for that server (for more information on how to do this,
Page 2 of 2
refer to the hint given at the end of this document). It then repeatedly
displays a menu with 5 options:
1. Get server connections
2. Find busiest server
3. Add new server
4. Backup files
5. Quit program
• When option 1 is selected, program asks the user to enter the server
name, searches for the server name and if it finds it, it returns the
number of connections for that particular server. If it doesn’t find it, it
returns a message stating that the server doesn’t exist in the file (or
some message like “unknown server”).
• When option 2 is selected, program finds the largest connections value
and then it returns the corresponding server.
• When option 3 is selected, program prompts the user for a new server
name and the corresponding number of connections and then adds the
server name and the corresponding number of connections at the end of
serverConnections.txt file and also updates the list of lists created
initially when the program was first executed (serverConnectionsList).
• When option 4 is selected, program opens a text file named
serversConnectionsBKUP.txt for writing and then copies the contents
of serverConnections.txt to it.
• When option 5 is selected, the program terminates.
[Hint: when the file is being read line by line in order to create the list of lists, you
should remove the newline character from each line before splitting it using the
split() function. This can be done by either using the
stringVariableName.rstrip(“\n”) or stringVariableName[:-1].
Remember that these methods do not (in fact cannot) modify the original line string.
They just produce a new one without the newline character which can then be used
with the split() function to produce a list to be added to the list of lists]
answer:-
def main():
file_variable = open("servers.txt" , "r")
listOFlist = []
for line in file_variable:
line = line.rstrip('\n')
mylist = line.split()
listOFlist.append(mylist)
choice = menu()
while choice != '5':
if choice == '1':
serverName = input("Enter the server name : ")
connections = findOfServer(serverName,listOFlist)
if connections == " ":
print(" server not found ")
else:
print("NUmber of Connection for server",serverName,"is",connections)
elif choice == '2':
busyServer = busiestServer(listOFlist)
print("busiest server is",busyServer)
elif choice == '3':
serverName = input("Enter new server you want to add : ")
connections = int(input("Enter the number of connection: "))
addServer(serverName , connections , listOFlist )
print("server added to the files")
elif choice == '4':
backupFile()
print("Backing Files up...")
print("Backed up")
else :
print("Invalid input")
print("Enter number between 1 and 5")
choice = menu()
if(choice == '5'):
print("program terminated")
def findOfServer(serverName,listOFlist):
for i in range(len(listOFlist)):
for j in range(len(listOFlist[i])):
if(listOFlist[i][j] == serverName):
return listOFlist[i][j+1]
return " "
def addServer(serverName , connections , listOFlist):
file_variable = open("servers.txt","a")
file_variable.write( serverName + '\t' + str(connections) + "\n")
file_variable.close()
#to add those records in list as well
appendList = [serverName , connections]
listOFlist.append(appendList)
def busiestServer(listOFlist):
largest = 0
for i in range(len(listOFlist)):
find_lar = int(listOFlist[i][1])
if(largest <= find_lar):
largest = find_lar
for i in range(len(listOFlist)):
find_server = int(listOFlist[i][1])
if(find_server == largest):
return listOFlist[i][0]
def backupFile():
file_variable = open("servers.txt","r")
file_backupServer = open("serversBACKUP.txt" , 'w')
for line in file_variable:
line = line.rstrip('\n')
file_backupServer.write(line + '\n')
file_backupServer.close()
file_variable.close()
def menu():
print("The main menu")
print("----------------")
print("1.Find server Conncetions")
print("2.Find busiest server ")
print("3.Add new server")
print("4.Backup files")
print("5.Quiet program")
print("----------------------------")
option = input("Enter your selection (1 - 5 ) : ")
return option
main()
From the exam,
Write a program which has two functions, main() and maximum(), with the following specifications:
• In the main() function, opens a text file named visitors.txt, which contains data relating to number of
visitors of several websites (structure and content of the file is given below)
• Reads the contents of the file, line by line and builds a list of lists, each small list containing one line of data as
two strings split from one line of data from the file (call this list visitorsList)
• Invokes the maximum() function from main(), passing the list visitorsList as the only argument
• The maximum()function uses the visitorsList to find the website with the maximum number of visitors
and returns this value to the main()
• The main()gets the maximum number of visitors returned from the maximum()function and displays it on the
screen
The structure and content of visitors.txt file:
www.melbourne.com.au 5463
www.roma.org.it 7777
www.famagusta.edu.cy 234
www.athena.com.gr 8953
www.newyork.com 3333
www.swinburne.edu.au 17990
www.istanbul.tr 3786
www.paris.com.fr 555
www.larnaca.cy 2534
www.london.org.en 965
[Hint: For a complete solution, this program should use exception handling to detect and respond to invalid data
from the file as well as possible errors occurring when attempting to open the file.]
answer:-
def main():
try:
visitors = open("visitors.txt", "r")
visitorsList = []
for line in visitors:
lineList = (line.rstrip()).split()
visitorsList.append(lineList)
max = maximum(visitorsList)
print("The maximum number of visitors is", max)
except ValueError:
print ("Error: Invalid input data!")
except IOError:
print ("Error: unable to open file!")
except:
print ("An error occurred!")
def maximum(visitorsList):
largest = 0
for i in range(len(visitorsList)):
find_lar = int(visitorsList[i][1])
if(largest <= find_lar):
largest = find_lar
return largest
main()
i will post chapter 11(Classes and Object-Oriented Programming) very soon