-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
  • 808
  • 1
  • 2
  • 13

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
  • 33,459
  • 6
  • 59
  • 67
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
Ani M
  • 1,868
  • 1
  • 2
  • 13