Files
2025PY/day11/02-经典练习.py
2025-05-22 16:50:44 +08:00

45 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 练习 1九九乘法表经典嵌套循环
# 题目: 打印标准的九九乘法表。
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}*{i}={i*j}", end='\t')
print()
# 练习 2计算列表中的素数个数
# 题目: 给定一个整数列表,找出其中的素数个数。
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def count_primes(lst):
count = 0
for num in lst:
if is_prime(num):
count += 1
return count
# 练习 3找出字符串中出现次数最多的字符
# 题目: 给定字符串 "aabbbccccdd", 输出出现次数最多的字符和次数(如:'c', 4
def most_common_char(s):
max_count = 0
result = ''
for char in set(s):
count = s.count(char)
if count > max_count:
max_count = count
result = char
return result, max_count
# 练习 4列表去重但保持原顺序
# 题目: 输入 [1, 2, 2, 3, 1, 4],输出 [1, 2, 3, 4]
def dedupe_keep_order(lst):
result = []
for item in lst:
if item not in result:
result.append(item)
return result