2017-10-22 2 views
3

나는 정수의 두 가지 목록을 가지고있다. 그래서 얻어야한다 : 여기 재귀 파이썬

[5,10,12,8] 

내 기능과 같습니다 : "****"굵은 부분에 대한

def sum(A,B): 
    a = len(A) 
    b = len(B) 

    if a == 0 : 
     return B 
    elif b == 0 : 
     return A 
    elif a >= b : 

     return A[0] + B[0] + sum(A[1:b],B[1:])+ **list1[(b+1):]** 
    else: 
     return A[0] +B[0] + sum(A[1:],B[1:a])+**list2[(a+1):]** 

, 내가 올바른 여부를 생각인지 모르겠습니다 나아가 프로그램을 실행했을 때 "A [0] + B [0] + sum (A [1 : b], B [1 :]) + A [(b + 1) :]을 반환했습니다.

TypeError: unsupported operand type(s) for +: 'int' and 'list'"

답변

3

재귀 케이스가 올바르지 않습니다. 반송해야합니다. g 목록 합계, 즉 A[0] + B[0]을 단일 요소 목록으로 추가해야 함을 의미합니다. 기본적으로, 이것은 당신이 무슨 일을하는지입니다 :

In [559]: 1 + [123] 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-559-01aa05245fd1> in <module>() 
----> 1 1 + [123] 

TypeError: unsupported operand type(s) for +: 'int' and 'list' 

을 그리고 이것이 당신이 일을해야 무엇 :

In [560]: [1] + [123] 
Out[560]: [1, 123] 

다음은 재귀 케이스의 작업 버전입니다, 살짝 정돈.

In [555]: def sum(A, B): 
    ...:  if not len(A): 
    ...:   return B 
    ...:  elif not len(B): 
    ...:   return A 
    ...: 
    ...:  return [A[0] + B[0]] + sum(A[1:], B[1:]) 
    ...: 

In [556]: sum(A, B) 
Out[556]: [5, 10, 12, 8] 

재미있는 사실, 당신은 한 줄에이 기능을 단축 할 수 있습니다.

In [557]: def sum(A, B): 
    ...:  return A if not len(B) \ 
         else (B if not len(A) \ 
         else ([A[0] + B[0]] + sum(A[1:], B[1:]))) 
    ...: 

In [558]: sum(A, B) 
Out[558]: [5, 10, 12, 8] 
+0

을하지만 프로그램을 실행할 때 여전히이 문제를 가지고 형식 오류 : 지원되지 않는 피연산자 유형 (들) +에 대한 : 'int'와 'list'. –

+0

@ J.Done 파일을 저장했다고 생각하지 않습니다. –

+0

OMG! 정말 고맙습니다 !! –

0

이 작업을 시도 할 수 있습니다 :

def the_sum(a, b, c): 
    if not a[1:] and b[1:]: 
     c.append(b[0]+a[0]) 
     return the_sum(a, b[1:], c) 
    if not b[1:]: 
     c.append(b[0]) 
     return c 
    if a[1:] and b[1:]: 
     c.append(a[0]+b[0]) 
     return the_sum(a[1:], b[1:], c) 

print(the_sum([1,5,3], [4,5,9,8], [])) 

출력 :

[5, 10, 12, 8] 
0

데프 합 (L1, L2, 결과 = 없음, ID = 0) :

if result is None: 
    result = [] 
if id < min(len(l1), len(l2)): 
    result.append(l1[id] + l2[id]) 
    return sum(l1, l2, result, id + 1) 
else: 
    if len(l1)>len(l2): 
     biggest=l1 
    else: 
     biggest=l2 

    return result+biggest[id:] 

입력

r=sum([1,5,3,2],[4,5,9,8,15]) 

출력

[5, 10, 12, 10, 15] 
1

이 수행하는 비 재귀 방법 :

>>> import itertools 
>>> a = [1,5,3] 
>>> b = [4,5,9,8] 
>>> [sum(i) for i in itertools.zip_longest(a,b,fillvalue=0)] 
[5, 10, 12, 8]