2

I am learning python and I meet some troubles.

I want to write the script to reverse a negative integer " -1234 to 4321- " and non-integer " 1.234 to 432.1". please help me. P.S. cannot use "str()" function

I just only can write the script to reverse positive integer 1234 to 4321

def reverse_int(n):

    x = 0
    while n > 0:
        x *= 10
        x += n % 10
        n /= 10
    return x
print reverse_int(1234)
6
  • 2
    4321- in not a valid number! do you want to convert it to string? Commented Apr 28, 2015 at 17:26
  • 3
    4321- is not a valid integer. How do you plan on representing that as anything other than a string? Commented Apr 28, 2015 at 17:26
  • 4
    He just said he mustn't use the function str(), not that he cannot use strings. Hence, def reverse_int(n): return '{}'.format(n)[::-1] should work. Commented Apr 28, 2015 at 17:31
  • I don't understant your script. Could you post details of your solution? Commented Apr 28, 2015 at 17:35
  • 1
    is this homework ? since you cannot use the str function Commented Apr 28, 2015 at 17:40

7 Answers 7

3
def reve(x):
    x=str(x)
    if x[0]=='-':
        a=x[::-1]
        return f"{x[0]}{a[:-1]}"
    else:
        return x[::-1]

print(reve("abc"))
print(reve(123))
print(reve(-123))

#output cba 321 -321

Sign up to request clarification or add additional context in comments.

1 Comment

While this code might answer the OP's question, you could make your answer much better by appending an explanation on how your code solves the problem
2

how about using your code, but just concatenate a - when n is negative?

rev_int.py:

def reverse_int(m):
    x = 0
    n = m
    if m < 0 :
      n *= -1
    while n > 0 :
        x *= 10
        x += n % 10
        n /= 10
    if m < 0:
      #concatenate a - sign at the end
      return `x` + "-"
    return x

print reverse_int(1234)
print reverse_int(-1234)

This produces:

$ python rev_int.py
4321
4321-

6 Comments

How are you concatenating a string with an integer at return `x` + "-"?
I can't get this code to work properly for negative numbers, either in Skulpt or in my Python 3 (changing print to a function and /= to //=).
How is that any different from using str()? You might as well just do return `m`[::-1].
@TigerhawkT3 The question is for reversing integers, the back ticks convert an integer to string; see link so the concatenation works. This code would work in Python 2.x, would need change for Python3. Also the question asks NOT to use str()
1. I don't think using the syntactic equivalent of repr() matches the spirit of the question any better than using str(), 2. the question clearly mentions non-integers in both the title and the body, giving an example of 1.234, and 3. if you're going to use repr()/``, you might as well replace the whole body of the function with return repr(m)[::-1], and then it'll work on Python 2 and 3, for both ints and floats.
|
0

Using SLICING EASILY DONE IT

def uuu(num):
if num >= 0: 
    return int(str(num)[::-1])
else:
    return int('-{val}'.format(val = str(num)[1:][::-1]))

Comments

0

Below code runs fine on Python-3 and handles positive and negative integer case. Below code takes STDIN and prints the output on STDOUT.

Note: below code handles only the integer case and doesn't handles the non-integer case.

def reverseNumber(number):
        x = 0
        #Taking absolute of number for reversion logic
        n = abs(number)
        rev = 0
        #Below logic is to reverse the integer
        while(n > 0):
            a = n % 10
            rev = rev * 10 + a
            n = n // 10
        #Below case handles negative integer case
        if(number < 0):
            return (str(rev) + "-")
        return (rev)
#Takes STDIN input from the user
number=int(input())
#Calls the reverseNumber function and prints the output to STDOUT
print(reverseNumber(number))

Comments

0

Using str convert method.

num = 123
print(str(num)[::-1])

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-1

Use this as a guide and make it work for floating point values as well:

import math

def reverse_int(n):
    if abs(n) < 10:
        v = chr(abs(n) + ord('0'))
        if n < 0: v += '-'
        return v
    else:
        x = abs(n) % 10
        if n < 0: return chr(x + ord('0')) + reverse_int(math.ceil(n / 10))
        else: return chr(x + ord('0')) + reverse_int(math.floor(n / 10))

print reverse_int(1234)

1 Comment

output is 40 no matter 1234 or -1234 @@
-3

Why not just do the following?:

def reverse(num):
    revNum = ''
    for i in `num`:
        revNum = i + revNum
    return revNum

print reverse(1.12345)
print reverse(-12345)

These would print 54321.1 and 54321-.

2 Comments

If you wanted simple, you could've copied my return `m`[::-1] comment exactly instead of adding a loop. And, of course, I don't think repr() (what `` does in Python 2 - repr() would be better anyway because it works in 2 and 3) is any better than str().
As written, your script produces 1000000000054321.1 for 1.12345.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.