Home > Software design >  Arrange a string if it's odd
Arrange a string if it's odd

Time:05-21

I have a string, I want to be able to move all the digits that appear odd numbers of times in the string to move to the front of the string IN ascending order. The rest of the string remains intact

This is what I have tried till now:

from collections import Counter

def getOddOccurrence(myString):
    count = Counter(myString)
    for letter in myString:
        if count[letter] % 2 != 0:
            return letter

myString = "sfsdfsdfs"
print(getOddOccurrence(myString))

Thank you so much!

CodePudding user response:

This is consistent with your expected output:

>>> s = "81454aDc5445bd"
>>> cntr = Counter(s)
>>> ''.join(sorted(s, key=lambda c: int(c) if c.isdigit() and cntr[c] % 2 else 10))
'1555844aDc44bd'

You can also make some optimization:

>>> mapping = {k: int(k) if k.isdigit() and v % 2 else 10 for k, v in cntr.items()}
>>> ''.join(sorted(s, key=mapping.get))
'1555844aDc44bd'
  • Related