-1

I have a function here which converts a number to its constituents.

def breakdown(number):
  res = []
  multiplier = 1
  while number != 0:
    digit = (number % 10)*multiplier
    number = number//10
    multiplier = multiplier*10
    res.append(digit)
  res.reverse()
  return res

Example breakdown(8541) gives [8000, 500, 40, 1].

This program works fine for any positive number, but goes into an infinite loop when provided with a negative integer. Any ideas on how to make it work with any number?

Sample:

Input: breakdown(-4562) should give output: [-4000,-500,-60,-2]

Keshav Bajaj
  • 863
  • 1
  • 5
  • 13
  • 6
    Can you not take the abs value, run the normal algorithm, then negate every element in the result list? – ggorlen Jul 29 '21 at 17:32
  • The reason for the infinite loop is that `//` rounds down, not towards 0. So `-2 // 10` is `-1`, not `0`. It will never get to `0`. – Barmar Jul 29 '21 at 17:34
  • See https://stackoverflow.com/questions/19919387/in-python-what-is-a-good-way-to-round-towards-zero-in-integer-division – jarmod Jul 29 '21 at 17:35

2 Answers2

1

Converting my comment to an answer (pardon the silly function name, I'll let you rename them):

def breakdown_possibly_negative_number(number):
    return [-x for x in breakdown(-number)] if number < 0 else breakdown(number)

where breakdown is your function. This converts the negative number to positive and takes the negation of the constituent parts while passing positive numbers through unaltered.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
1

The way the // operator works is that it will round DOWN the quotient. That means that the infinite loop is caused during negative numbers because it will never be 0, it will always be -1.

A potential solution to your problem is to have an if statement that checks whether or not the number is negative, and multiply the digit by -1, while performing the operations as if it were a positive number:

def breakdown(number):
  if number > 0:
    sign = 1
  else:
    number *= -1
    sign = -1
  res = []
  multiplier = 1
  while number != 0:
    digit = (number % 10)*multiplier
    number = number//10
    multiplier = multiplier*10
    res.append(digit * sign)
  res.reverse()
  return res
Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14