- How many permutations are there of the letters of the string
"elephant"?
Ans: There are 8 factorial permutations:
8! = 40,320 permulations.
- How do you change a string into a list of characters? Ans:
input_string = input("Enter a Jumble string: ")
input_list = list(input_string)
- How do you obtain all the permutations of a list? Ans:
perms = list(itertools.permutations(input_list)
Don't forget import itertools at the top of your script.
- How to you change the list of of tuples from Exercise 3 into a list of
strings? Ans:
output_list = [ ]
for p in perms:
output_list.append("".join(p))
- Choose six list methods from the
Builtin Methods document and test them. Ans:
a = list[45, 21, 87, 45, 1]
a.insert(1, 99)
print(a)
a.reverse( )
print(a)
print(a.count(45))
a.append(999)
print(a)
a.sort( )
print(a)
# Output
45 21 87 45 1
45 99 87 45 1
1 45 87 21 99 45 999
1 21 45 45 87 99 999
- Extract the specified method from these scripts. Do not include the input
and print statements in the extracted method.
a. # Method name: miles_to_km
# Input parameter: miles
# Return value: kilometers
# Original Script:
miles = input("Enter the distance in miles: ")
kilometers = miles * 5280 * 12 * 2.54 / 100000.0
print(f"Distance in km: {kilometers}.")
# Script with method extracted:
def miles_to_km(miles):
kilometers = miles * 5280 * 12 * 2.54 / 100000.0
return kilometers
m = input("Enter the distance in miles: ")
km = miles_to_km(m)
print("Distance in km:", km)
b. # Method name: collapse_list
# Input parameter: input_list
# Return value: output_string
# Original script:
input_list = eval(input("Enter a list of strings: ")
output_string = "".join(input_list)
print(output_string)
# Script with method extracted
def collapse_list(the_list):
output_string = "".join(the_list)
return output_string
input_list = eval(input("Enter a list of strings: ")
s = collapse_list(input_list)
print("Collapsed list:", s)
c. # Method name: vowel_count
# Input parameter: input_string
# Return value: number of vowels in input string
input_string = input("Enter a string: ")
v_count = 0
for char in input_string:
if char.upper( ) == "A" or \
char.upper( ) == "E" or \
char.upper( ) == "I" or \
char.upper( ) == "O" or \
char.upper( ) == "U":
v_count += 1
print("Vowel count: " + str(vowel_count))
# Script with extracted method
def vowel_count(input_string):
v_count = 0
for char in input_string:
if char.upper( ) == "A" or \
char.upper( ) == "E" or \
char.upper( ) == "I" or \
char.upper( ) == "O" or \
char.upper( ) == "U":
v_count += 1
return v_count
input_string = input("Enter a string: ")
count = vowel_count
print("Vowel count is", count)
- What is the difference between this list and tuple?
a1 = [5, 2, 4]
a2 = (5, 2, 4)
Check the datatypes of the objects a1 and
a2 like this:
print(type(a1))
print(type(a2))
Ans: a1 is a list, which is mutable (can be changed), a2 is a tuple,
which is immutable (cannot be changed).
Here is the outp
- We know about lists and tuples: they are examples of aggregate datatypes because
a list or tuple is each an aggregate or collection of objects. Later today, we will see that
a dictionary is also an aggregate datatype.
- A list is mutable (changeable) but a tuple is immutable (not changable).
- For example:
# Create and use list of strings
a = ['cherry', 'grape', 'kiwi', 'pear']
print(a[2])
a[2] = 'apple'
for f in a:
print(f)
# Create and use tuple of strings
b = ('cherry', 'grape', 'kiwi', 'pear')
print(a[2])
for f in b:
print(f)
- However, when we try to change the tuple, we get an error:
b[2] = 'apple'
# Error message:
TypeError: 'tuple' object does not support item assignment
- Immutable objects are considered to be safer than mutable objects
because they can't be changed inadvertantly.
- str objects (strings) are similar to tuples of characters:
(a) individual characters of a str object can be accessed by index
(b) str objects are immutable.
Try out this script:
s = 'elephant'
for char in s:
print(s)
print(s[4])
s[4] = 'k'
- A dictionary is an aggregate datetype whose values are
accessed by key.
- Summary table:
Datatype | How to Access | Immutable |
list | By index | No |
tuple | By index | Yes |
str | By index | Yes |
dict | By key | No |
- An example of the using a dictionary:
d = { 'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(d)
print(d['two'])
- Here is another example of a dictionary:
c = {'cherry': 4.36, 'grape':2.81, 'kiwi':3.60}
- In the dict object c, the key
is the name of the fruit, the value is the price per pound.
- A script that uses the dictionary c:
print(c['kiwi'])
for key in c:
print(key, c[key])
# Change the price of grapes:
c['grape'] = 2.39
# Add apple to the dictionary:
c['apple'] = 1.45
print(c)
- Practice Problem: The file grades.txt contains the course name, credit hours, and grade
for each course that Raymond Hoffman has taken. Use this dictionary to compute his gpa:
dictionary = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0}
# Ans:
dictionary = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0}
total_credit_hours = 0
total_grade_points = 0.0
fin = open("grades.txt", "r")
fin.readline( )
line = fin.readline( )
while line != "":
fields = line.split(",")
course_number = fields[0].strip( )
credit_hours = int(fields[1].strip( ))
grade = fields[2].strip( )
grade_points = dictionary[grade]
# print(course_number, credit_hours, grade_points)
total_credit_hours += credit_hours
total_grade_points += grade_points * credit_hours
# print(total_credit_hours, total_grade_points)
line = fin.readline( )
gpa = total_grade_points / total_credit_hours
print("GPA for Raymond Hoffman: ", round(gpa, 2))
- Write an interactive script that repeatedly inputs the English word for a number from one to nine,
and translates it into Spanish. Terminate script with the empty string
"". Sample session:
Enter English number: five
Spanish word for five is cinco.
Enter English number: twelve
Spanish word for twelve not in dictionary.
Enter English number:
Script terminated.
# Ans:
d = {'one': 'uno', 'two': 'dos': 'three': 'tres', 'four': 'cuatro', 'five': 'cinco', \
'six': 'seis', 'seven': 'siete', 'eight', 'ocho', 'nine', 'nueve'}
# Set eng_word to dummy value which is not "",
eng_word = 'abc'
while eng_word != "";
eng_word = input("Enter English word for number between 1 and 9: ")
# Look up English word in dictionary.
if eng_word in d:
span_word = d[eng_word]
print("Spanish word for", eng_word, "is", span_word)
else:
print("English word not in dictionary")