在一个列表中找到两个数字的接近程度是否有方法?

huangapple go评论61阅读模式
英文:

Is there a way to find the proximity in two numbers in a list?

问题

我试图编写一个程序,接收一个整数列表,并返回每个项目在列表中距离最近的0的接近程度列表。

例如:[5, 0, 8, 87, 96, 0, 54]
应返回 [1, 0, 1, 2, 1, 0, 1]

我尝试创建一个索引来监控进程,然后创建一个循环来查找它们,但最终超出了列表范围。

英文:

I was trying to write a program that received a list of intengers and return a list with the proximity of each item in the list to the closest number 0.

Ex: [5, 0, 8, 87, 96, 0, 54]
It should return [1, 0, 1, 2, 1, 0, 1]

I tried creating an index to monitor the process and then creating a loop to look through them "while list[index] != 0" but it ended up going out of the list range.

答案1

得分: 2

使用for循环来迭代列表。确保在正向和反向两个方向都获得距离的最简单方法是简单地正向和反向迭代:

>>> def zero_proximity(nums):
...     result = [len(nums) for _ in nums]
...     for d in (+1, -1):
...         p = len(nums)
...         for i in range(len(nums))[::d]:
...             if nums[i] == 0:
...                 p = 0
...             else:
...                 p += 1
...             result[i] = min(result[i], p)
...     return result
...
>>> zero_proximity([5, 0, 8, 87, 96, 0, 54])
[1, 0, 1, 2, 1, 0, 1]

这是代码示例的翻译部分。

英文:

Use a for loop to iterate over the list. The easiest way to make sure you get the distance in both directions is to simply iterate forward and backward:

>>> def zero_proximity(nums):
...     result = [len(nums) for _ in nums]
...     for d in (+1, -1):
...         p = len(nums)
...         for i in range(len(nums))[::d]:
...             if nums[i] == 0:
...                 p = 0
...             else:
...                 p += 1
...             result[i] = min(result[i], p)
...     return result
...
>>> zero_proximity([5, 0, 8, 87, 96, 0, 54])
[1, 0, 1, 2, 1, 0, 1]

答案2

得分: 0

我相信这个问题可以相对容易地通过数组解决:

arr_num = np.array([5, 0, 8, 87, 96, 0, 54])
num_of_0 = np.sum(arr_num == 0)
dist_to_0 = np.empty(len(arr_num),dtype=int)

for i in np.argsort(arr_num):
    dist_to_0[i] = min([abs(i-j) for j in np.argsort(arr_num)[:num_of_0]])

这段代码使用了np.argsort函数来获取数组中每个元素需要关联的索引,以使数组按升序排列。零值首先出现在排序后的数组中,其余元素具有与零值的排序索引相关联的排序索引。在提供的示例中,np.argsort(arr_num)等于np.array([1, 5, 0, 2, 6, 3, 4]),其中1和5是零值的索引,依此类推。

现在,对于arr_num的每个元素,我们需要计算到零值的最小差值,方法是取相应索引之间的差值的绝对值,这是通过使用列表推导语法创建这些差值列表,然后取最小值来完成的。这个值保存在一个新数组dist_to_0中。对于零值,它将必然为0,对于其余元素,它将是正确的距离。

如果你的数字列表包括负值,你需要将np.argsort的参数替换为abs(arr_num)

英文:

I believe this question can be solved with arrays relatively easily:

arr_num = np.array([5, 0, 8, 87, 96, 0, 54])
num_of_0 = np.sum(arr_num == 0)
dist_to_0 = np.empty(len(arr_num),dtype=int)

for i in np.argsort(arr_num):
    dist_to_0[i] = min([abs(i-j) for j in np.argsort(arr_num)[:num_of_0]])

This code uses the function np.argsort to obtain the indices that each element of the array would need to have associated, in order to have the array in ascending order. The zeros appear first in the ordered array, and the rest of the elements have an ordered index that can be related to the ordered index of the zeros. In the example provided, np.argsort(arr_num) is equal to np.array([1, 5, 0, 2, 6, 3, 4]), where the 1 and 5 are the indices of the zero elements and so on.

Now, for each element of arr_num, we need to compute the minimum difference to the zeros, by taking the absolute value of the difference of the corresponding indices, which is done creating a list of these differences with the list comprehension syntax, and then taking the minimum. This value is saved in a new array, dist_to_0. It will necessarily be 0 for the zeros, and the correct distance for the rest.

If your number list includes negative values, you need to replace the np.argsort argument with abs(arr_num).

答案3

得分: 0

让我们迭代您的列表,每次我们看到一个0,我们将记住该零在列表中的索引。当我们达到列表中的下一个0时,我们将决定介于它们之间的数字,这相当简单。从 last_0_seen 索引到中间将更接近第一个0,从中间索引到当前索引(其值为0)将更接近第二个0。唯一的特殊情况是第一个和最后一个0,它们之前和之后的数字应该处理。

list = [5, 0, 8, 87, 96, 0, 54]
distance = []  # 结果将存储在这个列表中

last_0_seen = -1
for index, value in enumerate(list):
    if value == 0 and last_0_seen == -1:  # 如果是第一个0
        new_distances = [*range(index + 1)]
        new_distances.reverse()
        distance.extend(new_distances)
        last_0_seen = index
    elif value == 0 and last_0_seen != -1:
        mid_index = (last_0_seen + index) // 2
        first_part_distance = [*range(1, mid_index - last_0_seen + 1)]
        second_part_distance = [*range(0, index - mid_index)]
        second_part_distance.reverse()
        distance.extend(first_part_distance + second_part_distance)
        last_0_seen = index

distance.extend([*range(len(list) - len(distance))])  # 处理最后一个0之后的数字

以上是您提供的代码的翻译部分。

英文:

Let's iterate your list, every time we see a 0, we're gonna remember the index of that zero in the list. When we reach the next 0 in the list, we're gonna make decision about the numbers in between, which is pretty straight forward. From the last_0_seen index to the middle will be closer to the first 0, and from the middle index to the index we are at now (which its value is 0) will be closer to the second 0. The only special cases are the first and the last 0, which the numbers before and after them should be handled.

list = [5, 0, 8, 87, 96, 0, 54]
distance = []  # the result will be in this list

last_0_seen = -1
for index, value in enumerate(list):
    if value == 0 and last_0_seen == -1:  # if it's the first 0
        new_distances = [*range(index + 1)]
        new_distances.reverse()
        distance.extend(new_distances)
        last_0_seen = index
    elif value == 0 and last_0_seen != -1:
        mid_index = (last_0_seen + index) // 2
        first_part_distance = [*range(1, mid_index - last_0_seen + 1)]
        second_part_distance = [*range(0, index - mid_index)]
        second_part_distance.reverse()
        distance.extend(first_part_distance + second_part_distance)
        last_0_seen = index

distance.extend([*range(len(list) - len(distance))])  # handling numbers after the last 0

答案4

得分: 0

Output:

[1, 0, 1, 2, 1, 0, 1]

Explanation:
indices 是一个仅包含在 numbers 中找到零的索引的列表:

>>> indices
[1, 5]

我们在索引 1 和索引 5 处找到零。

distance_lists 是一个列表的列表。每个子列表表示到我们的零之一的“距离”:

>>> distance_lists
[[1, 0, 1, 2, 3, 4, 5], [5, 4, 3, 2, 1, 0, 1]]

最后,这个列表 [min(tpl) for tpl in zip(*distance_lists)] 仅比较两个距离列表的值,并在任何给定索引处选择较小的值:

1, 0, 1, 2, 3, 4, 5
5, 4, 3, 2, 1, 0, 1
|  |  |  |  |  |  |
v  v  v  v  v  v  v
1, 0, 1, 2, 1, 0, 1
英文:
numbers = [5, 0, 8, 87, 96, 0, 54]
indices = [index for index, num in enumerate(numbers) if num == 0]
distance_lists = [[abs(num - index) for num in range(len(numbers))] for index in indices]

print([min(tpl) for tpl in zip(*distance_lists)])

Output:

[1, 0, 1, 2, 1, 0, 1]

Explanation:
indices is just a list of indices at which a zero was found in numbers:

>>>indices
   [1, 5]
>>>

We found a zero at index 1, and index 5.

distance_lists is a list of lists. Each sub-list represents the "distance" to just one of our zeros:

>>>distance_lists
   [[1, 0, 1, 2, 3, 4, 5], [5, 4, 3, 2, 1, 0, 1]]
>>>

Finally, this list:
[min(tpl) for tpl in zip(*distance_lists)] just compares the values of both distance lists, and picks the smaller value at any given index:

1, 0, 1, 2, 3, 4, 5
5, 4, 3, 2, 1, 0, 1
|  |  |  |  |  |  |
v  v  v  v  v  v  v
1, 0, 1, 2, 1, 0, 1

答案5

得分: 0

以下是您要翻译的内容:

在我看来,最简单的方法是获取列表中每个零的索引,然后遍历该列表以及原始列表。然后,通过使用abs计算每个正在迭代的项相减的结果的绝对值,并将其附加到另一个列表中。然后通过使用min从该列表中获取最小值。对每个项执行此操作,您将得到所需的列表。

可以在下面看到可在此处使用的完整算法。

'''
1 - 创建一个函数,该函数将接受一个数字列表并返回一个显示传入列表中最近的零的接近度的数字列表。
    1.1 - 创建一个空列表以保存每个零的索引,该列表在函数参数中传入。
    1.2 - 创建一个空列表以保存我们将在函数中返回的最终列表。
    1.3 - 创建一个循环,该循环将遍历函数参数中传入的每个数字。
        1.3.1 - 如果数字等于零,则将其索引附加到步骤'1.1'中创建的列表中。
    1.4 - 创建另一个循环,该循环将遍历函数参数中传入的每个数字。
        1.4.1 - 创建一个临时列表以保存到步骤'1.1'中创建的列表中每个零的距离。
        1.4.2 - 遍历步骤'1.1'中创建的列表中的每个项目。
            1.4.2.1 - 计算步骤'1.4'中循环中的数字索引减去步骤'1.4.2'中循环中的数字并将其绝对值附加到步骤'1.4.1'中创建的列表中。
        1.4.3 - 将步骤'1.4.1'中创建的列表中的最小值附加到步骤'1.2'中创建的列表中。
    1.5 - 返回步骤'1.2'中声明的列表。
'''

2 - 打印运行在步骤'1'中声明的函数的结果

检查下面的代码以了解如何使用Python实现这一点

```python
def get_proximity_to_zero_for_each_item_in_list(numbers: list[int]) -> list[int]:
    zero_indexes = []
    proximity_list = []

    for index in range(len(numbers)):
        if numbers[index] == 0:
            zero_indexes.append(index)

    if len(zero_indexes) != 0:
        for number_index in range(len(numbers)):
            distance_from_each_zero_index = []
            for zero_index in zero_indexes:
                distance_from_each_zero_index.append(abs(number_index - zero_index))
            proximity_list.append(min(distance_from_each_zero_index))

    return proximity_list

number_list = [5, 0, 8, 87, 96, 0, 54]
proximity_to_zero_list = get_proximity_to_zero_for_each_item_in_list(number_list)
print(proximity_to_zero_list) # should print [1, 0, 1, 2, 1, 0, 1]
英文:

In my opinion, the easiest way is to get a list of the indexes of each zero in a list and then iterate over that list as well as the original one. You then get the absolute value of the result of subtracting each item being iterated by using abs, and append it to another list. Then get the minimum number from that list by using min. Do that for each item, and you will have your desired list.

The complete algorithm that can be used here is shown below.

'''
1 - Create a function that will accept a list of numbers and return a list of numbers that show the proximity to the nearest zero in the passed in list.
    1.1 - Create an empty list to hold the indexes of each zero passed in the function parameters.
    1.2 - Create an empty list to hold the final list we will return with the function.
    1.3 - Create a for loop that will loop over each number passed in the function parameters.
        1.3.1 - If number equals zero then append its index to the list created in step '1.1'.
    1.4 - Create another for loop that will loop over each number passed in the function parameters.
        1.4.1 - Create a temporary list to hold the distance to each zero in the list created in step '1.1'.
        1.4.2 - Create a loop over each item in the list created in step '1.1'.
            1.4.2.1 - Calculate each number index from loop in step '1.4' minus the number from the loop in step '1.4.2' and append its absolute value to the list created in step '1.4.1'.
        1.4.3 -  Append the minimun value from the list created in step '1.4.1' to the list created in step '1.2'.
    1.5 - Return the list declared in step '1.2'.

2 - Print the result of running the function declared in step '1'.
'''

Check the code below for an example of implementing this using Python.

def get_proximity_to_zero_for_each_item_in_list(numbers: list[int]) -> list[int]:
    zero_indexes = []
    proximity_list = []

    for index in range(len(numbers)):
        if numbers[index] == 0:
            zero_indexes.append(index)

    if len(zero_indexes) != 0:
        for number_index in range(len(numbers)):
            distance_from_each_zero_index = []
            for zero_index in zero_indexes:
                distance_from_each_zero_index.append(abs(number_index - zero_index))    
            proximity_list.append(min(distance_from_each_zero_index))

    return proximity_list


number_list = [5, 0, 8, 87, 96, 0, 54]
proximity_to_zero_list = get_proximity_to_zero_for_each_item_in_list(number_list)
print(proximity_to_zero_list) # should print [1, 0, 1, 2, 1, 0, 1]

huangapple
  • 本文由 发表于 2023年5月7日 05:50:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定