HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python -- polynomial operations class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
classoperationspythonpolynomial

Problem

This Python class takes a GF2 (finite field mod 2, basically binary) polynomial in string form, converts it to a binary value, then does arithmetic operations, then converts the result back into a polynomial in string form.

There are 2 parts I'd like to direct your attention to. I'll call them exhibits a and b.

For exhibit a, the regex has to be done on the string upon intake, so there were some issues with how class instances were used in terms of still allowing the string format. So that's the reason why the class is being called at the bottom. That should be invisible to the user (unless they actually go looking in the file), and when they call the class in whatever file is being used, then it should just be another class and they go on about their business. Not saying it's good coding, just saying why it looks like that. I'm sure it looks duck-taped from the professional Python coder's perspective, but for me I was pretty glad to solve it any way possible.

Also somewhat duck-taped was the modular inverse function, which I'll give as exhibit b.

I'm teaching myself Python and trying to drop all my beginner bad habits quickly. Just trying to get some good advice on the code.

```
import re

class gf2pim:

def id(self,lst): #returns modulus 2 (1,0,0,1,1,....) for input lists
return [int(lst[i])%2 for i in range(len(lst))]

def listToInt(self,lst): #converts list to integer for later use
result = obj.id(lst)
return int(''.join(map(str,result)))

def parsePolyToListInput(self,poly):
c = [int(i.group(0)) for i in re.finditer(r'\d+', poly)] #re.finditer returns an iterator
return [1 if x in c else 0 for x in xrange(max(c), -1, -1)]

def prepBinary(self,x,y): #converts to base 2 and orders min and max for use
x = obj.parsePolyToListInput(x); y = obj.parsePolyToListInput(y)
a = obj.listToInt(x); b = obj.listToInt(y)
bina = int(str(a),2); binb = int(str(b),2)
#a = min(b

Solution

speaking to exhibit a:

Perhaps I'm missing something, but AFAICT your class does not seem to carry any state: there aren't any variables shared between functions or persisting between function calls.

If that's so, it's easier and simpler just to make it a module -- it's merely a collection of related functions, not collection of data and methods for manipulating the data. You can get away from the whole obj business by just removing the class header and all references to 'self'. Other users would import the module and call the functions directly with no extra work.

Context

StackExchange Code Review Q#27900, answer score: 2

Revisions (0)

No revisions yet.