collections.Counter() | HackerRank Solutions

admin
By -
0

This problem is not that much  hard it pretty ease if you know things likes input,data types, loops and mapping and dictionary  and here we have total  shoe sizes, and  multiple shoe sizes which some are duplicated and total customers and each customer desired shoe size if it existed in  we store its price and at end we just need sum of our total  selling , we using collections module Counter method which gives use each shoe sizes occurrences we have as key:value pairs in dict form and Counter can take , string, list of digits etc.




Below we provide two code an brute force and another more optimized code both are Big(O)n cause both runs single loops  and Space maybe one for log(1).

Problem: https://www.hackerrank.com/challenges/collections-counter/problem?isFullScreen=true

Code:

# Enter your code here. Read input from STDIN. Print output to STDOUT
#Naive Code
'''
O(n)    The code consists of a while loop that iterates 'z' times, where 'z' is the total number of customers. Inside the loop, there are constant time operations such as checking if a shoe size is in the Counter dictionary and updating the counts. Therefore, the overall time complexity is O(n) where n is the total number of customers.
'''
'''
from collections import Counter
#x = int(input("Enter no.Total Shoes:"))
#y = list(map(int, input("Enter shoe sizes: ").split()))
#z = int(input("Enter total customers:"))
x = int(input())
y = list(map(int, input().split()))
z = int(input())
counts = Counter(y)  
total_selling = []
count = 1
def total_sells(count, z):
    while count<=z:
        #print("hello")
        #x,y =input("Enter X,Y:").split()
        x,y =input().split()
        if int(x) in counts and counts[int(x)]>=1:
            total_selling.append(int(y))
            counts[int(x)]=counts[int(x)]-1
            #print(counts[int(x)])
        count+=1
    return print(sum(total_selling))

total_sells(count, z)
'''

# more optimized code:
from collections import Counter

def total_sells(shoe_sizes, num_customers):
    counts = Counter(shoe_sizes)
    total_revenue = 0

    for _ in range(num_customers):
        size, price = map(int, input().split())
        if counts[size] > 0:
            total_revenue += price
            counts[size] -= 1  # Decrease the count of that shoe size
           
    print(total_revenue)

# Read inputs
x = int(input())  # Total number of shoes, unused
shoe_sizes = list(map(int, input().split()))  # Shoe sizes available
z = int(input())  # Number of customers

# Call the function to calculate total revenue
total_sells(shoe_sizes, z)






Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*