【发布时间】:2022-01-14 21:02:33
【问题描述】:
我遇到了这个关于代码大战的练习,这让我困惑了几天。练习是编写一个接收方向列表的函数。然后该函数应该将方向“减少”到更简单的方向。例如,如果您要前往 'NORTH','SOUTH','EAST','NORTH' ;由于向北行驶,然后再次向南行驶,方向将减少为“东”、“北”,这会将您置于同一位置。所有变体都需要进行相同的“减少”过程: N S , W E
我最终不得不找到已经过测试并作为问题解决方案的代码。我的问题是我并不完全理解其背后的逻辑。我已经继续并将下面的代码与一些 cmets 放在我的思考过程中,代码中发生了什么。我
我只是想更清楚地了解这个粒子代码。谢谢!
def dirReduc(arr):
#create a dictionary with all the possible combinations that need to be 'reduced'
opposites = {'NORTH':'SOUTH', 'SOUTH':'NORTH', 'EAST':'WEST', 'WEST':'EAST'}
#create an empty list to store the valid directions that are not reduced.
new_list = []
#iterate through the list of items that has been passed to the function.
for item in arr:
#This is where i get lost. I dont understand the logic behind this.
#you check to see if the new list and the corrosponding item in the dictionary are equal to an empty list??
if new_list and opposites[item] == new_list[-1]:
new_list.pop()
else:
new_list.append(item)
return new_list
【问题讨论】:
-
"
if new_list" 检查new_list不为空(意味着我们至少移动了一次)。如果是这样,那么new_list[-1](最后一个元素)就是我们所做的最后一步。所以opposites[item] == new_list[-1]检查我们即将进行的移动是否与我们刚刚进行的移动相反,如果是,我们撤消上一个移动而不是添加一个新移动。 -
您可能会被
and绊倒。实际上,该条件的运算顺序解析为if (new_list) and (opposites[item] == new_list[-1]):-and运算符的优先级低于==运算符。 -
因此,由于列表为空,if 语句通过了第一次遍历,else 语句使用传递的参数中的第一项填充列表。然后在第二次迭代中,if 语句看到列表不再为空,然后使用比较运算符查看字典值是否等于新列表的最后一个索引?