Convert alphanumeric phone numbers with letters into numbers - python

I have an assignment where we have to convert alphanumeric phone numbers into just numbers. For example "555-PLS-HELP" should convert into "555-757-4357". I wrote some of it but it keeps giving me incorrect output.
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = str(input("Please enter a phone number: "))
counter = len(phone_number[:4])
total = phone_number[:4]
while counter > 0:
alpha = phone_number[-counter]
if alpha.isalpha():
total += num[alph.index(alpha)]
else:
total += alpha
counter -= 1
print(total)
I keep getting weird output.
For example:
Please enter a phone number: '555-PLS-HELP'
Gives:
555-4357

There are a few things to consider in your code:
Changing your first slice to counter = len(phone_number[4:]) produces a working solution: you'd like to iterate for the length of the rest of the number rather than the length of the area code prefix.
A simple for n in phone_number is preferable to taking len() and iterating using a counter variable and indexing from the rear with -counter, which is non-intuitive.
input() returns a str; there's no need for a superfluous cast.
This is a perfect situation for a dictionary data structure, which maps keys to values and is an explicit version of what you're already doing. Use zip to combine your strings into a dictionary.
In the list comprehension, each character is looked up in the keypad dictionary and its corresponding entry is returned. Using the dict.get(key, default) method, any items not present in the dictionary will be default.
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
keypad = dict(zip(alph, num))
phone_number = input("Please enter a phone number: ")
print("".join([keypad.get(x, x) for x in phone_number]))
Try it!

alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = str(input("Please enter a phone number: "))
counter = len(phone_number)
total = ''
while counter > 0:
alpha = phone_number[-counter]
if alpha.isalpha():
total += num[alph.index(alpha)]
else:
total += alpha
counter -= 1
print(total)
Test:
Please enter a phone number: '555-PLS-HELP'
Output:
555-757-4357

Try the following:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
# converts the above lists into a dict
lookup = dict(zip(alph, num))
phone_number = input("Please enter a phone number: ")
result = ''
for c in phone_number:
# if needs changing
if c.isalpha():
result += lookup[c.upper()]
# simply append otherwise
else:
result += c
print(result)
Result:
Please enter a phone number: 555-PLS-HELP
Output:
555-757-4357

You could just iterate through the inputted number, check if it's alphabet and get the corresponding number if so, all in one-line:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = input("Please enter a phone number: ")
print(''.join([num[alph.index(x.upper())] if x.isalpha() else x for x in phone_number]))
Sample run:
Please enter a phone number: 555-PLS-HELP
555-757-4357
If it's an alphabet, this gets the index of the alphabet from alph and use that to look up in the num to get corresponding number. In the else case, just copies the number.

Why you are considering only last 4 characters of an a-priori unknown string? You could search first if phone_number has some alphabetic characters, and if it does, then starting from the first occurrence of such an alphabetic character you can replace it with the correct digit. This works for capital letters:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = raw_input("Please enter a phone number: ")
def fstAlpha(string):
for i in range(0,len(string)):
if string[i].isalpha():
return i
return -1
index = fstAlpha(phone_number);
if index != -1:
for i in range(index,len(phone_number)):
if(phone_number[i].isalpha()):
to_replace = phone_number[i]
replace_with = num[alph.index(to_replace)]
phone_number = phone_number.replace(to_replace,replace_with)
print phone_number

Related

How can I limit the number of integers input?

I am trying to make a program that will ask the user to input 25 integers.
This is where I'm at now:
while True:
numbers = list(map(int, input("Enter 25 numbers (seperate it with space): ").split()))
This should do the trick. It will prompt you with the question again if you do not enter the right amount of characters. Plus, it does not count spaces as characters.
gettingInput = True
while gettingInput:
numbers = list(map(int, input("Enter 25 numbers (seperate it with space): ").split()))
if len(numbers) - numbers.count(" ") > 25:
gettingInput = True
else:
gettingInput = False
# (- numbers.count(" ") will not count spaces as characters.)

Verifying if user input is in multiple zero values

How can we check if a user enters the value 0 multiple times in a row?
I have tried below code- here I have tried to define multiple value in list, but if the user enters 000000000 or more, I have to define till 000000000 in list is there any other way to achieve this
list = [0,00,000,0000]
num = int(input("Enter a number: "))
if num in list:
print("Zero")
elif :
print(" None ")
You need to take the input as a string. And you can check if the user has entered a string that will have all zeros in it as follows
def all_zeros(string):
return all(ch == '0' for ch in string)
This worked for me
num = input("Enter: ")
if num.count('0') > 0 and num.startswith('0'):
print("0")
else:
print("none")
Since you asked in this way
How can we check if a user enters the value 0 multiple times in a row?
But, other answers were checking whether more than one 0's are present in the string or not. I assume you want to check continuous zero's only,
num = input("Enter Number: ") # returns string
if "00" in num: #checking substring
print("Found continuous zeros")
else:
print("Entered no continous zeros!")
value = int(num) # convert it to int if needed
It doesn't matter how many zeros in the string, all these [00,000,0000,00000...] belong to the same category.
Output:
>>> num = input("Enter Number: ")
Enter Number: 0008
>>> num
'0008'
>>> "00" in num
True
>>>
num = input("Enter: ")
if num.count("0") > 1 and int(num) == 0:
print("0")
else:
print("none")
don't change num to int it will remove all the trailing zeroes

Only the last item is being appended to a list in a while loop (Python)

I'm trying to create a program that gets each digit of an inputted number into a list using a while loop. However, it only appends the last digit of the number to the list.
Code -
num = int(input("Enter a number: "))
numstr = str(num)
numlen = len(numstr)
x = 0
while x < numlen:
digits = []
a = numstr[x]
digits.append(a)
x = x + 1
print(digits)
So if I were to put in 372 as the number, the list would just simply be ['2'] with a length of 1.
Try this code:
digits = [i for i in str(num)]
You cannot do better than digits = list(str(num)). In fact, since input returns a string, even the conversion to a number is not necessary:
num = input("Enter a number: ")
digits = list(num)
(You still may want to ensure that what's typed is indeed a number, not a random string.)

Basic list checker

I want to create a list, then enter an int, which will then add the int amount of strings to a list,then print it. So far so good:
list = []
number = int(raw_input("Enter a number: "))
while number > 0:
list.append(str(raw_input("Enter a word: ")))
number = number - 1
print list
However, how do I make it a little more advanced so that you cannot add the same string twice to the list?
You can keep a set of all the strings seen, only adding a string and if it has not been seen before, you don't need to keep a count variable either, you can loop until len(data) != number:
number = int(raw_input("Enter a number: "))
seen = set()
data = []
while len(data) != number:
inp = raw_input("Enter a word: ")
if inp not in seen:
data.append(inp)
seen.add(inp)
If the order was irrelevant you could just use a set altogether as sets cannot have dupes:
number = int(input("Enter a number: "))
data = set()
while len(data) != number:
inp = raw_input("Enter a word: ")
data.add(inp)
Check for whether the list already contain the entered string or not before appending. And don't use in-built keywords as variable names.
list_ = []
number = int(raw_input("Enter a number: "))
while number > 0:
x = raw_input("Enter a word: ")
if not x in list_:
list_.append(x)
number = number - 1
else:
print "Word is already available"
print list_
you can do something like this
mylist = []
number = int(raw_input("Enter a number: "))
while number > 0:
mystring = str(raw_input("Enter a word: "))
if mystring not in mylist:
mylist.append(mystring)
number = number - 1
else:
print('Choose different string')
next
print mylist
and try to avoid build-in function as variable name. Built-in functions are
https://docs.python.org/2/library/functions.html

Python function using appends with lists not very efficient

Trying to write a function which takes input of 4 digit numbers and compares them, output of Ys and Ns to try and check if they are the same. EG 1234 and 1235 would output YYYN. At the minute it's very inefficient to keep using all these append commands. How could I simplify that?
def func():
results=[]
firstn= str(input("Please enter a 4 digit number: "))
secondn= str(input("Please enter a 4 digit number: "))
listone= list(firstn)
listtwo= list(secondn)
if listone[0]==listtwo[0]:
results.append("Y")
else:
results.append("N")
if listone[1]==listtwo[1]:
results.append("Y")
else:
results.append("N")
if listone[2]==listtwo[2]:
results.append("Y")
else:
results.append("N")
if listone[3]==listtwo[3]:
results.append("Y")
else:
results.append("N")
print(results)
Furthermore, how can I validate this to just 4 digits for length and type IE. Nothing more or less than a length of four / only numerical input? I have been researching into the len function but don't know how I can apply this to validate the input itself?
For the validation, you can write a function that will ask repeatedly for a number until it gets one that has len 4 and is all digits (using the isdigit() string method).
The actual comparison can be done in one line using a list comprehension.
def get_number(digits):
while True:
a = input('Please enter a {} digit number: '.format(digits))
if len(a) == digits and a.isdigit():
return a
print('That was not a {} digit number. Please try again.'.format(digits))
def compare_numbers(a, b):
return ['Y' if digit_a == digit_b else 'N' for digit_a, digit_b in zip(a, b)]
first = get_number(4)
second = get_number(4)
print(compare_numbers(first, second))
I think this should work.
def compare(a,b):
a,b = str(a),str(b)
truthvalue = {True:"Y",False:"N"}
return "".join([truthvalue[a[idx]==b[idx]] for idx,digit in enumerate(a)])
print(compare(311,321)) #Returns YNY
print(compare(321312,725322)) #Returns NYNYNY
def two_fourDigits():
results = []
firstn = input("Please enter the first 4 digit number: ")
while firstn.isnumeric() == False and len(firstn) != 4:
firstn= input("Please enter the second 4 digit number: ")
secondn = input("Please enter a 4 digit number: ")
while secondn.isnumeric() == False and len(secondn) != 4:
secondn= input("Please enter a 4 digit number: ")
for i in range(0, len(firstn)):
if firstn[i] == secondn[i]:
results.append("Y")
else:
results.append("N")
print(results)
You don't need to convert the input to a string, the input() function automatically takes in the values as a string.
Second, I added in input validation for firstn and secondn to check that they were numeric, and to check if they are the correct length (4). Also, there is no need to change the input to a list, because you can search through the strings.
I tried to do your function like this. Basically, the function uses the length of the first string to iterate through all the values of each list, and return Y if they are the same and N if they are not.
Because you don't make it a global variable which can be used from out of the function. Here is an example:
my_list = []
def my_func():
global my_list
my_list.append(0)
return "Something..."
my_list.append(1)
print my_list

Categories

Resources