TIL # 14

Mikyung Lee·2021년 1월 14일
0
post-thumbnail

43. For Loops

Assignment

Input 으로 주어진 리스트에서 오직 한번만 나타나는 값 (unique value)을 가지고 있는 요소는 출력해주세요.
예를 들어, 다음과 같은 리스트가 주어졌다면:

[1, 2, 3, 4, 5, 1, 2, 3, 7, 9, 9, 7]

다음과 같이 출력되어야 합니다.

4
5
my_list = [1, 2, 3, 4, 5, 1, 2, 3, 7, 9, 9, 7]
new_list = []
for element in my_list:
  if element not in new_list:
    new_list.append(element)
  else:
    new_list.remove(element)
print(new_list)

새로운 리스트를 만든다. my_list에 있는 element 중에 new_list에 없으면 더하고 있으면 뺀다. 😁

44. For Loops - Iterate with For Loops

Assignment

반복문을 사용하여 1부터 5까지 my_list에 추가하는 함수 for_loop()를 완성해 주세요.

def for_loops():
  my_list = []
  for i in range(1,6):
    my_list.append(i)
  return my_list

반복문은 for i in range(a,b): 이다.

45. For Loops - Iterate Odd Numbers With a For Loop

Assignment

my_list에 1부터 9까지 홀수를 입력하는 함수 for_loops()를 완성 해주세요.

def for_loops() :
  my_list = [];
  for i in range(1,10,2):
    my_list.append(i)
  return my_list

(1,10,2) 1부터 9까지 2칸씩 건너띄기

47. For Loops - Iterate Through an Array with a For Loop

Assignment

my_list의 요소의 총 합을 리턴하는 list_loop함수를 완성해 주세요.
처음에 썼던 코드는 아래와 같다. 😥

def list_loop() :
  my_list = [ 2, 3, 4, 5, 6]
  total = 0
  for i in my_list(0,4):
    total=total+i
  return total

이렇게 my_list 뒤에 (0,4)를 넣었더니 오류가 떴다. my_list의 전체를 더하는 거니까 : 하나면 충분하다.

def list_loop() :
  my_list = [ 2, 3, 4, 5, 6]
  total = 0
  for i in my_list:
    total=total+i
  return total

48. For Loops - get_all_letters

get_all_letters 함수를 작성하세요.
단어가 주어졌을때, "get_all_letters" 함수는 주어진 단어에 포함된 모든 문자를 담고 있는 배열을 반환합니다.

def get_all_letters() :
  str_list = []
  mission_str = "wecode"
  for i in mission_str:
    str_list.append(i)
  return str_list

49. While Loops

Assignment

find_smallest_integer_divisor 라는 이름의 함수를 구현해 주세요.
find_smallest_integer_divisor 함수는 하나의 parameter를 받습니다.
Parameter 값은 integer만 주어집니다.
find_smallest_integer_divisor 주어진 parameter 값을 나눌 수 있는 1을 제외한 최소의 양의 정수를 리턴하여야 합니다.
예제:

find_smallest_integer_divisor(15) == 3
def find_smallest_integer_divisor(numb): 
  i = 2
  while numb % i != 0:
    i += 1
  return i

짝수인 경우 2가 나눌 수 있는 숫자 중 가장 작은 숫자이다. 3, 4, 5, 나눠질 때 까지 계속 더해가면서 i를 반환한다.

50. Looping Dictionary

Assignment

Input으로 주어진 list의 각 요소(element)가 해당 list에 몇번 나타나는지 수를 dictionary로 만들어서 리턴해주세요. Dictionary의 key는 list의 요소 값이며 value는 해당 요소의 총 빈도수 입니다.
예를 들어, 다음과 같은 list가 input으로 주어졌다면:

my_list = ["one", 2, 3, 2, "one"]

다음과 같은 dictionary가 리턴되어야 합니다.

{
   "one" : 2,
    2 : 2,
    3: 1
}
def get_occurrence_count(my_list):
  change_dict = dict()
  for list_element in my_list:
      change_dict[list_element] = my_list.count(list_element) 
  return change_dict

먼저 빈 dictionary를 만들어 준다. for문으로 my_list의 요소들을 순차적으로 list_element로 하나씩 넘겨주고 키-값 쌍으로 추가할 수 있게 list_element를 key로 value는 list_elemnet의 갯수를 count함수를 사용하여 지정해준다.

profile
front-end developer 🌷

0개의 댓글