Timus 2033. Devices – Python solution (Dictionary)


The puzzle is from Timus (submit your solution at this URL http://acm.timus.ru/problem.aspx?space=1&num=2033)

There are 6 friends, and the input tells you the names of these friends (useless), the phones they have and the corresponding prices. The same brand may be purchased at difference prices, and only the minimal price should be recorded.

So the idea is to use a dictionary structure in Python to easily associate the keys to the values (key-value pair). The key items are the names of the phones and the values would be the list containing the prices. The first loop deals with inputs, using has_key() to check if a key (phone) has been entered in the database, if yes, use append() to push the price to the list.

The second loop will look for the phone that has the most elements in the price list that is the number of friends who buy this phone. If it is the same number, then choose a smaller price.

dic = {}

for _ in range(6):
    name = raw_input()
    phone = raw_input()
    price = int(raw_input())
    if dic.has_key(phone):
        dic[phone].append(price)
    else:
        dic[phone] = [price]
        
name = ""
price = 999999999
c = -9999
for phone in dic.keys():
    curp = min(dic[phone])
    curc = len(dic[phone])
    if curc > c:    # more friends buy this phone
        c = curc
        price = curp
        name = phone
    elif curc == c: # choose a smaller price
        if curp < price:
            c = curc
            price = curp
            name = phone
            
print name

--EOF (The Ultimate Computing & Technology Blog) --

GD Star Rating
loading...
363 words
Last Post: Adsense Earnings with [One Visit Per Second]
Next Post: Win8.1 Update Takes Ages

The Permanent URL is: Timus 2033. Devices – Python solution (Dictionary) (AMP Version)

3 Comments

  1. Renata

Leave a Reply