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