简体   繁体   中英

why does this code go into infinite loop?

i don't understand why this snippet goes into a loop

def difference():
    for p, j in enumerate(listaDivisa[:-1]):
        if j[2] == listaDivisa[p + 1][2]:
            if j[3] == "ON" and listaDivisa[p + 1][3] == "OFF":
                time1= j[1]
                time2= listaDivisa[p + 1][1]
                d1 = datetime.strptime(time1, '%H:%M:%S')
                d2 = datetime.strptime(time2, '%H:%M:%S')

                diff = d2 - d1
                return diff

listaDivisa looks like this:

['2009-10-16', '21:06:34.00044', 'kitchen sensor', 'ON']
['2009-10-16', '21:13:22.00016, 'kitchen sensor', 'OFF']
['2009-10-16', '12:53:29.00004', 'bathroom sensor', 'ON']
['2009-10-16', '14:02:51.00056, 'bathroom sensor', 'OFF']

...

also, i tried printing time1 and time2 but it prints 08:50:00 and 08:55:00 for every elements and it's not correct but when i omit the return statement it prints the correct values even thought it goes in a loop

There are a couple of errors with your code. First, the input you provided is weird, is it a nested list? In the code below I assume is a nested list. Second, the time format is wrong, your input contains millisecond but you pass "%H:%M:%S" to datetime.strptime , you will get an error. The correct format in this case is "%H:%M:%S.%f" .

Here is the correct implementation. I commented out the print calls that helped me with the debugging.

from datetime import datetime

  
def difference(nested_list):
    for p, j in enumerate(nested_list[:-1]):
        #print(f'processing entry {p}')
        if j[2] == nested_list[p + 1][2]:
            if j[3] == "ON" and nested_list[p + 1][3] == "OFF":
                time1= j[1]
                time2= nested_list[p + 1][1]
                d1 = datetime.strptime(time1, '%H:%M:%S.%f')
                d2 = datetime.strptime(time2, '%H:%M:%S.%f')
                diff = d2 - d1
                #print(f'returning {diff}')
                return diff
    #print('finished without returning anything')

nested_list = [
    ['2009-10-16', '21:06:34.00044', 'kitchen sensor', 'ON'],
    ['2009-10-16', '21:13:22.00016', 'kitchen sensor', 'OFF'],
    ['2009-10-16', '12:53:29.00004', 'bathroom sensor', 'ON'],
    ['2009-10-16', '14:02:51.00056', 'bathroom sensor', 'OFF'],
]

result = difference(nested_list)
print(result) #datetime.timedelta(seconds=407, microseconds=999720)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM