-6

I want to get any number. e.g: 14892. And return it as 25903 (according to each character's unicode value)

This is what I have so far:

def convert(n):
    if len(n)>0:
        x = (chr(ord(str((int(n[0])+1)))))
        return x
Lucas Chad
  • 19
  • 1
  • 1
  • 3

3 Answers3

0
def convert(n):
    return int(''.join([str(int(elem)+1)[-1] for elem in str(n)]))

You could use a list comprehension.

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
0

To perform this transformation, you need to get each digit and add one to it, with 10 wrapping around to 0. The simple way to do that wrapping is to use the modulus operator. We can also use integer division and modulus to extract the digits, and we can do both operations using the built-in divmod function. We store the modified digits in a list, since the simple way to combine the digits back into a single number needs the digits in reverse order.

def convert(n):
    a = []
    while n:
        n, r = divmod(n, 10)
        a.append((r + 1) % 10)
    n = 0
    for u in reversed(a):
        n = 10 * n + u
    return n

# Test

print(convert(14892))

output

25903

That algorithm is fairly close to the usual way to do this transformation in traditional languages. However, in Python, it's actually faster to do this sort of thing using strings, since the str and int constructors can do most of their work at C speed. The resulting code is a little more cryptic, but much more compact.

def convert(n):
    return int(''.join([str((int(c) + 1) % 10) for c in str(n)]))
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

You could convert the number to a string, use the translate function to swap out the numbers, and convert back to integer again:

>>> t=str.maketrans('1234567890','2345678901')
>>> x = 14892
>>> y = int(str(x).translate(t))
>>> y
25903
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251