Is there a more pythonic way to write a while loop that updates only a variable?

I have this while loop, and I was wondering if they have a more pythonic way of writing it:

k = 1 while np.sum(s[0:k]) / s_sum < retained_variance: k += 1 

s - is a numeric vector. Thanks!

+6
source share
4 answers

This may not be the most efficient solution, but quickly if you need to find most of the array:

 import numpy as np ss = np.cumsum(s) # array with cumulative sum k = ss.searchsorted(retained_variance*s_sum) # exploit that ss is monotonically increasing 

EDIT: Simon noted that

 k = np.cumsum(s).searchsorted(retained_variance*s_sum) + 1 

is the value that matches the question.

+2
source

I would say this is pretty pythonic: explicit is better than implicit.

+4
source

The last line of the following code to find the value of k in a row:

 import numpy as np import math s = np.array([1,2,3,4,5,6,7,8,9]) s_sum = 1 retained_variance = 4.3 k = 1 while np.sum(s[0:k]) / s_sum < retained_variance: k += 1 print (k) print (np.ceil(np.interp(retained_variance,s.cumsum()/s_sum,range(1,len(s)+1)))) 
+2
source

this looks more like Haskell than python:

 >>> from itertools import count, dropwhile >>> pred = lambda k: np.sum(s[:k]) / s_sum < retained_variance >>> head = next # just to look more like haskell >>> head(dropwhile(pred, count())) 

edit: this will be more efficient:

 >>> from itertools import dropwhile, accumulate >>> pred = lambda x: x[1] / s_sum < retained_variance >>> head = next >>> head(dropwhile(pred, enumerate(accumulate(s), start=1)))[0] 
+2
source

All Articles