In: Computer Science
LANGUAGE PYTHON 3.7
Write a collection class named "Jumbler". Jumbler takes in an optional list of strings as a parameter to the constuctor with various strings. Jumbler stores random strings and we access the items based on the methods listed below.
Jumbler supports the following methods:
add() : Add a string to Jumbler
get() : return a random string from Jumbler
max() : return the largest string in the Jumbler based on the
length of the strings in the Jumbler.
iterator: returns an iterator to be able to iterate through all the
strings in the jumbler.
(*Note: Please up-vote. If any doubt, please let me know in the comments)
The class code and driver program code for testing are given below:
Class Code:
import random
class jumbler():
def __init__(self,string_list=[]):
self.mystrings = string_list #will assign supplied list if given by user or an empty list otherwise
#add method takes new string to be added as an argument
def add(self,new_string=""):
if new_string == "":
new_string = input("Please enter the string to be added: ") #Ask for string if not supplied while calling the method
self.mystrings.append(new_string)
def get(self):
random_index = random.randrange(0,len(self.mystrings)) #generating a random integer within range to use as index
return self.mystrings[random_index]
def max(self):
max_str = self.mystrings[0] #initialize max to be the first string in the list
for i in range(0,len(self.mystrings)):
if len(self.mystrings[i])>len(max_str):
max_str = self.mystrings[i]
return max_str
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n < len(self.mystrings):
result = self.mystrings[self.n] #return string at nth position
self.n += 1
return result
else:
raise StopIteration
Main driver program code for testing the class:
#main testing
J1 = jumbler(["This","is it"]) #Creating an object
print(J1.max())
J1.add("foolish") #testing add method
J1.add("pseudo turtle truth")
J1.add()
print(J1.get()) #testing get method
#testing the iterator using a for loop
for i in J1:
print(i)
Code screenshot (for indentation reference):
Test Output Screenshot: