I have the following OrderedDict
:
OrderedDict([('r', 1), ('s', 1), ('a', 1), ('n', 1), ('y', 1)])
This actually presents a frequency of a letter in a word.
In the first step - I would take the last two elements to create a union tuple like this;
pair1 = list.popitem()
pair2 = list.popitem()
merge_list = (pair1[0],pair2[0])
new_pair = {}
new_pair[merge_list] = str(pair1[1] + pair2[1])
list.update(new_pair);
This created for me the following OrderedList:
OrderedDict([('r', 1), ('s', 1), ('a', 1), (('y', 'n'), '2')])
I would like now to iterate over the elements, each time taking the last three and deciding based on the lower sum of the values what is the union object.
For instance the above list will turn to;
OrderedDict([('r', 1), (('s', 'a'), '2'), (('y', 'n'), '2')])
but the above was:
OrderedDict([ ('r', 1), ('s', 2), ('a', 1), (('y', 'n'), '2')])
The result would be:
OrderedDict([('r', 1), ('s', 2), (('a','y', 'n'), '3')])
as I want the left ones to have the smaller value
I tried to do it myself but doesn't understand how to iterate from end to beginning over an OrderedDict.
How can I do it?
EDITED Answering the comment:
I get a dictionary of frequency of a letter in a sentence:
{ 's':1, 'a':1, 'n':1, 'y': 1}
and need to create a huffman tree from it.
for instance:
((s,a),(n,y))
I am using python 3.3
Either:
Or: