3 10-min (at least they\'re supposed to be, I\'m stuck) python exercises. Please
ID: 3829200 • Letter: 3
Question
3 10-min (at least they're supposed to be, I'm stuck) python exercises. Please help!
1. write a function that is given a list of string values and a character value, returns the integer number of items that start with the given character. Use the following function definition def CountItems(items, letter):
2. Create a class named Student that has public data members kind (string) and scores (list of integer values). Provide a constructor that takes a parameter for initializing the kind and initializes the list to an empty list. Provide a public method Add(value) to add new items to the end of the list. Also provide a public method Lowest() that returns lowest of values in list or if there are no values in the list, return None.
3. Write a class MyClass which has one data member data which is a dictionary. Create a function load which takes in a filename and reads the lines to load elements in the dictionary and returns the number of lines read. Each line of the file contains item name and number of items separated by a vertical bar ('|') character. Each element in the dictionary is a key-value pair: name (string) and count (int). You must parse each line to store in the dictionary and if the value is invalid do not add it to the dictionary. You must handle when the file does not exist and return -1. (Hint: use try-except for exception handling, also make sure key values are stripped off white spaces). Write another function find which takes in an integer "num" and returns a list of keys from the dictionary which have the value same as num.
Please don't post without complete running code. Thank you!
Explanation / Answer
# 1 rite a function that is given a list of string values and a character value,
# returns the integer number of items that start with the given character.
def CountItems(items, letter):
count = 0
for item in items:
if item[0] == letter:
count += 1
return count
class Student:
def __init__(self, kind):
self.kind = kind
self.scores = []
def getKind(self):
return self.kidn
def getScores(self):
return self.scores
def Add(self, value):
self.scores.append(value)
def Lowest(self):
if not self.scores:
return None
return min(self.scores)
class MyClass:
def __init__(self):
sefl.data = {}
def load(self, filename):
count = 0
try:
with open(filename, "w") as fh:
for line in fh:
count += 1
try:
(name, itemCount) = line.split("|")
data[name.strip()] = int(itemCount.strip())
except:
continue
except:
return -1
def find(self, num):
keys = []
for key in self.data:
if self.data[key] == num:
keys.append(key)
return keys
# code link: https://paste.ee/p/oIkYJ
# ran few cases and it is working fine, if you face any issue comment and I will take a look.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.