考试题
"""
题目1: 按照下面的格式打印1~10的数字以及每个数的平方、几何级数和阶乘
数字 平方 几何级数 阶乘
1 1 2 1
2 4 4 2
3 9 8 6
4 16 16 24
5 25 32 210
...
"""
def main():
def factorial(n):
"""
:param n: 要求阶乘的数字
:return: 返回它的阶乘
"""
if n == 1:
return 1
return n * factorial(n - 1)
for x in range(1, 11):
print(x, x ** 2, 2 ** x, factorial(x))
if __name__ == '__main__':
main()
"""
题目1: 打印1~10的数字以及每个数的平方、几何级数和阶乘
"""
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)))
if __name__ == '__main__':
main()
数字 平方 几何级数 阶乘
1 1 2 1
2 4 4 2
3 9 8 6
4 16 16 24
5 25 32 120
6 36 64 720
7 49 128 5040
8 64 256 40320
9 81 512 362880
10 100 1024 3628800
"""
题目2: 设计一个函数,生成指定长度的验证码(由数字和大小写英文字母构成的随机字符串)
"""
from random import randint
def generate_code(length=4):
"""
:param length: 验证码长度
:return: 返回一个指定长度的有数字,字母组成的验证码
"""
code_string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
code = ''
for _ in range(length):
code += code_string[randint(0, len(code_string) - 1)]
return code
def main():
for _ in range(10):
print(generate_code())
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):
"""
:param string: 给定一个字符串
:return: 由字符串中英文字母和数字各自出现的次数组成的元组
"""
n = 0
m = 0
for s in string:
if s in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
n += 1
elif s in '0123456789':
m += 1
return n, m
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()
"""
题目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):
"""
:param num_list: 给定需要判断的列表
:return: 是等差数列返回True,否则返回False
"""
num_list.sort() # 这种方法函数会有副作用,所以这道题不得分
difference = num_list[1] - num_list[0]
for x in range(len(num_list) - 1):
if num_list[x + 1] - num_list[x] != difference:
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
print(list2)
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: 设计一个函数,计算字符串中所有数字序列的和
"""
import re
def sum_num_seq(string):
"""
:param string: 给定一个字符串
:return: 返回里面数字序列的和
"""
nums = re.compile(r'\d+')
mylist = nums.findall(string)
my_sum = 0
for num in mylist:
my_sum += int(num)
return my_sum
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()
"""
题目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):
"""
:param string: 给定一个字符串
:return: 返回加密后的字符串
"""
new_string = ''
all_string = 'abcdefghijklmnopqrstuvwxyz'
for x in string:
if x in all_string:
index = all_string.find(x)
if index >= len(all_string) - 3:
new_string += all_string[len(all_string) - index + 3]
else:
new_string += all_string[index + 3]
else:
new_string += x
return new_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()
"""
题目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):
"""
:param jump_list: 给定一个列表
:return: 返回最后获得的分数
"""
total = 0
for index, x in enumerate(jump_list):
if x:
total += 2
for y in range(index - 1, -1, -1):
if jump_list[y]:
total += 2
else:
break
else:
total += 1
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()
"""
题目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):
"""
:param string: 输入一个字符串
:return: 返回字符串中出现频率最高的字符及其出现次数
"""
my_dict={}
for x in string:
if x not in my_dict:
my_dict[x] = 1
else:
my_dict[x] += 1
max_num = 0
for y in my_dict:
if my_dict[y] > max_num:
max_num = my_dict[y]
max_list = []
for z in my_dict:
if my_dict[z] == max_num:
max_list += z
return max_list, max_num
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()
"""
题目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 is_leap_year(year):
"""
:param year: 给定一个年份
:return: 闰年返回True ,否则返回False
"""
return (year % 400 == 0 or year % 100 != 0) and year % 4 == 0
def my_data(data):
"""
:param data: 给一个日期的字符串
:return: 返回一个整型的年月日的元组
"""
data_year = data[:data.find('-')]
data_month = data[data.find('-') + 1: data.rfind('-')]
data_day = data[data.rfind('-') + 1:]
return int(data_year), int(data_month), int(data_day)
def days_month(year):
"""
:param year: 给定一个年份
:return: 返回一个包含所有月份天数的列表
"""
year_days_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)]
days_sum = 0
return year_days_month
def diff_days(data1, data2):
"""
:param data1: 一个日期的字符串
:param data2: 另一个日期的字符串
:return: 返回两个日期中间隔了多少天
"""
if my_data(data1)[0] == my_data(data2)[0]:
years_day = days_month(my_data(data1)[0])
total1 = 0
for index in range(my_data(data1)[1] - 1):
total1 += years_day[index]
days_data1 = total1 + my_data(data1)[2]
total2 = 0
for index2 in range(my_data(data2)[1] - 1):
total2 += years_day[index2]
days_data2 = total2 + my_data(data2)[2]
return abs(days_data1 - days_data2)
else:
(data1, data2) = (data1, data2) if my_data(data1)[0] > my_data(data2)[0] else (data2, data1)
data1_years_day = days_month(my_data(data1)[0])
total1 = 0
for index in range(my_data(data1)[1] - 1):
total1 += data1_years_day[index]
days_data1 = total1 + my_data(data1)[2]
data2_years_day = days_month(my_data(data2)[0])
total2 = 0
for index2 in range(my_data(data2)[1] - 1):
total2 += data2_years_day[index2]
days_data2 = total2 + my_data(data2)[2]
years_sum = 0
for num in data2_years_day:
years_sum += num
m_years_sum = 0
for year in range(my_data(data2)[0] + 1, my_data(data1)[0]):
year_days = days_month(year)
for day in year_days:
m_years_sum += day
return years_sum - days_data2 + days_data1 + m_years_sum
def main():
print(diff_days('2017-12-12', '2018-2-26')) # 76
print(diff_days('1979-12-31', '1980-11-28')) # 333
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
class Mahjong(object):
"""一张牌"""
def __init__(self, mytype, face):
"""
:param mytype:牌的类型
:param face: 牌的点数
"""
self._mytype = mytype
self._face = face
@property
def face(self):
return self._face
@property
def mytype(self):
return self._mytype
def __str__(self):
"""返回牌的类型和点数"""
return '%d%s'% (self._face, self._mytype)
class Mahjongs(object):
"""一副麻将"""
def __init__(self):
self._mahjongs = []
self._count = 0
for x in ['筒', '条', '万']:
for y in range(1, 10):
for _ in range(4):
mahjong = Mahjong(x, y)
self._mahjongs.append(mahjong)
def shuffle(self):
"""洗牌"""
self._count = 0
for index, ma in enumerate(self._mahjongs):
pos = randrange(len(self._mahjongs))
self._mahjongs[index], self._mahjongs[pos] = self._mahjongs[pos], self._mahjongs[index]
def deal(self):
"""发牌"""
if self._count < len(self._mahjongs):
mahjong = self._mahjongs[self._count]
self._count += 1
return mahjong
def ma_end(self):
"""判断是否发完"""
return self._count < len(self._mahjongs)
def show(self):
"""显示牌"""
return self._mahjongs
class Player(object):
def __init__(self, name):
"""
:param name: 玩家的名字
"""
self._name = name
self._ma_on_hand = []
@property
def name(self):
return self._name
@property
def ma_on_hand(self):
"""在手里的牌"""
return self._ma_on_hand
def get_ma(self, other):
"""摸牌"""
self._ma_on_hand.append(other.deal())
def show(self):
"""显示手里的牌"""
return self._ma_on_hand
def hand_sort(self):
"""整理手牌"""
self._ma_on_hand.sort(key=get_key)
def get_key(mahjong):
"""
:param mahjong: 一张牌
:return: 牌点数和类型所对应ACSII码的和
"""
return mahjong.face + ord(mahjong.mytype)
def display(player):
"""
:param player: 一个玩家
:return: 玩家的手牌
"""
player.hand_sort()
print(player.name, end= ':')
for mahjong in player.ma_on_hand:
print(mahjong, end=' ')
print()
def main():
players = [Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐')]
mahjongs = Mahjongs()
mahjongs.shuffle()
for index,player in enumerate(players):
if index == 0:
for _ in range(14):
player.get_ma(mahjongs)
else:
for _ in range(13):
player.get_ma(mahjongs)
for player in players:
display(player)
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()
转载自原文链接, 如需删除请联系管理员。
原文链接:Python测试题及答案,转载请注明来源!