编程语言
首页 > 编程语言> > python – 压缩正弦波表

python – 压缩正弦波表

作者:互联网

我有一个包含1024个条目的大型数组,其范围内有7位值(14,86)

这意味着有多个索引范围具有相同的值.

例如,

consider the index range 741 to 795. It maps to 14
consider the index range 721 to 740. It maps to 15
consider the index range 796 to 815. It maps to 15

我想将这个地图提供给一个python程序,该程序会显示以下内容:

if((index >= 741) and (index <= 795)) return 14;
if((index >= 721) and (index <= 740)) return 15;
if((index >= 796) and (index <= 815)) return 15;

groupby映射值的一些代码已准备就绪,但我很难使用pairwise编码表达式.

以前有人做过类似的事吗?

我已经以两种形式上传了数据集:

通常,ordered by index.

Grouped by mapped value.

解决方法:

关闭后,我姗姗来迟找到了这个解决方案“What’s the most Pythonic way to identify consecutive duplicates in a list?”.

注意:使用像sine这样的周期性fn,只需存储四分之一(即256个值)或表的一半,然后在查找时对索引执行一些(定点)算术.正如我评论的那样,如果你进一步不存储50的偏移量,你需要少一点,这需要在查找时间之后增加一个整数.因此,可以轻松实现79%的压缩. RLE会给你更多.即使fn有噪音,你仍然可以通过这种通用方法得到适当的压缩.

正如agf指出的那样,你的f(n)= 50 36 * sin(72 * pi * n / 1024)= 50 g(n).

因此,将g(n)= 36 * sin(72 * pi * n / 1024)的256个值制成表格,仅适用于范围n = 0..255

那么f(n)很容易通过以下公式计算:

if 0 <= n < 256, f(n) = 50 + g(n)
if 256 <= n < 512, f(n) = 50 + g(511-n)
if 512 <= n < 768, f(n) = 50 - g(n-512)
if 768 <= n < 1024, f(n) = 50 - g(1023-n)

无论如何这里是一个通用的表压缩器解决方案,它将生成(istart,iend,value)三元组.

我使用list comprehensions和itertools.takewhile()来解决如何使用Python进行更多操作的问题.需要抛光.

#import itertools

table_="""
    0       50
    1       50
    ...
    1021    49
    1022    50
    1023    50""".split()

# Convert values to int. Throw away the indices - will recover them with enumerate()
table = [int(x) for x in table_[1::2]]

compressed_table = []
istart = 0
for i,v in enumerate(table):
    if v != table[i-1]:
        iend = i-1
        compressed_table.append((istart,iend,table[i-1]))
        istart = i
    else:
        continue # skip identical values
# Slightly ugly: append the last value, when the iterator was exhausted
compressed_table.append((istart,i,table[i]))

(注意,在agf改变他的方法之前我开始使用表压缩器方法…试图获得一个itertools或list-comprehension解决方案)

标签:python,compression,sine,run-length-encoding
来源: https://codeday.me/bug/20190521/1147897.html