1. 문자열 뒤집기
문제
코드
def solution(my_string):
answer=[]
for i in my_string:
answer.append(i)
answer.reverse()
reversed_string = ''.join(answer)
return reversed_string
처음에 아래처럼 짰었는데 return문이 없어서 계속 null을 반환했다.
def solution(my_string):
answer=[]
for i in my_string:
answer.append(i)
answer.reverse()
for i in range(len(answer)):
print(answer[i], end='')
다른 사람 풀이
1. 문자열 마지막 파라미터를 -1로 설정하면 역순으로 슬라이싱한다. 시작, 끝 인덱스를 비워뒀으니까 마지막 인덱스부터 하나씩 반환한다.
def solution(my_string):
return my_string[::-1]
2. 리스트를 뒤집을 때는 reverse()를 사용하면 되고, 문자열을 뒤집을 때는 reversed(string)를 쓰면 된다.
문자열을 뒤집는 iterator가 반환되면 list로 만들고, join해서 return한다.
def solution(my_string):
return ''.join(list(reversed(my_string)))
2. 직각삼각형 출력하기
문제
코드
n = int(input())
for i in range(1,n+1):
print("*"*i)
3. 짝수 홀수 개수
문제
코드
def solution(num_list):
odd = 0
for i in num_list:
if(i%2 == 0):
odd+=1
answer = [odd, len(num_list) - odd]
return answer
2로 나눈 나머지가 0이면 odd변수에 1씩 더했고, 짝수 개수는 출력할 때 배열 길이에서 홀수 개수를 뻈다.
4. 문자 반복 출력하기
문제
코드
def solution(my_string, n):
answerList = []
for i in (my_string):
answerList.append(i*n)
return ''.join(answerList)
리스트를 만들어두고 n개만큼 각 문자를 집어넣고, join해줘서 string으로 만들어줬다.
다른 사람 풀이
그냥 바로 return문에 for문을 돌리고 join을 하는 방법도 있다.
def solution(my_string, n):
return ''.join(i*n for i in my_string)
728x90