Home > Mobile >  Best approach to adding integers in nested lists if they share a common string element?
Best approach to adding integers in nested lists if they share a common string element?

Time:10-03

The problem I have is I need to add/substract monomials in a polynomial equation e.g. 2xy abc-xy -> xy abc. So far I've approached this by extracting the various elements for each monomial using regex and placing them in a list of lists. Using the above example would look like this:

[[' ', '2', 'xy', 2], [' ', '3', 'abc', 3], ['-', '1', 'xy', 2]]

The fourth element in each list is just the length of the third element I'm retaining for sorting once the equation is reassembled.

Currently, I'm iteratively adding each value to a dictionary before pulling the result. Pseudocode for brevity:

if string not in dict:
    dict[string] = num
else:
    dict[string]  = num
result = [str(num)   string for item in dict.items]

I'm convinced there has to be a more efficient way of solving it. Routes explored so far:

  • comparing lists with set(), cmp()
  • using reduce() or zip, which I regretably don't know how to use well
  • using filter() to return lists with matching elements
  • lots of searching on SO

First question on stack overflow, any advice or pointers in the right direction most appreciated.

EDIT: For anyone curious, this is how I went about this particular section of the task. Thanks everyone for the pointers.

pattern = r"([ -]|)([\d] |)([a-z] )"
monomial_dict = {}
# poly = "-a 5ab 3a-c-2a"
for m in re.finditer(pattern, poly): 
        mono_val = m.group(2)
        if not mono_val: # if no num in front of monomial, make equal to 1 for dict addition
            mono_val = '1'
        num = int(m.group(1)   mono_val)
        string = ''.join(sorted(m.group(3)))
        if string not in monomial_dict:
            monomial_dict[string] = [num, string]
        else:
            monomial_dict[string][0]  = num
# monomial_dict = {'a': [0, 'a'], 'ab': [5, 'ab'], 'c': [-1, 'c']}

CodePudding user response:

I think at best you could skip the 'list of lists' step and accumulate the matches in the dictionary when iterating over the regex matches.

The current approach with the dictionary should already be quite efficient, as it scales O(n) with the size of the list.

  • Related