Practicing Python (using Codewars)

I'm using Codewars as means of practicing what I've learned and how I apply it. However I encountered a challenge where I passed the test, but there's an error?

I don't see anywhere I can ask for help if I get stuck there. If I just copy and paste everything here should my code work for anyone to help me debug?

6 comments · 100% upvoted · other discussions

comments

novel_yet_trivial

yeah, probably. Be sure to include the problem text and any example inputs and outputs.

Ben_HH [OP]

Objective: Remove n exclamation marks in the sentence from left to right. n is positive integer.

def remove(s, n):
    "Remove each '!' in the provided argument `n` number of times"

    removal_count = 0
    characters = list(s)

    while removal_count < n:
        position = characters.index("!")
        del characters[position]
        removal_count += 1

    return ''.join(characters)

Here are the tests for this challenge:

test.describe("Example Tests")

tests = [
    #[[input], [expected]],
    [["Hi!",1] , "Hi"],
    [["Hi!",100] , "Hi"],
    [["Hi!!!",1] , "Hi!!"],
    [["Hi!!!",100] , "Hi"],
    [["!Hi",1] , "Hi"],
    [["!Hi!",1] , "Hi!"],
    [["!Hi!",100] , "Hi"],
    [["!!!Hi !!hi!!! !hi",1] , "!!Hi !!hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",3] , "Hi !!hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",5] , "Hi hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",100] , "Hi hi hi"],
]


for inp, exp in tests:
    test.assert_equals(remove(*inp), exp)
ASIC_SP

also, there is already a string method to do this, check https://docs.python.org/3/library/stdtypes.html#string-methods

ASIC_SP

what is the error you get?

you need to be careful in not trying to deleting out of range index.. for example, the "Hi!",100 test case

>>> a = [1, 3, 5, 6]
>>> del a[3]
>>> a
[1, 3, 5]
>>> del a[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
Ben_HH [OP]

This is my error

position = characters.index("!")
ValueError: '!' is not in list
ASIC_SP

yeah, that is also a possibility..

and the error msg is self explanatory, if you have a list, say [1, 3, 5] and try to get index of an element which doesn't exists, say 2, you'll get this error..

you can avoid this by adding if '!' in characters to while condition... also, you can use remove method instead of getting index and using del..

but for this exercise, please use already existing string method :)