Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating a string to "robber's language"

I'm trying to practice for my upcoming practical programming test so have been browsing online for examples and came across this

"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".

I don't know why but I'm struggling with this a lot. So simple but yet I'm having a difficult time. Here is what I have tried

def translate(n):
    consonant="bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
    for letters in n:
        if letters in consonant:
            return (letters+"O"+letters)
        else:
            return("Vowel")

I'm sorry if my coding is super amateur. Just trying to learn :/

like image 218
xHalcyonx Avatar asked Mar 19 '23 15:03

xHalcyonx


2 Answers

consonants = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
original_string = "this is fun"
translated = ''.join(map(lambda x: x+"0"+x if x in consonants else x,original_string)
print translated

is one way I might do this ... this just maps each letter to letter+0+letter if its a consonant and then joins the resulting lists

like image 59
Joran Beasley Avatar answered Mar 29 '23 07:03

Joran Beasley


    mytext = 'thisisfun'
consonants = 'bcdfghjklmnpqrstuvwxyz'
newtext = []
def translate(mytext):
    for i in mytext:
        if i not in consonants:
            newtext.append(i)
        else:
            newtext.append(i)
            newtext.append('o')
            newtext.append(i)
    print(newtext)

translate(mytext)

It presents the result as a list right now, just working on a way to get it back to a string for you... ask if you have any queries, its working OK for me right now... there are more elegant ways to do, I'm working on it right now - you've given me something to do for 10 minutes at least!

like image 35
Ilmiont Avatar answered Mar 29 '23 09:03

Ilmiont