1. What I learned
a. Quotes
There is no difference between single and double quotes in Python. However, in general, single quotes are used for symbols and identifiers, and double quotes are used for text. In addition, when using different quotes between quotes, the backspace () should be added as follows.
print('It\'s me')
#It will print 'It's me'
b. Making a list a string
To make a list a string, write as follows.
mess_list = ['H','e','l','l','o']
mess = ''.join(mess_list)
print(mess)
#I will print 'Hello world'
c. Extracting keys and values in a dictionary
.items() extracts a key and a value pair at once.
samp_dict = {'a': 0, 'b': 1}
for key, value in samp_dict.items():
print(key, value)
#I will print (a 0) and (b 1)
2. How I sloved
I had to count the number of times for each domain. So I used a dictionary. The input was a list of the factors being a pair of counts and domains. I divided each element into counts and domains. And the domain was divided based on ‘.’. I combined domains divided by ‘.’ to create sub-domains. Counts were added if subdomains existed in the dictionary; otherwise, new elements were added. The output was a list of counts and pairs of subdomains.
3. Code
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
dom_dict = {}
for e in cpdomains:
cnt, subdomain = e.split(' ')
sub = subdomain.split('.')
for i in range(len(sub)):
domain = '.'.join(sub[i:len(sub)])
if domain in dom_dict:
dom_dict[domain] += int(cnt)
else: dom_dict[domain] = int(cnt)
output_list = []
for subdom, cnt in dom_dict.items():
output_list += [str(cnt)+ ' '+ subdom]
return output_list
4. Result
Runtime : 44 ms(97.28%), Memory usage : 14.2 MB(100.00%)
(Runtime can be different by a system even if it is a same code.)