2017-01-05 3 views
0

메신저에는 복제해야 할 두 개의 매개 변수 데이터와 데이터 복제 횟수를 취하는 함수를 작성합니다. 파이썬에 새로운 메신저, 사람이 당신은 output.split(' ')을 반환하는데이터를 복제하는 함수를 작성합니다.

def replicate_iter(times, data): 
    output = times * data 
    if type(data) != str: 
     raise ValueError('Invalid') 
    if times <= 0: 
     return [] 
    else: 
     return output.split(' ') 

print replicate_iter(4, '5') #expected output [5, 5, 5, 5] 

['5555'] 
+0

귀하의'output' 변수입니다. – Evert

답변

0

이 코드는 주석과 원하는 출력을 제공하지만, 크기가 times 인 for 루프를 사용합니다.

def replicate_iter(times, data): 
    output = [] #you can initialize your list here 
    if type(data) != str: 
     raise ValueError('Invalid') 
    #if times <= 0: # Since input was initialized earlier 
    # return [] # These two lines become unnecessary 
    else: 
     for i in range(times): #use a for loop to append to your list 
      output.append(int(data)) #coerce data from string to int 
     return output #return the list and control to environment 

print replicate_iter(4, '5') 

출력은 다음과 같습니다 공백 문자를 (당신이에 분할 사용하는)가 포함되어 있지 않습니다 주어진 예 입력이

[5, 5, 5, 5] 
+0

대단히 감사합니다. – Dolapo

0

을 도와하지만 입력 '5'는 공백이 없습니다. 따라서 '5555'.split(' ')['5555']을 반환합니다. 반환 조건을 변경하거나 요소 사이에 공백을 추가해야합니다.

공간을 추가 : 리턴/기능 변경

output = (times * (data + " ")).rstrip() # add a trailing space between elements and remove the last one 

(이것이 당신의 캐릭터 자체에 공백이 가정) : (이 공백 문자열을 지원합니다)를

def replicate_iter(times, data): 
    output = [] 
    if type(data) != str: 
     raise ValueError('Invalid') 
    while len(output) < times: 
     output.append(data) 
    return output 
관련 문제