# Pythonでの検索最適化

ジャック
``````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)
``````

この質問では、実行が長すぎるためにフラグが立てられ、それを高速化するために明確な最適化を行うことができるかどうか疑問に思っています。「for-loops」の使用は責任があると思いますが、私のステップを実行する他の方法がわかりません。

lllrnr101
``````Total_travels = [sum(Separate_Paths[0:i+1]) for i in range(len(Separate_Paths))]
``````

``````>>> 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にはcumsum組み込まれているので、あなたの問題にはやり過ぎだと思います。

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

0