Search code examples
pythonpython-3.xalgorithmdata-structuresordereddict

Trying to code a complex algorithm with `OrderedDict` data Structure


I am trying to write an algorithm:

i have this input of OrderedDict data type like the following:

odict_items([(3, [(0, 1), (1, 1), (1, 1)]), (11, [(0, 0), (1, 1), (1, 1)]), (12, [(0, 0), (1, 1), (1, 1)])])

I am trying to write a function to added the number of same tuple in the each key for example the expected output like the following: if there is (1,1) same tuple then 1 and if twice the 2 and so one:

odict_items([(3, [(0, 1), (1, 1), (1, 1)],2), (11, [(0, 0), (1, 1), (1, 1)],2), (12, [(0, 0), (1, 0), (1, 1)]),1])

this is my try but how to improve it and add it to the OrderedDict ?

def foo(OrderedDict):
    listOfDic = list(makeDataStruc().items())
    tupleCounter = 0
    for i in range(len(listOfDic[1])):
        if listOfDic[1][1][i][0] == 1 and listOfDic[1][1][i][1] == 1:
            tupleCounter += 1
    return tupleCounter

Where am i making error?


Solution

  • I am making the following assumptions,

    • You simply want to add the count of (1,1) to the OrderedDict value
    • You don't want to create a new data structure which overrides the current OrderedDict.
    • You can modify the original Dictionary

    Now based on the information available in the question and the above mentioned assumptions, one possible solution could be to replace every value with a list containing two elements, i.e. `[original value, count of (1, 1)]

    from collections import OrderedDict
    
    odict_items = [(3, [(0, 1), (1, 1), (1, 1)]),
                   (11, [(0, 0), (1, 1), (1, 1)]),
                   (12, [(0, 0), (1, 1), (1, 1)])]
    
    my_odict = OrderedDict()
    
    for item in odict_items:
        k, v = item
        my_odict[k] = v
    

    Now count the occurrence of (1,1) in every value and update the values accordingly

    pattern_to_find = (1, 1)
    
    for key, value in my_odict.items():
        tuple_count = value.count(pattern_to_find)
        new_value = [value, tuple_count]
        my_odict[key] = new_value
    

    Now the dictionary has the following contents:

    OrderedDict([(3, [[(0, 1), (1, 1), (1, 1)], 2]),
                 (11, [[(0, 0), (1, 1), (1, 1)], 2]),
                 (12, [[(0, 0), (1, 1), (1, 1)], 2])])
    

    Now you can create additional function to access only the value or tuple count

    # Returns the count of (1, 1) only
    def get_count(my_dict, key):
        return my_dict[key][1]
    
    # Return the original value only
    def get_tuple(my_dict, key):
        return my_dict[key][0]
    

    So you can use them like this

    print(my_odict[3])
    # [[(0, 1), (1, 1), (1, 1)], 2]
    
    print(get_count(my_odict,3))
    # 2
    
    print(get_tuple(my_odict, 3))
    # [(0, 1), (1, 1), (1, 1)]