Data Structures and Algorithms Python version of the seventh week OJ jobs

1 quicksort main element (10 minutes)

Title Contents:

The famous fast sorting algorithm in a classic division of the process: We usually use some method takes an element as a principal component (in value), through the exchange, put it into the left side of the main yuan less than the elements than the main Yuan elements into its right. The arrangement of the N positive integers different from each other after a given division, PCA may I ask how many elements can be divided into pre-selected?

For example, the arrangement is given [1, 3, 2, 4, 5]. then:

  • 1 left no elements, the elements on the right than it is large, so it could be PCA;
  • Although the left element 3 than it is small, but its right 2 is smaller than it, so it can not be a principal component;
  • Although the right elements 2 than it is big, but it left three larger than it, so it can not be a principal component;

For similar reasons, 4 and 5 are likely to be the main element.
Accordingly, three elements may be Principal Component Analysis.

Input formats:

Row arrangement of a plurality of integers, separated by a space

Output formats:

In line 1, the output may be the number of elements of the main element; these elements are output in ascending order in the second row, separated by a space therebetween, end to end row may not have extra space.

Sample input:

1 3 2 4 5

Sample output:

3

1 4 5

Problem-solving ideas:

Determine a number is not a principal component, it is to see the number on the left is not smaller than it, than the number on the right is not it great attention and discussion alone and last element to consider only one element of the case

code:

def prin_element(a):
    b = []
    if len(a) == 1:
        b = a
    else:
        for i in range(1,len(a)-1):
            if a[i] > max(a[:i]) and a[i] < min(a[i+1:]):
                b.append(a[i])
        if a[0] < min(a[1:]):
            b.insert(0,a[0])
        if a[-1] > max(a[:-1]):
            b.append(a[-1])
    print(len(b))
    print(' '.join([str(i) for i in b]))



lst = list(map(int,input().split()))
prin_element(lst)

The first version of a bad 2 (10 minutes)

Title Contents:

There are N number of versions of the same product, the number is an integer from 1 to N; all of them from a version after version have been damaged. Given now a function isBadVersion, N digital input determines whether the version can be damaged (the output True if the damage); Find the first version of the corrupted.

Note: Sometimes isBadVersion function runs slowly, please pay attention to find ways to optimize

Input formats:

Two lines

The first line integer number N is the total number of products

Analyzing the behavior of a given second function, given a valid Python expression, can be used to read eval

Output formats:

A column of figures, represents a corrupted version

Sample input:

50

lambda n:n>=30

Sample output:

30

Problem-solving ideas:

Use cases, time limitations, the dichotomy take to speed up the search speed, pay attention to when the intermediate element when damaged version, it is also possible that the first version of a damaged

code:

N = int(input())
isBadVersion = eval(input())


def firstBadVersion(n):
    first = 1
    last = n
    while first < last:
        mid = (first + last) // 2
        if isBadVersion(mid):
            last = mid # 这里不能用mid-1,因为mid也有可能是第一个坏版本
        else:
            first = mid + 1
    return first


print(firstBadVersion(N))

3 is inserted and merging (10 minutes)

Title Contents:

Given the following definition:

Insertion sort is an iterative algorithm, to obtain input data one by one, gradually produce ordered output sequence. Each iteration, the algorithm an element taken from the input sequence, insert it into the correct position in the ordered sequence. So iteration until all the elements in order.

Iterative merge sort following actions: First, as the original sequence of N ordered subsequences contains only one element, and each iteration of the ordered merge two adjacent sequences, only one until the last ordered the sequence of.

Now given the original sequence and middle sequence generated by a sorting algorithm, the algorithm determines whether you what kind of sorting algorithm?

Input formats:

Two rows of numbers separated by spaces, which corresponds to the length of the list is equal to

The first line represents an ordered list, a list of the second line is the intermediate step of the process of sorting algorithms

Output formats:

First output Insertion Sort represent insertion sort, merge sort, or Merge Sort represented in the first line; then the output of the ranking algorithm iterate a sequence of results in the second row. Topic ensure each test result is unique. Between numbers separated by a space, and the line from beginning to end may not have extra spaces

Sample input:

3 1 2 8 7 5 9 4 0 6

1 3 2 8 5 7 4 9 0 6

Sample output:

Merge Sort

1 2 3 8 4 5 7 9 0 6

Sample Input 2:

3 1 2 8 7 5 9 4 6 0

1 2 3 7 8 5 9 4 6 0

Output Sample 2:

Insertion Sort

1 2 3 5 7 8 9 4 6 0

Problem-solving ideas:

Inserting the first observation sorted list, the list can be seen that the front part of the ordered list, with the front portion of the insert exactly the same sort, by determining whether this feature is insertion sort, merge sort otherwise

code:

def check(lst1,lst2):
    position = 0
    for i in range(len(lst1)-1):
        if lst2[i+1]<lst2[i]:
            position = i+1
            break
    if lst1[position:] == lst2[position:]: # 判断是否为插入排序
        lst2 = sorted(lst2[:position+1])+lst2[position+1:]
        print('Insertion Sort')
        print(' '.join([str(i) for i in lst2]))
    else: # 否则为归并排序
        cnt = 2
        lst = lst2
        while lst == lst2: # 对排序后的列表不断进行归并排序直到列表改变
            lst = [sorted(lst2[i:i+cnt]) for i in range(0,len(lst2),cnt)]
            lst = [num for sub_lst in lst for num in sub_lst]
            cnt *= 2
        print('Merge Sort')
        print(' '.join([str(i) for i in lst]))


lst1 = list(map(int,input().split()))
lst2 = list(map(int,input().split()))
check(lst1, lst2)
Released nine original articles · won praise 0 · Views 1029

Guess you like

Origin blog.csdn.net/Divine0/article/details/105302915