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.
Related
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.
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 :)
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")
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.
I am trying to print out a series of die that will display as below:
___ ___ ___ ___ ___
|* | |* | |* *| |* | | |
| | | * | |* *| | * | | * |
| *| | *| |* *| | *| | |
^^^ ^^^ ^^^ ^^^ ^^^
These die should represent the numbers that are produced when I 'roll the dice'. I have created a Die class and a Hand class, and they are produced below.
import random
class Die():
def __init__(self):
self.value = random.randint(1,6)
def roll(self):
self.value = random.randint(1,6)
'''def __str__(self):
return str(self.value)'''
import Die
class Hand:
def __init__(self):
self.L=[]
for i in range(5):
self.L.append(Die.Die()) #makes the number of dice
def __str__(self):
"""converts hand to a string for printing"""
return "{0},{1},{2},{3},{4}".format(self.L[0], self.L[1], self.L[2], self.L[3], self.L[4])
def roll(self, keep):
for i in range(5):
if i+1 not in keep:
self.L[i].roll()
The code given above will produce a list of numbers when the main file enters
h = hand.Hand()
h.roll() #this rolls the hand again
print(h)
Any ideas how I can get my results to print in the provided display style? It has been suggested that the best way to do it is to print three rows to construct all 5 dice.
The most recent advice was "You have to
build the entire display of dice row-by-row, then add the rows together
in a single, multi-line string." I'm just not sure how to execute that.
Here's one way you could do it:
DIE_PARTS = [
['___'] * 6,
[' ', '* ', '* ', '* *', '* *', '* *'],
[' * ', ' ', ' * ', ' ', ' * ', '* *'],
[' ', ' *', ' *', '* *', '* *', '* *'],
['^^^'] * 6,
]
DIE_SPACING = ' ' * 3
def print_hand(dies):
# Build line parts
lines = [[],[],[],[],[]]
for i,line in enumerate(lines):
for d in dies:
if i in [1,2,3]: edge = '|'
else: edge = ' '
part = ''
part += edge # Leading edge of die
part += DIE_PARTS[i][d-1] # "pips"
part += edge # Trailing edge of die
line.append(part)
# Join lines
lines = [DIE_SPACING.join(l) for l in lines]
# Print lines
for l in lines: print(l)
print_hand([1,2,3,4,5,6])
Output:
___ ___ ___ ___ ___ ___
| | |* | |* | |* *| |* *| |* *|
| * | | | | * | | | | * | |* *|
| | | *| | *| |* *| |* *| |* *|
^^^ ^^^ ^^^ ^^^ ^^^ ^^^
If it's not clear, you're building each line of the 5 line output, line by line, then die for die.
So it goes something like
line 1 - die 1, line 1 - die 2, line 1 - die 3, ...
line 2 - die 1, line 2 - die 2, line 2 - die 3, ...
...
line 5 - die 1, line 5 - die 2, line 5 - die 3, ...
Then it joins the parts of the lines list using DIE_SPACING as the delimiter.
I'll leave integrating this into the rest of your code up to you.