Skip to content
Snippets Groups Projects
Commit 22711e0f authored by dario.genga's avatar dario.genga
Browse files

Small refactoring of the xor method

The code of the method is cleaner and easier to read.
parent 3c4648d0
Branches
No related tags found
No related merge requests found
...@@ -56,39 +56,42 @@ def mul_mod(a, b): ...@@ -56,39 +56,42 @@ def mul_mod(a, b):
return format(res, '04b') return format(res, '04b')
def xor(a,b):#a XOR b = str(binaire) # Return a string of the result of a XOR b
# CODE SPAGHETTI | À OPTIMISER SI POSSIBLE def xor(a, b):
# accepte des nombres (décimaux & binaires-str) qui n'ont pas la même taille (100 et 7, ou encore '101' et '10101010101'par exemple)
res = '' res = ''
if(type(a) != str): #transforme les int en str (5 = 101 ; pas 0b101) # Format to binary string
a = format(a, "b") if type(a) != str:
a = format(a, "04b")
if(type(b) != str): #transforme les int en str (7 = 111 ; pas 0b101)
b = format(b, "b")
if(len(a) > len(b)):#si len(a) > len(b), met b --> a & a --> b pour étape suivante où len(a) pourra être comme len(b)
tmp = a
a = b
b = tmp
if(len(a) < len(b)): #partie ou on met les 2 strings à la même taille.
l_a = len(a) #int
l_b = len(b) #int
list = []
list = ((l_b - l_a) * '0', a) #à gauche, le nombre de '0' nécessaire pour avoir la même taille que 'b'
# & à droite 'a' qui est le plus petit str
a = ''.join(list) #fusion des '0' et du str(a)
if type(b) != str:
b = format(b, "04b")
# Adjust the size of a and b
if len(a) != len(b):
# Add leading zero to the smallest value
if len(a) > len(b):
tmp = a
a = b
b = tmp
if len(a) < len(b):
# Create a list with the first element containing the leading zeroes and the second the initial value
value_as_list = ((len(b) - len(a)) * '0', a)
# Then concatenate the two elements into a string
a = ''.join(value_as_list)
# Parse the strings and apply the XOR operation
i = 0 i = 0
size = len(a) #choisis 'a', mais on aurait pu mettre 'b'; same size = len(a)
while i < size: #fonction XOR while i < size:
if a[i] == b[i]: if a[i] == b[i]:
res += '0' res += '0'
else: else:
res += '1' res += '1'
i += 1 i += 1
return res return res
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment