danger of recursive functions

前端 未结 4 1375
清酒与你
清酒与你 2021-01-05 05:03

Often people say that it\'s not recommended to use recursive functions in python (recursion depth restrictions, memory consumption, etc)

I took a permutation example

4条回答
  •  离开以前
    2021-01-05 05:29

    Your timings are completely wrong:

    def perms1(str):
      if len(str) <=1:
        yield str
      else:
        for perm in perms1(str[1:]):
            for i in range(len(perm)+1):
                yield perm[:i] + str[0:1] + perm[i:]
    
    def perms2(string):
      perm = [string[0]]
      for e in string[1:]:
        perm_next = []
        for p in perm:
            perm_next.extend(p[:i] + e + p[i:] for i in range(len(p) + 1))
        perm = perm_next
    
      for p in perm:
        yield p
    
    s = "01235678"
    import itertools
    perms3 = itertools.permutations
    

    Now test it with timeit:

    thc:~$ for i in 1 2 3; do echo "perms$i:"; python -m timeit -s "import permtest as p" "list(p.perms$i(p.s))"; done 
    perms1:
    10 loops, best of 3: 23.9 msec per loop
    perms2:
    10 loops, best of 3: 39.1 msec per loop
    perms3:
    100 loops, best of 3: 5.64 msec per loop
    

    As you can see itertools.permutations is by far the fastest, followed by the recursive version.

    But both the pure Python function had no chance to be fast, because they do costly operations such as adding lists ala perm[:i] + str[0:1] + perm[i:]

提交回复
热议问题