2013-05-16 2 views
-1
class Factor: 
def __init__(self, a, b, c):           
    self.a = a 
    self.b = b 
    self.c = c 

def commonFactor(self):            
    global cfa              
    cfa = self.a              
    cfb = self.b 
    while cfb:              
     cfa, cfb = cfb, cfa % cfb         
    return cfa              


def simplifyIntegers(self):           
    self.a = int(self.a/cfa)          
    self.b = int(self.b/cfa) 
    self.c = int(self.c/cfa) 
    return self.c             


def coefficients(self):            
    if self.a == 1:             
     coe1 = 1 
     coe2 = 1 
    else:               
     coe1 = self.a 
     coe2 = 1 
    return self.coe1             


def getFactors(self):             
    positivec = abs(self.c) 
    global result             
    result = set() 
    for i in range(1, int(positivec ** 0.5) + 1): 
     div, mod = divmod(positivec, i) 
     if mod == 0: 
      result |= {i, div} 
    return result             


def numbers(self):             
    if self.c < 0:             
     poslist = [int(x) for x in result]       
     neglist = [-(x) for x in poslist] 
     numpos = poslist[0]           
     numneg = neglist[-1]          
     for i in poslist:           
      number = numpos + numneg         
      poslist.remove(numpos)         
      neglist.remove(numneg) 
      if number == self.b:          
       num1 = numpos 
       num2 = numneg 
       return num1           
      elif len(poslist) > 0:         
       numpos = poslist[0] 
       numneg = neglist[-1] 
      else:             
       print("This equation can not be fully factored.") 
    if self.c > 0:             
     poslist1 = [int(x) for x in result]       
     poslist2 = [int(x) for x in result] 
     neglist1 = [-(x) for x in poslist1] 
     neglist2 = [-(x) for x in poslist1] 
     numpos1 = poslist1[0] 
     numpos2 = poslist2[-1] 
     numneg1 = neglist1[0] 
     numneg2 = neglist2[-1] 
     for i in poslist1:           
      number = numpos1 + numpos2 
      poslist1.remove(numpos1) 
      poslist2.remove(numpos2) 
      if number == self.b: 
       num1 = numpos1 
       num2 = numpos2 
       return num1 
      elif len(poslist1) > 0: 
       numpos1 = poslist1[0] 
       numpos2 = poslist2[-1] 
      else: 
       print("This equation can not be factored.")  
     for i in neglist1:           
      number = numneg1 + numneg2 
      neglist1.remove(numneg1) 
      neglist2.remove(numneg2) 
      if number == self.b: 
       num1 = numneg1 
       num2 = numneg2 
       return num1 
      elif len(neglist1) > 0: 
       numpos1 = neglist1[0] 
       numpos2 = neglist2[-1] 
      else: 
       print("This equation can not be factored.") 

def factoredForm(self):            
    cfa = str(cfa) 
    coe1 = str(coe1) 
    num1 = str(num1) 
    coe2 = str(coe2) 
    num2 = str(num2) 
    equation = (cfa,"(",coe1,"x + ",num1,")(",coe2,"x + ",num2,")") 
    return equation 


a = input("What is A?")             
a = int(a) 
b = input("What is B?") 
b = int(b) 
c = input("What is C?") 
c = int(c) 

e = Factor(a,b,c)              
print(e.factoredForm()) 

Я получаю это error-UnboundLocalError: локальная переменная ссылается перед тем вопрос о назначении

UnboundLocalError: local variable 'cfa' referenced before assignment 

Я смотрел на совсем немного вещей, говорящих о том, как это исправить, но ни один из них не казалось, предложил что-то исправить. Я делаю переменные глобальными, но это все еще не работает, а что-то еще не работает. Это моя программа, которую я сделал для определения квадратичности, если вам нужно знать, что она делает. Спасибо всем, кто может помочь.

ответ

3

Здесь похоже, что вы пытаетесь создать локальную версию cfa, которая представляет собой версию глобальной версии cfa.

def factoredForm(self):            
    cfa = str(cfa) 

Вы не можете смешивать оба типа доступа в одном и том же объеме. Вы должны использовать другое имя для локальной переменной.

В качестве альтернативы вы можете написать функцию, как этого

def factoredForm(self): 
    return map(str, (cfa, "(", coe1, "x + " ,num1, ")(", coe2, "x + " ,num2 ,")")) 
+0

Спасибо, это было очень полезно. Я написал свой конец, как и вы, но мой печатает его так: <объект карты в 0x0000000002F7BC18>, любая идея о том, как его исправить. Я никогда раньше не сталкивался с этими функциями сопоставления. – user2387637

+0

@ user2387637, используйте 'tuple (map (...))' для Python3 –

0

Эти операторы:

cfa = str(cfa) 
coe1 = str(coe1) 
num1 = str(num1) 
coe2 = str(coe2) 
num2 = str(num2) 

предполагают, что вы хотите, чтобы все эти переменные как переменные экземпляра (не глобалам). Я думаю, что вы нашли каждое использование и изменили способ доступа к ним.

Смежные вопросы