欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python(循环分支)

程序员文章站 2022-04-06 12:33:07
...

Python基础测试题目:Python(循环分支)

 

 

 

题目1: 打印1~10的数字以及每个数的平方、几何级数和阶乘

 
 
输出格式:
数字     平方    几何级数   阶乘
1     1     2     1
2     4     4     2
3     9     8     6
4     16    16    24
5     25    32    210

代码如下:

from math import factorial


def main():
    print('%-10s%-10s%-10s%-10s' % ('数字', '平方', '几何级数', '阶乘'))
    for num in range(1, 11):
        print('%-12d%-12d%-12d%-12d' % (num, num ** 2, 2 ** num, factorial(num)))
    
#%d前加数字表示间隔的字符数

if __name__ == '__main__':
    main()

题目2: 设计一个函数,生成指定长度的验证码
(由数字和大小写英文字母构成的随机字符串)

 

from random import randrange


def generate_code(length=4):
    all_chars = 'abcdefghijklmnopqrstuvwxyzABDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    all_chars_len = len(all_chars)
    code = ''
    for _ in range(length):
        index = randrange(all_chars_len)
        code += all_chars[index]
    return code


def main():
    for _ in range(10):
        print(generate_code())


if __name__ == '__main__':
    main()
 

题目3: 设计一个函数,统计字符串中英文字母和数字各自出现的次数

 

def count_letter_number(string):
    letter_count = 0
    digit_count = 0
    for ch in string:
        if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
            letter_count += 1
        elif '0' <= ch <= '9':
            digit_count += 1
    return letter_count, digit_count


def main():
    print(count_letter_number('a1b2c3d4'))  # (4, 4)
    print(count_letter_number('a123456b'))  # (2, 6)
    print(count_letter_number('123456!!'))  # (0, 6)


if __name__ == '__main__':
    main()
 

题目4: 设计一个函数,判断传入的整数列表(要求元素个数大于2个)

中的元素能否构成等差数列

 

def is_arithmetic_series(num_list):
    num_list_len = len(num_list)
    assert num_list_len > 2
    sorted_list = sorted(num_list)
    for index in range(2, num_list_len):
        if sorted_list[index] - sorted_list[index - 1] != \
                sorted_list[index - 1] - sorted_list[index - 2]:
            return False
    return True


def main():
    list1 = [1, 3, 5, 7, 9]
    list2 = [100, 500, 200, 400, 300]
    list3 = [1, 2, 3, 5, 6, 7]
    print(is_arithmetic_series(list1))  # True
    print(is_arithmetic_series(list2))  # True
    print(is_arithmetic_series(list3))  # False


if __name__ == '__main__':
    main()
题目5: 设计一个函数,计算字符串中所有数字序列的和

 

from re import findall


def sum_num_seq(string):
    total = 0
    for val in map(int, findall(r'\d+', string)):
        total += val
    return total


def main():
    print(sum_num_seq('a1b2c3d4'))  # 10
    print(sum_num_seq('123hello456good789bye'))  # 1368
    print(sum_num_seq('12345678'))  # 12345678
    print(sum_num_seq('abcdefgh'))  # 0


if __name__ == '__main__':
    main()
 

题目6: 设计一个函数,对传入的字符串(假设字符串中只包含小写字

母和空格)进行加密操作,加密的规则是a变d,b变e,c变f,……,

x变a,y变b,z变c,空格不变,返回加密后的字符串

def caesar_encrypt(string):
    base = ord('a')
    encrypted_string = ''
    for ch in string:
        if ch != ' ':
            curr = ord(ch)
            diff = (curr - base + 3) % 26
            ch = chr(base + diff)
        encrypted_string += ch
    return encrypted_string


def main():
    print(caesar_encrypt('attack at dawn'))  # dwwdfn dw gdzq
    print(caesar_encrypt('dinner is on me'))  # glqqhu lv rq ph


if __name__ == '__main__':
    main()

题目7: 设计“跳一跳”游戏的计分函数,“跳一跳”游戏中黑色
小人从一个方块跳到另一个方块上会获得1分,如果跳到方块的中
心点上会获得2分,连续跳到中心点会依次获得2分、4分、6分、
……。该函数传入一个列表,列表中用布尔值True或False表示是
否跳到方块的中心点,函数返回最后获得的分数

def calc_score(jump_list):
    total = 0
    prev_on_center = False
    on_center_point = 2
    for val in jump_list:
        if val:
            total += on_center_point
            on_center_point += 2
            prev_on_center = True
        else:
            total += 1
            on_center_point = 2
            prev_on_center = False
    return total


def main():
    list1 = [True, False, False, True, True, True]
    list2 = [True, True, True, True, False, True, True]
    list3 = [False, False, True, True, True, True, True, False]
    print(calc_score(list1))  # 16
    print(calc_score(list2))  # 27
    print(calc_score(list3))  # 33


if __name__ == '__main__':
    main()

题目8: 设计一个函数,统计一个字符串中出现频率最高的字符及其出

现次数

def find_most_freq(string):
    result_dict = {}
    for ch in string:
        if ch in result_dict:
            result_dict[ch] += 1
        else:
            result_dict[ch] = 1
    max_keys = []
    max_value = 0
    for key, value in result_dict.items():
        if value > max_value:
            max_value = value
            max_keys.clear()
            max_keys.append(key)
        elif value == max_value:
            max_keys.append(key)
    return max_keys, max_value


def main():
    print(find_most_freq('aabbaaccbb'))  # (['a', 'b'], 4)
    print(find_most_freq('hello, world!'))  # (['l'], 3)
    print(find_most_freq('a1bb2ccc3aa'))  # (['a', 'c'], 3)


if __name__ == '__main__':
    main()

 

题目9: 设计一个函数,传入两个代表日期的字符串,如“2018-2-26”

、“2017-12-12”,计算两个日期相差多少天

def date_to_tuple(date_str):
    year, month, day = map(int, date_str.split('-'))
    return year, month, day


def is_leap_year(year):
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0


def which_day(date_str):
    year, month, day = date_to_tuple(date_str)
    days_of_month = [
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    ][is_leap_year(year)]
    total = 0
    for index in range(month - 1):
        total += days_of_month[index]
    return total + day


def diff_days(date1, date2):
    year1, month1, day1 = date_to_tuple(date1)
    year2, month2, day2 = date_to_tuple(date2)
    if year1 > year2:
        return diff_days(date2, date1)
    elif year1 == year2:
        if month1 > month2:
            return diff_days(date2, date1)
        elif month1 == month2:
            return abs(day2 - day1)
        else:
            return which_day(date2) - which_day(date1)
    else:
        all_days = 366 if is_leap_year(year1) else 365
        rest_days = all_days - which_day(date1)
        past_days = which_day(date2)
        total = 0
        for year in range(year1 + 1, year2):
            total += 366 if is_leap_year(year) else 365
        return total + rest_days + past_days


def main():
    print(diff_days('2017-12-12', '2018-2-26'))  # 76
    print(diff_days('1979-12-31', '1980-11-28'))  # 333
    print(diff_days('1980-11-28', '1978-12-30'))  # 699
    print(diff_days('2018-3-23', '2018-2-26'))  # 25
    print(diff_days('2018-3-23', '2018-3-26'))  # 3


if __name__ == '__main__':
    main()

题目10: “四川麻将”共有108张牌,分为“筒”、“条”、“万”三种类型,每种类型的牌

有1~9的点数,每个点数有4张牌;游戏通常有4个玩家,游戏开始的时候,有一个玩家会拿到

14张牌(首家),其他三个玩家每人13张牌。要求用面向对象的方式创建麻将牌和玩家并实现

洗牌、摸牌以及玩家按照类型和点数排列手上的牌的操作,最后显示出游戏开始的时候每个玩

家手上的牌。

 

from random import randrange, shuffle


class Piece(object):

    def __init__(self, suite, face):
        self._suite = suite
        self._face = face

    @property
    def suite(self):
        return self._suite

    @property
    def face(self):
        return self._face

    def __str__(self):
        return str(self._face) + self._suite


class Mahjong(object):

    def __init__(self):
        self._pieces = []
        self._index = 0
        suites = ['筒', '条', '万']
        for suite in suites:
            for face in range(1, 10):
                for _ in range(4):
                    piece = Piece(suite, face)
                    self._pieces.append(piece)

    def shuffle(self):
        self._index = 0
        shuffle(self._pieces)

    @property
    def next(self):
        piece = self._pieces[self._index]
        self._index += 1
        return piece

    @property
    def has_next(self):
        return self._index < len(self._pieces)


class Player(object):

    def __init__(self, name):
        self._name = name
        self._pieces_on_hand = []

    @property
    def name(self):
        return self._name

    @property
    def pieces(self):
        return self._pieces_on_hand

    def get(self, piece):
        self._pieces_on_hand.append(piece)

    def drop(self, index):
        return self._pieces_on_hand.pop(index)

    def clear(self):
        self._pieces_on_hand.clear()

    def sort(self):
        self._pieces_on_hand.sort(key=get_key)


def get_key(piece):
    return piece.suite, piece.face


def display(player):
    print(player.name, end=': ')
    for piece in player.pieces:
        print(piece, end=' ')
    print()


def main():
    mahjong = Mahjong()
    mahjong.shuffle()
    players = [Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐')]
    for _0 in range(3):
        for player in players:
            for _1 in range(4):
                player.get(mahjong.next)
    players[0].get(mahjong.next)
    for player in players:
        player.get(mahjong.next)
    for player in players:
        player.sort()
        display(player)


if __name__ == '__main__':
    main()