Home > Enterprise >  Converting an integer to a sequence of letters using a function
Converting an integer to a sequence of letters using a function

Time:02-19

I want to create a function that takes an integer (say 234) and returns it as letters (cde).

I have managed to form some code that takes the number and separates it into its numeric components

def toLetter(n):
    x = str(n)
    for elem in x:
        print(elem)
    d = {0 : 'a', 1 : 'b', 2 : 'c', 3 : 'd', 4 : 'e', 5 : 'f', 6 : 'g', 7 : 'h', 8 : 'i', 9 : 'j'}
    for n in x:
        d[n]

toLetter(234)

But I am really struggling with;

  1. how to map the dictionary onto the number and
  2. get it to return it as:
cde 

rather than

c
d
e

Any help would be greatly appreciated. I am new so this may be trivial but I have come here as last resort.

CodePudding user response:

You should use strings as keys in your dictionary.

A simple way, use a generator/comprehension:

def toLetter(num):
    d = dict(zip('0123456789', 'abcdefghij'))
    return ''.join(d[i] for i in str(num))

Even better, use a translation table:

def toLetter(num):
    t = str.maketrans('0123456789', 'abcdefghij')
    return str(num).translate(t)

example:

toLetter(123)
# 'bcd'

CodePudding user response:

So, in order to select the elements in the dictionary you have to convert the digits back to integers. Also, to create the final answer I would simply append each letter to a string and print the final string:

def toLetter(n):
    d = {0 : 'a', 1 : 'b', 2 : 'c', 3 : 'd', 4 : 'e', 5 : 'f', 6 : 'g', 7 : 'h', 8 : 'i', 9 : 'j'}
    
    x = str(n)
    result = ''
    
    for elem in x:
        result = result   d[int(elem)]
    
    print(result)

toLetter(234)

Output:

cde
  • Related