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

这篇博客记录了Python新手在Coding Bat上遇到的List2模块中sum13和sum67的解题过程。在sum13问题中,遇到13及其后面一个数字时不计入总和;而在sum67中,遇到6到7之间的数字被忽略。作者通过对比和学习错误答案,理解了如何正确地使用旗标变量解决这类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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 an

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值