Explanation of iteration and recursion methods in python

Source: Internet
Author: User
In one case, recursive operations are required, but the number of recursion times is very large, with more than 10 thousand. The original test code is java without installing jdk or the compiling environment. In one case, recursive operations are required, but the number of recursion times is very large, more than 10 thousand times. Let's not mention the recursion for more than 10 thousand times. The original test code is java. if jdk and the compiling environment are not installed, use python.

Let's take a look at the original java code:

public class UpCount {    private long calc(int depth) {        if (depth == 0) return 1;        long cc = calc(depth - 1);        return cc + (depth % 7) + ((((cc ^ depth) % 4) == 0) ? 1 : 0);     }    public static void main(String[] args) {        UpCount uc = new UpCount();        System.out.println(uc.calc(11589));    }}

Java has never been used, but these lines of code are still not under pressure.

def calc(depth):    if depth == 0:        return 1    cc = long(calc(depth-1))    xor_mod = (cc ^ depth)%4    if xor_mod == 0:        return cc+(depth%7)+1    else:        return cc+(depth%7) number = long(calc(11589))print number

Code sticking up, F5, error

The code of this version is not added with long, because a string of more than a dozen digits can be used directly, so it is suspected that it has something to do with long.

Of course, in fact, it has nothing to do with long. the length of integers supported by python is very long. refer to the code written earlier:

cimal = 7original = 28679718602997181072337614380936720482949array = ""result= ""while original !=0:    remainder = original % cimal    array += str(remainder)    original /= cimallength = len(array)for i in xrange(0,length):    result += array[length-1-i]print result

The code above converts a long string of decimal digits into a 7-digit representation, and can also be converted to any hexadecimal notation. the code is changed to an octal or hexadecimal notation, an oct (), hex () is done. use the moving phase division to solve the problem.

Therefore, we can see that the error is not the size of the number. after all, 11589 is only a small dish for the current computer. what about 2 ^ 16 and 65536?

In fact, it was found that the real cause of the previous recursive error was not mentioned, and it was awkward.

The reason for recursive error is that python only has a limit of about 1000 recursion times by default, but it has to run more than 10000 times. it has been flushed for a long time: RuntimeError: maximum recursion depth exceeded

As a result, I quickly checked and found that I could set the limit for recursion. for details, see the maximum number of recursion times in python. as an extension, you can also view the official website documentation.

In general, in order to prevent benefits and crashes, the python language imposes a limit on the number of times by default. Is it okay if I change this limit?

Import sys

# Set the maximun depth as 20000

Sys. setrecursionlimit (20000)

Insert the code above and change it to 20000. if there is no such restriction, it should be okay, but the result is stunned and nothing is lost.

I did not continue to check it. I asked my friend littlehann and discussed it. I did not go deep into this issue. Instead, we mention the efficiency of recursive operations in practical applications. it is true that recursive operations are rarely used in addition to textbooks.

The original goal was to evaluate the value. I didn't want to go deep into it. I 'd like to use iteration instead. although I'm not very impressed, I can get a for statement.

The code is as follows:

def calc(depth):    tmp = 0    result = 1        for i in xrange(0,depth+1):        cc = result        if (cc ^ i)%4 == 0:            tmp = 1        else:            tmp = 0        result = result + (i)%7 + tmp            return resultfinal = calc(11589)print final

Just a few lines of code. When I thought of the last interview, the interviewer of tx asked me about the algorithm. at that time, I mentioned using recursion to implement an operation. Can I also use iteration?

The time has passed for a long time, and I cannot clearly remember the questions at that time. but today's lesson is: in most cases (the code is rarely written and the estimation value is based on my feelings, recursive efficiency is relatively low, which can be determined by class

Also mentioned. The efficiency of iteration is obviously higher than recursion (the specific concept of iteration is not clearly remembered). at least it is okay to use a loop to calculate hundreds of thousands of times, but even if I changed the recursive limit, I still encountered a strike.

Finally, paste a link to python long vs c long. if you are interested, you can check it out.

The above is a detailed explanation of the iterations and recursion methods in python. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.