- MysGln 的博客
solutions
- @ 2024-8-13 15:19:15
Programming exercise on 13 August
A
This problem asks to handle strings and loop structures like for statements.
According to the problem statement, it asks to find the minimum integer (or if none of them does) such that:
- ;
- the -th character of is
A; - the -th character of is
B; - the -th character of is
C;
Therefore, it is sufficient to scan for each in a for statement, and determine for each if it satisfies the condition. To obtain the -th character of , most programming language provides array subscript operator S[n].
Sample codes in Python follow. (When reading a sample code, note that the index differs by , since the initial character of a string is considered as S[0].)
def main():
N = int(input())
S = input()
ans = -1
for i in range(N-2):
if S[i] == 'A' and S[i+1] == 'B' and S[i+2] == 'C':
ans = i + 1
break
print(ans)
main()
B
This problem asks to determine if an integer is a multiple of an appropriately use an array.
To determine if is a multiple of , one can divide by and check if the remainder is .
In most programming languages, one can find the remainder using % operator. See also the sample code.
Sample code (Python):
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
result = []
for i in range(n):
if a[i] % k == 0:
result.append(a[i] // k)
print(*result)
main()
about *result
In Python, the
*resultsyntax is used to unpack the listresult, meaning it expands the list into individual elements. When you useprint(*result), each element in theresultlist is passed as a separate argument to theprint()function. Here's how it works:
print(result)would output the entire list as a single object, so ifresultis[1, 2, 3], it would print[1, 2, 3]print(*result)would unpack the list and print its elements separated by spaces. For the sameresultlist[1, 2, 3], it would print1 2 3.Using
*resultinprint()is useful when you want to display the elements of the list with spaces between them, rather than displaying the list structure itself
C
This problem asks to enumerate substrings and count them without duplicates.
In order to obtain a substring in Python, it is convenient to treat the string as a list and use the slicing feature
In order to remove duplicates, it is convenient to use a data structure called set.
Sample code (Python):
def main():
S = input()
N = len(S)
substrings = set()
for L in range(1, N + 1):
for i in range(N - L + 1):
substrings.add(S[i:i + L])
print(len(substrings))
main()