python作业03

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20

1

Please generate a random float where the value is between 5 and 95 using Python math module.

Use random.random() to generate a random float in [0,1].

分析:random.random()可以生成随机数

1
2
3
4
import random
x = random.random()
# random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
print(5+x*90)

image-20231007204145109

2

Please generate a random float where the value is between 10 and 100 using Python math module.

1
2
import random
print(10+random.random()*90)

image-20231007204258393

3

Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.

分析:二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
li =[1,3,4,6,8,10,15]
def search(x,l,r):
if l>r:
return "error"
elif l==r and li[l]!=x :
return "not found"
elif l==r and li[l]==x :
return l
elif li[(l+r)//2] == x :
return (l+r)//2
elif li[(l+r)//2]>x:
return search(x,l,(l+r)//2-1)
else :
return search(x,(l+r)//2+1,r)

for i in range(0,7):
print( "{}在第{}位".format(li[i],search(li[i],0,6)) )
image-20231007204501377

4

Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.

分析:二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
li =[1,3,4,6,8,10,15]
def search(x,l,r):
if l>r:
return "error"
elif l==r and li[l]!=x :
return "not found"
elif l==r and li[l]==x :
return l
elif li[(l+r)//2] == x :
return (l+r)//2
elif li[(l+r)//2]>x:
return search(x,l,(l+r)//2-1)
else :
return search(x,(l+r)//2+1,r)

for i in range(0,7):
print( "{}在第{}位".format(li[i],search(li[i],0,6)) )
image-20231007204501377

5

Please write a program which accepts basic mathematic expression from console and print the evaluation result.

分析:eval()可以把读入的字符串转换为数学表达式并计算

1
print(eval(input("请输入数学表达式:")))

image-20231007204856947

6

Please write assert statements to verify that every number in the list [2,4,6,8] is even.

分析:Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。

1
2
3
li=[2,4,6,8]
for i in li:
assert i%2==0

image-20231007205209335

7

Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.

分析:yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator

1
2
3
4
5
6
7
8
9
10
n = input("Please input n:")
n = int (n)
def fun():
i=0
while i*35<n:
yield i*35
i+=1

for i in fun():
print(i)

image-20231007212047286

8

Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.

1
2
3
4
5
6
7
8
9
10
11
12
n = input("please input n:")
n = int(n)
def fun():
i =0
while i<=n:
yield i
i+=2
for i in fun():
if i==n or i+1==n:
print(i)
else:
print(i,end=",")

image-20231007212202423

9

The Fibonacci Sequence is computed based on the following formula:

f(n)=0 if n=0

f(n)=1 if n=1

f(n)=f(n-1)+f(n-2) if n>1

Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console.

分析:递归

1
2
3
4
5
6
7
8
9
10
11
li=[]
def fun( n ):
if n==0:
return 0
elif n==1:
return 1
else :
return fun(n-1)+fun(n-2)
n = int (input("Please input n:"))
values = [str(fun(x)) for x in range(0,n+1)]
print(",".join(values))

image-20231007212325499

10

The Fibonacci Sequence is computed based on the following formula:

f(n)=0 if n=0

f(n)=1 if n=1

f(n)=f(n-1)+f(n-2) if n>1

Please write a program to compute the value of f(n) with a given n input by console.

1
2
3
4
5
6
7
8
9
def fun( n ):
if n==0:
return 0
elif n==1:
return 1
else :
return fun(n-1)+fun(n-2)
n=int(input("Please input n:"))
print(fun(n))

image-20231007212817429

11

Write a program to compute:

f(n)=f(n-1)+100 when n>0 and f(0)=1

with a given n input by console (n>0).

1
2
3
4
5
6
def f(n):
if n==0: return 0
else: return f(n-1)+100
n = int(input("Please input n:"))

print(f(n))

image-20231007221806889

12

Write a program to compute 1/2+2/3+3/4+…+n/n+1 with a given n input by console (n>0).

分析:递归

1
2
3
4
5
def f(n):
if n==0: return 0
else: return f(n-1)+n/(n+1)
n = float(input("Please input n:"))
print("{:.2f}".format(f(n)))

image-20231007221906161

13

Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.

1
2
3
s = input("input:")
u = str(s)
print(u)

image-20231007222013054

14

Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.

分析:考察正则表达式 re.findall()可以查找字符串中所有匹配模式的子串,并以列表的形式存储

1
2
3
4
5
import re
# 正则表达式
s = input("Please input a sequence:")
result1 = re.findall(r'\d+',s)
print(result1)

image-20231007222321205

15

Assuming that we have some email addresses in the “username@companyname.com“ format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only.

分析:正则表达式,re.sub()可以替换掉匹配模式的字符串

1
2
3
4
5
6
import re
# 正则表达式
s = input("Please input a sequence:")
s = re.sub(r'^\w+@',"",s)
companyname = re.sub(r'.com$',"",s)
print(companyname)

image-20231007222551570

16

Assuming that we have some email addresses in the “username@companyname.com“ format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only

1
2
3
4
import re
adress = input("please input a email adress:")
username = re.sub(r'@\w+.com',"",adress)
print(username)

image-20231007222856600

17

Define a custom exception class which takes a string message as attribute.

1
2
3
4
class MyError(Exception):
def __init__(self,msg):
self.msg = msg
error = MyError("something wrong")

image-20231007223008404

18

Write a function to compute 5/0 and use try/except to catch the exceptions.

分析:考察 异常

1
2
3
4
5
6
7
8
def f():
return 5/0
try:
f()
except ZeroDivisionError:
print("division by zero")
finally:
print ("In finally block for cleanup")

image-20231007223221881

19

Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape’s area is 0 by default.

分析:考察类的继承 和 方法的覆写

1
2
3
4
5
6
7
8
9
10
11
12
13
class Shape (object):
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self,l):
Shape.__init__(self)
self.length = l
def area(self):
return self .length*self.length
aSquare=Square(3)
print(aSquare.area())

image-20231007223558951

20

Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.

1
2
3
4
5
6
7
8
class Rectangle(object):
def __init__(self,l,w):
self.length =l
self.width = w
def area(self):
return self.length*self.width
a =Rectangle(2,5)
print(a.area())

image-20231007223702836


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论