I am trying to write a function in python that takes a phone number as a string and provides me all the permutations of number combinations that are 1 "character" away.
So for example if the phone number is 9879876 it would return 8879876, 6879876, 9579876, 9779876, 9979876, so on so forth. I have tried mapping it out each of the 10 options using str.replace but it changes all instances of that number rather than only that specific number. I've also tried using the "count" parameter in the replace function but it still did not work.
So to clarify, I wanted to create permutations with a pattern format.
rep1 = ["2","4"]
rep2 = ["1","3","5"]
rep3 = ["2","6"]
rep4 = ["1","5","7"]
rep5 = ["2","4","6","8"]
rep6 = ["3","5","9"]
rep7 = ["4","8"]
rep8 = ["5","7","9","0"]
rep9 = ["6","8"]
rep0 = ["8"]
If the current digit in the loop is 1 then replace that with each char in rep1 while keeping the rest of the phone number intact. If the current digit is a 2 then replace it with each char in rep2. I'm didn't use this list approach in my current code, its just for explanation of the conditional changes.
def myfunc(phone:str):
for digit in phone:
if digit == "1":
newphone = phone.replace("1", "2", 1)
print(newphone)
newphone = phone.replace("1", "4",1)
print(newphone)
if digit == "2":
newphone = phone.replace("2", "1",1)
print(newphone)
newphone = phone.replace("2", "3",1)
print(newphone)
newphone = phone.replace("2", "5",1)
print(newphone)
if digit == "3":
newphone = phone.replace("3", "2",1)
print(newphone)
newphone = phone.replace("3", "6",1)
print(newphone)
if digit == "4":
newphone = phone.replace("4", "1",1)
print(newphone)
newphone = phone.replace("4", "5",1)
print(newphone)
newphone = phone.replace("4", "7",1)
print(newphone)
if digit == "5":
newphone = phone.replace("5", "2",1)
print(newphone)
newphone = phone.replace("5", "4",1)
print(newphone)
newphone = phone.replace("5", "6",1)
print(newphone)
newphone = phone.replace("5", "8",1)
print(newphone)
if digit == "6":
newphone = phone.replace("6", "3",1)
print(newphone)
newphone = phone.replace("6", "5",1)
print(newphone)
newphone = phone.replace("6", "9",1)
print(newphone)
if digit == "7":
newphone = phone.replace("7", "4",1)
print(newphone)
newphone = phone.replace("7", "8",1)
print(newphone)
if digit == "8":
newphone = phone.replace("8", "5",1)
print(newphone)
newphone = phone.replace("8", "7",1)
print(newphone)
newphone = phone.replace("8", "9",1)
print(newphone)
newphone = phone.replace("8", "0",1)
print(newphone)
if digit == "9":
newphone = phone.replace("9", "6",1)
print(newphone)
newphone = phone.replace("9", "8",1)
print(newphone)
if digit == "0":
newphone = phone.replace("0", "8",1)
print(newphone)
This didn't work and there must be a more elegant solution and probably easier solution. Any help would be appreciated, thanks!