아마도 모듈 내에서, 스스로 관리하기가 더 쉬운 함수 그룹을 만들고 있습니다. 그러나 이것을 학급 수준으로 돌리는 것에 대해 생각하고 싶은 학비를 넘어선 이유가 있습니다. 그러나 다항식 입력을 문자열로 변환하기 때문에 정규 표현식은 문자열에서 작동하지만 일단 입력이 클래스 인스턴스가되면 그 후에 끝내기로 결정합니다.파이썬 - 클래스 대 모듈
그래서 내 질문에 어떻게 이것을 클래스로 바꾸고 여전히 기능 (초기화 방법 등)을 유지하는 것입니다. 또는이 사건이 모듈이되는 데 더 적합하다면 논쟁 할 수는 있지만 완전히 이해해야합니다. 나는이 체크 아웃하지만 난이 문제를 해결하기 위해 그들 중 충분한지고있어 정말 확실하지 않다 :
http://docs.python.org/2/tutorial/classes.html
organising classes and modules in python이
import re
def id(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(lst): #converts list to integer for later use
result = id(lst)
return int(''.join(map(str,result)))
def parsePolyToListInput(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(x,y): #converts to base 2 and orders min and max for use
x = parsePolyToListInput(x); y = parsePolyToListInput(y)
a = listToInt(x); b = listToInt(y)
bina = int(str(a),2); binb = int(str(b),2)
#a = min(bina,binb); b = max(bina,binb);
return bina,binb #bina,binb are binary values like 110100101100.....
def add(a,b): # a,b are GF(2) polynomials like x**7 + x**3 + x**0 ....
bina,binb = prepBinary(a,b)
return outFormat(bina^binb) #returns binary string
def subtract(x,y): # same as addition in GF(2)
return add(x,y)
def multiply(a,b): # a,b are GF(2) polynomials like x**7 + x**3 + x**0 ....
a,b = prepBinary(a,b)
return outFormat(a*b) #returns product of 2 polynomials in gf2
def divide(a,b): #a,b are GF(2) polynomials like x**7 + x**3 + x**0 ....
a,b = prepBinary(a,b)
#bitsa = "{0:b}".format(a); bitsb = "{0:b}".format(b)
return outFormat(a/b),outFormat(a%b) #returns remainder and quotient formatted as polynomials
def quotient(a,b): #separate quotient function for clarity when calling
return divide(a,b)[1]
def remainder(a,b): #separate remainder function for clarity when calling
return divide(a,b)[0]
def outFormat(raw): # process resulting values into polynomial format
raw = "{0:b}".format(raw); raw = str(raw[::-1]); g = [] #reverse binary string for enumeration
g = [i for i,c in enumerate(raw) if c == '1']
processed = "x**"+" + x**".join(map(str, g[::-1]))
if len(g) == 0: return 0 #return 0 if list empty
return processed #returns result in gf(2) polynomial form
def extendedEuclideanGF2(a,b): # extended euclidean. a,b are values 10110011... in integer form
inita,initb=a,b; x,prevx=0,1; y,prevy = 1,0
while b != 0:
q = int("{0:b}".format(a//b),2)
a,b = b,int("{0:b}".format(a%b),2);
x,prevx = (int("{0:b}".format(prevx-q*x)), int("{0:b}".format(x,2))); y,prevy=(prevy-q*y, y)
#print("%d * %d + %d * %d = %d" % (inita,prevx,initb,prevy,a))
return a,prevx,prevy # returns gcd of (a,b), and factors s and t
def modular_inverse(a,mod): # a,mod are GF(2) polynomials like x**7 + x**3 + x**0 ....
a,mod = prepBinary(a,mod)
bitsa = int("{0:b}".format(a),2); bitsb = int("{0:b}".format(mod),2)
#return bitsa,bitsb,type(bitsa),type(bitsb),a,mod,type(a),type(mod)
gcd,s,t = extendedEuclideanGF2(a,mod); s = int("{0:b}".format(s))
initmi = s%mod; mi = int("{0:b}".format(initmi))
print ("%d * %d mod %d = 1"%(a,initmi,mod))
if gcd !=1: return outFormat(mi),False
return outFormat(mi) # returns modular inverse of a,mod
a = "x**14 + x**1 + x**0"; b = "x**6 + x**2 + x**1"
c = "x**2 + x**1 + x**0"; d = "x**3 + x**1 + x**0"
e = "x**3 + x**2 + x**1 + x**0"; f = "x**2"; g = "x**1 + x**0"
p = "x**13 + x**1 + x**0"; q = "x**12 + x**1"
print "add: [%s] + [%s] = %s "%(a,b,add(a,b))
print "add: [%s] + [%s] = %s "%(c,d,add(c,d))
print "multiply: [%s] * [%s] = %s "%(a,b,multiply(a,b))
print "multiply: [%s] * [%s] = %s "%(c,d,multiply(c,d))
print "multiply: [%s] * [%s] = %s "%(f,g,multiply(f,g))
print "quotient (max(a,b)/min(a,b): [%s]/[%s] = %s "%(a,b,quotient(a,b))
print "quotient (max(a,b)/min(a,b): [%s]/[%s] = %s "%(c,d,quotient(c,d))
print "remainder (max(a,b) mod min(a,b)): [%s] mod [%s] = %s "%(a,b,remainder(a,b))
print "remainder (max(a,b) mod min(a,b): [%s] mod [%s] = %s "%(c,d,remainder(c,d))
valuemi1 = modular_inverse(a,b)
print "modular_inverse: [%s] * [%s] mod [%s] = 1 [%s]"%(a,valuemi1[0],b,valuemi1[1])
valuemi2 = modular_inverse(p,q)
print "modular_inverse: [%s] * [%s] mod [%s] = 1 [%s]"%(p,valuemi2[0],q,valuemi2[1])
산술 연산의 각 단지에 걸립니다 문자열 형식의 GF (2) 다항식은 각각의 이진 값으로 파싱 한 다음 다시 다항식으로 변환하기 위해 outFormat()을 보냅니다. 지금은 잘 작동하므로 부러지지 않으면 수리하지 않을 것입니다. 내가 제대로 다음 질문을 이해하면
을 덕분에 내가 뭘 찾고 있었는지. 단지 2 가지 : 1. 클래스의 대부분은'클래스 수학 :'... 대신에'클래스 수학 (객체) : '을 사용합니다. 2. 그러면 인스턴스를 생성하고 사용할 때 왜 그런지 모르겠습니다. 정규 표현식 문제로 실행되고 있었지만 지금은이 인스턴스가 입력을 처리하는 것 같습니다. – stackuser
@Rami : 표준''self'' 변수를 사용하는 것이 더 좋을 수 있습니다 - 가독성을 향상시킵니다. @stackuser : 당신이하려는 것은 클래스에 몇 가지 함수를 패키지하는 것입니다. 귀하의 기능이 데이터를 교환하는 것을 보지 못했습니다. 정적 함수를 사용하지 않는 이유는 무엇입니까? 예 : ''클래스 MathOperations : @staticmethod 데프 ID (LST) : 열거의 난에 대한 INT (발) % 2 발 (LST)] 반환 주목해야 할 일들의 '' 몇 : 당신이 다음과 같이 호출 할 수 있습니다. MathOperations.id ([1,2]) – goofd
형식이 엉망이지만 죄송합니다. 새 덧글을 추가하고 싶지 않습니다. – goofd