I have a Connect Four program which runs appropriately but i would like to print my match_in_direction() method onto the screen...My code is as follows
class ConnectFour(object):
This initializes the board:
def __init__(self):
self.board = [[None for i in range(7)] for j in range(8)]
This gets a position of each play spot:
def get_position(self, row, column):
assert row >= 0 and row < 6 and column >= 0 and column < 7
return self.board[row][column]
This is supposed to check if the chips played are matching:
def match_in_direction(self, row, column, step_row, step_col):
assert row >= 0 and row < 6 and column >= 0 and column < 7
assert step_row != 0 or step_col != 0 # (0,0) gives an infinite loop
match = 1
while True:
nrow = row + step_row
ncolumn = column + step_col
if nrow >=0 and nrow <6 and ncolumn >=0 and ncolumn <7:
if self.board[row][column] == self.board[nrow][ncolumn]:
match == match+1
row = nrow
column = ncolumn
else:
return match
else:
return match
print match
This will be a play based on user input
def play_turn(self, player, column):
""" Updates the board so that player plays in the given column.
player: either 1 or 2
column: an integer between 0 and 6
"""
assert player == 1 or player == 2
assert column >= 0 and column < 7
for row in xrange(6):
if self.board[row][column] == None:
self.board[row][column] = player
return
Prints the Board:
def print_board(self):
print "-" * 29
print "| 0 | 1 | 2 | 3 | 4 | 5 | 6 |"
print "-" * 29
for row in range(5,-1,-1):
s = "|"
for col in range(7):
p = self.get_position(row, col)
if p == None:
s += " |"
elif p == 1:
s += " x |"
elif p == 2:
s += " o |"
else:
# This is impossible if the code is correct, should never occur.
s += " ! |"
print s
print "-" * 29
And my usage:
b = ConnectFour()
b.play_turn(1, 3)
b.play_turn(1, 3)
b.play_turn(1, 4)
b.match_in_direction(0,3,0,2)
b.print_board()
My current Output gives me the positions just fine...However it doesn't print the match_in_direction(0,3,0,2) which should be 2 because that is how many chips are matching....Any Help will be greatly appreciated.
From a quick glance in match_in_direction it looks like you have match == match+1 instead of match = match + 1 (or "better" yet match += 1)
add this to your test code:
f = b.match_in_direction(0,3,0,2)
print(m)
you don't need "print match" in the match_in_direction function because of the return statements, and print board doesn't utilize (for lack of a better word) the match in direction function so you have to print it out separately.
The formatting of your match_in_direction function is a little confusing, but I think it is because of the typo here:
if self.board[row][column] == self.board[nrow][ncolumn]:
match == match+1
It should be
match += 1
Related
I have an assignment for my Python course that I'm struggling with.
We are supposed to make a function that prints out binary as follows:
If the input is:
chessboard(3)
It should print out:
101
010
101
And so forth..
Its a "simple" program but I'm really new to coding.
I can produce a while loop that writes out the correct length and amount of lines but I'm struggling to produce variation between the lines.
This is what I have come up with so far:
def chessboard(n):
height = n
length = n
while height > 0:
while length > 0:
print("1", end="")
length -= 1
if length > 0:
print("0", end="")
length -= 1
height -= 1
if length == 0:
break
else:
print()
length = n
With the input:
chessboard(3)
It prints out:
101
101
101
Could someone help me figure out how I could start every other line with zero instead of one?
As I understand it, it is simple :
print("stackoverflow")
def chessboard(n):
finalSentence1 = ""
finalSentence2 = ""
for i in range(n): #we add 0 and 1 as much as we have n
if i%2 == 0: #
finalSentence1 += "1"
finalSentence2 += "0"
else:
finalSentence1 += "0"
finalSentence2 += "1"
for i in range(n): #we print as much as we have n
if i%2 == 0:
print(finalSentence1)
else:
print(finalSentence2)
chessboard(3)
returns :
stackoverflow
101
010
101
I am working on the same kind of assignment, but as we have only covered conditional statements and while loops so far, following the same logic, here is my solution:
def chessboard(size):
output_1 = ''
output_2 = ''
i = 1
j = 1
while j <= size:
while i <= size:
if i % 2 == 0:
output_1 += '1'
output_2 += '0'
i += 1
else:
output_1 += '0'
output_2 += '1'
i += 1
if j % 2 == 0:
print(output_1)
j += 1
else:
print(output_2)
j += 1
chessboard(5)
returns:
10101
01010
10101
01010
10101
def chessboard(x):
i = 0
while i < x:
if i % 2 == 0:
row = "10"*x
else:
row = "01"*x
print(row[0:x])
i += 1
i try to make square number but i stuck to print * in middle of square, the program should not using list cause this simple basic. i use looping with if else. i have try my best, maybe someone want's help me to fixed it.
sample
input:
5
a
8
output:
88888
8aaa8
8a*a8
8aaa8
8aaa8
my code:
a = int(input("Enter number: "))
b = input("Enter string: ")
c = int(input("Enter number: "))
row = 1
while(row <= a):
column = 1
while(column <= a ):
if(row == 1 or row == a or column == 1 or column == a):
print(c, end = ' ')
elif(row == a / 2 or column == a / 2)://this for * in middle
print("*" - 2, end=" ")
else:
print(b, end = ' ')
column = column + 1
row = row + 1
print()
My code that I have commented in line does not print right results, which should print *.
elif(row == a / 2 or column == a / 2) change your code to elif(row == a // 2+1 and column == a // 2+1) and remove -2 from print('*' - 2)
while(row <= a):
column = 1
while(column <= a ):
if(row == 1 or row == a or column == 1 or column == a):
print(c, end = ' ')
elif(row == a // 2+1 and column == a // 2+1):
print("*", end=" ")
else:
print(b, end = ' ')
column = column + 1
row += 1
print()
You should use Integer Division feature of Python.
You wrote a/2 which gives floating value 2.5.
But, a//2 gives integer 2
Try this for line: 11, 12:
elif((row == 1 + (a // 2)) and (column == 1 + (a // 2))): # this for * in middle
print("*", end=" ")
NOTE: I CAN NOT use any external module that is not built-in to python.
Problem:
A new and upcoming artist has a unique way to create checkered patterns. The idea is to
use an M-by-N canvas which is initially entirely black. Then the artist repeatedly chooses
a row or column and runs their magic brush along the row or column. The brush changes
the colour of each cell in the row or column from black to gold or gold to black.
Given the artist’s choices, your job is to determine how much gold appears in the pattern
determined by these choices.
Input Specification
The first line of input will be a positive integer M. The second line of input will be a positive
integer N. The third line of input will be a positive integer K. The remaining input will be
K lines giving the choices made by the artist. Each of these lines will either be R followed
by a single space and then an integer which is a row number, or C followed by a single space
and then an integer which is a column number. Rows are numbered top down from 1 to M.
Columns are numbered left to right from 1 to N.
Output Specification
Output one non-negative integer which is equal to the number of cells that are gold in the
pattern determined by the artist’s choices.
Limitations
M and N can be up to 5 000 000
K can be up to 1 000 000
My Solution
import sys
raw_input = sys.stdin.readline
m = int(raw_input())
n = int(raw_input())
brushes = raw_input()
stroke = []
colors = [['B' for _ in range(n)] for _ in range(m)]
for i in range(int(brushes)):
g = raw_input().split(' ')
if stroke.count(g) == 1:
stroke.remove(g)
else:
stroke.append(g)
def changeColumn(num,colors,index):
if num == 0:
return colors
colors[num-1][index] = 'G' if colors[num-1][index] == 'B' else 'B'
num -= 1
changeColumn(num,colors,index)
def countGold(c,options,i):
if options == []:
s = 0
for l in c:
s += l.count("G")
print(s)
return
area = options[i][0]
times = int(options[i][1]) - 1
if area == "R":
c[times] = list(''.join(c[times]).replace("G","A").replace("B","G").replace("A","B"))
elif area == "C":
changeColumn(m,c,times)
options.remove(options[i])
countGold(c,options,i)
countGold(colors,stroke,0)
Got everything right except for some problems. I exceeded the Time Limit of 4 seconds. I know that making colors takes up a lot of time. Is there any way to do this without generating the 2d array?
UPDATED CODE (doesn't work)
import sys
M = int(input())
N = int(input())
K = int(input())
dup = []
numR = 0
numC = 0
for i in range(K):
choice = input().split()
if choice not in dup:
if choice[0] == "R":
numR += 1
elif choice[0] == "C":
numC += 1
dup.append(choice)
print((M * numR) + (N * numC) - (2*numR*numC))
Let me put all that discussion in comments into the code:
import sys
M = int(input())
N = int(input())
K = int(input())
dup = set()
result = {'numR': 0, 'numC': 0}
def update(char, num):
if char == 'R':
result['numR'] += num
elif char == 'C':
result['numC'] += num
for i in range(K):
choice = input().split()
if choice in dup:
dup.remove(choice)
update(choice[0], -1)
else:
dup.add(choice)
update(choice[0], 1)
numR = result['numR']
numC = result['numC']
print((M * numR) + (N * numC) - (2*numR*numC))
The code sent by Freakish still doesn't work for some reason. Here is an updated code that works:
import sys
rw = sys.stdin.readline
M = int(rw())
N = int(rw())
choices = set()
K = int(rw())
for i in range(K):
g = input()
if g in choices:
choices.remove(g)
else:
choices.add(g)
numR = 0
numC = 0
s = 0
for choice in choices:
if choice[0] == "R":
numR += 1
elif choice[0] == "C":
numC += 1
for choice in choices:
if choice[0] == "R":
# numR += 1
s += N - numC
elif choice[0] == "C":
# numC += 1
s += M - numR
print(s)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I wrote a program (1) that prints my name in patterns (each letter in the name is made of its letters that makes a pattern). I am trying to modify it to be inside a function instead (2). I have read some stuff on docs.python.org, but I cannot find enough information to do it correctly. At this point, Python does not print anything at all, not even an error. Just a blank page.
Here is my original code that works well and prints RISH (see pix I attached - enter image description here):
1
String = '';
for row in range(0,8):
for column in range(0,30):
if (column == 0 or row == 0 or column == 29):
String =String + '*'
elif (column == 2 or ((row == 1 or row == 4) and column > 2 and column < 6) or (column == 6 and row != 1 and row < 4) or (column == row - 1 and row > 3)):
String = String + 'R'
elif (column == 11 or (row == 1 and column > 8 and column <14) or ( row == 7 and column > 8 and column <14 )):
String =String+'I'
elif (((row == 1 or row == 4 or row == 7) and column > 16 and column < 20) or (column == 16 and (row == 2 or row == 3 or row == 7)) or (column == 20 and (row == 1 or row == 5 or row == 6))):
String = String + 'S'
elif (column == 23 or column == 27 or row ==4 and (column>23 and column <27)):
String = String + 'H'
else:
String = String + ' '
String = String + '\n'
print(String)
What I am trying to do is to place my "if-elif-else statement" into a function and returns pattern. Could anyone help me understand if I need to define something before the statement in order for it to return the pattern or there is something else has to be written after each statement? Because the else statement (String = String + '\n') is very important to print the pattern and I have no clue how to modify it.
Grazie! Thanks a bunch!
2
def printName(string = ''):
for row in range(0,8):
for column in range(0,30):
if (column == 0 or row == 0 or column == 29):
return '*'
elif (column == 2 or ((row == 1 or row == 4) and column > 2 and column < 6) or (column == 6 and row != 1 and row < 4) or (column == row - 1 and row > 3)):
return 'R'
elif (column == 11 or (row == 1 and column > 8 and column <14) or ( row == 7 and column > 8 and column <14 )):
return 'I'
elif (((row == 1 or row == 4 or row == 7) and column > 16 and column < 20) or (column == 16 and (row == 2 or row == 3 or row == 7)) or (column == 20 and (row == 1 or row == 5 or row == 6))):
return 'S'
elif (column == 23 or column == 27 or row ==4 and (column>23 and column <27)):
return 'H'
else:
return ' '
String = String + '\n'
printName()
I think what you were missing about functions is that when a function reaches a return statement it immediately stops the function and exits. So really you just need to take your original code and indent it under a def statement.
Also, since your function is only meant to write one name it is unnecessary to provide the string argument in the function call. You can create the string within the function's scope. Since the function isn't generating anything that you want to keep in memory a return statement isn't required.
def printName():
String = ''
for row in range(0,8):
for column in range(0,30):
if (column == 0 or row == 0 or column == 29):
String =String + '*'
elif (column == 2 or ((row == 1 or row == 4) and column > 2 and column < 6) or (column == 6 and row != 1 and row < 4) or (column == row - 1 and row > 3)):
String = String + 'R'
elif (column == 11 or (row == 1 and column > 8 and column <14) or ( row == 7 and column > 8 and column <14 )):
String =String+'I'
elif (((row == 1 or row == 4 or row == 7) and column > 16 and column < 20) or (column == 16 and (row == 2 or row == 3 or row == 7)) or (column == 20 and (row == 1 or row == 5 or row == 6))):
String = String + 'S'
elif (column == 23 or column == 27 or row ==4 and (column>23 and column <27)):
String = String + 'H'
else:
String = String + ' '
String = String + '\n'
print(String)
printName()
The above code should provide what you are after.
If you wanted to return the resulting string from your function you could do the following:
def printName():
String = ''
for row in range(0,8):
for column in range(0,30):
if (column == 0 or row == 0 or column == 29):
String =String + '*'
elif (column == 2 or ((row == 1 or row == 4) and column > 2 and column < 6) or (column == 6 and row != 1 and row < 4) or (column == row - 1 and row > 3)):
String = String + 'R'
elif (column == 11 or (row == 1 and column > 8 and column <14) or ( row == 7 and column > 8 and column <14 )):
String =String+'I'
elif (((row == 1 or row == 4 or row == 7) and column > 16 and column < 20) or (column == 16 and (row == 2 or row == 3 or row == 7)) or (column == 20 and (row == 1 or row == 5 or row == 6))):
String = String + 'S'
elif (column == 23 or column == 27 or row ==4 and (column>23 and column <27)):
String = String + 'H'
else:
String = String + ' '
String = String + '\n'
return String
name = printName()
#now the string is in the variable name, outside of the function's scope.
print(name)
So I'm trying to implement a ConnectFour game in python, and I'm having some trouble with counting the pieces (from a single player) that are lined up together in a row. My code:
class ConnectFour(object):
def __init__(self):
self.row=6
self.col=7
self.board = []
#initialize the board
for arow in range(self.row):
row = []
for acol in range(self.col):
row.append(None)
self.board.append(row)
#function for counting the number of the same pieces in a row
def count_it(self, row, column, step_row, step_col):
assert row >= 0 and row < 6 and column >= 0 and column < 7
assert step_row != 0 or step_col != 0
counter1 = 0
counter2 = 0
if self.board[row][column] == None:
return 0
elif self.board[row][column] == 1:
for i in range(6):
while self.board[row + (i*step_row)][column + (i*step_col)] == 1:
counter1 += 1
return counter1
else:
for i in range(6):
while self.board[row + (i * step_row)][column + (i*step_col)] == 2:
counter2 += 1
return counter2
When I input a location and "step" in my function, I would like to get the number of pieces player 1 or player 2 has lined up but when I enter:
x= ConnectFour()
x.board[5][6] = 1
x.board[4][6] = 1
x.count_it(5,6,-1,0)
I get no output.
There is no need for that while inside for: whenever the while condition is true, it will become an infinite loop since the body of that loop does not affect the condition, it just keeps incrementing a counter forever.
One approach would be a single while loop:
while self.board[row + (counter1*step_row)][column + (counter1*step_col)] == 1:
counter1 += 1
Another approach is to leave the for loop, but i and counter1 actually serve the same purpose:
for i in range(6):
if self.board[row + (i*step_row)][column + (i*step_col)] != 1:
break
counter1 += 1
In both cases, take care of array boundaries, either by some ifs, or by placing sentinels at the border of the array.