News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

js(0)

jk(0)

tag  

js(0)

date  

no datas

Python Experiment Eight Functions (Part 2)

posted on 2023-05-21 17:12     read(471)     comment(0)     like(1)     collect(3)


15. Duplicate element determination. Write a function that takes a list as an argument and returns True if an element appears more than once in the list, but does not change the value of the source list. Finally test the function in the main program.

def fun(ls):
    for n in ls:
        if ls.count(n) > 1:
            return True
    else:
        return False


def fun2(ls):
    return len(set(ls)) < len(ls)


ls = eval(input('请按照列表格式输入列表元素:'))
if fun(ls) == True:
    print('该列表中存在重复元素')
else:
    print('该列表中不存在重复元素')

if fun2(ls) == True:
    print('该列表中存在重复元素')
else:
    print('该列表中不存在重复元素')

output sample

Please enter the list elements in the list format: 11,16
There are no repeated elements in this list
There are no repeated elements in this list

16. Linearly convert the data in list a into data within the specified range, and store them in list b. Assume that the maximum value of the elements in list a is max_value, and the minimum value is max_value. When the value range of the data in the specified list b is [low, high], the transformation formula for linearly converting the element a[i] in the list a to the element b[i] in the list b is b[i]
= low+(a[i]-min_value)*(high-low)/(max_value-min-value)

import random


def transfer(a, low, high):
    b = []
    max_value = max(a)
    min_value = min(a)
    for p in a:
        new_value = low + (p - min_value) * (high - low) / (max_value - min_value)
        new_value = round(new_value, 4)
        b.append(new_value)
    return b


def transfer2(a, low, high):
    max_value = max(a)
    min_value = min(a)
    b = [round(low + (p - min_value) * (high - low) / (max_value - min_value), 4) for p in a]
    return b


a = [random.randint(1, 100) for i in range(10)]
print(a)
low = int(input("low:"))
high = int(input("high:"))
b = transfer(a, low, high)
print(b)

b = transfer2(a, low, high)
print(b)

output sample

[61, 89, 29, 42, 59, 65, 44, 84, 23, 86]
low:0
high:1
[0.5758, 1.0, 0.0909, 0.2879, 0.5455, 0.6364, 0.3182, 0.9242, 0.0, 0.9545]

17. Enter a string of characters as the password, and the password can only consist of numbers and letters. Write a function judge (password) to find the strength level of the password, and test the function in the main program, and output the corresponding password strength according to the input. The password strength judgment criteria are as follows (meeting one of them, the password is strengthened by one level): 1, there are numbers;
2, there are uppercase letters; 3, there are lowercase letters; 4, the number of digits is not less than 8.
Test data:

Please enter the test password: abc123
The password strength of abc123 is level 2
Please enter the test password: Abc123
The password strength of Abc123 is level 3
Please enter the test password: Abc12345
The password strength of abc12345 is level 4

def judge(password):
    level = 0

    n = len(password)
    if n >= 8:
        level += 1

    for ch in password:
        if '0' <= ch <= '9':
            level += 1
            break

    for ch in password:
        if 'A' <= ch <= 'Z':
            level += 1
            break

    for ch in password:
        if 'a' <= ch <= 'z':
            level += 1
            break

    return level


while True:
    s = input('请输入测试密码(直接回车为退出):')
    if s == '':
        break;

    level = judge(s)
    print(f'{s}的密码强度为{level}级')

output sample

Please enter the test password (directly press Enter to exit): ABc123456
The password strength of ABc123456 is level 4

18. The median is one of the common statistics, widely used in probability theory and statistics, and has important value in skewed distribution. For example, if you want to know the average wealth of people from a set of data, suppose 100 people earn 100 yuan a month, and 10 people earn 1,000,000 yuan. If you calculate the average value, you get 91,000 yuan, which is a strange value that does not show people the real situation at all. In this case, the median provides a more useful value and a better description. For lists with different numbers of elements, the median is calculated in the following two ways:
(1) If the number of elements in the list is odd, the median is the number in the middle of the sorted list.
(2) If the number of elements in the list is even, the median is the average of the two numbers in the middle of the sorted list.
Please write a function that takes a list argument, returns the median of the high list, and finally test the function in the main program.

import random


def median(ls):
    _ls = sorted(ls)
    _len = len(_ls)
    if _len % 2 == 0:
        return (_ls[_len // 2 - 1] + _ls[_len // 2]) / 2
    else:
        return _ls[_len // 2]


data = [random.randint(1, 100) for i in range(5)]
print(sorted(data))
print(median(data))

data = [random.randint(1, 100) for i in range(6)]
print(sorted(data))
print(median(data))

output sample

[2, 22, 57, 62, 84]
57
[44, 54, 69, 80, 81, 81]
74.5

insert image description here

import random
import math


def fun(ls):
    avg = sum(ls) / len(ls)

    ls2 = [(n - avg) ** 2 for n in ls]
    std = math.sqrt(sum(ls2) / (len(ls) - 1))
    variance = std ** 2

    return avg, std, variance


data = [random.randint(1, 100) for i in range(5)]
print(data)
print(fun(data))

data = [0, 8, 12, 20]
print(data)
print(fun(data))

data = [8, 9, 11, 12]
print(data)
print(fun(data))

output sample

[2, 16, 15, 84, 66]
(36.6, 36.052739146977444, 1299.8)
[0, 8, 12, 20]
(10.0, 8.32666399786453, 69.33333333333333)
[8, 9, 11, 1 2]
(10.0, 1.8257418583505538, 3.3333333333333335)

20. Define a function delSame(li), the parameter li is a list; this function returns a new list, the new list does not contain repeated elements, and only the elements that appear in the original list for the first time are kept. If the original list is [1,2,3,4,5,2,1,4,5,3,8,8,9], the processed list is [1,2,3,4,5, 8,9]. Define and initialize a list in the main program, call this function, output this function, and output a new list.

import random


def delSame(ls):  # 此方法可以保持元素的原始顺序
    t = []
    for p in ls:
        if p not in t:
            t.append(p)
    return t


def delSame2(ls):
    return list(set(ls))  # 使用集合去重,但不能保持元素的原始顺序


data = [random.randint(1, 100) for i in range(12)]
print(data)
print(delSame(data))
print(delSame2(data))

data = [1, 2, 3, 4, 5, 2, 1, 4, 5, 3, 8, 8, 9]
print(data)
print(delSame(data))
print(delSame2(data))

output result

[69, 75, 3, 54, 3, 100, 93, 12, 25, 75, 9, 86] [69, 75, 3, 54, 100, 93, 12, 25, 9, 86] [3
,
100 , 69, 9, 75, 12, 54, 86, 25, 93]
[1, 2, 3, 4, 5, 2, 1, 4, 5, 3, 8, 8, 9] [1, 2,
3 , 4, 5, 8, 9]
[1, 2, 3, 4, 5, 8, 9]

21. A company uses a public phone to transmit data. The data (plain text) is 4 digits and encrypted during transmission. The encryption rule: add 5 to each number, and then replace the number with the remainder divided by 10 , then swap the first and fourth digits, and the second and third digits. If the plaintext is "1234", the ciphertext is "9876"; if the plaintext is "2345", the ciphertext is "0987".
(1) Define a function encrypt(s), the parameter s is a 4-digit string, and this function returns the ciphertext according to the encryption rules.
(2) Enter the plaintext in the main program, call the encryption function, and enter the ciphertext.

def encrypt(s):
    li = [str((int(i) + 5) % 10) for i in s]
    li.reverse()
    return ''.join(li)


s = input('input plaintext:')
print(f'明文:{s},密文:{encrypt(s)}')

output sample

input plaintext: 4567
plaintext: 4567, ciphertext: 2109

22. Find all the integers x in the closed interval [low, high] that satisfy the values ​​of x*x and whose digits are different from each other. For example, enter the values ​​of low and high respectively: 2000, 2100. The integers and their squares that satisfy the conditions in the range [2000,2100] are as follows:

xx*x
20134052169
20274108729
20694280761
20954389025

Total is: 4

def isdiff(n):
    li = [0] * 10

    s = str(n)
    flag = True

    for i in s:
        k = int(i)
        li[k] += 1
        if li[k] > 1:
            flag = False
            break

    return flag


def isdiff2(n):
    s = str(n)
    m = set(s)
    return len(m) == len(s)


low = int(input("low:"))
high = int(input("high:"))
print("x\tx*x")
k = 0
for n in range(low, high + 1):
    if isdiff(n * n) == True:
        print(f"{n}\t{n * n}")
        k += 1
print("总数为:", k)

output sample

low:2000
high:2300
xx*x
2013 4052169
2027 4108729
2069 4280761
2095 4389025
2123 4507129 2126 4519876
2175 4730625 2199 483560 1
2203 4853209 2277 5184729 Total: 10



23. For students' grades, students usually pay attention to their own grades while teachers often pay attention to the grades of the whole class. Now there is a dictionary (the key is the student number, the value is the grade), which stores the grades of several students, such as {"9601":95, "9602":96, "9603:87,..."}, where "9601 "Represents the student number, 95 represents the student's grade. Please write a program.
(1) Define a global dictionary to save students' grades.
(2) Define a function that accepts a parameter that represents the student number, and the function returns the grade corresponding to the student number in the dictionary. If the student number does not exist in the dictionary, the function returns -1.
(3) Define a function to output student information in descending order of grades, for example:
9602, 96
9601, 95
9603, 87
(4) Test these two functions in the main program.

dicScore = {
    '9601': 95,
    '9602': 96,
    '9603': 87,
}


def get_score(id):
    return dicScore.get(id, -1)


def sort_score():
    ls = sorted(dicScore.items(), key=lambda x: x[1], reverse=True)
    for i in ls:
        print(f'{i[0]},{i[1]}')


print(get_score('9602'))
sort_score()

output result

96
9602,96
9601,95
9603,87

24. A person's favorite color can reflect his personality, and the corresponding relationship between color and personality is shown in Figure 8-1.

Table 8-1
colorcharacter description
redlively and aggressive person
yellowintelligent theorist
blueromantic person
greenprudent and sensible person
PurplePeople who value beauty and individuality
blackmysterious and self-respecting person
Whitehonest person

Please write a program to realize the character color test. It is required to display 7 colors first when the program is running, and prompt the user to choose, and output the corresponding character description after the selected color; then ask the user whether to continue the test, if continue the test and repeat the previous operation, otherwise exit the program . Please design the function reasonably and test the function in the main program.

def menu():  # 显示用户颜色选择菜单
    print('1:红色\n2:黄色\n3:蓝色\n4:绿色')
    print('5:紫色\n6:黑色\n7:白色')
    while True:
        option = input("请输入您的选择(数字0-7,0代表停止测试):")
        if option.isdigit():
            return int(option)
        else:
            print('您输入的不是数字!')


def test(option):  # 根据颜色选项获取测试结果
    dic = {  # 用字典保存颜色与性格的对应关系
        1: "活泼而充满斗志的人",
        2: "智慧型的理论家",
        3: "浪漫的人",
        4: "谨慎而知性的人",
        5: "注重美感和个性化的人",
        6: "神秘而自尊的人",
        7: "诚实的人"
    }
    return dic.get(option, '颜色选择错误')


while True:
    op = menu()
    if op == 0:  # 输入0表示测试结束
        print('测试结束')
        break;
    result = test(op)
    print(result)
    print()

output sample

1: Red
2: Yellow
3: Blue
4: Green
5: Purple
6: Black
7: White
Please enter your choice (numbers 0-7, 0 stands for stop testing): 6
mysterious and self-respecting people

insert image description here

#25题
import random

fun = lambda n: n ** 2

data = [random.randint(1, 10) for i in range(5)]
print(data)
data2 = [fun(d) for d in data]
print(sum(data2))

output sample

[4, 2, 8, 10, 9]
265

#26题
import math

fun = lambda n: (1 + math.log(n)) / (2 * math.pi)

a = math.e ** 3
b = [fun(k) for k in range(1, 101)]
print(a + sum(b))

output result

93.89195084920446

#27题
def fun(n):
    if n == 1:
        return 1
    else:
        return fun(n - 1) + 1 / n


print(fun(1))
print(fun(2))
print(fun(10))
print(fun(100))
print(fun(500))

output result

1
1.5
2.9289682539682538
5.187377517639621
6.79282342999052

#28题
def fun(n):
    if n == 1:
        return 1 / 3
    else:
        return fun(n - 1) + n / (2 * n + 1)


print(fun(1))
print(fun(2))
print(fun(10))
print(fun(100))
print(fun(500))

output result

0.3333333333333333
0.7333333333333334
4.409562711110699
48.85534134316012
248.4549709267233

#29题
def fun(n):
    if n <= 2:
        return n
    else:
        return fun(n - 1) + fun(n - 2) + fun(n - 3)


print(fun(1))
print(fun(2))
print(fun(3))
print(fun(9))     #当n为9时函数的值

output result

1
2
3
125



Category of website: technical article > Blog

Author:mmm

link:http://www.pythonblackhole.com/blog/article/25247/bd55a6f2960efd604168/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

1 0
collect article
collected

Comment content: (supports up to 255 characters)