message stringlengths 2 23.4k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 129 108k | cluster float64 6 6 | __index_level_0__ int64 258 216k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.
At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.
Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.
He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
Input
The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format.
The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat.
The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line:
* <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat.
* <?>:<text> — the format of a message with unknown sender.
The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters.
We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha".
It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
Output
Print the information about the t chats in the following format:
If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format:
<username>:<text>
If there are multiple answers, print any of them.
Examples
Input
1
2
Vladik netman
2
?: Hello, Vladik!
?: Hi
Output
netman: Hello, Vladik!
Vladik: Hi
Input
1
2
netman vladik
3
netman:how are you?
?:wrong message
vladik:im fine
Output
Impossible
Input
2
3
netman vladik Fedosik
2
?: users are netman, vladik, Fedosik
vladik: something wrong with this chat
4
netman tigerrrrr banany2001 klinchuh
4
?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
?: yes, netman
banany2001: yes of course.
Output
Impossible
netman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
tigerrrrr: yes, netman
banany2001: yes of course.
Submitted Solution:
```
#!/usr/bin/python3
# BEGIN template
import sys
import re
import pprint
def dbg(x,y=''):
if len(y) > 0: y += ' = '
sys.stderr.write('\n>>> '+y+pprint.pformat(x)+'\n')
oo = 0x3f3f3f3f3f3f3f3f
# END template
def main():
t = int(input())
for t in range(t):
# input
n = int(input())
users = set(input().split())
m = int(input())
msg = []
for i in range(m):
user, text = input().split(':')
alts = set()
if user != '?':
alts.add(user)
else:
# this shit is pretty fucked up, dude
alts = users - set(re.findall('[a-zA-Z][a-zA-Z0-9]*',text))
msg.append(dict(user=user, text=text, users=alts))
# remove before and after
for i in range(m-1):
if len(msg[i]['users']) == 1:
msg[i+1]['users'].difference_update(msg[i]['users'])
for i in range(m-1,0,-1):
if len(msg[i]['users']) == 1:
msg[i-1]['users'].difference_update(msg[i]['users'])
# compute answer
last = ''
impo = False
for i in range(m):
msg[i]['users'].discard(last)
if len(msg[i]['users']) == 0:
impo = True
break
last = next(iter(msg[i]['users']))
msg[i]['user'] = last
if impo:
print('Impossible')
continue
for i in range(m):
print(msg[i]['user']+':'+msg[i]['text'])
'''
dp = [[0 for j in range(n+5)] for i in range(m+5)]
for i in range(1,n+5):
dp[m+1][i] = oo
for i in range(m,0,-1):
for j in range(n+1):
for k in msg[i]['users']:
if k != j and dp[i+1][k]:
dp[i][j] = k
break
# output
if not dp[1][0]:
print('Impossible')
continue
j = 0
for i in range(1,m+1):
print(users[dp[i][j]]+':'+msg[i]['text'])
j = dp[i][j]'''
main()
``` | instruction | 0 | 65,325 | 6 | 130,650 |
No | output | 1 | 65,325 | 6 | 130,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.
At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.
Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.
He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
Input
The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format.
The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat.
The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line:
* <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat.
* <?>:<text> — the format of a message with unknown sender.
The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters.
We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha".
It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
Output
Print the information about the t chats in the following format:
If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format:
<username>:<text>
If there are multiple answers, print any of them.
Examples
Input
1
2
Vladik netman
2
?: Hello, Vladik!
?: Hi
Output
netman: Hello, Vladik!
Vladik: Hi
Input
1
2
netman vladik
3
netman:how are you?
?:wrong message
vladik:im fine
Output
Impossible
Input
2
3
netman vladik Fedosik
2
?: users are netman, vladik, Fedosik
vladik: something wrong with this chat
4
netman tigerrrrr banany2001 klinchuh
4
?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
?: yes, netman
banany2001: yes of course.
Output
Impossible
netman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
tigerrrrr: yes, netman
banany2001: yes of course.
Submitted Solution:
```
messages = []
users = []
class Message:
senders = []
def __init__(self, data):
self.text = data[1]
self.sender = None if data[0] == '?' else data[0]
if self.sender is None:
self.find_sender()
def find_sender(self):
users_found = set()
for user in users:
found = self.text.find(user)
if found != -1:
if self.text[found-1] == ' ' or not (self.text[found-1].isdigit() and self.text[found-1].isalpha()):
users_found.add(user)
self.senders = list(users ^ users_found)
if len(self.senders) == 1:
self.sender = self.senders[0]
def check(self, next=None, prev=None):
if len(self.senders) > 3:
return None
else:
if next is not None:
try:
self.senders.remove(messages[next].sender)
except ValueError:
pass
if prev is not None:
try:
self.senders.remove(messages[prev].sender)
except ValueError:
pass
if len(self.senders) != 1:
return None
else:
self.sender = self.senders[0]
return 1
def main():
global messages
tests = int(input())
for test in range(tests):
if current_test():
for msg in messages:
print(msg.sender, msg.text, sep=':')
else:
print("Impossible")
def current_test():
global messages
global users
messages = []
users = input()
users = set(input().split(' '))
message_count = int(input())
for message in range(message_count):
messages.append(Message(input().split(':')))
for message_id in range(len(messages)):
message = messages[message_id]
if message.sender is None:
if message_id != 0 and message_id != len(messages) - 1:
if message.check(message_id + 1, message_id - 1) is None:
return False
elif message_id == 0:
if message.check(next=message_id + 1) is None:
return False
else:
if message.check(prev=message_id - 1) is None:
return False
return True
main()
``` | instruction | 0 | 65,326 | 6 | 130,652 |
No | output | 1 | 65,326 | 6 | 130,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.
At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.
Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.
He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
Input
The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format.
The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat.
The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line:
* <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat.
* <?>:<text> — the format of a message with unknown sender.
The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters.
We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha".
It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
Output
Print the information about the t chats in the following format:
If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format:
<username>:<text>
If there are multiple answers, print any of them.
Examples
Input
1
2
Vladik netman
2
?: Hello, Vladik!
?: Hi
Output
netman: Hello, Vladik!
Vladik: Hi
Input
1
2
netman vladik
3
netman:how are you?
?:wrong message
vladik:im fine
Output
Impossible
Input
2
3
netman vladik Fedosik
2
?: users are netman, vladik, Fedosik
vladik: something wrong with this chat
4
netman tigerrrrr banany2001 klinchuh
4
?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
?: yes, netman
banany2001: yes of course.
Output
Impossible
netman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
tigerrrrr: yes, netman
banany2001: yes of course.
Submitted Solution:
```
import re
def proc(msgs):
chg = False
for i, msg in enumerate(msgs):
if msg[0] != '?': continue
ppn = msg[1]
if i > 0: ppn.discard(msgs[i-1][0])
if i != len(msgs)-1: ppn.discard(msgs[i+1][0])
if len(ppn) == 1:
msg[0] = ppn.pop()
chg = True
return chg
TC = int(input())
for tc in range(0, TC):
N = int(input())
persons = set(input().split())
M = int(input())
msgs = []
for m in range(M):
line = input()
m1 = re.match(r'(.*)\:(.*)', line)
ppn = set(persons)
for un in re.findall(r'[a-zA-Z0-9]+', m1.group(2)):
ppn.discard(un)
msgs.append([m1.group(1), ppn, m1.group(2)])
while proc(msgs):
pass
works = True
for i, msg in enumerate(msgs):
if msg[0] == '?' or (i > 0 and msg[0] == msgs[i-1][0]) or (i != len(msgs)-1 and msg[0] == msgs[i+1][0]):
works = False
break
if works:
for msg in msgs:
print('%s:%s' % (msg[0], msg[2]))
else:
print('Impossible')
``` | instruction | 0 | 65,327 | 6 | 130,654 |
No | output | 1 | 65,327 | 6 | 130,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.
At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.
Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.
He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
Input
The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format.
The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat.
The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line:
* <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat.
* <?>:<text> — the format of a message with unknown sender.
The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters.
We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha".
It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
Output
Print the information about the t chats in the following format:
If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format:
<username>:<text>
If there are multiple answers, print any of them.
Examples
Input
1
2
Vladik netman
2
?: Hello, Vladik!
?: Hi
Output
netman: Hello, Vladik!
Vladik: Hi
Input
1
2
netman vladik
3
netman:how are you?
?:wrong message
vladik:im fine
Output
Impossible
Input
2
3
netman vladik Fedosik
2
?: users are netman, vladik, Fedosik
vladik: something wrong with this chat
4
netman tigerrrrr banany2001 klinchuh
4
?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
?: yes, netman
banany2001: yes of course.
Output
Impossible
netman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?
klinchuh: yes, coach!
tigerrrrr: yes, netman
banany2001: yes of course.
Submitted Solution:
```
#!/usr/bin/python3
# BEGIN template
import sys
import re
import pprint
def dbg(x,y=''):
if len(y) > 0: y += ' = '
sys.stderr.write('\n>>> '+y+pprint.pformat(x)+'\n')
oo = 0x3f3f3f3f3f3f3f3f
# END template
def main():
for t in range(int(input())):
# input
n = int(input())
users = set(input().split())
m = int(input())
msg = []
for i in range(m):
user, text = input().split(':')
alts = set()
if user != '?':
alts.add(user)
else:
# this shit is pretty fucked up, dude
alts = users - set(re.findall('[a-zA-Z][a-zA-Z0-9]*',text))
msg.append(dict(user=user, text=text, users=alts))
# remove before and after
for i in range(m):
if len(msg[i]['users']) > 1: continue
t = False
if 0 <= i-1:
msg[i-1]['users'].difference_update(msg[i]['users'])
t = True
if t and i+1 < m: msg[i+1]['users'].difference_update(msg[i]['users'])
# compute answer
last = ''
impo = False
for i in range(m):
msg[i]['users'].discard(last)
if len(msg[i]['users']) == 0:
impo = True
break
last = next(iter(msg[i]['users']))
msg[i]['user'] = last
if impo:
print('Impossible')
continue
for i in range(m):
print(msg[i]['user']+':'+msg[i]['text'])
'''
dp = [[0 for j in range(n+5)] for i in range(m+5)]
for i in range(1,n+5):
dp[m+1][i] = oo
for i in range(m,0,-1):
for j in range(n+1):
for k in msg[i]['users']:
if k != j and dp[i+1][k]:
dp[i][j] = k
break
# output
if not dp[1][0]:
print('Impossible')
continue
j = 0
for i in range(1,m+1):
print(users[dp[i][j]]+':'+msg[i]['text'])
j = dp[i][j]'''
main()
``` | instruction | 0 | 65,328 | 6 | 130,656 |
No | output | 1 | 65,328 | 6 | 130,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1 | instruction | 0 | 65,382 | 6 | 130,764 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
print(-1)
else:
res = []
for i in range(n):
k = 0
while(s[k] != t[i]):
k += 1
res += [n - k - 1, 1, n]
s = ''.join(reversed(s[:k])) + s[k + 1:] + s[k]
# print(s)
print(len(res))
print(*res)
``` | output | 1 | 65,382 | 6 | 130,765 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1 | instruction | 0 | 65,383 | 6 | 130,766 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
t = input()[:n]
s = input()[:n]
ops =[]
def shift(k, cur):
if k == 0:
return cur
return cur[:-k-1:-1] + cur [:-k]
def move_to_front(k, curst):
if k == n-1:
ops.append(1)
curst = curst[-1] +curst [:-1]
else:
ops.append(n-1)
ops.append(k)
ops.append(1)
curst = curst[k] + curst[:k] + curst[-1:k:-1]
return curst
def find_char(char, t):
for m,cur_c in enumerate(t[::-1]):
if cur_c == char:
# print(t, 'found', char, ' at', n-m -1)
return n- m -1
return 0
# t = 'abcdefg'
# for j in range(len(t)):
# print('before', j, t)
# t = move_to_front(j, t )
# print(' after', j, t)
# print()
from collections import Counter
scount = Counter(s)
tcount = Counter(t)
ori_t = t
if scount != tcount:
print(-1)
exit()
for char in s[::-1]:
t = move_to_front(find_char(char, t), t)
# print('got t', t)
print(len(ops))
print(*ops)
# for op in ops:
# print(op, ori_t, shift(op, ori_t))
# ori_t = shift(op, ori_t)
#
# print(ori_t)
``` | output | 1 | 65,383 | 6 | 130,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1 | instruction | 0 | 65,384 | 6 | 130,768 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
print(-1)
else:
ans = []
for i in t:
j = 0
for j in range(n):
if i == s[j]:
break
ans.append(n-j-1)
ans.append(1)
ans.append(n)
s = "".join(reversed(s[:j])) + s[j+1:] + s[j]
print(len(ans))
for i in ans:
print(i, end=' ')
``` | output | 1 | 65,384 | 6 | 130,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1 | instruction | 0 | 65,385 | 6 | 130,770 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
print(-1)
else:
ans = []
for i in t:
j = 0
for j in range(n):
if i == s[j]:
break
ans.append(n-j-1)
ans.append(1)
ans.append(n)
s =s[j-n-1:-n-1:-1] + s[j+1:] + s[j]
print(len(ans))
for i in ans:
print(i, end=' ')
``` | output | 1 | 65,385 | 6 | 130,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1 | instruction | 0 | 65,386 | 6 | 130,772 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
print(-1)
else:
res = []
for i in range(n):
k = 0;
while(s[k] != t[i]):
k += 1
res += [n-k-1, 1, n]
s = "".join(reversed(s[:k])) + s[k+1:] + s[k]
#print(s)
print(len(res))
print(*res)
``` | output | 1 | 65,386 | 6 | 130,773 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1
Submitted Solution:
```
n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
print(-1)
else:
ans = []
for i in t:
j = 0
for j in range(n):
if i == s[j]:
break
ans.append(n-j-1)
ans.append(1)
ans.append(n)
p = s[:j] + s[j+1:] + s[j]
s = p
print(len(ans))
print(ans)
``` | instruction | 0 | 65,387 | 6 | 130,774 |
No | output | 1 | 65,387 | 6 | 130,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1
Submitted Solution:
```
n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
print(-1)
else:
ans = []
for i in t:
j = 0
for j in range(n):
if i == s[j]:
break
ans.append(n-j-1)
ans.append(1)
ans.append(n)
p = s[:j] + s[j+1:] + s[j]
s = p
print(len(ans))
for i in ans:
print(i, end=' ')
``` | instruction | 0 | 65,388 | 6 | 130,776 |
No | output | 1 | 65,388 | 6 | 130,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1
Submitted Solution:
```
n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
print(-1)
else:
res = []
for i in range(n):
k = 0
while(s[k] != t[i]):
k += 1
res += [k + 1, n - k, n]
s = ''.join(reversed(s[:k])) + s[k + 1:] + s[k]
print(s)
print(len(res))
print(*res)
``` | instruction | 0 | 65,389 | 6 | 130,778 |
No | output | 1 | 65,389 | 6 | 130,779 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
Input
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
Output
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
Examples
Input
6
abacbb
babcba
Output
4
6 3 2 3
Input
3
aba
bba
Output
-1
Submitted Solution:
```
n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
print(-1)
else:
res = []
for i in range(n):
k = 0
while(s[k] != s[i]):
k += 1
res += [k + 1, n - k, n]
s = s[k - 1::-1] + s[k + 1:] + s[k]
print(len(res))
print(*res)
``` | instruction | 0 | 65,390 | 6 | 130,780 |
No | output | 1 | 65,390 | 6 | 130,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Input
The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message.
The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper.
Here |a| means the length of the string a.
Output
Print two integers separated by a space:
* the first number is the number of times Tanya shouts "YAY!" while making the message,
* the second number is the number of times Tanya says "WHOOPS" while making the message.
Examples
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
3 4 | instruction | 0 | 65,992 | 6 | 131,984 |
Tags: greedy, implementation, strings
Correct Solution:
```
first = input()
second = input()
dicty = {}
for i in first:
if(i not in dicty):
dicty[i] = 1
else:
dicty[i] += 1
yay = 0
whoops = 0
array_bool = [False for x in second]
for i in range(len(second)):
if (second[i] in dicty and dicty[second[i]] != 0):
yay+=1
dicty[second[i]] -= 1
array_bool[i] = True
for i in range(len(second)):
if(not array_bool[i]):
if (second[i].upper() in dicty and dicty[second[i].upper()] != 0):
whoops += 1
dicty[second[i].upper()] -= 1
elif (second[i].lower() in dicty and dicty[second[i].lower()] != 0):
whoops += 1
dicty[second[i].lower()] -= 1
print(yay,whoops)
``` | output | 1 | 65,992 | 6 | 131,985 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Input
The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message.
The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper.
Here |a| means the length of the string a.
Output
Print two integers separated by a space:
* the first number is the number of times Tanya shouts "YAY!" while making the message,
* the second number is the number of times Tanya says "WHOOPS" while making the message.
Examples
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
3 4 | instruction | 0 | 65,993 | 6 | 131,986 |
Tags: greedy, implementation, strings
Correct Solution:
```
s = input()
t = input()
oc = {}
yay=0
whoops=0
resto=''
for l1 in t:
oc[l1] = oc.get(l1, 0)+1
for l2 in s:
if oc.get(l2, 0)>0:
oc[l2]-=1
yay+=1
else:
resto+=l2
for l3 in resto:
aux=l3.swapcase()
if oc.get(aux, 0)>0:
oc[aux]-=1
whoops+=1
print(yay,whoops)
``` | output | 1 | 65,993 | 6 | 131,987 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Input
The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message.
The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper.
Here |a| means the length of the string a.
Output
Print two integers separated by a space:
* the first number is the number of times Tanya shouts "YAY!" while making the message,
* the second number is the number of times Tanya says "WHOOPS" while making the message.
Examples
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
3 4 | instruction | 0 | 65,994 | 6 | 131,988 |
Tags: greedy, implementation, strings
Correct Solution:
```
alth = "abcdefghijklmnopqrstuvwxyz"
alth2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
s2 = [[0]*26 for i in range(2)]
s3 = [[0]*26 for i in range(2)]
s = input()
t = input()
num = 0
num2 = 0
for i in s:
temp = alth.find(i)
if temp != -1:
s2[0][temp] += 1
temp = alth2.find(i)
if temp != -1:
s2[1][temp] += 1
for i in t:
temp = alth.find(i)
if temp != -1:
s3[0][temp] += 1
temp = alth2.find(i)
if temp != -1:
s3[1][temp] += 1
for i in range(2):
for j in range(26):
x = min(s2[i][j],s3[i][j])
num += x
s2[i][j] -= x
s3[i][j] -= x
for i in range(2):
for j in range(26):
num2 += min(s2[i][j],s3[1-i][j])
print(num,num2)
``` | output | 1 | 65,994 | 6 | 131,989 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Input
The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message.
The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper.
Here |a| means the length of the string a.
Output
Print two integers separated by a space:
* the first number is the number of times Tanya shouts "YAY!" while making the message,
* the second number is the number of times Tanya says "WHOOPS" while making the message.
Examples
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
3 4 | instruction | 0 | 65,995 | 6 | 131,990 |
Tags: greedy, implementation, strings
Correct Solution:
```
import math
t=1
for _ in range(t):
msg=input()
news=input()
newsdict=dict()
for i in news:
a=newsdict.get(i,0)
newsdict[i]=a+1
yay=0
remainingdict=dict()
for i in msg:
a=newsdict.get(i,0)
if(a>0):
newsdict[i]-=1
yay+=1
else:
b=remainingdict.get(i,0)
remainingdict[i]=b+1
whoops=0
for i in remainingdict.keys():
char=i
othercase=i.swapcase()
c=newsdict.get(othercase,0)
if(c>0):
whoops+=min(remainingdict[i], newsdict[othercase])
print(yay, whoops)
``` | output | 1 | 65,995 | 6 | 131,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Input
The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message.
The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper.
Here |a| means the length of the string a.
Output
Print two integers separated by a space:
* the first number is the number of times Tanya shouts "YAY!" while making the message,
* the second number is the number of times Tanya says "WHOOPS" while making the message.
Examples
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
3 4 | instruction | 0 | 65,996 | 6 | 131,992 |
Tags: greedy, implementation, strings
Correct Solution:
```
s1 = input()
s2 = input()
TAM = 26
a_min = ord("a")
a_mai = ord("A")
ls1_min = [0]*TAM
ls1_mai = [0]*TAM
ls2_min = [0]*TAM
ls2_mai = [0]*TAM
for letra in s1:
if letra.islower():
ls1_min[ord(letra) - a_min] += 1
else:
ls1_mai[ord(letra) - a_mai] += 1
for letra in s2:
if letra.islower():
ls2_min[ord(letra) - a_min] += 1
else:
ls2_mai[ord(letra) - a_mai] += 1
yay = 0
whoops = 0
for letra in range(TAM):
casos = min(ls1_min[letra], ls2_min[letra])
yay += casos
ls1_min[letra] -= casos
ls2_min[letra] -= casos
casos = min(ls1_mai[letra], ls2_mai[letra])
yay += casos
ls1_mai[letra] -= casos
ls2_mai[letra] -= casos
for letra in range(TAM):
casos = min(ls1_min[letra], ls2_mai[letra])
casos += min(ls1_mai[letra], ls2_min[letra])
whoops += casos
print(yay, whoops)
``` | output | 1 | 65,996 | 6 | 131,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Input
The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message.
The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper.
Here |a| means the length of the string a.
Output
Print two integers separated by a space:
* the first number is the number of times Tanya shouts "YAY!" while making the message,
* the second number is the number of times Tanya says "WHOOPS" while making the message.
Examples
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
3 4 | instruction | 0 | 65,997 | 6 | 131,994 |
Tags: greedy, implementation, strings
Correct Solution:
```
msg = input()
letters = input()
yays = 0
whoops = 0
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
rest = []
leaks = []
i= 0
for l in alphabet:
original = msg.count(l)
journal = letters.count(l)
if journal >= original:
yays += original
journal -= original
if (len(rest) < 26):
rest.append(journal)
leaks.append(0)
else:
rest[i%26] += journal
else:
yays += journal
original -= journal
if (len(leaks) < 26):
leaks.append(original)
rest.append(0)
else:
leaks[i%26] += original
i+=1
for i in range(26):
if rest[i] > 0 and leaks[i] > 0:
if rest[i] >= leaks[i]: whoops += leaks[i]
else: whoops += rest[i]
print(yays,whoops)
``` | output | 1 | 65,997 | 6 | 131,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Input
The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message.
The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper.
Here |a| means the length of the string a.
Output
Print two integers separated by a space:
* the first number is the number of times Tanya shouts "YAY!" while making the message,
* the second number is the number of times Tanya says "WHOOPS" while making the message.
Examples
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
3 4 | instruction | 0 | 65,998 | 6 | 131,996 |
Tags: greedy, implementation, strings
Correct Solution:
```
def solve():
d={}
s=input()
t=input()
n=len(s)
m=len(t)
for i in range(0,26):
d[chr(ord('a')+i)]=0
d[chr(ord('A')+i)]=0
for i in range(0,m):
d[t[i]]+=1
y=0
w=0
x=[0]*n
for i in range(0,n):
if(d[s[i]]>0):
x[i]=1
y+=1
d[s[i]]-=1
for i in range(0,n):
if(x[i]):
continue
if(ord(s[i])<=ord('z') and ord(s[i])>=ord('a')):
if(d[chr(ord(s[i])-ord('a')+ord('A'))]>0):
w+=1
d[chr(ord(s[i])-ord('a')+ord('A'))]-=1
else:
if(d[chr(ord(s[i])-ord('A')+ord('a'))]>0):
w+=1
d[chr(ord(s[i])-ord('A')+ord('a'))]-=1
print(y,w)
t=1
#t=int(input())
for _ in range(t):
solve()
``` | output | 1 | 65,998 | 6 | 131,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
Input
The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message.
The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper.
Here |a| means the length of the string a.
Output
Print two integers separated by a space:
* the first number is the number of times Tanya shouts "YAY!" while making the message,
* the second number is the number of times Tanya says "WHOOPS" while making the message.
Examples
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
3 4 | instruction | 0 | 65,999 | 6 | 131,998 |
Tags: greedy, implementation, strings
Correct Solution:
```
s1 = input()
s2 = input()
ms1 = [0]*26
ms2 = [0]*26
ms3 = [0]*26
ms4 = [0]*26
m = 0
n = 0
for i in range (len(s1)):
if ord(s1[i]) <= ord('Z'):
ms1[ord(s1[i])-ord('A')] += 1
else:
ms2[ord(s1[i])-ord('a')] += 1
for i in range (len(s2)):
if ord(s2[i]) <= ord('Z'):
ms3[ord(s2[i])-ord('A')] += 1
else:
ms4[ord(s2[i])-ord('a')] += 1
for i in range(len(ms1)):
if ms3[i] and ms1[i]:
mn = min(ms3[i],ms1[i])
m += mn
ms3[i] -= mn
ms1[i] -= mn
if ms2[i] and ms4[i]:
mn = min(ms2[i],ms4[i])
m += mn
ms2[i] -= mn
ms4[i] -= mn
for i in range (len(ms1)):
if ms3[i] and ms2[i]:
mn = min(ms2[i],ms3[i])
n += mn
ms3[i] -= mn
ms2[i] -= mn
if ms1[i] and ms4[i]:
mn = min(ms1[i],ms4[i])
n += mn
ms1[i] -= mn
ms4[i] -= mn
print(m, n)
``` | output | 1 | 65,999 | 6 | 131,999 |
Provide a correct Python 3 solution for this coding contest problem.
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.
Input
A text is given in a line. You can assume the following conditions:
* The number of letters in the text is less than or equal to 1000.
* The number of letters in a word is less than or equal to 32.
* There is only one word which is arise most frequently in given text.
* There is only one word which has the maximum number of letters in given text.
Output
The two words separated by a space.
Example
Input
Thank you for your mail and your lectures
Output
your lectures | instruction | 0 | 66,370 | 6 | 132,740 |
"Correct Solution:
```
x = list(input().split())
print(max(x,key=x.count), max(x,key=len))
``` | output | 1 | 66,370 | 6 | 132,741 |
Provide a correct Python 3 solution for this coding contest problem.
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.
Input
A text is given in a line. You can assume the following conditions:
* The number of letters in the text is less than or equal to 1000.
* The number of letters in a word is less than or equal to 32.
* There is only one word which is arise most frequently in given text.
* There is only one word which has the maximum number of letters in given text.
Output
The two words separated by a space.
Example
Input
Thank you for your mail and your lectures
Output
your lectures | instruction | 0 | 66,371 | 6 | 132,742 |
"Correct Solution:
```
x=input().split()
longestWord= ""
mostWord=0
currentCount=0
THEmostWord=""
for r in range (len(x)):
if len(x[r])> len(longestWord):
longestWord=x[r]
for j in range (len(x)):
currentCount=x.count(x[j])
if currentCount > mostWord:
mostWord= currentCount
THEmostWord=x[j]
print(THEmostWord, longestWord)
``` | output | 1 | 66,371 | 6 | 132,743 |
Provide a correct Python 3 solution for this coding contest problem.
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.
Input
A text is given in a line. You can assume the following conditions:
* The number of letters in the text is less than or equal to 1000.
* The number of letters in a word is less than or equal to 32.
* There is only one word which is arise most frequently in given text.
* There is only one word which has the maximum number of letters in given text.
Output
The two words separated by a space.
Example
Input
Thank you for your mail and your lectures
Output
your lectures | instruction | 0 | 66,373 | 6 | 132,746 |
"Correct Solution:
```
from collections import defaultdict as dd
a=dd(int)
freq=0
leng=""
seq=""
b=input().split()
for i in b:
a[i]+=1
if a[seq]<a[i]:
seq=i
if len(leng)<len(i):
leng=i
print(seq,leng)
``` | output | 1 | 66,373 | 6 | 132,747 |
Provide a correct Python 3 solution for this coding contest problem.
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.
Input
A text is given in a line. You can assume the following conditions:
* The number of letters in the text is less than or equal to 1000.
* The number of letters in a word is less than or equal to 32.
* There is only one word which is arise most frequently in given text.
* There is only one word which has the maximum number of letters in given text.
Output
The two words separated by a space.
Example
Input
Thank you for your mail and your lectures
Output
your lectures | instruction | 0 | 66,374 | 6 | 132,748 |
"Correct Solution:
```
text = input().split()
l = {}
dc = {}
for i in text:
l[i] = len(i)
if i in dc.keys():
dc[i] += 1
else:
dc[i] = 0
print(max(dc, key=dc.get), max(l, key=l.get))
``` | output | 1 | 66,374 | 6 | 132,749 |
Provide a correct Python 3 solution for this coding contest problem.
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.
Input
A text is given in a line. You can assume the following conditions:
* The number of letters in the text is less than or equal to 1000.
* The number of letters in a word is less than or equal to 32.
* There is only one word which is arise most frequently in given text.
* There is only one word which has the maximum number of letters in given text.
Output
The two words separated by a space.
Example
Input
Thank you for your mail and your lectures
Output
your lectures | instruction | 0 | 66,375 | 6 | 132,750 |
"Correct Solution:
```
from collections import Counter
s = list(input().split())
c = Counter(s)
n,m = 0,0
for e in s:
if n < len(e):
n = len(e)
m = e
print(c.most_common()[0][0],m)
``` | output | 1 | 66,375 | 6 | 132,751 |
Provide a correct Python 3 solution for this coding contest problem.
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.
Input
A text is given in a line. You can assume the following conditions:
* The number of letters in the text is less than or equal to 1000.
* The number of letters in a word is less than or equal to 32.
* There is only one word which is arise most frequently in given text.
* There is only one word which has the maximum number of letters in given text.
Output
The two words separated by a space.
Example
Input
Thank you for your mail and your lectures
Output
your lectures | instruction | 0 | 66,377 | 6 | 132,754 |
"Correct Solution:
```
import collections
x = input().split()
c = collections.Counter(x)
max = 0
for i in range(len(x)):
a = len(x[i])
if a>max:
max = a
M = x[i]
print(c.most_common()[0][0], M)
``` | output | 1 | 66,377 | 6 | 132,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | instruction | 0 | 66,985 | 6 | 133,970 |
Tags: implementation, strings
Correct Solution:
```
e=int(input())
print(len(set([''.join(sorted(list(set(x)))) for x in input().split()])))
``` | output | 1 | 66,985 | 6 | 133,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | instruction | 0 | 66,986 | 6 | 133,972 |
Tags: implementation, strings
Correct Solution:
```
ar = []
n = int(input())
a = list(input().split())
for i in a:
temp = set(i)
temp = "".join(sorted(temp))
if temp not in ar:
ar.append(temp)
print(len(ar))
``` | output | 1 | 66,986 | 6 | 133,973 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | instruction | 0 | 66,987 | 6 | 133,974 |
Tags: implementation, strings
Correct Solution:
```
import atexit
import io
import sys
# Buffering IO
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
def main():
n = int(input())
ss = input().split()
s = set()
for x in ss:
s.add(''.join(sorted(list(set(x)))))
print(len(s))
if __name__ == '__main__':
main()
``` | output | 1 | 66,987 | 6 | 133,975 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | instruction | 0 | 66,988 | 6 | 133,976 |
Tags: implementation, strings
Correct Solution:
```
n = int(input())
l = list(map(set, input().split(' ')))
s = list()
for i in l:
if not i in s:
s.append(i)
print(len(s))
``` | output | 1 | 66,988 | 6 | 133,977 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | instruction | 0 | 66,989 | 6 | 133,978 |
Tags: implementation, strings
Correct Solution:
```
n=int(input())
ar=input().split()
z=set()
for x in ar:
x=list(x)
x.sort()
x=''.join(list(set(''.join(x))))
z.add(x)
print(len(z))
``` | output | 1 | 66,989 | 6 | 133,979 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | instruction | 0 | 66,990 | 6 | 133,980 |
Tags: implementation, strings
Correct Solution:
```
n = int(input())
s = {''.join(sorted(set(s))) for s in input().split()}
print(len(s))
``` | output | 1 | 66,990 | 6 | 133,981 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | instruction | 0 | 66,991 | 6 | 133,982 |
Tags: implementation, strings
Correct Solution:
```
n = input()
s = input().split()
a = set()
list = []
for i in s:
if set(i) not in list:
list.append(set(i))
print(len(list))
``` | output | 1 | 66,991 | 6 | 133,983 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | instruction | 0 | 66,992 | 6 | 133,984 |
Tags: implementation, strings
Correct Solution:
```
def f():
n = int(input())
b = []
x = input().split()
for i in range(n):
a = x[i]
a = list(set([i for i in a]))
b.append(frozenset(a))
b = list(set(b))
print(b.__len__())
f()
``` | output | 1 | 66,992 | 6 | 133,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Submitted Solution:
```
n = int(input())
a = list(map(list,input().split()))
b = []
for i in range(len(a)):
a[i] = list(set(a[i])); a[i].sort()
if not a[i] in b: b.append(a[i])
print(len(b))
``` | instruction | 0 | 66,993 | 6 | 133,986 |
Yes | output | 1 | 66,993 | 6 | 133,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Submitted Solution:
```
n = int(input())
mas = map(set, input().split())
gas = []
q = 0
pr = set('zyxwvutsrqponmlkjihgfedcba')
for el in mas:
if not el & pr in gas:
q += 1
gas.append(el & pr)
print(q)
``` | instruction | 0 | 66,994 | 6 | 133,988 |
Yes | output | 1 | 66,994 | 6 | 133,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Submitted Solution:
```
input(); print(len(set(''.join(sorted(set(x))) for x in input().split())))
``` | instruction | 0 | 66,995 | 6 | 133,990 |
Yes | output | 1 | 66,995 | 6 | 133,991 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Submitted Solution:
```
n=int(input())
s=set()
l=list(input().split())
for i in l:
s.add("".join(sorted(list(set(i)))))
print(len(list(s)))
``` | instruction | 0 | 66,996 | 6 | 133,992 |
Yes | output | 1 | 66,996 | 6 | 133,993 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Submitted Solution:
```
n=int(input())
s=input().split()
for i in range(n):
s[i]=str(set(s[i]))
print(len(set(s)))
``` | instruction | 0 | 66,997 | 6 | 133,994 |
No | output | 1 | 66,997 | 6 | 133,995 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Submitted Solution:
```
input()
print(len(list(set(list(map(str,map(set, input().split(' '))))))))
``` | instruction | 0 | 66,998 | 6 | 133,996 |
No | output | 1 | 66,998 | 6 | 133,997 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Submitted Solution:
```
def j(x):
return "".join(list(x))
input()
print(len(set(list(map(j,list(map(set, input().split(' '))))))))
``` | instruction | 0 | 66,999 | 6 | 133,998 |
No | output | 1 | 66,999 | 6 | 133,999 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Aramic language words can only represent objects.
Words in Aramic have special properties:
* A word is a root if it does not contain the same letter more than once.
* A root and all its permutations represent the same object.
* The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".
* Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
Input
The first line contains one integer n (1 ≤ n ≤ 10^3) — the number of words in the script.
The second line contains n words s_1, s_2, …, s_n — the script itself. The length of each string does not exceed 10^3.
It is guaranteed that all characters of the strings are small latin letters.
Output
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
Examples
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
Note
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Submitted Solution:
```
input()
print(len(set(map(str,map(set,input().split())))))
``` | instruction | 0 | 67,000 | 6 | 134,000 |
No | output | 1 | 67,000 | 6 | 134,001 |
Provide tags and a correct Python 3 solution for this coding contest problem.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:
* A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.
* A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.
* A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm:
1. Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list.
2. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
Input
The first line of the input contains a single integer n (0 ≤ n ≤ 40) — the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer m (1 ≤ m ≤ 40) — the number of lines in the input source code.
Next m lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
Output
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
Examples
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e | instruction | 0 | 67,283 | 6 | 134,566 |
Tags: greedy, implementation
Correct Solution:
```
from collections import defaultdict
n = int(input())
reserved = set(input().split())
m = int(input())
lines = [ input().split('#')[0].split() for _ in range(m) ]
tokens = sum(lines, [])
def isword(t):
return not t[0].isdigit() and all(c.isalnum() or c == '_' or c == '$' for c in t)
def ok(t):
return t in reserved or t.isdigit() or isword(t)
def tokenize(t):
res = []
i = 0
n = len(t)
while i < n:
for j in range(n, i, -1):
if ok(t[i:j]):
res.append(t[i:j])
i = j
break
return res
tokens = sum(map(tokenize, tokens), [])
dig = 1
k = 0
limit = 26
def next_token():
global dig, k, limit
if k == limit:
k = 0
dig += 1
limit = 26 ** dig
w = []
l = k
for _ in range(dig):
w += chr(ord('a') + l % 26)
l //= 26
w = ''.join(reversed(w))
k += 1
if w in reserved:
return next_token()
return w
dc = defaultdict(next_token)
def replace(t):
if t in reserved or t.isdigit():
return t
return dc[t]
def can_append(a, b, bg):
if len(a) == 0:
return True
#if a not in reserved and b not in reserved:
# return False
for i, s in enumerate(bg):
if i + 1 != len(bg) and len(a) - s > 21:
continue
for i in range(len(b)):
if ok(a[s:] + b[:i+1]):
#print(a, b, a[s:] + b[:i+1])
return False
#print('can append', a, b)
return True
res = ['']
begin = []
for t in map(replace, tokens):
if not can_append(res[-1], t, begin):
res.append('')
begin = []
begin.append(len(res[-1]))
res[-1] += t
print(' '.join(res))
``` | output | 1 | 67,283 | 6 | 134,567 |
Provide tags and a correct Python 3 solution for this coding contest problem.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:
* A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.
* A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.
* A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm:
1. Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list.
2. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
Input
The first line of the input contains a single integer n (0 ≤ n ≤ 40) — the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer m (1 ≤ m ≤ 40) — the number of lines in the input source code.
Next m lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
Output
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
Examples
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e | instruction | 0 | 67,284 | 6 | 134,568 |
Tags: greedy, implementation
Correct Solution:
```
def main():
t = int(input())
reserved = set(input().split())
lines = int(input())
code = ''
for i in range(lines):
code += input() + '\n'
def is_word(suspect):
if suspect[0].isdigit(): return False
for x in suspect:
if (not x.isalpha()) and (not x in {'_', '$'}) and (not x.isdigit()):
return False
return True
def is_token(suspect):
if suspect in reserved: return True
if is_word(suspect): return True
if suspect.isdigit(): return True
return False
def remove_comments(code):
rez = ''
state = None
for i in range(len(code)):
if code[i] == '#':
state = 'comment'
elif code[i] == '\n':
rez += code[i]
state = None
else:
if state != 'comment':
rez += code[i]
return rez
code = remove_comments(code)
code = code.replace('\n', ' ')
def split(code):
tokens = []
i = 0
while i < len(code):
if code[i] == ' ':
i += 1
continue
for l in range(min(len(code), 90), 0, -1):
if is_token(code[i:i + l]):
tokens.append(code[i:i + l])
i += l
break
else:
return []
return tokens
def minmize(tokens):
all = []
pref = [chr(i + ord('a')) for i in range(26)]
all.extend(pref)
for ext in range(3):
cur = []
for i in range(26):
for p in pref:
cur.append(p + chr(i + ord('a')))
cur.sort()
all.extend(cur)
pref = cur[::]
all.reverse()
zip = dict()
for i in range(len(tokens)):
if not tokens[i] in reserved and not tokens[i][0].isdigit():
if not zip.get(tokens[i], None):
while all[-1] in reserved:
all.pop()
zip[tokens[i]] = all[-1]
all.pop()
tokens[i] = zip[tokens[i]]
return tokens
tokens = (minmize(split(code)))
def cmp(a, b):
if len(a) != len(b): return False
for i in range(len(a)):
if a[i] != b[i]: return False
return True
final = []
for i in range(len(tokens)):
p = 0
for j in range(i - 1, -1, -1):
if len(''.join(tokens[j:i + 1])) > 23:
p = j
break
st = ''
if i and (not cmp(tokens[p:i + 1], split(''.join(final[p:i]) + tokens[i]))):
st += ' '
final.append(st + tokens[i])
print(''.join(final))
main()
``` | output | 1 | 67,284 | 6 | 134,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:
* A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.
* A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.
* A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm:
1. Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list.
2. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
Input
The first line of the input contains a single integer n (0 ≤ n ≤ 40) — the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer m (1 ≤ m ≤ 40) — the number of lines in the input source code.
Next m lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
Output
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
Examples
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e | instruction | 0 | 67,285 | 6 | 134,570 |
Tags: greedy, implementation
Correct Solution:
```
#!/usr/bin/python3
input()
reserved = input().split(' ')
lines = int(input())
numbers = '0123456789'
let = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890_$'
def wytnij_res(slowo):
r = ''
for res in reserved:
if len(res) > len(r) and slowo.startswith(res):
r = res
return r
def wytnij_num(slowo):
nm = ''
for c in slowo:
if c in numbers:
nm += c
else:
break
return nm
def wytnij_word(slowo):
nm = ''
if slowo[0] in numbers:
return ''
for c in slowo:
if c in let:
nm += c
else:
break
return nm
def wytnij(slowo):
rs = wytnij_res(slowo)
nm = wytnij_num(slowo)
wrd = wytnij_word(slowo)
ret = ''
for r in [rs, nm, wrd]:
if len(r) > len(ret):
ret = r
if ret == '':
print([rs, nm, wrd])
print(slowo)
assert False
return ret
prog = []
#print(reserved)
for _ in range(lines):
line = input()
line = line.split('#')[0]
line = line.split(' ')
for l in line:
while len(l) > 0:
wrd = wytnij(l)
l = l[len(wrd):]
prog.append(wrd)
letters = 'abcdefghijklmnopqrstuvwxyz'
def gen(st):
ln = len(letters)
res = []
for i in range(ln**st):
j = i
if st == 1:
res.append(letters[i])
else:
res.append(letters[i // ln] + letters[i % ln])
return res
toks = gen(1) + gen(2)
toks = [t for t in toks if t not in reserved]
dct = {}
tprog = []
for p in prog:
if p not in reserved and p[0] not in numbers:
if p not in dct:
dct[p] = toks[0]
toks = toks[1:]
p = dct[p]
tprog.append(p)
# print(prog)
# print(tprog)
res = ''
#na_pale = ''.join(tprog)
for tok in reversed(tprog):
nres = tok + res
if wytnij(nres) != tok:
# print('wycialem {} a tok {}'.format(wytnij(na_pale), tok))
res = tok + ' ' + res
else:
res = tok + res
print(res)
``` | output | 1 | 67,285 | 6 | 134,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:
* A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.
* A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.
* A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm:
1. Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list.
2. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
Input
The first line of the input contains a single integer n (0 ≤ n ≤ 40) — the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer m (1 ≤ m ≤ 40) — the number of lines in the input source code.
Next m lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
Output
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
Examples
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e | instruction | 0 | 67,286 | 6 | 134,572 |
Tags: greedy, implementation
Correct Solution:
```
#!/usr/bin/env python3
import sys
n, reserved, m, *lines = sys.stdin.readlines()
n = int(n)
reserved = set(reserved.split())
m = int(m)
#assert len(lines) == m
def strip_comment(line):
return line[:-1].split('#', maxsplit=1)[0]
lines = ' '.join(map(strip_comment, lines))
#print(repr(lines))
def is_digit(c):
return '0' <= c <= '9'
def is_word_char(c):
return c == '_' or c == '$' or '0' <= c <= '9' or 'A' <= c <= 'Z' or 'a' <= c <= 'z'
def digit_match(s, ind):
assert ind < len(s)
res = 0
while res + ind < len(s) and is_digit(s[res + ind]):
res += 1
return res
def word_match(s, ind):
assert ind < len(s)
if is_digit(s[ind]):
return 0
res = 0
while res + ind < len(s) and is_word_char(s[res + ind]):
res += 1
return res
def reserved_match(s, ind):
assert ind < len(s)
return max((len(r) for r in reserved if s.startswith(r, ind)), default=0)
def tokenize(s):
ind = 0
while ind < len(s):
if s[ind] == ' ':
ind += 1
continue
l = max(digit_match(s, ind), word_match(s, ind), reserved_match(s, ind))
if l == 0:
yield '\0' # yield a garbage character to mess up the stream
return
yield s[ind:ind+l]
ind += l
def simplify_tokens(tokens):
def lex_next(s):
for i in range(len(s)-1, -1, -1):
assert 'a' <= s[i] <= 'z'
if s[i] < 'z':
return s[:i] + chr(ord(s[i])+1) + 'a' * (len(s) - i - 1)
return 'a' * (len(s)+1)
converted = {}
cur_word = ''
for token in tokens:
if token in reserved:
yield token
elif '0' <= token[0] <= '9':
yield token
elif token in converted:
yield converted[token]
else:
cur_word = lex_next(cur_word)
while cur_word in reserved:
cur_word = lex_next(cur_word)
converted[token] = cur_word
yield cur_word
tokens = list(simplify_tokens(tokenize(lines)))
#print(tokens)
cur_tokens = []
result = []
for token in tokens:
#assert token
cur_tokens.append(token)
# only have to check the last 20 tokens
if list(tokenize(''.join(cur_tokens[-21:]))) != cur_tokens[-21:]:
result.append(''.join(cur_tokens[:-1]))
cur_tokens = [token]
#assert cur_tokens
if cur_tokens:
result.append(''.join(cur_tokens))
print(' '.join(result))
``` | output | 1 | 67,286 | 6 | 134,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:
* A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.
* A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.
* A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm:
1. Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list.
2. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
Input
The first line of the input contains a single integer n (0 ≤ n ≤ 40) — the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer m (1 ≤ m ≤ 40) — the number of lines in the input source code.
Next m lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
Output
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
Examples
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e
Submitted Solution:
```
print("Hello, world!")
``` | instruction | 0 | 67,287 | 6 | 134,574 |
No | output | 1 | 67,287 | 6 | 134,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:
* A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.
* A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.
* A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm:
1. Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list.
2. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
Input
The first line of the input contains a single integer n (0 ≤ n ≤ 40) — the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer m (1 ≤ m ≤ 40) — the number of lines in the input source code.
Next m lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
Output
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
Examples
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e
Submitted Solution:
```
#!/usr/bin/python3
input()
reserved = input().split(' ')
lines = int(input())
numbers = '0123456789'
let = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890_$'
def wytnij_res(slowo):
r = ''
for res in reserved:
if len(res) > len(r) and slowo.startswith(res):
r = res
return r
def wytnij_num(slowo):
nm = ''
for c in slowo:
if c in numbers:
nm += c
else:
break
return nm
def wytnij_word(slowo):
nm = ''
if slowo[0] in numbers:
return ''
for c in slowo:
if c in let:
nm += c
else:
break
return nm
def wytnij(slowo):
rs = wytnij_res(slowo)
nm = wytnij_num(slowo)
wrd = wytnij_word(slowo)
ret = ''
for r in [rs, nm, wrd]:
if len(r) > len(ret):
ret = r
if ret == '':
print([rs, nm, wrd])
print(slowo)
assert False
return ret
prog = []
#print(reserved)
for _ in range(lines):
line = input()
line = line.split('#')[0]
line = line.split(' ')
for l in line:
while len(l) > 0:
wrd = wytnij(l)
l = l[len(wrd):]
prog.append(wrd)
letters = 'abcdefghijklmnopqrstuvwxyz'
def gen(st):
ln = len(letters)
res = []
for i in range(ln**st):
j = i
if st == 1:
res.append(letters[i])
else:
res.append(letters[i // ln] + letters[i % ln])
return res
toks = gen(1) + gen(2)
toks = [t for t in toks if t not in reserved]
dct = {}
tprog = []
for p in prog:
if p not in reserved and p[0] not in numbers:
if p not in dct:
dct[p] = toks[0]
toks = toks[1:]
p = dct[p]
tprog.append(p)
# print(prog)
# print(tprog)
res = ''
na_pale = ''.join(tprog)
for tok in tprog:
res += tok
if wytnij(na_pale) != tok:
# print('wycialem {} a tok {}'.format(wytnij(na_pale), tok))
res += ' '
na_pale = na_pale[len(tok):]
print(res)
``` | instruction | 0 | 67,288 | 6 | 134,576 |
No | output | 1 | 67,288 | 6 | 134,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below:
* A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process.
* A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive.
* A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm:
1. Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list.
2. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
Input
The first line of the input contains a single integer n (0 ≤ n ≤ 40) — the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer m (1 ≤ m ≤ 40) — the number of lines in the input source code.
Next m lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
Output
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
Examples
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e
Submitted Solution:
```
def main():
t = int(input())
reserved = set(input().split())
lines = int(input())
code = ''
for i in range(lines):
code += input() + '\n'
def is_word(suspect):
if suspect[0].isdigit(): return False
for x in suspect:
if (not x.isalpha()) and (not x in {'_', '$'}) and (not x.isdigit()):
return False
return True
def is_token(suspect):
if suspect in reserved: return True
if is_word(suspect): return True
if suspect.isdigit(): return True
return False
def remove_comments(code):
rez = ''
state = None
for i in range(len(code)):
if code[i] == '#':
state = 'comment'
elif code[i] == '\n':
rez += code[i]
state = None
else:
if state != 'comment':
rez += code[i]
return rez
code = remove_comments(code)
code = code.replace('\n', ' ')
def split(code):
tokens = []
i = 0
while i < len(code):
if code[i] == ' ':
i += 1
continue
for l in range(min(len(code), 81), 0, -1):
if is_token(code[i:i + l]):
tokens.append(code[i:i + l])
i += l
break
else:
0 // 0
return tokens
def minmize(tokens):
all = []
pref = [chr(i + ord('a')) for i in range(26)]
all.extend(pref)
for ext in range(2):
cur = []
for i in range(26):
for p in pref:
cur.append(p + chr(i + ord('a')))
cur.sort()
all.extend(cur)
pref = cur[::]
all.reverse()
zip = dict()
for i in range(len(tokens)):
if not tokens[i] in reserved and not tokens[i][0].isdigit():
if not zip.get(tokens[i], None):
while all[-1] in reserved:
all.pop()
zip[tokens[i]] = all[-1]
all.pop()
tokens[i] = zip[tokens[i]]
return tokens
tokens = (minmize(split(code)))
def cmp(a, b):
if len(a) != len(b): return False
for i in range(len(a)):
if a[i] != b[i]: return False
return True
final = ''
for i in range(len(tokens)):
t = ''
if i:
t += tokens[i - 1]
if i and (not cmp(tokens[i - 1:i + 1], split(t + tokens[i]))):
final += ' '
final += tokens[i]
print(final)
main()
``` | instruction | 0 | 67,289 | 6 | 134,578 |
No | output | 1 | 67,289 | 6 | 134,579 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.