第七次作业

 1.

2.

3.

4.

5.

 if number in occurrences:
            occurrences[number] += 1
        else:
            occurrences[number] = 1

6.

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a
 
def find_gcd(numbers):
    n = len(numbers)
    result = numbers[0]
    for i in range(1, n):
        result = gcd(result, numbers[i])

7.

def shuffle_array(nums):
    random.shuffle(nums)
    return nums

 

 8.

def simulate_bean_machine(ball_count, slot_count):
    slots = [0] * slot_count
    paths = []
    
    for _ in range(ball_count):
        path = ""
        position = 0
        
        for _ in range(slot_count - 1):
            direction = random.choice(["L", "R"])
            path += direction
            
            if direction == "R":
                position += 1
        
        slots[position] += 1
        paths.append(path)
    
    return paths, slots

9. 

def simulate_lockers():
    lockers = [False] * 100
 
    for student in range(1, 101):
        for locker in range(student, 101, student):
            lockers[locker - 1] = not lockers[locker - 1]
 
    open_lockers = [i + 1 for i, locker in enumerate(lockers) if locker]
    return open_lockers

10.

    merged_array = []
    i, j = 0, 0
    len_a, len_b = len(array_a), len(array_b)
 
    while i < len_a and j < len_b:
        if array_a[i] <= array_b[j]:
            merged_array.append(array_a[i])
            i += 1
        else:
            merged_array.append(array_b[j])
            j += 1
 
    while i < len_a:
        merged_array.append(array_a[i])
        i += 1
 
    while j < len_b:
        merged_array.append(array_b[j])
        j += 1

 

11.

def partition_array(nums):
    pivot = nums[0]  # 选择第一个元素作为枢纽
    i = 0  # i指向第一个区间的末尾
    j = 0  # j指向第二个区间的末尾
 
    for k in range(1, len(nums)):
        if nums[k] < pivot:  # 小于枢纽的元素放入第一个区间
            nums[k], nums[i] = nums[i], nums[k]
            i += 1
            j += 1
        elif nums[k] == pivot:  # 等于枢纽的元素放入第二个区间
            nums[k], nums[j] = nums[j], nums[k]
            j += 1

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值