python输入名字输出姓_Python函数返回名字和姓氏中的常见字母的列表

Question: DO NOT USE SETS IN YOUR FUNCTION: Uses lists to return a list of the common letters in the first and last names (the intersection) Prompt user for first and last name and call the function with the first and last names as arguments and print the returned list.

I can't figure out why my program is just printing "No matches" even if there are letter matches. Anything helps! Thanks a bunch!

Code so far:

import string

def getCommonLetters(text1, text2):

""" Take two strings and return a list of letters common to

both strings."""

text1List = text1.split()

text2List = text2.split()

for i in range(0, len(text1List)):

text1List[i] = getCleanText(text1List[i])

for i in range(0, len(text2List)):

text2List[i] = getCleanText(text2List[i])

outList = []

for letter in text1List:

if letter in text2List and letter not in outList:

outList.append(letter)

return outList

def getCleanText(text):

"""Return letter in lower case stripped of whitespace and

punctuation characters"""

text = text.lower()

badCharacters = string.whitespace + string.punctuation

for character in badCharacters:

text = text.replace(character, "")

return text

userText1 = raw_input("Enter your first name: ")

userText2 = raw_input("Enter your last name: ")

result = getCommonLetters(userText1, userText2)

numMatches = len(result)

if numMatches == 0:

print "No matches."

else:

print "Number of matches:", numMatches

for letter in result:

print letter

解决方案

Try this:

def CommonLetters(s1, s2):

l1=list(''.join(s1.split()))

l2=list(''.join(s2.split()))

return [x for x in l1 if x in l2]

print CommonLetters('Tom','Dom de Tommaso')

Output:

>>> ['T', 'o', 'm']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值