以下是第21到30题的代码示例:
num_list = [10, 5, 8, 2, 15, 3]
sorted_list = sorted(num_list)
min_numbers = sorted_list[:2]
print("列表中的最小的两个数为:", min_numbers)
def fibonacci(n):
if n <= 0:
return "请输入一个正整数"
elif n == 1:
return 0
elif n == 2:
return 1
else:
a, b = 0, 1
for _ in range(3, n+1):
a, b = b, a + b
return b
n = int(input("请输入一个正整数:"))
fib_result = fibonacci(n)
print("斐波那契数列的第", n, "项为:", fib_result)
num_list = [1, 2, 3, 4, 3, 2, 5]
unique_list = list(set(num_list))
print("移除重复元素后的列表为:", unique_list)
import re
string = input("请输入一个字符串:")
string = re.sub(r'[^a-zA-Z]', '', string).lower()
if string == string[::-1]:
print("是回文串")
else:
print("不是回文串")
num = int(input("请输入一个整数:"))
if num > 1:
for i in range(2, int(num/2)+1):
if num % i == 0:
print(num, "不是素数")
break
else:
print(num, "是素数")
else:
print(num, "不是素数")
string = input("请输入一个字符串:")
sub_string = input("请输入要查找的子字符串:")
if sub_string in string:
print("子字符串存在于字符串中")
else:
print("子字符串不存在于字符串中")
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
num_list = [10, 5, 8, 2, 15, 3]
prime_numbers = [num for num in num_list if is_prime(num)]
print("列表中的素数为:", prime_numbers)
num_list = [1, 2, 3, 4, 5]
reversed_list = num_list[::-1]
print("反转后的列表为:", reversed_list)
string = input("请输入一个字符串:")
char_count = {}
for char in string:
char_count[char] = char_count.get(char, 0) + 1
print("每个字符出现的次数:")
for char, count in char_count.items():
print(char, ":", count)
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
num1 = int(input("请输入第一个整数:"))
num2 = int(input("请输入第二个整数:"))
gcd_result = gcd(num1, num2)
print(num1, "和", num2, "的最大公约数为:", gcd_result)
这是第21到30题的代码示例。如果你还需要更多的练习题代码,请随时告诉我。