简体   繁体   English

Python find() function 如何在下面的代码中工作?

[英]How does the Python find() function work in below code?

i was going through the solution for beautiful matrix(ques of CodeForces).Can you explain what is happening in the below code?我正在研究漂亮矩阵的解决方案(CodeForces 的问题)。你能解释一下下面的代码中发生了什么吗?

l=[2,1,0,1,2]
for i in l:
    s=input()
    if "1" in s:print(i+l[s.find("1")//2])

The code gives an error.该代码给出了一个错误。 The result is shown below:结果如下所示:

Traceback (most recent call last): File "main.py", line 3, in s=input() EOFError: EOF when reading a line回溯(最近一次调用最后一次):文件“main.py”,第 3 行,在 s=input() EOFError:读取一行时出现 EOF

You have a list of numbers.你有一个数字列表。 Then your iterating through each one such that i = 2, i = 1, .. etc. If the user input is 1 then it will print off whatever i currently is plus whichever input index has the 1 divided by 2 and floored.然后你遍历每一个,使得 i = 2,i = 1,.. 等。如果用户输入是 1,那么它将打印出 i 当前是什么加上任何输入索引具有 1 除以 2 并取底。

I would probably format like this我可能会像这样格式化

l=[2,1,0,1,2]
for i in l:
    s=input()
    if "1" in s:
        print(i+l[s.find("1")//2])

The code iterates through the given list of numbers, l.代码遍历给定的数字列表 l。 Then, for each of the elements in this list, it will ask the user for an input.然后,对于此列表中的每个元素,它将要求用户输入。 If the user input has a 1 in it, it will print the sum of the list element + the floored division by 2 (the // operators) of the index of the FIRST occurence in the user-inputted value.如果用户输入中有 1,它将打印列表元素的总和 + 用户输入值中第一次出现的索引的 2(// 运算符)的下限除法。 Note that the indexes start counting from 0. The floored division means a divison without commas, rounding to the nearest number on the lower side (eg 2.7 will be rounded to 2)请注意,索引从 0 开始计数。地板除法表示不带逗号的除法,四舍五入到下侧最接近的数字(例如 2.7 将四舍五入为 2)

The question is basically this:问题基本上是这样的:

How many steps are required to move a '1' to the center of a 5x5 matrix (The matrix has all values as '0' except a single position where it is '1')将“1”移动到 5x5 矩阵的中心需要多少步(该矩阵的所有值都为“0”,除了单个 position 为“1”)

The solution provided above is something like this:上面提供的解决方案是这样的:

//(2,2) is the final (center) position

l=[2,1,0,1,2] // l denotes the number of steps required if '1' was found in the ith row (for instance, 2 in the 0th row indicates that two steps would be required to move from 0th row to 2nd row)

for i in l:
    s=input() // s contains values for the ith row
    // If a "1" is present in the ith row, it would mean you need to move i position up/down to reach the center row
    // Let k = s.find("1"), k here gives the column in which the "1" is present. So, an additional k//2 steps would be required to move across the columns to reach the center
    // hence i (for row movement) + k(for column movement) steps would be required to reach the center
    if "1" in s:
        print(i+l[s.find("1")//2]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM