In: Computer Science
In python! please be thorough and read question carefully :) if possible, give explanation for code
We’re going to create a class which stores information about product ratings on a website such as Amazon. The ratings are all numbers between 1 and 5 and represent a number of “stars” that the customer gives to the product. We will store this information as a list of integers which is maintained inside the class StarRatings. You will be asked to write the following:
1) A constructor which takes and stores the product name.
2) A function “giveRating” which takes an integer between 1 and 5 and stores it. If the number is outside that range, it should not store the number.
3) A function “calcAverage” which returns the average of the ratings. This can be done in linear time
4) A function getStarCount which returns a five element list containing the count of the number of ratings for each star. For example if the ratings were 5,5,2,3,1, and 1, this function would return [2,1,1,0,2] (2x 1 stars, 1x 2 stars, 1x 3 stars, 0x 4 stars, 2x 5 stars)
5) Sometimes a mistake is made and the site posts the same product twice. If that’s the case we will need to “add” the two star ratings together to produce a larger list with the result. write a function so that two StarRatings class objects can be “added” together using the + operator
6) If the product manufacturer pays us, we can adjust the star ratings by an amount. Allow for “multiplication” of every star rating by a constant amount. For example if the StarRatings Object is sr, allow for “sr1.5”. However, the star ratings must ALWAYS remain integers. In that example all 1 star reviews would become 2 stars (11.5 = 1.5, rounded to integer would be 2), 2 star reviews would be 3(2*1.5 = 3) etc.
Program Code Screenshot:
Sample output:
The screenshots are attached below for reference.
Please follow them for proper indentation and output.
Program to copy:
import math
class StarRatings:
def __init__(self,name):#constructor of class
self.pname=name
self.ratings=[]
def giveRating(self,r):
if r in [1,2,3,4,5]:#check rating value and append only if it is
valid
self.ratings.append(r)
def calcAverage(self):
return sum(self.ratings)//len(self.ratings)#calculate and return
average
def getStarCount(self):
res=[0,0,0,0,0]
for i in self.ratings:#for each rating in list increment it in res
list for getting count
res[i-1]+=1
return res
def add(self,other):
self.ratings=self.ratings+other.ratings#add two ratings list when
there are two same products
def adjust_ratings(self,n):
for i in range(len(self.ratings)):
if self.ratings[i]*n > 5:
self.ratings[i]=(5)
else:
self.ratings[i]=math.ceil(self.ratings[i]*n)#adjust the rating
after multplication
s1=StarRatings("P1")
s1.giveRating(2)
s1.giveRating(2)#create object and giveRating
s1.giveRating(3)
s1.giveRating(4)
s1.giveRating(5)
s1.giveRating(5)
print(s1.getStarCount())#get the count
s1.adjust_ratings(1.5)
print(s1.getStarCount())