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)
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.
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().
There are lots of similar posts out there, but I could not find something that directly matched, or resulted in a solution to, the issue I am dealing with.
I want to use the second instance of a repeated index contained in a list as the index of another list. When the function is executed, I want all numbers from the start of the list up to the first '\*' to print after Code1, all numbers between the first '\*' and the second '\*' to print after Code2, and then all numbers following the second '\*' until the end of the list to print after Code3. Example data for digit would be "['1', '2', '3', '4', '5', '\*', '6', '\*', '7', '8', '9', '10', '1']".
In other words, I want the code below to print , assuming those digits exist, User Code: 12345, Pass Code: 6, Pin Code: 789101, all in one line.
print_string += 'User Code: {} '.format(''.join(str(dig) for dig in digit[:digit.index('*')])) + \
'Pass Code: {} '.format(''.join(str(dig) for dig in digit[digit.index('*'):digit.index('*')])) + \
'Pin Code: {} '.format(''.join(str(dig) for dig in digit[digit.index('*'):]))
print(print_string)
Essentially, I would like to call the first asterisk as the right index for User Code, the first asterisk as the left index and the second asterisk as the right index for Pass Code, and the second asterisk as the left index for Pin Code.
I just cannot figure out how make it look for sequential asterisks. If there is a simpler way to execute this, please let me know!
Given,
L = ['1', '2', '3', '4', '5', '\*', '6', '\*', '7', '8', '9', '10', '1']
Then
str.join('', L)
will form a string
'12345\\*6\\*789101'
which you can split into the three parts
parts = str.join('', L).split('\*')
and then pull out what you need
user_code = parts[0]
pass_code = parts[1]
pin = parts[2]
If you have actually got all the digits in a list like shape ina string,
"['1', '2', '3', '4', '5', '\*', '6', '\*', '7', '8', '9', '10', '1']"
it might be worth just having them as a list, then you can use the join/split method above.
I'm relatively new to python(3.5.2) and I'd love some help with my assignment on lists& strings.
I am required to write a code that replaces: e and E with 3, a and A with 4, i and I with 1, o and O with 0 in any given string. Here is my attempt:
s = input("Enter a string: ")
leet = {'a':'4','e':'3','i':'1','o':'0','A':'4','E':'3','I':'1','O':'0'}
for character in s:
if character == leet.keys():
str.replace(leet.keys(),leet.values())
print(s)
This code does not yield any satisfying results for me, I'm wondering if I can use the str.replace method or is there any easier way of doing this?
Thanks!
you can do that in one line using a generator comprehension converted to a string using str.join (Using dict.get with defaults to the input character if not found in dictionary):
s = "a string Entered"
leet = {'a':'4','e':'3','i':'1','o':'0','A':'4','E':'3','I':'1','O':'0'}
crypted = "".join(leet.get(k,k) for k in s)
print(crypted)
result:
4 str1ng 3nt3r3d
replace() method is good. But you use it wrong. Remember that leet.keys() will return a list of all keys in the dictionary. So I suggest this:
s = input("Enter a string: ")
leet = {'a': '4', 'e': '3', 'i': '1', 'o': '0', 'A': '4', 'E': '3', 'I': '1', 'O': '0'}
for k, v in leet.items(): #iterating through dictionary (not string)
s = s.replace(k, v)
print(s)
I'm trying to get a function to take a string dec, representing a decimal number, for example "11" and I want said function to return a string, which contains the corresponding binary format, in this case "1011".
So this is what I have so far:
def dec2bin(dec):
dec = str("11")
if dec > 1:
binary(dec//2)
return (dec % 2,end = "")
I'm very new to Python, so I'm not sure how to turn a number into a string (using str()) in the first place and how to make it return the corresponding binary value. Can anyone point me in the right direction?
This should work:
def dec2bin(num):
return bin(int(num))[2:]
int converts the string num into an integer. bin converts it into its binary representation (a string again). The [2:] drops the first two characters, which are only an indicator for the binary representation.
The following will work:
def dec2bin(dec):
return format(int(dec), "b")
You can test it like this:
print dec2bin("11")
Assuming you can use int to convert the string to an integer:
def dec2bin(snum):
n = int(snum)
bin_s = ['1' if (n >> b) & 1 else '0' for b in range(n.bit_length())]
return ''.join(reversed(bin_s))
let's test it
>>> dec2bin('11')
'1011'
Basically, it scans the integer obtained from the string and checks every bit in it.
It shifts the number to the right and checks the least significant bit and-ing it with the value 1 (alternatively we could shift the mask to the left and leave the number unchanged).
The result of each bit-check is used to populate a list, which is then reversed and joined to form a string.
If using list comprehensions would make you look too cool to be true, use a for loop:
def dec2bin(snum):
n = int(snum)
bin_s = []
for b in range(n.bit_length()):
cur_bit = (n >> b) & 1
sbit = chr(ord('0') + cur_bit)
bin_s.append(sbit)
return ''.join(reversed(bin_s))
Another solution, in case you can use python's builtin format function, would be:
def dec2bin(snum):
return format(int(snum),"b")
Further note to clarify the algorithm (the main assumption is that we are only talking about unsigned integers):
Computers use binary representation of data (i.e. bits, zero and ones). Put one after the other, from right to left, they form a number in ascending powers of two, just like decimal digits do.
For example the number thirteen (13 is its representation in base ten: 1*10^1+3*10^0) is written as 1101 in binary (1*2^3+1*2^2+0*2^1+1*2^0) and stored in memory as bits within bytes (8-bits).
The LSB (Least Significant Bit) is the least powerful bit (binary digit), i.e. the rightmost one in 1101, because it weighs the least in terms of power of two.
Python allows a variable size for integers, that is why I use the bit_length method to find out how many bits are necessary to store that number. Other languages (e.g. C) allocate a predefined size to numbers, normally the same (or less) as the width of the registers the CPU provides.
Here is a function that also allows you to choose the number of digits in the output.
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)])
It normally takes an int:
print int2bin(44)
'000000000000000000101100'
but you can use a string by converting it to int first:
print int2bin(int("44"))
'000000000000000000101100'
The challenge here is to write a string processing algorithm that doesn't use any python math function. A specification for the following program can be found here.
Python Program
while True:
indecimal_str = input('Enter (decimal) integer: ')
if indecimal_str == '':
raise SystemExit
indecimal = list(indecimal_str)
exbin = []
print(indecimal, '<->', exbin)
while True:
if len(indecimal) == 0:
print('Conversion', indecimal_str, '=', "".join(exbin))
print()
break
carry_state = False
g = indecimal[len(indecimal)-1]
if g in '02468':
exbin.insert(0, '0')
elif g in '13579':
exbin.insert(0, '1')
if g == '1': indecimal[len(indecimal)-1] = '0'
elif g == '3': indecimal[len(indecimal)-1] = '2'
elif g == '5': indecimal[len(indecimal)-1] = '4'
elif g == '7': indecimal[len(indecimal)-1] = '6'
else : indecimal[len(indecimal)-1] = '8'
else:
print('Input not valid')
raise SystemError
for i in range(0,len(indecimal)):
if carry_state == False:
if indecimal[i] in '13579':
carry_state = True
if indecimal[i] in '01':
indecimal[i] = '0'
elif indecimal[i] in '23':
indecimal[i] = '1'
elif indecimal[i] in '45':
indecimal[i] = '2'
elif indecimal[i] in '67':
indecimal[i] = '3'
elif indecimal[i] in '89':
indecimal[i] = '4'
else:
print('Input not valid')
raise SystemError
else: # carry_state == True
if indecimal[i] in '02468':
carry_state = False
if indecimal[i] in '01':
indecimal[i] = '5'
elif indecimal[i] in '23':
indecimal[i] = '6'
elif indecimal[i] in '45':
indecimal[i] = '7'
elif indecimal[i] in '67':
indecimal[i] = '8'
elif indecimal[i] in '89':
indecimal[i] = '9'
else:
print('Input not valid')
raise SystemError
if indecimal[0] == '0':
indecimal.pop(0)
print(indecimal, '<->', exbin)
OUTPUT
Enter (decimal) integer: 8
['8'] <-> []
['4'] <-> ['0']
['2'] <-> ['0', '0']
['1'] <-> ['0', '0', '0']
[] <-> ['1', '0', '0', '0']
Conversion 8 = 1000
Enter (decimal) integer: 37
['3', '7'] <-> []
['1', '8'] <-> ['1']
['9'] <-> ['0', '1']
['4'] <-> ['1', '0', '1']
['2'] <-> ['0', '1', '0', '1']
['1'] <-> ['0', '0', '1', '0', '1']
[] <-> ['1', '0', '0', '1', '0', '1']
Conversion 37 = 100101
Enter (decimal) integer: 409
['4', '0', '9'] <-> []
['2', '0', '4'] <-> ['1']
['1', '0', '2'] <-> ['0', '1']
['5', '1'] <-> ['0', '0', '1']
['2', '5'] <-> ['1', '0', '0', '1']
['1', '2'] <-> ['1', '1', '0', '0', '1']
['6'] <-> ['0', '1', '1', '0', '0', '1']
['3'] <-> ['0', '0', '1', '1', '0', '0', '1']
['1'] <-> ['1', '0', '0', '1', '1', '0', '0', '1']
[] <-> ['1', '1', '0', '0', '1', '1', '0', '0', '1']
Conversion 409 = 110011001