2018.4.17(Python)程序的循环

遍历某个结构形成的循环运行方式

  for <循环变量> in <遍历结构>:

                          <语句块>

-从遍历结构中逐一提取元素,放在循环变量中

-由保留字for和in组成,完整遍历所有元素后结束

-每次循环,所获元素放入循环变量,并执行一次语句块


计数循环(N次)

for  i  in range(N):

        <语句块>


计数循环(特定次)

for  i  in range(N,M,K):               以N为开始不到M ,K为补偿

        <语句块>


文件遍历循环

for  line in fi :

        <语句块>

fi是一个文件标识符,遍历其每行,产生循环



循环控制保留字: break          continue



循环与else

-当循环没有被break语句退出时,执行else语句块

-else语句块可以作为“正常”完成循环的奖励


例子:

for c in "python":

    if c=="t":
     continue
    print(c,end=" ")
else:
    print("正常退出")

输出: p y h o n 正常退出



python算法 循环单词

09-27

我在做一题lintcode上的字符串算法,题目是挺简单的,只是一直timeout,不知道该如何优化,有人帮我看下吗(本人实在是菜)rn这是原网站:http://www.lintcode.com/zh-cn/problem/rotate-words/rnrn我的代码如下:rn# -*- coding: cp936 -*-rnclass Solution:rn """rn @param: A: a stringrn @param: B: a stringrn @return: a booleanrn """rnrn def countRotateWords(self, words):rn # Write your code herern dic = rn result = 0rn flag = Falsern for word in words:rn flag = Falsern lengh = len(word)rn if dic.has_key(lengh):rn for w in dic[lengh]:rn if Solution.compare(word,w):rn flag = Truern else:rn dic[lengh] = list()rn if not flag:rn dic[lengh].append(word)rn result += 1rn rn rn return resultrn rn @staticmethodrn def compare(word1,word2):rn if word1 != word2:rn len1 = len(word1)rn len2 = len(word2)rn if len1 == len2:rn for i in range(1,len1):rn if word1 == Solution.stringMove(word2,i):rn return Truern return Falsern else:rn return Falsern return Truern rn '''此方法更慢rn @staticmethodrn def compare(word1,word2):rn if word1 != word2:rn len1 = len(word1)rn len2 = len(word2)rn if len1 == len2:rn s = word1 + word1rn if s.find(word2) != -1:rn return Truern return Falsern return Truern '''rn @staticmethodrn def stringMove(A, n):rn # write code herern alist = list(A)rn result = []rn lengh = len(alist)rn if lengh <=0 :rn return ''rn for i in range(0,lengh):rn result.append(alist[(i+n)%lengh])rn return ''.join(result)rn rnrnif __name__ == '__main__':rn s = Solution()rn # print s.compare('bbaa','abba')rn print s.countRotateWords(["abba", "bbaa", "baab", "aabb", "abba"])rnrnrnrn

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试