[Python] Solutions to AI programming exercises


Note: Since the programming language used in the course is Python, the problem solutions are implemented using Python programming. The problem solutions are for reference only. If you have better problem-solving ideas, please comment and discuss.

A. Logistic function

Question link:Logistic function.
Answer 1: Just write the Python expression based on the mathematical expression.

print("{:.1f}".format(1 / (1 + 2.71828 ** (-float(input())))))

Answer 2: Use the exp function of the math library to implement it.

from math import exp
print("%.1f" % (1 / (1 + exp(-float(input())))))

B. Circumference of a circle

Question link:Perimeter of a circle
Analysis: According to the area formula and perimeter formula given in the question, we can get the relationship between perimeter and area The relationship is C = 2 π S C = 2\sqrt{\pi S} C=2πS . Note that the question requires six decimal places, so π \pi The accuracy of π should be as high as possible, otherwise it may be WA.
Answer 1: Just write a Python expression based on the derived formula.

print("{:.6f}".format(2 * (3.14159265358979 * float(input())) ** 0.5))

Answer 2: You can also use the constant pi and sqrt functions that come with the math library.

import math
print("%.6f" % (2 * math.sqrt(math.pi * float(input()))))

C. Number of words

Question link:Number of words
Answer: Since matching is not case-sensitive, both the article and query words can be converted to Lowercase (or all converted to uppercase), and because the whole word is required to match, it can be divided directly according to spaces.

print(input().lower().split().count(input().lower()))

D. Reverse a string

Question link:Reverse string
Answer 1: Define the case conversion function f according to the question requirements, and then convert the reversed characters It exists in the list and can be reversed and output using the reverse method. Among them, the ord function that comes with Python can convert characters into ASCII codes, and the chr function can convert ASCII codes into characters.

def f(c):
	asc = ord(c)
	a_low, a_up = ord('a'), ord('A')
	if a_low <= asc <= ord('z'):
		return chr(asc - a_low + a_up)
	return chr(asc - a_up + a_low)

string = [f(char) for char in input()]
string.reverse()
print(''.join(string))

Answer 2: You can also use a dictionary to complete case conversion, and use [::-1] to reverse.

f = dict(zip(map(chr, range(ord('a'), ord('z'))), map(chr, range(ord('A'), ord('Z')))))
f.update(dict(zip(map(chr, range(ord('A'), ord('Z'))), map(chr, range(ord('a'), ord('z'))))))
print(''.join([f[c] for c in input()[::-1]]))

E. Reverse numbers

Question link:Reverse numbers
Answer: The idea is similar to reversing strings, no case conversion is required, but the input characters must be removed The last one in the string 0 0 0. Demand attention, 0 0 0 is contrary to this 0 0 0 needs to be considered separately.

num = input().rstrip('0')
print(num[::-1] if len(num) else 0)

F. Modified Linear Element

Question link:Corrected linear unit
Answer: Just judge whether the input number is a positive number. If it is a positive number, output it directly. If not, If the number is positive, output 0 0 0. For the last set of test data, since n n n is very large, so you cannot save all the input, otherwise MLE will occur. In addition, since ∣ x i ∣ |x_i| a>xi is very large. It takes a long time to convert it into an integer using the int function. It knows TLE, so it cannot be converted into an integer. You can directly determine whether the string starts with a negative sign. That’s it.

for _ in range(int(input())):
    x = input()
    print(0 if x.startswith('-') else x)

G. Score

Question link:Scoring
Answer: Use the max function and the min function to find the highest score and the lowest score, and average the other numbers. , and finally use the ceil function of the math library to round up.

from math import ceil
n = int(input())
scores = [int(input()) for _ in range(n)]
print(ceil((sum(scores) - max(scores) - min(scores)) / (n - 2)))

H. Improvisation

Question link:Cramming
Answer: Just sort everyone according to their scores.

data = []
for _ in range(int(input())):
    name, score = input().split()
    data.append([name, int(score)])
for output in sorted(data, key=lambda x: x[1], reverse=True):
    print(output[0])

I. Who won the second prize?

Question link:Who won the second prize
Answer: First use the max function to find the highest score, and then iterate through the results to find the second prize Just high scores.

index, second = None, -1
data = [tuple(map(int, input().split())) for _ in range(int(input()))]
best = max(data, key=lambda x: x[1])[1]
for num, score in data:
	if second < score < best:
		index, second = num, score
print(index)

J. Simple calculator

Question link:Simple calculator
Answer: The question seems complicated, but it actually means inputting a Python expression, outputting the value of the expression, and Replace the exponentiation symbol ^ with ** and then call the eval function to solve the problem.

[print(int(eval(input().replace('^', "**")))) for _ in range(int(input()))]

K. Days

Question link:Day of day
Answer: Obtain the year, month and date through string slicing, and then use the The number of days determines what day it is. Pay attention to the situation of leap years.

s = input()
y, m, d = int(s[:4]), int(s[4:6]), int(s[6:])
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0:
    days[1] += 1
print(sum(days[:m - 1]) + d)

L. Solve equations

Question link:Solve the equation
Solution: According to Fermat’s last theorem, the equation x n + y n = z n x^n + y^n = z^n xn+andn=Withn n > 2 n > 2 n>There is no positive integer solution for 2, so if and only if n = 1 n = 1 n=1 When there is an equation that has a positive integer solution, in other cases only the first two equations have positive integer solutions. For the last set of examples, the input n n n may be very large. Using int conversion is very slow and will cause TLE, so use string judgment directly n n n to be or not 1 1 1

print(1 if input() == '1' else 2)

M. High-altitude parabola

Question link:High-altitude parabola
Solution: The sum of geometric series. The distance traveled when first landing is h h h, the height of each subsequent bounce is h 2 \dfrac{h}{2} 2h, common ratio 1 2 \dfrac{1}{2} 21 is a geometric sequence. Since it is a one-up-and-down process after bouncing up and then landing, the distance traveled after each bounce is the first term is h h h, common ratio 1 2 \dfrac{1}{2} 21Geometric sequence of , number n n n needs to find the first part of this sequence n − 1 n - 1 n1 项和、GET到 2 h ( 1 − 2 1 − n ) 2h\left (1 - 2^{1-n } \right) 2h(121n), Distance from beginning to end h h h

h = int(input())
n = int(input())
p = 1 << (n - 1)
print(h + 2 * h * (p - 1) // p)

N. Seafood dinner

Question link:Seafood dinner
Answer: This question is essentially a list deduplication problem, but you can think differently, because seafood The maximum number of categories is 5 × 1 0 5 5 \times 10^5 5×105, so we use a length of 5 × 1 0 5 5 \times 10^5 5×10The list of 5 stores whether each type of seafood has been bought by Xiaowei. During the loop, every time a seafood comes, it is judged whether this type of seafood is Already have it, if not, mark it as yes, otherwise add one to the answer, so that the code is not only fast but also takes up very little memory.

ans = 0
seafoods = [False] * (5 * 10 ** 5 + 1)
for _ in range(int(input())):
	index = int(input())
	if seafoods[index]:
		ans += 1
	else:
		seafoods[index] = True
print(ans)

O. Least common multiple

Question link:Least common multiple
Answer: First use what you learned in elementary school< a i=4> Find by euclidean division method a a a sum b b The greatest common factor of b is based on the least common multiple and greatest common factor learned in primary school relationship ( a a a sum b b The product of the greatest common factor and the least common multiple of b is equal to a b ab ab) Calculated answer.

a, b = int(input()), int(input())
y, x = sorted([a, b])
while y:
	x, y = y, x % y
print(a * b // x)

P. Looking for books

Question link:Find books
Answer: Since the book numbers are in order, we use the binary search method. The specific method is, given n n n Book and number to look for t t t,前前找次 n 2 \dfrac{n}{2} 2n Is the number of this book t t t,As a result t t t, it is found, if than t t t is small, continue at 1 1 1 Book arrived n 2 \dfrac{n}{2} 2n This book will continue to use this method to find, if it is compared to t t t Great, in place n 2 \dfrac{n}{2} 2n Book arrived n n n In this book, we will continue to use this method until we find the number t t t, or if the range of the book you are looking for is empty, it means there is no book numbered t t t's book. The code implementation is a recursive function.

def find(books, num):
    n = len(books)
    if n == 0:
        return False
    if n == 1:
        return num == books[0]
    mid = n >> 1
    if num == books[mid]:
        return True
    if num < books[mid]:
        return find(books[:mid], num)
    else:
        return find(books[mid + 1:], num)

numbers = tuple(map(int, input().split()))
while True:
    query = int(input())
    if query == 0:
        break
    print('Y' if find(numbers, query) else 'N')

Q. Formation of troops

Question link:Arrangement
Answer: This is a search problem. It is necessary to find all possible battle situations and finally count the number. We use a set to store the full arrangement of everyone, and the arrangement is represented by a tuple. Since the set has its own deduplication function, the final answer is the length of the set. So how to get the full arrangement of everyone, write m m m for loops are enough, can write a recursive function f ( x , y ) f(x, y) f(x,y), inside x x x is a tuple, representing the result of the current traversal, x x The length of x indicates which for loop we are currently in, y y y is also a tuple, indicating which people have been traversed. Each time it is traversed, a for loop is used to remove the items that are not in y y y village person z z z Joined x x x During, afterward delivery f ( x + z , y + z ) f(x + z, y + z) < /span>f(x+z,and+ m m The effect of m for loops.

s = set()
n, m = map(int, input().split())
array = list(map(int, input().split()))

def dfs(now, indexes):
    if len(now) == m:
        s.add(now)
        return
    for i, a in enumerate(array):
        if i in indexes:
            continue
        dfs(now + (a,), indexes + (i,))

dfs((), ())
print(len(s))

R. Legality of brackets

Question link:Legality of brackets
Answer 1: Consider using a list to assist us in making judgments and traverse the string from left to right , if a left bracket is encountered, add it to the list. If a right bracket is encountered, see if the list is empty (because the list only stores left brackets). If it is not empty, take out a left bracket to match it. , if empty, it means that this right bracket does not have a matching left bracket. Finally, if the list is empty, it means that all left brackets have corresponding right brackets, otherwise it means that there are extra left brackets.

stack = []
for char in input():
	if char == '(':
		stack.append(char)
	elif len(stack):
		stack.pop()
	else:
		print('N')
		exit()
print('N' if len(stack) else 'Y')

Solution 2: Use the universal eval function. Because brackets can represent tuples, operators and function calls in Python, if the brackets are legal, then either no error will be reported after eval, or an error (TypeError) will be reported that the tuple cannot be called, otherwise it will report that it does not conform to the syntax. Specification error (SyntaxError), so use the eval function and exception handling statement to solve it.

try:
    eval(input())
    print('Y')
except TypeError:
    print('Y')
except SyntaxError:
    print('N')

S. first place

Question link:First place
Answer: In fact, it is to find the maximum value, just use the max function directly. However, the logic of comparing two scores here to determine who is higher and who is lower is very complicated. The max function can only be used to determine the total score or the score of a certain subject. That's okay, because we can operator overloading! Define a Score class and overload the greater than and less operator methods of this class.

N, M = map(int, input().split())

class Score:
    def __init__(self, name: int, scores: list):
        self.id = name
        self.score = scores
        self.total = sum(scores)
    
    def __eq__(self, other):
        if self.total != other.total:
            return False
        return self.score == other.score
    
    def __gt__(self, other):
        delta = self.total - other.total
        if delta > 0:
            return True
        if delta < 0:
            return False
        for m in range(M):
            delta = self.score[m] - other.score[m]
            if delta > 0:
                return True
            if delta < 0:
                return False
        return False
    
    def __lt__(self, other):
        delta = self.total - other.total
        if delta < 0:
            return True
        if delta > 0:
            return False
        for m in range(M):
            delta = self.score[m] - other.score[m]
            if delta < 0:
                return True
            if delta > 0:
                return False
        return False
    
    def __ge__(self, other):
        return self > other or self == other
    
    def __le__(self, other):
        return self < other or self == other

print(max([Score(i, list(map(int, input().split()))) for i in range(N)]).id + 1)

T. single-plank bridge

Question link:Single-plank bridge
Answer: This question seems to be a very complicated process, but you can think of it this way, when two people meet When they turned around, it was equivalent to two people passing each other directly. Therefore, the answer to this question is the maximum value of the maximum distance between all people walking north and the northernmost part of the bridge and the maximum value of the maximum distance between all people walking south and the southernmost part of the bridge.

L = int(input())
s, n = [0], [L]
for _ in range(int(input())):
    direction, distance = input().split()
    (s if len(direction) == 2 else n).append(int(distance))
print(max(max(s), L - min(n)))

U. Choose a gift

Question link:Choose a gift
Answer 1: First translate the question, given a length of n n For an array of n, what is the maximum sum of several consecutive numbers in it? Solve it with two loops to get 100 100 100 minutes, the outer loop traverses the starting value L L L, inner loop traversal termination value R R R, just find the maximum value.

n = int(input())
ans = -float("inf")
a = [int(input()) for _ in range(n)]
for i in range(n):
    s = 0
    for j in range(i, n):
        s += a[j]
        ans = max(ans, s)
print(ans)

Answer 2: In fact, one loop can solve this problem. Use variables s s s records the maximum value of the sum of the current array, variable m m m Record the answer. Initially, variable s = 0 s = 0 s=0, change amount m = − ∞ m = -\infty m=. Each time it is traversed, find the sum of the current array and update m ← max ⁡ { m , s } m \gets \max \lbrace m, s \rbrace mmax{ m,s}, the sum of the number combinations s < 0 s < 0 s<0, indicating that the previous numbers have had side effects, discard these numbers directly, and reset s = 0 s = 0 s=0. Full marks for this approach.

s, m = 0, -float("inf")
for _ in range(int(input())):
    s += int(input())
    m = max(m, s)
    if s < 0:
        s = 0
print(m)

V. Evenly matched

Question link:Equally matched
Solution 1: Use a two-level for loop to compare the difference in the number of questions answered by two students. Get 100 100 100 minutes.

n = int(input())
a = [int(input()) for _ in range(n)]
ans = 10 ** 6
for i in range(n):
    for j in range(i + 1, n):
        ans = min(ans, abs(a[j] - a[i]))
print(ans)

Answer 2: The two-level for loop is too slow. Consider sorting the number of questions for each student. Then the two closest students will definitely appear in adjacent positions in the sorted list and will get full marks.

n = int(input())
a = [int(input()) for _ in range(n)]
ans = 10 ** 6
a.sort()
for i in range(1, n):
    ans = min(ans, a[i] - a[i - 1])
print(ans)

W. Climb the stairs

Question link:Climbing stairs
Answer 1: For the sake of simplicity, let us first consider s = 2 s = 2 s=2, that is, Xiaowei can only walk up to two steps per step:

  • Result n = 1 n = 1 n=1, just exist 1 1 1 type;
  • Result n = 2 n = 2 n=2,Nana Yu 2 2 2 ways, that is, take two steps directly and take one step in two steps
  • Result n ≥ 3 n \ge 3 n3, then Xiaowei can start from n − 1 n - 1 n1 Single platform 1 1 Access directly from the 1 steps, or from the n − 2 n - 2 n2 steps one step at a time 2 2 2 steps are reached directly. Therefore, if we reach the n n The total number of ways of n steps is f ( n ) f(n) f(n),则有 f ( n ) = f ( n − 1 ) + f ( n − 2 ) f(n) = f(n-1) + f(n - 2) f(n)=f(n1)+f(n2)

Next, we consider s = 3 s = 3 s=3 circumstances:

  • Result n = 1 n = 1 n=1, just exist 1 1 1 type;
  • Result n = 2 n = 2 n=2,Nana Yu 2 2 2 ways, that is, take two steps directly or take one step in two steps;
  • Result n = 3 n = 3 n=3,Nana Yu 4 4 4 method, that is, take three steps directly, or take one step first and then two steps, or take two steps first and then one step, or divide it into three steps. Take only one step at a time;
  • Result n ≥ 4 n \ge 4 n4, then Xiaowei can start from n − 1 n - 1 n1 Single platform 1 1 Access directly from the 1 steps, or from the n − 2 n - 2 n2 steps one step at a time 2 2 It can be reached directly from the steps 2 or from the steps n − 3 n - 3 n3 steps one step at a time 3 3 3 steps are reached directly. Therefore, if we reach the n n The total number of ways of n steps is f ( n ) f(n) f(n),则有 f ( n ) = f ( n − 1 ) + f ( n − 2 ) + f ( n − 3 ) f(n) = f(n-1) + f(n - 2) + f(n - 3) f(n)=f(n1)+f(n2)+f(n3)

Let’s consider again s = 1 s = 1 s=1 circumstances:

  • Result n = 1 n = 1 n=1, just exist 1 1 1 kind method, immediately f ( 1 ) = 1 f(1) = 1 f(1)=1
  • Result n ≥ 2 n \ge 2 n2,also just have 1 1 1 ways (because you can only go up one staircase at a time), that is: f ( n ) = 1 f(n) = 1 f(n)= f(n)=f(n1)

What did you find?
Yes, if we use f ( n ) f(n) f(n)Display arrival n n The total number of ways of n steps, then when n ≥ s + 1 n \ge s + 1 ns+1 time, exists f ( n ) = ∑ i = n − s n − 1 f ( n − i ) f(n) = \sum_{i=n-s}^{n-1}f(n-i) f(n)=i=nsn1f(ni) Isn’t this something similar to the Fibonacci sequence. Finally, we need to note that we only need to save the last two digits of this sequence, otherwise MLE will occur. The following code can get 100 100 100 minutes.

s, n = int(input()), int(input())
f = [1, 2, 4][:s]
if n <= s:
	print(f[n - 1] % 100)
else:
	for _ in range(n - s):
	    f.append(sum(f[-s:]) % 100)
	print(f[-1])

Answer 2: If you want to get full marks, you need to consider s ≤ 10 s \le 10 sIn the case of 10, we actually need to calculate f f f in front of the target s s s 项, n ≤ s n \le s ns time, exist f ( n ) = 1 + ∑ i = 1 n − 1 f ( i ) f(n) = 1+\sum_{i=1}^{n-1}f(i) f(n)=1+i=1n1f(i) f ( 1 ) = 1 f(1) = 1 f(1)=1 f ( 2 ) = 2 f(2) = 2 f(2)= 1 = 2 n − 1 f(n) = 1 + \sum_{i=1}^{n-1}2^{i-1} = 2^{n-1} f(n)=1+i=1n12i1=2n1In this way, f f < /span>f is initialized to length s s s list. In addition, since n n n is extremely large. The for loop will definitely TLE in the end, so you need to find the sequence f f f The last two digits of the cycle period.

s = int(input())
f = [(2 ** p) % 100 for p in range(s)]
while True:
    f.append(sum(f[-s:]) % 100)
    if f[:s] == f[-s:]:
        f = f[:-s]
        break
print(f[int(input()) % len(f) - 1])

X. Sum of squares

Question link:Sum of squares
Answer 1: Get the sequence { a n } \lbrace a_n \ rbrace { an} Target formula a n = 10 a n − 1 + 8 a_n = 10a_{n-1} + 8 an=10an1+8, you can get it by summing with a for loop 100 100 100 minutes.

a, s = 8, 0
for _ in range(int(input())):
    s += a ** 2
    a = 10 * a + 8
print(s)

Answer 2: For the last two test data, n n n is relatively large, and the for loop summation will be TLE, so you need to do some simple mathematics derivation.
Let { b n } \lbrace b_n \rbrace { bn} This is the number of people 9 9 9 sequence, immediately a n = 8 9 b n a_n = \dfrac{8}{9}b_n an=98bn,于是 S n = ∑ i = 1 n a i 2 = 8 2 9 2 ∑ i = 1 n b i 2 = 64 81 ∑ i = 1 n ( 1 0 i − 1 ) 2 = 64 81 ∑ i = 1 n ( 1 0 2 i − 2 × 1 0 i + 1 ) \begin{alignat}{2} S_n & = \sum_{i=1}^{n}a_i^2 \nonumber \\ & = \dfrac{8^2}{9^2}\sum_{i=1}^{n}b_i^2 \nonumber \\ & = \dfrac{64}{81}\sum_{i=1}^{n}(10^i - 1)^2 \nonumber \\ & = \dfrac{64}{81}\sum_{i=1}^{n}\left(10^{2i} - 2 \times 10^i + 1\right) \nonumber \end{alignat} Sn=i=1nai2=9282i=1nbi2=8164i=1n(10i1)2=8164i=1n(102i2×10i+1) Inside: ∑ i = 1 n 1 0 2 i = 1010 ⋯ 10 ⏟ n 个 10 0 \sum_{i=1}^{n}10^{2i} = \underbrace{1010 \cdots 10}_{n个10}0 i=1n102i=n10 1010100 ∑ i = 1 n 2 × 1 0 i = 22 ⋯ 2 ⏟ n 个 2 0 \sum_{i=1}^{n}2 \times 10^i = \underbrace{22 \cdots 2}_{n个2}0 i=1n2×10i=n2 2220 ∑ i = 1 n 1 = n \sum_{i=1}^{n}1 = n i=1n1=n So we can directly obtain S n S_n Sn

n = int(input())
print(((int("10" * n) - int('2' * n)) * 10 + n) * 64 // 81)

Y. play games

Question link:Playing games
Answer 1: First translate the question, given a length of n n n numerical combination h h h,从 h h Take out some numbers from h and make sure that these numbers are monotonous and do not decrease. Ask how many numbers can be taken out at most. The final answer is the number of numbers minus one (because the question It’s the number of moves, not the number of pillars). We assume g ( i ) g(i) g(i) From display h i h_i hi is the longest length of the monotonic non-decreasing sequence at the end, then it is not difficult to write the recurrence formula g ( i + 1 ) = max ⁡ { 1 , max ⁡ j < i , h j ≤ h i { g ( j ) + 1 } } g(i + 1) = \max \lbrace 1, \underset{j < i, h_j \le h_i}{\max} \lbrace g(j) + 1 \rbrace \rbrace g(i+1)=max{ 1,j<i,hjhimax{ g(j)+1}} The final answer is max ⁡ 1 ≤ i ≤ n { g ( i ) } \underset{1 \le i \le n}{\max} \lbrace g(i) \rbrace 1inmax{ g(i)},可得 100 100 100 minutes.

n = int(input())
g = [1] * n
h = [int(input()) for _ in range(n)]
for i in range(1, n):
    g[i] = max([g[i]] + [g[j] + 1 for j in range(i) if h[j] <= h[i]])
print(max(g) - 1)

Solution 2: Suppose f ( x ) f(x) f(x) Display h h h Medium-term longevity x x The minimum value of the last number in the sequence of x, initial order x = 0 x = 0 x=0, after the beginning, the result is h i ≥ f ( x ) h_i \ge f(x) hif(x),则更新 f ( x + 1 ) = h i f(x + 1) = h_i f(x+1)=hi,并集 x x Add one to the value of x if h i < f ( x ) h_i < f(x) hi<f(x),就从后往前更新 f ( x ) , f ( x − 1 ) , ⋯   , f ( 1 ) f(x),f(x-1),\cdots,f(1) f(x),f(x1),,f(1), j j j 满足 f ( j − 1 ) ≤ h i < f ( j ) f(j - 1) \le h_i < f(j) f(j1)hi<f(j) , fruitful, Explanation length j j The last number of the sequence of j has a smaller value h i h_i hi. Full marks for this approach.

f = [0]
for _ in range(int(input())):
	h = int(input())
    if h >= f[-1]:
        f.append(h)
    else:
        for i in range(len(f) - 1, 0, -1):
            if f[i - 1] <= h < f[i]:
                f[i] = h
print(len(f) - 2)

Guess you like

Origin blog.csdn.net/qq_56131580/article/details/134173760