Maionic
Maionic

Reputation: 25

Arrange a string if it's odd

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))

Upvotes: 0

Views: 72

Answers (1)

Mechanic Pig
Mechanic Pig

Reputation: 7736

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'

Upvotes: 1

Related Questions