본문 바로가기
개발일기/PYTHON [codecademy]

[Beginner] Code Challenge: Strings

by 르네팜 2022. 8. 13.

1. Check Name

  • 인사말에 유저 이름이 들어가있는지 확인하는 function 만들기
  • 2 function parameters, both strings, one is a sentence and one a name
  • 이름이 인사말에 있다면, return True (※ 대소문자 상관없이 확인할 수 있게 할 것)

   

내가 처음 작성한 코드는

def check_for_name(sentence, name):
  lowered_sentence = sentence.lower()
  lowered_name = name.lower()
  if lowered_name in lowered_sentence:
    return True
  else: return False

이었고 결과값에는 문제는 없었다.

 

하지만 답을 확인해보니 아래처럼 더 짧고 효율적으로 쓸 수 있었더라.

def check_for_name(sentence, name):
  return name.lower() in sentence.lower()

 

 

값을 저장해서 다시 쓸 것이 아니면 짧은 코드 구성에 굳이 variable을 만들어서 넣을 필요가 없다.

 

 

2. Every Other Letter

  • return every other letter from the input as a string

방법1. 짝수 index만 사용하기

첫 시도는 

def every_other_letter(word):
  result = ""
  for letter in word:
    word.find(letter) % 2 == 0
    result.append(letter)
  return result

 

이었는데 그 결과는

 

AttributeError: 'str' object has no attribute 'append'

 

attribute error 발생.

string에는 .append 를 사용하지 않는다

string은 += 로 간단하게 문자열을 추가할 수 있다.

 

 

다시 고쳐서 시도해 보았다

def every_other_letter(word):
  result = ""
  for letter in word:
    word.find(letter) % 2 == 0
    result += letter
  return result

 

그랬더니 결과값이 Codecamemy가 나왔다... 무엇이 잘못된 것인가 보았더니 if가 없다...!

 

def every_other_letter(word):
  result = ""
  for letter in word:
    if word.find(letter) % 2 == 0:
    	result += letter
  return result

 

수정해서 다시 돌려보니 올바른 결과값이 나왔다. (0.2~0.3초)

.find() 대신에 .index()를 사용해도 변수의 위치 자리값이 나온다.

 

 

방법2. 카운터 사용하기

def every_other_letter(word):
  counter = 0
  result = ""
  while counter <= (len(word)-1):
    result += word[counter]
  return result

결과는 infinite loop. while 조건문 안에서 카운터를 안 올렸으니 당연함.

 

카운터 올려서 다시 진행

def every_other_letter(word):
  counter = 0
  result = ""
  while counter <= (len(word)-1):
    result += word[counter]
    counter += 2
  return result

올바른 결과값이 잘 나온다. (0.2~0.3초)

 

 

방법 3. 짝수 index 사용하기2 (0.2초)

1의 방법은 카운터를 2씩 직접 올린 거라면, 이번엔 아예 처음부터 설정을 2씩 올리도록 한다.

이 방법은 답안지에 나와있었고 생각을 못했었다 😭

def every_other_letter(word):
  every_other = ""
  for i in range(0, len(word), 2):
    every_other += word[i]
  return every_other

range() 복습

for i in range(start, stop, step)

: start부터 stop전까지 step만큼 증가

: 역순으로 가기 위해서는 꼭 step까지 모두 써줘야 함 ex) list[range(5, -1, -1)] -> [5, 4, 3, 2, 1, 0]

 

 

3. Reverse (기록 건너뜀. 위 range() 복습으로 대체)

 

4. Make Snooperism

  • a function taking 2 parameters
  • switch the first syllables of the two words
def make_spoonerism(word1, word2):
  spoon_word1 = word2[0] + word1[1:len(word1)]
  spoon_word2 = word1[0] + word2[1:len(word2)]
  return spoon_word1 + " " + spoon_word2

결과값은 제대로 나왔지만 여기서도 1번과 마찬가지로

값을 저장해서 다시 쓸 것이 아니면 짧은 코드 구성에 굳이 variable을 만들어서 넣을 필요가 없다.

 

 

더 짧은 코드:

def make_spoonerism(word1, word2):
  return word2[0]+word1[1:]+" "+word1[0]+word2[1:]

 

 

 

5. Add Exclamation

  • make a function taking 1 parameter, which should be a string with 20 or more syllables
  • if the parameter is less than 20 letters, fill the remaining space with exclamation marks until the size reaches 20
def add_exclamation(word):
  if len(word) >= 20:
    return word
  else:
    result = word
    while len(result) < 20:
      result += "!"
    return result

결과값 올바르게 나왔으나 이것도 짧게 쓸 수 있었음

 

def add_exclamation(word):
  while(len(word) < 20):
    word += "!"
  return word

단순하게 주어진 단어를 길이가 20이 넘을 때까지 업데이트해주면 됨

댓글