为什么WHILE在这个python函数中比FOR更有效

时间:2016-11-09 11:01:56

标签: python

SUBJECT :给定一个字符串,找到最长子字符串的长度而不重复字符。 的 CODE

import time
import string
import random

class Solution:


    def getRandomStr(self,length):
        s = ""
        for x in range(0,length):
            s += random.choice(string.ascii_letters+string.digits)
        return s

    # O(n)
    def hasValue(self,s,v,p,r):
        for k in range(p,r+1):
            if s[k] == v:
                return True
        return False

    # O(n^3)
    # if s[j] is found in prestr , 
    def lengthOfLongestSubstringWhile(self,s):

        maxlen = 0
        i = 0
        j = 0
        exitsign = False
        t0 = time.clock()
        while i < len(s):
            j = i+1
            while j < len(s):
                if self.hasValue(s,s[j],i,j-1):
                    maxlen = max(maxlen,j-i)
                    break
                elif j == len(s)-1:
                    maxlen = max(maxlen,j-i+1)
                    exitsign = True
                    break
                j+=1
            if exitsign:
                break
            i+=1
        # print maxlen

    def lengthOfLongestSubstringFor(self,s):
        maxlen = 0
        exitsign = False
        for i in range(0,len(s)):
            for j in range(i+1,len(s)):
                if self.hasValue(s,s[j],i,j-1):
                    maxlen = max(maxlen,j-i)
                    break
                elif j == len(s)-1:
                    maxlen = max(maxlen,j-i+1)
                    exitsign = True
                    break 
            if exitsign:
                break
        # print maxlen


S = Solution()
s = S.getRandomStr(10000)

t0 = time.clock()
S.lengthOfLongestSubstringWhile(s)

t1 = time.clock()
S.lengthOfLongestSubstringFor(s)
t2 = time.clock()

print t1-t0,t2-t1

结果如下:

  

0.187118

     

0.868182

以1.2秒结束

为什么while的功能比使用for的功能更快?

1 个答案:

答案 0 :(得分:2)

首先,range正在生成并丢弃大量数字数组作为&#34; for&#34;中的循环索引。版。比如,10000个阵列每个平均5000个项目。尝试将range替换为xrange(生成器版本),您也不会那么做。