The seventh day of learning python --- basic advanced

1. Array flipping

insert image description here

One way of writing: myself

The slice is too good

a[:size]=a[:size][::-1]

First take out the first size number, and then flip it.
It is necessary to pay attention to the rules of left-closed and right-open intervals in the slicing operation

n,size=map(int,input().split())
a=list(map(int,input().split()))
a[:size]=a[:size][::-1]
for i in range(n):
    print(a[i],end=' ')

Writing method 2: function

n, m = map(int, input().split())

a = list(map(int, input().split()))

def reverse(a, size):
    for i in range(size // 2):
        a[i], a[size - 1 - i] = a[size - 1 - i], a[i]

reverse(a, m)

for x in a:
    print(x, end = " ")

Writing method three:

n, s = map(int, input().split())
a = input().split()
print(*reversed(a[:s]), *a[s:])

Second, copy the array

insert image description here

Writing method one:

lambda x: int(x) is an anonymous function that converts a string argument x to an integer and returns that integer. Normally, the int() function in Python converts a string argument to an integer. Lambda functions provide a convenient way to define a function, typically in cases where functions need to be passed as arguments to other functions.

al,bl,size = map(lambda x:int(x),input().split(" "))
a = list(map(lambda x:int(x),input().split(" ")))
b = list(map(lambda x:int(x),input().split(" ")))

def copy(a,b,size):
    for i in range(size):
        b[i] = a[i]
    return b

print(*copy(a,b,size))

Writing method two:

n,m,s=map(int,input().split())
a=list(input().split())
b=list(input().split())
def copy(a,b,s):
    b[:s]=a[:s]
copy(a,b,s)
for i in range(m):
    print(b[i],end=' ')

Writing method three:

n, m, s = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(*(a[:s] + b[s:]))

3. Least Common Multiple

insert image description here
The least common multiple and the greatest common divisor are things that I haven't quite figured out, but I figured it out a bit now.

Writing method one:

lcm(a,b) = a * b / gcd(a,b)

Among them, gcd(a,b) is the greatest common divisor of a and b. This formula is based on the simple fact that the product of two numbers is equal to the product of their greatest common divisor and least common multiple. So we only need to find their greatest common divisor, and then we can divide their product by the greatest common divisor to get the least common multiple.

The gcd function here implements finding the greatest common divisor of two integers. It is implemented in a recursive manner, that is, the remainder is continuously replaced with a larger number until the remainder is 0. This is a classic Euclidean algorithm, also known as division by roll.

def gcd(a, b):
    return a if b == 0 else gcd(b, a % b)
a, b = list(map(int, input().split()))
c = gcd(a, b)
print(a * b // c)

Writing method two:

This code implements finding the least common multiple of two integers.

The parameters of the function lcm are two integers a and b, by enumerating all possible least common multiples starting from max(a, b), when encountering the first number that can be divisible by a and b at the same time, output the number and Break out of the loop.

In the main program, first read in two integers a and b, then call the function lcm, and pass them in as parameters. The execution result of the function lcm is to output the least common multiple of these two integers.

def lcm(a,b):
    for i in range(max(a,b),a * b + 1):
        if i % a == 0 and i % b == 0:#用的就是他的定义,遍历啦
            print(i)
            break
s = list(map(int,input().split(' ')))
a = s[0]
b = s[1]
lcm(a,b)

Writing method three:

gcd

from math import gcd

from math import gcd
a = list(map(int,input().split()))
print(a[0]*a[1]//gcd(a[0],a[1]))

Writing four:

def gcd (m, n):

    if n > m:
        m, n = n, m

    if m % n == 0:
        return n

    return gcd (n, m % n)

def lcm(m, n):

    return  m * n // gcd(m, n)

m, n = map(int, input().split())
print(lcm(m, n))

Other: add two numbers

I never thought I could write like this

x, y = map(float, input().split())
print(f'{
      
      x + y:.2f}')

You can also write like this

print("%.2f" % sum(list(map(float, input().split()))))

Other: print numbers

a=input().split()
print(*a[:size],end=' ')

4. Sorting

sort by dictionary
insert image description here

This code implements the full arrangement of output 1~n.

First, read in an integer n representing the length of the array.

Define a global variable list nums with a length of 10 to store the permutation results; define a global variable list st with a length of 10 to indicate whether the number has been used.

Then define a depth-first search function dfs, which means enumerating the number at the uth position in the current arrangement. If u==n, that is, after enumerating all positions, output the current arrangement result.

Inside the function, traverse all numbers from 1 to n, if the current number is not used, mark it as used, store it in the nums array, and then continue to search for the next position, that is, call dfs(u+1). If the end of the permutation is reached, i.e. u==n, the current permutation is output.

Finally, call dfs(0) at the outermost layer of the program to start searching for the permutation results.

n = int(input())
N = 10
nums = [0] * N
st = [False] * N

def dfs(u):
    if u == n:
        print(*nums[:n])
        return
    for i in range(1, n + 1):
        if st[i] == False:
            st[i] = True
            nums[u] = i
            dfs(u + 1)
            st[i] = False

dfs(0)

Five, go square

insert image description here

Writing method one:

n,m=map(int,input().split())
ans=0
def f(a,b):
    if a==n and b==m:
        return 1
    if a>n or b>m:
        return 0
    return f(a+1,b)+f(a,b+1) 

print(f(0,0))

Writing method two:

global is a global variable!

n, m = map(int, input().split())
res = 0

def dfs(a, b):
    global res
    if a == n and b == m:
        res += 1
    else:
        if a < n:
            dfs(a + 1, b)
        if b < m:
            dfs(a, b + 1)
dfs(0, 0)
print(res)

Writing method three:

n, m = map(int, input().split())
def f(a, b):
    if a < 0 or b < 0:
        return 0
    if a == 0 and b == 0:
        return 1
    return f(a - 1, b) + f(a, b - 1)
print(f(n, m))

6. Array deduplication

insert image description here

Writing method one:

Specifically, Counter(a) returns a dictionary in which each element is a different element in list a, and the corresponding value is the number of times that element occurs in the list. Therefore, len(Counter(a)) returns the number of distinct elements. In addition, it should be noted that this code may have efficiency problems. Since the Counter function needs to traverse the entire list, there may be a certain time complexity problem for large-scale lists. If you need to optimize performance, you can consider using other algorithm implementations.

from collections import Counter
n = int(input())
a = list(map(int, input().split()))
print(len(Counter(a)))

Writing method two:

def unique(a):
    return len(set(a))

m = map(int, input().split())
lst = list(map(int, input().split()))
print(unique(lst))

Writing method three:

n = int(input())
data = list(map(lambda x:int(x),input().split(" ")))

def get_unique_count(data,n):
    res = {
    
    }
    c = 0
    for d in data:
        if res.get(d,False):
            continue 
        else:
            res[d] = d
            c+=1
    return c

print(get_unique_count(data,n))

Seven, triple sorting

insert image description here

n = int(input())
res = []
for i in range(n):
    n = list(input().split())
    res.append((int(n[0]), float(n[1]), n[2]))
res.sort(key=lambda x: x[0])
for i in res:
    print("{} {:.2f} {}".format(*i))

Guess you like

Origin blog.csdn.net/qq_51408826/article/details/129418548