空瓶子-算法


import sys


def drink_soda(n):
    if n == 0:
        exit(0)

    total_drinks = 0
    empty_bottles = n

    while empty_bottles >= 3:
        drinks = empty_bottles // 3
        total_drinks += drinks
        empty_bottles = empty_bottles % 3 + drinks
    if empty_bottles == 2:
        tot...

Read more

列表推导式-初级-Python


当你处理列表并输出结果时,你可以使用列表推导式来实现一行表达式。列表推导式允许你在一行代码中对列表进行转换、筛选或处理。

举个例子,如果你想要将一个列表中的每个元素乘以 2 并输出结果,你可以这样做:

original_list = [1, 2, 3, 4, 5]
result = [x * 2 for x in original_list]
print(result)  # 输出结果为 [2, 4, 6, 8, 10]

在这个例子中,[x * 2 for x in original_list] 就是一个列表推导式,它遍历原始列表中的每个元素,并将每个元素乘以 2,最后生成一个新的列...

Read more

运算符-初级-Python


在 Python 中,双斜杠 // 是整除运算符,它用来执行整数除法并返回一个整数结果。即,它会计算除法操作后的商,并向下取整到最接近的整数。举个例子:

result = 10 // 3
print(result)  # 输出结果为 3

在这个例子中,10 // 3 的结果是 3,因为 3 乘以 3 是最接近但小于 10 的整数。

Read more

切片-初级-Python


在 Python 中,可以使用数组切片(slice)来获取列表、元组或字符串等序列类型的子集。数组切片的语法如下:

sequence[start:stop:step]
  • start:起始索引,表示切片开始的位置(包含该位置)。
  • stop:结束索引,表示切片结束的位置(不包含该位置)。
  • step:步长,表示从起始索引到结束索引的步长大小。

下面是一些示例:

  1. 对列表进行切片:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[2:6])  # 输出 [3, 4, 5, 6]
print(my_list[::2])  # 使用步长...

Read more