def task10(str1,str2):
str1=str1.lower()
str2=str2.lower()
badchars = ['$','@','%',';',':','!',"*"," ",'1',"2","3","4","5","6","7","8","9","0",'^','&','#','~','?','[]','{',']'," ",'=','-','_','-',",",'"',"'",'`',"|","\\",'(',')']
for i in badchars:
str1=str1.replace(i,"")
str2=str2.replace(i,"")
common = list(set([c for c in str1 if c in str2]))
i=len(common)
if i==0:
common=['no common letters']
common.sort()
if i>1:
common.insert(-1,"and")
common= ','.join(common)
print(f'{common}')
task10('icl!','i cannot lie!')
CodePudding user response:
Do a string replace for ,and,
with and
to get the correct output.
def task10(str1,str2):
str1=str1.lower()
str2=str2.lower()
badchars = ['$','@','%',';',':','!',"*"," ",'1',"2","3","4","5","6","7","8","9","0",'^','&','#','~','?','[]','{',']'," ",'=','-','_','-',",",'"',"'",'`',"|","\\",'(',')']
for i in badchars:
str1=str1.replace(i,"")
str2=str2.replace(i,"")
common = list(set([c for c in str1 if c in str2]))
i=len(common)
if i==0:
common=['no common letters']
common.sort()
if i>1:
common.insert(-1,"and")
common= ','.join(common)
common = common.replace(',and,', ' and ')
print(f'{common}')
task10('icl!','i cannot lie!')
Output:
c,i and l
CodePudding user response:
You can do this efficiently with set manipulation. Note that badchars is a set and not a list as in the original question.
badchars = {'$', '@', '%', ';', ':', '!', "*", " ", '1', "2", "3", "4", "5", "6", "7", "8", "9", "0", '^',
'&', '#', '~', '?', '[', '{', ']', " ", '=', '-', '_', '-', ",", '"', "'", '`', "|", "\\", '(', ')', '£'}
def task10(str1, str2):
match len(rv := (set(str1) & set(str2)) - badchars):
case 0:
return ''
case 1:
return rv.pop()
case _:
rv = list(rv)
return ', '.join(rv[:-1]) ' and ' rv[-1]
print(task10('ic!', 'i cannot lie!'))
Output:
i, c and l