The goal is to display the output of the list as an integer. e.g. :
>>> x = 3498
>>> x_list = [int(digit) for digit in str(x)]
>>> x_list.reverse()
>>> print(x_list)
[8, 9, 4, 3]
The output is a list.
And what is my expected output :
8943
CodePudding user response:
you can also just reverse the list if that's your goal :).
x = 3498
x = str(x)
print(int(x[::-1]))
CodePudding user response:
Remember that a digit of the form abcd
is actually (a * 10**3) (b * 10**2) (c * 10**1) (d * 10**0)
. By using this fact, you can do your reversion without even using x_list.reverse()
:
x = 3498
x_list = [int(digit) for digit in str(x)]
reversed_x = sum(digit * 10**i for i, digit in enumerate(x_list))
assert reversed_x == 8943
Or, to make everything in a single operation (thanks to @Chiheb Nexus for the suggestion):
x = 3498
reversed_x = sum(int(digit) * 10**i for i, digit in enumerate(str(x)))
assert reversed_x == 8943
CodePudding user response:
x = 3498
x_list = [digit for digit in str(x)]
x_list.reverse()
x_list = int(''.join(x_list))
print(x_list)
8943
CodePudding user response:
If you do not want to convert to string:
import math
def reverse_digits(num):
q, r = divmod(num, 10)
if q == 0:
return r
return r * 10**(int(math.log10(q)) 1) reverse_digits(q)
print(reverse_digits(3498)) # 8943