python - Define range for index for lists in for loops -


i'm complete beginner in python. coding "minimum difference between array elements" problem. idea sort array , find difference between adjacent elements, find 1 minimum difference.

however, wonder how define range index of list in loops index doesn't exceed size-2.

import sys  a=[34,56,78,32,97,123] a,size=sorted(a),len(a) min=sys.maxint  i,x in enumerate(a):  # need range index 0 size-2     if(abs(a[i]-a[i+1])<min):           min=abs(a[i]-a[i+1])  print min 

if want use manual indexing, dont use enumerate() , create range() (or xrange() if python 2.x) of right size, ie:

for in xrange(len(a) - 2):    # code here 

now don't have manually take care of indexes @ - if want iterate on (a[x], a[x+1]) pairs need zip():

for x, y in zip(a, a[1:]):    if abs(x - y) < min:        min = abs(x - y) 

zip(seq1, seq2) build list of (seq1[i], seq2[i]) tuples (stopping when smallest sequence or iterator exhausted). using a[1:] second sequence, have list of (a[i], a[i+1]) tuples. use tuple unpacking assign each of tuple's values x , y.

but can use builtin min(iterable) function instead:

min(abs(x - y) x, y in zip(a, a[1:])) 

which pythonic way smallest value of sequence or iterable.

note python 2.x, if real list way bigger, you'll benefit using itertools.izip instead of zip

as side note, using min (actually using builtin name) variable name possibly not idea shadows builtin in current namespace. if typeerror: 'int' object not callable message trying code you'll know why...


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -