2014-10-10 28 views
0

재귀를 사용하여 2 진수를 10 진수로 변환하는 데 도움이 필요합니다.재귀를 사용하여 10 진수로 2 진수, 파이썬

지금까지 난 가지고

(2 * INT (S [0])) + INT (S [1])과 S == 0베이스 케이스와

및 S == 1 .

이 함수를 재귀 적으로 전달하여 함수가 입력에서 모두 1과 0을 통과하도록하는 방법을 모르겠습니다.

+0

우선's == 0'과's == 1'은 's'가 분명히 시퀀스이기 때문에 가능하지 않습니다. 당신은'len (s) == 0'과'len (s) == 1'을 의미할까요? 아니면 다른 무엇입니까? – abarnert

+0

둘째, 재귀의 기본 개념을 이해합니까? 최소한 기본 케이스를 처리하는 함수를 작성할 수 있습니까? 추측 할 수 있습니까? 아니면 나머지 부분에 대해이 부분을 도와 주시겠습니까? – abarnert

답변

0

기본 아이디어는 문자열의 마지막 문자를 선택하여 숫자로 변환 한 다음 적절한 2의 제곱으로 곱하는 것입니다. 코드를 주석 처리했습니다.

# we need to keep track of the current string, 
# the power of two, and the total (decimal) 
def placeToInt (str, pow, total): 
    # if the length of the string is one, 
    # we won't call the function anymore 
    if (len(str) == 1): 
     # return the number, 0 or 1, in the string 
     # times 2 raised to the current power, 
     # plus the already accumulated total 
     return int(str) * (2 ** pow) + total 
    else: 
     # grab the last digit, a 0 or 1 
     num = int(str[-1:]) 
     # the representation in binary is 2 raised to the given power, 
     # times the number (0 or 1) 
     # add this to the total 
     total += (num * (2 ** pow)) 
     # return, since the string has more digits 
     return placeToInt(str[:-1], pow + 1, total) 

# test case 
# appropriately returns 21 
print(placeToInt("10101", 0, 0)) 

이제 수동으로 살펴보고 이것이 작동하는 이유를 이해하십시오.

# n = 101 (in binary 
# this can also be represented as 1*(2^2) + 0*(2^1) + 1*(2^0) 
# alternatively, since there are three digits in this binary number 
# 1*(2^(n-1)) + 0*(2^(n-2)) + 1*(2^(n-3)) 

그렇다면이 의미는 무엇입니까? 음, 오른쪽 자리는 0의 제곱수까지 1 또는 0 곱하기 2입니다. 즉, 총계에 1 또는 0을 더합니다. 두 번째 맨 오른쪽 숫자는? 총계에 0 또는 2를 더합니다. 다음에? 0 또는 4입니다.

는의는 의사를 쓰기 보자

우리는 힘과 0의 총 시작부터
let n = input, in binary 
total = 0 
power of 2 = 0 
while n has a length: 
    lastDigit = last digit of n 
    add (2^pow)*lastDigit to the current total 

이 작동 왜, 당신이 볼 수 있습니다.

+0

나는의 말을하자이 같은 문제를 해결하려고 노력하고있어 S = 1010 '101 + 0 10 + 1 1 + 0 는 다음과 같이 작동합니다 : (2 * 1) + 0 = 2 (2 * 2) + 1 = 5 (5 * 2) + 0 = 10 최종 대답은 지금까지 내가이 함께 왔어요 (10) 것 반환 : 경우의 == ' 0 ': return 0 elif s =='1 ': return 1 else : if (len (s))> 1 :(2 * n) + (int (s [-1 :])) print (n) rest = (2 * n) + (int (s [-1]))) print (rest)' 이 작업은 s = '100'또는 s = '111'이지만 그보다 높지는 않습니다. – user4127524

+0

@ user4127524 http://pastebin.com에 코드를 넣을 수 있습니까? 내가 읽을거야? – royhowie

0
def IntegerConvert(num, base): 
    if num == 0: 
     return 0 
    else: 
     IntegerConvert.sum += pow(10, IntegerConvert.counter)*(num % base) 
     IntegerConvert.counter += 1 
     IntegerConvert(num/base, base) 
    return IntegerConvert.sum 
IntegerConvert.counter = 0 
IntegerConvert.sum = 0 
print IntegerConvert(10, 2) 
관련 문제