Total time required to travel a path denoted by a given string | Function to calculate time taken to travel the path ; Stores total time ; Initial position ; Stores visited segments ; Check whether segment is present in the set ; Increment the value of time by 2 ; Insert segment into the set ; Print the value of time ; Driver Code
def calcTotalTime ( path ) : NEW_LINE INDENT time = 0 NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE s = set ( [ ] ) NEW_LINE for i in range ( len ( path ) ) : NEW_LINE INDENT p = x NEW_LINE q = y NEW_LINE if ( path [ i ] == ' N ' ) : NEW_LINE INDENT y += 1 NEW_LINE DEDENT elif ( path [ i ] == ' S ' ) : NEW_LINE INDENT y -= 1 NEW_LINE DEDENT elif ( path [ i ] == ' E ' ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT elif ( path [ i ] == ' W ' ) : NEW_LINE INDENT x -= 1 NEW_LINE DEDENT if ( p + x , q + y ) not in s : NEW_LINE INDENT time += 2 NEW_LINE s . add ( ( p + x , q + y ) ) NEW_LINE DEDENT else : NEW_LINE INDENT time += 1 NEW_LINE DEDENT DEDENT print ( time ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT path = " NSE " NEW_LINE calcTotalTime ( path ) NEW_LINE DEDENT