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.

3 Answers 3

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))
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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']

2 Comments

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.
Ok so I've found a way to group ['U', U', ...] into ['UU'] with itertools.groupbyand then using re on that. But I'm not grouping ['Ri', 'R', ...] for example.
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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.