Skips Elif Condition - python

during the execution of the code the program skips all ELIF conditions, going directly to ELSE, even if the ELIF condition is TRUE
a = 0
b = 0
c = 0
r = 0
soma = 1
sub = 2
div = 3
mult = 4
print('enter the number corresponding to the operation you want to do:\n')
print('Sum [1]')
print('Subtraction[2]')
print('Divisao [3]')
print('Multiplication [4]')
r = int(1)
while (r == 1):
operacao = 0
operacao = input('\n>')
if operacao == soma:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a + b
print ('\n A Soma de {} mais {} equivale a: {}'.format(a,b,c))
elif operacao == sub:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a - b
print ('\n A subtracao de {} menos {} equivale a: {}'.format(a,b,c))
elif operacao == div:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a / b
print ('\n A divisao de {} de {} equivale a: {}'.format(a,b,c))
elif operacao == mult:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a * b
print ('\n The multiplication of {} by {} is equivalent to: {}'.format(a,b,c))
else: #going direct to here...
print('\n Unrecognized operation')
EXPECTED that the ELIF conditions would work when true,but not working.

input returns a string, so you'll need to do operacao = int(input('\n>')), otherwise str == int will always be False:
x = input("\n>") # I've input 5
x
# '5'
# returns False because x is a string
x == 5
# False
# converts x to int, so returns True
int(x) == 5
# True
# returns True because we are comparing to a string
x == '5'
# True
So for your code:
# convert the return of input to int for comparing against other ints
operacao = int(input('\n>')) # I'll put 3
if operacao == 1:
print('got one')
elif operacao == 3:
print('got three')
# got three

Related

function unable to work with user inputs?

I have the following code, which is a code for a connect 4 game, the problem is that the functions seem to break in the user input part of the code. I don't know if I accidentally edited something to break it but I'm almost certain that it isn't as typing the adding this to the code:
addcounter(1,1)
addcounter(1,1)
addcounter(1,1)
addcounter(1,1)
addcounter(2,1)
addcounter(2,1)
addcounter(2,1)
addcounter(3,1)
addcounter(3,1)
addcounter(4,1)
checkdiagonal(4,1,1)
The output of this does return true as expected.
The code is as follows:
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 17:24:35 2019
#author: Norbert
"""
import numpy as np
h = 8
w = 9
x = 0
y = 0
playspace = np.zeros((h,w))
playspace[:, [0,-1]] = 8
def addcounter(column,team):
placed = False
while not placed:
for i in range(h-1,0,-1):
if playspace[i,column] > 0:
continue
else:
if team == 1:
playspace[i,column] = 1
if team == 2:
playspace[i,column] = 2
if team != 1 and team != 2:
print("error, invalid team")
placed = True
break
def height(column):
for i in range(h-1,0,-1):
if playspace[i,column] > 0:
continue
else:
return i
def checkhorizontal(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
for i in range(4):
try:
if playspace[h-y,x+i] == team:
a1 += 1
if playspace[h-y,x+i-1] == team:
a2 += 1
if playspace[h-y,x+i-2] ==team:
a3 += 1
if playspace[h-y,x+i-3] ==team:
a4 += 1
except:
pass
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
def checkvertical(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
checking = playspace[:,x]
for i in range(4):
try:
if checking[h-(y+i)] == team:
a1 += 1
if checking[h-(y+i-1)] == team:
a2 += 1
if checking[h-(y+i-2)] ==team:
a3 += 1
if checking[h-(y+i-3)] == team:
a4 += 1
except:
pass
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
def checkdiagonal(y,x,team):
diag1 = 0
diag2 = 0
if playspace[h-y,x] == team:
diag1 += 1
diag2 += 1
for i in range(1,4):
broken1 = False
try:
if playspace[h-y+i,x+i] == team and not broken1:
diag1 += 1
if playspace[h-y+i,x+i] != team:
broken1 = True
except:
pass
for i in range(1,4):
broken2 = False
try:
if playspace[h-y-i,x-i] == team and not broken2:
diag1 += 1
if playspace[h-y-i,x-i] != team:
broken2 = True
except:
pass
for i in range(1,4):
broken3 = False
try:
if playspace[h-y+i,x-i] == team and not broken3:
diag2 += 1
if playspace[h-y+i,x-i] != team:
broken3 = True
except:
pass
for i in range(1,4):
broken4 = False
try:
if playspace[h-y-i,x+i] == team and not broken4:
diag2 += 1
if playspace[h-y-i,x+i] != team:
broken4 = False
except:
pass
if (diag1 >= 4) or (diag2 >= 4):
return True
finished = False
turn = 0
team_turn = 1
print(playspace)
while not finished:
valid = False
print("turn: {}".format(turn))
print("It is player {}'s turn".format(team_turn))
while not valid:
player_input = int(input("Where would you like to drop a counter?"))
if playspace[0,player_input] != 0:
print("That isn't a valid column")
else:
valid = True
if team_turn == 1:
addcounter(player_input,team_turn)
if checkhorizontal(height(player_input),player_input,team_turn) == True or checkvertical(height(player_input),player_input,team_turn) == True or checkdiagonal(height(player_input),player_input,team_turn) == True:
print("Player {} wins".format(team_turn))
finished = True
if team_turn == 2:
addcounter(player_input,team_turn)
if checkhorizontal(height(player_input),player_input,team_turn) == True or checkvertical(height(player_input),player_input,team_turn) == True or checkdiagonal(height(player_input),player_input,team_turn) == True:
print("Player {} wins".format(team_turn))
finished = True
turn += 1
turn_changed = False
while not turn_changed:
if team_turn == 1:
team_turn = 2
turn_changed = True
break
if team_turn == 2:
team_turn = 1
turn_changed = True
break
print(playspace)
any help in trying to solve the bugs in the code would be grately appreciated. The connect 4 game uses simple 2-d arrays to display and store the game board. I have plans to use this array to create a pygame later on.
EDIT:
To clarify, the checks don't run to execute a victory message and end the game. despite the if statements being True. Only the vertical win seems to end the game.
I managed to correct the horizontal part, the code correction is as follows:
if (checkhorizontal(height(player_input)+1,player_input,team_turn) == True) or (checkvertical(height(player_input),player_input,team_turn) == True) or (checkdiagonal(height(player_input),player_input,team_turn) == True):
and in the horizontalcheck function:
def checkhorizontal(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
checking = playspace[y,:]
print(checking)
for i in range(4):
try:
if checking[x+i] == team:
a1 += 1
if checking[x+i-1] == team:
a2 += 1
if checking[x+i-2] ==team:
a3 += 1
if checking[x+i-3] ==team:
a4 += 1
except:
pass
print(a1,a2,a3,a4)
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
Ignore the prints, they're for debugging. But I basically removed one dimension and flipped the h-y value to become the y value.

I need to make a EAN-13 number validity checker in Python2. I don't see why this doesn't work

inp = raw_input("Input a EAN-13 number.")
aaa = False
bbb = False
if len(inp) == 13:
bbb = True
else:
print "Error input"
exit
ean_number = int(inp)
def ean13(value_1):
mult_of_ten = 0
sum_of_digits = 0
done = False
for z in len(value_1):
if not z == 0:
if z % 2 == 0:
value_1[z] *= 3
elif not z % 2 == 0:
value_1[z] *= 1
for a in len(value_1):
sum_of_digits += value_1[a]
if sum_of_digits % 10 == 0:
result = 0
elif not sum_of_digits % 10 == 0:
while done == False:
mult_of_ten = sum_of_digits
for d in True:
mult_of_ten += d
if sum_of_digits % 10 == 0:
done == True
result = mult_of_ten - sum_of_digits
if result == value_1[12]:
print "True"
if bbb == True:
ean13(ean_number)
I really don't see why teacher can't help either.
I need to make a EAN-13 number validity checker in Python2. I don't see why this doesn't work. Can anyone help?
I have made an EAN 13 Number Validity Checker in Python2.
Hope it helps you out.
# ean = '9780201379624'
ean = raw_input("Input a EAN-13 number:\n")
err = 0
even = 0
odd = 0
check_bit = ean[len(ean)-1]#get check bit(last bit)
check_val = ean[:-1]#Get all vals except check bit
if len(ean) != 13:#Check the input length
print "Invalid EAN 13"
else:
for index,num in enumerate(check_val):#Gather Odd and Even Bits
if index%2 == 0:
even += int(num)
else:
odd += int(num)
if ((3*odd)+even+int(check_bit)) % 10 == 0:# Check if the algorithm 3 * odd parity + even parity + check bit matches
print "Valid EAN 13"
else:
print "Invalid EAN 13"

Change from base Shadocks to Base 10 in Python

I have a little problem who block me, I've a work where I must to convert a number to Shadocks (base 4 it seems), and I must to make a decrypter.
So I made the first part, but my code won't work on the second.
Here it's :
def Base10toShadocks(n):
q = n
r = 0
Base4=[]
Shads=["GA","BU","ZO","MEU"]
if q == 0:
Base4.append(0)
else:
while q > 0:
q = n//4
r = n%4
n = q
Base4.append(r)
Base4.reverse()
VocShad = [Shads[i] for i in Base4]
print(VocShad)
def ShadockstoBase10(n):
l=len(n)
Erc_finale=[]
for i in range(l):
Sh=(n[i])
i=i+1
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale)
print(F)
F=F.replace("[","")
F=F.replace("]","")
F=F.replace(",","")
F=F.replace(" ","")
L2=len(F)
F=int(F)
print(L2)
print(F)
r=0
while f < 4 or F ==4:
d=(F%4)-1
F=F//4
print(d)
r=r+d*(4**i)
print(r)
inp = 0
inp2 = 0
print("Tapez \"1\" pour choisir de traduire votre nombre en shadock, ou \"2\" pour inversement")
inp = int(input())
if inp == 1:
print("Quel est le nombre ?")
inp2 = int(input())
if inp2 != None:
Base10toShadocks(inp2)
elif inp == 2:
print("Quel est le nombre ?")
inp2 = str(input())
if inp2 != None:
ShadockstoBase10(inp2)
It blocks at the F=int(F), I don't understand why.
Thanks for your help.
First, some errors in your code:
for i in range(l):
Sh=(n[i])
i=i+1 #### Won't work. range() will override
##### Where do "a","b","o","e" come from
##### Shouldn't it be "G","B","Z","M" ("GA","BU","ZO","MEU")?
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale) ### Not how you join an array into a string
Here's a corrected way:
def ShadockstoBase10(n):
n = n.upper(); # Convert string to upper case
l = len(n)
Erc_finale = "" # Using a string instead of an array to avoid conversion later
i = 0
while i < l: # while loop so we can modify i in the loop
Sh = n[i:i+2] # Get next 2 chars
i += 2 # Skip 2nd char
if Sh == "GA":
Erc_finale += "0"
elif Sh == "BU":
Erc_finale += "1"
elif Sh == "ZO":
Erc_finale += "2"
elif Sh =="ME" and "U" == n[i]:
Erc_finale += "3"
i += 1; # MEU is 3 chars
else:
break; # bad char
return int(Erc_finale, 4) # Let Python do the heavy work
Like everything in Python, there are other ways to do this. I just tried to keep my code similar to yours.

Python battleship, double the trouble

Why does it ask you twice where you want to put you battleship?
I have no clue way is does what it does.
Anyway in this link you can see the full code, because I don't know if that is necessary. http://speedy.sh/QYJWp/battleship-goed.txt
I think that the problem occurs before the //_________________________________________________________// part
board1 = []
board2 = []
for x in range(10):
board1.append(["O"] * 10)
for x in range(10):
board2.append(["O"] * 10)
def print_board1(board):
for row in board:
print " ".join(row)
def print_board2(board):
for row in board:
print " ".join(row)
print "Board User 1"
print_board1(board1)
print "----------------------------------------------"
print "Board User 2"
print_board2(board2)
print "Let's play Battleship!"
print "Try to destroy all your opponents battleship!"
print"Good luck!"
print " "
print " "
def U1_Input_row1(board1):
x = float(raw_input("User 1, in what row do you want to place your first ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_row1(board1)
def U1_Input_col1(board1):
x = float(raw_input("User 1, in what col do you want to place your first ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_col1(board1)
ship1 = [U1_Input_row1(board1), U1_Input_col1(board1)]
def U1_Input_row2(board1):
x = float(raw_input("User 1, in what row do you want to place your second ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_row2(board1)
def U1_Input_col2(board1):
x = float(raw_input("User 1, in what col do you want to place your second ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_col2(board1)
ship2 = [U1_Input_row2(board1), U1_Input_col2(board1)]
def U1_Input_row3(board1):
x = float(raw_input("User 1, in what row do you want to place your third ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_row3(board1)
def U1_Input_col3(board1):
x = float(raw_input("User 1, in what col do you want to place your third ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_col3(board1)
ship3 = [U1_Input_row3(board1), U1_Input_col3(board1)]
def U1_Input_row4(board1):
x = float(raw_input("User 1, in what row do you want to place your fourth ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_row4(board1)
def U1_Input_col4(board1):
x = float(raw_input("User 1, in what col do you want to place your fourth ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_col4(board1)
ship4 = [U1_Input_row4(board1), U1_Input_col4(board1)]
if ship1 == ship2 or ship1 == ship3 or ship1 == ship4 or ship2 == ship3 or ship2 == ship4 or ship3 == ship4:
print "YOU CANT PLACE 2 SHIPS IN THE SAME SPOT"
U1_Input_row1(board1)
U1_Input_col1(board1)
U1_Input_row2(board1)
U1_Input_col2(board1)
U1_Input_row3(board1)
U1_Input_col3(board1)
U1_Input_row4(board1)
U1_Input_col4(board1)
def U2_Input_row1(board2):
x = float(raw_input("User 2, in what row do you want to place your first ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_row1(board2)
def U2_Input_col1(board2):
x = float(raw_input("User 2, in what col do you want to place your first ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_col1(board2)
ship1u2 = [U2_Input_row1(board1), U2_Input_col1(board1)]
def U2_Input_row2(board2):
x = float(raw_input("User 2, in what row do you want to place your second ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_row2(board2)
def U2_Input_col2(board2):
x = float(raw_input("User 2, in what col do you want to place your second ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_col2(board2)
ship2u2 = [U2_Input_row2(board1), U2_Input_col2(board1)]
def U2_Input_row3(board2):
x = float(raw_input("User 2, in what row do you want to place your third ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_row3(board2)
def U2_Input_col3(board2):
x = float(raw_input("User 2, in what col do you want to place your third ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_col3(board2)
ship3u2 = [U2_Input_row3(board1), U2_Input_col3(board1)]
def U2_Input_row4(board2):
x = float(raw_input("User 2, in what row do you want to place your fourth ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_row4(board2)
def U2_Input_col4(board2):
x = float(raw_input("User 2, in what col do you want to place your fourth ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_col4(board2)
ship4u2 = [U2_Input_row4(board1), U2_Input_col4(board1)]
if ship1u2 == ship2u2 or ship1u2 == ship3u2 or ship1u2 == ship4u2 or ship2u2 == ship3u2 or ship2u2 == ship4u2 or ship3u2 == ship4u2:
print "YOU CANT PLACE 2 SHIPS IN THE SAME SPOT"
U2_Input_row1(board2)
U2_Input_col1(board2)
U2_Input_row2(board2)
U2_Input_col2(board2)
U2_Input_row3(board2)
U2_Input_col3(board2)
U2_Input_row4(board2)
U2_Input_col4(board2)
U1_Input_row1 = U1_Input_row1(board1)
U1_Input_col1 = U1_Input_col1(board1)
U1_Input_row2 = U1_Input_row2(board1)
U1_Input_col2 = U1_Input_col2(board1)
U1_Input_row3 = U1_Input_row3(board1)
U1_Input_col3 = U1_Input_col3(board1)
U1_Input_row4 = U1_Input_row4(board1)
U1_Input_col4 = U1_Input_col4(board1)
U2_Input_row1 = U2_Input_row1(board2)
U2_Input_col1 = U2_Input_col1(board2)
U2_Input_row2 = U2_Input_row2(board2)
U2_Input_col2 = U2_Input_col2(board2)
U2_Input_row3 = U2_Input_row3(board2)
U2_Input_col3 = U2_Input_col3(board2)
U2_Input_row4 = U2_Input_row4(board2)
U2_Input_col4 = U2_Input_col4(board2)
It's asking it twice because it goes through the script and hits these between the functions:
ship1 = [U1_Input_row1(board1), U1_Input_col1(board1)]
ship2 = [U1_Input_row2(board1), U1_Input_col2(board1)]
ship3 = [U1_Input_row3(board1), U1_Input_col3(board1)]
ship4 = [U1_Input_row4(board1), U1_Input_col4(board1)]
ship1u2 = [U2_Input_row1(board1), U2_Input_col1(board1)]
ship2u2 = [U2_Input_row2(board1), U2_Input_col2(board1)]
ship3u2 = [U2_Input_row3(board1), U2_Input_col3(board1)]
ship4u2 = [U2_Input_row4(board1), U2_Input_col4(board1)]
Then at the end it asks for input again with these calls:
U1_Input_row1 = U1_Input_row1(board1)
U1_Input_col1 = U1_Input_col1(board1)
U1_Input_row2 = U1_Input_row2(board1)
U1_Input_col2 = U1_Input_col2(board1)
U1_Input_row3 = U1_Input_row3(board1)
U1_Input_col3 = U1_Input_col3(board1)
U1_Input_row4 = U1_Input_row4(board1)
U1_Input_col4 = U1_Input_col4(board1)
U2_Input_row1 = U2_Input_row1(board2)
U2_Input_col1 = U2_Input_col1(board2)
U2_Input_row2 = U2_Input_row2(board2)
U2_Input_col2 = U2_Input_col2(board2)
U2_Input_row3 = U2_Input_row3(board2)
U2_Input_col3 = U2_Input_col3(board2)
U2_Input_row4 = U2_Input_row4(board2)
U2_Input_col4 = U2_Input_col4(board2)
The script is poorly thought out though, as most of these functions could have just been stuffed into a single function to save fewer lines of code.
This would be annoying for the user since he would have to go through the whole process of inputting ship positions even though 7/8 of them were ok.
if ship1u2 == ship2u2 or ship1u2 == ship3u2 or ship1u2 == ship4u2 or ship2u2 == ship3u2 or ship2u2 == ship4u2 or ship3u2 == ship4u2:
You can also use while statement to keep asking a question if the user inputs something wrong. The way it's being done now is a bit weird.
If the user inputs a bunch of letters or whatnot the script will crash right away because there's no error checking there. The use of isdigit() can help determine if the input is an integer before converting to int, and a try except can be use if the field is simply left empty.
Hope this helps out :)
I don't see where it would do what you described, but I think you should use an array instead of doing ship1u1... It would make it a lot easier to read your code and it would save you a couple lines.

Need help in adding binary numbers in python

If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011
But suppose I have to do 001+001, how should I create a code to figure out how to take carry over responses?
bin and int are very useful here:
a = '001'
b = '011'
c = bin(int(a,2) + int(b,2))
# 0b100
int allows you to specify what base the first argument is in when converting from a string (in this case two), and bin converts a number back to a binary string.
This accepts an arbitrary number or arguments:
>>> def bin_add(*bin_nums: str) -> str:
... return bin(sum(int(x, 2) for x in bin_nums))[2:]
...
>>> x = bin_add('1', '10', '100')
>>> x
'111'
>>> int(x, base = 2)
7
Here's an easy to understand version
def binAdd(s1, s2):
if not s1 or not s2:
return ''
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
Can be simple if you parse the strings by int (shown in the other answer). Here is a kindergarten-school-math way:
>>> def add(x,y):
maxlen = max(len(x), len(y))
#Normalize lengths
x = x.zfill(maxlen)
y = y.zfill(maxlen)
result = ''
carry = 0
for i in range(maxlen-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
# r can be 0,1,2,3 (carry + x[i] + y[i])
# and among these, for r==1 and r==3 you will have result bit = 1
# for r==2 and r==3 you will have carry = 1
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(maxlen)
>>> add('1','111')
'1000'
>>> add('111','111')
'1110'
>>> add('111','1000')
'1111'
It works both ways
# as strings
a = "0b001"
b = "0b010"
c = bin(int(a, 2) + int(b, 2))
# as binary numbers
a = 0b001
b = 0b010
c = bin(a + b)
you can use this function I did:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
#a = int('10110', 2) #(0*2** 0)+(1*2**1)+(1*2**2)+(0*2**3)+(1*2**4) = 22
#b = int('1011', 2) #(1*2** 0)+(1*2**1)+(0*2**2)+(1*2**3) = 11
sum = int(a, 2) + int(b, 2)
if sum == 0: return "0"
out = []
while sum > 0:
res = int(sum) % 2
out.insert(0, str(res))
sum = sum/2
return ''.join(out)
def addBinary(self, A, B):
min_len, res, carry, i, j = min(len(A), len(B)), '', 0, len(A) - 1, len(B) - 1
while i>=0 and j>=0:
r = carry
r += 1 if A[i] == '1' else 0
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
j -= 1
while i>=0:
r = carry
r += 1 if A[i] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
while j>=0:
r = carry
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
j -= 1
if carry == 1:
return '1' + res
return res
#addition of two binary string without using 'bin' inbuilt function
numb1 = input('enter the 1st binary number')
numb2 = input("enter the 2nd binary number")
list1 = []
carry = '0'
maxlen = max(len(numb1), len(numb2))
x = numb1.zfill(maxlen)
y = numb2.zfill(maxlen)
for j in range(maxlen-1,-1,-1):
d1 = x[j]
d2 = y[j]
if d1 == '0' and d2 =='0' and carry =='0':
list1.append('0')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='1':
list1.append('1')
carry = '1'
elif (d1 == '1' and d2 =='0' and carry =='0') or (d1 == '0' and d2 =='1' and
carry =='0') or (d1 == '0' and d2 =='0' and carry =='1'):
list1.append('1')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='0':
list1.append('0')
carry = '1'
else:
list1.append('0')
if carry == '1':
list1.append('1')
addition = ''.join(list1[::-1])
print(addition)
Not an optimal solution but a working one without use of any inbuilt functions.
# two approaches
# first - binary to decimal conversion, add and then decimal to binary conversion
# second - binary addition normally
# binary addition - optimal approach
# rules
# 1 + 0 = 1
# 1 + 1 = 0 (carry - 1)
# 1 + 1 + 1(carry) = 1 (carry -1)
aa = a
bb = b
len_a = len(aa)
len_b = len(bb)
min_len = min(len_a, len_b)
carry = 0
arr = []
while min_len > 0:
last_digit_aa = int(aa[len(aa)-1])
last_digit_bb = int(bb[len(bb)-1])
add_digits = last_digit_aa + last_digit_bb + carry
carry = 0
if add_digits == 2:
add_digits = 0
carry = 1
if add_digits == 3:
add_digits = 1
carry = 1
arr.append(add_digits) # will rev this at the very end for output
aa = aa[:-1]
bb = bb[:-1]
min_len -= 1
a_len_after = len(aa)
b_len_after = len(bb)
if a_len_after > 0:
while a_len_after > 0:
while carry == 1:
if len(aa) > 0:
sum_digit = int(aa[len(aa) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
aa = aa[:-1]
else:
carry = 0
arr.append(sum_digit)
aa = aa[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(aa) > 0:
arr.append(aa[len(aa) - 1])
aa = aa[:-1]
a_len_after -= 1
if b_len_after > 0:
while b_len_after > 0:
while carry == 1:
if len(bb) > 0:
sum_digit = int(bb[len(bb) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
bb = bb[:-1]
else:
carry = 0
arr.append(sum_digit)
bb = bb[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(bb) > 0:
arr.append(bb[len(bb) - 1])
bb = bb[:-1]
b_len_after -= 1
if carry == 1:
arr.append(carry)
out_arr = reversed(arr)
out_str = "".join(str(x) for x in out_arr)
return out_str

Categories