PYTHON Homework

Python作业

已更新至第八章:文件 模组

Python基本语法元素 习题

1.数据类型

  • 列表属于 序列 类型,元组属于 序列 类型,字典属于 映射 类型。
  • 集合内的元素是否可以重复 不可以

2.变量

  • 判断一下变量命名是否合法

    A._boy B. 4student C.class D.first number

    B,C, D错误 命名首字母不能是数字,class 为保留字,命名中间不能有空格

  • 请将1,2,3,4,5 打包赋值给变量 a,b,c,d,e

    a,b,c,d,e = 1,2,3,4,5

  • 请分别用下划线命名方式和驼峰体命名方式命名一个变量

    this_is_underline = 1

    ThisIsCamel = 2

3.控制语句

  • 分别简述 for 循环、while 循环和if分支语句的执行过程

    for i in iteration:

    ​ 代码

  • while(判断):

    ​ 代码

  • if ():

    ​ 代码

    else():

    ​ 代码

4.输入输出

  • 用input语句分别输入两个数字,并实现两个数字的相乘

a=eval(input(“please enter number a”))

b=eval(input(“please enter number b”))

print(a,b,”a times b = “,a*b)

  • 用 format 分别实现黄金分割比值 0.6180339887 保留前三位的浮点数输出以及保留一位小数的百分比输出

GOLDNUM = 0.6180339887

print(“{0:.3f},{0:.1%}”.format(GOLDNUM))

  • 将下列 X 处代码补全,实现如图所示的格式化输出

    for i in [0,1,2,3,4,5]:

    ​ print(“{X1}”.format(“X2”(2i+1)))

X1: 0:-^20

X2: *

5.程序格式

  • 一下格式是否符合 PEP8 的格式建议

    A x*=10 rectify: x *= 10

    B y = (3-1)/8 rectify: (3-1) / 8

    C t = (1,2,3,4,5) rectify: t = (1, 2, 3, 4, 5)

    D x = 10 rectify: x = 10

    E def fun(x = 1,y=2) rectify: def fun(x=1, y=2)

    F if m > 3: rectify: if m > 3:

    ​ print(“m大于3”) print(“m大于3”)

基本数据类型 习题

3.1.PNG

3.2.PNG

3.3.PNG

my answer:

填空题:

  • 6,400

  • 2.5,2

    2,3

  • 3.14,3

操作题

  • s[:6]

    s[-26:-21:-1]

  • s.title()

  • s.count(‘o’)

  • s.replace(“Python”,”C++”)

  • a = s.split(‘ ‘)

  • “*”.join(a)

  • a = bin(255)

    oct(255)

    hex(255)

    int(a,2) #binary case

判断题

  • F
  • T
  • F
  • T!!
  • T
  • F

复合的数据类型

image.png

1.

a = []
a
for i in range(1,101):
while(i%2 == 0):
a.append(i)
break
print(a)

2.

  • ls[2],ls[-3]
  • ls[1:4:2]
  • ls[::-1]

3.

  • ls.append(‘toyota’)

  • cars.insert(1,’chery’)

  • cars.extend([‘bmw’,’benz’])

  • cars.pop(3),cars.pop(3)

  • cars.remove(‘geely’)

  • cars[cars.index(‘chery’)] = ‘qq’

  • b = cars.copy() a = cars[:]

  • enternal:cars.sort() temporary: sorted(cars,reverse=false)

  • cars.reverse()

image.png

4.

  • 一旦定义,内部元素不可增删改查

5.

for food,prices in zip(food,prices):
print(‘The price of {} is {}’.format(food,prices))

6.BD不合法

7.

  • len()
  • dict[‘Jen’]
  • favorite_fruits[‘Tom’] = ‘peach’
    favorite_fruits[‘Bob’] = ‘Tomato’
  • del favorite_fruits[‘Judy’]
  • favorite_fruits.popitem()
  • favorite_fruits[‘Sarah’] = ‘watermelon’
  • for key,value in favorite_fruits.items():
    print("{}' favourite fruit is {} ".format(key,value))

image.png

8.

d = {}
for i in s:
d[i] = d.get(i,0)+1
print(d)

image.png

9.

  • vegetables.remove(‘meat’)

  • vegetables.add(‘eggplant’)

  • vegetables&fruits

  • vegetables|fruits

  • vegetables-fruits

  • vegetables^fruits

程序控制结构

image.png

  • 空的
  • true
  • true true

2.1

color = input(‘fetch a ball’)
if color == ‘black’:
print(‘you win 0 ‘)
elif color == ‘white’:
print(‘win 10’)
elif color == ‘blue’:
print(‘win 20’)
elif color == ‘pink’:
print(‘win 30’)
elif color == ‘purple’:
print(‘win 50’)

image.png

3.

for i in range(1, 10):
for j in range(1, i + 1):
print(“{} × {} = {}”.format(j, i, i * j), end=” “)
print()

4.

students_of_grande3_class2 = {}
flag = True
while flag:
first_input = input(‘please input your data’)
if first_input in [‘q’,’Q’]:
flag = False
print(‘program end’)
else:
second_input = input(‘please input second data’)
students_of_grande3_class2[first_input] = second_input

5.

死循环

6.代码难以阅读

7.拆分条件测试

函数-面向过程的编程

image.png

1.

  • T

  • T

  • a
    ('b', 'c', 'd')
    {'name': 'Sarah', 'age': 18}
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63

    2.

    ```python
    import random

    def main():
    win_rate_A, win_rate_B, number_of_games = get_input()
    win_A, win_B, = sim_n_games(win_rate_A, win_rate_B, number_of_games)
    print_summary(win_A, win_B, number_of_games)

    def get_input():
    win_rate_A = eval(input('please input win_rate of player A: '))
    while not 1>win_rate_A>0 :
    win_rate_A = eval(input('WARRING! win_rate of player A should be in (0,1), please input again: '))
    win_rate_B = round(1-win_rate_A,3)
    number_of_games = eval(input('please input number of total games: '))
    print('total games: {}:'.format(number_of_games))
    print('win_rate of player A: {}'.format(win_rate_A))
    print('win_rate of player B: {}'.format(win_rate_B))
    return win_rate_A, win_rate_B, number_of_games

    def sim_n_games(win_rate_A, win_rate_B, number_of_games):
    win_A, win_B = 0, 0
    count_A, count_B = 0, 0
    game_finish = False
    for i in range(number_of_games):
    game_finish = False
    while not game_finish:
    score_A, score_B = sim_one_game(win_rate_A, win_rate_B)
    if score_A > score_B:
    count_A += 1
    elif score_B > score_A:
    count_B += 1
    if count_A == 2:
    win_A += 1
    count_A, count_B = 0, 0
    game_finish = True
    elif count_B == 2:
    win_B += 1
    count_A, count_B = 0, 0
    game_finish = True
    return win_A, win_B

    def sim_one_game(win_rate_A, win_rate_B):
    score_A, score_B = 0, 0
    while not game_over(score_A, score_B):
    if random.random() < win_rate_A:
    score_A += 1
    else:
    score_B += 1
    return score_A, score_B

    def game_over(score_A, score_B):
    return ((score_A>=21)&(score_A-score_B>=2)) or ((score_B>=21)&(score_B-score_A>=2))

    def print_summary(win_A, win_B, number_of_games):
    print('total simulation:{}'.format(number_of_games))
    print('player A win {}'.format(win_A))
    print('player B win {}'.format(win_B))

    if __name__ == "__main__":
    main()

Output:

1
2
3
4
5
6
7
please input number of total games: 10000
total games: 10000:
win_rate of player A: 0.55
win_rate of player B: 0.45
total simulation:10000
player A win 8452
player B win 1548

image.png

3.

print(sorted(a.items(), key = lambda x : x[1], reverse = True))

类-面向对象的编程

image.png

image.png

1.

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    class UnionPay_Card():

    def __init__(self, user_name, card_credit, current_credit, single_quota):
    self.user_name = user_name
    self.card_credit = card_credit
    self.current_credit = current_credit
    self.single_quota = single_quota

    def get_card_attr(self):
    print('User name :{} '.format(self.user_name))
    print('Init credit:{} '.format(self.card_credit))
    print('Current credit:{} '.format(self.current_credit))
    print('Maxmium quota per withdrew:{} '.format(self.single_quota))

    def change_card_credit(self, card_crddit):
    if self.card_credit>=0:
    self.card_credit = card_crddit
    print("card_credit has changed to:{}".format(card_crddit))

    def cash(self, cash_number):
    if cash_number<=self.card_credit and cash_number<=self.current_credit and cash_number<= self.single_quota:
    print('You have cashed {} dollers!'.format(cash_number))
    self.current_credit -= cash_number
    else:
    print('Faild!')

2.

  • version one1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class BOC_Card(UnionPay_Card):

def __init__(self, user_name, card_credit, current_credit, single_quoto, score, discount_shop):
super().__init__(user_name, card_credit, current_credit, single_quoto)
# self.user_name = user_name
# self.card_credit = card_credit
# self.current_credit = current_credit
# self.single_quoto = single_quoto
self.score = score
self.discount_shop = discount_shop

def cash(self, shop_name, cash_number):
if cash_number<=self.card_credit and cash_number<=self.current_credit and cash_number<= self.single_quota:
if shop_name in self.discount_shop:
print('You enjoyed discount!!')
self.current_credit -= cash_number*0.95
self.score += cash_number*0.95//10
print('You have cashed {} dollers!'.format(cash_number*0.95))
else:
self.current_credit -= cash_number
print('You have cashed {} dollers!'.format(cash_number))
else:
print('Faild!')

def get_score(self):
print(self.user_name)
print(self.score)
  • v-modified
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class BOC_Card(UnionPay_Card):

def __init__(self, user_name, card_credit, current_credit, single_quoto, score):
super().__init__(user_name, card_credit, current_credit, single_quoto)
# self.user_name = user_name
# self.card_credit = card_credit
# self.current_credit = current_credit
# self.single_quoto = single_quoto
self.score = score
self.discount_shop = []

def cash(self, shop_name, cash_number):
if cash_number<=self.card_credit and cash_number<=self.current_credit and cash_number<= self.single_quota:
if shop_name in self.discount_shop:
print('You enjoyed discount!!')
self.current_credit -= cash_number*0.95
self.score += cash_number*0.95//10
print('You have cashed {} dollers!'.format(cash_number*0.95))
else:
self.current_credit -= cash_number
print('You have cashed {} dollers!'.format(cash_number))
else:
print('Faild!')

def get_score(self):
print(self.user_name)
print(self.score)

def add_discount_shop(self, discount_shop):
self.discount_shop.append(discount_shop)
print(self.discount_shop)

文件、异常和模块

image.png

1.

1
2
3
4
5
6
7
8
9
d = {}
with open('笑傲江湖.txt', 'r', encoding = 'gbk')as t:
ls = t.read()
for i in ls:
d[i] = d.get(i, 0)+1

with open('笑傲江湖_字数统计.txt', 'w', encoding = 'gbk')as t:
for k,v in d.items():
t.writelines('{}: {} \n'.format(k, v))

2.

1
2
3
4
5
6
7
8
while True:
try:
num = eval(input('Please input number(s)'))
except Exception:
print('what you have entered is not a number(s)')
else:
print('what you have entered is {}'.format(num))
break

3.

1
2
3
4
5
6
7
8
from screening_prime import *

def is_veg(n):
for a in range(n+1):
if is_prime(a):
print(a,end=' ')

is_veg(100)
  1. 附录

    判断是否为素数的程序:

    1
    2
    3
    4
    5
    6
    7
    8
    def is_prime(num):
    '''判断一个数是否为素数'''
    if num == 1:
    return False
    for i in range(2, int(sqrt(num)) + 1):
    if num % i == 0:
    return False
    return True

第九章 有益的探索()

image.png

image.png

image.png

第一题

[1, 1, 1]

[

[name:mary, id:2]

[name:mary, id:2]

[name:mary, id:2]

]

第二题

1.

1
2
3
4
5
6
7
8
9
10
11
12
13
from math import sqrt

def is_prime(num):
'''判断一个数是否为素数'''
if num == 1:
return False
for i in range(2, int(sqrt(num)) + 1):
if num % i == 0:
return False
return True


[i for i in range(1, 100) if is_prime(i)]

2.

1
2
3
4
5
6
from math import pow

x = [1, 2, 3, 4]
y = [0, 2, 3, 1]
z = [pow(x[i], y[i]) for i in range(len(x))]
z

3.

1
2
z = x if x > y else y
z

第三题:

1.有点难

2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
good = {'water':1.5, 'egg':1, 'meat':15}

def outer(good_name, number):
res = change(good_name, number)
print('happy midautumn')
return res*0.8





def change(good_name, number):
total = good[good_name]*number
if 5<number<11:
return total * 0.95
if number>10:
return total * 0.9
return total
分享到