【问题标题】:In Python (2.7.3) how do I write a function that answers if any characters in str(x) are in str(y) (or str(y) are in str(x))?在 Python (2.7.3) 中,我如何编写一个函数来回答 str(x) 中的任何字符是否在 str(y) 中(或 str(y) 在 str(x) 中)?
【发布时间】:2013-12-05 06:58:31
【问题描述】:
def char_check(x,y):

    if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):

        return True

    else:

        return False

print "You will enter two words that you think use some of the same letters."

x = raw_input('Enter one of the words: ')

y = raw_input('Enter the other word: ')

print char_check(x,y)

我要做的是输入两个字符串,例如 str(x) 的 "terrible" 和 str(y) 的 "bile" 并返回 "True" 因为字符 'b'、'i'、' l' 和 'e' 由两个字符串共享。

我是新手,正在努力学习,但我似乎无法自己解决这个问题。谢谢大家。

【问题讨论】:

  • 您想要任何字符还是所有字符?例如terribleboo 的输出应该是什么?
  • 感谢您的回复。对于 'terrible' 和 'boo' 函数应该返回 True 因为 'b'
  • 这是一些教程中的练习吗?即使没有集合,您也应该能够使用 for 循环和 in 编写快速解决方案。
  • @RemcoGerlich :是的,这是来自练习。我正在审核的课程还没有介绍套路。我如何只使用 for 循环和“in”来做到这一点?
  • 循环遍历其中一个字符串中的所有字符。如果字符在另一个字符串中,欢呼,返回 True。如果我们完成但尚未返回,则返回 False。

标签: python string python-2.7 user-defined-functions


【解决方案1】:

套装几乎可以肯定是要走的路。

>>> set1 = set("terrible")
>>> set2 = set("bile")
>>> set1.issubset(set2)
False
>>> set2.issubset(set1)  # "bile" is a subset of "terrible"
True
>>> bool(set1 & set2)  # at least 1 character in set1 is also in set2
True

【讨论】:

  • 非常感谢!我看了几个小时的 Python 文档,试图看看我可以改变什么语法,但“集合”完成了我想要的!
【解决方案2】:

试试这个 -

def char_check(x,y):
    if set(x) & set(y):
        return True
    else:
        return False

【讨论】:

  • 当两个分支只返回 TrueFalse 时,值得避免使用 if 语句 - 只是 return not (setx - sety) or not (sety - setx)。此外,这两个条件都可以使用子集表示法更清楚地拼写:return setx <= sety or sety <= setx
  • 感谢您的建议。我运行了这个块,但如果我为 x 输入 'shout',为 y 输入'true',它会打印 True。但他们共享字符“t”。
  • 抱歉,我的要求有误。我认为它们必须是彼此的完整子集。现已更正!
  • @Aro 谢谢!几个答案的代码使用集合,这实现了我的目标。但是,我的教科书还没有介绍套装。 (它也没有引入&符号(&),但您的答案和上面使用集合的答案实现了我的目标。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 2022-08-18
相关资源
最近更新 更多