using python array in recursive function cause the reference loss - python

I tried to solve the question in a recursive way which is known as letter combinations of a telephone number.
In this question, telephone numbers are mapped to letters and for a given digits, the combinations of letters corresponding to the given digits are asked.
dic = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
}
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
I tried to solve it with recursion function but I got the unexpected output [""].
def telephoneHelper(digits, index, ans):
if(index==len(digits)):
return ans
else:
tmp=[]
for letter in dic[digits[index]]:
for an in ans:
tmp.append(an+letter)
ans=tmp
telephoneHelper(digits, index+1, ans)
def telephoneNumberRec(digits):
ans=[""]
if(len(digits)!=0):
telephoneHelper(digits, 0, ans)
return ans
ans=telephoneNumberRec("23")
print(ans)
I know there are many answers related to this topic but I am trying to understand the problem in this code.

You need to add two return statements (one in the telephoneNumberRec and one in the telephoneHelper function) so that the recursion actually works. The working code would look like this:
dic = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
}
def telephoneHelper(digits, index, ans):
if(index==len(digits)):
return ans
else:
tmp=[]
for letter in dic[digits[index]]:
for an in ans:
tmp.append(an+letter)
ans=tmp
return telephoneHelper(digits, index+1, ans)
def telephoneNumberRec(digits):
ans=[""]
if(len(digits)!=0):
return telephoneHelper(digits, 0, ans)
return ans
ans=telephoneNumberRec("23")
print(ans)

combinations = []
def telephoneHelper(digits,index, ans):
n = len(digits[0])
for i in range(n):
item = ans + digits[0][i]
if (index==len(digits)):
combinations.append(item)
else:
telephoneHelper(digits[1:],index+1, item)
return(combinations)
def telephoneNumberRec(input_):
a = []
for letter in input_:
a.append(dic[letter])
return (telephoneHelper(a, 0, '')) # a = [['a', 'b', 'c'], ['d', 'e', 'f']]
print (telephoneNumberRec('23'))
output:
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']

Related

How to convert a Python string in a list using no libraries

I'm trying to convert a string into a list wherever there is a bracket and using no libraries. So a string like '[wewr[sfs]]' should return ['w','e','w','r',['s','f','s']]. I'm not looking for a solution, just some guidance or advice over what is wrong with my code, the outcome I'm getting so far is ['w']
def my_function(s):
final_list = []
if d[0] == '[' and d[-1] == ']':
for i in d:
if i == '[':
final_list.append(my_function(d[(d.index('[')+1):(d.rindex(']'))]))
i = d(d.rindex(']') +1)
continue
elif i == ']':
break
else:
final_list.append(i)
return final_list```
You just have to think carefully about if-else-conditions:
def string_to_list(my_str):
out = []
for s in my_str.split('['):
if ']' in s[:-1]:
s1 = s.split(']')
s1 = [list(s1[0])]+list(s1[1])
elif s[-1:] == ']':
s1 = [list(s.strip(']'))]
else:
s1 = list(s)
out.extend(s1)
return out
print(string_to_list('[wewr[sfs]]'))
print(string_to_list('[wewr[sfs]da]'))
print(string_to_list('[wewr[sfs]da[ds]]'))
print(string_to_list('[wewr[sfs]da[ds][dfd]]'))
Output:
['w', 'e', 'w', 'r', ['s', 'f', 's']]
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a']
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a', ['d', 's']]
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a', ['d', 's'], ['d', 'f', 'd']]

Selection of inputs from given list

If I make list for e.g.
lst=['a','b','c','d','e','f','g','h','i','j','k','l','n','o','p','q','s','t','u','v','w','x','y','z']
I want a user to select input only from this given list
def select():
select=''
while guess not in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'p', 'q', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:
guess=input("select a letter? ")
return (select)
We can use this method but is there any other method so instead of putting the whole list we can put variable assign to that list
You need a while loop to ask the user get input till the input is valid like below:
In [1]: valid_input_lst=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
...: 'j', 'k', 'l', 'n', 'o', 'p', 'q', 's', 't',
...: 'u', 'v', 'w', 'x', 'y', 'z']
In [2]:
In [2]: input_char = None
In [4]: while True:
...: print("Input:")
...: input_char = input()
...: if input_char in valid_input_lst:
...: break
...: print("The input is not valid..\n. It should be one of :{}".format(valid_input_lst))
...:
Input:
sy
The input is not valid..
. It should be one of :['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'p', 'q', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Input:
x
You probably want something like this:
char = input('Enter a character')
if char not in list:
print("not a valid character")
You can't deny the user from entering anything, you should write software that knows how to handle the possible input.
get inquirer using pip:
pip install inquirer
here is an example
import inquirer
options = [
inquirer.List("option",
message="Select an option ",
choices=["A","B","C","D"],
),
]
select = inquirer.prompt(options)
#you can print option using 'select' variable

Print all possible strings of length k that can be formed from a set of n characters returns >n characters

Python novice here. The goal of the following Code is, to print all possible combinations to pair n characters of the set.
The Problem is that the following code gives an output, that also has more then n characters.
In the Following Code example n=3, but in the Output there are combinations with more then 3.
Code:
def printAllKLength(set, k):
n = len(set)
printAllKLengthRec(set, "", n, k)
def printAllKLengthRec(set, prefix, n, k):
if (k == 0) :
print(prefix)
return
for i in range(n):
newPrefix = prefix + set[i]
printAllKLengthRec(set, newPrefix, n, k-1)
if __name__ == "__main__":
print("First Test")
set1 = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S','T','V','W','Y']
k = 3
printAllKLength(set1, k)
Output:
WNT
WNV
WNW
WNY
WPQA
WPQC
WPQD
WPQE
WPQF
WPQG
WPQH
WPQI
WPQK
WPQL
WPQM
WPQN
WPQPQ
WPQR
WPQS
WPQT
WPQV
WPQW
WPQY
WRA
The aim would be to generate strictly strings of length 3, so if anyone could point me in the right direction, I would be more than grateful.
I rewrote you functions a bit and stripped them to the essentials:
def printAllKLength(set, k):
printAllKLengthRec(set, "", k)
def printAllKLengthRec(set, string, k):
if len(string) == k:
print(string)
return
for c in set:
printAllKLengthRec(set, string + c, k)
return
if __name__ == "__main__":
print("First Test")
set1 = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K',
'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
k = 3
printAllKLength(set1, k)
A little hint for next time, break you sample size down to for example len(set1) = 3. then it is far easier to debug and you don't get lost in your own code.
You can use Itertools' combinations function. It takes an iterable and the length of the combination as parameters.
import itertools
num_char = 3
my_set = {'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'}
combinations = itertools.combinations(my_set, num_char)
for i in combinations:
print("".join(i))

How do I converted the string of a nested list back to a nested list?

Sorry if this is breaking any rules, it's my first time posting here. The project that we're working on is to create Connect 4 in Python. We're currently struggling on how to get the game to save and load.
What we're doing so far is saving our 2D list in a .txt file and trying to load the game by reading it. The problem that we've encountered is when you're trying to read the file, it reads as a string instead of a list. For example:
[['R', 'R', 'Y', 'R', 'Y', 'Y', 'Y'], ['Y', 'Y', 'R', 'R', 'R', 'Y', 'Y'], ['R', 'R', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E']]
That gets saved as a string and we'd like to convert it back to be used to place saved dots back where they belong.
def save():
global GAME_LIST
save_file = open("savedGame.txt","w")
print('Game', GAME_LIST)
save_file.write(str(GAME_LIST))
#Will basically be the new def main() once you load a file.
def load():
global PIECES
savedFile = open("savedGame.txt","r")
loadedState = savedFile.readline()
print(loadedState)
grid()
PIECES = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0}
def newRed(column):
coordinates = {'1': -210, '2': -140, '3': -70, '4': 0, '5': 70, '6': 140, '7': 210}
red = turtle.Turtle()
red.hideturtle()
red.up()
#Pieces * Cell length for Y value
red.goto(coordinates[column], -160 + (PIECES[column] * 70))
PIECES[column] += 1
red.dot(60, 'red')
def newYellow(column):
coordinates = {'1': -210, '2': -140, '3': -70, '4': 0, '5': 70, '6': 140, '7': 210}
#Computer turtle
yellow = turtle.Turtle()
yellow.hideturtle()
yellow.up()
yellow.goto(coordinates[column], -160 + (PIECES[column] * 70))
PIECES[column] += 1
yellow.dot(60, 'yellow')
def toList(stringState):
sublist = []
for characters in stringState:
sublist.append(characters)
print(sublist)
return sublist
def reDot(loadedState):
global ROW
global COLUMN
for sortList in range(ROW):
newList = loadedState[sortList]
for sortSubList in range(COLUMN):
sortSubList = int(sortSubList)
if newList[sortSubList] == "R":
newRed(sortSubList + 1)
elif newList[sortSubList] == "Y":
newYellow(sortSubList + 1)
newList = toList(loadedState)
reDot(newList)
This is a snippet of our code for reference. reDot() is supposed to take the location of 'R'/'Y' and place a dot there.
If you want to save data into files and read them back, I think JSON library will be helpful to you, very easy to use, this way:
data = [['R', 'R', 'Y', 'R', 'Y', 'Y', 'Y'], ['Y', 'Y', 'R', 'R', 'R', 'Y', 'Y'], ['R', 'R', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E']]
with open('game_data.json', 'w') as fp:
json.dump(data, fp)
And then when you want to read it back:
with open('game_data.json', 'r') as fp:
data = fp.read()
You may also want to wrap the above code with a try-except block in case the file was not found or any other exception.

Split python list into rows without libraries

I have a list of letters in Python that I would like to split into even-length chunks that will display as rows. For pedagogical reasons, I want to do it without using and libraries (including numpy or Pandas). No, this is not a homework question-- I'm teaching myself.
In R I would be using a vector instead of a list; a simple as.matrix(vector, ncol = n) would do the trick. Is there an equivalent in Python?
As an example, I've tried the following based on other SO answers:
alphabet = map(chr, range(65, 91))
print alphabet
> ['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']
def chunks(l, n):
n = max(1, n)
return [l[i:i + n] for i in range(0, len(l), n)]
print chunks(alphabet, 4)
> [['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']]
That generally works, but I would like the output to look like this:
[['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']]
Ideally, I will extend the functionality to make the "most square" rectangle. Ie, I will pull out the highest factors of the length of the list and then use the smaller number as the number of columns, so if possible I want a very generalized answer.
I would define a new function that prints the chunks line by line.
def print_chunks(chunk_result):
for chunk in chunks:
print(chunk)
I believe this will give you the output you're looking for.
To get slicing behaviour, you will want to implement your own class. I have quickly whipped out something that should get you started, but I have not checked it thoroughly.
class Chunk(object):
"""docstring for Chunk"""
def __init__(self, l, n):
super(Chunk, self).__init__()
self.chunks = self.chunk(l, n)
def __repr__(self):
"""
Done in a non-standard way.
"""
for chunk in self.chunks:
print(chunk)
def __getitem__(self, key):
if isinstance(key, slice):
return self.chunks[i] for i in xrange(*key.indices(len(self.chunks)))
elif isinstance(key, int):
if key < 0:
key += len(self.chunks)
if key >= len(self):
raise IndexError('The index {0} is out of range'.format(key))
return self.chunks[i]
For reference, I looked at the following SO posts:
Python: Implementing slicing in __getitem__
Just use print each list within:
for line in chunks(alphabet, 4):
print line

Categories

Resources