def CountingVallys(PathsTaken):
#Converts the Strings U and D into 1 and -1 respectively
Separate_Paths = [i for i in PathsTaken]
for index, i in enumerate(Separate_Paths):
if i == "D":
Separate_Paths[index] = -1
else:
Separate_Paths[index] = 1
Total_travels = [sum(Separate_Paths[0:i+1]) for i in range(len(Separate_Paths))]
#ValleyDistance shows the indexes where the traveller is below sea level and Valley Depth shows the depth at those
#Indexes
ValleyDistance = []
ValleyDepth = []
for Distance, Depth in enumerate(Total_travels):
if Depth < 0:
ValleyDistance.append(Distance)
ValleyDepth.append(Depth)
#Checks the distance between each index to shows if the valley ends (Difference > 1)
NumberOfValleys = []
DistanceOfValleys = []
TempDistance = 1
for index, Distance in enumerate(ValleyDistance):
# Check if final value, if so, check if the valley is distance 1 or 2 and append the final total of valleys
if ValleyDistance[index] == ValleyDistance[-1]:
if ValleyDistance[index] - ValleyDistance[index - 1] == 1:
TempDistance = TempDistance + 1
DistanceOfValleys.append(TempDistance)
NumberOfValleys.append(1)
elif ValleyDistance[index] - ValleyDistance[index - 1] > 1:
DistanceOfValleys.append(TempDistance)
NumberOfValleys.append(1)
#For all indexes apart from the final index
if ValleyDistance[index] - ValleyDistance[index-1] == 1:
TempDistance = TempDistance + 1
elif ValleyDistance[index] - ValleyDistance[index-1] > 1:
DistanceOfValleys.append(TempDistance)
NumberOfValleys.append(1)
TempDistance = 1
NumberOfValleys = sum(NumberOfValleys)
return NumberOfValleys
if __name__ == "__main__":
Result = CountingVallys("DDUDUUDUDUDUD")
print(Result)
一个狂热的徒步旅行者会仔细记录他们的徒步旅行。远足总是在海平面处开始和结束,并且每次向上(U)或向下(D)代表高度的单位变化。我们定义以下术语:
山谷是指一系列从海平面以下的连续台阶,从海平面向下的台阶开始,直至海平面的台阶结束。
查找并打印经过的山谷数。
在这个问题中,由于执行时间过长而被标记,我想知道是否可以进行任何明显的优化以使其更快。我认为应该责怪使用“ for循环”,但是我不确定执行我的步骤的任何其他方式。
Total_travels = [sum(Separate_Paths[0:i+1]) for i in range(len(Separate_Paths))]
在上面的代码中,为什么要重复已经执行的计算?sum(Separate_Paths [0:i + 1])= sum(Separate_Paths [0:i] + Separate_Paths [i + 1]
您可以高效地制作列表Total_travels。那应该解决程序执行时间过长的问题。
>>> a
[2, 6, 4, 9, 10, 3]
>>> cumulative_sum = []
>>> sum_till_now = 0
>>> for x in a:
... sum_till_now += x
... cumulative_sum.append(sum_till_now)
...
>>> cumulative_sum
[2, 8, 12, 21, 31, 34]
>>>
numpy具有内置的累积量,我认为这对您的问题来说是过大的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句