Search code examples
pythonpython-3.xlistloopsindex-error

Program on execution shows "IndexError". It is a code for the problem on HackerRank


Problem: An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps, for every step it was noted if it was an uphill, , or a downhill, step. Hikes always start and end at sea level, and each step up or down represents a unit change in altitude. We define the following terms:

A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.


n = int(input("Enter the no. of steps:"))
steps = input("Enter the path:")[:n].upper()
uc,dc = 0,0
vc = 0
valley = []
for i in steps:
    #to count the no. of down steps
    if i == 'D': 
        dc += 1

    #to count the no. of up steps        
    if i == 'U': 
        uc += 1
    valley.append(i) #list for valleys or mountains

    #Start recounting if up_count == down_count; to get to **sea level**
    if dc == uc:
        dc,uc = 0,0
    
    #--Valleys--
    if valley[0] == 'D'  and uc == 0 and dc==0:
        vc += 1 #No. of valleys
        valley.clear() #clear the list

    #--Mountains--
    if valley[0] == 'U' and uc == 0 and dc==0:
        valley.clear()

print(vc)

Solution

  • This is because the following code clears valley if the condition is True-

    #--Valleys--
    if valley[0] == 'D'  and uc == 0 and dc==0:
        vc += 1 #No. of valleys
        valley.clear() #clear the list
    

    And you still try to check valley[0] here-

    #--Mountains--
    if valley[0] == 'U' and uc == 0 and dc==0:
        valley.clear()
    

    You either need to use elif instead of if or you need to check if valley is not empty.