I need help with some code

I’m trying to write a function that satisfies the conditions below:

Test.assert_equals(accum("ZpglnRxqenU"), "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu")
Test.assert_equals(accum("NyffsGeyylB"), "N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb")
Test.assert_equals(accum("MjtkuBovqrU"), "M-Jj-Ttt-Kkkk-Uuuuu-Bbbbbb-Ooooooo-Vvvvvvvv-Qqqqqqqqq-Rrrrrrrrrr-Uuuuuuuuuuu")
Test.assert_equals(accum("EvidjUnokmM"), "E-Vv-Iii-Dddd-Jjjjj-Uuuuuu-Nnnnnnn-Oooooooo-Kkkkkkkkk-Mmmmmmmmmm-Mmmmmmmmmmm")
Test.assert_equals(accum("HbideVbxncC"), "H-Bb-Iii-Dddd-Eeeee-Vvvvvv-Bbbbbbb-Xxxxxxxx-Nnnnnnnnn-Cccccccccc-Ccccccccccc")

Here is what I have so far:

def accum(s):
    x = s.upper()
    my_string = ''
    for letter in x:
            my_string += letter + letter.lower() * (x.index(letter)) + '-'
        
    my_string = my_string[:-1]
    return my_string

It works until there is a duplicate letter in the input, for example:
Let’s say the input is: "nsn"

My function would output "N-Ss-N"

When it should output "N-Ss-Nnn"

Do you guys have any ideas?

The problem is that x.index() returns the index of the first occurrence if the argument, whereas you are looking for the actual index of the letter.

I’d use enumerate().

2 Likes

I fixed it:

def accum(s):
    x = s.upper()
    my_string = ''
    count = 0
    for letter in x:
            count += 1
            my_string += letter + letter.lower() * (count - 1) + '-'
        
    my_string = my_string[:-1]
    return my_string
1 Like

Is that a CodeWars challenge?

2 Likes

Yes! I’ve been trying to do some to get more skilled

2 Likes

Me, too. I love that site :grinning:

3 Likes