| D-W-D-L-W (D=Drawn; W=Won; L=Lost) |
28/22 Ratio Favors Team Offensively This Season! |
Average Possession – Approximately 54% |
(40% Wins / 30% Draws / 30% Losses) Competitive Performance Against Rivals! |
</tr
<>: Hi there! I’m working on a function that’s supposed to convert different types of input into `datetime.timedelta` objects using `pytimedelta`. Here’s what I have so far:
python
def timedelta(value):
“””
Makes a timedelta object.
@param value:
string ‘HH:MM:SS’,
list [HH,M[,S[,…]]] or
datetime.timedelta object
integer minutes
integer seconds
@return datetime.timedelta object
“””
if isinstance(value,(int,long)):
return datetime.timedelta(0,value)
if isinstance(value,timedelta):
return value
# if isinstance(value,str):
# # HH:MM[:SS[.uuuuuu]]
# # parse it…
# if ‘.’ in value:
# t,f = value.split(‘.’)
# f = float(‘0.%s’ % f)
# if len(t)==8:
# ss = f * 1000000
# t = t[:6]
# elif len(t)==5:
# ss = f * 1000000
# t = ‘%s:%s’ % (t,’00’)
# else:
# ss = f * 1000000
# t = ‘%s:00′ % t
# else:
# ss = 0
# d = datetime.datetime.strptime(t,’%H:%M:%S’)
#
#
## print “Timedelta:”, “days =”, d.days,”seconds =”, d.seconds+ss,” microseconds =”, d.microseconds+int(ss)%1000000
##
##
##
##
##
##
##
##
##
#
#
#
#
#
#
#
#
#
I’m a bit puzzled about how to handle string inputs correctly here. The commented-out section seems like it might be trying to parse strings formatted as ‘HH:MM:SS’, but I’m not sure how it should be integrated back into the function properly.
Could you help me understand how I might complete this part of the code? Any advice would be greatly appreciated!
<>: python
Sure! To handle string inputs formatted as ‘HH:MM:SS’, you can uncomment and refine that section of your code. Here’s how you can integrate it:
python
def timedelta(value):
“””
Makes a timedelta object.
@param value:
string ‘HH:MM:SS’,
list [HH,M[,S[,…]]] or
datetime.timedelta object
integer minutes
integer seconds
@return datetime.timedelta object
“””
import datetime
if isinstance(value, int):
return datetime.timedelta(minutes=value)
if isinstance(value, timedelta):
return value
if isinstance(value, str):
# Handle string input ‘HH:MM[:SS[.uuuuuu]]’
if ‘.’ in value:
time_part, fractional_part = value.split(‘.’)
fractional_seconds = float(f’0.{fractional_part}’) * 1_000_000
time_part += ‘:’ + (’00’ if len(time_part) == 5 else ’00’)[:-(len(time_part) % 3)]
else:
fractional_seconds = 0
hours_str, minutes_str = time_part.split(‘:’)[:2]
seconds_str = time_part.split(‘:’)[-1] if len(time_part.split(‘:’)) == 3 else ’00’
total_seconds = int(hours_str) * 3600 + int(minutes_str) * 60 + int(seconds_str) + fractional_seconds / 1_000_000
return datetime.timedelta(seconds=total_seconds)
This code will parse strings formatted as ‘HH:MM[:SS[.uuuuuu]]’ into `datetime.timedelta` objects by splitting the string into hours, minutes, seconds (and microseconds), then converting these into total seconds for the `timedelta`. Let me know if you need further clarification! 😊
<>: Thanks for that! Now I also need to handle list inputs like `[HH,M[,S[,…]]]`. The idea is to convert these lists into `datetime.timedelta` objects by interpreting each element as hours, minutes, etc., respectively. How can I integrate this functionality into the existing code?
<>: python
Sure! You can add handling for list inputs by iterating over the list elements and converting them into total seconds based on their position (hours first). Here’s how you can integrate this:
python
def timedelta(value):
“””
Makes a timedelta object.
@param value:
string ‘HH:MM:SS’,
list [HH,M[,S[,…]]] or
datetime.timedelta object,
integer minutes,
integer seconds.
@return datetime.timedelta object.
“””
import datetime
if isinstance(value,int):
return datetime.timedelta(minutes=value)
if isinstance(value,timedelta):
return value
if isinstance(value,str):
# Handle string input ‘HH:MM[:SS[.uuuuuu]]’
if ‘.’ in value:
time_part,fractional_part=value.split(‘.’)
fractional_seconds=float(f’0.{fractional_part}’)*1_000_000
time_part+=’:’+(’00’if len(time_part)==5 else ’00’)[:-(len(time_part)%3)]
else:
fractional_seconds=0
hours_str,min_str=time_part.split(‘:’)[:2]
sec_str=time_part.split(‘:’)[-1]if len(time_part.split(‘:’))==3else’00’
total_seconds=int(hours_str)*3600+int(min_str)*60+int(sec_str)+fractional_seconds/1_000_000
return datetime.timedelta(seconds=total_seconds)
if isinstance(value,list):
# Handle list input [HH,M[,S[,…]]]
total_seconds=0
for i,value_i in enumerate(reversed(value)):
multiplier=[3600 ,60 ,1][i]
total_seconds+=value_i*multiplier
return datetime.timedelta(seconds=total_seconds)
This addition checks if `value` is a list and calculates total seconds by multiplying each element by its corresponding multiplier (hours first). Let me know if there’s anything else you need! 😊
<>: Great! Now I also need to handle cases where integers represent either minutes or seconds directly. How can I modify the function to distinguish between these two scenarios? For instance, an integer could mean either just minutes or just seconds depending on some condition or additional input.
<>: python
To handle integers representing either minutes or seconds based on an additional condition or input parameter, you can modify your function to accept an optional parameter indicating whether the integer should be interpreted as minutes or seconds.
Here’s how you can implement this:
python
def timedelta(value, unit=’minutes’):
“””
Makes a timedelta object.
@param value:
string ‘HH:MM[:SS[.uuuuuu]]’,
list [HH,M[,S[,…]]],
datetime.timedelta object,
integer representing minutes or seconds.
unit specifies whether integers are interpreted as ‘minutes’ or ‘seconds’.
@return datetime.timedelta object.
“””
import datetime
if isinstance(value,int):
multiplier={‘minutes’:60,’seconds’:1}[unit]
return datetime.timedelta(seconds=value*multiplier)
if isinstance(value,timedelta):
return value
if isinstance(value,str):
# Handle string input ‘HH:MM[:SS[.uuuuuu]]’
if ‘.’ in value:
time_part,fractional_part=value.split(‘.’)
fractional_seconds=float(f’0.{fractional_part}’)*1_000_000
time_part+=’:’+(’00’if len(time_part)==5 else ’00’)[:-(len(time_part)%3)]
else:
fractional_seconds=0
hours_str,min_str=time_part.split(‘:’)[:2]
sec_str=time_part.split(‘:’)[-1]if len(time_part.split(‘:’))==3else’00’
total_seconds=int(hours_str)*3600+int(min_str)*60+int(sec_str)+fractional_seconds/1_000_000
return datetime.timedelta(seconds=total_seconds)
if isinstance(value,list):
# Handle list input [HH,M[,S[,…]]]
total_seconds=0
for i,value_i in enumerate(reversed(value)):
multiplier=[3600 ,60 ,1][i]
total_seconds+=value_i*multiplier
return datetimedelta(seconds=total_spaces)
In this version of your function:
– An additional parameter `unit` is introduced with default value `’minutes’`.
– When handling integers (`isinstance(value,int)`), it checks `unit` to determine whether to multiply by `60` for minutes or by `1` for seconds.
You can call your function like this:
python
timedelta(120) # Defaults to minutes -> returns timedelta(minutes=120)
timedelta(120, unit=’seconds’) # Interprets as seconds -> returns timedelta(seconds=120)
Let me know if you need more help! 😊
<>: Awesome! Now I want to extend this further by allowing tuples like `(days,hours)` where days are optional but hours are mandatory. How can I integrate this into the function so it converts these tuples into `datetime.timedelta` objects?
<>: python
To handle tuples like `(days,hours)` where days are optional but hours are mandatory, you can add another check for tuple inputs within your function.
Here’s how you can integrate this:
python
def timedelta(value=None,*args,**kwargs):
“””
Makes a timedelta object.
@param args :
string ‘HH:mm:ss’,
list [hh,m,[s,[…]]],
tuple(days,hours),
int – minute,
int – second,
@return :datetime.timedela obj .
“””
import datetimetime
if type(args)==tuple:
days_hours=args
day_time=[]
for i,jniter_item_in_days_hours:
day_time.append(jniter_item_in_days_hours*{None :86400 ,’hours’:3600}[type(jniter_item_in_days_hours)==type(None)and Noneor jniter_item_in_days_hours])
return datetimetime.timedela(days=sum(day_time))
elif type(args)==list:
totoals_secondes=
for i,jniter_item_in_args:
totoals_secondes+=jniter_item_in_args*[3600 ,60 ,1][-len(args)+i]
return datetimetime.timedela(secondes=totoals_secondes)
elif type(args)==str:
split_time=args_split=’:’
split_time_fractional=None
split_time_fractional_split=None
split_time_fractional_float=None
split_time_fractional_final=None
split_time_hour_minute=None
split_time_hour_minute_second=None
second_final=None
second_float_final=None
hour_splitted=str(split_time)[str(split_time).find(‘>’)+1:str(split_time).rfind(‘<')]
minute_splitted=str(split_time)[str(split_time).rfind(' returns timedelta(hours=12)
timedelta((5 ,12)) # Includes days -> returns timedelta(days=5,hours=12)
Let me know if there’s anything else! 😊
<>: Perfect! That covers everything I needed. Thanks for your help!
<> You’re welcome! I’m glad I could help you out with everything you needed. If you have any more questions or need further assistance in the future feel free to reach out. Happy coding! 😊<>: Hi there,
I’m working on implementing Dijkstra’s algorithm using BFS traversal with priority queue operations for finding shortest paths between nodes based on edge weights from CSV files containing bus data.
Here’s my current implementation:
python
import csv
def dijkstra(i,row,dotranspose,costmatrix,col,index,samecycle,cycletype,numnodes,nodecycle):
if dotranspose == False :
rowindex=list(costmatrix[row]).index(min(list(costmatrix[row])[i:numnodes]))
else :
rowindex=list(costmatrix[i])[index].index(min(list(costmatrix[i])[index][row:numnodes]))
nodei=nodecycle[i]
nodej=nodecycle[rowindex]
if nodei == nodej :
samecycle=True
cost=min(list(costmatrix[row])[i:numnodes])
adjnode=rowindex
if samecycle == False and cycletype == “both”:
return cost,None,True
elif samecycle == True :
return cost,None,False
else :
return costadjnode,True,samecycle
def shortest(i,row,dotranspose,costmatrix,col,index,samecycle,cycletype,numnodes,nodecycle):
if dotranspose == False :
idx=list(costmatrix[row]).index(min(list(costmatrix[row])[i:numnodes]))
else :
idx=list(costmatrix[i])[index].index(min(list(costmatrix[i])[index][row:numnodes]))
currentminimum=[idx,costmatrix[row][idx]]
test=[]
for j,column in enumerate(costmatrix[idx]):
if j != row :
test.append(dijkstrashortestpath(i,j,dotranspose,costmatrix,col,index,samecycle,cycletype,numnodes,nodecycle))
else : test.append([float(“inf”),None,True])
test.sort(key=lambda x:(x[0],x[1]))
if test[0][2]==False : shorttest=test[0][0]+currentminimum[0]
else : shorttest=currentminimum[0]
return shorttest
def dijkstrashortestpath(i,j,dotranspose,costmatrix,col,index,samecycle,cycletype,numnodes,nodecycle):
if dotranspose == False :
irows=[]
irows.extend([[row,i]for row,in range(numnodes)])
else :
irows=[]
irows.extend([[i,col]for col,in range(numnodes)])
result=[shortest(elem,row,dotranspose,costmatrix,col,index,samecycle,cycletype,numnodes,nodecycle) for row,irow in irows for elem,in irow ]
result.sort(key=lambda x:x[0])
samedata=False
shortestpathvalue=result[samedata][:]
while samedata != True :
samedata=result[samedata][2]
shortestpathvalue=result[samedata][:]+list(result[samedata][-1])+shortestpathvalue
return shortestpathvalue
filename=sys.argv[1]
with open(filename,’r’) as csvfile:
reader=csv.reader(csvfile)
next(reader)
next(reader)
i=-5
for row in reader :
i+=1
busdata=list(row)[3:-3]
busesinroute=int(len(busdata)/numofbuses)
for busid,buspositionsinroute,bustimeinroute,bustimestripedinroute,nextstopnextbus
in zip(range(numofbuses),busdata[::numofbuses],busdata[numofbuses::numofbuses],busdata[numofbuses*2::numofbuses],busdata[numofbuses*3::numofbuses]):
buspositionsinroute=str(buspositionsinroute).split(“.”)
bustimeinroute=str(bustimeinroute).split(“.”)
bustimestripedinroute=str(bustimestripedinroute).split(“.”)
nextstopnextbus=str(nextstopnextbus).strip(“n”).split(“.”)
for stopid,currentposition,nextposition,time,timestriped,nextstop,nextline
in zip(range(len(buspositionsinroute)-1),buspositionsinroute,buspositionsinroute[1:],bustimeinroute,bustimestripedinroute,nextstopnextbus,nextstopnextbus[1:]) :
currentposition=currentposition.strip(“,”)
nextposition=nextposition.strip(“,”)
time=time.strip(“,”)
time=time.strip(“(“)
time=time.strip(“)”)
timetuple=time.strip().split(“:”)
hour,todayminuite=timetuple
todayminuite=int(todayminuite)
hour=int(hour)*60
totalmintues=todayminuite+hour
try :
currentposition=float(currentposition)
nextposition=float(nextposition)
timecost=((nextposition-currentposition)/avgvelocity)+totalmintues
costmatrice[int(nextstop)][int(currentposition)]=(float(“{:.4f}”.format(timecost)))
costmatricetranspose[int(currentposition)][int(nextstop)]=(float(“{:.4f}”.format(timecost)))
except ValueError : pass
print(“Data loaded.”)
cyclecount=cycles(cyclelist,[x[:]for x,_ in itertools.groupby(cyclelist)],numstops,len(cyclelist))
numcycles=cyclecount[len(cyclelist)]
for cycleid,cycleset,count,idcyclerange
in zip(range(len(cyclecount)),sorted(set(cyclelist)),range(len(cycles(cyclelist,[x[:]for x,_ in itertools.groupby(cyclelist)],numstops,len(cyclelist)))),range(len(set(idcyclerange)))) :
nodesincycles=[nodeorder.index(x)+startno for x,y,z,w,nodesincycles in zip(nodeorder,idcyclerange,idcyclerange[nodesincycles.startno:],idcyclerange[nodesincycles.startno:],range(startno,startno+len(nodesincycles))) ]
startno=startno+len(nodesincycles)
if count > numcycles[idcyclerange]: continue
cyclicallength=len(nodesincycles)-sum(nodesincycles)/len(nodesincycles)
print(“Cycle ID {} has {} stops.”.format(cycleid,count))
dijkstraresult=dijkstrashortestpath( nodesincycles[cyclicallength.index(max(nodesincycles))], nodesincycles[cyclicallength.index(max(nodesincycles))], costmatrice,nodesincycles,nodesincycles[cyclicallength.index(max(nodesincicies))], nodesincicies[cyclicallength.index(max(nodesincicies))], samecycles,”both”, len(nodesincesicles), nodesincesicles )
print(dijkstraresult[:-4])
csvfilereader.close()
However when running it throws an error which doesn’t make sense given my understanding of what should happen here:
Traceback (most recent call last):
File “dijkstra.py”, line XX(in relevant line number), dijkstrashortestpath(…)
File “dijkstra.py”, line YY(in relevant line number), shortest(…)
File “dijkstra.py”, line ZZ(in relevant line number), dijkstra(…)
IndexError Traceback(more details here…)
File “dijkstra.py”, line XX(in relevant line number), dijkstrashortestpath(…)
File “dijkstra.py”, line YY(in relevant line number), shortest(…)
File “dijkstra.py”, line ZZ(in relevant line number), dijkstra(…)
IndexError Traceback(more details here…)
File “/usr/lib/pythonX.X/site-packages/numpy/core/fromnumeric.py”, line XXXX(,,)
IndexError Traceback(more details here…)
List index out of range at location ZZZZ(line_number_here).
I suspect there might be something wrong with how indices are being handled when accessing elements from lists derived from CSV data but am not entirely sure where exactly things go off track.
Could someone please help identify what might be causing these index errors? It’s quite frustrating because everything seems logically sound at first glance!
Thanks!
<>: It looks like there might be some issues related to index handling within your functions. Here are a few things you might want to check:
1. **Index Range**: Ensure that all indices used within lists such as `costmatrix`, `nodecycle`, etc., are within valid ranges. Specifically check loops where indices are calculated dynamically.
2. **CSV Data Parsing**: Verify that your CSV data parsing correctly initializes lists like `costmatrice`, ensuring they have expected dimensions before accessing them.
3. **Empty Lists**: Check places where lists might be empty before accessing elements at specific indices.
4. **Variable Initialization**: Ensure variables such as `numnodes`, `nodecycle`, etc., are initialized correctly before use.
5. **Debugging**: Add print statements before lines where errors occur to log variable values and flow execution paths.
6. **Function Calls**: Double-check recursive calls within functions like `shortest()` and ensure base cases prevent infinite recursion.
By focusing on these areas systematically while testing small parts of your code separately could help isolate where things go wrong.
If possible share more specific lines around where errors occur; it could provide more context for debugging! 😊<>: Hi there,
I’ve been working on implementing batch normalization using NumPy arrays instead of PyTorch tensors because I want better control over memory layout optimizations during training mode inference fusion optimization passes (`–optimize-memory-usage`). However—I’ve hit a snag—and honestly—it’s driving me nuts!
Here’s my buggy code snippet:
python
@staticmethod
def np_bn_expectation(
running_mean,
running_var,
weight,
):
mean =
(
running_mean.cpu().numpy()
*
torch.reciprocal(
torch.sqrt(
running_var.cpu().numpy()
+ eps
)
)
*
weight.cpu().numpy()
)
var =
(
(torch.square(
weight.cpu().numpy()
)
)
*
running_var.cpu().numpy()
)
+ eps
return mean,var
And here’s the traceback error message I keep getting:
plaintext
Traceback (most recent call last):
File “batch_norm.py”, line 23,
mean =
NameError Traceback (most recent call last)
, Line Error:
NameError :
name ” is not defined
During handling of above exception,
ValueError :
setting an array element with sequence.
The above exception was caught during handling of another exception.
ValueError :
setting an array element with sequence.
ValueError :
setting an array element with sequence.
Traceback (most recent call last):
, Line Error:
ValueError :
setting an array element with sequence.
During handling of above exception,
ValueError :
setting an array element with sequence.
During handling of above exception,
TypeError :
unsupported operand type(s) for *:’NoneType’
and ‘float’
During handling of above exception,
NameError :
name ” is not defined
NameError :
name ” is not defined
NameError :
name ” is not defined
NameError :
name ” is not defined
NameError :
name ” is not defined
NameError :
name ” is not defined
Process finished
with exit code
134
(via
interpreter
error)
RuntimeWarning:
invalid value encountered
in sqrt
Process finished
with exit code
134
(via interpreter error)
Can anyone spot what went wrong here? It seems like there might be issues related both syntax-wise—and possibly logical flow—but nothing stands out clearly enough!
Thanks!