Last active
November 12, 2018 20:22
-
-
Save DarthJahus/a6ac5d456530d1793321 to your computer and use it in GitHub Desktop.
Converts a number to an array of its constituting digits.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Jahus, 2015-12-13 | |
These functions convert a number to an array containing | |
the digits constituting that number. | |
""" | |
def count_digits(number): | |
i = 0 | |
while int(number / (10 ** i)) > 0: | |
i += 1 | |
print("The number has %i digits." % i) | |
return i | |
def number_to_array_of_digits(number): | |
digits = [] | |
prev = 0 | |
count = count_digits(number) | |
for j in range(count): | |
k = count - (j + 1) | |
red = prev * 10 | |
digit = int(number / (10 ** k)) | |
digits.append(digit - red) | |
prev = digit | |
return digits | |
def array_of_digits_to_number(number_array): | |
number = 0 | |
count = len(number_array) | |
for i in range(count): | |
number += number_array[count - (i + 1)] * (10 ** i) | |
return number | |
def start(arg): | |
try: | |
nbr = int(arg) | |
except ValueError: | |
print("Please, enter a number.") | |
return | |
print("Number: %s" % nbr) | |
nbr_array = number_to_array_of_digits(nbr) | |
nbr_sorted = nbr_array.copy() | |
nbr_sorted.sort(reverse=True) | |
print("Biggest number with these digits: %i" % array_of_digits_to_number(nbr_sorted)) | |
if __name__ == "__main__": | |
import sys | |
_args = sys.argv | |
if len(_args) != 2: | |
print("Incorrect arguments.\nUse:\n\tNumToArray 1234567890") | |
else: | |
start(_args[1]) | |
""" | |
Edited on 2018-11-12: | |
* PEP8; | |
* Refactored all the parts; | |
* Add array_of_digits_to_number; | |
* Used to find the biggest number with given digits. | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment