Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Thank you so much!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading