So I am working on this problem: Recall from the Number Systems unit the method for converting hexadecimal numbers to
binary by converting each hex digit to its equivalent four binary digits. Write a Python
function named hexToBinary with parameters (number, table) that uses this algorithm to
convert a hexadecimal number to a (return) binary number. The algorithm visits each digit
in the hexadecimal number, selecting from table the corresponding four bits that represent
that digit in binary and then adds these bits to the result string.
This is the code I have written, but I'm not getting it able to work properly:
def hexToBinary (hex, table):
hexToBinary= {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
final_hexToBinary = ''
for hex in hexToBinary:
final_hexToBinary+=hex
print(final_hexToBinary)
I am wondering what is wrong with the function, I have a feeling it is a simple mistake.
You forget this:
final_hexToBinary += hexToBinary[hex]
Also:
'table' -- not used var.
hexToBinary name of function and dict.
hex -- reserved word, argument and iterator.
It's not a problem, but sometime you can achieve mistake with that.
def hexToBinary (hex, table):
final_hexToBinary = ''
for each in hex:
final_hexToBinary+=table[each]
print(final_hexToBinary)
hexToBinaryTable = {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
hexToBinary("3FB",hexToBinaryTable)
As mentioned it comment your might want to look up the dictionary.
If you need not implement the function go for the one mentioned by john galt in comment.
if I am correct you are trying this:
def hexToBinary(my_hex):
hexToBinary= {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
final_hexToBinary = ''
for x in my_hex: # here it should be my_hex instead of table
final_hexToBinary += hexToBinary[x] # here was the mistake
print(final_hexToBinary)
hexToBinary("ABC12")
output:
10101011110000010010
NOTE: dont use hex as variable name its built-in python
Try this:
hexToBinary= {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
to_conv= input("enter a num: ")
final_hexToBinary = ''
for hex in to_conv:
final_hexToBinary += hexToBinary.get(hex,"!!") + " "
print(final_hexToBinary)
Related
As the title says I need help with the code as I can't understand what
other code I could write, per se I need
instructions exactly on how to write the following code:
Using letters as the telephone number is frequently used. So, for
instance the words GOT MILK can be converted to the phone number
468-6455.
Write a Python program that asks the user to enter a telephone number
as letters and then outputs the corresponding telephone number in
digits.
The program should output the '-' after the third digit. The program
should accept both upper- and lower-case letters, and spaces.
My Code:
input("Enter the telephone number as letters: ")
numbers = [('abc',2), ('def',3), ('ghi',4), ('jkl',5), ('mno',6), ('pqrs',7), ('tuv',8), ('wxyz',9)]
phone = ""
You can use a dictionary here,
d = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9'}
def convert(s):
r = ''.join(d.get(i, '') for i in s.lower())
return '{}-{}'.format(r[:3], r[3:])
print(convert('GOT MILK'))
# '468-6455'
You can use a dictionary for conversion.
numbers={'a':'2','b':'2','c':'2','d':'3','e':'3','f':'3','g':'4','h':'4','i':'4','j':'5','k':'5','l':'5','m':'6','n':'6',
'o':'6','p':'7','q':'7','r':'7','s':'7','t':'8','u':'8','v':'8','w':'9','x':'9','y':'9','z':'9'}
phone = ''
for l in input("Enter the telephone number as letters: "):
phone += numbers[l]
The above code have a predefined key value pairs. Then at the beginning of the loop, it asks the user to input and then it converts the user input to an iterator and assign each letter of the input to the variable l, and then concatenate to the empty phone variable. At the end of the loop, all the characters, would be mapped to a digit.
Just note that the user input should be exactly similar to the keys in the number variable. Other than those keys, the program raises and error. In the other suggested answer, the complexity comes from handling several common scenarios that may arise such as if the user input 'A' instead of 'a' and so on.
Given a word of input, all in uppercase letters, print the numbers you would need to type on a standard mobile phone keypad to enter that word. Assume that the phone can perfectly predict the word you want, and there are no numbers or punctuation symbols in the word.
For example:
Enter word: HELLO
43556
43556 is printed out since HELLO is entered by pressing 4, 3, 5, 5, 6.
My Code:
# A dictionary containing the letter to digit phone keypad mappings.
KEYPAD = {
'A': '2', 'B': '2', 'C': '2', 'D': '3', 'E': '3',
'F': '3', 'G': '4', 'H': '4', 'I': '4', 'J': '5',
'K': '5', 'L': '5', 'M': '6', 'N': '6', 'O': '6',
'P': '7', 'Q': '7', 'R': '7', 'S': '7', 'T': '8',
'U': '8', 'V': '8', 'W': '9', 'X': '9', 'Y': '9',
'Z': '9',
}
word = input("Enter word: ")
word = "\n".join(word)
wordx = word.split("\n")
for c in wordx:
if c in wordx:
print(KEYPAD[c], end="")
I have managed to produce the correct output. However, the problem case states that a "trailing newline character" must be included. Please note that I want the code to be printed on one line, such as in example.
You have a lot of unnecessary lines of code:
word = "\n".join(word)
wordx = word.split("\n")
This is not necessary. You insert newlines between the characters, just to split them again by new-line to a list. These two lines are equivalent to list(word). But this conversion is not necessary as well because input() returns a string which is iterable. Iterating over a string iterates over its characters.
for c in wordx:
if c in wordx:
...
It is not necessary to check if c in wordx. It obviously is because you are iterating over wordx...
A simplified version of your code would be:
word = input("Enter word: ")
for c in word:
print(KEYPAD[c], end="")
print()
Which can also be simplified further by using join instead of end=, just in a different way that you were using:
word = input("Enter word: ")
print(''.join(KEYPAD[c] for c in word)
I have a list like:
list = ['1', 'call-appr', '5', 'call-pickup', '2', 'call-appr', '6', 'call-park', '3', 'call-appr', '7', 'empty', '4', 'team', 'E', '123-456-212', 'R.']
I want to group them to get a dictionary of following format:
dict1 = {
'1': 'call-appr',
'2': 'call-appr',
'3':'call-appr',
'4': ['team','E','123-456-212','R'],
'5':'call-pickkup',
'6':'call-park',
'7':'empty'
}
Here's the code I tried:
for value in list:
if value.isdigit():
index = list.index(value)
list_index_num.append(index)
print (list_index_num)
for value in range(len(list_index_num)):
if value != len(list_index_num)-1:
number = range(list_index_num[value]+1, list_index_num[value+1])
else:
number = range(list_index_num[value]+1, len(list))
for i in number:
dct = {list[list_index_num[value]]:list[i]}
print (number)
You can use itertools.takewhile() and enumerate() with dictionary comprehension to achieve this as:
from itertools import takewhile
my_list = ['1', 'call-appr', '5', 'call-pickup', '2', 'call-appr', '6', 'call-park', '3', 'call-appr', '7', 'empty', '4', 'team', 'E', '123-456-212', 'R.']
my_dict = {s: list(takewhile(lambda x: not x.isdigit(), my_list[i+1:])) for i, s in enumerate(my_list) if s.isdigit()}
where my_dict will have:
{'1': ['call-appr'], '5': ['call-pickup'], '2': ['call-appr'], '6': ['call-park'], '3': ['call-appr'], '7': ['empty'], '4': ['team', 'E', '123-456-212', 'R.']}
Here I am using str.isdigit() as a filter to identify whether the string is a digit or not.
Note that here you are getting even single value items as list instead of string in your dictionary, which you can remove by doing explicit iteration on dictionary.
If you are on Python version 3.8+, you can remove it within dictionary comprehension by using Walrus Operator := as:
my_dict = {s: l if len(l:=list(takewhile(lambda x: not x.isdigit(), my_list[i+1:]))) > 1 else l[0] for i, s in enumerate(my_list) if s.isdigit()}
which will return you the dictionary in your desired format:
{
'1': 'call-appr',
'5': 'call-pickup',
'2': 'call-appr',
'6': 'call-park',
'3': 'call-appr',
'7': 'empty',
'4': ['team', 'E', '123-456-212', 'R.']
}
You could do this in a loop that avoids going through the list twice:
data = ['1', 'call-appr', '5', 'call-pickup', '2', 'call-appr',
'6', 'call-park', '3', 'call-appr', '7', 'empty',
'4', 'team', 'E', '123-456-212', 'R.']
dict1 = dict()
for v in data:
if v.isdigit(): dict1[v] = group = []
else: group.append(v)
print(dict1)
{'1': ['call-appr'], '5': ['call-pickup'], '2': ['call-appr'],
'6': ['call-park'], '3': ['call-appr'], '7': ['empty'],
'4': ['team', 'E', '123-456-212', 'R.']}
I would not recommend using a data structure where the type of value changes depending on the number of occurrences. This will make all the code using it more complex as it will constantly need to perform type checking.
If you need to do that however, you could modify the loop like this
dict1 = dict()
for v in data:
if v.isdigit(): k = v
elif k not in dict1: dict1[k],group = v,[v]
else: dict1[k] = group = group+[v]
print(dict1)
{'1': 'call-appr', '5': 'call-pickup', '2': 'call-appr',
'6': 'call-park', '3': 'call-appr', '7': 'empty',
'4': ['team', 'E', '123-456-212', 'R.']}
dict1 ={}
for element in list1:
if element.isdigit():
current_key = element
dict1[current_key] = []
else:
dict1[current_key].append(element)
# this part only flattens one-element lists
for key in list(dict1.keys()):
if len(dict1[key]) == 1:
dict1[key] = dict1[key][0]
I came up with something like this, it appears to do exactly what you were looking for.
I believe this would work:
dict={}
for i in range(0,len(my_list),2):
dict[my_list[i]]=my_list[i+1]
(note I changed your identifier list to my_list)
I am ordering a list of items that I replace with new ones, but by changing the letters by an equivalent in number and then ordering it, it cuts the order and does it in parts.
for (i) in range(len(unico)):
if unico[i] == 'A':
unico[i] = '14'
elif unico[i] == 'D':
unico[i] = '10'
elif unico[i] == 'J':
unico[i] = '11'
elif unico[i] == 'Q':
unico[i] = '12'
elif unico[i] == 'K':
unico[i] = '13'
for (i) in range(len(unico2)):
if unico2[i] == 'A':
unico2[i] = '14'
elif unico2[i] == 'D':
unico2[i] = '10'
elif unico2[i] == 'J':
unico2[i] = '11'
elif unico2[i] == 'Q':
unico2[i] = '12'
elif unico2[i] == 'K':
unico2[i] = '13'
repetido, repetido2, unico, unico2 =
sorted(repetido, reverse=True), sorted(repetido2, reverse=True),
sorted(unico, reverse=True), sorted(unico2, reverse=True)
print (unico,unico2)
I was expecting this output:
['14', '13', '10','8','4','3'] ['14', '13', '12', '10', '7', '6', '5']
..but this is what I am getting:
['8', '4', '3', '14', '13', '10'] ['7', '6', '5', '14', '13', '12', '10']
Your python code is behaving correctly. You have a list of strings. So, sorted() sorts the list by comparing them as a string. As '8' is greater than all other element, so appears in front of the list.
What you want, is to compare the elements of the list as integer. You can pass the key attribute of sort() to return the element as integer like this -
unico = ['3', '4', '8', '10', '14', '13']
unico.sort(key=lambda x: int(x), reverse=True)
print(unico)
Output:
['14', '13', '10', '8', '4', '3']
The code uses a lambda function to convert string element to integer during sorting but the element itself remains unchanged. Another thing is you are overriding your list after sort. So, you can just use sort() method of list instead of sorted().
I am looking to create a translator with Python that converts English into Morse Code. I was able to get it working but would like to improve it.
Here is what I have:
morse = {'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..',
'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..',
'0': '-----', '1': '.----', '2': '..---',
'3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..',
'9': '----.'}
print (morse['G'])
Now this works fine, but I would like for it to prompt me with a question such as "What would you like to translate?" and then have someone type (as a example) "This will will be converted to Morse Code". and have whatever is typed converted. Does anyone know a way to do this? it seems like such a hassle to type "print (morse['G'])" for each letter.
You can prompt users for input using the raw_input (python 2) or input (python 3) functions.
The input to these functions is the prompt that is displayed, and the function returns what is entered.
>stored_input = input('Please enter a line: ')
Please enter a line: Some input
>print stored_input
Some input
This function will return to you a string. I'll leave it up to you to learn how to break the string into its characters. Also, what if an input is not a capital letter or a number (e.g. a lower case number, or a '\')? Be sure to utilize google to figure out the rest, this question has been asked many, many times.