新手入门,记录一下在新手村遇到的难题。
List 2 - sum13
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
sum13([1, 2, 2, 1]) → 6
sum13([1, 1]) → 2
sum13([1, 2, 2, 1, 13]) → 6
def sum13(nums):
i = 0
result = 0
while i < len(nums): #用while函数逐个查找nums里面的数字,并且限定了范围
if nums[i] == 13:
i += 1 #如为true,i+1后会跳到第八行,变成i+2,跳过了13后面的数字
else:
result = result + nums[i] #把不等于13的数字相加
i += 1 检查下一个数字
return result
看了sum67的答案后试图改写sum13答案,未果。
List2 - sum67
Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.
sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4
def sum67(nums):
result = 0
flag = True
for i in nums:
if i == 6:
flag = False
if flag:
result += i
if i == 7:
flag = True
return result
答案来自python - CodingBat sum67: why is this solution wrong? - Stack Overflow
一开始我用for...in循环找到6,然后计算(第一个数字~6),找到7再计算(7~最后一个数字),总是出错显示getitem..啥的。看了这个用flag来判断是否把数字相加的答案后恍然大悟。
List2 - has22
|
def has22(nums):
for i in range(len(nums)):
if nums[i:i+2] == [2,2]:
return True
else: #这样写是错误的,会导致只检查第一个数字是否为2,如为False将直接结束循环。
return False
#应该改成:
def has22(nums):
for i in range(len(nums)):
if nums[i:i+2] == [2,2]:
return True
return False


![[python学习日记]-coding bat难题记录-List 2 [python学习日记]-coding bat难题记录-List 2](http://www.mshxw.com/aiimages/31/892847.png)
