You only check if the digit is equal to the last digit, but this does not work, for example, 2452 . You must keep track of all previous numbers, using, for example, a dictionary , as in @wjmccann answer .
You can do this a little shorter, but by combining defaultdict with count . defaultdict remembers already seen digits, and count provides values ββfor new ones.
import itertools, collections, functools def convert(n): d = collections.defaultdict(functools.partial(next, itertools.count(1))) return int(''.join(str(d[x]) for x in str(n))) print(convert(5678))
Or even shorter as suggested in the comments :
def convert(n): d = collections.defaultdict(list("987654321").pop) return int(''.join(d[x] for x in str(n)))
This uses defaultdict again, but uses pop from the list of numbers as a factory function, removing items from the end of the list when new numbers are needed.
source share