Iterate individual elements in python sets

Given m, sets integers containing n elements.

I have the code below that outputs an element that occurs the 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 neat / elegant way to iterate through the individual elements of a set?

+4
source share
2 answers

You can just use collections.Counterand itertools.chain.from_iterablelike that

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 smooth the input set of tuples to get one iterative, which gives the values ​​from each tuple one by one.

Counter , , .

most_common(1) Counter n ( ) (item, count). , [0][0].

+4

:

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
+4

Source: https://habr.com/ru/post/1624416/


All Articles