Given m sets of integers that have n elements.
I have the below code, which outputs the element which occurs maximum number of times.
def find_element_which_appeared_in_max_sets(input_set):
hash_table = {}
# count the frequencies
for pair in input_set:
for i in range(0,len(pair)):
if pair[i] in hash_table:
hash_table[pair[i]] = hash_table[pair[i]] + 1
else:
hash_table[pair[i]] = 1 # first occurence
# scan and find the element with highest frequency.
max_freq = 0
for elem in hash_table:
if hash_table[elem] > max_freq:
max_freq = hash_table[elem]
max_occured_elem = elem
return max_occured_elem
input_set = {(5,4),(3,2),(4,3),(8,3)}
print ""+str(find_element_which_appeared_in_max_sets(input_set))
Output:
3
Is there a more neater/elegant way of iterating through individual elements of the set?
You can simply use collections.Counter
and itertools.chain.from_iterable
, like this
def find_element_which_appeared_in_max_sets(input_set):
return Counter(chain.from_iterable(input_set)).most_common(1)[0][0]
chain.from_iterable(input_set)
will flatten out the input set of tuples to get a single iterable which gives values from each of the tuples, one by one.
Then Counter
counts the number of times each and every item occurred and maintains the item and its count as a dictionary.
Then the most_common(1)
call on Counter
returns a list of items with top n
(parameter passed to it) maximum number of occurrences, in the format (item, count)
. Since we are only interested in the item, we return the first item with [0][0]
.
Using only built-ins, without standard library imports:
def find_element_which_appeared_in_max_sets(input_set):
hash_table = {}
for pair in input_set:
for item in pair:
#enhanced as proposed by thefourtheye
hash_table[item] = hash_table.get(item, 0) + 1
max_occured_element = max(hash_table, key=hash_table.get)
return max_occured_element
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With