Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to test if a string contains more than N nested function calls?

There is a set of strings that represents a list of nested function calls:

# (string, number of nested calls)
tests = [('f1(p1)', 0), ('f1(f2(p1, p2))', 1), ('f1(p1, f2(p2, f3(f4(p1), p2), p1)', 3)] 

How to write a function to test if a string contains more than N nested function calls?

Only valid functions calls.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The real answer is that you need a full language tokenizer to handle all cases of parsing function calls where ( and ) may be inside strings or tuples and newlines or whitespace may split things in weird ways.

For fun.. parsing just your well-formed examples, count the opening parentheses ( before any closing ) ones.

tests = [('f1(p1)', 0), ('f1(f2(p1, p2))', 1), ('f1(p1, f2(p2, f3(f4(p1), p2), p1)', 3)]

N = 2
for ts,tn in tests:
    for s in ts.split(')'):
        if s.count('(') > N:
            print(ts, 'has more than', N, 'nested funcs')

Outputs the last expression.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading