Search code examples
pythonenumerate

how do I reference first argument of an enumeration?


I am writing code with enumerate() in Python, and I am having issues with referencing the first argument in enumerate:

For example, let nums be temperatures of different days:

nums = [1,5,20,9,3,10,50,7]
array = []

for j, distance in enumerate(nums): 
    for k, distance2 in enumerate(nums[1:],1): 
        if nums[j] < nums[k]: 
            array.append(distance2[j]-distance[k]) 

So, the challenge I have is: how do I reference the 'distance' and 'distance2' of each element respectively in my enumerations?

The aim of the problem is to determine for each day, how many days you'll have to wait for a warmer day, so for the example above, the output would be [1,1,4,3,1,1,0,0]; where there are no warmer days ahead, return 0.

Thanks


Solution

  • You need to calculate the distance based off the indexes not the values at the index.

    You should not restart your subscript and inner index at 1 each time but rather at i each iteration.

    nums = [1, 5, 20, 9, 3, 10, 50, 7]
    array = []
    
    for i, curr_temp in enumerate(nums):
        days = 0
        for j, future_temp in enumerate(nums[i:], i):
            if curr_temp < future_temp:
                # Set Days to Distance between Indexes
                days = j - i
                # Stop Looking Once Higher Value Found
                break
    
        array.append(days)
    
    print(array)
    

    Output:

    [1, 1, 4, 2, 1, 1, 0, 0]