Trying to reorganize a random string so that all the letters are grouped up in the order that a different random string dictates

Question:

I am creating a matrix that will list these a random string of letters that are used for colors and they are to be organized so that, for example all of the G’s will be together and then R, etc.

legoString = "YRRBRBYBGRBRGRRRYRGBRBGBBRBG"
shuffledColString = "YRBG"

for letter in shuffledColString:
    for index in range(len(legoString)):

        if letter == legoString[index]:
                legoString = legoString.replace(legoString[index], "") + "R"

        elif letter == legoString[index]:
                legoString = legoString.replace(legoString[index], "") + "G"

        elif letter == legoString[index]:
                legoString = legoString.replace(legoString[index], "") + "B"

        elif letter == legoString[index]:
                legoString = legoString.replace(legoString[index], "") + "C"

        elif letter == legoString[index]:
                legoString = legoString.replace(legoString[index], "") + "Y"
Asked By: KludgyCartoon79

||

Answers:

try this

legoString = "YRRBRBYBGRBRGRRRYRGBRBGBBRBG"
shuffledColString = "YRBG"

ns="".join(sorted(legoString,key=lambda x:shuffledColString.index(x)))
print(ns)

#OR IF ABOVE IS NOT CLEAR
ns=""
for c in shuffledColString:
    ns=ns+ c*legoString.count(c)

print(ns)
    

Answered By: wrbp
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.