0

I have a list of Rubik's Cube movements and a dictionary of shortcuts like this :

mvts = ['U', 'U', 'R', 'Ri', 'L2', ...]
shortcuts = {'UU' : 'U2', 'RRi' : '', ...}

What I'm trying to do is applying a "search and replace" on the mvts list based on the contents of shortcuts.

Here is what the result would be in the example :

mvts = ['U2', 'L2', ...]

I'm using Python3 and I can't use a library that doesn't come with Python from scratch.

I'm stuck. I can do this with some regex on a String but I don't see how to make this search quick on my list.

Guillaume Wuip
  • 343
  • 5
  • 13

3 Answers3

1

Try this :

for i in range(len(mvts)):
      if(mvts[i] in shortcuts):
           mvts[i] = shortcuts[mvts[i]]

Notice

If you are Already sure that list elements exist in dictionary you can delete if line

and if you want delete duplications in list:

mvts = list(set(mvts))
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
  • Thanks @arman. Your code doesn't really do what I need as mvts[i] - which is a single mouvement - is not in shortcuts. But maybe mvts[i]+mvts[i+1] is, for example. – Guillaume Wuip Jan 10 '16 at 05:36
0

You could use re.sub

import re

mvts = ['UUU', 'U', 'R', 'Ri', 'L2']
shortcuts = {'UU' : 'U2', 'RRi' : ''}

def do_sub(m):
    for k, v in shortcuts.items():
        m = re.sub(k, v, m)
    return m

[do_sub(m) for m in mvts]

Output:

['U2U', 'U', 'R', 'Ri', 'L2']
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • Thank you @martin-konecny but I don't have directly `'UUU'` in `mvts` so I can't use re on each list cell. I have instead ['U', 'U', 'U', ...]. I'm going to look for a way to group successive same cells. – Guillaume Wuip Jan 10 '16 at 05:36
  • Ok so I've found a way to group `['U', U', ...]` into `['UU']` with `itertools.groupby`and then using `re` on that. But I'm not grouping `['Ri', 'R', ...]` for example. – Guillaume Wuip Jan 10 '16 at 05:48
0

I've found a solution by googling with the good terms : "Search/replace sublist in list Python".

So I've used @latty's solution explained here https://stackoverflow.com/a/12898180/2058840.

I had to change my dictionary structure to :

shortcuts = {'U U' : ['U2'], 'R Ri' : '', ...}

And then :

for (sublist, shortcut) in shortcuts:
    replace_list(mvts, sublist.split(), shortcut) #@latty's function

Thanks @martin-konecny and @arman for your help !

Community
  • 1
  • 1
Guillaume Wuip
  • 343
  • 5
  • 13