0

I have this code that sorts characters in a string and counts the number of times it's repeated.

def char_repetition(str):
    
    reps = dict()
    word = [character.lower() for character in str.split()]
    word.sort()
    
    for x in word:
        if x in reps:
            reps[x] += 1
        else:
            reps[x] = 1

    return reps


for x in char_repetition(str):
    print (x,char_repetition(str)[x])

So an input of '1 2 3 2 1 a b c b a' would yield:

1   2
2   2
3   1
a   2
b   2
c   1

The problem is that I want the numbers to appear at the end of the output like that:

a   2
b   2
c   1
1   2
2   2
3   1

j_4321
  • 15,431
  • 3
  • 34
  • 61

1 Answers1

1

Change

    word = [character.lower() for character in str.split()]
    word.sort()

to

    digits = []
    chars = []
    for c in sorted(st.split()):
        if c.isdigit():
            digits.append(c)
        else:
            chars.append(c.lower())
    word = chars + digits

From ekhumoro in the comments, you can use a custom key to sort the list:

From:

    word = [character.lower() for character in str.split()]
    word.sort()

to:

    word = [character.lower() for character in str.split()]
    word.sort(key=lambda i: (1, int(i)) if i.isdigit() else (0, i))
Red
  • 26,798
  • 7
  • 36
  • 58
  • 1
    PS: if the the list contains multi-digit numbers, it would be better to do: `word.sort(key=lambda i: (1, int(i)) if i.isdigit() else (0, i))`. – ekhumoro Dec 11 '20 at 13:33