Q1 of this problem set is the following:
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).
For example:
print fix_machine('UdaciousUdacitee', 'Udacity') should output "Give me something that's not useless next time."
and:
print fix_machine('buy me dat Unicorn', 'Udacity') should output 'Udacity'
This is the solution I came up with by myself:
def fix_machine(debris, product):
i = -1
while True:
i = i +1
if debris.find(product[i]) == -1:
return "Give me something that's not useless next time."
break
word = product[0:i+1]
if word == product:
break
return word
I found this other sample solution online:
def fix_machine(debris, product):
x = 0
while x < len(product):
if debris.find(product[x]) == -1:
return "Give me something that's not useless next time."
x += 1
return product
My code executes correctly, but I was wondering if it makes sense the way I'm using the break function. Any recommendation about how to better understand while-loops and optimize them?