Cannot find error trying to convert zipcode to binary - python

Here is my code I feel like this should be working. I added the zipcode = str(zipcode) just now to see if it would work which it didnt so I will probably take that out and just have the original zipcode be a string. I need it to be a string because I dont want the binary numbers to actually add to eachother. When I initialize the function in the python shell it just returns nothing
def digitConvert(zipcode):
zipcode = str(zipcode)
n = 0
binary = ""
while n < len(zipcode):
if zipcode[n] == 0:
binary = binary + "11000"
n = n + 1
elif zipcode[n] == 1:
binary = binary + "00011"
n = n + 1
elif zipcode[n] == 2:
binary = binary + "00101"
n = n + 1
elif zipcode[n] == 3:
binary = binary + "00110"
n = n + 1
elif zipcode[n] == 4:
binary = binary + "01001"
n = n + 1
elif zipcode[n] == 5:
binary = binary + "01010"
n = n + 1
elif zipcode[n] == 6:
binary = binary + "01100"
n = n + 1
elif zipcode[n] == 7:
binary = binary + "10001"
n = n + 1
elif zipcode[n] == 8:
binary = binary + "10010"
n = n + 1
elif zipcode[n] == 9:
binary = binary + "10100"
n = n + 1
return binary
Thanks for any help!

If I understand correctly, the zip code is an integer. Here is a little python function that converts an integer to binary. Default is you want 24 bits of binary.
def int2bin(n, count=24):
"""returns the binary of integer n, using count number of digits"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
For example, my zip code is 60517 so I would do this:
>>> print int2bin(60517)
000000001110110001100101
If I only want 16 binary bits:
>>> print int2bin(60517, 16)
1110110001100101

The main problem is that zipcode[n] is a character, not a number, so it will never compare equal to numbers (Python doesn't convert them automatically). There are also a number of simplifications you can make, such as using a for loop instead of indexing the string, and using a dictionary to map from decimal digits to binary strings.
def digitConvert(zipcode):
zipcode = str(zipcode)
digitMap = { '0': '11000', '1': '00011', '2': '00101', ... }
binary = ""
for digit in zipcode:
if digit in digitMap:
binary += digitMap[digit]
return binary

I dont see any problem with your code... other than the indents and checking the if conditions.
def digitConvert(zipcode):
zipcode = str(zipcode)
n = 0
binary = ""
while n < len(zipcode):
if zipcode[n] == '0':
binary = binary + "11000"
elif zipcode[n] == '1':
binary = binary + "00011"
elif zipcode[n] == '2':
binary = binary + "00101"
elif zipcode[n] == '3':
binary = binary + "00110"
elif zipcode[n] == '4':
binary = binary + "01001"
elif zipcode[n] == '5':
binary = binary + "01010"
elif zipcode[n] == '6':
binary = binary + "01100"
elif zipcode[n] == '7':
binary = binary + "10001"
elif zipcode[n] == '8':
binary = binary + "10010"
elif zipcode[n] == '9':
binary = binary + "10100"
n = n + 1
return binary
Update:
You can simplify the entire thing to this :
def digitConvert(zipcode):
zipcode = str(zipcode)
x = {
"0" : "11000",
"1" : "00011",
"2" : "00101",
"3" : "00110",
"4" : "01001",
"5" : "01010",
"6" : "01100",
"7" : "10001",
"8" : "10010",
"9" : "10100"
}
return "".join(x[i] for i in zipcode if i in x)

Related

Converting hexadecimal to binary example

I do not seem to understand the error of this code. I am trying to convert from hexadecimal to decimal. For example for a hexadecimal string that starts with 0x. Can someone help me, please? Thank you
def hex_char_decode(digit): # 0xbadf00d
if digit[0:2] == "0x":
digit = digit[2:]
bit_index = len(digit) - 1
sum = 0
i = 0
while bit_index >= 0:
if digit[len] >= "0" and digit[len] <= "9":
res = int(digit[len])
elif digit[len] >= "A" and digit[len] <= "F":
res = ord(digit[len]) - 55
elif hex[len] >= 'a' and hex[len] <= 'f':
res = ord(digit[len]) - 87
else:
sum = 1
break
sum += (res * (16 ** i))
bit_index -= 1
i += 1
return sum
if __name__ == "__main__":
# you should have all your main logic including inputs.
# function calls and output inside of if statement.
hexa = input()
result = hex_char_decode(hexa)
print(result)

I am trying to make a simple calculator without eval() and whole equations

I am trying to make a simple calculator with an input of the whole equation, but the catch is that i can not use eval() or anything similar to it. I wrote something and is probably not the best solution but this is what i came up with. The problem is that if i enter "2 + 5" as an input the final output is an error saying that it can not int() "2+"
Here is the code:
print("Calculator 2.0")
while True:
equation = input(": ")
# Remove spaces
calculate = equation.replace(" ", "")
# Converting to list
calculate = list(calculate)
# Merging numbers next to one another
i = 0
startingIndex = -1
numCounter = 1
num = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
while i < len(calculate):
if calculate[i] in num:
if startingIndex == -1:
startingIndex = i
numCounter += 1
else:
calculate[startingIndex : numCounter] = [''.join(calculate[startingIndex : numCounter])]
startingIndex = -1
numCounter = 1
i += 1
solved = False
answer = 0
while solved == False:
# Check for multiplication and division
i = 0
while i < len(calculate):
divideIndex = -1
multiplyIndex = -1
j = 0
while j < len(calculate):
if calculate[j] == "*":
multiplyIndex = j
elif calculate[j] == "/":
divideIndex = j
j += 1
# Solve the multiplication and division
if multiplyIndex != -1:
calculate[multiplyIndex] = str(int(calculate[multiplyIndex - 1]) * int(calculate[multiplyIndex + 1]))
del calculate[multiplyIndex - 1]
del calculate[multiplyIndex + 1]
if divideIndex != -1:
calculate[divideIndex] = str(int(calculate[divideIndex - 1] / int(calculate[divideIndex + 1])))
del calculate[divideIndex - 1]
del calculate[divideIndex + 1]
i += 1
# Check for addition and subtraction
i = 0
while i < len(calculate):
sumIndex = -1
subtractIndex = -1
j = 0
while j < len(calculate):
if calculate[j] == "+":
sumIndex = j
elif calculate[j] == "-":
subtractIndex = j
j += 1
# Solve the addition and subtraction
if sumIndex != -1:
calculate[sumIndex] = str(int(calculate[sumIndex - 1]) + int(calculate[sumIndex + 1]))
del calculate[sumIndex - 1]
del calculate[sumIndex + 1]
if subtractIndex != -1:
calculate[subtractIndex] = str(int(calculate[subtractIndex - 1]) - int(calculate[subtractIndex + 1]))
del calculate[subtractIndex - 1]
del calculate[subtractIndex + 1]
i += 1
answer = int(calculate[0])
print(answer)
solved = True
Give this a shot:
def Numbers(var):
return (
var == "0"
or var == "1"
or var == "2"
or var == "3"
or var == "4"
or var == "5"
or var == "6"
or var == "7"
or var == "8"
or var == "9"
)
def Test4Num(varstr):
n = 0
var = ""
try:
while Numbers(varstr[n]):
var += varstr[n]
n += 1
except:
pass
return (int(var), n)
def operation(string, num1, num2):
if string == "+":
return num1 + num2
if string == "-":
return num1 - num2
if string == "*":
return num1 * num2
if string == "/":
return num1 / num2
if string == "^":
return num1**num2
def operator(operato):
return (
operato == "+"
or operato == "-"
or operato == "*"
or operato == "/"
or operato == "^"
)
def eval_math_expr(expr):
negate = False
expr = expr.replace(" ", "")
while True:
try:
if expr[0] == "-": # for negative numbers
negate = True # because here the numbers are string format
expr = expr[1:]
number1 = Test4Num(expr)[0]
if negate == True:
number1 = -number1
negate = False
end_number1 = Test4Num(expr)[1]
expr = expr[end_number1:]
if expr == "":
return number1
op = expr[0]
expr = expr[1:]
number2 = Test4Num(expr)[0]
end_number2 = Test4Num(expr)[1]
result = operation(op, number1, number2)
number1 = result
expr = str(number1) + expr[end_number2:]
except Exception as e:
print(e)
break
return number1
if __name__ == "__main__":
expr = input("Enter your expression:")
print(expr + "=")
print(eval_math_expr(expr))

Why I cannot change index inside the while loop?

I want to implement basic calculator only includes numbers, '+' and '-' in Python. But I found that I cannot change index i inside the while loop.
def basicCalculator(expression):
res = 0
sign = 1
i = 0
while i < len(expression): # using while loop here
if expression[i] == '+':
sign = 1
elif expression[i] == '-':
sign = -1
elif '0' <= expression[i] <= '9':
temp = int(expression[i])
while i + 1 < len(expression) and '0' <= expression[i + 1] <= '9':
i += 1 # want to increase i, but failed
temp = temp * 10 + int(expression[i])
res += sign * temp
return res
s = "2+3-999"
print(basicCalculator(s)) # ouput should be -994, but infinite
Then I tried another way: using for loop instead of while loop, get incorrect answer.
def basicCalculator(expression):
res = 0
sign = 1
for i in range(len(expression)): # using for loop
if expression[i] == '+':
sign = 1
elif expression[i] == '-':
sign = -1
elif '0' <= expression[i] <= '9':
temp = int(expression[i])
while i + 1 < len(expression) and '0' <= expression[i + 1] <= '9':
i += 1 # increase i
temp = temp * 10 + int(expression[i])
res += sign * temp
return res
s = "2+3-999"
print(basicCalculator(s)) # ouput should be -994, but got -1102
I don't know why I cannot change the index inside the while loop or for loop. It is not a good idea to change i in for loop. What is the best way to fix the bug?
(I wrote the same code in Java using approach 2, everything is good, any difference?)
Rather than incrementing the index in a loop within the loop, I suggest just accumulating the current number in the main loop so you have less to keep track of:
def basicCalculator(expression):
res = 0
sign = 1
num = ""
for c in expression:
if c.isdecimal():
num += c
continue
res += int(num) * sign
num = ""
if c == "+":
sign = 1
elif c == "-":
sign = -1
else:
raise ValueError(f"Invalid operator {c}")
return res + int(num) * sign
print(basicCalculator("2+3-999")) # -994

Evaluate mathematical expression from String - Python

I need to evaluate an expression from a string given such as "(19 + ((91 -96)-13))" but I have to make te algorithm myself, which I can't use eval() or something similar.
I've been tried alot with this code but it gives me problems with negative numbers:
while counter < 1:
chunks = []
counter2 = 1
for character in operation:
if character.isdigit():
if chunks[-1].isdigit(): # If the last chunk is already a number
chunks[-1] += character # Add onto that number
else:
chunks.append(character) # Start a new number chunk
elif character in '+-/*()':
chunks.append(character) # This doesn't account for `1 ++ 2`.
for e in reversed(chunks):
if e == '(':
counter2 = len(chunks) - counter2
break
else:
counter2 = counter2 + 1
if chunks[counter2+2] == '+':
result2 = int (chunks[counter2+1]) + int (chunks[counter2+3])
elif chunks[counter2+2] == '-':
result2 = int (chunks[counter2+1]) - int (chunks[counter2+3])
elif chunks[counter2+2] == '*':
result2 = int (chunks[counter2+1]) * int (chunks[counter2+3])
elif chunks[counter2+2] == '/':
result2 = int (chunks[counter2+1]) / int (chunks[counter2+3])
chunks[counter2] = ''
chunks[counter2 + 1] = ''
chunks[counter2 + 2] = str (result2)
chunks[counter2 + 3] = ''
chunks[counter2 + 4] = ''
operation = ''.join(chunks)
Don't pay attention to the while condition, I'm updating it as I need just to check
You should try to debug code more on your own. The problem you have is the int conversion is being done on "-" and not "-5". You need to combine "-" and integer next in the sequence and convert that to int and use.
temp = str(chunks[counter2+3]) + str(chunks[counter2+4])

Binary Subtraction - Python

I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I've found on this website).
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 <= 0:
if carry == 0 and s != 0:
carry = 1
result = result + "1"
else:
result = result + "0"
else:
if carry == 1:
result = result + "0"
carry = 0
else:
result = result + "1"
i = i - 1
if carry>0:
result = result + "1"
return result[::-1]
The program works fine with some binaries subtraction but it fails with others.
Can someone please help me because I can't find the mistake? Thanks a lot.
Short answer: Your code is wrong for the case when s1[i] == s2[i] and carry == 1.
Longer answer: You should restructure your code to have three separate cases for s==-1, s==0, and s==1, and then branch on the value of carry within each case:
if s == -1: # 0-1
if carry == 0:
...
else:
...
elif s == 0: # 1-1 or 0-0
if carry == 0:
...
else:
...
else: # 1-0
if carry == 0:
...
else:
...
This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.
I hope the answer below it helps.
def binarySubstration(str1,str2):
if len(str1) == 0:
return
if len(str2) == 0:
return
str1,str2 = normaliseString(str1,str2)
startIdx = 0
endIdx = len(str1) - 1
carry = [0] * len(str1)
result = ''
while endIdx >= startIdx:
x = int(str1[endIdx])
y = int(str2[endIdx])
sub = (carry[endIdx] + x) - y
if sub == -1:
result += '1'
carry[endIdx-1] = -1
elif sub == 1:
result += '1'
elif sub == 0:
result += '0'
else:
raise Exception('Error')
endIdx -= 1
return result[::-1]
normalising the strings
def normaliseString(str1,str2):
diff = abs((len(str1) - len(str2)))
if diff != 0:
if len(str1) < len(str2):
str1 = ('0' * diff) + str1
else:
str2 = ('0' * diff) + str2
return [str1,str2]

Categories

Resources