class Board:
array = [[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]]
def reset(self):
self.array = [[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]]
class AI(Board):
def __init__(self):
self.array[0][0] = "X"
ai = AI()
board = Board()
print(ai.array) # [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
print(board.array) # [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
ai.reset()
print(ai.array) # [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
print(board.array) # [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
My question is why board.array is changed while ai.array was. If they are connected to each other, why both the attributes are not changed together while the method belongs to AI is run.
This can be understood in the following manner:
When you get self.array to use or modify it, as in the expression self.array[0][0] = "X", then
first the instance is checked to see if it has such an attribute;
if it does not, the type of the instance is checked for the attribute.
(this is a simplification of what happens, but its all you need to know for this case)
When you set an instance, as you do in the expression self.array = [...] you are setting the attribute directly on the instance
So in your example code:
print(ai.array) # ai does not have an array, Board.array is returned
print(board.array) # board does not have an array, Board.array is returned
ai.reset() # this adds an attribute to ai
print(ai.array) # ai **does** have an array, it is returned
print(board.array) # board does not have an array, Board.array is returned
Related
Im having a hard time understanding the output of the Difflib module of python.
This output seems fine here:
import difflib
from difflib import SequenceMatcher, Differ
diff = Differ()
test_string_1 = "Ava D Ava: I'll try... :)"
test_string_2 = "AvaDAva:I'lltry...:)"
diffs = list(diff.compare(test_string, test_string_2))
print(diffs)
[
" A",
" v",
" a",
"- ",
"- :",
" D",
"- ",
" A",
" v",
" a",
" :",
"- ",
" I",
" '",
" l",
" l",
"- ",
" t",
" r",
" y",
" .",
" .",
" .",
"- ",
" :",
" )",
]
But when add a colon before the D character the output changes drastically:
test_string_1 = "Ava :D Ava: I'll try... :)"
test_string_2 = "Ava:DAva:I'lltry...:)"
diffs = list(diff.compare(test_string, test_string_2))
['- A',
'- v',
'- a',
'- ',
'- :',
'- D',
'- ',
' A',
' v',
' a',
' :',
'- ',
'+ D',
'+ A',
'+ v',
'+ a',
'+ :',
' I',
" '",
' l',
' l',
'- ',
' t',
' r',
' y',
' .',
' .',
' .',
'- ',
' :',
' )']
The output suggests both strings start differently when they are the same. I really need help, this doesn't make sense to me.
So what we've got is some processes that log into databases and we need to have the credentials for that encrypted (at least the password). What we're looking for is the ability to call something that will encrypt and decrypt the password when called so we can use that for the credentials. Something like the below:
Start program
call external decryption program to get credentials
connect to database
do stuff
disconnect
end program
So basically I would like to encrypt the password so that it's not sitting stored as plain text. I have seen a variety of solutions using Wallet's and Python Cyrptography library. Where I am stuck is how to deploy my solution so that only the correct oracle user with permissions is able to decrypt the password file. Is there a way to validate the Oracle user using CX_Oracle?
Below find my current .py file with my connection to CX_Oracle:
import cx_Oracle
def get_ldif_string(row, isFirst):
ldif = ""
if isFirst == False:
ldif += "\r\n"
ldif += "dn: sk-ban=" + \
row[0] + ",ou=XXXXXXXX,ou=XXXXXXXXX,ou=XXXXXX,dc=XXXXXXXXX,dc=com" + "\r\n"
ldif += "objectClass: sk-account\r\n"
ldif += "objectClass: top\r\n"
ldif += "sk-ban: " + row[0] + "\r\n"
if row[1].strip():
ldif += "sk-billingFullName: " + row[1] + "\r\n"
if row[3].strip():
ldif += "sk-billingAddress: " + row[3] + "\r\n"
if row[4].strip():
ldif += "sk-billingCity: " + row[4] + "\r\n"
if row[5].strip():
ldif += "sk-billingProvince: " + row[5] + "\r\n"
if row[6].strip():
ldif += "sk-billingPostalCode: " + row[6] + "\r\n"
if row[7].strip():
ldif += "sk-billingAccountType: " + row[7] + "\r\n"
if row[8].strip():
ldif += "sk-billingServiceNumber: " + row[8] + "\r\n"
if row[9].strip():
ldif += "sk-active: " + row[9] + "\r\n"
if row[10].strip():
ldif += "sk-inactive: " + row[10] + "\r\n"
#print (ldif)
return ldif
def writeToFile(textToWrite, file):
file.write(textToWrite)
dsn_tns = cx_Oracle.makedsn(
'XXXXXXXX', 'XXXX', service_name='XXXXXXXXXXXXXXX')
conn = cx_Oracle.connect(
user=r'XXXXXXX', password=r'XXXXXXX', dsn=dsn_tns)
query = """Select * FROM (
select
COALESCE(ACCT_NO, ' ') as ACCT_NO
, COALESCE(BILLING_FIRST_NAME, '') || ' ' || COALESCE(BRM_LAST_NAME, '')
, COALESCE(BRM_LAST_NAME, ' ')
, COALESCE(BRM_ADDRESS, ' ')
, COALESCE(BRM_CITY, ' ')
, COALESCE(BRM_PROVINCE, ' ')
, COALESCE(BRM_POSTAL_CODE, ' ')
, COALESCE(BRM_ACCOUNT_TYPE, ' ')
, COALESCE(CRB_TN_SN, ' ')
, CASE WHEN BRM_DEAL_STATUS = 'ACTIVE' THEN COALESCE(BRM_DEAL_NAME, ' ') ELSE ' ' END as BRM_ACTIVE
, CASE WHEN BRM_DEAL_STATUS <> 'ACTIVE' THEN COALESCE(BRM_DEAL_NAME, ' ') ELSE ' ' END as
BRM_INACTIVE
from PIN.V_SK_IDM_DATA
ORDER BY ACCT_NO
)
--where ACCT_NO in ('7135942-00002', '7133100', '7206065-00011', '0042006-00003', '0044070-00001')
"""
fileName = "load/loadLDIF.ldif"
open(fileName, 'w').close()
file = open(fileName, "a+")
c = conn.cursor()
c.execute(query)
ban = ""
ldif = ""
isFirst = True
for row in c:
newBan = row[0]
if newBan != ban:
writeToFile(ldif, file)
ldif = get_ldif_string(row, isFirst)
isFirst = False
ban = newBan
else:
if row[9].strip():
ldif += "sk-active: " + row[9] + "\r\n"
else:
ldif += "sk-inactive: " + row[10] + "\r\n"
writeToFile(ldif, file)
conn.close()
file.close()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
So I am trying to create a dungeon type game for my assignment. But I have no clue how to create a map like that with a nested list? Any help would be appreciated.
Example of the map:
+---+---+---+---+---+---+---+---+
| T | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | T | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | T | | |
+---+---+---+---+---+---+---+---+
| | T | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | T | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | K |
+---+---+---+---+---+---+---+---+
The list:
world_map = [['T', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', 'T', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', 'T', ' ', ' '],\
[' ', 'T', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', 'T', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K']]
Here what I have:
current_row = 0
current_column = 0
def View_Map():
for i in world_map:
world_map[current_row][current_column] = "H/T"
print(i)
The output I get:
You can use string formatting to print this, you would need to print
for each line in your data a header ('+---+- etc -+---+'))
for each cell in your data a value V ('+ V +')
a end line after all of them ('+---+- etc -+---+'))
Header and cells would need to adapt to the maximal widht of all cell contents to get an even looking map.
You can do it like this:
m = [['T', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', 'T', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', 'T', ' ', ' '],
[' ', 'T', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', 'T', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K']]
def print_map(data):
"""Prints a list of lists, puts data centered
into each boxand pads other boxes accordingly. """
# max widht of all elelemts to be printed
max_w = max(len(o) for l in data for o in l)
# fitting header
header = f"+-{'-' * max_w}-" * len(data[0]) + "+"
for line in data:
print(header)
print("+", end="")
for char in line:
# center format each "box"
print(f" {char:^{max_w}} +", end="")
print()
print(header)
print_map(m)
Output:
+---+---+---+---+---+---+---+---+
+ T + + + + + + + +
+---+---+---+---+---+---+---+---+
+ + + + T + + + + +
+---+---+---+---+---+---+---+---+
+ + + + + + T + + +
+---+---+---+---+---+---+---+---+
+ + T + + + + + + +
+---+---+---+---+---+---+---+---+
+ + + + + + + + +
+---+---+---+---+---+---+---+---+
+ + + + + T + + + +
+---+---+---+---+---+---+---+---+
+ + + + + + + + K +
+---+---+---+---+---+---+---+---+
If you have a "non-1-character-content" the code will space out the other cells as needed:
+-------+-------+-------+-------+-------+-------+-------+-------+
+ T + + + + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + TTTTT + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + + T + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + T + + + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + T + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + + + + K +
+-------+-------+-------+-------+-------+-------+-------+-------+
Lookup string format mini language for centering text
theBoard = {'top left': ' ', 'top middle': ' ', 'top right': ' ',
'center left': ' ', 'center middle': ' ', 'center right': ' ',
'bottom left': ' ', 'bottom middle': ' ', 'bottom right': ' '}
def printBoard(board):
print(board['top left'] + '|' + board['top middle'] + '|' + board['top right'])
print('-+-+-')
print(board['center left'] + '|' + board['center middle'] + '|' + board['center left'])
print('-+-+-')
print(board['bottom left'] + '|' + board['bottom middle'] + '|' + board['bottom right'])
turn = 'X'
for i in range (9):
printBoard(theBoard)
print('Turn for ' + turn + '.Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
I think you've just got your indentation wrong:
theBoard = {'top left': ' ', 'top middle': ' ', 'top right': ' ',
'center left': ' ', 'center middle': ' ', 'center right': ' ',
'bottom left': ' ', 'bottom middle': ' ', 'bottom right': ' '}
def printBoard(board):
print(board['top left'] + '|' + board['top middle'] + '|' + board['top right'])
print('-+-+-')
print(board['center left'] + '|' + board['center middle'] + '|' + board['center left'])
print('-+-+-')
print(board['bottom left'] + '|' + board['bottom middle'] + '|' + board['bottom right'])
turn = 'X'
for i in range (9):
printBoard(theBoard)
print('Turn for ' + turn + '.Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
I am a beginner at python and I am attempting to create a simple game. I am struggling to create a function that is required to take in zero arguments and returns a grid which contains randomly placed explosives.
As a general requirement, there should be a ten percent chance of getting a mine.
This is my code so far, but I'm struggling to figure out where to go from here. I also don't really understand the ten percent chance of placing a mine requirement because I thought there would have to be 10 different boxes? If someone could help push me in the right direction, I'd really appreciate it.
def mines():
gridSize = 3
createGrid = [[' ' for i in range(gridSize)] for i in range(gridSize)]
return createGrid
print(initMines())
All of these answers were really helpful, thanks! :)
Using the random library, you can use randint to get your 1 in 10 chance, and implement via an if statement
import random
GRIDSIZE = 3
CHANCE = 10
def mines():
createGrid = [[("x" if random.randint(0, CHANCE) == 0 else " ") for i in range(GRIDSIZE)] for i in range(GRIDSIZE)]
return createGrid
print(mines())
Output example
[['x', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
Edit: I have added global constants for the grid size and chance based on your question, however I would pass these as parameters if I were you.
I'm not most familiar with Python, so sorry if things don't quite work, but from the looks of things you're looking at making a 2d array, and then filling them with either an empty string "" or a mine "x", based on probability.
Based on the first answer here, you're mostly on the right track with initialising the array, though you may have to make the two "i"s different (given they represent "coordinates" in an array I'd suggest x and y)
createGrid = [[' ' for x in range(gridSize)] for y in range(gridSize)]
You then need to populate the array, and the way I'd suggest you do this would be using nested for loops as shown below:
for i in range(gridSize)
for j in range(gridSize)
createGrid[i][j] = //code for mine/empty
This will loop through all values in the array, and then update them based on whether or not it should contain a mine or be empty.
To decide whether or not it should be a mine, your best bet would probably be to import the random module, and use either the randint function or the random function, and then use an if statement to determine whether or not it should be a mine.
(The if statement goes within the for loops, the import happens before anything else in your code)
e.g.
import random
if random.randint(0, 10) <= 1
createGrid[i][j] = "x"
Hope that makes sense and is helpful!
For a 1/10 chance of a mine, you can just use something like (remembering to import random):
opts = "M........."
[[random.choice(opts) for c in range(gridSize)] for r in range(gridSize)]
It just chooses one of the characters from the string, which happens to have a 10% chance of getting a mine.
Using that in a complete program, and making it more configurable:
import random
def mines(gsz, pct):
# Silently enforce int 0-100, create choices, then choose.
pct = max(0, min(100, int(pct)))
opts = "M" * pct + ' ' * (100 - pct)
return [[random.choice(opts) for i in range(gsz)] for i in range(gsz)]
# Test harness. First, create a grid.
sz = 10
grid = mines(sz, 20)
# Then dump it for confirmation.
for line in grid: print(line)
mineCount = sum([cell == 'M' for row in grid for cell in row])
print('\nActual percentage was', 100 * mineCount / sz / sz)
shows it in action:
[' ', ' ', 'M', ' ', ' ', ' ', 'M', ' ', ' ', ' ']
['M', ' ', ' ', ' ', 'M', ' ', ' ', ' ', ' ', ' ']
['M', ' ', ' ', ' ', 'M', 'M', ' ', ' ', ' ', ' ']
[' ', 'M', 'M', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
['M', ' ', ' ', ' ', ' ', 'M', ' ', ' ', ' ', ' ']
['M', ' ', ' ', ' ', ' ', ' ', 'M', 'M', ' ', ' ']
[' ', ' ', 'M', ' ', 'M', ' ', 'M', ' ', ' ', 'M']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', 'M', ' ', ' ', ' ']
Actual percentage was 19.0
In case you want guaranteed number of mines you could do this:
import random
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
size = int(input('Enter length of row: '))
# By default 1/size of cells will be mines.
mines = (size**2)//size
# There is probably a better way to get user input, but this will do.
try:
mines = int(input('Enter number of mines [default=%s]: ' % mines))
except:
mines = (size**2)//size
# Make an one dimensional list of size square.
field_1d = [' ']*(size**2)
# Stick the mines into the list.
for m in range(mines):
field_1d[m] = '*'
# Randomly place the mines.
random.shuffle(field_1d)
# Make a 2D list out of the 1D list.
field = [r for r in chunks(field_1d,size)]
# Display it.
for row in field:
print(row)
Here is the output:
$ ./minesweeper.py
Enter length of row: 3
Enter number of mines [default=3]: 1
[' ', ' ', ' ']
[' ', '*', ' ']
[' ', ' ', ' ']
$ ./minesweeper.py
Enter length of row: 10
Enter number of mines [default=10]:
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', '*', ' ', ' ', '*', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', '*', ' ', ' ']
[' ', '*', '*', ' ', ' ', ' ', ' ', ' ', ' ', '*']
[' ', ' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
Sorry I could resist. I went ahead and wrote a complete minesweeper game:
import random
class Cell():
def __init__(self,i,j,field):
self.i = i
self.j = j
self.exposed = False
self.field = field
self.value = self.calc_value()
def display(self):
if self.exposed:
return self.value
return '_'
def expose(self):
self.exposed = True
def calc_value(self):
i = self.i
j = self.j
f = self.field
if self.field[i][j] == '*':
return '*'
v=0
try:
if f[i-1][j-1] == '*':
v += 1
except:
pass
try:
if f[i-1][j] == '*':
v += 1
except:
pass
try:
if f[i-1][j+1] == '*':
v += 1
except:
pass
try:
if f[i][j-1] == '*':
v += 1
except:
pass
try:
if f[i][j+1] == '*':
v += 1
except:
pass
try:
if f[i+1][j-1] == '*':
v += 1
except:
pass
try:
if f[i+1][j] == '*':
v += 1
except:
pass
try:
if f[i+1][j+1] == '*':
v += 1
except:
pass
return str(v)
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
size = int(input('Enter size of field: '))
# 1/10th of cells will be mines.
mines = (size**2)//size
try:
mines = int(input('Enter number of mines [default=%s]: ' % mines))
except:
mines = (size**2)//size
# Make an one dimensional list of size square.
field_1d = [' ']*(size**2)
# Stick the mines into the list.
for m in range(mines):
field_1d[m] = '*'
# Randomly place the mines.
random.shuffle(field_1d)
# Make a 2D list out of the 1D list.
field = [r for r in chunks(field_1d,size)]
# Display it.
for row in field:
print(row)
board_1d = []
for i in range(size):
for j in range(size):
print(i,j)
board_1d.append(Cell(i,j,field))
board = [r for r in chunks(board_1d,size)]
def display(board):
for i in range(size):
for j in range(size):
print(board[i][j].display(), end='|')
print("")
def win(board):
unexposed = 0
for i in range(size):
for j in range(size):
if board[i][j].exposed == False:
unexposed += 1
if unexposed == mines:
print('WINNER!!!!')
return True
return False
gameover = False
while not gameover:
display(board)
I = int(input('Enter I: '))
J = int(input('Enter J: '))
c = board[I][J]
c.expose()
if c.value == '*':
print("BOOM!")
gameover = True
gameover = win(board)
display(board)