Python将二进制多项式读入列表

我正在尝试在GF(2)有限域中读多项式,对于系数或常数,它基本上只有1或0,并且真正将多项式的一部分与其他部分区分开的唯一数字是指数。但是指数最终仅标记结果列表中位置的“位置”或索引,然后仅将其标记为1。结果列表中的每个其他位置均为0。


一些示例代码:


a = "x**14 + x**1 + x**0"

#b = [int(s) for s in a.split() if s.isdigit()]

import re

b = re.findall(r'\d+', a)

print b

c = [int(x) for x in b]

print c

d = []; m = max(c)

print c[1]

for i in range(m):

    d.append(0)

#    if c[i]>=0: d.insert(i,1)

#    else: d.insert(i,0)


for i in c:

    del d[i-1]

    d.insert(i,1)


#d.insert(m,1);

d.reverse()

print d,len(d)

如您所见,这将输出:


>>> 

['14', '1', '0']

[14, 1, 0]

1

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1] 14

>>> 

但是应该在列表的开头输出1(多项式度从左到右从高到低,列表也应该如此)。长度是正确的,因为那是最高的程度。我现在正在自学Python,因此我确信专业Python人士对我的代码很满意。对于那些是专业人士的人,请随意提出一个更Python化的解决方案,或者其他任何有建设性的建议,因为我正试图尽快摆脱所有初学者的习惯。稍后,我将其放入一个函数中(实际上它会放入一个类中的函数中),这只是为了使基本思想变得清晰。


HUH函数
浏览 166回答 1
1回答

九州编程

range(14) 返回的数字从0到13、14不包括在内:尝试:d = []#no need of two loops here, if the number is present in c then append 1 else 0for i in range(m, -1, -1): #goes from 14 to 0, -1 is not inclusive    if i in c:        d.append(1)    else:        d.append(0)#one-liner : d = [1 if x in c else 0  for x in xrange(14, -1, -1)]print d,len(d)#prints [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1] 15您的代码的简短版本:import rea = "x**14 + x**1 + x**0"c = [int(m.group(0)) for m in re.finditer(r'\d+', a)] #re.finditer returns an iteratorm = max(c)d = [1 if x in c else 0  for x in xrange(m, -1, -1)]print d,len(d)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python