栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

[python学习日记]-coding bat难题记录-List 2

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[python学习日记]-coding bat难题记录-List 2

 新手入门,记录一下在新手村遇到的难题。

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

Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.

has22([1, 2, 2]) → True
has22([1, 2, 1, 2]) → False
has22([2, 1, 2]) → False

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 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/892847.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号