Home > front end >  Trying to reorganize a random string so that all the letters are grouped up in the order that a diff
Trying to reorganize a random string so that all the letters are grouped up in the order that a diff

Time:11-26

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"

CodePudding user response:

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)
    

  • Related