0

I have to Convert a number into linked list such that each digit is in a node and pointing to node having next digit.The function should return head of the linked list. e.g input 120 should create a list of Nodes 1 -> 2 -> 0 and return the reference.If it is a negative number say -120 it should return -1->-2->0.I tried to do it in this way:

def number_to_list(number):
    head,tail = None,None
    for x in str(number):
        if x<0:
           x = -int(x)
           node = Node(int(x))
        else:
           node = Node(int(x))
        if head:
           tail.next = node
        else:
            head = node
        tail = node
    return head
    pass

It is working fine for positive numbers but if I pass -120.It is showing an error:

ValueError: invalid literal for int() with base 10: '-'. 

How can I fix it.

3
  • 1
    If you're iterating through the characters in the string representation of a number and calling int() on each, you'll need to special-case "-", because it's not an integer. Commented Feb 3, 2014 at 16:54
  • My function call is this:'head = number_to_list(-120)'@Wooble Commented Feb 3, 2014 at 16:54
  • Isn't this basically your other question asked again? stackoverflow.com/questions/21532916/… Commented Feb 3, 2014 at 17:06

6 Answers 6

1

In the first iteration with negative number you actually do:

int('-')
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is you are iterating over a string

for x in string(number):

Makes x a character, which iterates over the string number. Now when you have a positive number, each digit in the number can be converted to an int. But when you pass a negative number, x takes the value of '-' which cannot be converted to an integer. There you get the error. By what I see, I think you are storing the absolute values of the digits of the numbers in the list. This can be done by checking if the character is '-', where you can just give a pass to do nothing in this iteration.

if x=='-':
    continue

Comments

1

You should add a line of code to check for '-' (and possibly '.' if you allow decimal values.)

if(x=='-'):
    # Mark the number as negative
    negative = True
    # Move on to the next character
    continue

Comments

0

str(-120) return '-','1','2','0'

try this:

    needMinus = number < 0
    for x in str(abs(number)):
        if needMinus:
            x = -int(x)
            needMinus = False
            node = Node(int(x))
        else:
            node = Node(int(x))
        if head:
            tail.next = node

        else:
            head = node
        tail = node

Comments

0

Converting a string of non (base 10, by default) integer gives a ValueError:

In [1034]: int('-')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1034-4c2a77a1869c> in <module>()
----> 1 int('-')

ValueError: invalid literal for int() with base 10: '-'

likewise, int('10L'), int('0x1a'), int('abc'), etc.

You can treat number as a positive, and then add a negative sign to each single digit if number is actually a negative:

def number_to_list(number):
    head,tail = None,None
    if number<0: number=-number
    sign=-1 if number<0 else 1

    for x in str(number):
        node = Node(sign*x)

        if head:
            tail.next = node
        else:
            head = node
        tail = node
    return head
    pass

Comments

0

when you pass a negative number this int('-') is called in the first iteration. You can keep a boolean flag through which you can identify if a number is positive or negative.

Example: Note: I have not tested this code. This code is just to give an idea

  def number_to_list(number):
    head,tail = None,None
    positive = True
    for x in str(number):
        if x=='-':
           positive = False
           continue
        else:
          if postive:
             node = Node(int(x))
          else:
             node = Node(int("-"+x))
        if head:
           tail.next = node
        else:
            head = node
        tail = node
    return head
    pass

Comments

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.