Related
The field is created like this:
field = []
for row in range(10):
field.append([])
for col in range(15):
field[-1].append(" ")
Tuples represent free squares where mines can be layed
free = []
for x in range(15):
for y in range(10):
free.append((x, y))
I have to lay the mines trough this function:
def lay_mines(field, free, number_of_mines):
for _ in number_of_mines:
mines = random.sample(free, number_of_mines)
field(mines) = ["x"]
I was thinking using random.sample() or random.choice(). I just can't get it to work. How can I place the string "x" to a certain random coordinate?
import random
def lay_mines(x, y, number_of_mines=0):
f = [list(' ' * x) for _ in range(y)]
for m in random.sample(range(x * y), k=number_of_mines): # random sampling without replacement
f[m % y][m // y] = 'X'
return f
field = lay_mines(15, 10, 20)
print(*field, sep='\n')
Prints:
['X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', 'X', ' ', ' ', ' ', ' ', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ']
[' ', 'X', ' ', ' ', 'X', ' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', 'X', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X', ' ', 'X', ' ', ' ', ' ', ' ']
I am currently in a coding class and I am trying to learn Python (Python 3) and I have written some code here for an assignment but I am apparently getting the swapping wrong and I don't know how to fix it. I have the assignment's instructions and I also have a comment on my code that I need help understanding. Can someone please show me how to flip the rows by swapping the different values?
Here are the instructions:
Here is my code:
def flipIt(array):
for i in range(len(array)):
length = len(array[i])
for j in range(length // 2):
temp = array[i][j]
array[i][j] = array[i][length - 1 - j]
array[i][length - 1 - j] = temp
pic = [['#', ' ', ' ', ' ', ' ', '#'],
['#', '#', ' ', ' ', ' ', '#'],
['#', ' ', '#', ' ', ' ', '#'],
['#', ' ', ' ', '#', ' ', '#'],
['#', ' ', ' ', ' ', '#', '#'],
['#', ' ', ' ', ' ', ' ', '#']]
flipIt(pic)
for i in pic:
for j in i:
print(j,end=' ')
print()
Here is the comment:
How do I do what the comment says?
Mmh, it took me some time to realize the problem because flipping this picture vertically and horizontally gives the same result. In your case, what you want to do is:
def flipIt(array):
height = len(array)
for i in range(len(array) // 2):
temp = array[i]
array[i] = array[height-1-i]
array[height-1-i] = temp
# No need for return because it is modified in place
pic = [['#', ' ', ' ', ' ', ' ', '#'],
['#', '#', ' ', ' ', ' ', '#'],
['#', ' ', '#', ' ', ' ', '#'],
['#', ' ', ' ', '#', ' ', '#'],
['#', ' ', ' ', ' ', '#', '#'],
['#', ' ', ' ', ' ', ' ', '#']]
flipIt(pic)
for i in pic:
for j in i:
print(j,end=' ')
print()
Of course, as Sam Stafford suggested, you can make it even simpler (given that you are allowed) with
def flipIt(array):
array.reverse()
The flipIt function is unneeded since Python has a built-in way to do this. All you need to do is replace:
flipIt(pic)
with:
pic.reverse()
(You could also do something like flipIt = lambda img: img.reverse() if you wanted an extra layer of abstraction in there, or because the assignment required you to have a function that was specifically called flipIt.)
The list.reverse() method operates on any list and does an in-place reversal of its elements. Since pic is a list of rows in the image, reversing the order has the effect of flipping it vertically.
You can also simplify your print loop by using str.join() to turn each row into a single string.
>>> pic = [['#', ' ', ' ', ' ', ' ', '#'],
... ['#', '#', ' ', ' ', ' ', '#'],
... ['#', ' ', '#', ' ', ' ', '#'],
... ['#', ' ', ' ', '#', ' ', '#'],
... ['#', ' ', ' ', ' ', '#', '#'],
... ['#', ' ', ' ', ' ', ' ', '#']]
>>> pic.reverse() # flip the rows from top to bottom
>>> for row in pic:
... print(' '.join(row))
...
# #
# # #
# # #
# # #
# # #
# #
Your current code actually works just fine. You just forgot to return your flipped array from your function:
def flipit(array):
for i in range(len(array)):
length = len(array[i])
for j in range(length // 2):
temp = array[i][j]
array[i][j] = array[i][length - 1 - j]
array[i][length -1 -j] = temp
return array
pic = [['#', ' ', ' ', ' ', ' ', '#'],
['#', '#', ' ', ' ', ' ', '#'],
['#', ' ', '#', ' ', ' ', '#'],
['#', ' ', ' ', '#', ' ', '#'],
['#', ' ', ' ', ' ', '#', '#'],
['#', ' ', ' ', ' ', ' ', '#']
]
x = flipit(pic)
print(x)
I am in the middle of my course work and I am now having trouble with one of my for loops.
def update():
update=[]
update1=[]
with open('Stock2.txt','r') as stockFile:
for eachLine in stockFile:
eachLine=eachLine.strip().split()
update.append(eachLine)
update.remove(update[0])
stockFile.close()
with open('Stock2.txt','r') as stockFile:
for eachLine in stockFile:
eachLine=eachLine.strip().split(' ')
update1.append(eachLine)
update1.remove(update1[0])
for eachList in update1:
loopCon=-1
for eachItem in eachList:
loopCon+=1
if eachItem=='':
eachList[loopCon]=' '
count=-1
for eachList in update1:
for eachItem in eachList:
count+=1
if eachItem != ' ':
print(count)
The last for loop that I have been working on is looping ok but when I add one to count every time it loops on the for loop 'for eachItem in eachList:' it comes up with random numbers as follows:
0 10 14 21 28 35 36 46 62 69 76 83 84 94 111
Here is the stock file I am using - Stock2.txt
GTIN-8 Product-Name Price(£) CSL ROL TSL
95820194 Windows-10-64bit 119.99 0 1 3
68196167 Cheese 1.00 0 3 8
62017014 Bread 0.93 0 3 9
86179616 10tb-memory-stick 916.96 0 0 4
19610577 Freddo 0.15 0 2 9
So on.
Is there anything I have done wrong whilst doing this as I probably would not be able to detect it that easily as I have only been doing python for almost 1 year.
Thank you for your time.
You increment count outside the if that prints. Try this instead:
for eachList in update1:
for eachItem in eachList:
if eachItem != ' ':
count+=1
print(count)
If I put a print update1 statement before your last for loop, i.e., before the statement for eachList in update1:, I get the following output:
[['95820194', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'Windows-10-64bit', ' ', ' ', ' ', '119.99', ' ', ' ', ' ', ' ', ' ', ' ', '0', ' ', ' ', ' ', ' ', ' ', ' ', '1', ' ', ' ', ' ', ' ', ' ', ' ', '3'], ['68196167', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'Cheese', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1.00', ' ', ' ', ' ', ' ', ' ', ' ', '0', ' ', ' ', ' ', ' ', ' ', ' ', '3', ' ', ' ', ' ', ' ', ' ', ' ', '8'], ['62017014', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'Bread', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0.93', ' ', ' ', ' ', ' ', ' ', ' ', '0', ' ', ' ', ' ', ' ', ' ', ' ', '3', ' ', ' ', ' ', ' ', ' ', ' ', '9'], ['86179616', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '10tb-memory-stick', ' ', ' ', '916.96', ' ', ' ', ' ', ' ', ' ', ' ', '0', ' ', ' ', ' ', ' ', ' ', ' ', '0', ' ', ' ', ' ', ' ', ' ', ' ', '4'], ['19610577', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'Freddo', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0.15', ' ', ' ', ' ', ' ', ' ', ' ', '0', ' ', ' ', ' ', ' ', ' ', ' ', '2', ' ', ' ', ' ', ' ', ' ', ' ', '9']]
So by this it seems the output isnt random at all. What you are doing is traversing each list inside the list update1, and you are incrementing count each time you get an element in eachItem.
However you are printing count only when eachItem != ' '. So as you can see it prints 0 when eachItem == '95820194', and then it prints 10 when eachItem == 'Windows-10-64bit', and so on. Though it is incremented even when eachItem == ' ', just not printed.
I have a problem with dictionaries that I need help with.
Here is an excerpt from weather.txt:
Hail : 1 : xxx
Hail : 2 : xxx
Hail : 3 : xxx
Rain : 1 : xxx
Rain : 2 : xxx
Rain : 3 : xxx
The first value is the weather, the second value is the intensity and the third is just a short description.
Here is an excerpt from my game:
weather = open("weather.txt")
weather_list = {}
for line in weather:
line = line.rstrip().split(":")
weather_list[line[0][int(line[1]) -1]] = (line[0], line[1], line[2])
for key, value in weather_list.items():
print key, ":", value
That prints this:
a : ('Rain ', ' 2 ', ' xxx')
i : ('Rain ', ' 3 ', ' xxx')
H : ('Hail ', ' 1 ', ' xxx')
R : ('Rain ', ' 1 ', ' xxx')
But I want it to print this:
'Rain': [('Rain ', ' 1 ', ' xxx'), ('Rain ', ' 2 ', ' xxx'), i : ('Rain ', ' 3 ', ' xxx')]
'Hail': etc...
I know my issue is with the syntax "weather_list[line[0][int(line[1]) -1]]". What I want it to do is have 1 key for each weather, and each value to be a tuple or list containing all the values for that weather, sorted by intensity, (intensity 1, intensity 2, intensity 3).
Any and all help is appreciated. Hope I explained it better this time.
Solution
This works:
weather = {}
with open('weather.txt') as fobj:
for line in fobj:
data = line.strip().split(':')
weather.setdefault(data[0], []).append(tuple(data))
weather = {key: sorted(value, key=lambda x: x[1]) for key, value in weather.items()}
The result looks like this:
>>> weather
{'Hail ': [('Hail ', ' 1 ', ' xxx'),
('Hail ', ' 2 ', ' xxx'),
('Hail ', ' 3 ', ' xxx')],
'Rain ': [('Rain ', ' 1 ', ' xxx'),
('Rain ', ' 2 ', ' xxx'),
('Rain ', ' 3 ', ' xxx')]}
Variation
The above solution has, as requested, redundant information for Rain and Hail. This version does not store them as first element in tuple but only as key in the dictionary:
weather = {}
with open('weather.txt') as fobj:
for line in fobj:
data = line.strip().split(':')
weather.setdefault(data[0], []).append(tuple(data[1:]))
weather = {key: sorted(value) for key, value in weather.items()}
The sorting is simpler and the result looks like this:
>>> weather
{'Hail ': [(' 1 ', ' xxx'), (' 2 ', ' xxx'), (' 3 ', ' xxx')],
'Rain ': [(' 1 ', ' xxx'), (' 2 ', ' xxx'), (' 3 ', ' xxx')]}
This question already has answers here:
Iterating over dictionaries using 'for' loops
(15 answers)
Closed 7 years ago.
I'm trying to get the names in a dictionary and their corresponding key values.
Sorry if this has already been asked. This code is not working because I suck at programming and just starting. Please tell me what's wrong with it.
theBoard = {'top-L': ' ',
'top-M': ' ',
'top-R': ' ',
'mid-L': ' ',
'mid-M': ' ',
'mid-R': ' ',
'low-L': ' ',
'low-M': ' ',
'low-R': ' '
'Check for closed moves'
def openMoves:
for i in theBoard:
if theBoard[i] == ' ':
print "the move %s is open" % theBoard[i]
else:
print "the move %s is taken" % theBoard[i]
print openMoves()
theBoard = {'top-L': ' ',
'top-M': ' ',
'top-R': ' ',
'mid-L': ' ',
'mid-M': ' ',
'mid-R': ' ',
'low-L': ' ',
'low-M': ' ',
'low-R': ' '
} # <--- Close your dictionary
# <--- remove random string 'Check for c...'
def openMoves(): # <--- add parenthesis to function
for k, v in theBoard.items(): # <--- loop over the key, value pairs
if v == ' ':
print "the move %s is open" % k
else:
print "the move %s is taken" % k
openMoves() # <-- remove the print statement
theBoard = {'top-L': ' ',
'top-M': ' ',
'top-R': ' ',
'mid-L': ' ',
'mid-M': ' ',
'mid-R': ' ',
'low-L': ' ',
'low-M': ' ',
'low-R': ' '}
def openMoves():
for k,v in theBoard.items():
if v == ' ':
print "the move %s is open" %k
else:
print "the move %s is taken" %k
I think your tabbing is off too...