Reputation: 333
A balanced array would be an array in which each element appears the same number of times.
Given an array with n elements: return a dictionary with the key as the element and the value as the count of elements needed to balance the given array
Examples
elements = ["a", "b", "abc", "c", "a"]
Expected output: {"b":1, "abc":1, "c":1}
Because there are 2 a
, we need 1 more of b, abc, c
Hope that helps
Upvotes: 1
Views: 1293
Reputation: 1
def return_missing_balanced_numbers(input):
input.sort()
counts = []
new_dict = {}
for item in input:
counts.append(input.count(item))
for item in input:
item_count = input.count(item)
if item_count < max(counts):
new_dict[item] = max(counts)-item_count
return new_dict
Output:
✓Test #1
✓Test #2
✓Test #3
✓Test #4 <-- created my own test case :)
Upvotes: 0
Reputation: 11
During frequency count we can also store the max value which we need to subtract those values which are less than that max value to get balance score for each element
def return_missing_balanced_numbers(input):
dd = {}
mv = 0
for i in input:
dd[i] = 1 + dd.get(i, 0)
mv = max(mv, dd[i])
res = {}
for k, v in dd.items():
if mv != v:
res[k] = abs(mv - v)
return res
Upvotes: 0
Reputation: 33
Without using Counter and lamba. Keeping it simple!
You might want to look into Dictionary Comprehension
def return_missing_balanced_numbers(input):
# Write your code here
my_dict = {}
for i in input:
if i in my_dict:
my_dict[i] += 1
else:
my_dict[i] = 1
return {a:max(my_dict.values())-b for (a,b) in my_dict.items() if b!= max(my_dict.values())}
Upvotes: 1
Reputation: 1
count = {}
for element in input:
count[element] = count.get(element,0) + 1
return {key:max(count.values()) - value for (key,value) in count.items() if value != max(count.values())}
Upvotes: 0
Reputation: 327
This isn't homework but a Meta Data Engineer interview prep question ;)
This is my solution without using Counter
lst = ["a", "b", "abc", "c", "a"]
tuples = [(i, lst.count(i)) for i in lst]
tuples.sort(key=lambda x: -x[1])
max_value = tuples[0]
{k: max_value[1] - v for k,v in tuples if v < max_value[1]}
Upvotes: 0
Reputation: 678
You can use the Counter
to calculate frequencies and then get required frequencies by iterating through it -
from collections import Counter
elements = ["a", "b", "abc", "c", "a"]
counts = Counter(elements)
max_freq = max(counts.values()) # 2 in this case
ans = {k: max_freq - v for k, v in counts.items() if v < max_freq}
print(ans)
outputs -
{'b': 1, 'abc': 1, 'c': 1}
Upvotes: 1