LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Python: Reversing ints ie 432 into 234 (https://www.linuxquestions.org/questions/programming-9/python-reversing-ints-ie-432-into-234-a-125516/)

Luantum 12-13-2003 11:35 AM

Python: Reversing ints ie 432 into 234
 
I need to reverse a number like 876 into 678. Also is there a way to take a list like:
[122, 123, 124, 663, 808, 777]
and weed out the repeats(122, 663, 808, 777)
I was thinking a for loop would work but I don't know exactly how to do it.

Thanks

Tesl 12-13-2003 03:25 PM

What programming language are you writing this in?

unfortunately, its not that simple. You would need to change the int into something else, and then rearrange, and convert it back into an int.

Its difficult to help when i dont really know what language your using, because there are different methods. If you had the number as a string, you could write a nice little for loop to reverse the character order, and then convert it into an Integer.

As for the best way of making a list, it depends what your trying to do. You could just slap the values into an array (if thats feasible) or you could try making use of a Linked List data structure (for example)

coolman0stress 12-13-2003 08:22 PM

I'm not very familiar with Python, but here's a possible way of doing all that:

Reversing numbers:
Convert number to string, reverse string, parse string back into integer.

Weeding out repeats:
Again, convert number to string, then using a loop move through each character and compare to each character in the string (again a for loop). If any are the same, then flag it and get rid of it from the list.

These aren't the best possible solutions, but that's the first thing that came to my mind. Again i'm not exactly a pro in Python, but i can provide you with a c++ or java version.

Hope it helps.

Luantum 12-13-2003 08:45 PM

Err Im using Python just like it says in my topic. :D I will look into that
coolman0stress. Thanks

h/w 12-14-2003 02:28 AM

im new to python too, so here goes -

[12, 34, 56, 78, 89] gives [21, 43, 65, 87, 98]
and,
[123,345,567,678] gives [321, 543, 765, 876]

if thats what ur lookin for, i did a
Code:

map (rev.rev, [12, 34, 56, 78, 89])
where rev is the function rev in that namespace, defined by:
Code:

def rev(x):
        result=0
        i=0
        while x/10 > 0:
                result = (result * 10) + (x % 10)
                x = x/10
        result = (result * 10) + (x % 10)
        return result

you'll see some quirky ans if u give some number with a leading zero, but all others should work. its mainly cos i wanted to have a stmt equivalent to
Code:

if x != NULL
and i dont know the equivalent in python. that first while condition doesnt look too good, but i havent looked too much into python syntax (yet!).

as for weeding out duplicates, look at operations on tuples. it has these 2 - count(), and index() . find the number of occurrences with count, for 1 less than that count, remove the occurrence at index. i think its prolly a line or two more...but u can do that.

hope that helps.


fr0zen 12-14-2003 03:09 AM

Likewise, an alternative (recursive) function:

Code:

#!/usr/bin/python
import math

def rev(val):
        if val < 10: return val
        else:
                expon = int(math.log10(val))
                ival = val%10
                dval = val/10
                return int(ival*math.pow(10,expon))  + rev(dval)

print rev(123456)

# [frozen@Fr0ZeN stuff]$ python int_rev.py
# 654321

Also, h/w, I believe what you are looking for is:

Code:

if x != None:

Tesl 12-14-2003 02:59 PM

Quote:

Originally posted by Luantum
Err Im using Python just like it says in my topic. :D I will look into that
coolman0stress. Thanks

lol, i swear to god you must have editted that in :P

if not i really am going insane :(

(edit - if you do happen to need either a C or Java version im sure i can send one your way :P)

Luantum 12-14-2003 06:38 PM

fr0zen, your code works well but if I reverse say 980 I get 89. This effects my code.

Code:

# Solves the Gym Puzzle
# Made by Reed Winn using Python under the GPL
# Notes:
# Range is 123 to 987
# You start with the number(can't have repeat digits)
# and reverse it and subtract the reversed number from the original
# Take the answer to that and flip it and add them if its NOT 1089 or 1098 you won!

# Imports
import math
import time

# Funtions

def rev(val):
# Reverses the number Thanks a bunch to fr0zen of the Linux Questions website :)
        if val < 10: return val
        else:
                expon = int(math.log10(val))
                ival = val%10
                dval = val/10
                return int(ival*math.pow(10,expon))  + rev(dval)



stream = range(123,987) # Builds a list between 123 and 987


counter = 0
for x in stream: # A for loop to go over the list

        counter = counter + 1 # A counter to track the position in the list

        if counter >= 864: # An if loop that makes sure the counter can't overun
                print "Counter grew bigger than list range...exiting in 5"
                time.sleep(5) # Sleeps

                pass # Kills the if loop
        else:
                # The main fliping logic
                start_num = stream[counter] # Grabs the number to be tested
                second_num = rev(start_num) # Makes the second num by flipping 1st #
                answer1 = start_num - second_num # Subtracts second from 1st
                last_num1 = rev(answer1) # flips the answer to get the last number
                real_Answer = answer1 + last_num1 # Adds the pair to get the real deal
                print '%d        %d' %(start_num,real_Answer)

This is for a math puzzle my gym teacher gave us. If I win I get a 2liter. The programming chalange is fun too. You are supposed to get 6 answers that arn't 198 or 1024. You can't have repeats in the first collum ie no 332 or 696. I can weed out the repeats by hand so thats not a problem. However the negitives are. I need to find a way to change a negitive like -198 into 198. Also what I said at the top. Frozens code is great but I can't understand it(not learning that math in school yet). It dosn't work for numbers like 560 it just outputs 65

Help is wanted because my teacher gave us over the weekend to do this and its due on monday. Its not for a grade but I told this kid that I could do it and I will lose face if I can't(arr my big mouth) I thought it would be simple but you know how dificultes spring up in programming)

Thanks

Tesl 12-14-2003 06:52 PM

Quote:

Originally posted by Luantum
fr0zen, your code works well but if I reverse say 980 I get 89. This may not effect my code however but I will have to see.
it depends on what you want you want to reverse the number for. If its important that it remains as an integer, then it shouldnt be a problem if it stays as 89 instead of 089. If you really want it to be represented as 089 you would have to represent it in a string form for this to be seen.

Luantum 12-14-2003 07:02 PM

Tesla, its the problem with the zero at the right side.
190 and 19 are NOT the same.

Luantum 12-15-2003 12:05 AM

I finaly got it done and it looks like a winner!
Code:

# Solves the Gym Puzzle
# Made by Reed Winn using Python under the GPL
# Notes:
# Range is 123 to 987
# You start with the number(can't have repeat digits)
# and reverse it and subtract the reversed number from the original
# Take the answer to that and flip it and add them if its NOT 1089 or 198 you won!

# Imports
import math
import time

# Funtions

def rev(val):
# Reverses the number Thanks a bunch to fr0zen of the Linux Questions website :)
        if val < 10: return val
        else:
                expon = int(math.log10(val))
                ival = val%10
                dval = val/10
                return int(ival*math.pow(10,expon))  + rev(dval)



stream = range(123,987) # Builds a list between 123 and 987

file = open('puzzle.log','a') # Prepares a file for writing the log output
file.write('Gym Puzzle Log File - Generated by puzzle.py\n\n\n')


counter = 0
for x in stream: # A for loop to go over the list

        counter = counter + 1 # A counter to track the position in the list

        if counter >= 864: # An if loop that makes sure the counter can't overun
                print "Counter grew bigger than list range...exiting in 5"
                time.sleep(5) # Sleeps

                pass # Kills the if loop
        else:
                # The main fliping logic
                start_num = stream[counter] # Grabs the number to be tested

                second_num = rev(start_num) # Makes the second num by flipping 1st #
                if second_num < 100:
                        second_num = str(second_num)
                        second_num = second_num + '0'
                        second_num = int(second_num)
                else:
                        pass


                answer1 = start_num - second_num # Subtracts second from 1st
                if answer1 < 0: # If negitive change to positive
                        answer1 = abs(answer1) #Absolutes the answer
                else:
                        pass

                last_num1 = rev(answer1) # flips the answer to get the last number

                real_Answer = answer1 + last_num1 # Adds the pair to get the real deal



                print '%d        %d        %d        %d        %d' %(start_num,second_num,answer1,last_num1,real_Answer)# prints data


                file.write("%d                %d                %d                %d                %d\n"%(start_num,second_num,answer1,last_num1,real_Answer)) # Writes data to log file yay! logs!


file.close() # Cleans up

Thanks everyone for there help!:D :D :D I learned alot and now I can get a free drink!

h/w 12-15-2003 12:54 PM

what kinda school has a gym teacher giving math problems to solve in python? lol. and on top, promises beer?
hellloooo - i wanna join this school of yours. :)


All times are GMT -5. The time now is 11:14 AM.