Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the items in a range

p1 = (0, 10, 1)
p2 = (0, -20, -2)
p3 = (0,10,2)

Hi,

I have the above code and I'd simply like a quick way to count how many items are in each range without iterating through it? (its part of a few nested loops). So p1 would return 9.

Also is there a better way to pass those variables in to the range function?

right now i'm suing:

range(p1[0], p1[1], p1[2])
like image 847
novawaly Avatar asked Oct 25 '25 00:10

novawaly


2 Answers

>>> p1 = (0, 10, 1)
>>> len(range(*p1))
10

range objects are clever and don't require iteration to calculate the length.

like image 143
wim Avatar answered Oct 26 '25 19:10

wim


The virtue of this is that you don't have to create a new object to calculate.

def c(p):
  return max((p[1] - p[0]) // p[2], 0)

c(p1)

10
like image 38
piRSquared Avatar answered Oct 26 '25 17:10

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!