财富通灵塔的乘驾【难度:3级】:

答案1:

def ride_of_fortune(artifact, explorers):STATES = {'A': 'B', 'B': 'A'}DIRS = {'E': (0, 1), 'S': (1, 0), 'W': (0, -1), 'N': (-1, 0)}ROUTES = {'A': {'E': 'S', 'S': 'E', 'W': 'N', 'N': 'W'},'B': {'E': 'N', 'N': 'E', 'W': 'S', 'S': 'W'},}h, w = len(artifact), len(artifact[0])gotos, switches, ends = {}, {}, {}# Scan artifact in four directionsy = x = 0for outer, inner in zip('ESWN', 'SWNE'):(dy, dx), (dv, du) = DIRS[outer], DIRS[inner]while 0 <= y < h and 0 <= x < w:v, u = y, xstart = v - dv, u - duwhile 0 <= v < h and 0 <= u < w:if artifact[v][u] != ' ':gotos[inner, start] = v, ustart = v, uswitches[start] = artifact[v][u]v += dv; u += duv -= dv; u -= duends[inner, start] = [v, u] if inner != 'W' else Noney += dy; x += dxy -= dy; x -= dx# Send each explorer from switch to switchexits = []for door in explorers:dir, pos = 'E', (door, -1)while (dir, pos) not in ends:pos = gotos[dir, pos]state = switches[pos]dir = ROUTES[state][dir]switches[pos] = STATES[state]exits.append(ends[dir, pos])return exits​

答案2:

def ride_of_fortune(artifact,explorers):ziggurat = [[y for y in x] for x in artifact]def mowe(pos,direct):if ziggurat[pos[0]][pos[1]]=='A':direct.reverse()ziggurat[pos[0]][pos[1]]='B'else: if ziggurat[pos[0]][pos[1]]=='B':direct.reverse()direct = [x*-1 for x in direct]ziggurat[pos[0]][pos[1]]='A'nextStep = list(map(lambda x,y:x+y,pos,direct))if max(nextStep)>=len(ziggurat) or nextStep[0]<0:return posif nextStep[1]<0:return None    return mowe(nextStep,direct)return list(map(lambda x:mowe([x,0],[0,1]),explorers))        ​

答案3:

from itertools import chain, countdef ride_of_fortune(artifact, cars):def moveCar(start, x,y):goal = next( (x+n*d[0], y+n*d[1]) for n in count(start) if (x+n*d[0], y+n*d[1]) in board )newD, what = d, board[goal]if isinstance(what,int):newD = tuple( z * (-1)**(what) for z in d[::-1] )        # Change direction on switchesboard[goal] ^= 1                                         # swap the switchreturn goal, newD, whatlX, lY = len(artifact), len(artifact[0])board = {(x,y):c=='B' for x,line in enumerate(artifact) for y,c in enumerate(line) if c in 'AB'}board.update(dict(it for it in chain( ( ((x,-1),   None  ) for x in range(lX)),( ((x,lY), (x,lY-1)) for x in range(lX)),( ((-1,y),   (0,y)) for y in range(lY)),( ((lX,y) ,(lX-1,y)) for y in range(lY)) )))lst = []for x in cars:pos, d, start = (x,0), (0,1), 0while True:start, (pos, d, what) = 1, moveCar(start, *pos)if not isinstance(what,int):lst.append(what and list(what))breakreturn lst​

答案4:

def ride_of_fortune(Map,Explorer) :Map = [[' A B'.index(V) for V in V] for V in Map]U = []for R in Explorer :D,C = 1,0while 9 :if Map[R][C] :Map[R][C] ^= 2D ^= Map[R][C]r,c = [[-1,0],[0,1],[1,0],[0,-1]][D]R += rC += cif R < 0 or len(Map) <= R or C < 0 or len(Map[R]) <= C :U.append(None if C < 0 else [R - r,C - c])breakreturn U​

答案5:

def ride_of_fortune(artifact,explorers):r,n=[],len(artifact)d={(idx,jdx):switch(j) for idx,i in enumerate(artifact) for jdx,j in enumerate(i) if j in 'AB'}for i in explorers:x,y=i,0tx,ty=d[(x,y)](0,1) if (x,y) in d else (0,1)while -1<x+tx<n and -1<y+ty<n:x+=txy+=tyif (x,y) in d:tx,ty=d[(x,y)](tx,ty)r+=[None] if y==0 and ty==-1 else [[x,y]] return rdef switch(state):d={'A':-1,'B':1}t=[d[state]]def f(x,y):t[0]=t[0]*-1return (t[0]*y,t[0]*x)return f ​

答案6:

class Explorer:"""Explorer object which 'moves' about in the artifact"""def __init__(self, y: int, x: int = 0, direction: str = "E"):""":param y: The vertical start coordinate.:param x: The horizontal start coordinate.:param direction: The initial explorer direction."""self._x = xself._y = yself._dir = directiondef move(self) -> None:"""Moves the explorer by 1 unit given their current direction"""east_west_movement = {"E": 1, "W": -1}north_south_movement = {"N": -1, "S": 1}if self._dir in east_west_movement:self._x += east_west_movement[self._dir]else:self._y += north_south_movement[self._dir]@propertydef get_dir(self) -> str:return self._dir@propertydef get_x(self):return self._x@propertydef get_y(self):return self._ydef change_dir(self, direction) -> None:self._dir = directionclass Switch(object):"""Switch object which has two states: A or B. An Explorer will change direction upon entering a Switch"""def __init__(self, state: str, x: int, y: int):""":param state: Current Switch state. Must be either 'A' or 'B':param x: Switch x coordinate.:param y: Switch y coordinate."""self.state = stateself.x = xself.y = ydef state_change(self) -> None:"""Changes the artifact's state from A to B or from B to A"""state_dict = {"A": "B", "B": "A"}self.state = state_dict[self.state]def operation(self, explorer: Explorer) -> None:"""This method changes the explorer's direction based onthe artifact's current state"""direction_dict = {"A": {"W": "N", "E": "S", "S": "E", "N": "W"},"B": {"W": "S", "E": "N", "S": "W", "N": "E"}}explorer.change_dir(direction_dict[self.state][explorer.get_dir])self.state_change()def __repr__(self):return "state: {}, x: {}, y: {}".format(self.state, self.x, self.y)def ride(explorer_list: list, switch_list: list, switch_coordinates: dict) -> list:"""Determines the explorer's final destination"""result = []exit_north_south = {"N": 0, "S": len(switch_list) - 1}exit_east_west = {"E": len(switch_list[0]) - 1, "W": 0}for y_position in explorer_list:explorer = Explorer(y_position)# While explorer is still in the artifact and has not exited itwhile True:if (explorer.get_x, explorer.get_y) in switch_coordinates:switch = switch_coordinates[(explorer.get_x, explorer.get_y)]switch.operation(explorer)if explorer.get_x == 0 and explorer.get_dir == "W":result.append(None)breakelif explorer.get_dir in exit_east_west:if exit_east_west[explorer.get_dir] == explorer.get_x:result.append([explorer.get_y, explorer.get_x])breakelif explorer.get_dir in exit_north_south:if exit_north_south[explorer.get_dir] == explorer.get_y:result.append([explorer.get_y, explorer.get_x])breakexplorer.move()return resultdef create_switch_coordinates(array: list) -> dict:"""Finds all Switch coordinates"""switch_coordinates = dict()for col in range(len(array)):for row in range(len(array)):value = array[col][row]if value != " ":switch_coordinates[(row, col)] = Switch(value, row, col)return switch_coordinatesdef ride_of_fortune(matrix: list, explorers: list) -> list:"""Main function"""positions = [list(row) for row in matrix]artifact_coords = create_switch_coordinates(positions)return ride(explorers, positions, artifact_coords)​

答案7:

# 0: North, 1: East, 2: South, 3: West
deltaRow = [-1, 0, 1, 0]
deltaCol = [0, 1, 0, -1]def ride_of_fortune(artifact, explorers):answer = []height, width = len(artifact), len(artifact[0])switches = {}for row, rowchars in enumerate(artifact):for col, char in enumerate(rowchars):if char in "AB":switches[row, col] = char == "A"for explorer in explorers:row, col, direction = explorer, 0, 1while True:if (row, col) in switches:isA = switches[row, col]if isA:direction = [3, 2, 1, 0][direction]else: #isBdirection = [1, 0, 3, 2][direction]switches[row, col] = not isArowNext = row + deltaRow[direction]colNext = col + deltaCol[direction]if rowNext < 0 or rowNext >= height or colNext >= width:answer.append([row, col])breakelif colNext < 0:answer.append(None)breakrow, col = rowNext, colNextreturn answer​

答案8:

"""
Solution to Codewar's 'Ziggurat Ride of Fortune' problem by docgunthrop
"""class Explorer(object):def __init__(self, y):self.x = 0self.y = yself.dir = "E"def move(self):"""Moves the explorer by 1 unit given their current direction"""latitude_movement = {"E": 1, "W": -1}longitude_movement = {"N": -1, "S": 1}if self.dir in latitude_movement:self.x += latitude_movement[self.dir]else:self.y += longitude_movement[self.dir]   class Artifact(object):def __init__(self, state, x, y):self.state = stateself.x = xself.y = ydef state_change(self):"""Changes the artifact's state from A to B or from B to A"""state_dict = {"A": "B", "B": "A"}self.state = state_dict[self.state]def operation(self, explorer):"""This method changes the explorer's direction based onthe artifact's current state"""direction_dict = {"A": {"W":"N", "E":"S", "S":"E", "N":"W"}, "B": {"W":"S", "E":"N", "S":"W", "N":"E"}}explorer.dir = direction_dict[self.state][explorer.dir]def __repr__(self):return "state: {}, x: {}, y: {}".format(self.state, self.x, self.y)def main(explorer_list: list, artifact_list: list, artifact_coordinates: dict) -> list:"""Determines where explorers end their ride"""result = [] quit_long = {"N": 0, "S": len(artifact_list) - 1} quit_lat = {"E": len(artifact_list[0]) - 1, "W": 0}for y_position in explorer_list:explorer = Explorer(y_position)while True:                              if (explorer.x, explorer.y) in artifact_coordinates:               artifact = artifact_coordinates[(explorer.x, explorer.y)]artifact.operation(explorer)artifact.state_change()if explorer.x == 0 and explorer.dir == "W":result.append(None)break           elif explorer.dir in quit_long:if quit_long[explorer.dir] == explorer.y:result.append([explorer.y, explorer.x])breakelif explorer.dir in quit_lat:if quit_lat[explorer.dir] == explorer.x:result.append([explorer.y, explorer.x])breakexplorer.move()              return resultdef create_artifact_coordinates(artifact_list: list) -> dict:artifact_coordinates = {}for col in range(len(artifact_list)):for row in range(len(artifact_list)):value = artifact_list[col][row]if value != " ":artifact_coordinates[(row, col)] = Artifact(value, row, col)return artifact_coordinatesdef ride_of_fortune(artifact: list, explorers: list) -> list:   artifacts = [list(row) for row in artifact]artifact_coords = create_artifact_coordinates(artifacts)       result = main(explorers, artifacts, artifact_coords)return result​

答案9:


dic = {("A", (0, 1)): (1, 0), ("A", (0, -1)): (-1, 0), ("A", (1, 0)): (0, 1), ("A", (-1, 0)): (0, -1), ("B", (0, 1)): (-1, 0), ("B", (0, -1)): (1, 0), ("B", (1, 0)): (0, -1), ("B", (-1, 0)): (0, 1)}def ride_of_fortune(artifact,explorers):res = []a = artifactfor e in explorers:d = (0, 1)pos = (e, 0)while True:if a[pos[0]][pos[1]] is "A":d = dic[("A", (d))]a[pos[0]] = a[pos[0]][:pos[1]] + "B" + a[pos[0]][pos[1]+1:]elif a[pos[0]][pos[1]] is "B":d = dic[("B", (d))]a[pos[0]] = a[pos[0]][:pos[1]] + "A" + a[pos[0]][pos[1]+1:]if any([(x+d[c]==-1 or x+d[c]==len(a)) for c, x in enumerate(pos)]):if pos[1]+d[1]==-1: res.append(None)else: res.append(list(pos))breakpos = tuple(sum(x) for x in zip(pos, d))return res​

景越Python基础训练营QQ群


欢迎各位同学加群讨论,一起学习,共同成长!

Python练习题答案: 财富通灵塔的乘驾【难度:3级】--景越Python编程实例训练营,1000道上机题等你来挑战相关推荐

  1. Python练习题答案: 馏分类【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

    馏分类[难度:2级]: 答案1: # Something goes Here ...class Fraction:def __init__(self, numerator, denominator): ...

  2. Python练习题答案: IRR计算 - 盈利能力的评价【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

    IRR计算 - 盈利能力的评价[难度:2级]: 答案1: def irr(c):precision, guess, v, lastPositiveGuess, lastNegativeGuess = ...

  3. Python练习题答案: 杰克的家【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

    杰克的家[难度:2级]: 答案1: VERSES = """\ This is the house that Jack built.This is the malt th ...

  4. Python练习题答案: 分类新会员【难度:1级】--景越Python编程实例训练营,1000道上机题等你来挑战

    分类新会员[难度:1级]: 答案1: def openOrSenior(data):return ["Senior" if age >= 55 and handicap &g ...

  5. Python练习题答案: CIS 122#12中的构造【难度:1级】--景越Python编程实例训练营,1000道上机题等你来挑战

    CIS 122#12中的构造[难度:1级]: 答案1: # For your convenience, the following functions from previous challenges ...

  6. Python练习题答案: 转换货币II【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

    转换货币II[难度:2级]: 答案1: def solution(to,lst):dolSym, eurSym, power = ('', '€', -1) if to=='EUR' else ('$ ...

  7. Python练习题答案: 海盗!是大炮准备好了!?【难度:0级】--景越Python编程实例训练营,1000道上机题等你来挑战

    海盗!是大炮准备好了!?[难度:0级]: 答案1: def cannons_ready(gunners):return 'Shiver me timbers!' if 'nay' in gunners ...

  8. Python练习题答案: 摩门经【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

    摩门经[难度:2级]: 答案1: from math import log, ceil def mormons(starting_number, reach, target):return ceil( ...

  9. Python练习题答案: 赛车#1:简化拖动赛【难度:1级】--景越Python编程实例训练营,1000道上机题等你来挑战

    赛车#1:简化拖动赛[难度:1级]: 答案1: def drag_race(length, anna, bob):a = length / anna.speed + anna.reaction_tim ...

最新文章

  1. 【Android】Touch事件分发
  2. VBA遍历文件夹下文件文件实用源码
  3. geany搭建python环境_第一章:搭建Python的开发环境
  4. python中二进制整数_Python程序查找表示二进制整数的必要位数
  5. 【算法分析与设计】证明插入排序的正确性
  6. 操作系统之进程管理:4、线程与多线程
  7. python 参数_python脚本命令行参数解析
  8. Linux 更改共享内存tmpfs的大小
  9. 976. 三角形的最大周长
  10. AI考拉技术分享会--Node.js APM 软件调研报告
  11. chrome导入与导出书签
  12. 倒排索引Inverted index
  13. 谷粒商城-个人笔记(基础篇一)
  14. android截屏保存目录,Android实现截屏,将截图文件保存到本地文件夹
  15. 面相对象的总结项目(嗖嗖业务大厅)
  16. 电脑编程从哪里开始学习_我想学习编程,但我不知道从哪里开始
  17. iOS开发之应用首次启动显示用户引导 - 疯狂的萝卜 - 博客园
  18. 实验九:采用异步方式实现文件读/写
  19. Error:1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL
  20. Oracle12C--触发器(52)

热门文章

  1. 微信小程序获取用户唯一标识openid的若干个坑
  2. 转载:16条有用的句子
  3. 哈工大李治军老师的操作系统学习笔记
  4. 计算机和软件技术相关文献资料,APA参考文献格式计算机软件及应用IT计算机专业资料-APA参考文(9页)-原创力文档...
  5. Microsoft Graph for Office 365 - 身份验证路线图和访问令牌
  6. 大学计算机专业容易挂科的内容,大学最“烧脑”的3类专业,很容易挂科,但就业前景一片大好!...
  7. python集合运算_python集合的运算(交集、并集、差集、补集)
  8. win32-win10-防止打开ie浏览器跳转至edge-启动ie浏览器
  9. HBITMAP与BITMAP 的区别 BMP图像的格式
  10. 淋雨量matlab,对雨中人跑步淋雨量问题的探讨