Udacity的练习:超级英雄滋扰单行答案?

时间:2016-03-31 15:52:10

标签: python

我正在使用Python进行Udacity“计算机科学入门”课程编码,在第2课问题集(可选2)中遇到了以下问题:

tokenizer = new StringTokenizer(Text,"\\.");
Pattern KEYWORD = Pattern.compile("\\b"+Keyword+"\\b", Pattern.CASE_INSENSITIVE);
StringBuilder sb = new StringBuilder(sum);
while(tokenizer.hasMoreTokens())
{
    String x = tokenizer.nextToken();
    if (KEYWORD.matcher(x).find()) {
        sb.append(x.replaceAll("\\s+", " ")).append('.');
    }
}
sum = sb.toString();

我的代码:

# Write a Python procedure fix_machine to take 2 string inputs
# and returns the 2nd input string as the output if all of its
# characters can be found in the 1st input string and "Give me
# something that's not useless next time." if it's impossible.
# Letters that are present in the 1st input string may be used
# as many times as necessary to create the 2nd string (you
# don't need to keep track of repeat usage).

现在,我很好奇的是,他们说只能在一行中完成

def fix_machine(debris, product):
  i = 0
  while i <= len(product)-1:
    if debris.find(product[i]) == -1:
      return "Give me something that's not useless next time."
    elif i == len(product)-1:
      return product
    else:
      i = i + 1

这个问题的单行答案怎么样?

4 个答案:

答案 0 :(得分:3)

def fix_machine(a, b):
  return set(a) >= set(b) and b or "Give me something that's not useless next time."

特别感谢@ajcr

PS:正如@ user2357112所提到的,它将以空字符串失败。

def fix_machine(a, b):
  return b if set(a) >= set(b) else "Give me something that's not useless next time."

答案 1 :(得分:0)

def fix_machine(debris, product):
    return 'Give me something that\'s not useless  next time' if ''.join([i for i in product if i in debris]) != product else product

我尝试一线解决方案。

答案 2 :(得分:-1)

我的代码:

def fix_machine(debris, product):
### WRITE YOUR CODE HERE ###

    for s in product:
        if debris.find(s) == -1:
            return "Give me something that's not useless next time."
    return product

无论如何,它给了我一个正确的答案!&#34;

答案 3 :(得分:-1)

def count(碎片,i):

if i in debris:
    return 0
else:
    return 1

def fix_machine(碎片,产品):

sum = 0
for i in range(0,len(product)):   
    sum = count(debris, product[i]) + sum
if sum == 0:
    return product
else
    return "Give me something that's not useless next time."