Converting hexadecimal to binary example - python

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)

Related

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

python: if condition, it is very simple calculation, but it does not work

I wrote very simple calculation function as below;
direction == B
number == 2
def price_cal():
if direction == 'A' and (number == 1):
return 1
elif direction == 'A' and (1 < number <= 9):
return 2
elif direction == 'A' and (9 < number <= 13):
return 3
elif direction == 'B' and (number == 1):
return 4
elif direction == 'B' and (1 < number <= 9):
return 5
else:
return 6
price_cal()
If I run the function above with those inputs, then return has to be '5' right? but I got '6' (return 6)
When I run this function, only I get right answers from the first
if direction == 'A' and number == 1:
return 1
the rest of them, I get only answers from the last function
else:
return 6
I don't know why this happen... please correct this simple function, much appreciated
ps; someone asked me to put some input... I think he does not understand this simple function anyway I put some above now.
I refactor your code to make it more readable, maybe now you realize your mistake:
def price_cal():
no_p = int(no_of_passenger)
sub = int(suburbs.get(suburb))
if direction == 'A' :
if no_p == 1 :
return sub + (no_p * 10)
if 1 < no_p <= 9:
return sub + (no_p * 10) - 10
if 9 < no_p <= 13:
return sub + (no_p * 10) + 20
if direction == 'B':
if no_p == 1 :
return sub + (no_p * 10) + 10
if 1 < no_p <= 9:
return sub + (no_p * 10)
return sub + (no_p * 10) + 20
post some input sample values for direction no_p and sub with the respective expected output, to offer you further help
just want to let you know that when you use and it checks for both being true, and or checks for at least one being true. So here it might execute
if direction == 'Drop off to airport' or no_p == 1: return sub + (no_p * 10)
and
elif direction == 'Pickup from airport' or no_p == 1: return sub + (no_p * 10) + 10
no matter the input, because I assume direction is always exactly "Drop off to airport" or "Pickup from airport". if the and wasn't working why don't you check which of the conditions was not being checked properly?+ the direction string might not have the capital letter in the input or no_p might be a string(instead of integer type)
*disclaimer I am a beginner myself
I found the answer for my question
here are the codes it works fine below;
def price_detail(request):
if request.method == "POST":
flight_date = request.POST.get('flight_date')
direction = request.POST.get('direction')
suburb = request.POST.get('suburb')
no_of_passenger = request.POST.get('no_of_passenger')
sub = int(suburbs.get(suburb))
no_p = int(no_of_passenger)
def price_cal1():
if direction == 'Drop off to airport' and no_p == 1:
return sub + (no_p * 10)
elif direction == 'Drop off to airport' and 1 < no_p <= 9:
return sub + (no_p * 10) - 10
elif direction == 'Drop off to airport' and 9 < no_p <= 13:
return sub + (no_p * 10) + 10
elif direction == 'Pickup from airport' and no_p == 1:
return sub + (no_p * 10) + 10
elif direction == 'Pickup from airport' and 1 < no_p <= 9:
return sub + (no_p * 10)
else:
return sub + (no_p * 10) + 20
price_cal1()
price = str(price_cal1())
Sorry... I found what the problem was. On html (webpage) {key and value} was not exactly same as objects in views.py... it was capital in html, just one letter but it was small letter in views. simeple mistake!

Convert between str and int without using built-in typecasting

NB: You may not use built-in typecasting: code this yourself.
def str2int(s):
result = 0
if s[0] == '-':
sign = -1
i = 1
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
result = sign * result
return result
else:
i = 0
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
return result
NB: You may not use built-in str() or string template. Code this yourself.
def int2str(i):
strng = ""
if i > 0:
while i != 0:
num = i % 10
strng += chr(48+num)
i = i / 10
return strng[::-1]
else:
while i != 0:
num = abs(i) % 10
strng += chr(48+num)
i = abs(i) / 10
return '-' + strng[::-1]
I am a newbie and I have to write code based on basic. I write these function by myself but these look weird. Can you help me to improve code? Thank you
This maybe a better question for https://codereview.stackexchange.com/.
Not withstanding there is no error checking, one obvious comment is you have common code that can be factored out. Only capture in the if, else what is unique rather than repeat the while loop:
def str2int(s):
if s[0] == '-':
sign = -1
i = 1
else:
sign = 1
i = 0
result = 0
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
return sign * result
It is generally considered better form in python to iterate over list rather than indices:
def str2int(s):
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
result = 0
for c in s:
num = ord(c) - ord('0')
result = result * 10 + num
return sign * result
These last lines are equivalent to a standard map and reduce (reduce is in functools for py3). Though some would argue against it:
from functools import reduce # Py3
def str2int(s):
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
return sign * reduce(lambda x,y: x*10+y, map(lambda c: ord(c) - ord('0'), s))
There are similar opportunities to do the same for int2str().

Cannot find error trying to convert zipcode to binary

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)

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