Python ----- Experiment 5 Homework 2

1. Short answer questions (5 questions in total, 100.0 points)

1 Write a function to implement selection method sorting. (Upload code and screenshot of running result)

correct answer:

def selectSort(lst, reverse=False):

    length = len(lst)

    for i in range(0, length):

        #假设剩余元素中第一个最小或最大

        m = i

        #扫描剩余元素

        for j in range(i+1, length):

            #如果有更小或更大的,就记录下它的位置

            exp = 'lst[j] < lst[m]'

            if reverse:

                exp = 'lst[j] > lst[m]'

            if eval(exp):

                m = j

        #如果发现更小或更大的,就交换值

        if m!=i:

            lst[i], lst[m] = lst[m], lst[i]

my answer:

def sort(A):

    for i in range(len(A)):

        min = i

        for j in range(i + 1, len(A)):  

            if A[min] > A[j]:  

                min = j

        A[i], A[min] = A[min], A[i]  



    print ('排序后的数组:', A)

A=list(map(int, input("输入要排序的数:").split()))

sort(A)

operation result:

Enter the number to sort: 5 4 78 36 1 6

Sorted array: [1, 4, 5, 6, 36, 78]

2 Write a function to realize the dichotomy search. (Upload code and screenshot of running result)

correct answer:

def binarySearch(lst, value):

    start = 0

    end = len(lst)

    while start < end:

        #计算中间位置

        middle = (start + end) // 2

        #查找成功,返回元素对应的位置

        if value == lst[middle]:

            return middle

        #在后面一半元素中继续查找

        elif value > lst[middle]:

            start = middle + 1

        #在前面一半元素中继续查找

        elif value < lst[middle]:

            end = middle - 1

    #查找不成功,返回False

    return False

my answer:

d

ef sort(A):

    for i in range(len(A)):

        min = i

        for j in range(i + 1, len(A)):  

            if A[min] > A[j]:  

                min = j

        A[i], A[min] = A[min], A[i]  



    print ('排序后的数组:', A)

A=list(map(int, input("输入要排序的数:").split()))

sort(A)





def Search(alist, item):

    n = len(alist)

    if n == 0:

        return False

    else:

        mid = n // 2

        if alist[mid] == item:

            return True

        elif item < alist[mid]:

            return Search(alist[: mid], item)

        else:

            return Search(alist[mid + 1:], item) 

        

item = int(input("搜索值:"))

print(Search(A,item))

operation result:

Enter the number to sort: 8 9 1 4 2 3

Sorted array: [1, 2, 3, 4, 8, 9]

Search value: 1

True

3 Write a function to find the longest increasing subsequence of a given sequence. (Upload code and screenshot of running result)

correct answer:

from itertools import combinations

from random import sample



def subAscendingList(lst):

    '''返回最长递增子序列'''

    for length in range(len(lst), 0, -1):

        #按长度递减的顺序进行查找和判断

        for sub in combinations(lst, length):

            #判断当前选择的子序列是否为递增顺序

            if list(sub) == sorted(sub):

                #找到第一个就返回

                return sub

def getList(start=0, end=1000, number=20):

    '''生成随机序列'''

    if number > end-start:

        return None

    return sample(range(start, end), number)



def main():

    #生成一个包含10个随机数的列表进行测试

    lst = getList(number=10)

    if lst:

        print(lst)

        print(subAscendingList(lst))



main()

operation result:

[608, 543, 915, 787, 545, 128, 930, 852, 844, 322]

(608, 915, 930)

4 Write a function to find the two numbers with the smallest difference in a given sequence. (Upload code and screenshot of running result)

correct answer:

import random



def getTwoClosestElements(seq):

    #先进行排序,使得相邻元素最接近

    #相差最小的元素必然相邻

    seq = sorted(seq)

    #无穷大

    dif = float('inf')

    #遍历所有元素,两两比较,比较相邻元素的差值

    #使用选择法寻找相差最小的两个元素

    for i,v in enumerate(seq[:-1]):

        d = abs(v - seq[i+1])

        if d < dif:

            first, second, dif = v, seq[i+1], d

    #返回相差最小的两个元素

    return (first, second)



seq = [random.randint(1, 10000) for i in range(20)]

print(seq)

print(sorted(seq))

print(getTwoClosestElements(seq))

operation result:

Original sequence: [2462, 6108, 330, 1112, 9219, 8152, 5373, 3708, 4292, 7772, 6783, 2107, 8479, 4355, 9791, 2815, 1456, 8381, 406, 6948]

After sorting: [330, 406, 1112, 1456, 2107, 2462, 2815, 3708, 4292, 4355, 5373, 6108, 6783, 6948, 7772, 8152, 8381, 8479, 9219, 9791]

Results: (4292, 4355)

5 Use Monte Carlo method to calculate the approximate value of pi. (Upload code and screenshot of running result)

correct answer:

from random import random



def estimatePI(times):

    hits = 0

    for i in range(times):

        x = random()*21 #random()生成介于0和1之间的小数

        y = random()*2 - 1 #该数字乘以2再减1,则介于-1和1之间

        if x*x + y*y <= 1:       #落在圆内或圆周上

            hits += 1

    return 4.0 * hits/times



print(estimatePI(10000))

print(estimatePI(1000000))

operation result:

3.1444

3.141404

Published 27 original articles · won 3 · views 1418

Guess you like

Origin blog.csdn.net/weixin_41860600/article/details/105484567