📋 专项习题

第 5 章 · 序列 · 共 100 题 · 分 10 页 · 列表综合练习 · 由易到难

答案默认折叠,点击题目或右侧开关控制显示
展开所有答案
1
编写一个Python程序,从给定数字列表中找出最大的k个数字。
📝 样例输入1:列表[1, 2, 3, 4, 5, 5, 3, 6, 2],k=1
▶ 输出结果1:[6]
📝 样例输入2:列表[1, 2, 3, 4, 5, 5, 3, 6, 2],k=3
▶ 输出结果2:[6, 5, 5]
参考答案
python
def top_k_largest(num_list, k):
    # 降序排序后取前k个
    return sorted(num_list, reverse=True)[:k]

# 测试用例执行
if __name__ == "__main__":
    print(top_k_largest([1, 2, 3, 4, 5, 5, 3, 6, 2], 1))
    print(top_k_largest([1, 2, 3, 4, 5, 5, 3, 6, 2], 3))
2
编写一个Python程序,找出需要追加到列表末尾的数字,使得列表所有元素的总和为0。
📝 样例输入1:[1, 2, 3, 4, 5]
▶ 输出结果1:-15
📝 样例输入2:[-1, -2, -3, -4, 5]
▶ 输出结果2:5
参考答案
python
def get_zero_sum_number(num_list):
    return -sum(num_list)

# 测试用例执行
if __name__ == "__main__":
    print(get_zero_sum_number([1, 2, 3, 4, 5]))
    print(get_zero_sum_number([-1, -2, -3, -4, 5]))
3
编写一个Python程序,接收一个整数,判断该数是否大于4的4次方(256),且该数对34取余的结果等于4。满足条件返回True,否则返回False。
📝 样例输入1:922
▶ 输出结果1:True
📝 样例输入2:914
▶ 输出结果2:False
📝 样例输入3:854
▶ 输出结果3:True
参考答案
python
def check_num_condition(num):
    return num > 4 ** 4 and num % 34 == 4

# 测试用例执行
if __name__ == "__main__":
    print(check_num_condition(922))
    print(check_num_condition(914))
    print(check_num_condition(854))
4
编写一个Python程序,忽略字符串的大小写,找出其中所有不同的字符,返回字符列表。
📝 样例输入1:HELLO
▶ 输出结果1:['h', 'o', 'l', 'e']
📝 样例输入2:HelLo
▶ 输出结果2:['h', 'o', 'l', 'e']
参考答案
python
def distinct_char_ignore_case(input_str):
    # 转小写后去重,转为列表
    return list(set(input_str.lower()))

# 测试用例执行
if __name__ == "__main__":
    print(distinct_char_ignore_case("HELLO"))
    print(distinct_char_ignore_case("HelLo"))
5
编写一个Python程序,用原列表中的元素生成一个严格递增的序列。
📝 样例输入1:[1, 3, 79, 10, 4, 2, 39]
▶ 输出结果1:[1, 2, 3, 4, 10, 39, 79]
📝 样例输入2:[11, 31, 40, 68, 77, 93, 48, 1, 57]
▶ 输出结果2:[1, 11, 31, 40, 48, 57, 68, 77, 93]
参考答案
python
def increasing_sequence_from_list(num_list):
    # 去重后升序排序
    return sorted(list(set(num_list)))

# 测试用例执行
if __name__ == "__main__":
    print(increasing_sequence_from_list([1, 3, 79, 10, 4, 2, 39]))
    print(increasing_sequence_from_list([11, 31, 40, 68, 77, 93, 48, 1, 57]))
6
编写一个Python程序,生成一个非负整数,使其包含指定个数的偶数位数字和奇数位数字。
📝 样例输入1:偶数位个数2,奇数位个数3
▶ 输出结果1:22333
📝 样例输入2:偶数位个数4,奇数位个数7
▶ 输出结果2:22223333333
参考答案
python
def make_num_with_even_odd_digit(even_count, odd_count):
    # 偶数位用2,奇数位用3
    even_part = "2" * even_count
    odd_part = "3" * odd_count
    return int(even_part + odd_part)

# 测试用例执行
if __name__ == "__main__":
    print(make_num_with_even_odd_digit(2, 3))
    print(make_num_with_even_odd_digit(4, 7))
7
编写一个Python程序,判断一个整数列表中,数字19恰好出现2次,且数字5至少出现3次。满足条件返回True,否则返回False。
📝 样例输入1:[19, 19, 15, 5, 3, 5, 5, 2]
▶ 输出结果1:True
📝 样例输入2:[19, 15, 15, 5, 3, 3, 5, 2]
▶ 输出结果2:False
📝 样例输入3:[19, 19, 5, 5, 5, 5, 5]
▶ 输出结果3:True
参考答案
python
def check_nineteen_and_five(num_list):
    return num_list.count(19) == 2 and num_list.count(5) >= 3

# 测试用例执行
if __name__ == "__main__":
    print(check_nineteen_and_five([19, 19, 15, 5, 3, 5, 5, 2]))
    print(check_nineteen_and_five([19, 15, 15, 5, 3, 3, 5, 2]))
    print(check_nineteen_and_five([19, 19, 5, 5, 5, 5, 5]))
8
编写一个Python程序,生成一个由0到n(包含n)的非负整数组成的、空格分隔的字符串。
📝 样例输入1:4
▶ 输出结果1:0 1 2 3 4
📝 样例输入2:15
▶ 输出结果2:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
参考答案
python
def generate_num_string(n):
    return " ".join(str(i) for i in range(n + 1))

# 测试用例执行
if __name__ == "__main__":
    print(generate_num_string(4))
    print(generate_num_string(15))
9
编写一个Python程序,将两个输入的二进制字符串视为二进制数字,计算它们的按位异或结果,以0b开头的二进制格式输出。
📝 样例输入1:['0001', '1011']
▶ 输出结果1:0b1010
📝 样例输入2:['100011101100001', '100101100101110']
▶ 输出结果2:0b110001001111
参考答案
python
def binary_string_xor(bin_str_list):
    # 转换为十进制整数
    num1 = int(bin_str_list[0], 2)
    num2 = int(bin_str_list[1], 2)
    # 异或运算后转回二进制
    return bin(num1 ^ num2)

# 测试用例执行
if __name__ == "__main__":
    print(binary_string_xor(['0001', '1011']))
    print(binary_string_xor(['100011101100001', '100101100101110']))
10
编写一个Python程序,接收一个非空字符串列表,返回每个字符串的长度组成的列表。
📝 样例输入1:['cat', 'car', 'fear', 'center']
▶ 输出结果1:[3, 3, 4, 6]
📝 样例输入2:['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
▶ 输出结果2:[3, 3, 7, 5, 2, 4, 0]
参考答案
python
def get_string_lengths(str_list):
    return [len(s) for s in str_list]

# 测试用例执行
if __name__ == "__main__":
    print(get_string_lengths(['cat', 'car', 'fear', 'center']))
    print(get_string_lengths(['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']))
11
编写一个Python程序,还原压缩后的字符串:压缩规则为3个及以上连续空格压缩为`-`,1-2个连续空格替换为`_`,根据压缩后的字符串还原原始字符串。
📝 样例输入1:Python-Exercises
▶ 输出结果1:Python Exercises
📝 样例输入2:Python_Exercises
▶ 输出结果2:Python Exercises
📝 样例输入3:-Hello,_world!__This_is-so-easy!-
▶ 输出结果3:Hello, world! This is so easy!
参考答案
python
def restore_compressed_string(compressed_str):
    # 先替换-为3个空格,_为1个空格
    restored = compressed_str.replace("-", "   ").replace("_", " ")
    # 去除首尾空格
    return restored.strip()

# 测试用例执行
if __name__ == "__main__":
    print(restore_compressed_string("Python-Exercises"))
    print(restore_compressed_string("Python_Exercises"))
    print(restore_compressed_string("-Hello,_world!__This_is-so-easy!-"))
12
编写一个Python程序,判断给定的三元组列表中,哪些三元组的三个数字之和为0,返回一一对应的布尔值列表。
📝 样例输入1:[[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]]
▶ 输出结果1:[False, True, True, False, True]
📝 样例输入2:[[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]]
▶ 输出结果2:[True, True, False, False, False]
参考答案
python
def check_zero_sum_triples(triple_list):
    return [sum(triple) == 0 for triple in triple_list]

# 测试用例执行
if __name__ == "__main__":
    print(check_zero_sum_triples([[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]]))
    print(check_zero_sum_triples([[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]]))
13
编写一个Python程序,对输入字符串的每个字符进行ASCII码偏移,返回偏移后的字符串。
📝 样例输入1:Ascii character table,shift=1
▶ 输出结果1:@rbhhbgqbsdqsakd
📝 样例输入2:Ascii character table,shift=-1
▶ 输出结果2:Btdjj!dibsbdufs!ubcmf
参考答案
python
def ascii_shift_string(input_str, shift):
    return "".join(chr(ord(char) + shift) for char in input_str)

# 测试用例执行
if __name__ == "__main__":
    print(ascii_shift_string("Ascii character table", 1))
    print(ascii_shift_string("Ascii character table", -1))
14
编写一个Python程序,批量判断给定的字符串是否为回文字符串,返回与输入一一对应的布尔值列表。
📝 样例输入1:['palindrome', 'madamimadam', '', 'foo', 'eyes']
▶ 输出结果1:[False, True, True, False, False]
参考答案
python
def check_palindrome_list(str_list):
    return [s == s[::-1] for s in str_list]

# 测试用例执行
if __name__ == "__main__":
    print(check_palindrome_list(['palindrome', 'madamimadam', '', 'foo', 'eyes']))
15
编写一个Python程序,从给定的字符串序列中,筛选出所有包含指定子串的字符串。
📝 样例输入1:子串ca,字符串序列('cat', 'car', 'fear', 'center')
▶ 输出结果1:['cat', 'car']
📝 样例输入2:子串o,字符串序列('cat', 'dog', 'shatter', 'donut', 'at', 'todo', '')
▶ 输出结果2:['dog', 'donut', 'todo']
参考答案
python
def filter_by_substring(sub_str, str_sequence):
    return [s for s in str_sequence if sub_str in s]

# 测试用例执行
if __name__ == "__main__":
    print(filter_by_substring("ca", ('cat', 'car', 'fear', 'center')))
    print(filter_by_substring("o", ('cat', 'dog', 'shatter', 'donut', 'at', 'todo', '')))
16
编写一个Python程序,找出能使给定数字列表的均方偏差最小的x值(即列表的算术平均值)。
📝 样例输入1:[4, -5, 17, -9, 14, 108, -9]
▶ 输出结果1:17.142857142857142
📝 样例输入2:[12, -2, 14, 3, -15, 10, -45, 3, 30]
▶ 输出结果2:1.1111111111111112
参考答案
python
def min_mean_squared_deviation(num_list):
    if not num_list:
        return 0
    return sum(num_list) / len(num_list)

# 测试用例执行
if __name__ == "__main__":
    print(min_mean_squared_deviation([4, -5, 17, -9, 14, 108, -9]))
    print(min_mean_squared_deviation([12, -2, 14, 3, -15, 10, -45, 3, 30]))
17
编写一个Python程序,判断给定字符串列表中,倒数第二个字符串是否是最后一个字符串的真子串。满足条件返回True,否则返回False。
📝 样例输入1:['a', 'abb', 'sfs', 'oo', 'de', 'sfde']
▶ 输出结果1:True
📝 样例输入2:['a', 'abb', 'sfs', 'oo', 'ee', 'sfde']
▶ 输出结果2:False
📝 样例输入3:['a', 'abb', 'sad', 'ooaaesdfe', 'sfsdfde', 'sfsd', 'sfsdf', 'qwrew']
▶ 输出结果3:False
参考答案
python
def check_last_substring(str_list):
    if len(str_list) < 2:
        return False
    return str_list[-2] in str_list[-1]

# 测试用例执行
if __name__ == "__main__":
    print(check_last_substring(['a', 'abb', 'sfs', 'oo', 'de', 'sfde']))
    print(check_last_substring(['a', 'abb', 'sfs', 'oo', 'ee', 'sfde']))
    print(check_last_substring(['a', 'abb', 'sad', 'ooaaesdfe', 'sfsdfde', 'sfsd', 'sfsdf', 'qwrew']))
18
编写一个Python程序,从给定的字符串序列中,筛选出所有以指定前缀开头的字符串。
📝 样例输入1:前缀ca,字符串序列('cat', 'car', 'fear', 'center')
▶ 输出结果1:['cat', 'car']
📝 样例输入2:前缀do,字符串序列('cat', 'dog', 'shatter', 'donut', 'at', 'todo')
▶ 输出结果2:['dog', 'donut']
参考答案
python
def filter_by_prefix(prefix, str_sequence):
    return [s for s in str_sequence if s.startswith(prefix)]

# 测试用例执行
if __name__ == "__main__":
    print(filter_by_prefix("ca", ('cat', 'car', 'fear', 'center')))
    print(filter_by_prefix("do", ('cat', 'dog', 'shatter', 'donut', 'at', 'todo')))
19
编写一个Python程序,找出四个正偶数,使其和等于给定的整数n。
📝 样例输入1:100
▶ 输出结果1:[94, 2, 2, 2]
📝 样例输入2:1000
▶ 输出结果2:[994, 2, 2, 2]
📝 样例输入3:1234567890
▶ 输出结果3:[1234567884, 2, 2, 2]
参考答案
python
def four_even_sum(n):
    # 保证四个数都是正偶数,最小的三个正偶数为2,2,2
    if n < 8:
        return []
    return [n - 6, 2, 2, 2]

# 测试用例执行
if __name__ == "__main__":
    print(four_even_sum(100))
    print(four_even_sum(1000))
    print(four_even_sum(1234567890))
20
我们要创建n堆石子:第一堆有n个石子;如果n是偶数,所有堆的石子数都必须是偶数;如果n是奇数,所有堆的石子数都必须是奇数;每一堆的石子数必须比前一堆多,且增量尽可能小。编写Python程序,输出每堆石子的数量。
📝 样例输入1:2
▶ 输出结果1:[2, 4]
📝 样例输入2:10
▶ 输出结果2:[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
📝 样例输入3:3
▶ 输出结果3:[3, 5, 7]
参考答案
python
def stone_piles(n):
    # 步长固定为2,保证奇偶性一致,增量最小
    return [n + 2 * i for i in range(n)]

# 测试用例执行
if __name__ == "__main__":
    print(stone_piles(2))
    print(stone_piles(10))
    print(stone_piles(3))
21
编写一个Python程序,找出给定字符串列表中长度最长的字符串。
📝 样例输入1:['cat', 'car', 'fear', 'center']
▶ 输出结果1:center
📝 样例输入2:['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
▶ 输出结果2:shatter
参考答案
python
def get_longest_string(str_list):
    if not str_list:
        return ""
    return max(str_list, key=lambda x: len(x))

# 测试用例执行
if __name__ == "__main__":
    print(get_longest_string(['cat', 'car', 'fear', 'center']))
    print(get_longest_string(['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']))
22
编写一个Python程序,找出给定列表中,所有数值小于指定阈值的元素的下标索引。
📝 样例输入1:列表[0, 12, 45, 3, 4923, 322, 105, 29, 15, 39, 55],阈值100
▶ 输出结果1:[0, 1, 2, 3, 7, 8, 9, 10]
📝 样例输入2:列表[0, 12, 4, 3, 49, 9, 1, 5, 3],阈值10
▶ 输出结果2:[0, 2, 3, 5, 6, 7, 8]
参考答案
python
def get_index_below_threshold(num_list, threshold):
    return [idx for idx, num in enumerate(num_list) if num < threshold]

# 测试用例执行
if __name__ == "__main__":
    print(get_index_below_threshold([0, 12, 45, 3, 4923, 322, 105, 29, 15, 39, 55], 100))
    print(get_index_below_threshold([0, 12, 4, 3, 49, 9, 1, 5, 3], 10))
23
编写一个Python程序,根据字典中字符和对应的出现次数,生成空格分隔的字符串。
📝 样例输入1:{'f': 1, 'o': 2}
▶ 输出结果1:f o o
📝 样例输入2:{'a': 1, 'b': 1, 'c': 1}
▶ 输出结果2:a b c
参考答案
python
def char_count_to_string(count_dict):
    char_list = []
    for char, count in count_dict.items():
        char_list.extend([char] * count)
    return " ".join(char_list)

# 测试用例执行
if __name__ == "__main__":
    print(char_count_to_string({'f': 1, 'o': 2}))
    print(char_count_to_string({'a': 1, 'b': 1, 'c': 1}))
24
编写一个Python程序,从给定的字符串列表中,选出包含唯一字符数量最多的字符串。
📝 样例输入1:['cat', 'catatatatctsa', 'abcdefhijklmnop', '124259239185125', '', 'foo', 'unique']
▶ 输出结果1:abcdefhijklmnop
📝 样例输入2:['Green', 'Red', 'Orange', 'Yellow', '', 'White']
▶ 输出结果2:Orange
参考答案
python
def most_unique_char_string(str_list):
    if not str_list:
        return ""
    # 按唯一字符数量排序,取最大值
    return max(str_list, key=lambda s: len(set(s)))

# 测试用例执行
if __name__ == "__main__":
    print(most_unique_char_string(['cat', 'catatatatctsa', 'abcdefhijklmnop', '124259239185125', '', 'foo', 'unique']))
    print(most_unique_char_string(['Green', 'Red', 'Orange', 'Yellow', '', 'White']))
25
编写一个Python程序,接收一个整数列表,判断列表长度是否为8,且列表的第5个元素(下标4)在列表中至少出现3次。满足条件返回True,否则返回False。
📝 样例输入1:[19, 19, 15, 5, 5, 5, 1, 2]
▶ 输出结果1:True
📝 样例输入2:[19, 15, 5, 7, 5, 5, 2]
▶ 输出结果2:False
📝 样例输入3:[11, 12, 14, 13, 14, 13, 15, 14]
▶ 输出结果3:True
参考答案
python
def check_fifth_element(num_list):
    if len(num_list) != 8:
        return False
    fifth_item = num_list[4]
    return num_list.count(fifth_item) >= 3

# 测试用例执行
if __name__ == "__main__":
    print(check_fifth_element([19, 19, 15, 5, 5, 5, 1, 2]))
    print(check_fifth_element([19, 15, 5, 7, 5, 5, 2]))
    print(check_fifth_element([11, 12, 14, 13, 14, 13, 15, 14]))
26
编写一个Python程序,对每组[已吃数量、还需数量、库存数量],计算总需求量和剩余库存。
📝 样例输入1:[[2, 5, 6], [3, 9, 22]]
▶ 输出结果1:[[7, 1], [12, 13]]
📝 样例输入2:[[2, 3, 18], [4, 9, 2], [2, 5, 7]]
▶ 输出结果2:[[5, 15], [6, 0], [7, 2]]
参考答案
python
def stock_appetite_calc(data_groups):
    result = []
    for eaten, need, stock in data_groups:
        total_appetite = eaten + need
        remaining = stock - total_appetite
        result.append([total_appetite, remaining])
    return result

# 测试用例执行
if __name__ == "__main__":
    print(stock_appetite_calc([[2, 5, 6], [3, 9, 22]]))
    print(stock_appetite_calc([[2, 3, 18], [4, 9, 2], [2, 5, 7]]))
27
编写一个Python程序,将字符串中的逗号和句号都视为小数点,解析出对应的数字,返回其中最大的数值。
📝 样例输入1:['100', '102,1', '101.1']
▶ 输出结果1:102.1
参考答案
python
def get_max_number_with_comma_dot(str_list):
    num_list = []
    for s in str_list:
        # 逗号替换为小数点,转换为浮点数
        num = float(s.replace(",", "."))
        num_list.append(num)
    return max(num_list)

# 测试用例执行
if __name__ == "__main__":
    print(get_max_number_with_comma_dot(['100', '102,1', '101.1']))
28
编写一个Python程序,将数字的十进制位向左循环移动n位,超出的数字补到末尾;如果移位数大于数字的位数,直接反转数字字符串。
📝 样例输入1:n=12345,shift=1
▶ 输出结果1:23451
📝 样例输入2:n=12345,shift=2
▶ 输出结果2:34512
📝 样例输入3:n=12345,shift=6
▶ 输出结果3:54321
参考答案
python
def circular_left_shift(num, shift):
    num_str = str(num)
    digit_len = len(num_str)
    if shift > digit_len:
        return int(num_str[::-1])
    # 循环左移
    shifted_str = num_str[shift:] + num_str[:shift]
    return int(shifted_str)

# 测试用例执行
if __name__ == "__main__":
    print(circular_left_shift(12345, 1))
    print(circular_left_shift(12345, 2))
    print(circular_left_shift(12345, 6))
29
编写一个Python程序,计算给定列表中所有数字的个位数字的乘积。
📝 样例输入1:[12, 23]
▶ 输出结果1:6
📝 样例输入2:[12, 23, 43]
▶ 输出结果2:18
📝 样例输入3:[1002, 2005]
▶ 输出结果3:10
参考答案
python
def product_of_units_digits(num_list):
    product = 1
    for num in num_list:
        # 取个位数字
        unit_digit = abs(num) % 10
        product *= unit_digit
    return product

# 测试用例执行
if __name__ == "__main__":
    print(product_of_units_digits([12, 23]))
    print(product_of_units_digits([12, 23, 43]))
    print(product_of_units_digits([1002, 2005]))
30
编写一个Python程序,比较两个字符串列表,返回总字符数更少的那个列表。
📝 样例输入1:[['this', 'list', 'is', 'narrow'], ['I', 'am', 'shorter but wider']]
▶ 输出结果1:['this', 'list', 'is', 'narrow']
📝 样例输入2:[['Red', 'Black', 'Pink'], ['Green', 'Red', 'White']]
▶ 输出结果2:['Red', 'Black', 'Pink']
参考答案
python
def fewer_total_chars_list(list_group):
    list1, list2 = list_group
    # 计算每个列表的总字符数
    total1 = sum(len(s) for s in list1)
    total2 = sum(len(s) for s in list2)
    return list1 if total1 < total2 else list2

# 测试用例执行
if __name__ == "__main__":
    print(fewer_total_chars_list([['this', 'list', 'is', 'narrow'], ['I', 'am', 'shorter but wider']]))
    print(fewer_total_chars_list([['Red', 'Black', 'Pink'], ['Green', 'Red', 'White']]))
31
编写一个Python程序,从给定单词列表中找出长度为偶数的单词,并按单词长度升序排序。
📝 样例输入1:['Red', 'Black', 'White', 'Green', 'Pink', 'Orange']
▶ 输出结果1:['Pink', 'Orange']
📝 样例输入2:['The', 'worm', 'ate', 'a', 'bird', 'imagine', 'that', '!', 'Absurd', '!!']
▶ 输出结果2:['!!', 'bird', 'that', 'worm', 'Absurd']
参考答案
python
def sort_even_length_words(word_list):
    # 筛选偶数长度的单词
    even_words = [word for word in word_list if len(word) % 2 == 0]
    # 按长度升序排序
    return sorted(even_words, key=lambda x: len(x))

# 测试用例执行
if __name__ == "__main__":
    print(sort_even_length_words(['Red', 'Black', 'White', 'Green', 'Pink', 'Orange']))
    print(sort_even_length_words(['The', 'worm', 'ate', 'a', 'bird', 'imagine', 'that', '!', 'Absurd', '!!']))
32
编写一个Python程序,计算a到b(不包含b)之间所有整数的平均值,四舍五入到最近的整数,以二进制格式返回结果;如果区间无数字,返回-1。
📝 样例输入1:a=4,b=7
▶ 输出结果1:0b101
📝 样例输入2:a=11,b=19
▶ 输出结果2:0b1110
参考答案
python
def range_average_binary(a, b):
    if b <= a:
        return -1
    num_range = range(a, b)
    average = sum(num_range) / len(num_range)
    rounded_avg = round(average)
    return bin(rounded_avg)

# 测试用例执行
if __name__ == "__main__":
    print(range_average_binary(4, 7))
    print(range_average_binary(11, 19))
33
编写一个Python程序,将列表中的每个浮点数向上取整,计算取整后整数的平方,并返回平方值的累加和列表。
📝 样例输入1:[2.6, 3.5, 6.7, 2.3, 5.6]
▶ 输出结果1:[9, 25, 74, 83, 119]
参考答案
python
import math
def ceil_square_running_total(num_list):
    running_total = 0
    result = []
    for num in num_list:
        ceil_num = math.ceil(num)
        running_total += ceil_num ** 2
        result.append(running_total)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(ceil_square_running_total([2.6, 3.5, 6.7, 2.3, 5.6]))
34
编写一个Python程序,按照数字各位数之和的大小,对列表中的数字进行升序排序。
📝 样例输入1:[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
▶ 输出结果1:[10, 11, 20, 12, 13, 14, 15, 16, 17, 18, 19]
📝 样例输入2:[23, 2, 9, 34, 8, 9, 10, 74]
▶ 输出结果2:[10, 2, 23, 34, 8, 9, 9, 74]
参考答案
python
def sort_by_digit_sum(num_list):
    # 定义计算数字各位和的函数
    def digit_sum(num):
        return sum(int(char) for char in str(abs(num)))
    # 按各位和升序排序
    return sorted(num_list, key=digit_sum)

# 测试用例执行
if __name__ == "__main__":
    print(sort_by_digit_sum([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]))
    print(sort_by_digit_sum([23, 2, 9, 34, 8, 9, 10, 74]))
35
编写一个Python程序,找出列表中第一个破坏递增顺序的两个元素的下标;如果列表是严格递增的,返回空列表。
📝 样例输入1:[1, 2, 3, 0, 4, 5, 6]
▶ 输出结果1:[2, 3]
📝 样例输入2:[1, 2, 3, 4, 5, 6]
▶ 输出结果2:[]
📝 样例输入3:[1, 2, 3, 4, 6, 5, 7]
▶ 输出结果3:[4, 5]
参考答案
python
def first_non_increasing_indices(num_list):
    for i in range(1, len(num_list)):
        if num_list[i] < num_list[i-1]:
            return [i-1, i]
    return []

# 测试用例执行
if __name__ == "__main__":
    print(first_non_increasing_indices([1, 2, 3, 0, 4, 5, 6]))
    print(first_non_increasing_indices([1, 2, 3, 4, 5, 6]))
    print(first_non_increasing_indices([1, 2, 3, 4, 6, 5, 7]))
36
编写一个Python程序,计算列表中位于奇数下标位置的偶数元素的总和。
📝 样例输入1:[1, 2, 3, 4, 5, 6, 7]
▶ 输出结果1:12
📝 样例输入2:[1, 2, 8, 3, 9, 4]
▶ 输出结果2:6
参考答案
python
def sum_even_at_odd_index(num_list):
    total = 0
    for idx, num in enumerate(num_list):
        if idx % 2 == 1 and num % 2 == 0:
            total += num
    return total

# 测试用例执行
if __name__ == "__main__":
    print(sum_even_at_odd_index([1, 2, 3, 4, 5, 6, 7]))
    print(sum_even_at_odd_index([1, 2, 8, 3, 9, 4]))
37
编写一个Python程序,判断字符串是否为「快乐字符串」(每三个连续字符都不相同);如果不是,返回首次出现连续三个相同字符的后两个下标;如果是,返回None。
📝 样例输入1:Python
▶ 输出结果1:None
📝 样例输入2:Unhappy
▶ 输出结果2:[4, 5]
📝 样例输入3:Street
▶ 输出结果3:[3, 4]
参考答案
python
def unhappy_string_indices(input_str):
    for i in range(len(input_str) - 2):
        if input_str[i] == input_str[i+1] == input_str[i+2]:
            return [i+1, i+2]
    return None

# 测试用例执行
if __name__ == "__main__":
    print(unhappy_string_indices("Python"))
    print(unhappy_string_indices("Unhappy"))
    print(unhappy_string_indices("Street"))
38
编写一个Python程序,对输入字符串按单词拆分,每个单词内部的字符按ASCII码升序重排,再拼接成新的字符串。
📝 样例输入1:Ascii character table
▶ 输出结果1:Aciis aaccehrrt abelt
📝 样例输入2:maltos won
▶ 输出结果2:almost now
参考答案
python
def sort_char_by_ascii(input_str):
    words = input_str.split()
    sorted_words = []
    for word in words:
        # 单词内字符按ASCII排序
        sorted_char = sorted(word)
        sorted_words.append("".join(sorted_char))
    return " ".join(sorted_words)

# 测试用例执行
if __name__ == "__main__":
    print(sort_char_by_ascii("Ascii character table"))
    print(sort_char_by_ascii("maltos won"))
39
编写一个Python程序,在数字列表的每一对相邻元素之间,插入指定的分隔数字,返回新的列表。
📝 样例输入1:列表[12, -7, 3, -89],分隔符6
▶ 输出结果1:[12, 6, -7, 6, 3, 6, -89]
📝 样例输入2:列表[1, 2, 3, 4, 5, 6],分隔符9
▶ 输出结果2:[1, 9, 2, 9, 3, 9, 4, 9, 5, 9, 6]
参考答案
python
def insert_separator_between(num_list, separator):
    result = []
    for i in range(len(num_list)):
        result.append(num_list[i])
        # 不是最后一个元素,就插入分隔符
        if i != len(num_list) - 1:
            result.append(separator)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(insert_separator_between([12, -7, 3, -89], 6))
    print(insert_separator_between([1, 2, 3, 4, 5, 6], 9))
40
编写一个Python程序,找出列表中数值发生下降的位置的索引(即当前元素小于前一个元素的下标)。
📝 样例输入1:[0, -1, 3, 8, 5, 9, 8, 14, 2, 4, 3, -10, 10, 17, 41, 22, -4, -4, -15, 0]
▶ 输出结果1:[1, 4, 6, 8, 10, 11, 15, 16, 18]
📝 样例输入2:[6, 5, 4, 3, 2, 1]
▶ 输出结果2:[1, 2, 3, 4, 5]
参考答案
python
def get_drop_indices(num_list):
    drop_idx = []
    for i in range(1, len(num_list)):
        if num_list[i] < num_list[i-1]:
            drop_idx.append(i)
    return drop_idx

# 测试用例执行
if __name__ == "__main__":
    print(get_drop_indices([0, -1, 3, 8, 5, 9, 8, 14, 2, 4, 3, -10, 10, 17, 41, 22, -4, -4, -15, 0]))
    print(get_drop_indices([6, 5, 4, 3, 2, 1]))
41
编写一个Python程序,生成一个新列表,新列表的第i个元素是输入列表前i个元素中的最大值。
📝 样例输入1:[0, -1, 3, 8, 5, 9, 8, 14, 2, 4, 3, -10, 10, 17, 41, 22, -4, -4, -15, 0]
▶ 输出结果1:[0, 0, 3, 8, 8, 9, 9, 14, 14, 14, 14, 14, 14, 17, 41, 41, 41, 41, 41, 41]
📝 样例输入2:[6, 5, 4, 3, 2, 1]
▶ 输出结果2:[6, 6, 6, 6, 6, 6]
参考答案
python
def running_max_list(num_list):
    if not num_list:
        return []
    result = []
    current_max = num_list[0]
    for num in num_list:
        current_max = max(current_max, num)
        result.append(current_max)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(running_max_list([0, -1, 3, 8, 5, 9, 8, 14, 2, 4, 3, -10, 10, 17, 41, 22, -4, -4, -15, 0]))
    print(running_max_list([6, 5, 4, 3, 2, 1]))
42
编写一个Python程序,给定三角形的三条边长,返回该三角形在直角坐标系中的一组坐标。
📝 样例输入1:[3, 4, 5]
▶ 输出结果1:[[0.0, 0.0], [3, 0.0], [3.0, 4.0]]
📝 样例输入2:[5, 6, 7]
▶ 输出结果2:[[0.0, 0.0], [5, 0.0], [3.8, 5.878775382679628]]
参考答案
python
import math
def triangle_coordinates(sides):
    a, b, c = sorted(sides)
    # 直角坐标系简化计算:第一个点在原点,第二个点在x轴
    x1, y1 = 0.0, 0.0
    x2, y2 = a, 0.0
    # 用余弦定理计算第三个点坐标
    cos_angle = (a**2 + b**2 - c**2) / (2 * a * b)
    sin_angle = math.sqrt(1 - cos_angle**2)
    x3 = b * cos_angle
    y3 = b * sin_angle
    return [[x1, y1], [x2, y2], [x3, y3]]

# 测试用例执行
if __name__ == "__main__":
    print(triangle_coordinates([3, 4, 5]))
    print(triangle_coordinates([5, 6, 7]))
43
编写一个Python程序,计算列表前k个元素中,位数大于等于2的数字之和。
📝 样例输入1:列表[4, 5, 17, 9, 14, 108, -9, 12, 76],k=4
▶ 输出结果1:0
📝 样例输入2:列表[4, 5, 17, 9, 14, 108, -9, 12, 76],k=6
▶ 输出结果2:108
参考答案
python
def sum_two_digit_in_first_k(num_list, k):
    # 截取前k个元素
    check_part = num_list[:k]
    total = 0
    for num in check_part:
        if abs(num) >= 10:
            total += num
    return total

# 测试用例执行
if __name__ == "__main__":
    print(sum_two_digit_in_first_k([4, 5, 17, 9, 14, 108, -9, 12, 76], 4))
    print(sum_two_digit_in_first_k([4, 5, 17, 9, 14, 108, -9, 12, 76], 6))
44
编写一个Python程序,计算给定字符串中所有大写字母的ASCII码值之和。
📝 样例输入1:PytHon ExerciSEs
▶ 输出结果1:373
📝 样例输入2:JavaScript
▶ 输出结果2:157
参考答案
python
def sum_uppercase_ascii(input_str):
    total = 0
    for char in input_str:
        if char.isupper():
            total += ord(char)
    return total

# 测试用例执行
if __name__ == "__main__":
    print(sum_uppercase_ascii("PytHon ExerciSEs"))
    print(sum_uppercase_ascii("JavaScript"))
45
编写一个Python程序,找出给定字符串中,位于偶数下标位置的大写元音字母(A、E、I、O、U,不含Y)的下标。
📝 样例输入1:w3rEsOUrcE
▶ 输出结果1:[6]
📝 样例输入2:AEIOUYW
▶ 输出结果2:[0, 2, 4]
参考答案
python
def uppercase_vowel_even_index(input_str):
    vowels = {"A", "E", "I", "O", "U"}
    result = []
    for idx, char in enumerate(input_str):
        if idx % 2 == 0 and char in vowels:
            result.append(idx)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(uppercase_vowel_even_index("w3rEsOUrcE"))
    print(uppercase_vowel_even_index("AEIOUYW"))
46
编写一个Python程序,找出两个数m和n之间(包含m和n)的最大偶数。
📝 样例输入1:m=12,n=51
▶ 输出结果1:50
📝 样例输入2:m=1,n=79
▶ 输出结果2:78
📝 样例输入3:m=100,n=200
▶ 输出结果3:200
参考答案
python
def max_even_in_range(m, n):
    # 确保m <= n
    start, end = sorted([m, n])
    # 从后往前找第一个偶数
    for num in range(end, start - 1, -1):
        if num % 2 == 0:
            return num
    return None

# 测试用例执行
if __name__ == "__main__":
    print(max_even_in_range(12, 51))
    print(max_even_in_range(1, 79))
    print(max_even_in_range(100, 200))
47
编写一个Python程序,对整数列表进行去重,同时保留元素在原列表中的出现顺序。
📝 样例输入1:[1, 3, 4, 10, 4, 1, 43]
▶ 输出结果1:[1, 3, 4, 10, 43]
📝 样例输入2:[10, 11, 13, 23, 11, 25, 23, 76, 99]
▶ 输出结果2:[10, 11, 13, 23, 25, 76, 99]
参考答案
python
def deduplicate_preserve_order(num_list):
    seen = set()
    result = []
    for num in num_list:
        if num not in seen:
            seen.add(num)
            result.append(num)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(deduplicate_preserve_order([1, 3, 4, 10, 4, 1, 43]))
    print(deduplicate_preserve_order([10, 11, 13, 23, 11, 25, 23, 76, 99]))
48
编写一个Python程序,找出列表中两个和为0的数字的下标索引。
📝 样例输入1:[1, -4, 6, 7, 4]
▶ 输出结果1:[4, 1]
📝 样例输入2:[1232, -20352, 12547, 12440, 741, 341, 525, 20352, 91, 20]
▶ 输出结果2:[1, 7]
参考答案
python
def zero_sum_pair_indices(num_list):
    # 用字典存储数值和下标,提升效率
    num_index = {}
    for idx, num in enumerate(num_list):
        if -num in num_index:
            return [idx, num_index[-num]]
        num_index[num] = idx
    return []

# 测试用例执行
if __name__ == "__main__":
    print(zero_sum_pair_indices([1, -4, 6, 7, 4]))
    print(zero_sum_pair_indices([1232, -20352, 12547, 12440, 741, 341, 525, 20352, 91, 20]))
49
编写一个Python程序,接收由英文数字单词组成的字符串,按数字的数值大小对单词进行升序排序,输出排序后的字符串。
📝 样例输入1:six one four one two three
▶ 输出结果1:one two three four six
📝 样例输入2:nine eight seven six five four three two one
▶ 输出结果2:one two three four five six seven eight nine
参考答案
python
def sort_number_words(input_str):
    # 英文数字单词和数值的映射
    num_map = {
        "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4,
        "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9
    }
    words = input_str.split()
    # 按数值排序
    sorted_words = sorted(words, key=lambda w: num_map.get(w, 0))
    return " ".join(sorted_words)

# 测试用例执行
if __name__ == "__main__":
    print(sort_number_words("six one four one two three"))
    print(sort_number_words("nine eight seven six five four three two one"))
50
编写一个Python程序,找出小于等于n的所有偶数回文数。
📝 样例输入1:50
▶ 输出结果1:[0, 2, 4, 6, 8, 22, 44]
📝 样例输入2:100
▶ 输出结果2:[0, 2, 4, 6, 8, 22, 44, 66, 88]
参考答案
python
def find_even_palindromes(n):
    result = []
    # 遍历所有小于等于n的偶数
    for num in range(0, n + 1, 2):
        num_str = str(num)
        # 判断是否为回文
        if num_str == num_str[::-1]:
            result.append(num)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(find_even_palindromes(50))
    print(find_even_palindromes(100))
51
编写一个Python程序,校验给定整数列表,是否对于每一个下标i,前i个整数的和等于i。全部满足返回True,否则返回False。
📝 样例输入1:[0, 1, 2, 3, 4, 5]
▶ 输出结果1:False
📝 样例输入2:[1, 1, 1, 1, 1, 1]
▶ 输出结果2:True
📝 样例输入3:[2, 2, 2, 2, 2]
▶ 输出结果3:False
参考答案
python
def check_sum_equal_index(num_list):
    total = 0
    for idx, num in enumerate(num_list):
        total += num
        if total != idx:
            return False
    return True

# 测试用例执行
if __name__ == "__main__":
    print(check_sum_equal_index([0, 1, 2, 3, 4, 5]))
    print(check_sum_equal_index([1, 1, 1, 1, 1, 1]))
    print(check_sum_equal_index([2, 2, 2, 2, 2]))
52
编写一个Python程序,检查给定列表中每个字符串的最后一个字符是否为孤立字母(即最后一个字符前后都被空格包裹),返回一一对应的布尔值列表。
📝 样例输入1:['cat', 'car', 'fear', 'center']
▶ 输出结果1:[False, False, False, False]
📝 样例输入2:['ca t', 'car', 'fea r', 'cente r']
▶ 输出结果2:[True, False, True, True]
参考答案
python
def check_isolated_last_char(str_list):
    result = []
    for s in str_list:
        if len(s) < 3:
            result.append(False)
            continue
        # 最后一个字符是字母,且倒数第二个是空格,倒数第三个也是空格
        is_isolated = s[-1].isalpha() and s[-2] == " " and s[-3] == " "
        result.append(is_isolated)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(check_isolated_last_char(['cat', 'car', 'fear', 'center']))
    print(check_isolated_last_char(['ca t', 'car', 'fea r', 'cente r']))
53
编写一个Python程序,对数组进行排序:如果数组第一个元素加最后一个元素的和是奇数,按升序排序;如果和是偶数,按降序排序。
📝 样例输入1:[3, 7, 4]
▶ 输出结果1:[3, 4, 7]
📝 样例输入2:[2, 7, 4]
▶ 输出结果2:[7, 4, 2]
📝 样例输入3:[1, 5, 6, 7, 4, 2, 9]
▶ 输出结果3:[9, 7, 6, 5, 4, 2, 1]
参考答案
python
def reorder_by_edge_sum(num_list):
    if not num_list:
        return []
    edge_sum = num_list[0] + num_list[-1]
    if edge_sum % 2 == 1:
        return sorted(num_list)
    else:
        return sorted(num_list, reverse=True)

# 测试用例执行
if __name__ == "__main__":
    print(reorder_by_edge_sum([3, 7, 4]))
    print(reorder_by_edge_sum([2, 7, 4]))
    print(reorder_by_edge_sum([1, 5, 6, 7, 4, 2, 9]))
54
编写一个Python程序,用输入的字符串生成一个指定长度的回文字符串。
📝 样例输入1:字符串madam,长度7
▶ 输出结果1:madaadam
📝 样例输入2:字符串madam,长度6
▶ 输出结果2:maddam
📝 样例输入3:字符串madam,长度2
▶ 输出结果3:mm
参考答案
python
def generate_palindrome_by_length(input_str, length):
    if length <= 0:
        return ""
    # 取前半部分
    half_length = (length + 1) // 2
    half = input_str[:half_length].ljust(half_length, input_str[0])
    # 生成回文
    if length % 2 == 0:
        return half + half[::-1]
    else:
        return half + half[:-1][::-1]

# 测试用例执行
if __name__ == "__main__":
    print(generate_palindrome_by_length("madam", 7))
    print(generate_palindrome_by_length("madam", 6))
    print(generate_palindrome_by_length("madam", 2))
55
编写一个Python程序,对列表中的字符串进行处理:如果字符串仅包含字母,翻转所有字母的大小写;如果字符串不包含字母,直接反转整个字符串。
📝 样例输入1:['cat', '124259239185125', '!@#']
▶ 输出结果1:['CAT', '521581932952421', '#@!']
📝 样例输入2:['Green', 'Red', '']
▶ 输出结果2:['gREEN', 'rED', '']
参考答案
python
def swap_case_or_reverse(str_list):
    result = []
    for s in str_list:
        if s.isalpha():
            result.append(s.swapcase())
        else:
            result.append(s[::-1])
    return result

# 测试用例执行
if __name__ == "__main__":
    print(swap_case_or_reverse(['cat', '124259239185125', '!@#']))
    print(swap_case_or_reverse(['Green', 'Red', '']))
56
编写一个Python程序,找出与输入字符串最接近的回文字符串。
📝 样例输入1:cat
▶ 输出结果1:cac
📝 样例输入2:madan
▶ 输出结果2:madam
📝 样例输入3:abc
▶ 输出结果3:aba
参考答案
python
def closest_palindrome(input_str):
    n = len(input_str)
    if n == 1:
        return input_str
    # 取前半部分生成回文
    half = input_str[:(n + 1) // 2]
    if n % 2 == 0:
        palindrome = half + half[::-1]
    else:
        palindrome = half + half[:-1][::-1]
    return palindrome

# 测试用例执行
if __name__ == "__main__":
    print(closest_palindrome("cat"))
    print(closest_palindrome("madan"))
    print(closest_palindrome("abc"))
57
编写一个Python程序,生成前n项斐波那契数列。
📝 样例输入1:10
▶ 输出结果1:[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
📝 样例输入2:15
▶ 输出结果2:[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
参考答案
python
def fibonacci_sequence(n):
    if n <= 0:
        return []
    fib = [1, 1]
    if n == 1:
        return [1]
    for i in range(2, n):
        fib.append(fib[i-1] + fib[i-2])
    return fib

# 测试用例执行
if __name__ == "__main__":
    print(fibonacci_sequence(10))
    print(fibonacci_sequence(15))
58
编写一个Python程序,判断一个整数列表是否满足:恰好包含4种不同的数值,且列表前20个元素中,没有连续重复的整数。满足条件返回True,否则返回False。
📝 样例输入1:[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
▶ 输出结果1:True
📝 样例输入2:[1, 2, 3, 3, 1, 2, 3, 3, 1, 2, 3, 3, 1, 2, 3, 3]
▶ 输出结果2:False
📝 样例输入3:[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
▶ 输出结果3:False
参考答案
python
def check_four_unique_no_consecutive(num_list):
    # 校验恰好4种不同值
    if len(set(num_list)) != 4:
        return False
    # 截取前20个元素,校验无连续重复
    check_part = num_list[:20]
    for i in range(1, len(check_part)):
        if check_part[i] == check_part[i-1]:
            return False
    return True

# 测试用例执行
if __name__ == "__main__":
    print(check_four_unique_no_consecutive([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]))
    print(check_four_unique_no_consecutive([1, 2, 3, 3, 1, 2, 3, 3, 1, 2, 3, 3, 1, 2, 3, 3]))
    print(check_four_unique_no_consecutive([1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]))
59
编写一个Python程序,对给定列表中的数值进行缩放和平移,使其数值范围覆盖[0, 1]区间。
📝 样例输入1:[18.5, 17.0, 18.0, 19.0, 18.0]
▶ 输出结果1:[0.75, 0.0, 0.5, 1.0, 0.5]
📝 样例输入2:[13.0, 17.0, 17.0, 15.5, 2.94]
▶ 输出结果2:[0.7155049786628734, 1.0, 1.0, 0.8933143669985776, 0.0]
参考答案
python
def rescale_to_01(num_list):
    min_val = min(num_list)
    max_val = max(num_list)
    # 最大值和最小值相等时,全部返回0.0
    if max_val == min_val:
        return [0.0 for _ in num_list]
    # 归一化公式:(x - min) / (max - min)
    return [(x - min_val) / (max_val - min_val) for x in num_list]

# 测试用例执行
if __name__ == "__main__":
    print(rescale_to_01([18.5, 17.0, 18.0, 19.0, 18.0]))
    print(rescale_to_01([13.0, 17.0, 17.0, 15.5, 2.94]))
60
编写一个Python程序,找出整数指数x,使得a的x次方等于n。
📝 样例输入1:a=2,n=1024
▶ 输出结果1:10
📝 样例输入2:a=3,n=81
▶ 输出结果2:4
参考答案
python
def find_integer_exponent(a, n):
    if a == 1:
        return 1 if n == 1 else None
    exponent = 0
    current = 1
    while current < n:
        current *= a
        exponent += 1
    return exponent if current == n else None

# 测试用例执行
if __name__ == "__main__":
    print(find_integer_exponent(2, 1024))
    print(find_integer_exponent(3, 81))
61
编写一个Python程序,计算h指数:最大的正整数h,使得h在序列中至少出现了h次;如果没有这样的正整数,返回-1。
📝 样例输入1:[1, 2, 2, 3, 3, 4, 4, 4, 4]
▶ 输出结果1:4
📝 样例输入2:[1, 2, 2, 3, 4, 5, 6]
▶ 输出结果2:2
参考答案
python
def calculate_h_index(num_list):
    from collections import Counter
    count_map = Counter(num_list)
    h = -1
    # 从大到小遍历可能的h值
    for candidate in sorted(count_map.keys(), reverse=True):
        if candidate <= 0:
            continue
        if count_map[candidate] >= candidate and candidate > h:
            h = candidate
    return h

# 测试用例执行
if __name__ == "__main__":
    print(calculate_h_index([1, 2, 2, 3, 3, 4, 4, 4, 4]))
    print(calculate_h_index([1, 2, 2, 3, 4, 5, 6]))
62
编写一个Python程序,校验一个包含100个0-999之间整数的列表,是否所有相邻元素之间的差值都为10。满足条件返回True,否则返回False。
📝 样例输入1:[0,10,20,...,990](步长10的100个元素)
▶ 输出结果1:True
📝 样例输入2:[0,20,40,...,980](步长20的元素)
▶ 输出结果2:False
参考答案
python
def check_diff_ten(num_list):
    # 校验列表长度为100,且所有元素在0-999之间
    if len(num_list) != 100 or not all(0 <= x <= 999 for x in num_list):
        return False
    # 校验相邻元素差值为10
    for i in range(1, len(num_list)):
        if abs(num_list[i] - num_list[i-1]) != 10:
            return False
    return True

# 测试用例执行
if __name__ == "__main__":
    # 生成符合条件的测试列表
    test1 = [i * 10 for i in range(100)]
    test2 = [i * 20 for i in range(50)]
    print(check_diff_ten(test1))
    print(check_diff_ten(test2))
63
编写一个Python程序,找出输入字符串中包含「辅音+元音+辅音」结构的子串。
📝 样例输入1:Hello
▶ 输出结果1:Hel
📝 样例输入2:Sandwhich
▶ 输出结果2:San
📝 样例输入3:Python
▶ 输出结果3:hon
参考答案
python
def find_cvc_substring(input_str):
    vowels = {"a", "e", "i", "o", "u"}
    for i in range(len(input_str) - 2):
        char1 = input_str[i].lower()
        char2 = input_str[i+1].lower()
        char3 = input_str[i+2].lower()
        if char1 not in vowels and char2 in vowels and char3 not in vowels:
            return input_str[i:i+3]
    return ""

# 测试用例执行
if __name__ == "__main__":
    print(find_cvc_substring("Hello"))
    print(find_cvc_substring("Sandwhich"))
    print(find_cvc_substring("Python"))
64
编写一个Python程序,找出数组中最小的偶数数值及其下标索引;如果有多个相同最小值,返回下标最小的;如果没有偶数,返回空列表。
📝 样例输入1:[1, 9, 4, 6, 10, 11, 14, 8]
▶ 输出结果1:[4, 2]
📝 样例输入2:[1, 7, 4, 4, 9, 2]
▶ 输出结果2:[2, 5]
📝 样例输入3:[1, 7, 7, 5, 9]
▶ 输出结果3:[]
参考答案
python
def min_even_with_index(num_list):
    # 筛选偶数及其下标
    even_list = [(num, idx) for idx, num in enumerate(num_list) if num % 2 == 0]
    if not even_list:
        return []
    # 按数值升序,再按下标升序排序
    even_list.sort(key=lambda x: (x[0], x[1]))
    min_num, min_idx = even_list[0]
    return [min_num, min_idx]

# 测试用例执行
if __name__ == "__main__":
    print(min_even_with_index([1, 9, 4, 6, 10, 11, 14, 8]))
    print(min_even_with_index([1, 7, 4, 4, 9, 2]))
    print(min_even_with_index([1, 7, 7, 5, 9]))
65
编写一个Python程序,处理输入字符串:如果字符串包含空格,按空格拆分;如果没有空格但有逗号,按逗号拆分;如果既无空格也无逗号,返回字符串中奇数下标(a下标为0,b为1,以此类推)的小写字母列表。
📝 样例输入1:a b c d
▶ 输出结果1:['a', 'b', 'c', 'd']
📝 样例输入2:a,b,c,d
▶ 输出结果2:['a', 'b', 'c', 'd']
📝 样例输入3:abcd
▶ 输出结果3:['b', 'd']
参考答案
python
def special_string_split(input_str):
    if " " in input_str:
        return input_str.split()
    elif "," in input_str:
        return input_str.split(",")
    else:
        return [input_str[i].lower() for i in range(1, len(input_str), 2)]

# 测试用例执行
if __name__ == "__main__":
    print(special_string_split("a b c d"))
    print(special_string_split("a,b,c,d"))
    print(special_string_split("abcd"))
66
编写一个Python程序,筛选列表中各位数字之和大于0的数字(数字的第一位可以是负数)。
📝 样例输入1:[11, -6, -103, -200]
▶ 输出结果1:[11, -103]
📝 样例输入2:[1, 7, -4, 4, -9, 2]
▶ 输出结果2:[1, 7, 4, 2]
参考答案
python
def filter_by_digit_sum_positive(num_list):
    def digit_sum(num):
        # 取绝对值,计算各位和
        return sum(int(char) for char in str(abs(num)))
    return [num for num in num_list if digit_sum(num) > 0]

# 测试用例执行
if __name__ == "__main__":
    print(filter_by_digit_sum_positive([11, -6, -103, -200]))
    print(filter_by_digit_sum_positive([1, 7, -4, 4, -9, 2]))
67
编写一个Python程序,筛选列表中大于10,且首位和末位数字均为奇数的数字。
📝 样例输入1:[1, 3, 79, 10, 4, 1, 39, 62]
▶ 输出结果1:[79, 39]
📝 样例输入2:[11, 31, 77, 93, 48, 1, 57]
▶ 输出结果2:[11, 31, 77, 93, 57]
参考答案
python
def filter_odd_first_last(num_list):
    result = []
    for num in num_list:
        if num <= 10:
            continue
        num_str = str(abs(num))
        first_digit = int(num_str[0])
        last_digit = int(num_str[-1])
        if first_digit % 2 == 1 and last_digit % 2 == 1:
            result.append(num)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(filter_odd_first_last([1, 3, 79, 10, 4, 1, 39, 62]))
    print(filter_odd_first_last([11, 31, 77, 93, 48, 1, 57]))
68
编写一个Python程序,计算给定数字中所有奇数位数字的乘积;如果没有奇数位数字,返回0。
📝 样例输入1:123456789
▶ 输出结果1:945
📝 样例输入2:2468
▶ 输出结果2:0
📝 样例输入3:13579
▶ 输出结果3:945
参考答案
python
def product_of_odd_digits(num):
    num_str = str(abs(num))
    product = 1
    has_odd = False
    for char in num_str:
        digit = int(char)
        if digit % 2 == 1:
            product *= digit
            has_odd = True
    return product if has_odd else 0

# 测试用例执行
if __name__ == "__main__":
    print(product_of_odd_digits(123456789))
    print(product_of_odd_digits(2468))
    print(product_of_odd_digits(13579))
69
编写一个Python程序,找出数字n的小于n的最大整数因数。
📝 样例输入1:18
▶ 输出结果1:9
📝 样例输入2:100
▶ 输出结果2:50
📝 样例输入3:102
▶ 输出结果3:51
参考答案
python
def largest_proper_divisor(n):
    if n <= 1:
        return 0
    # 从n/2倒序查找,第一个能整除的就是最大真因数
    for i in range(n // 2, 0, -1):
        if n % i == 0:
            return i
    return 1

# 测试用例执行
if __name__ == "__main__":
    print(largest_proper_divisor(18))
    print(largest_proper_divisor(100))
    print(largest_proper_divisor(102))
70
编写一个Python程序,提取列表中数字的个位数字,按降序排序后,转换为对应的英文数字单词。
📝 样例输入1:[1, 3, 4, 5, 11]
▶ 输出结果1:['five', 'four', 'three', 'one']
📝 样例输入2:[27, 3, 8, 5, 1, 31]
▶ 输出结果2:['eight', 'five', 'three', 'one']
参考答案
python
def single_digit_to_english_reverse(num_list):
    digit_word_map = {
        0: "zero", 1: "one", 2: "two", 3: "three", 4: "four",
        5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"
    }
    # 提取个位数字,去重
    unit_digits = list(set(abs(num) % 10 for num in num_list))
    # 降序排序
    unit_digits_sorted = sorted(unit_digits, reverse=True)
    # 转换为英文单词
    return [digit_word_map[d] for d in unit_digits_sorted if d != 0]

# 测试用例执行
if __name__ == "__main__":
    print(single_digit_to_english_reverse([1, 3, 4, 5, 11]))
    print(single_digit_to_english_reverse([27, 3, 8, 5, 1, 31]))
71
不规则矩阵(每行元素个数不同),编写一个Python程序,找出目标值在矩阵中所有出现位置的[行号, 列号]索引。
📝 样例输入1:矩阵([1, 3, 2, 32, 19], [19, 2, 48, 19], [], [9, 35, 4], [3, 19]),目标值19
▶ 输出结果1:[[0, 4], [1, 0], [1, 3], [4, 1]]
📝 样例输入2:矩阵([1, 2, 3, 2], [], [7, 9, 2, 1, 4]),目标值2
▶ 输出结果2:[[0, 1], [0, 3], [2, 2]]
参考答案
python
def find_target_in_ragged_matrix(matrix, target):
    index_list = []
    for row_idx, row in enumerate(matrix):
        for col_idx, value in enumerate(row):
            if value == target:
                index_list.append([row_idx, col_idx])
    return index_list

# 测试用例执行
if __name__ == "__main__":
    print(find_target_in_ragged_matrix(([1, 3, 2, 32, 19], [19, 2, 48, 19], [], [9, 35, 4], [3, 19]), 19))
    print(find_target_in_ragged_matrix(([1, 2, 3, 2], [], [7, 9, 2, 1, 4]), 2))
72
编写一个Python程序,判断一个数字序列的单调性,返回`Increasing.`(递增)、`Decreasing.`(递减)或`Not a monotonic sequence!`(非单调序列)。
📝 样例输入1:[1, 2, 3, 4, 5, 6]
▶ 输出结果1:Increasing.
📝 样例输入2:[6, 5, 4, 3, 2, 1]
▶ 输出结果2:Decreasing.
📝 样例输入3:[19, 19, 5, 5, 5, 5, 5]
▶ 输出结果3:Not a monotonic sequence!
参考答案
python
def check_monotonic_direction(num_list):
    is_increasing = all(num_list[i] <= num_list[i+1] for i in range(len(num_list)-1))
    is_decreasing = all(num_list[i] >= num_list[i+1] for i in range(len(num_list)-1))
    if is_increasing:
        return "Increasing."
    elif is_decreasing:
        return "Decreasing."
    else:
        return "Not a monotonic sequence!"

# 测试用例执行
if __name__ == "__main__":
    print(check_monotonic_direction([1, 2, 3, 4, 5, 6]))
    print(check_monotonic_direction([6, 5, 4, 3, 2, 1]))
    print(check_monotonic_direction([19, 19, 5, 5, 5, 5, 5]))
73
编写一个Python程序,计算多组银行存取款记录中,每组首次出现负余额时的余额;如果全程无负余额,返回None。
📝 样例输入1:[[12, -7, 3, -89, 14, 88, -78], [-1, 2, 7]]
▶ 输出结果1:[-81, -1]
📝 样例输入2:[[1200, 100, -900], [100, 100, -2400]]
▶ 输出结果2:[None, -2200]
参考答案
python
def first_negative_balance(record_groups):
    result = []
    for records in record_groups:
        balance = 0
        negative_balance = None
        for num in records:
            balance += num
            if balance < 0 and negative_balance is None:
                negative_balance = balance
        result.append(negative_balance)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(first_negative_balance([[12, -7, 3, -89, 14, 88, -78], [-1, 2, 7]]))
    print(first_negative_balance([[1200, 100, -900], [100, 100, -2400]]))
74
编写一个Python程序,找出所有n位整数中,以2开头或以2结尾的数字。
📝 样例输入1:1
▶ 输出结果1:[2]
📝 样例输入2:2
▶ 输出结果2:[12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32, 42, 52, 62, 72, 82, 92]
参考答案
python
def n_digit_start_end_with_two(n):
    if n == 1:
        return [2]
    start = 10 ** (n - 1)
    end = 10 ** n - 1
    result = []
    for num in range(start, end + 1):
        num_str = str(num)
        if num_str[0] == "2" or num_str[-1] == "2":
            result.append(num)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(n_digit_start_end_with_two(1))
    print(n_digit_start_end_with_two(2))
75
编写一个Python程序,对输入字符串进行处理:先翻转所有字母的大小写,再将元音字母替换为ASCII码+2的字符,输出最终结果。
📝 样例输入1:Python
▶ 输出结果1:pYTHQN
📝 样例输入2:aeiou
▶ 输出结果2:CGKQW
📝 样例输入3:Hello, world!
▶ 输出结果3:hGLLQ, WQRLD!
参考答案
python
def flip_case_shift_vowel(input_str):
    vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
    # 先翻转大小写
    swapped_str = input_str.swapcase()
    result = []
    for char in swapped_str:
        if char in vowels:
            # 元音字母ASCII+2
            result.append(chr(ord(char) + 2))
        else:
            result.append(char)
    return "".join(result)

# 测试用例执行
if __name__ == "__main__":
    print(flip_case_shift_vowel("Python"))
    print(flip_case_shift_vowel("aeiou"))
    print(flip_case_shift_vowel("Hello, world!"))
76
编写一个Python程序,计算数组中所有元素绝对值的和,结果的符号与数组中所有元素乘积的符号一致。
📝 样例输入1:[1, 3, -2]
▶ 输出结果1:-6
📝 样例输入2:[10, 32, 3]
▶ 输出结果2:45
📝 样例输入3:[-25, -12, -23]
▶ 输出结果3:-60
参考答案
python
def signed_abs_sum(num_list):
    abs_total = sum(abs(num) for num in num_list)
    # 计算乘积的符号
    sign = 1
    for num in num_list:
        if num < 0:
            sign *= -1
        elif num == 0:
            sign = 0
            break
    return abs_total * sign

# 测试用例执行
if __name__ == "__main__":
    print(signed_abs_sum([1, 3, -2]))
    print(signed_abs_sum([10, 32, 3]))
    print(signed_abs_sum([-25, -12, -23]))
77
编写一个Python程序,找出列表中两个数值最接近的不同数字。
📝 样例输入1:[1.3, 5.24, 0.89, 21.0, 5.27, 1.3]
▶ 输出结果1:[5.24, 5.27]
📝 样例输入2:[12.02, 20.3, 15.0, 19.0, 11.0, 14.99, 17.0, 17.0, 14.4, 16.8]
▶ 输出结果2:[14.99, 15.0]
参考答案
python
def closest_distinct_pair(num_list):
    # 去重
    unique_nums = list(set(num_list))
    if len(unique_nums) < 2:
        return []
    unique_nums.sort()
    min_diff = float("inf")
    min_pair = []
    for i in range(1, len(unique_nums)):
        diff = unique_nums[i] - unique_nums[i-1]
        if diff < min_diff:
            min_diff = diff
            min_pair = [unique_nums[i-1], unique_nums[i]]
    return min_pair

# 测试用例执行
if __name__ == "__main__":
    print(closest_distinct_pair([1.3, 5.24, 0.89, 21.0, 5.27, 1.3]))
    print(closest_distinct_pair([12.02, 20.3, 15.0, 19.0, 11.0, 14.99, 17.0, 17.0, 14.4, 16.8]))
78
编写一个Python程序,找出列表中最大的负数和最小的正数;如果没有负数,最大负数返回0;如果没有正数,最小正数返回0。
📝 样例输入1:[-12, -6, 300, -40, 2, 2, 3, 57, -50, -22, 12, 40, 9, 11, 18]
▶ 输出结果1:[-6, 2]
📝 样例输入2:[-1, -2, -3, -4]
▶ 输出结果2:[-1, 0]
📝 样例输入3:[1, 2, 3, 4]
▶ 输出结果3:[0, 1]
参考答案
python
def max_neg_min_pos(num_list):
    negatives = [num for num in num_list if num < 0]
    positives = [num for num in num_list if num > 0]
    max_negative = max(negatives) if negatives else 0
    min_positive = min(positives) if positives else 0
    return [max_negative, min_positive]

# 测试用例执行
if __name__ == "__main__":
    print(max_neg_min_pos([-12, -6, 300, -40, 2, 2, 3, 57, -50, -22, 12, 40, 9, 11, 18]))
    print(max_neg_min_pos([-1, -2, -3, -4]))
    print(max_neg_min_pos([1, 2, 3, 4]))
79
编写一个Python程序,对整数列表进行排序:保留奇数下标位置的元素不动,对偶数下标位置的元素进行升序排序,返回新列表。
📝 样例输入1:[2, 5, 6, 3, 1, 4, 34]
▶ 输出结果1:[1, 5, 2, 3, 6, 4, 34]
📝 样例输入2:[8, 0, 7, 2, 9, 4, 1, 2, 8, 3]
▶ 输出结果2:[1, 0, 7, 2, 8, 4, 8, 2, 9, 3]
参考答案
python
def sort_keep_odd_fixed(num_list):
    # 提取偶数下标元素
    even_indices = [i for i in range(0, len(num_list), 2)]
    even_values = [num_list[i] for i in even_indices]
    # 升序排序
    even_values_sorted = sorted(even_values)
    # 生成新列表
    new_list = num_list.copy()
    for idx, pos in enumerate(even_indices):
        new_list[pos] = even_values_sorted[idx]
    return new_list

# 测试用例执行
if __name__ == "__main__":
    print(sort_keep_odd_fixed([2, 5, 6, 3, 1, 4, 34]))
    print(sort_keep_odd_fixed([8, 0, 7, 2, 9, 4, 1, 2, 8, 3]))
80
编写一个Python程序,找出数字列表中数值最接近的一对元素的下标索引。
📝 样例输入1:[1, 7, 9, 2, 10]
▶ 输出结果1:[0, 3]
📝 样例输入2:[1.1, 4.25, 0.79, 1.0, 4.23]
▶ 输出结果2:[4, 1]
参考答案
python
def closest_pair_indices(num_list):
    min_diff = float("inf")
    min_pair = []
    for i in range(len(num_list)):
        for j in range(i+1, len(num_list)):
            diff = abs(num_list[i] - num_list[j])
            if diff < min_diff:
                min_diff = diff
                min_pair = [i, j]
    return min_pair

# 测试用例执行
if __name__ == "__main__":
    print(closest_pair_indices([1, 7, 9, 2, 10]))
    print(closest_pair_indices([1.1, 4.25, 0.79, 1.0, 4.23]))
81
编写一个Python程序,对列表进行特殊排序:第一个元素是最小值,第二个是剩余元素的最大值,第三个是剩余元素的最小值,第四个是剩余元素的最大值,以此类推。
📝 样例输入1:[1, 3, 4, 5, 11]
▶ 输出结果1:[1, 11, 3, 5, 4]
📝 样例输入2:[27, 3, 8, 5, 1, 31]
▶ 输出结果2:[1, 31, 3, 27, 5, 8]
参考答案
python
def min_max_alternate_sort(num_list):
    sorted_list = sorted(num_list)
    left = 0
    right = len(sorted_list) - 1
    result = []
    turn_min = True
    while left <= right:
        if turn_min:
            result.append(sorted_list[left])
            left += 1
        else:
            result.append(sorted_list[right])
            right -= 1
        turn_min = not turn_min
    return result

# 测试用例执行
if __name__ == "__main__":
    print(min_max_alternate_sort([1, 3, 4, 5, 11]))
    print(min_max_alternate_sort([27, 3, 8, 5, 1, 31]))
82
编写一个Python程序,将一个由逗号和空格分隔的单词字符串,拆分为两个列表:一个是单词列表,一个是分隔符列表。
📝 样例输入1:W3resource Python, Exercises.
▶ 输出结果1:[['W3resource', 'Python', 'Exercises.'], [' ', ', ']]
📝 样例输入2:The dance, held in the school gym, ended at midnight.
▶ 输出结果2:[['The', 'dance', 'held', 'in', 'the', 'school', 'gym', 'ended', 'at', 'midnight.'], [' ', ', ', ' ', ' ', ' ', ' ', ', ', ' ', ' ']]
参考答案
python
import re
def split_word_and_separator(input_str):
    # 正则匹配分割,保留分隔符
    parts = re.split(r'(\s+|,\s*)', input_str)
    words = []
    separators = []
    for part in parts:
        if part.strip() != "" and not re.match(r'^\s*,\s*$', part):
            words.append(part)
        else:
            separators.append(part)
    return [words, separators]

# 测试用例执行
if __name__ == "__main__":
    print(split_word_and_separator("W3resource Python, Exercises."))
    print(split_word_and_separator("The dance, held in the school gym, ended at midnight."))
83
编写一个Python程序,找出所有小于n、且能被9或15整除的整数中,数字5出现的位置和次数。
📝 样例输入1:n=50
▶ 输出结果1:[[15, 1], [45, 1]]
📝 样例输入2:n=65
▶ 输出结果2:[[15, 1], [45, 1], [54, 0]]
参考答案
python
def find_five_in_divisible(n):
    result = []
    for num in range(1, n):
        if num % 9 == 0 or num % 15 == 0:
            # 找出5的下标
            five_indices = [idx for idx, char in enumerate(str(num)) if char == "5"]
            for idx in five_indices:
                result.append([num, idx])
    return result

# 测试用例执行
if __name__ == "__main__":
    print(find_five_in_divisible(50))
    print(find_five_in_divisible(65))
84
编写一个Python程序,找出列表中三个和为0的数字的下标索引。
📝 样例输入1:[12, -7, 3, -89, 14, 4, -78, -1, 2, 7]
▶ 输出结果1:[1, 2, 5]
📝 样例输入2:[1, 2, 3, 4, 5, 6, -7]
▶ 输出结果2:[2, 3, 6]
参考答案
python
def zero_sum_triple_indices(num_list):
    n = len(num_list)
    for i in range(n):
        for j in range(i+1, n):
            for k in range(j+1, n):
                if num_list[i] + num_list[j] + num_list[k] == 0:
                    return [i, j, k]
    return []

# 测试用例执行
if __name__ == "__main__":
    print(zero_sum_triple_indices([12, -7, 3, -89, 14, 4, -78, -1, 2, 7]))
    print(zero_sum_triple_indices([1, 2, 3, 4, 5, 6, -7]))
85
编写一个Python程序,找出输入字符串中,包含指定个数辅音字母的所有单词。
📝 样例输入1:this is our time,辅音个数3
▶ 输出结果1:['this']
📝 样例输入2:this is our time,辅音个数2
▶ 输出结果2:['time']
参考答案
python
def find_word_with_consonant_count(input_str, consonant_num):
    vowels = {"a", "e", "i", "o", "u"}
    words = input_str.split()
    result = []
    for word in words:
        # 统计辅音数量
        count = 0
        for char in word.lower():
            if char.isalpha() and char not in vowels:
                count += 1
        if count == consonant_num:
            result.append(word)
    return result

# 测试用例执行
if __name__ == "__main__":
    print(find_word_with_consonant_count("this is our time", 3))
    print(find_word_with_consonant_count("this is our time", 2))
86
编写一个Python程序,提取字符串中的元音字母;如果字母y出现在单词末尾,也视为元音。
📝 样例输入1:['w3resource', 'Python', 'Java', 'C++']
▶ 输出结果1:['eoue', 'o', 'aa', '']
📝 样例输入2:['ably', 'abruptly', 'abecedary', 'apparently', 'acknowledgedly']
▶ 输出结果2:['ay', 'auy', 'aeeay', 'aaey', 'aoeey']
参考答案
python
def extract_vowel_include_y_end(word_list):
    vowels = {"a", "e", "i", "o", "u"}
    result = []
    for word in word_list:
        word_lower = word.lower()
        vowel_chars = []
        for idx, char in enumerate(word_lower):
            if char in vowels:
                vowel_chars.append(char)
            elif char == "y" and idx == len(word_lower) - 1:
                vowel_chars.append(char)
        result.append("".join(vowel_chars))
    return result

# 测试用例执行
if __name__ == "__main__":
    print(extract_vowel_include_y_end(['w3resource', 'Python', 'Java', 'C++']))
    print(extract_vowel_include_y_end(['ably', 'abruptly', 'abecedary', 'apparently', 'acknowledgedly']))
87
编写一个Python程序,从列表中筛选出所有数字位均为奇数的数字,按升序排序后返回。
📝 样例输入1:[1, 3, 79, 10, 4, 2, 39]
▶ 输出结果1:[1, 3, 39, 79]
📝 样例输入2:[11, 31, 40, 68, 77, 93, 48, 1, 57]
▶ 输出结果2:[1, 11, 31, 57, 77, 93]
参考答案
python
def all_odd_digit_sublist(num_list):
    def is_all_odd_digit(num):
        num_str = str(abs(num))
        for char in num_str:
            if int(char) % 2 == 0:
                return False
        return True
    # 筛选并排序
    result = [num for num in num_list if is_all_odd_digit(num)]
    return sorted(result)

# 测试用例执行
if __name__ == "__main__":
    print(all_odd_digit_sublist([1, 3, 79, 10, 4, 2, 39]))
    print(all_odd_digit_sublist([11, 31, 40, 68, 77, 93, 48, 1, 57]))
88
编写一个Python程序,校验文件名是否合法:合法文件名必须以.txt、.exe、.jpg、.png、.dll结尾,文件名中最多包含3个数字,且不能有多余的句点。返回一一对应的校验结果。
📝 样例输入1:['abc.txt', 'windows.dll', 'tiger.png', 'rose.jpg', 'test.py', 'win32.exe']
▶ 输出结果1:['Yes', 'Yes', 'Yes', 'Yes', 'No', 'Yes']
📝 样例输入2:['.txt', 'windows.exe', 'tiger.jpeg', 'rose.c', 'test.java']
▶ 输出结果2:['No', 'Yes', 'No', 'No', 'No']
参考答案
python
def validate_filenames(filename_list):
    valid_suffix = {"txt", "exe", "jpg", "png", "dll"}
    result = []
    for filename in filename_list:
        # 校验只有一个句点
        if filename.count(".") != 1:
            result.append("No")
            continue
        main_name, suffix = filename.split(".")
        # 校验后缀合法
        if suffix not in valid_suffix:
            result.append("No")
            continue
        # 校验数字数量不超过3
        digit_count = sum(1 for char in main_name if char.isdigit())
        if digit_count > 3:
            result.append("No")
            continue
        result.append("Yes")
    return result

# 测试用例执行
if __name__ == "__main__":
    print(validate_filenames(['abc.txt', 'windows.dll', 'tiger.png', 'rose.jpg', 'test.py', 'win32.exe']))
    print(validate_filenames(['.txt', 'windows.exe', 'tiger.jpeg', 'rose.c', 'test.java']))
89
编写一个Python程序,按照给定的GPA区间规则,将GPA分数转换为对应的字母等级。 ### 等级规则 | GPA区间 | 等级 | |---------|------| | ≥4.0 | A+ | | ≥3.7 | A | | ≥3.4 | A- | | ≥3.0 | B+ | | ≥2.7 | B | | ≥2.4 | B- | | ≥2.0 | C+ | | ≥1.7 | C | | ≥1.4 | C- | | <1.4 | F |
📝 样例输入1:[4.0, 3.5, 3.8]
▶ 输出结果1:['A+', 'A-', 'A']
📝 样例输入2:[5.0, 4.7, 3.4, 3.0, 2.7, 2.4, 2.0, 1.7, 1.4, 0.0]
▶ 输出结果2:['A+', 'A+', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'F']
参考答案
python
def gpa_to_grade(gpa_list):
    grade_rules = [
        (4.0, "A+"),
        (3.7, "A"),
        (3.4, "A-"),
        (3.0, "B+"),
        (2.7, "B"),
        (2.4, "B-"),
        (2.0, "C+"),
        (1.7, "C"),
        (1.4, "C-"),
        (0, "F")
    ]
    result = []
    for gpa in gpa_list:
        for threshold, grade in grade_rules:
            if gpa >= threshold:
                result.append(grade)
                break
    return result

# 测试用例执行
if __name__ == "__main__":
    print(gpa_to_grade([4.0, 3.5, 3.8]))
    print(gpa_to_grade([5.0, 4.7, 3.4, 3.0, 2.7, 2.4, 2.0, 1.7, 1.4, 0.0]))
90
编写一个Python程序,找出字典中大小写格式与其他所有键不同的那个键。
📝 样例输入1:{'red': '', 'GREEN': '', 'blue': 'orange'}
▶ 输出结果1:GREEN
📝 样例输入2:{'RED': '', 'GREEN': '', 'orange': '#125GD'}
▶ 输出结果2:orange
参考答案
python
def find_odd_case_key(dict_data):
    keys = list(dict_data.keys())
    if len(keys) < 2:
        return None
    # 统计小写键和大写键的数量
    lower_count = 0
    upper_count = 0
    lower_key = ""
    upper_key = ""
    for key in keys:
        if key.islower():
            lower_count += 1
            lower_key = key
        elif key.isupper():
            upper_count += 1
            upper_key = key
    # 数量少的就是特殊的键
    if lower_count == 1:
        return lower_key
    elif upper_count == 1:
        return upper_key
    else:
        return None

# 测试用例执行
if __name__ == "__main__":
    print(find_odd_case_key({'red': '', 'GREEN': '', 'blue': 'orange'}))
    print(find_odd_case_key({'RED': '', 'GREEN': '', 'orange': '#125GD'}))
91
编写一个Python程序,找出字符串中每个括号对应的匹配括号的下标,按原字符串顺序返回下标列表。
📝 样例输入1:()(())
▶ 输出结果1:[1, 0, 5, 4, 3, 2]
📝 样例输入2:()()()
▶ 输出结果2:[1, 0, 3, 2, 5, 4]
📝 样例输入3:((()))
▶ 输出结果3:[5, 4, 3, 2, 1, 0]
参考答案
python
def bracket_matching_indices(input_str):
    stack = []
    match_map = {}
    for idx, char in enumerate(input_str):
        if char == "(":
            stack.append(idx)
        elif char == ")":
            if stack:
                left_idx = stack.pop()
                match_map[left_idx] = idx
                match_map[idx] = left_idx
    # 按原顺序生成结果
    result = [match_map[idx] for idx in range(len(input_str)) if idx in match_map]
    return result

# 测试用例执行
if __name__ == "__main__":
    print(bracket_matching_indices("()(())"))
    print(bracket_matching_indices("()()()"))
    print(bracket_matching_indices("((()))"))
92
编写一个Python程序,计算字符串中每组匹配括号的嵌套深度,返回深度列表。
📝 样例输入1:(()) (()) () ((()()()))
▶ 输出结果1:[2, 2, 1, 3]
📝 样例输入2:() (()) () () () ()
▶ 输出结果2:[1, 2, 1, 1, 1, 1]
参考答案
python
def bracket_group_depth(input_str):
    # 拆分括号组
    groups = split_parenthesis_groups_v2(input_str)
    depth_list = []
    for group in groups:
        current_depth = 0
        max_depth = 0
        for char in group:
            if char == "(":
                current_depth += 1
                if current_depth > max_depth:
                    max_depth = current_depth
            elif char == ")":
                current_depth -= 1
        depth_list.append(max_depth)
    return depth_list

# 测试用例执行
if __name__ == "__main__":
    print(bracket_group_depth("(()) (()) () ((()()()))"))
    print(bracket_group_depth("() (()) () () () ()"))
93
给定一个由空格和成对匹配的括号组组成的字符串,编写一个Python程序,将其拆分为完全匹配的括号组列表,并去除所有空格。
📝 样例输入1:( ()) ((()()())) (()) ()
▶ 输出结果1:['(())', '((()()()))', '(())', '()']
📝 样例输入2:() (( ( )() ( )) ) ( ())
▶ 输出结果2:['()', '((()()()))', '(())']
参考答案
python
def split_parenthesis_groups(input_str):
    # 去除所有空格
    s = input_str.replace(" ", "")
    stack = []
    groups = []
    start = 0
    for idx, char in enumerate(s):
        if char == "(":
            if not stack:
                start = idx
            stack.append(char)
        elif char == ")":
            if stack:
                stack.pop()
                if not stack:
                    groups.append(s[start:idx+1])
    return groups

# 测试用例执行
if __name__ == "__main__":
    print(split_parenthesis_groups("( ()) ((()()())) (()) ()"))
    print(split_parenthesis_groups("() (( ( )() ( )) ) ( ())"))
94
给定一个由空格和成对匹配的括号组组成的字符串,编写一个Python程序,将其拆分为完全匹配的括号组列表,并去除所有空格。
📝 样例输入1:( ()) ((()()())) (()) ()
▶ 输出结果1:['(())', '((()()()))', '(())', '()']
📝 样例输入2:() (( ( )() ( )) ) ( ())
▶ 输出结果2:['()', '((()()()))', '(())']
参考答案
python
def split_parenthesis_groups_v2(input_str):
    s = input_str.replace(" ", "")
    stack = []
    groups = []
    start = 0
    for idx, char in enumerate(s):
        if char == "(":
            if not stack:
                start = idx
            stack.append(char)
        elif char == ")":
            if stack:
                stack.pop()
                if not stack:
                    groups.append(s[start:idx+1])
    return groups

# 测试用例执行
if __name__ == "__main__":
    print(split_parenthesis_groups_v2("( ()) ((()()())) (()) ()"))
    print(split_parenthesis_groups_v2("() (( ( )() ( )) ) ( ())"))
95
编写一个Python程序,判断十六进制数的每一位字符对应的十进制数值是否为质数,返回一一对应的布尔值列表。
📝 样例输入1:123ABCD
▶ 输出结果1:[False, True, True, False, True, False, True]
📝 样例输入2:123456
▶ 输出结果2:[False, True, True, False, True, False]
参考答案
python
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def hex_char_prime_check(hex_str):
    result = []
    for char in hex_str:
        # 十六进制字符转十进制
        decimal_val = int(char, 16)
        result.append(is_prime(decimal_val))
    return result

# 测试用例执行
if __name__ == "__main__":
    print(hex_char_prime_check("123ABCD"))
    print(hex_char_prime_check("123456"))
96
编写一个Python程序,从输入句子中,筛选出长度为质数的单词,拼接成新的字符串。
📝 样例输入1:The quick brown fox jumps over the lazy dog.
▶ 输出结果1:The quick brown fox jumps the
📝 样例输入2:Omicron Effect: Foreign Flights Won't Resume On Dec 15, Decision Later.
▶ 输出结果2:Omicron Effect: Foreign Flights Won't On Dec 15,
参考答案
python
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def concat_prime_length_words(sentence):
    words = sentence.split()
    result = []
    for word in words:
        if is_prime(len(word)):
            result.append(word)
    return " ".join(result)

# 测试用例执行
if __name__ == "__main__":
    print(concat_prime_length_words("The quick brown fox jumps over the lazy dog."))
    print(concat_prime_length_words("Omicron Effect: Foreign Flights Won't Resume On Dec 15, Decision Later."))
97
编写一个Python程序,从给定字符串中找出包含嵌套结构的合法括号子串。
📝 样例输入1:]][][[]]]
▶ 输出结果1:[[]]
📝 样例输入2:]]]]][[[][[][[[[[][][][]][[[[[[[[[[[[[[[[[[
▶ 输出结果2:[[][][][]]
参考答案
python
def valid_nested_bracket_substring(input_str):
    stack = []
    start = 0
    max_nested = 0
    result = ""
    for idx, char in enumerate(input_str):
        if char == "(":
            if not stack:
                start = idx
            stack.append(char)
            # 记录嵌套深度
            if len(stack) > max_nested:
                max_nested = len(stack)
        elif char == ")":
            if stack:
                stack.pop()
                if not stack:
                    current_sub = input_str[start:idx+1]
                    # 有嵌套结构
                    if max_nested >= 2:
                        result = current_sub
                    max_nested = 0
    return result

# 测试用例执行
if __name__ == "__main__":
    print(valid_nested_bracket_substring("]][][[]]]"))
    print(valid_nested_bracket_substring("]]]]][[[][[][[[[[][][][]][[[[[[[[[[[[[[[[[["))
98
编写一个Python程序,找出列表中与质数相邻的所有数字,去重后按升序排序返回。
📝 样例输入1:[2, 17, 16, 0, 6, 4, 5]
▶ 输出结果1:[2, 4, 16, 17]
📝 样例输入2:[1, 2, 19, 16, 6, 4, 10]
▶ 输出结果2:[1, 2, 16, 19]
参考答案
python
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def adjacent_to_prime(num_list):
    result = set()
    for idx, num in enumerate(num_list):
        if is_prime(num):
            # 左边相邻的数
            if idx > 0:
                result.add(num_list[idx-1])
            # 右边相邻的数
            if idx < len(num_list) - 1:
                result.add(num_list[idx+1])
    return sorted(list(result))

# 测试用例执行
if __name__ == "__main__":
    print(adjacent_to_prime([2, 17, 16, 0, 6, 4, 5]))
    print(adjacent_to_prime([1, 2, 19, 16, 6, 4, 10]))
99
编写一个Python程序,找出列表中最大的质数,返回它的下标索引和它的各位数字之和。
📝 样例输入1:[3, 7, 4]
▶ 输出结果1:[1, 7]
📝 样例输入2:[3, 11, 7, 17, 19, 4]
▶ 输出结果2:[4, 10]
参考答案
python
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def max_prime_index_and_digit_sum(num_list):
    prime_list = []
    for idx, num in enumerate(num_list):
        if is_prime(num):
            prime_list.append((num, idx))
    if not prime_list:
        return None
    # 找最大的质数
    max_prime, max_idx = max(prime_list, key=lambda x: x[0])
    # 计算各位和
    digit_sum = sum(int(char) for char in str(max_prime))
    return [max_idx, digit_sum]

# 测试用例执行
if __name__ == "__main__":
    print(max_prime_index_and_digit_sum([3, 7, 4]))
    print(max_prime_index_and_digit_sum([3, 11, 7, 17, 19, 4]))
100
编写一个Python程序,找出所有小于等于1000、且恰好是三个质数乘积的整数,返回每个数的三个质因数列表。
📝 样例输入1:10
▶ 输出结果1:[[2, 2, 2]]
📝 样例输入2:50
▶ 输出结果2:[[2, 2, 2], [2, 2, 3], [2, 2, 5], [2, 2, 7], [2, 2, 11], ...]
参考答案
python
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def three_prime_product(max_num):
    # 生成小于max_num的质数列表
    primes = [p for p in range(2, max_num + 1) if is_prime(p)]
    result = []
    for a in primes:
        for b in primes:
            for c in primes:
                product = a * b * c
                if product <= max_num:
                    result.append([a, b, c])
    return result

# 测试用例执行
if __name__ == "__main__":
    print(three_prime_product(10))