Quantcast
Channel: Count and summation of positive and negative number sequences - Stack Overflow
Viewing all articles
Browse latest Browse all 15

Answer by user5538922 for Count and summation of positive and negative number sequences

$
0
0

The other solutions look okay but you don't really need to use sophisticated language features or library functions for this simple problem.

result, prev = [], Nonefor idx, cur in enumerate(x):    if not prev or (prev > 0) != (cur > 0):        n, summation = 1, cur    else:        n, summation = n + 1, summation + cur    result.append((idx, cur, n, summation))    prev = cur

As you can see, you don't really need sign_indicator list, two for-loops or range function as in the snippet in the question section.

If you want index to start from 1, use enumerate(x, 1) instead of enumerate(x)

To see the result, you can run the following code

for idx, num, length, summation in result:     print(f"{idx:>2d} {num:.3f} {length:>2d} {summation:.3f}")

Viewing all articles
Browse latest Browse all 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>