-
[BOJ 9167, Python 3] 도발 봇알고리즘/BOJ 2022. 5. 7. 03:55반응형
https://www.acmicpc.net/problem/9167
풀이
지문에 나온대로 구현을 하면 됩니다.
1) 모든 것을 딕셔너리에 저장하고 시뮬레이션 돌리기 (재귀 O)
2) taunt, sentence, ..., past-rel은 함수로 구현하고, 나머지는 딕셔너리에 저장하기 (재귀 X)
풀이는 위처럼 크게 두 가지로 나뉠 것 같구요. 저는 두 가지 방법 모두로 풀었습니다..
2번 풀이 같은 경우엔 jinhan814님 블로그에서 보고 풀었습니다.
계속 틀렸습니다가 나와서 블로그 풀이 글을 보고 코드를 짠 후에 틀린 점을 비교해봤는데, 예시에 나온 Knight의 경우엔 입력값의 첫 알파벳이 모두 대문자라서 이것도 도발 봇과 같이 첫글자를 대문자로 출력하게 만든게 원인이였네요. 그냥 입력값 그대로 출력을 해야했습니다.
코드 1
공유 소스 링크: https://www.acmicpc.net/source/share/a239afba917f457f9898dd7b7856f0fe
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687def go(sentence):global taunt_countnew_sentence = []for info in sentence:if info not in rule:new_sentence.append(info)elif info == 'taunt' and taunt_count <= taunt_need_count:taunt_count += 1count[info] += 1new_sentence += go(rule[info][count[info] % len(rule[info])])elif info != 'taunt':new_sentence += go(rule[info][count[info] % len(rule[info])])count[info] += 1return new_sentenceimport sysinput = sys.stdin.readlinerule = {'taunt': [['sentence'], ['taunt', 'sentence'], ['noun', '!'], ['sentence']],'sentence': [['past-rel', 'noun-phrase'], ['present-rel', 'noun-phrase'], ['past-rel','a', 'noun']],'noun-phrase': [['a', 'modified-noun']],'modified-noun': [['noun'], ['modifier', 'noun']],'modifier': [['adjective'], ['adverb', 'adjective']],'present-rel': [['your', 'present-person', 'present-verb']],'past-rel': [['your', 'past-person', 'past-verb']],'present-person': [['steed'], ['king'], ['first-born']],'past-person': [['mother'], ['father'], ['grandmother'], ['grandfather'], ['godfather']],'noun': [['hamster'], ['coconut'], ['duck'], ['herring'], ['newt'], ['peril'], ['chicken'], ['vole'], ['parrot'], ['mouse'], ['twit']],'present-verb': [['is'], ['masquerades as']],'past-verb': [['was'], ['personified']],'adjective': [['silly'], ['wicked'], ['sordid'], ['naughty'], ['repulsive'], ['malodorous'], ['ill-tempered']],'adverb': [['conspicuously'], ['categorically'], ['positively'], ['cruelly'], ['incontrovertibly']]}count = __import__('collections').defaultdict(lambda: 0)exception_sentence = 'theholygrail'array = [s.strip() for s in sys.stdin]for _ in range(len(array)):arr = array[_].split()word = 0for val in arr:flag = Falsefor i in range(len(val)):if 0 <= ord(val[i].lower()) - ord('a') <= ord('z') - ord('a'):flag = Trueif flag: word += 1taunt_need_count = word // 3 + (1 if word % 3 else 0)taunt_count = 0answer = []exception_count = 0exception_rule = Falsefor i in range(len(array[_])):if exception_rule: breakif array[_][i].lower() == exception_sentence[exception_count]:exception_count += 1if exception_count == len(exception_sentence):exception_rule = Trueif exception_rule:taunt_count += 1answer.append(['(A childish hand gesture)'])while taunt_count < taunt_need_count:taunt_count += 1answer += [go(rule['taunt'][count['taunt'] % len(rule['taunt'])])]count['taunt'] += 1print('Knight:', ' '.join(arr))for i in range(len(answer)):print('Taunter: ', end='')upper_flag = Truefor j in range(len(answer[i])):for k in range(len(answer[i][j])):if answer[i][j][k] == '!':print(answer[i][j][k], end='')upper_flag = Trueelif upper_flag:print(answer[i][j][k].upper(), end='')upper_flag = Falseelse: print(answer[i][j][k], end='')if j + 1 != len(answer[i]) and answer[i][j + 1] == '!': print('', end='')elif j != len(answer[i]) - 1: print(' ', end='')else: print('', end='')print('. ')if _ != len(array) -1: print()cs
코드 2
http://boj.kr/418ba93a03cb4b11b22fd34ac86b27e3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137def sentence():val = count['sentence'] % 3count['sentence'] += 1if val == 0: return past_rel() + ' ' + noun_phrase()elif val == 1: return present_rel() + ' ' + noun_phrase()else: return past_rel() + ' a ' + noun()def noun_phrase():return 'a ' + modified_noun()def modified_noun():val = count['modified-noun'] % 2count['modified-noun'] += 1if val == 0: return noun()else: return modifier() + ' ' + noun()def modifier():val = count['modifier'] % 2count['modifier'] += 1if val == 0: return adjective()else: return adverb() + ' ' + adjective()def present_rel():return 'your' + ' ' + present_person() + ' ' + present_verb()def past_rel():return 'your' + ' ' + past_person() + ' ' + past_verb()def present_person():val = count['present-person'] % 3count['present-person'] += 1return rule['present-person'][val]def past_person():val = count['past-person'] % 5count['past-person'] += 1return rule['past-person'][val]def noun():val = count['noun'] % 11count['noun'] += 1return rule['noun'][val]def present_verb():val = count['present-verb'] % 2count['present-verb'] += 1return rule['present-verb'][val]def past_verb():val = count['past-verb'] % 2count['past-verb'] += 1return rule['past-verb'][val]def adjective():val = count['adjective'] % 7count['adjective'] += 1return rule['adjective'][val]def adverb():val = count['adverb'] % 5count['adverb'] += 1return rule['adverb'][val]import sysinput = sys.stdin.readlinerule = {'present-person': ['steed', 'king', 'first-born'],'past-person': ['mother', 'father', 'grandmother', 'grandfather', 'godfather'],'noun': ['hamster', 'coconut', 'duck', 'herring', 'newt', 'peril', 'chicken', 'vole', 'parrot', 'mouse', 'twit'],'present-verb': ['is', 'masquerades as'],'past-verb': ['was', 'personified'],'adjective': ['silly', 'wicked', 'sordid', 'naughty', 'repulsive', 'malodorous', 'ill-tempered'],'adverb': ['conspicuously', 'categorically', 'positively', 'cruelly', 'incontrovertibly']}count = __import__('collections').defaultdict(lambda: 0)exception_sentence = 'theholygrail'array = []for s in sys.stdin:array.append(s.strip())for _ in range(len(array)):arr = array[_].split()word = 0for val in arr:flag = Falsefor i in range(len(val)):if 0 <= ord(val[i].lower()) - ord('a') <= ord('z') - ord('a'):flag = Trueif flag: word += 1taunt_need_count = word // 3 + (1 if word % 3 else 0)taunt_count = 0answer = []# 예외 규칙 확인exception_count = 0exception_rule = Falsefor i in range(len(array[_])):if exception_rule: breakif array[_][i].lower() == exception_sentence[exception_count]:exception_count += 1if exception_count == len(exception_sentence):exception_rule = Trueif exception_rule:taunt_count += 1answer.append('(A childish hand gesture)')# 일반 도발봇while taunt_count < taunt_need_count:if count['taunt'] % 3 == 1:taunt_count += 2answer.append(noun() + '! ' + sentence())else:taunt_count += 1answer.append(sentence())count['taunt'] += 1# 답 출력print('Knight:', ' '.join(arr))if len(answer) == 0: print('Taunter: ')for i in range(len(answer)):print('Taunter: ', end='')if answer[i] == '(A childish hand gesture)': print(answer[i] + '.')else:upper_flag = Truefor j in range(len(answer[i])):if answer[i][j] == '!':print(answer[i][j], end='')upper_flag = Trueelif answer[i][j] != ' ' and upper_flag:print(answer[i][j].upper(), end='')upper_flag = Falseelse: print(answer[i][j], end='')print('. ')if _ != len(array) -1: print()cs
반응형'알고리즘 > BOJ' 카테고리의 다른 글
[BOJ 4354, C++] 문자열 제곱 (2) 2022.08.15 [BOJ 8394, C++] 악수 (0) 2022.08.09 [BOJ 2424, Python 3] 부산의 해적 (0) 2021.10.26 [BOJ 23288, Python 3] 주사위 굴리기 2 (0) 2021.10.25 [BOJ 23240, Python 3] Colorful Tower of Hanoi (0) 2021.10.13