python - (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
解决方案
您可以为此使用 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)
推荐阅读
- sql - 基于 Pyspark 中其他值的一列的条件聚合
- amazon-web-services - 无法在亚马逊 Ec2 实例上的 docker 中运行 Elasticsearch
- r - 可以根据轴的变量更改的散点图函数
- jquery - 使用 html2canvas 和 jspdf 创建的 PDF 文件 - pdf 中不允许选择文本
- reactjs - 如何使用 React 和 Material-UI 嵌入 Calendly 锚标签
- clickhouse - 有没有办法在 ClickHouse 中漂亮地打印 SELECT 查询结果?
- django - django 使用 URL 中的字符串进行动态查询集过滤
- javascript - 如何制作这样的内容卷轴?
- c++ - 编译器没有显示错误,但我没有得到任何输出。怎么了?
- javascript - VueJS组件显示其他组件内容