首页 > 解决方案 > (Python)一系列布尔值中的等距真值

问题描述

我正在尝试制作一个自定义 PWM 脚本来与我的 Charlieplexed 系列 LED 一起使用。但是,我正在努力使某些强度值看起来平滑而没有闪烁。不同的亮度值会使 LED 亮起不同的刻度。为了让它感觉平滑,我需要优化 LED 的开和关刻度的间距,但我完全可以弄清楚如何做到这一点。

如果您有一个模式,其中有 x 个布尔值并且其中 n 个为真,那么您将如何尽可能地等距分隔真值?

这是我正在寻找的示例:

x = 10, n = 7

期望的结果:1,1,1,0,1,1,0,1,1,0

x = 10, n = 4

期望的结果:1,0,1,0,0,1,0,1,0,0

标签: pythonsorting

解决方案


您可以为此使用 numpy 的 linspace 函数。

import numpy as np

x = 10
n = 7

# Gets the indices that should be true
def get_spaced_indices(array_length, num_trues):
  array = np.arange(array_length)  # Create array of "indices" 0 to x
  indices = np.round(np.linspace(0, len(array) - 1, num_trues)).astype(int)  # Evenly space the indices
  values = array[indices]
  return values

true_indices = get_spaced_indices(x, n)
print("true_indices:", true_indices)

result = [0] * x  # Initialize your whole result to "false"
for i in range(x):
  if i in true_indices:  # Set evenly-spaced values to true in your result based on indices from get_spaced_indices
    result[i] = 1

print("result:", result)

推荐阅读