2017-11-23 3 views
0

다른 종류의 데이터를 수신하고 있지만 다른 종류의 데이터를 수신하고 있다는 오류가 발생했다고 생각합니다. ? 난 코드만큼 입력 값이 50 이하로 잘 실행왜 계속 ValueError : 10 진법의 long()에 대한 리터럴이 잘못 되었습니까? '5-1'

#Program to calculate factorial of a long number 

def multiply(multiplier,multiplicand): 

    a = long(''.join(multiplier)) 
    b = long(''.join(multiplicand)) 
    a = a*b 
    multiplier = list(str(a)) 
    b = b-1 
    multiplicand = list(str(b)) 
    if(b == 1): 
     return False,multiplier,multiplicand 
    else: 
     return True,multiplier,multiplicand 


num = "" 
f = True # A flag variable 
while(f):     #checks if the string consists of digits only 
     num = raw_input("Enter number:") 
     f = False 
     if num.isdigit() == False: 
       print "oops,try again!" 
       f = True 
multiplier = list(num) 
multiplicand = multiplier[:] 
multiplicand.pop() 
multiplicand.insert(len(multiplier),str(long(multiplier[-1])-1)) #mand now contains multiplier -1 in list form 

f = True 
while (f): 
     f,multiplier,multiplicand = multiply(multiplier,multiplicand) 
num = ''.join(multiplier) 
print num #print the ans as a string 

python.Anyone에서 초보자이 고정 할 수있는 방법을 알고,하지만 50 후 오류 보여줍니다

Traceback (most recent call last): 
File "test.py", line 31, in <module> 
    f,multiplier,multiplicand = multiply(multiplier,multiplicand) 
File "test.py", line 5, in multiply 
    b = long(''.join(multiplicand)) 
ValueError: invalid literal for long() with base 10: '5-1' 

'5-1'은 무엇을 의미합니까?

답변

0

여러 자리 숫자를 목록으로 처리하고 대입을 다시 구현합니다. 너는 mand = mplier - 1을 원한다. mplier은 숫자 목록이므로 (이 필요 없음, 답변 끝 부분에 자세한 정보가 있음) mandmplier의 마지막 숫자 인 1을 제외한 마지막 숫자를 제외한 mplier과 동일해야한다고 가정합니다.

이 0에 끝나지 않는 번호에 대한 진정한 보유 : ['5', '3']['5', '2'] 될 것입니다,하지만 ['5', '0']['5', '-1']하지 ['4', '9'] 될 것입니다. b = long(''.join(mand))에서 전화 번호를 재구성하려고하면 b = long('4-1')으로 끝나고 '4-1'은 숫자가 아니므로 예외가 발생합니다.

Python does not have a precision limit on integer numbers이므로 긴 숫자를 다르게 처리 할 필요가 없습니다. ,

#Program to calculate factorial of a long number 

def factorial(n): 
    result = 1 
    for r in xrange(0, n): 
     result = result * (r+1) 
    return result 

num = 0 

while(True):     #checks if the string consists of digits only 
     num = raw_input("Enter number:") 
     if not num.isdigit(): 
       print "oops,try again!" 
     else: 
      num = int(num) 
      break 

print factorial(num) 

또한 보조 노트로, 코드는 혼란이고 그것을 당신이 무엇을하고 있는지 이해하는 나에게 조금을했다 :

나는 그것을 유용 경우 코드를 다시 작성했다. CodeReview을 통해 모범 사례 (유용한 변수 이름, 쓸모없는 변수 제거, 코드에 대한 적절한 문서, 최신 기법 등)를 익힐 수 있습니다.

관련 문제