In: Computer Science
PYTHON QUESTION:
- Write the body of a function most_ending_digit(L) that consumes a non-empty list of natural numbers L and return the single digit that occurs most frequently at the end of the numbers in the list. The function returns the smallest digit in the case of a tie. Your function should run in O(n) time. Do not mutate the passed parameter.
def most_ending_digit(L)
'''
Returns the single digit that occurs most frequently
as the last digit of numbers in L. Returns the
smallest in the case of a tie.
most_ending_digit: (listof Nat) -> Nat
Requires: len(L) > 0
Examples:
most_ending_digit([1,2,3]) => 1
most_ending_digit([105, 201, 333,
995, 9, 87, 10]) => 5
'''
## CODE
- Write the body of a function __eq__ method for this class that returns True if the two objects compared are Movie objects each having the same fields and False otherwise.
class Movie:
'''
Fields:
name (Str),
year (Nat),
rating (Nat)
'''
def __init__(self, n, y, r):
self.name = n
self.year = y
self.rating = r
def __eq__(self, other):
'''
Returns True if the movies are equal
__eq__: Movie Any -> Bool
'''
##CODE
def most_ending_digit(l):
res=[]
for i in l:
res.append(i%10)#get the last digits
s=list(set(res))
s.sort()#sort list to return the least value digit in case of
tie
sc=[]
for i in s:
sc.append(res.count(i))#get the count of each digit
return s[sc.index(max(sc))]#return the value of the maximum count
digit
print(most_ending_digit([1,2,3]))#call the function and print
output.
print(most_ending_digit([105,201,333,995,9,87,10]))
Screenshots:
The screenshots are attached below for reference.
Please follow them for proper indentation.
2)
class Movie:
def __init__(self, n, y, r):
self.name = n
self.year = y
self.rating = r
def __eq__(self, other):
if other.name==self.name and other.year==self.year and
other.rating==self.rating:#compare the fields
return True#return true if fields are same
else:
return False
m1=Movie("n1",2019,5)
m2=Movie("n1",2019,5)
print(m1.__eq__(m2))
Screenshots:
The screenshots are attached below for reference.
Please follow them for proper indentation.
Please upvote my answer. Thank you.