Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to F#’s Seq.scan() method in Python?

Is there a function like a F#'s Seq.scan() in Python?

I want to do some cumsum() or cumproduct() kind of things without looping.

like image 877
tk. Avatar asked May 10 '10 19:05

tk.


People also ask

Is F same as C?

The two scales have different zero points and the Celsius degree is bigger than the Fahrenheit. However, there is one point on the Fahrenheit and Celsius scales where the temperatures in degrees are equal. This is -40 °C and -40 °F.

Is K the same as F?

To convert Kelvin into Fahrenheit, the formula is: (K − 273.15) × 9/5 + 32 = °F.


1 Answers

Ignacio's solution is almost right I think, but requires a operator of type ('a -> 'a -> 'a) and doesn't yield the first element.

def scan(f, state, it):
  for x in it:
    state = f(state, x)
    yield state
# test
>>> snoc = lambda xs,x: xs+[x]
>>> list(scan(snoc, [], 'abcd'))
[['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd']]
>>> list(scan(operator.add, 0, [1,2,3]))
[1,3,6]

Specifically, the type of Seq.scan is

('State -> 'T -> 'State) -> 'State -> seq<'T> -> seq<'State>

The default approach in Python is to write a scan with the type

('State -> 'State -> 'State) -> seq<'State> -> seq<'State>

This comes from the way that Python specifies reduce, which has the same type by default.

like image 99
Nathan Shively-Sanders Avatar answered Sep 16 '22 11:09

Nathan Shively-Sanders