2016-03-31 2 views
1

Я иду через Udacity «Введение в информатику» курс кодирования с Python, и в уроке 2 Проблемы Set (Необязательно 2) Я столкнулся со следующей проблемой:Упражнение Udacity: супергероя неприятный однострочный ответ?

# 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 

Теперь, что мне интересно, что они говорят это может быть сделано только в одной строке:

# BONUS: # 
# 5***** # If you've graduated from CS101, 
# Gold # try solving this in one line. 
# Stars! # 

Как будет однострочный ответ этой проблемы?

ответ

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

Должен быть 'установлен (а)> = множество (б)', чтобы быть правдой к оригинальному вопросу, я думаю. –

+1

Вы должны использовать условное выражение ('true_option if condition else false_option') вместо этого и/или взломать здесь. Ошибка и/или взлом, если 'b' пуст. – user2357112

+0

Просто ради этого вы можете сохранить еще одну строку, повернув 'def' в функцию лямбда. –

0

мой код:

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 

в любом случае, это дает мне "правильно!"

+1

Запрос на однострочный ответ. –

0

Защиту рассчитывать (мусор, я):

if i in debris: 
    return 0 
else: 
    return 1 

четкости 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." 
Смежные вопросы