I need a sanity check. The top1
and top2
functions are nearly the same but output very different contents for the freq
variable. Why? What am I not seeing?
def top1(nums, k):
count = {}
for i in nums:
if i not in count:
count[i] = 1
else:
count[i] += 1
freq = (len(nums) + 1) * [[]]
print('count', count)
print('freq', freq)
for n, c in count.items():
freq[c].append(n)
print('freq', freq)
def top2(nums, k):
count = {}
for n in nums:
count[n] = 1 + count.get(n, 0)
freq = [[] for i in range(len(nums) + 1)]
print('count', count)
print('freq', freq)
for n, c in count.items():
freq[c].append(n)
print('freq', freq)
top1([1], 1)
print()
top2([1], 1)
OUTPUT
count {1: 1}
freq [[], []]
freq [[1], [1]]
count {1: 1}
freq [[], []]
freq [[], [1]]