一、题目
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.11 is read off as "two 1s" or 21.21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Subscribe to see which companies asked this question
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ num = [‘1‘] for i in range(n): num.append(self.say(num[-1])) return num[-2] def say(self, n): lenN = len(n) if lenN == 0: return "" elif lenN == 1: return ‘1‘ + n[0] count = 1 rst = "" for cur in range(1, lenN): if n[cur] == n[cur - 1]: count += 1 if cur == len(n) - 1: rst += str(count) + n[cur] else: rst += str(count) + n[cur - 1] count = 1 if n[-1] != n[-2]: rst += ‘1‘ + n[-1] return rst else: return rst
四、感悟
1.列表包含
1)一般循环
nums = [i for i in range(5)] = [0,1,2,3,4]
square = [n * n for n in nums]
2)加判断
[expression for item1 in iter1 if condition1
for item2 in iter2 if condition2
...
for itemn in itern if conditionn]
等价于:
for item1 in iter1:
if condition1:
for item2 in iter2:
if condition2:
....
实例:
a = [-3, 4 ,5, -10]
b = "abc"
e = [(x, y) for x in a
for y in b
if x > 0]
原文:http://www.cnblogs.com/breada/p/4932655.html