알고리즘/BOJ

[BOJ 9167, Python 3] 도발 봇

70825 2022. 5. 7. 03:55
반응형

https://www.acmicpc.net/problem/9167

 

9167번: 도발 봇

중세 기사 시대에, 사악한 조롱에 대항하는 정신력, 즉 '멘탈'은 아주 중요한 것이었다. 킹 현우는 자신의 노예들이 약한 멘탈을 갖기를 바라지 않았다. 그래서 자신의 엄청난 코딩 능력으로 트

www.acmicpc.net

 

 

풀이


지문에 나온대로 구현을 하면 됩니다.

1) 모든 것을 딕셔너리에 저장하고 시뮬레이션 돌리기 (재귀 O)

2) taunt, sentence, ..., past-rel은 함수로 구현하고, 나머지는 딕셔너리에 저장하기 (재귀 X)

 

풀이는 위처럼 크게 두 가지로 나뉠 것 같구요. 저는 두 가지 방법 모두로 풀었습니다..

2번 풀이 같은 경우엔 jinhan814님 블로그에서 보고 풀었습니다.

 

계속 틀렸습니다가 나와서 블로그 풀이 글을 보고 코드를 짠 후에 틀린 점을 비교해봤는데, 예시에 나온 Knight의 경우엔 입력값의 첫 알파벳이 모두 대문자라서 이것도 도발 봇과 같이 첫글자를 대문자로 출력하게 만든게 원인이였네요. 그냥 입력값 그대로 출력을 해야했습니다.


 

 

 

코드 1


공유 소스 링크: https://www.acmicpc.net/source/share/a239afba917f457f9898dd7b7856f0fe

 

공유 소스 보기

def go(sentence): global taunt_count new_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 += 1 count[info] += 1 new_sentence += go(rule[info][count[info

www.acmicpc.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def go(sentence):
    global taunt_count
    new_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 += 1
            count[info] += 1
            new_sentence += go(rule[info][count[info] % len(rule[info])])
        elif info != 'taunt':
            new_sentence += go(rule[info][count[info] % len(rule[info])])
            count[info] += 1
    return new_sentence
 
import sys
input = sys.stdin.readline
rule = {'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 = 0
    for val in arr:
        flag = False
        for i in range(len(val)):
            if 0 <= ord(val[i].lower()) - ord('a'<= ord('z'- ord('a'):
                flag = True
        if flag: word += 1
 
    taunt_need_count = word // 3 + (1 if word % 3 else 0)
    taunt_count = 0
    answer = []
 
    exception_count = 0
    exception_rule = False
 
    for i in range(len(array[_])):
        if exception_rule: break
        if array[_][i].lower() == exception_sentence[exception_count]:
            exception_count += 1
        if exception_count == len(exception_sentence):
            exception_rule = True
    if exception_rule:
        taunt_count += 1
        answer.append(['(A childish hand gesture)'])
 
    while taunt_count < taunt_need_count:
        taunt_count += 1
        answer += [go(rule['taunt'][count['taunt'] % len(rule['taunt'])])]
        count['taunt'+= 1
 
    print('Knight:'' '.join(arr))
    for i in range(len(answer)):
        print('Taunter: ', end='')
        upper_flag = True
        for 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 = True
                elif upper_flag:
                    print(answer[i][j][k].upper(), end='')
                    upper_flag = False
                elseprint(answer[i][j][k], end='')
            if j + 1 != len(answer[i]) and answer[i][j + 1== '!'print('', end='')
            elif j != len(answer[i]) - 1print(' ', end='')
            elseprint('', end='')
        print('. ')
    if _ != len(array) -1print()
cs

 

 

 

코드 2


http://boj.kr/418ba93a03cb4b11b22fd34ac86b27e3

 

공유 소스 보기

def sentence(): val = count['sentence'] % 3 count['sentence'] += 1 if 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 ' + modi

www.acmicpc.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def sentence():
    val = count['sentence'] % 3
    count['sentence'+= 1
    if val == 0return past_rel() + ' ' + noun_phrase()
    elif val == 1return present_rel() + ' ' + noun_phrase()
    elsereturn past_rel() + ' a ' + noun()
 
def noun_phrase():
    return 'a ' + modified_noun()
 
def modified_noun():
    val = count['modified-noun'] % 2
    count['modified-noun'+= 1
    if val == 0return noun()
    elsereturn modifier() + ' ' + noun()
 
def modifier():
    val = count['modifier'] % 2
    count['modifier'+= 1
    if val == 0return adjective()
    elsereturn 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'] % 3
    count['present-person'+= 1
    return rule['present-person'][val]
 
def past_person():
    val = count['past-person'] % 5
    count['past-person'+= 1
    return rule['past-person'][val]
 
def noun():
    val = count['noun'] % 11
    count['noun'+= 1
    return rule['noun'][val]
 
def present_verb():
    val = count['present-verb'] % 2
    count['present-verb'+= 1
    return rule['present-verb'][val]
 
def past_verb():
    val = count['past-verb'] % 2
    count['past-verb'+= 1
    return rule['past-verb'][val]
 
def adjective():
    val = count['adjective'] % 7
    count['adjective'+= 1
    return rule['adjective'][val]
 
def adverb():
    val = count['adverb'] % 5
    count['adverb'+= 1
    return rule['adverb'][val]
 
import sys
input = sys.stdin.readline
rule = {'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 = 0
    for val in arr:
        flag = False
        for i in range(len(val)):
            if 0 <= ord(val[i].lower()) - ord('a'<= ord('z'- ord('a'):
                flag = True
        if flag: word += 1
 
    taunt_need_count = word // 3 + (1 if word % 3 else 0)
    taunt_count = 0
    answer = []
 
    # 예외 규칙 확인
    exception_count = 0
    exception_rule = False
 
    for i in range(len(array[_])):
        if exception_rule: break
        if array[_][i].lower() == exception_sentence[exception_count]:
            exception_count += 1
        if exception_count == len(exception_sentence):
            exception_rule = True
    if exception_rule:
        taunt_count += 1
        answer.append('(A childish hand gesture)')
 
    # 일반 도발봇
    while taunt_count < taunt_need_count:
        if count['taunt'] % 3 == 1:
            taunt_count += 2
            answer.append(noun() + '! ' + sentence())
        else:
            taunt_count += 1
            answer.append(sentence())
        count['taunt'+= 1
 
    # 답 출력
    print('Knight:'' '.join(arr))
 
    if len(answer) == 0print('Taunter: ')
    for i in range(len(answer)):
        print('Taunter: ', end='')
        if answer[i] == '(A childish hand gesture)'print(answer[i] + '.')
        else:
            upper_flag = True
            for j in range(len(answer[i])):
                if answer[i][j] == '!':
                    print(answer[i][j], end='')
                    upper_flag = True
                elif answer[i][j] != ' ' and upper_flag:
                    print(answer[i][j].upper(), end='')
                    upper_flag = False
                elseprint(answer[i][j], end='')
            print('. ')
    if _ != len(array) -1print()
cs

 

반응형