Python: Build a function that takes as input a string of letters and returns an encoded version of the string

Viewed 25

Build a function that takes as input a string of letters and returns an encoded version of the string. The encoding scheme converts letters regardless of case, that appear once in the string to the '#' character and letters that appear more than once to the '&' character. Each letter should be encoded according to this scheme. The following strings and their conversions are provided as examples.

one | ### 
three | ###&& 
Heartbreak hotel | &&&&&#&&&##&#&&# 

I'm assuming something like this

new_str = ""
if count == 1:
  new_str += "#"
else:
  new_str += "&"

but how do I get it to count the old string? and output the new one?

Solution:

# 
def encoder(string):
    string = str(string)

    # define the delimiter
    delimeter = " "

    # split the string according to the space 
    str_lst = string.split(" ")


    hashmap_counts = {}
    spaces = 0 
    for word in str_lst:
        for letter in word:
            _ = letter.lower() # change all to lowercase
            hashmap_counts[_] = hashmap_counts.get(_,0) + 1
        spaces += 1
    hashmap_counts[delimeter] = hashmap_counts.get(delimeter,0) + (spaces - 1)
    # mapping to # if count == 1 else &
    encoder_map = {}
    for key,value in hashmap_counts.items():
        if value > 1: # if value is > 1 , &
            encoder_map[key] = '&'
        else: # else, #
            encoder_map[key] = '#'
    encoded_string = ""
    for letter in string:
        _ = letter.lower() # change all to lowercase
        encoded_string = encoded_string + encoder_map[_]
    return encoded_string

# Test Cases

input = "one"
output = encoder(input)
print(f"> {input}")
print(output)

input = "three"
output = encoder(input)
print(f"> {input}")
print(output)

input = "Heartbreak hotel"
output = encoder(input)
print(f"> {input}")
print(output)
0 Answers
Related