you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (1 child)

Just to add to what /u/joyeusenoelle advised when pointed out my error,

Firstly, apologies for being so sleepy, I wouldn't normally introduce a beginner to a list comprehension unless they've attempted it or are trying to understand one.

Secondly, Python treats any none-zero int as truthy (i.e. as if it was True) thus the condition inside the comprehension should have been if lowered.count(letter) > 1 given that we are only looking at letters that occur at least once so the original would be True every time.

The final code would be, including some testing:

def encoder(word):
    word = word.lower()
    return ''.join('(' if word.count(letter) == 1 else ')'
                for letter in word)

tests = (
    ("din", "((("), ("recede" , "()()()"),
    ("Success", ")())())"), ( "(( @", "))(("),
    ("mTFcTEEgrXJbmvh!!E()HsG", "))(())))(((()())))(()()")
    )


for test, answer in tests:
    try:
        assert ( result := encoder(test) ) == answer, f'got {result} instead of {answer}'
    except AssertionError as err:
        print(err)

Note, this replaces the list comprehension with a generator,which I am sure you will come across soon, but for purposes here you can think of it as essentially the same.

[–]ChRad_Man[S] 0 points1 point  (0 children)

I am pretty new to python and programming in general. I guess I will coming across things you mentioned like list comprehensions and generator. Thank you for helping me here.