I have the following definition for a function named intervals.
From the print statement at the bottom I get this results (which are half-hour time intervals like 9:00, 9:30, etc expressed as lists in lists, I believe).
[[9, 0], [10, 30], [10, 30], [10, 30]]
I would like the following result.
[[9, 0], [ 9, 30], [10, 0], [10, 30]]
The complete log of the run is as follows. Notice that the list list is only updated once in the while loop between the print "b(efore)" and the print "a(fter)" statements and yet list changes after the after and before the next before. How can that happen?
[9, 30] [[9, 0]] b
[9, 30] [[9, 0], [9, 30]] a
[10, 0] [[9, 0], [10, 0]] b
[10, 0] [[9, 0], [10, 0], [10, 0]] a
[10, 30] [[9, 0], [10, 30], [10, 30]] b
[10, 30] [[9, 0], [10, 30], [10, 30], [10, 30]] a
[[9, 0], [10, 30], [10, 30], [10, 30]]
def intervals(start,end):
if start>=end:
return []
else:
if 0<=start[1]<30:
start[1]=0
else:
start[1]=30
list = []
list.append(start)
last = start
new=[0,0]
while end>last:
if 30==last[1]:
new[0]=1+last[0]
new[1]=0
else:
new[0]=last[0]
new[1]=30
last=new
print new,list,"b"
list.append(new)
print new,list,"a"
return list
print intervals([9,0],[10,30])
Can anyone fix it?
The reason you see this is that on each iteration of the
whileloop you append the listnewto the end of your listlist(which you should really rename, since it masks the built-in list type).Just move the
new=[0,0]line so that it is the first line in thewhileloop, this will create a new list on each iteration so that your final list won’t have several references to the same list:Note that if you plan on adding any more complexity to this (for example different intervals than 30 minutes), I would really suggest using the datetime module,
datetime.timedelta(minutes=30)would probably be useful, for example: