实验四

实践任务1:

print(sum)
sum = 42
print(sum)

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

sum = inc(7) + inc(7)
print(sum)

截图:

 

 实践任务2.2:

list1 = [1, 9, 8, 4]

print( sorted(list1) )
print( sorted(list1, reverse=True) )
print( sorted(list1, True) )

截图:

 

 实践任务2.3:

def func(a, b, c, /, *, d, e, f):
    return( [a,b,c,d,e,f] )

print(func(1,2,3,d=5,e=6,f=7))

截图:

 

 实践任务3:

def solve(a,b,c):
    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

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()

截图:

 

 

 

 实验任务4:

def list_generator(begin,end,step=1):
    x = []
    i = begin
    while i >= begin and i<= end:
        x.append(i)
        i += step
    return x

list1=list_generator(-5, 5)
print(list1)

list2=list_generator(-5, 5, 2)
print(list2)

list3=list_generator(1, 5, 0.5)
print(list3)

截图:

 

 实践任务5:

def is_prime(n):
    if n < 2:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

h=[i for i in range(21)]
for x in h[::2]:
    for a in range(0,21):
        if is_prime(a) is True:
            if is_prime(x-a) is True:
                print(f'{x}={a}+{x-a}')
                break
            else:
                a=1+a
        else:
            a=1+a

截图:

 

 实践任务6:

def encoder(strs):
    a=list(strs)
    i=0
    while i <len(strs):
        b = ord(a[i])
        if 65<=b<=85 or 97<=b<=117:
            c=chr(b+5)

        elif 85<=b<=90 or 117<=b<=122:
            c=chr(b-21)
        else:
            c=chr(b)
        a[i]=c
        i+=1
    return ''.join(a)

def decoder(strs):
    a = list(strs)
    i=0
    while i < len(strs):
        b = ord(a[i])
        if 70<=b<=90 or 102<=b<=122:
            c=chr(b-5)
        elif 65<=b<=70 or 97<=b<=102:
            c=chr(b+21)
        else:
            c=chr(b)
        a[i] = c
        i+=1
    return ''.join(a)

a=input('输入英文文本: ')
print(f'编码后的文本:{encoder(a)}')
print(f'对编码后的文本解码:{decoder(encoder(a))}')

截图:

 

 

 

 实践任务7:

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

截图:

 

posted @ 2022-05-10 23:03  天天三顿  阅读(2)  评论(1编辑  收藏  举报