Python
- 练习一
- 练习二
- 练习三
练习一
实现代码:
def merge(list1, list2):
merged_list = []
i = 0
j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1
merged_list += list1[i:]
merged_list += list2[j:]
return merged_list
list1 = input("Enter list1: ").split()
list1 = [int(x) for x in list1]
list2 = input("Enter list2: ").split()
list2 = [int(x) for x in list2]
merged = merge(list1, list2)
print("The merged list is", ' '.join(map(str, merged)))
结果截图:
练习二
实现代码:
def isConsecutiveFour(values):
for i in range(len(values) - 3):
if values[i] == values[i + 1] == values[i + 2] == values[i + 3]:
return True
return False
input_values = input("输入空格分开的整数序列: ").split()
values = [int(x) for x in input_values]
if isConsecutiveFour(values):
print("包含具有相同值的四个连续数字")
else:
print("不包含具有相同值的四个连续数字")
练习三
实现代码:
def countnum():
input_numbers = input("Enter integers between 1 and 100: ").split()
counts = {}
for number in input_numbers:
number = int(number)
if 1 <= number <= 100:
if number in counts:
counts[number] += 1
else:
counts[number] = 1
for number, count in sorted(counts.items()):
if count == 1:
print(f"{number} occurs 1 time")
else:
print(f"{number} occurs {count} times")
countnum()
结果截图: