Python Forum
Division of an integer into sub-numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Division of an integer into sub-numbers
#5
If you want to use math, you can do following:

  1. Get the digits of the number with math.log10
  2. Convert the result of digits to integer
  3. In a for-loop with reversed(range(digits + 1))
  4. Each iteration give you a integer (large > 0), which should be the position of the digt.
  5. Integer division: big_number // 10**digits
  6. Use modulo, to get only one digit: result = result % 10

The implementation, of what I described:
def split_numbers(number):
    digits = int(math.log10(number))
    for d in reversed(range(digits + 1)):
        digit = (number // 10 ** d) % 10
        yield digit
Much easier is following code:
def split_digits(number):
    return [int(d) for d in str(number)]
The number could be a int or a str.
Math is not used. I use the fact, that str is iterable. If you
iterate over a str you'll get char by char.



+If you want to check, if a number is really an integer, use exceptions:
try:
    big_number = int(big_number_as_str)
except ValueError:
    print('Is not a int')
else:
    print('Is a int')
    print(big_number)
In Python a complex consists of two floats. One float for the real part, one float for the imaginary part.
Floats do have the method is_integer(), so you can test also, each part of the complex if it's an integer.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Division of an integer into sub-numbers - by DeaD_EyE - Jun-14-2019, 11:47 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Division questions Dionysis 5 1,088 Feb-14-2023, 02:02 PM
Last Post: Dionysis
  Division by zero and value of argument Lawu 5 3,198 Jul-01-2022, 02:28 PM
Last Post: Lawu
  Floor division problem with plotting x-axis tick labels Mark17 5 2,146 Apr-03-2022, 01:48 PM
Last Post: Mark17
  Division calcuation with answers to 1decimal place. sik 3 2,148 Jul-15-2021, 08:15 AM
Last Post: DeaD_EyE
  Floor division return value Chirumer 8 3,840 Nov-26-2020, 02:34 PM
Last Post: DeaD_EyE
  Integer division plozaq 2 2,005 Sep-28-2020, 05:49 PM
Last Post: plozaq
  Overcoming ZeroDivisionError: division by zero Error dgrunwal 8 5,092 Jun-12-2020, 01:52 PM
Last Post: dgrunwal
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,774 May-09-2019, 12:19 PM
Last Post: Pleiades
  Logic of using floor division and modulus for a different variable at different time SB_J 2 2,537 Nov-01-2018, 07:25 PM
Last Post: SB_J
  20 x 20 Integer array with random numbers harryk 3 3,372 Jul-28-2018, 03:38 PM
Last Post: harryk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020