Reverse digits of a list of numbers in python

Question:

for i in range(len(primo)):
    reversed_num = 0
    while i > 0:
       digit = i % 10
       reversed_num = reversed_num * 10 + digit
       i //= 10
       reversed.append (reversed_num)
    
for r in range(len(reversed)):
    print (r)

I’m writing a program to reverse a series of numbers from a list. For example:

Input: 1234,124,654

Output: 4321,421,456

The script works correctly with one number, but with a list it doesn’t work properly.

EDIT:
………………………………..

This is the working whole code.

#program to find the multiple of the first number that summed to its reverse creates a number divisible for the second number chosen. Results are shown up to five digits.

import sys

def main():
    x = 0
    y = 0
    k = 0
    z = 0
    print ("Hello! Let's compare some numbers!nPress input to continue")
    input()
    print ("Insert the first number")
    x = input()
    print ("Insert the second number")
    y = input()
    print()
    
    primo = []
    secondo = []
    
    #list multiples
    
    while k < 99999:
        k = int(k) + int(x)
        print (k)
        primo.append (k)
        
    while z < 99999:
        z = int(z) + int(y)
        print(z)
        secondo.append (z)
        
    print("The numbers have been calculated! Press to proceed")

    input()
    
    print("LOADING...")

    #reverse all numbers of the first list
    
    def myReverser(n: float) -> float:
       return float(''.join(list(reversed(str(n)))))
    
    reversedList = [myReverser(i) for i in primo]
    reversedList = [int(i) for i in reversedList]
    
    #sum the multiple of the first number and its reversed and search common values in res and secondo
    
    res = [
    x
    for x, y in zip(primo, reversedList)
    if (x + y) in secondo
]

    print()
    print()

    if len(res) == 0:
        print ("No results found")
    else:
        print ("The numbers are: ", res)

    #ending

    print ()
    print ("Thank you for using my program!")
    print ()
    choice = input ("Would you try with another number? [Y/N] ").capitalize()

    if choice == "Y":
        main()
    if choice == "N":
        sys.exit()

main()

#no copyright intended. This code is open-source. Feel free to use it in other projects.

The script can compare the two given numbers to find the multiple of the first number that summed to its reverse creates a number divisible for the second number chosen. Results are shown up to five digits.

Asked By: Andrea Valsesia

||

Answers:

Well, you are only printing the range of the length, so I don’t know how this would print your numbers at all. Here is a brief method that does what you are after, I believe.

In [1]: [int(str(x)[::-1]) for x in [1234, 124, 654]]
Out[1]: [4321, 421, 456]

or:

def reverse_items(l: list[int]) -> list[int]:
    return [int(str(x)[::-1]) for x in l]


if __name__ == "__main__":
    print(reverse_items([4321, 421, 456]))

output:

[1234, 124, 654]

This creates a list of integer values generated from reversing the string values of given list items.

Answered By: theherk

Nice try, but what about a function that reverses the numbers? You should be happy to know that reversed already exists in Python, and you can use it this way:

>>> list(reversed(str(0.1223142131)))
['1', '3', '1', '2', '4', '1', '3', '2', '2', '1', '.', '0']
>>> float(''.join(reversed(str(0.1223142131))))
1312413221.0

so you can implement your own function:

def myReverser(n: float) -> float:
    return float(''.join(reversed(str(n))))

and then use it over the whole list:

reversedList = [myReverser(i) for i in [1234, 124, 654]]

If you don’t want the .0 at the end of all the numbers, this means that you don’t want floating point numbers, but integers, so you can just do this:

reversedList = [int(i) for i in reversedList]
Answered By: FLAK-ZOSO

You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object.

Answered By: L8R

code:

l = input().split(',')
l = list(map(lambda x: list(map(lambda d: int(d), x))[::-1], l))
print(l)

input:

123,456,789

output:

[[3, 2, 1], [6, 5, 4], [9, 8, 7]]
Answered By: h1w

A string-free approach based on the old polynomial representation of numbers. Compute the quotients and remainders by a recursive long division and keeping track of them as pair in a list. Once the breaking condition is hit travel the list with a decreasing powers of 10.

def digit_reverser(n):
    
    def base_10_representation(n):
        d = []
        q, r = divmod(n, 10) # quotient, remainder
        d.append((q, r)) 
        if q < 10:
            return d
        d.extend(base_10_representation(q))
        return d

    # reversing the digits    
    d = base_10_representation(n)
    n_digits = len(d)
    return sum(r*10**(n_digits-i) for i, (_, r) in enumerate(d)) + d[-1][0]

n = 123456789
d = digit_reverser(n)

print(d)

Output

987654321

For an extension to list of numbers:

nrs = [1234, 124, 654]
nrs_rev = [digit_reverser(n) for n in nrs]

Output

[4321, 421, 456]
Answered By: cards
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.