본문 바로가기

Baekjoon

백준 1157번 : 단어 공부

 

<소스코드>

words = input().lower()
words_list = list(set(words))   #중복 제거하고 리스트에 저장
word_cnt = list()             # 리스트 생성

for i in words_list :
    cnt = words.count(i)
    word_cnt.append(cnt)

if word_cnt.count(max(word_cnt)) >= 2 :     #개수가 가장 많은 것이 여러개일 경우
    print("?")
else :                                      # 그 외의 경우
    print(words_list[word_cnt.index(max(word_cnt))].upper())

set함수

- set은 집합과 비슷

- 순서가 없고, 집합 안에서는 독특한 값을 가진 mutable 객체이다

- 중괄호를 사용하는 것은 dictionary와 비슷 , 하지만 key가 없고 값만 존재한다

- dict타입과 동일한 중괄호를 사용하므로 중괄호만으로 생성 X

중복된 값은 자동으로 중복이 제거 된다

set(집합)은 순서가 없다

word = 'Mississipi'
print(set(word))
-----------------------------------------------
>>> {'s', 'M', 'p', 'i'}

 

  1. set에 추가  : add
    num = set([1,2,3,4,5])
    print(s)
    -------------------------------------
    >>> {1,2,3,4,5}
    
    num = set([1,2,3,4,5])
    num.add(6)
    print(num)
    --------------------------------------
    >>> {1, 2, 3, 4, 5, 6}​
  2. set에 여러개의 값을 추가 : update
    word_1 = set('Hello')		
    word_2 = set('Everyone')	
    word_1.update(word_2)			#update를 이용해 여러 개의 값을 추가
    print(set(word_1)
    ------------------------------------------------
    >>> {'r', 'l', 'v', 'E', 'y', 'e', 'o', 'n', 'H'}​
  3. set 안의 값 제거 : remove(set 집합 안에 원소가 없는 경우 KeyError가 발생), discard (set 집합 안에 원소가 없는경우에도 KeyError 발생 X)
    list = {0,1,2,3,4,5,4,3,2,1}
    print(list)
    list.discard(0)
    print(list)
    list.discard(7)         # discard는 set집합 안에 원소가 없는 경우에도 KeyError가 발생 X
    print(list)
    list.remove(7)          # remove는 set 집합 안에 원소가 없는 경우 KeyError가 발생
    print(list)
    -------------------------------------------------
    >>> {0, 1, 2, 3, 4, 5}
    >>> {1, 2, 3, 4, 5}
    >>> {1, 2, 3, 4, 5}
    >>> KeyError: 7
  4. set 연산자 활용 : 합집합( | or union), 교집합( & or intersection), 차집합( - or difference), 대칭차집합= 합집합- 교집합( ^ or symmetric_difference)
    i = {1,2,3,4,5}
    j = {2,5,8,0}
    print(i | j)						#합집합	
    print(i.union(j))					#합집합
    print(i & j)						#교집합
    print(i.intersection(j))			#교집합
    print(i-j)							#차집합
    print(i.difference(j))				#차집합
    print(i ^ j)						#대칭차집합
    print(i.symmetric_difference(j))	#대칭차집합
    -------------------------------------------------
    >>> {0, 1, 2, 3, 4, 5, 8}
    >>> {0, 1, 2, 3, 4, 5, 8}
    >>> {2, 5}
    >>> {2, 5}
    >>> {1, 3, 4}
    >>> {1, 3, 4}
    >>> {0, 1, 3, 4, 8}
    >>> {0, 1, 3, 4, 8}

 

<참고자료>

https://aigong.tistory.com/30

https://wikidocs.net/16044

'Baekjoon' 카테고리의 다른 글

백준 2908번 : 상수  (0) 2021.07.24
백준 1152 : 단어의 개수  (0) 2021.07.24
백준 2675번 : 문자열 반복  (0) 2021.07.24
백준 10809번 : 알파벳 찾기  (0) 2021.07.24
백준 11720번 : 숫자의 합  (0) 2021.07.23