From a60525edbc47bde83a15fc593383f6dee3798a44 Mon Sep 17 00:00:00 2001 From: devansh-07 Date: Mon, 19 Oct 2020 11:02:25 +0530 Subject: [PATCH] Added 2's complement --- mathgenerator/funcs/__init__.py | 1 + mathgenerator/funcs/binary2sComplement.py | 26 +++++++++++++++++++++++ mathgenerator/mathgen.py | 1 + 3 files changed, 28 insertions(+) create mode 100644 mathgenerator/funcs/binary2sComplement.py diff --git a/mathgenerator/funcs/__init__.py b/mathgenerator/funcs/__init__.py index efb1ce7..b43d727 100644 --- a/mathgenerator/funcs/__init__.py +++ b/mathgenerator/funcs/__init__.py @@ -71,3 +71,4 @@ from .multiplyComplexNumbersFunc import * from .geomProgrFunc import * from .geometricMeanFunc import * from .harmonicMeanFunc import * +from .binary2sComplement import * \ No newline at end of file diff --git a/mathgenerator/funcs/binary2sComplement.py b/mathgenerator/funcs/binary2sComplement.py new file mode 100644 index 0000000..f51b797 --- /dev/null +++ b/mathgenerator/funcs/binary2sComplement.py @@ -0,0 +1,26 @@ +from .__init__ import * + +def binary2sComplementFunc(maxDigits=10): + digits = random.randint(1, maxDigits) + question = ''.join([str(random.randint(0, 1)) for i in range(digits)]).lstrip('0') + + answer = [] + for i in question: + answer.append(str(int(not bool(int(i))))) + + carry = True + j = len(answer) - 1 + while j >= 0: + if answer[j] == '0': + answer[j] = '1' + carry = False + break + answer[j] = '0' + j -= 1 + + if j == 0 and carry == True: + answer.insert(0, '1') + + problem = "2's complement of " + question + " =" + solution = ''.join(answer).lstrip('0') + return problem, solution \ No newline at end of file diff --git a/mathgenerator/mathgen.py b/mathgenerator/mathgen.py index 0e813a6..860c89b 100644 --- a/mathgenerator/mathgen.py +++ b/mathgenerator/mathgen.py @@ -156,3 +156,4 @@ complexNumMultiply = Generator("Multiplication of 2 complex numbers", 64, "(x + geometricprogression=Generator("Geometric Progression", 65, "Initial value,Common Ratio,nth Term,Sum till nth term =", "a,r,ar^n-1,sum(ar^n-1", geomProgrFunc) geometricMean=Generator("Geometric Mean of N Numbers",66,"Geometric mean of n numbers A1 , A2 , ... , An = ","(A1*A2*...An)^(1/n) = ans",geometricMeanFunc) harmonicMean=Generator("Harmonic Mean of N Numbers",67,"Harmonic mean of n numbers A1 , A2 , ... , An = "," n/((1/A1) + (1/A2) + ... + (1/An)) = ans",harmonicMeanFunc) +binary2sComplement = Generator("Binary 2's Complement", 68, "2's complement of 11010110 = ", "101010", binary2sComplementFunc) \ No newline at end of file