python maze using recursion - python

I want to solve a maze using recursion. The program opens a text file like this one:
10 20
1 1
10 20
-----------------------------------------
| | | | | | | | | |
|-+ +-+-+ +-+ + +-+ + + +-+-+ +-+-+ + + |
| | | | | | | | | |
| + +-+ + + +-+-+-+ + + + + + +-+ + + + |
| | | | | | | | | | |
| +-+-+-+-+ +-+ +-+-+-+-+ +-+ + +-+-+ +-|
| | | | | | | | | | |
| + + +-+ +-+-+ + + + +-+ +-+ + + + +-+ |
| | | | | | | | | | | |
|-+-+ +-+-+-+-+-+-+-+ +-+ +-+-+ +-+-+ +-|
| | | | | | | | | | | |
| +-+-+ +-+-+ +-+ + +-+-+ +-+ +-+ + + + |
| | | | | | | | | | |
|-+ +-+ + + +-+ +-+-+ + +-+ + + +-+ +-+ |
| | | | | | | | | | | | | | | | |
|-+ + +-+ + + + + + +-+ + + + + +-+-+ + |
| | | | | | | |
| + + +-+ + +-+-+-+ + +-+ + + +-+-+ +-+ |
| | | | | | | | | | |
-----------------------------------------
The first line of the file is the size of the maze(10 20), the second line is the starting point(1 1), and the third line is the exit(10, 20). I want to mark the correct path with "*". This is what my code looks like:
EDIT: I change some of the code in the findpath() funtion, and now I dont get any errors but the maze is empty, the path('*') is not 'drawn' on the maze.
class maze():
def __init__(self, file):
self.maze_list = []
data= file.readlines()
size = data.pop(0).split() # size of maze
start = data.pop(0).split() # starting row and column; keeps being 0 because the previous not there anymore
self.start_i = start[0] # starting row
self.start_j = start[1] # starting column
exit = data.pop(0).split() # exit row and column
self.end_i = exit[0]
self.end_j = exit[1]
for i in data:
self.maze_list.append(list(i[:-1])) # removes \n character off of each list of list
print(self.maze_list) # debug
def print_maze(self):
for i in range(len(self.maze_list)):
for j in range(len(self.maze_list[0])):
print(self.maze_list[i][j], end='')
print()
def main():
filename = input('Please enter a file name to be processed: ') # prompt user for a file
try:
file = open(filename, 'r')
except: # if a non-existing file is atempted to open, returns error
print("File Does Not Exist")
return
mazeObject = maze(file)
mazeObject.print_maze() # prints maze
row = int(mazeObject.start_i)
col = int(mazeObject.start_j)
findpath(row, col, mazeObject) # finds solution route of maze if any
def findpath(row, col, mazeObject):
if row == mazeObject.end_i and col == mazeObject.end_j: # returns True if it has found the Exit of the maze
mazeObject.maze_list[row][col] = ' ' # to delete wrong path
return True
elif mazeObject.maze_list[row][col] == "|": # returns False if it finds wall
return False
elif mazeObject.maze_list[row][col] '-': # returns False if it finds a wall
return False
elif mazeObject.maze_list[row][col] '+': # returns False if it finds a wall
return False
elif mazeObject.maze_list[row][col] '*': # returns False if the path has been visited
return False
mazeObject.maze_list[row][col] = '*' # marks the path followed with an *
if ((findpath(row + 1, col, mazeObject))
or (findpath(row, col - 1, mazeObject))
or (findpath(row - 1, col, mazeObject))
or (findpath(row, col + 1, mazeObject))): # recursion method
mazeObject.maze_list[row][col] = ' ' # to delete wrong path
return True
return False
So now my question is, where is the error? I mean the program just prints out the maze without the solution. I want to fill the correct path with "*".

Looking at your code I see several errors. You do not handle the entry and exit row/column pairs correctly. (10,20) is correct for this maze, if you assume that every other row, and every other column, is a grid line. That is, if the | and - characters represent infinitely thin lines that have occasional breaks in them, much like traditional maze drawings.
You'll need to multiple/divide by two, and deal with the inevitable fencepost errors, in order to correctly translate your file parameters into array row/column values.
Next, your findpath function is confused:
First, it should be a method of the class. It accesses internal data, and contains "inner knowledge" about the class details. Make it a method!
Second, your exit condition replaces the current character with a space "to delete wrong path". But if you have found the exit, the path is by definition correct. Don't do that!
Third, you have a bunch of if statements for various character types. That is fine, but please replace them with a single if statement using
if self.maze_list[row][col] in '|-+*':
return False
Fourth, you wait to mark the current cell with a '*' until after your checks. But you should mark the cell before you declare victory when you reach the exit location. Move the exit test down, I think.
That should clean things up nicely.
Fifth, and finally, your recursive test is backwards. Your code returns True when it reached the exit location. Your code returns False when it runs into a wall, or tries to cross its own path. Therefore, if the code takes a dead end path, it will reach the end, return false, unroll the recursion a few times, returning false all along, until it gets back.
Thus, if you EVER see a True return, you know the code found the exit down that path. You want to immediately return true and do nothing else. Certainly don't erase the path - it leads to the exit!
On the other hand, if none of your possible directions return true, then you have found a dead end - the exit does not lie in this direction. You should erase your path, return False, and hope that the exit can be found at a higher level.

Related

Can't solve this for loop

So I'm a beginner and I need to write a code that prints a x-y graph.
Here is my code:
dimx = int(input('lengte van de x-as: '))
dimy = int(input('lengte van de y-as: '))
b = int(input('b: '))
print("^")
for x in range(dimy):
print("|")
if x == b+1:
for x in range(dimx):
print("-",end="")
print("+"+"-"*dimx + ">")
The problem I have is my output prints out in the wrong order:
^
|
|
|
|
|
|
------------------------------|
|
|
|
+------------------------------>
What I need is:
^
|
|
|
|
|
|
|------------------------------
|
|
|
+------------------------------>
You used print("|") which without end = "" will print a new line afterwards unconditionally
You can instead print the newline at the end using an empty print()
dimx = int(input('lengte van de x-as: '))
dimy = int(input('lengte van de y-as: '))
b = int(input('b: '))
print("^")
for x in range(dimy):
print("|",end="") # print without newline
if x == b+1:
for x in range(dimx):
print("-",end="")
print() # print newline here
print("+"+"-"*dimx + ">")
The last | is from the next line because there's no newline after ------------------. Add a | with no newline before the for loop, and add a newline at the end.

Adding a newline to the printed data from an imported file

I made the following code, which imports a file and prints its content :
import pandas as pd
file = r"..\test.xlsx"
try:
df = pd.read_excel(file)
#print(df)
except OSError:
print("Impossible to read", file)
test =
df['Date'].map(str) + ' | ' \
+ df['Time'].map(str) + ' | ' \
+ df['Description'].map(str) + ' | ' \
+ '\n'
print(test)
The output is (Edit : I precise that it is printed in an html file) :
20/01 | 17:00 | Text description here1 17/01 | 11:00 | Text
description here2 16/01 | 16:32 | Text description here3 <- In orange
when the the "Urgence" is equal to 3
But what I want is :
20/01 | 17:00 | Text description here1
17/01 | 11:00 | Text description here2
16/01 | 16:32 | Text description here3
I added a new line at the end of my statement + '\n' but it doesn't seem to change anything. How should I proceed ? Thank you.
Edit : I believe that the problem comes from the fact that the entire file is printed, and not line by line so it doesn't add the newline to each line. So I made this code :
test = []
for index, row in df.iterrows():
x = row['Date'] + ' | ' + row['Description'] + '\n'
test.append(x)
print(test)
But the result is the same..
Try this:
test = df['Date'].map(str) + ' | ' +
df['Time'].map(str) + ' | ' +
df['Description'].map(str) + ' | '
list(map(lambda x: print(x), test))
I removed the end of the test string and added the print function.
Let me know if there is any problem :)

Translating an EBNF grammar to pyparsing give error

I am making a parser to convert a simple DSL into elasticsearch query. some of the possible queries are:
response:success
response:success AND extension:php OR extension:css
response:sucess AND (extension:php OR extension:css)
time >= 2020-01-09
time >= 2020-01-09 AND response:success OR os:windows
NOT reponse:success
response:success AND NOT os:windows
I have written the following EBNF grammar for this :
<expr> ::= <or>
<or> ::= <and> (" OR " <and>)*
<and> ::= <unary> ((" AND ") <unary>)*
<unary> ::= " NOT " <unary> | <equality>
<equality> ::= (<word> ":" <word>) | <comparison>
<comparison> ::= "(" <expr> ")" | (<word> (" > " | " >= " | " < " | " <= ") <word>)+
<word> ::= ("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")+
The precdence of operators in the DSL is:
() > NOT > AND > OR
aslo exact mathing i.e ':' has higher precedence than comparison operators.
I believe the above grammar capture the idea of my DSL. I am having a difficult time translating it to pyparsing, this is what i have now:
from pyparsing import *
AND = Keyword('AND') | Keyword('and')
OR = Keyword('OR') | Keyword('or')
NOT = Keyword('NOT') | Keyword('not')
word = Word(printables, excludeChars=':')
expr = Forward()
expr << Or
Comparison = Literal('(') + expr + Literal(')') + OneOrMore(word + ( Literal('>') | Literal('>=') | Literal('<') | Literal('<=')) + word)
Equality = (word + Literal(':') + word) | Comparison
Unary = Forward()
Unary << (NOT + Unary) | Equality
And = Unary + ZeroOrMore(AND + Unary)
Or = And + ZeroOrMore(OR + And)
The error i get is :
Traceback (most recent call last):
File "qql.py", line 54, in <module>
expr << Or
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyparsing.py", line 5006, in __lshift__
self.mayIndexError = self.expr.mayIndexError
AttributeError: type object 'Or' has no attribute 'mayIndexError'
I think its becuase i am unable to understand Forward() correctly.
Questions: how can i correctly translate the above grammar to pyparsing?
**EDIT **: when i changed the pyparsing code to:
AND = Keyword('AND')
OR = Keyword('OR')
NOT = Keyword('NOT')
word = Word(printables, excludeChars=':')
expr = Forward()
Comparison = Literal('(') + expr + Literal(')') + OneOrMore(word + ( Literal('>') | Literal('>=') | Literal('<') | Literal('<=')) + word)
Equality = (word + Literal(':') + word) | Comparison
Unary = Forward()
Unary << ((NOT + Unary) | Equality)
And = Unary + ZeroOrMore(AND) + Unary
Or = And + ZeroOrMore(OR + And)
expr << Or
Q = """response : 200 \
AND extesnion: php \
OR extension: css \
"""
print(expr.parseString(Q))
I get this output:
['response', ':', '200', 'AND', 'extesnion', ':', 'php']
why OR expression is not parsed?

Replace output in Python [duplicate]

This question already has answers here:
How can I overwrite/print over the current line in Windows command line?
(11 answers)
Closed 3 years ago.
I have a small command-line hold'em hand generator:
hole_cards = deck.draw(2)
h1, h2 = hole_cards
print(f'Your Hole Cards: {h1} | {h2}\n')
flop_cards = deck.draw(3)
f1, f2, f3 = flop_cards
print(f'Flop: {f1} | {f2} | {f3}\n')
turn_card = deck.draw(1)
t = turn_card[0]
print(f'Turn: {f1} | {f2} | {f3} | {t}\n')
river_card = deck.draw(1)
r = river_card[0]
print(f'River: {f1} | {f2} | {f3} | {t} | {r}\n')
Which outputs like this:
Your Hole Cards: ♦Four♦ | ♣Five♣
Flop: ♣Two♣ | ♣Ace♣ | ♦Two♦
Turn: ♣Two♣ | ♣Ace♣ | ♦Two♦ | ♠Seven♠
River: ♣Two♣ | ♣Ace♣ | ♦Two♦ | ♠Seven♠ | ♠Ace♠
Is there any way I could, instead of printing the turn and river after the flop, replace the word flop with turn and then river? I know that I can print the new cards on the same line, but I don't know how to replace the already-printed word "flop" or "turn"
Try something like this:
import time
for i in range(5):
print('{} of 5'.format(i), end='\r')
time.sleep(1)
add end="\r" to youre print statements and youre output will replace with new content:
hole_cards = deck.draw(2)
h1, h2 = hole_cards
print(f'Your Hole Cards: {h1} | {h2}', end="\r")
flop_cards = deck.draw(3)
f1, f2, f3 = flop_cards
print(f'Flop: {f1} | {f2} | {f3}', end="\r")
turn_card = deck.draw(1)
t = turn_card[0]
print(f'Turn: {f1} | {f2} | {f3} | {t}', end="\r")
river_card = deck.draw(1)
r = river_card[0]
print(f'River: {f1} | {f2} | {f3} | {t} | {r}', end="\r")

Create a 3x3 grid

I am fairly new to Python and I want to create a printable 3x3 grid to represent a Tic-Tac-Toe board. I just want ideas to tidy it up and make the code look better many thanks
def display_board(board):
print(' | | ')
print(board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | | ')
print('---- ---- ----')
print(' | | ')
print(board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | | ')
print('---- ---- ----')
print(' | | ')
print(board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | | ')
This function does create the desired result but I want ideas of how to tidy it up. I've tried for loops but it ends up breaking.
print("""
| |
------------
| |
------------
| |
""")
will result in a board like this:
| |
------------
| |
------------
| |
Similar to Brian's answer however you can set the value for each case within the .format method.
print("""
{}|{}|{}
-----
{}|{}|{}
-----
{}|{}|{}
""".format('x','x','o','o','o','x','o','x','o'))
will result with:
x|x|o
-----
o|o|x
-----
o|x|o
Each {} will be replaced by an argument of the .format method; in order.
Check this link for more information.

Categories

Resources