From cb9bab62533005a3bb8d6bf2ece54caf062c1ef7 Mon Sep 17 00:00:00 2001 From: Dm1tr1y147 Date: Tue, 7 Apr 2020 22:10:04 +0500 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20-=20=D0=A1=D0=B8=D1=81=D1=82=D0=B5=D0=BC=D1=8B=20?= =?UTF-8?q?=D1=81=D1=87=D0=B8=D1=81=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 1.py | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 1.py diff --git a/1.py b/1.py new file mode 100644 index 0000000..2ce70cb --- /dev/null +++ b/1.py @@ -0,0 +1,77 @@ +dictionary = [chr(i) for i in range(ord('0'), ord('9')+1)] + \ + [chr(i) for i in range(ord('A'), ord('F')+1)] + + +def validation(string, ibase, tbase): + for n in string: + if not n in dictionary[:ibase] + [',', '.']: + return False + if ibase < 2 or ibase > 16 or tbase < 2 or tbase > 16: + return False + return True + + +def convert(string, ibase, tbase): + if string == '0': + return 0 + if ibase != 10: + string = other_to_dec(string, ibase) + if tbase == 10: + return string + string = float(string) + integer = dec_to_other(int(string), tbase) + decimal = string - int(string) + if decimal: + decimal = float_dec_with__to_other(decimal, tbase) + return integer + ',' + decimal + return integer + + +def other_to_dec(string, ibase): + sum = 0 + amount = len(string.split('.')[0])-1 + for n in string: + if n != '.': + sum += int(dictionary.index(n)) * ibase**amount + amount -= 1 + return sum + + +def dec_to_other(num, tbase): + result = '' + while num // tbase > 0: + result += str(dictionary[int(num % tbase)]) + num //= tbase + result += str(dictionary[int(num % tbase)]) + return result[::-1] + + +def float_dec_with__to_other(num, tbase): + result = '' + counter = 0 + while num - int(num) > 0 and counter < 8: + result += str(dictionary[int(num * tbase)]) + num = num * tbase - int(num * tbase) + counter += 1 + return result[:7] + +# _____ MAIN PROGRAMM _____ + +input_number = input("Число: ").upper().replace(",", ".") +init_base = int(input("Основание исходной системы: ")) +target_base = int(input("Основание конечной системы: ")) + +hasSign = False +if input_number[0] == '-': + hasSign = True + input_number = input_number[1:] + +if not validation(input_number, init_base, target_base): + print("Wrong input!") + exit() + +output = convert(input_number, init_base, target_base) + +if hasSign: + output = '-' + str(output) +print(output)