Last active
March 24, 2018 11:00
-
-
Save komasaru/cd069235a890dc0537de6da247b4931f to your computer and use it in GitHub Desktop.
Python script to compare big 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
#! /usr/local/bin/python3.6 | |
""" | |
Comparison between two big-digit integers | |
""" | |
import random | |
import sys | |
import traceback | |
class CompareBigDigits: | |
D_L = 1000 # Number of big-digit integer (Left-hand side) | |
D_R = 1001 # Number of big-digit integer (Right-hand side) | |
def __init__(self): | |
self.l = [random.randrange(10) for _ in range(self.D_L)] | |
self.r = [random.randrange(10) for _ in range(self.D_R)] | |
def exec(self): | |
""" Execution """ | |
try: | |
s = self.__compare(self.l, self.r) | |
self.__display(self.l, self.r, s) | |
except Exception as e: | |
raise | |
def __compare(self, l, r): | |
""" Comparison | |
:param list l | |
:param list r | |
:return int s: 1 (l > r) | |
0 (l = r) | |
-1 (l < r) | |
""" | |
try: | |
size_l, size_r = len(l), len(r) | |
if size_l > size_r: | |
for i in range(size_l - 1, size_r - 1, -1): | |
if l[i] != 0: | |
return 1 | |
if size_l < size_r: | |
for i in range(size_r - 1, size_l - 1, -1): | |
if r[i] != 0: | |
return -1 | |
for i in range(min([size_l, size_r]) - 1, -1 , -1): | |
if l[i] > r[i]: | |
return 1 | |
if l[i] < r[i]: | |
return -1 | |
return 0 | |
except Exception as e: | |
raise | |
def __display(self, l, r, s): | |
""" Display | |
:param list l | |
:param list r | |
:param int s:-1 or 0 or 1 | |
""" | |
try: | |
print("[LEFT] =") | |
for i in range(self.D_L - 1, -1, -1): | |
print(l[i], end="") | |
if (self.D_L - i) % 10 == 0: | |
print(" ", end="") | |
if (self.D_L - i) % 50 == 0: | |
print() | |
print() | |
print("[RIGHT] =") | |
for i in range(self.D_R - 1, -1, -1): | |
print(r[i], end="") | |
if (self.D_R - i) % 10 == 0: | |
print(" ", end="") | |
if (self.D_R - i) % 50 == 0: | |
print() | |
print() | |
# 大小比較結果 | |
sign = "=" if s == 0 else (">" if s > 0 else "<") | |
print("[LEFT] {} [RIGHT]".format(sign)) | |
except Exception as e: | |
raise | |
if __name__ == '__main__': | |
try: | |
obj = CompareBigDigits() | |
obj.exec() | |
except Exception as e: | |
traceback.print_exc() | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment