题解 | #MP3光标位置#
MP3光标位置
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
Python3
代码如下:
while True: try: n = int(input()) cmd = input() playlist = [i for i in range(1, n + 1)] showlist = [1, 2, 3, 4] pt, pts = 0, 0 # pt表示只能在底部或顶部的元素在整个playlist的索引;pts表示在showlist中的指针 for i in cmd: if n <= 4: showlist = [i for i in range(1, n + 1)] if i == 'U': pts -= 1 if pts == -1: # 重置 0 为 n - 1,即移动头部到尾部位置 pts == n - 1 else: pts += 1 if pts == n: # 重置 n - 1 为 0,即移动尾部到头部位置 pts = 0 else: if pts == 0: # 处于showlist顶部 if i == "U": if pt == 0: pts = 3 pt = n - 1 showlist = playlist[pt - 3 :] else: pt = showlist[0] - 1 - 1 # 更新showlist,pts仍然在顶部; pt在底部 showlist = playlist[pt: pt + 4] elif i == "D": pts += 1 # 不更新showlist,仅向下移动光标即 pts + 1 elif pts == 3: # 处于showlist底部 if i == "U": pts -= 1 # 不更新showlist,仅向上移动光标即 pts - 1 elif i == "D": if pt == n - 1: pts = 0 pt = 0 showlist = playlist[pt:4] else: pt = showlist[-1] + 1 - 1 # 更新showlist, pts仍然在底部 showlist = playlist[pt - 3 : pt + 1] else: if i == "U": pts -= 1 # 不更新showlist,pts - 1 elif i == "D": pts += 1 # 不更新showlist, pts + 1 print(" ".join(map(str, showlist))) print(showlist[pts]) except: break几个if和elif子句里重复出现的可以优化。