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

[Beginner] Code Challenge: Dictionaries 2

by 르네팜 2022. 8. 13.

1. Word Length Dict (길이 계산)

  • write a function that creates a new dictionary based on a list of strings
  • keys = strings / values = length of each of the words

방법 1.

def word_length_dictionary(words):
  word_lengths = {}
  for word in words:
    word_lengths[word] = len(word)
  return word_lengths

 

방법 2 - 방법 1 간소화

def word_length_dictionary(words):
  return {word:len(word) for word in words}

 

해설지에는 방법1 제시했음

 

 

2. Frequency Count (빈도 계산)

  • make a function that accepts a list of strings as input, counts the frequency of each string, and returns a new dictionary with strings as keys and the frequencies as values

 

def frequency_dictionary(words):
  frequency_dictionary = {}
  for word in words:
    if word not in frequency_dictionary.keys():
      frequency_dictionary[word] = 1
    else:
      frequency_dictionary[word] += 1
  return frequency_dictionary

 

해설:

def frequency_dictionary(words):
  freqs = {}
  for word in words:
    if word not in freqs:
      freqs[word] = 0
    freqs[word] += 1
  return freqs

 

 

3. Unique Values

  • create a function that takes a dictionary and returns a number indicating how many values are unique

이미 나온 단어 리스트 / 고유 단어 카운트 만들고

value를 처음부터 끝까지 확인해서 value가 리스트에 없으면 카운트 올리기

def unique_values(my_dictionary):
  value_lst = []
  uniques = 0
  for key in my_dictionary:
    if my_dictionary[key] not in value_lst:
      uniques += 1
      value_lst.append(my_dictionary[key])
  return uniques

 

해설:

def unique_values(my_dictionary):
  seen_values = []
  for value in my_dictionary.values():
    if value not in seen_values:
      seen_values.append(value)
  return len(seen_values)

어짜피 고유값이 몇 개인지 세는 거니, 굳이 하나하나 카운트안하고 리스트 길이로 return해도 됨

 

 

4. Count First Letter

  • provided dictionary = [last_names:first_names]
  • calculate the number of people who have the same first letter in their last name
  • ['letter':count] should return

이미 확인한 알파벳 저장할 리스트 만들어 놔야 함

만들 필요 없음. 사전에 저장될 것임

 

def count_first_letter(names):
  initial_count = {}
  for name in names:
    initial = name[0]
    initial_count[initial] += len(names[name])
  return initial_count

 

오류

print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}))
  File "script.py", line 5, in count_first_letter
    initial_count[initial] += len(names[name])
KeyError: 'S'

 

수정

def count_first_letter(names):
  initial_count = {}
  for name in names:
    initial = name[0]
    if initial not in initial_count:
      initial_count[initial] = 0
    initial_count[initial] += len(names[name])
  return initial_count

 

 

댓글