krahets / hello-algo

《Hello 算法》:动画图解、一键运行的数据结构与算法教程。支持 Python, Java, C++, C, C#, JS, Go, Swift, Rust, Ruby, Kotlin, TS, Dart 代码。简体版和繁体版同步更新,English version ongoing
https://www.hello-algo.com
Other
95.04k stars 12.07k forks source link

Python 数组代码修改 #1294

Closed LRoInT closed 4 months ago

LRoInT commented 4 months ago

原来使用list表示array,建议使用tuple

codes\python\chapter_array_and_linkedlist\array.py:

def random_access(nums: tuple[int]) -> int:
    """随机访问元素"""
    # 在区间 [0, len(nums)-1] 中随机抽取一个数字
    random_index = random.randint(0, len(nums) - 1)
    # 获取并返回随机元素
    random_num = nums[random_index]
    return random_num

# Python 中的 tuple 为 不可变 数组,无法直接修改
def extend(nums: tuple[int], enlarge: int) -> tuple[int]:
    """扩展数组长度"""
    # 初始化一个扩展长度后的数组
    res = [0] * (len(nums) + enlarge)
    # 将原数组中的所有元素复制到新数组
    for i in range(len(nums)):
        res[i] = nums[i]
    # 返回扩展后的新数组
    return res

def insert(nums: tuple[int], num: int, index: int):
    """在数组的索引 index 处插入元素 num"""
    # 把索引 index 以及之后的所有元素向后移动一位
    for i in range(len(nums) - 1, index, -1):
        nums[i] = nums[i - 1]
    # 将 num 赋给 index 处的元素
    nums[index] = num

def remove(nums: tuple[int], index: int):
    """删除索引 index 处的元素"""
    # 把索引 index 之后的所有元素向前移动一位
    for i in range(index, len(nums) - 1):
        nums[i] = nums[i + 1]

def traverse(nums: tuple[int], func=lambda x: print(x,end=' ')):
    """遍历数组"""
    count = 0
    # 通过索引遍历数组
    for i in range(len(nums)):
        count += nums[i]
        func(nums[i])
    # 直接遍历数组元素
    for num in nums:
        count += num
        func(num)
    # 同时遍历数据索引和元素
    for i, num in enumerate(nums):
        count += nums[i]
        count += num
        func((i, num))
    print()

def find(nums: tuple[int], target: int) -> int:
    """在数组中查找指定元素"""
    for i in range(len(nums)):
        if nums[i] == target:
            return i
    return -1
krahets commented 4 months ago

Hi,在 Python 中,tuplelist 都无法完全匹配经典数组的概念。

我更建议将 list 看作数组,因为它更常用,也更符合大家对数组的认识。

另外,由于 tuple 不可变,实际上 insert()remove() 函数都无法生效。