Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

list - Python - counting sign changes

I have a list of numbers I am reading left to right. Anytime I encounter a sign change when reading the sequence I want to count it.

X = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1] 
X = [-, +, +, -, +, -, +, +, -, -,-,+]

So, in this list there are 8 sign changes.

When Item [0] (in this case -3) is negative it is considered a sign change. Also, any 0 in the list is considered [-].

Any help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use itertools.groupby to count the groups of positive and non-positive numbers:

>>> x = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1] 

>>> import itertools
>>> len(list(itertools.groupby(x, lambda x: x > 0)))

Result:

8

In your question you state that you want:

  • to count the changes, not the groups
  • to count an extra change if the first element is not positive.

You can do this either by testing the first element directly and adjusting the result:

>>> len(list(itertools.groupby(x, lambda x: x > 0))) - (x[0] > 0)

or by prepending a positive number to the input before doing the grouping then subtracting 1 from the result:

>>> len(list(itertools.groupby(itertools.chain([1], x), lambda x: x > 0))) - 1

Watch out if your input list could by empty - the former solution will raise an exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...