Data Types - Reference Answers
Assignment 1
Write code for the following variable and implement each feature as required
name = " alberT"
# 1 Remove the spaces on both sides of the value of the variable name, and print the result
print(name.strip())
# 2 Check whether the value of the variable name starts with "al", and print the result
print(name.startswith('al'))
# 3 Check whether the value of the variable name ends with "T", and print the result
print(name.endswith('T'))
# 4 Replace "l" in the value of the variable name with "p", and print the result
print(name.replace('l', 'p'))
# 5 Split the value of the variable name on "l", and print the result.
print(name.split('l'))
# 6 Convert the value of the variable name to uppercase, and print the result
print(name.capitalize())
# 7 Convert the value of the variable name to lowercase, and print the result
print(name.lower())
# 8 Print the 2nd character of the value of the variable name?
print(name[2])
# 9 Print the first 3 characters of the value of the variable name?
print(name[:3])
# 10 Print the last 2 characters of the value of the variable name?
print(name[-2:])
# 11 Print the index of "e" in the value of the variable name?
print(name.index('e'))
# 12 Get a subsequence without the last character. For example: from albert get alber
print(name[:-1])
Assignment 2
Given the list data=[‘albert’,18,[2000,1,1]], extract the name, age, and the year, month and day of birth from the list and assign them to separate variables.
data = ['albert', 18, [2000, 1, 1]]
name = data[0]
age = data[1]
birthday = data[2]
year = birthday[0]
month = birthday[1]
day = birthday[2]
Assignment 3
Given the collection of values [11,22,33,44,55,66,77,88,99,90], save all values greater than 66 under the first key of a dictionary and all values less than 66 under the second key, i.e.: {‘k1’: all values greater than 66, ‘k2’: all values less than 66}
a = {'k1': [], 'k2': []}
c = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
for i in c:
if i > 66:
a['k1'].append(i)
elif i < 66:
a['k2'].append(i)
print(a)
Exercise 4
- The list l=[‘a’,‘b’,1,‘a’,‘a’], whose elements are all immutable types: remove duplicates to get a new list; the new list does not need to keep the original order
- Building on the previous question, keep the original order of the list
- For the following list, whose elements are mutable types, remove duplicates to get a new list; the new list must keep the original order
l = [
{'name': 'albert', 'age': 18, 'sex': 'male'},
{'name': 'james', 'age': 35, 'sex': 'male'},
{'name': 'taylor', 'age': 25, 'sex': 'female'},
{'name': 'albert', 'age': 18, 'sex': 'male'},
{'name': 'albert', 'age': 18, 'sex': 'male'},
]
l = ['a', 'b', 1, 'a', 'a']
# 1 Unordered deduplication
print(set(l))
# 2 Ordered deduplication
# Method 1: without a set
l1 = []
for i in l:
if i not in l1:
l1.append(i)
print(l1)
# Method 2: with the help of a set
l1 = []
s = set()
for i in l:
if i not in s:
s.add(i) # add an element to the set
l1.append(i)
print(l1)
# Deduplicating dictionaries
l = [
{'name': 'albert', 'age': 18, 'sex': 'male'},
{'name': 'james', 'age': 35, 'sex': 'male'},
{'name': 'taylor', 'age': 25, 'sex': 'female'},
{'name': 'albert', 'age': 18, 'sex': 'male'},
{'name': 'albert', 'age': 18, 'sex': 'male'},
]
# print(set(l)) # error: unhashable type: 'dict'
s = set()
l1 = []
for item in l:
val = (item['name'], item['age'], item['sex'])
if val not in s:
s.add(val)
l1.append(item)
print(l1)
# Define a function that works for both hashable and unhashable types (covered in the next stage of the course)
def func(items, key=None):
s = set()
for item in items:
val = item if key is None else key(item)
if val not in s:
s.add(val)
yield item
print(list(func(l, key=lambda dic: (dic['name'], dic['age'], dic['sex']))))
Exercise 5
Use at least two methods to count the occurrences of each word in the string s=‘hello albert albert say hello world world’. The result should look like:
{'hello': 2, 'albert': 2, 'say': 1, 'world': 2}
s = 'hello albert albert say hello world world'
# Method 1
list1 = s.split()
dict1 = {}
for item in list1:
if item in dict1:
dict1[item] += 1
else:
dict1[item] = 1
print(dict1)
# Method 2
dict2 = {}
words = s.split()
for word in words:
dict2[word] = s.count(word)
print(dict2)
# Method 3
dict3 = {}
words = s.split()
for word in words:
dict3.setdefault(word, s.count(word))
print(dict3)
Exercise 6
Implement a simple shopping program with the following requirements: first print the product details, then ask the user to enter a product name and quantity, and add the product name, price and quantity to the shopping list. If the input is empty or otherwise invalid, ask the user to enter it again
msg_dic = {
'apple': 10,
'tesla': 1000000,
'mac': 10000,
'iphone': 8000,
'chicken': 30,
'pen': 3,
'ruler': 5
}
msg_dic = {
'apple': 10,
'tesla': 1000000,
'mac': 10000,
'iphone': 8000,
'chicken': 30,
'pen': 3,
'ruler': 5
}
goods_list = []
while True:
for product, price in msg_dic.items():
print('product: %s, price: %s' % (product, price))
choice = input('please choose product>>:').strip()
if choice == 'q': # user can quit the program by inputting 'q'
break
elif choice not in msg_dic:
print('The product you choose is invalid')
continue
else:
while True:
count = input('please input the number of the product>>:').strip()
if not count.isdigit():
print('The content you input is not number')
continue
else:
goods_list.append((choice, msg_dic[choice], count))
print(goods_list)
break