'.get()' functionality of mappings for sequences
1 2 | time=(2,5)
all_minutes=(time[0:1] or [0])[0]*60+(time[1:2] or [0])[0]
|
to get element number 'n' from list 'lst' and default value 'default' use:
(lst[n:n+1] or [default])[0]
When using mappings we can use something like:
time={"hours":2,"minutes":5} time={"hours":2} all_minutes=time.get("hours",0)*60+time.get("minutes",0)
But sometimes we get a sequence instead of a mapping:
time=(2,5) time=(2,) time=map(int,raw_input().split(":"))
all_minutes=(time[0:1] or [0])[0]*60+(time[1:2] or [0])[0]
can replace things like: time=(2,5) all_minutes=0 if len(time)>0: ....all_minutes+=time[0]*60 if len(time)>1: ....all_minutes+=time[1]
Slices do not produce runtime errors for out of bound indexes. 'or' shortcircuit hack is also used for this receipt.
Your already using the 'or shortcircuit hack', so why not use the 'and shortcircuit hack' and skip the 1 element slice and lookup altogether:
time=(2,5)
all_minutes=(len(time)>0 and time[0])*60 + (len(time)>1 and time[1])
Looks fine. And while where at it, we could factor "len(time)" out:
I probably should have used another example. The problem is, this last version only works for default values of 0.
By the way here is another way of doing this, avoiding shortcircuit. Dunno if there is any benefit to it: