[英]Coding exercise - grabbing garbage for each player movement python
想象一個二維網格 (NxN),其中每個方格中都有垃圾,對於由 N、S、E、W(北、南、東和西)描述的每個移動,玩家相應地移動並抓取那里的垃圾在那個廣場。
如果輸入 = 'NESW' 則 output 應該 = 4 - 1 玩家開始的方格 - 1 向北,1 向東,1 向南,0 向西,因為他到達了他開始的初始方格,該方格已經“清理” "
對於輸入 = 'NSNSNSNS' output = 2 出於同樣的原因。
我無法計算垃圾並知道玩家是否已經去過那個地方。
def total_garbage(positions):
garbage = 0
N, S, E, W = 0, 0, 0, 0
for direction in positions:
if direction.upper() == 'N':
N += 1
garbage += 1
elif direction.upper() == 'S':
S += 1
garbage += 1
elif direction.upper() == 'E':
E += 1
garbage += 1
elif direction.upper() == 'W':
W += 1
garbage += 1
if N == S and E == W and E != 0 and W != 0:
return garbage
elif N == S and E == 0 and W == 0:
return (garbage - min(N,S))
qp = total_garbage(['N','E','S','W'])
print(qp)
這是我到目前為止所擁有的,只是開始嘗試一些東西,但還不是很成功:/
由於您的網格是二維的,因此 model 將其作為二維網格 - 所以選擇一個起始位置(例如(0,0))並且每個方向都會改變該位置 - 所以從(0,0)開始:
等等
您將訪問過的位置存儲在 python 集合中 - 在您將 go 存儲到新位置之前,您檢查該位置是否已經在集合中。 也就是說,如果您只希望每個位置有一塊垃圾 - 如果您最終希望有多個垃圾,您可以將網格 model 作為字典; 但作為一組——
def total_garbage(positions):
# Create a dictionary translating direction to co-ordinate changes
deltas = {'N':(0,-1),'S':{0,1),'E':(1,0),'W':(-1,0)}
cleaned_locations = set()
start_location = (0,0)
garbage = 0
for direction in positions:
dx, dy = deltas[direction]
x,y = start_location
nx, xy = x + dx, y+dx
# Count this site so long as it isn't already cleaned.
if (nx, ny) not in cleaned:
garbage += 1
cleaned.add((nx,ny))
else:
return garbage
qp = total_garbage(['N','E','S','W'])
print(qp)
您可以按照 Ahmet 在評論中建議的方式創建一個數組,但如果您不想這樣做,可以這樣做:
x, y = 0, 0 # this will be our position
visited_idx = set() # indexes where we have already gathered garbage
for direction in positions:
if direction.upper() == 'N':
y += 1
elif direction.upper() == 'S':
y -= 1
elif direction.upper() == 'E':
x += 1
elif direction.upper() == 'W':
x -= 1
current_idx = (x,y)
# You wrote that there is no garbage in the first cell hence the second codition
if current_idx not in visited_idx and current_idx != (0,0):
visited_idx.add(current_idx)
units_of_garbage_gathered = len(visited_idx)
首先,當我運行此代碼時,我相信您正在尋找 4。 如果你想知道你的廣場是否已經收集了垃圾,我認為你可能需要在你的動作和 collections 的同時跟蹤它。有幾種方法可以做到這一點,我會建議你的列表列表網格,如果您想要一個 3x3 網格,請創建如下內容:
grid = [[0,0,0],[0,0,0],[0,0,0]]
您現在可以有一些東西來跟蹤垃圾已被拾取的位置以及是否有任何要拾取的東西。
所以現在,你的下一步是找出一個起點,比如
grid[0][0]
那么如果你上移一個,你就會進入
grid[1][0]
如果您訪問該地點,在您的 function 中,執行以下操作:
newPos = grid[1][0]
if (newPos != 1) {
// do your collecting and change grid[1][0] form 0 to 1
} else {
// don't collect, track your movement or whatever else you want.
}
我希望這有幫助! 祝你好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.