Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am coding on morse, where i wanted to encode my text. Since I am working on the text, I am using string-to-morse and code is as fallows:

def coder(text, to_morse=True):

    morse_key = {'A': '.-',     'B': '-...',   'C': '-.-.',

            'D': '-..',    'E': '.',      'F': '..-.',

            'G': '--.',    'H': '....',   'I': '..',

            'J': '.---',   'K': '-.-',    'L': '.-..',

            'M': '--',     'N': '-.',     'O': '---',

            'P': '.--.',   'Q': '--.-',   'R': '.-.',

            'S': '...',    'T': '-',      'U': '..-',

            'V': '...-',   'W': '.--',    'X': '-..-',

            'Y': '-.--',   'Z': '--..',

            '0': '-----',  '1': '.----',  '2': '..---',

            '3': '...--',  '4': '....-',  '5': '.....',

            '6': '-....',  '7': '--...',  '8': '---..',

            '9': '----.', ' ': ' '

            }

    key_reversed = {value: key for key, value in morse_key.items()}

    if to_morse:

        return ' '.join(morse_key.get(i.upper()) for i in text)

    else:

        x = ''.join([key_reversed.get(i) for i in text.split() for i in (i, ' ')][:-1])

        return str(x)

The output which I am getting is not satisfactory. I am getting out like this as shown below:

'D A T A S C I E N C E'

for this code:

coder('-.. .- - .-   ... -.-. .. . -. -.-. .', False)

But I wanted the output to be like this:

'DATA SCIENCE'

So I wanted to implement split(). Can anyone suggest to me how to use it?

1 Answer

0 votes
by (36.8k points)

Well it's very simple since you have done your part pretty much good, you just need to change the else part code as shown below to achieve desired results:

text = text.replace(' ', ',').replace(',,,', ', ,')

return ''.join(key_reversed.get(i) for i in text.split(','))

I hope this will work with no issue.

You can use the link Data Science for more information on the subject and improve your knowledge

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...