实验四

task1

print(sum)
sum = 42
print(sum)
def inc(n):
    sum = n+1
    print(sum)
    return sum
sum = inc(7) + inc(7)
print(sum)

第一个sum,内置作用域.第二个sum变量名,第三个sum局部作用域,第四个sum全局作用域

task2.2

list1 = [1, 9, 8, 4]
print( sorted(list1) )
print( sorted(list1, reverse=True) )
print( sorted(list1, True) )

  对比结果可知,sorted中,reverse的传递方式使用关键字传递

task2.3

def func(a, b, c, /, *, d, e, f):
    return( [a,b,c,d,e,f] )
print(func(1,2,3,d=4,e=5,f=6))

 

 

 

task3

def solve(a, b, c):
    '''
    求解一元二次方程, 返回方程的两个根
    :para: a,b,c: int 方程系数
    :return: tuple
    '''
    delta = b*b - 4*a*c
    delta_sqrt = abs(delta)**0.5
    p1 = -b/2/a;
    p2 = delta_sqrt/2/a
    if delta>=0:
        root1 = p1 + p2
        root2 = p1 - p2
    else:
        root1 = complex(p1, p2)
        root2 = complex(p1, -p2)
    return root1, root2
print(solve.__doc__)
while True:
        try:
            a,b,c = eval(input('Enter eqution coefficient: '))
            if a == 0:
                raise
        except:
                print('invalid input, or, a is zero')
                break
        else:
            root1, root2 = solve(a, b, c)
            print(f'root1 = {root1:.2f}, root2 = {root2:.2f}')
            print()

task4

def list_generator(b,e,s=1):
    l=[]
    while b<e:
        l.append(b+s)
        b=b+s
    return l
list1 = list_generator(-5, 5)
print(list1)
list2 = list_generator(-5, 5, 2)
print(list2)
list3 = list_generator(1, 5, 0.5)
print(list3)

task5

def is_prime(n):
    if n==1:
        return False
    for i in range(2,n-1):
        if n%i==0:
            return False
            break
    else:
        return True
l1=[]
for i in range(2,21):
    if is_prime(i):
        l1.append(i)
l2=[]
for i in range(4,21):
    if i%2==0:
        l2.append(i)
for i in l2:
    for j in l1:
        if (i-j)in l1:
            print(f'{i}={j}+{i-j}')
            break

 task6

if __name__ == '__main__':
    main()
import string
s=input('输入英文文本:')
low=string.ascii_lowercase+'abcde'
upp=low.upper()
l=low+upp
def encoder(s):
    for i in s:
        if i.isalpha():
            s=s.replace(i,l[l.find(i)+5])
    return s
s2=encoder(s)
l2=l[::-1]
def decoder(s2):
    for i in s2:
        if i.isalpha():
            s2=s2.replace(i,l2[l2.find(i)+5])
    return s2
print(f'编码后的文本:{encoder(s)}')
print(f'对编码后的文本解码:{decoder(s2)}')

 

task7

def collatz(n):
    if n%2==0:
        n=n/2
        return n
    else:
        n=3*n+1
        return n
l=[]
try:
    n=eval(input())
    if n<0 or type(n)!=int:
        raise
except:
    print('Error:must be a positive integer')
else:
    l.append(n)
    while n!=1:
        n=int(collatz(n))
        l.append(n)
    print(l)

 

posted @ 2022-05-05 13:25  沉迷学习ing  阅读(18)  评论(2编辑  收藏  举报