Functional programming in Python: Longest substring

Viewed 66

I am reading and hearing people talking about functional programming and I am trying to wrap my head around it and understand if it is applicable to me. I am a sysadmin (please, talk slowly) who writes lots of Python code.

Unfortunately most examples of FP I find are using esoteric languages and solving complex math problems.

If anyone has a few minutes to spare, would you mind show me how you would solve this using Python + FP, please? It's a much more realistic problem for me.

This is my "regular" approach:

def long(text: str) -> int:
    visited = []
    longest, count = 0, 0
    for i in text:
        if i not in visited:
            count += 1
            if longest < count:
                longest = count
            visited.append(i)
        else:
            count = 1
            visited = [i]
    return longest

And the test case:

@pytest.mark.parametrize(('input', 'output'), [("", 0), ('abc', 3), ('a', 1), ('abcabc', 3),
                        ('abcabcd', 4), ('abcab', 3), ('abcabcdabcdeab', 5), ('aaaa', 1),
                        (string.ascii_lowercase, 26)])
def test_long(input, output):
    x = long.long(input)
    assert x == output
0 Answers
Related