我正在尝试在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 reb = re.findall(r'\d+', a)print bc = [int(x) for x in b]print cd = []; 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化的解决方案,或者其他任何有建设性的建议,因为我正试图尽快摆脱所有初学者的习惯。稍后,我将其放入一个函数中(实际上它会放入一个类中的函数中),这只是为了使基本思想变得清晰。
1 回答

九州编程
TA贡献1785条经验 获得超4个赞
range(14) 返回的数字从0到13、14不包括在内:
尝试:
d = []
#no need of two loops here, if the number is present in c then append 1 else 0
for 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 re
a = "x**14 + x**1 + x**0"
c = [int(m.group(0)) for m in re.finditer(r'\d+', a)] #re.finditer returns an iterator
m = max(c)
d = [1 if x in c else 0 for x in xrange(m, -1, -1)]
print d,len(d)
添加回答
举报
0/150
提交
取消