oquiroz oquiroz - 2 months ago 6
Python Question

Udacity's exercise: superhero nuisance one-line answer?

I'm going through the Udacity "Intro to Computer Science" course coding with Python, and in Lesson 2 Problem Set (Optional 2) I encountered the following problem:

# 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).


My code:

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


Now, what I'm curious about is that they say it can be done in just one line:

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


How would the one-line answer of this problem be like?

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

special thanks to @ajcr

PS: as @user2357112 mentioned, it will fail with empty strings.

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