Inclusive range of list Python -
i'm trying find minimum elements within section of list. in next example, start , b end. these indexes partition list inclusively, if list [1,2,3,9,4,10] indexes 1 4 include 2 , 4.
def minimum (a,b,list): homecoming min(list[a:b])
in other words, there way create list[a:b]
inclusive?
by default, no.
for case, more conventional do:
min(li[a:b + 1])
also beware of naming variable list, can have unintended consequences (silent namespace issues), "list" names built-in list container type.
if want write own minimum method, can encapsulate behavior in minimum method using above method don't have think ever again.
side note: standard list-slicing uses o(n) space , can expensive big lists if minimum called on , on gain. cheaper o(1) space alternative be:
def minimum(a, b, li): min(itertools.islice(li, a, b + 1))
edit: don't utilize islice unless slicing starting @ origin of list or have tight memory constraints. first iterates a, rather straight indexing a, can take o(b) run-time.
a improve solution this, runs o(b-a) run-time , o(1) space:
def minimum(li, a=0, b=none): if b none: b = len(li) - 1 if b - < 0: raise valueerror("minimum() arg empty sequence") current_min = li[a] index in xrange(a, b + 1): current_min = min(current_min, li[index]) homecoming current_min
a fancier solution can utilize if list static (elements not deleted , inserted during series of queries) perform range minimum queries using segment trees: http://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/
building tree requires o(n) run-time , o(n) space, although queries after require o(log(n)) run-time , o(1) additional space.
python-2.7 python-3.x
No comments:
Post a Comment