我有一个简单的python代码,继续在CodeChef在线评判中显示NZEC错误。代码适用于问题GRANAMA。
Chef已经学会了一种比较两种食谱的新技术。食谱包含 成分列表按处理时间的递增顺序排列。 一种成分用字母'a' - 'z'表示。食谱中的第i个字母表示 第i个成分。一种成分可以在配方中多次使用。
该技术如下。通过比较它们各自的列表来比较两个食谱。
如果两种配方中使用的成分组相同且每种成分为
在两者中使用相同的次数(处理顺序无关紧要),
他们被宣布为granama食谱。 (“granama”是“类似”的Chef-ian词。)
厨师拿了他昨天发明的两个食谱。他想用它来比较它们
技术。不幸的是,厨师忘了跟踪每个人的次数
配料已被用于配方中。他只比较了成分而不是他们的成分
频率。更确切地说,如果没有,厨师会将两个食谱视为格兰玛
在一个配方中使用但未在其他配方中使用的成分。
您的任务是报告Chef是否正确分类了这两个食谱(如
granama or not granama)虽然他忘了跟踪频率。
Input
The first line of the input contains a single integer T denoting the number of test
cases. The description for T test cases follows. Each test case consists of a single
line containing two space-separated strings R and S denoting the two recipes.
Output
For each test case, output a single line containing "YES" (quotes for clarity) if Chef
correctly classified the two recipes as granama or not granama. Otherwise, output a
single line containing "NO" (quotes for clarity) if Chef declared two recipes as
granama when they actually are not.
Constraints
1 ≤ T ≤ 100
1 ≤ |R|, |S| ≤ 1000
Example
Input:
3
alex axle
paradise diapers
alice bob
Output:
YES
NO
YES
Explanation:
Example case 1: Chef declared them as granama recipes. They are actually granama
because the sets of ingredients and the number of times each ingredient has been used
are equal. The Chef got it right!
Example case 2: Chef declared them as granama recipes because both sets of ingredients
are equal. But they are NOT granama since ingredient 'a' has been used twice in the
first recipe but only once in the second. The Chef was incorrect!
Example case 3: Chef declare them as not granama. They are not granama as the sets of
ingredients are different. Hence, the Chef was right!
以下是代码:
k=int(raw_input())
for n in range(k):
recipes=raw_input().split(' ')
w1=recipes[0]
w2=recipes[1]
for i in w1:
if i in w1:
w1=w1.replace(i,'')
w2=w2.replace(i,'')
if w1=='' and w2=='':
dict1={}
dict2={}
for i in recipes[0]:
if i in dict1:
dict1[i]+=1
else:
dict1[i]=1
for i in recipes[1]:
if i in dict2:
dict2[i]+=1
else:
dict2[i]=1
flag=True
for i in dict1:
if not dict1[i]==dict2[i]:
print 'NO'
flag=False
break
if flag:
print 'YES'
else:
print 'YES'
答案 0 :(得分:1)
我相信错误就在这里 -
for i in w1:
if i in w2: # You were checking again in 'w1'
w1=w1.replace(i,'')
w2=w2.replace(i,'')
这应解决NZEC问题。您可以通过here查看我提交的解决方案。运行时间是0.23秒。
这个代码紧凑有很大的空间。让我拿起你的一些代码片段并展示如何 -
w1=recipes[0]
w2=recipes[1]
for i in w1:
if i in w2:
w1=w1.replace(i,'')
w2=w2.replace(i,'')
if w1=='' and w2=='':
Python有一个set data structure,在这种情况下可以派上用场。
if set(recipes[0]) == set(recipes[1]): # Check for equality between two sets
为了查看两个食谱之间每个字符的频率是否匹配,您不需要字典。您可以简单地比较排序的字符串。
if sorted(recipes[0]) == sorted(recipes[1])
因此,30行代码可以替换为7行。
if set(recipes[0]) == set(recipes[1]):
if sorted(recipes[0]) == sorted(recipes[1]):
print 'YES'
else:
print 'NO'
else:
print 'YES'
我基于上面的那个在code上以略微不同的方式输入了输入。它运行时间为0.09秒。