Python - 计算符号变化Python - counting sign changes

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

8 个回复8

#1楼 票数：15 已采纳

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

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

``````8
``````

• 计算变化，而不是组
• 如果第一个元素不是正数，则计算额外的变化。

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

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

#2楼 票数：6

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

last_sign = 1
sign_changes = 0

for x in X:
if x == 0:
sign = -1
else:
sign = x / abs(x)

if sign == -last_sign:
sign_changes = sign_changes + 1
last_sign = sign

print sign_changes
``````

#3楼 票数：1

``````def lolwut((x,c), y):
return (y, c+(x^y))

print reduce( lolwut ,(x > 0 for x in X), (True,0)) # 8
print reduce( lolwut ,(x > 0 for x in X), (False,0)) # 7
``````

#4楼 票数：1

``````x = np.array([-3,2,7,-4,1,-1,1,6,-1,0,-2,1])
positive= x>0
count = np.logical_xor(positive[1:],positive[:-1]).sum()
count += not(positive[0])
print count
``````

#5楼 票数：1

``````def countSignChanges(seq):
# make sure 0's are treated as negative
seq = [-1 if not x else x for x in seq]

# zip with leading 1, so that opening negative value is
# treated as sign change
return sum((a^b)<0 for a,b in zip([1]+seq, seq))

X = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]
print countSignChanges(X)
``````

#6楼 票数：0

``````numbers = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]
# could be replaced by     signs = [x > 0 for x in numbers]
# but this methods gives us nice minus and plus signs
signs = map(lambda x: "+" if x > 0 else "-", numbers)

# zip(…) creates the pairs, each pair that has different signs
count = sum(1 for x,y in zip(signs[:-1], signs[1:]) if x != y)
``````

-> 7

#7楼 票数：0

``````def pairs(iterable):
'iter -> (iter0, iter1), (iter1, iter2), (iter3, iter4), ...'
from itertools import izip, tee
first, second = tee(iterable)
second.next()
return izip(first, second)

def sign_changes(l):
result = 0
if l and l[0]<=0: result += 1
result += sum(1 for a,b in pairs(l) if b*a<=0 and (a!=0 or b!=0))
return result
``````

#8楼 票数：0

``````Input = [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12]

for i in range(len(Input)):
if(Input[i]<1):
Input[i]=0
else:
Input[i]=1

print(Input) #[0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1]

count=0
check=Input[0]
for i in range(len(Input)-1):

if check != Input[i + 1]:
count+=1
check=Input[i+1]

print(count) #9
``````

1回复

3回复

2回复

2回复

4回复

4回复

3回复

2回复