问题1:
编写接受两个字符串参数的occurrences(text1、text2)的函数定义。该函数返回第一个参数中的字符在第二个参数中出现的次数。(使用for循环解决)
eg: occurrences("fooled","hello, world") == 7
问题2:
编写一个函数接受两个参数输入remove(text1,text2),将单词text1中和text2重复的字母删除,输出过滤后的text1。(使用for循环解决)
eg: remove("good","go") == d
新手求大神给指导指导,多谢啦
Q1.
def occurrences(text1,text2):
s = list(set(text1))
count = 0
for i in text2:
if i in s:
count +=1
return count
print(occurrences("fooled","hello, world"))
Q2
def remove(text1,text2):
s1 = list(set(text2))
ls = list()
for i in text1:
if i in s1:
continue
else:
ls.append(i)
return ls
print("".join(remove("good","go")))
问题1
def occurrences(tx1,tx2):
# 将tx1去除重复字母后组成list
a = list(set(tx1))
num = 0 # 字符统计
for i in a:
num += tx2.count(i)
return num
n = occurrences('fooled','hello,world')
print(n)
问题2
def remove(tx1,tx2):
a = list(tx1) #将字符串转换成list
b = list(tx2)
s = ''
for i in a:# 遍历a
if i not in b:# 如果a中的字符不在b中,就记录下来
s += ''.join(i)
return s
m = remove("good","go")