1

I'm doing this question on HackerRank.

Based on their initial test case, the code seems to be working fine, but there are plenty of issues when it comes to larger test cases. The question requires us to output the number of occurrences of each string in the order of the input, so I am wondering is the use of a dictionary the cause of the issue, as a dictionary may not follow the order of input even when iterating over it.

import sys

d = {}

for line in sys.stdin.readlines()[1:]:
    if line.strip('\n') in d:
        d[line.strip('\n')] += 1
    
    else:
        d[line.strip('\n')] = 1
    
sorted_dict = sorted(d.items(),key=lambda x:x[1])

print(len(d))

for tup in sorted_dict:
    print(tup[1],end=' ')
Xiddoc
  • 3,369
  • 3
  • 11
  • 37
Prometheus
  • 11
  • 1
  • 2
    You don't use the input order in this code -- you explicitly sort the items by name. Iteration over dictionaries in Python3.7 and higher gives you the insertion order. – Paul Hankin May 03 '21 at 11:08

1 Answers1

-1

You don't use the input order in this code -- you explicitly sort the items by name. Iteration over dictionaries in Python3.7 and higher gives you the insertion order.

-- comment by Paul Hankin

wjandrea
  • 28,235
  • 9
  • 60
  • 81