我在这里有这个代码,它应该从列表n1和n2中删除常用字母.但是当我运行这个代码时它只运行一次,因为它只从n1和n2中删除'a'并且不会删除'k'.
只是为了澄清这段代码应该总是只用2个单词.
name1 = "abdjek"
name2 = "doarhsnk"
n1l = list(name1)
n2l = list(name2)
for i in range(len(n1l)):
for j in range(len(n2l)):
if n1l[i] == n2l[j]:
n1l.pop(i)
n2l.pop(j)
n1l.append('0')
n2l.append('1')
Run Code Online (Sandbox Code Playgroud)
好的等等,它似乎适用于上述两个名字,但当我有name1 ="naveen"和name2 ="darshana"它不起作用!
我建议采用一种更简单的方法:
def removecommon(name1, name2):
common = set(name1).intersection(name2)
res1 = ''.join(n for n in name1 if n not in common)
res2 = ''.join(n for n in name2 if n not in common)
return res1, res2
n1, n2 = removecommon('naveen', 'darshana')
print n1, n2
Run Code Online (Sandbox Code Playgroud)
vee drsh根据需要发出.
编辑:正如现在指定的OP(在评论中 - 请记住编辑你的问题,哦OP!),他实际上只想删除每个常用字母的每个单词中的第一个出现,所需的算法当然是完全的不同.一种简单的方法(如果单词的长度不是太高,则可行):
def removefirstcommon(name1, name2):
common = set(name1).intersection(name2)
n1 = list(name1)
for c in common: n1.remove(c)
n2 = list(name2)
for c in common: n2.remove(c)
return ''.join(n1), ''.join(n2)
Run Code Online (Sandbox Code Playgroud)
更精细的方法(对于正常长度的单词来说速度较慢)对于极长的单词会更快(因为以下是O(N)而前者的O(N平方)):
def removefirstcommonlongwords(name1, name2):
common = set(name1).intersection(name2)
def mustrem(c, copycom):
res = c not in copycom
copycom.discard(c)
return res
cop = set(common)
n1 = [c for c in name1 if mustrem(c, cop)]
n2 = [c for c in name2 if mustrem(c, common)]
return ''.join(n1), ''.join(n2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
370 次 |
| 最近记录: |