跳至主要內容

06-codingbat

AI悦创原创Python 一对一教学uicUIC Information SpacecodingbatPython 一对一教学uicUIC Information Spacecodingbat大约 4 分钟...约 1345 字

1. xyz_there

link: https://codingbat.com/prob/p149391open in new window

String-2open in new window > xyz_there

prevopen in new window | next | chanceopen in new window

Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.

xyz_there('abcxyz')True
xyz_there('abc.xyz')False
xyz_there('xyz.abc')True
def xyz_there(str):
    pass
问题
def xyz_there(str):
    condition = False
    if str[:3] == "xyz":
        condition = True
        return condition
    elif len(str) > 3:
        for i in range(1, len(str) - 2):
            if str[i: i + 3] == "xyz" and str[i - 1] != ".":
                condition = True
            else:
                condition = False
        return condition
    else:
        return condition


r = xyz_there("axyz.zp")
print(r)

问题在于

您的代码逻辑存在一个错误。在循环中,您在每次循环时都更新了 condition 的值,这意味着您的代码只会检查字符串的最后一个“xyz”子字符串。如果这最后一个子字符串满足条件,则函数返回 True,否则返回 False。为了解决这个问题,您需要在找到满足条件的子字符串后立即返回 True,而不是在循环结束后返回结果。

2. sum67

Link: https://codingbat.com/prob/p108886open in new window

List-2open in new window > sum67
prevopen in new window | nextopen in new window | chanceopen in new window

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
Answer
# 定义一个名为 sum67 的函数,接受一个名为 numbers 的列表作为参数
def sum67(numbers):
    # 初始化 total 变量,用于存储和
    total = 0
    # 初始化 ignore 变量,用于记录是否忽略当前数字
    ignore = False

    # 遍历 numbers 列表中的每个数字
    for number in numbers:
        # 如果当前数字是 6
        if number == 6:
            # 设置 ignore 变量为 True,开始忽略数字
            ignore = True
        # 否则,如果当前数字是 7 且 ignore 变量为 True
        elif number == 7 and ignore:
            # 设置 ignore 变量为 False,结束忽略数字
            ignore = False
        # 否则,如果不需要忽略当前数字
        elif not ignore:
            # 将当前数字添加到 total 变量中
            total += number

    # 返回 total 变量的值
    return total

# 测试用例
print(sum67([1, 2, 2]))  # 输出: 5
print(sum67([1, 2, 2, 6, 99, 99, 7]))  # 输出: 5
print(sum67([1, 1, 6, 7, 2]))  # 输出: 4
公众号:AI悦创【二维码】

AI悦创·编程一对一

AI悦创·推出辅导班啦,包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发、Web、Linux」,全部都是一对一教学:一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然,还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线,随时响应!微信:Jiabcdefh

C++ 信息奥赛题解,长期更新!长期招收一对一中小学信息奥赛集训,莆田、厦门地区有机会线下上门,其他地区线上。微信:Jiabcdefh

方法一:QQopen in new window

方法二:微信:Jiabcdefh

上次编辑于:
贡献者: AndersonHJB
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度