Given a list of inputs. The last x of the list, are a number that I want to use for a test. So, the beginning n-x elements are the ones I want to test using the elements in x.
For example:
test_case = [0.18677649597722776, 0.21992417009282958, 0.21001370207789635, 0.2576939078119566, -0.26790678064174844, 0.23723906040549575, 0.23796810219833633, 0.12311570730540798, 0.291222989748139, -0.46589179980005796, -0.5679935337540711, -0.541967302717414, 0.2797199715268191, -0.0462338707795437, 0.3352382038488532, -0.6395453091791992, -0.7116194799285872, -0.6827853559995019, 0.4131897184013285, 0.07125041194386302, 0.47179441094288416, -0.5670171363969451, -0.6493889334859158, -0.6214861349381114, 0.6332084272531783, 0.2946607775328391, 0.7252115985158697, -0.48494480580385074, -0.5584250339723696, -0.5329318548632481, 0, 1, 0, 5, 5, 5]
The last 6 numbers I want to use as part of my test on the first 30 numbers. I want to cycle through the 30 numbers such that when test_case[31] < 3, give me test_case[0], else give me -999. This iterates until test_case[36] < 3, give me test_case[5]. Then I want test_case[31] to go back and be used on test_case[6] and loop again.
After I'm at test_case[30], I want it to stop.
Here's what I have:
def test_inputs(x, comp_size):
counts = x[-comp_size:]
inputs = x[:(len(x)-comp_size+1)]
counts_pos = 0
inputs_pos = 0
while inputs_pos < (len(x)-comp_size+1):
if counts_pos == 6:
counts_pos = 0
if counts[counts_pos] < 3:
x.append(inputs[inputs_pos])
print inputs_pos
print counts_pos
inputs_pos += 1
counts_pos += 1
else:
x.append(-999)
print inputs_pos
print counts_pos
inputs_pos += 1
counts_pos += 1
I'm trying to make a generalized function. In this case, should be able to run:
test_inputs(test_case, 6)
However, this doesn't stop at inputs_pos == 31. I put in print statements, and it looks like it just keeps going.
Is there a simpler way using a filter?
-
Your loop condition depends on len(x) but you're appending one item to x every iteration through the loop, so len(x) keeps increasing.jarmod– jarmod2016年12月11日 22:58:03 +00:00Commented Dec 11, 2016 at 22:58
-
That's it, thank you!!WhitneyChia– WhitneyChia2016年12月11日 22:59:34 +00:00Commented Dec 11, 2016 at 22:59
2 Answers 2
Am I understanding correctly that you want:
from itertools import cycle
def test_inputs(x, comp_size):
return [(input if count<3 else -999) for (input,count)
in zip(x[:-comp_size], cycle(x[-comp_size:]))]
You can restore the in-place modification behaviour by using x.extend instead of return. As the slices are performed before the extend call, it will produce the exact same items. Still, I don't think it's generally a good idea to mix data types in one list like this, when it would be as easy to pass (inputs,counts) tuples.
Comments
The loop doesn't stop because len(x) is evaluated at each iteration. In your cycle you increment count_pos and append a new element to x.