Advertisement
aaaranes

CMSC 12 - 2nd Exam - Problem Solving

Nov 22nd, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | Source Code | 0 0
  1. # Function for counting and returning the 2 most instances in a given list parameter
  2. def count(list1):
  3.  
  4.     # initialize dictionary (dict is not recommended name for the dictionary as it might cause some errors)
  5.     dict = {}
  6.    
  7.     # count
  8.     for element in list1:
  9.         if element in dict:
  10.             dict[element] += 1
  11.         else:
  12.             dict[element] = 1
  13.    
  14.     # initialize elements and corresponding values to compare
  15.     element1 = "None"       # String None to annotate
  16.     element2 = "None"
  17.     first = 0
  18.     second = 0
  19.  
  20.     if len(dict) > 0:
  21.         for key in dict:
  22.             if dict[key] > first:
  23.                 element2 = element1
  24.                 second = first
  25.                 element1 = key
  26.                 first = dict[key]
  27.             elif dict[key] > second:
  28.                 element2 = key
  29.                 second = dict[key]
  30.  
  31.     # put results in a list
  32.     output = [element1, element2]
  33.  
  34.     return output
  35.  
  36.  
  37. # Main part
  38. list1 = ["a","a","a","b","c","c","d","d","d","d","b","a"]
  39. output = count(list1)
  40. print("The two items with most instances are "+output[0]+" and "+output[1])
  41.  
Tags: counter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement