Python: Checking whether all characters of one string are found in another

One of the challenges from Udacity’s Introduction to Computer Science.

Apparently it’s possible to solve this problem in one line, so I’ll come back to this later once I’ve learned more.

EDIT: Although this code passes the test cases, it was pointed out to me that it is actually not correct! The reason it passes Test case 1 is because the value 0 is returned from the if loop and 0 as a boolean value evaluates to False.

def fix_machine(debris, product):
    # iterate through each character in product
    for x in product: 
        # check whether each character in product is found in debris
        if debris.find(x): 
            return product
        else: return "Give me something that's not useless next time."

### TEST CASES ###
print "Test case 1: ", fix_machine('UdaciousUdacitee', 'Udacity') == "Give me something that's not useless next time."
print "Test case 2: ", fix_machine('buy me dat Unicorn', 'Udacity') == 'Udacity'
print "Test case 3: ", fix_machine('AEIOU and sometimes y... c', 'Udacity') == 'Udacity'
print "Test case 4: ", fix_machine('wsx0-=mttrhix', 't-shirt') == 't-shirt'

This code, however, does work. One thing it doesn’t do, though, is account for multiple occurrences of characters, so I’ll come back to it later.

def fix_machine(debris, product):
    # iterate through each character in product
    for x in product:
        # check whether each character in product is found in debris
        if x not in debris:
            return "Give me something that's not useless next time."
    return product
 
### TEST CASES ###
print "Test case 1: ", fix_machine('UdaciousUdacitee', 'Udacity') == "Give me something that's not useless next time."
print "Test case 2: ", fix_machine('buy me dat Unicorn', 'Udacity') == 'Udacity'
print "Test case 3: ", fix_machine('AEIOU and sometimes y... c', 'Udacity') == 'Udacity'
print "Test case 4: ", fix_machine('wsx0-=mttrhix', 't-shirt') == 't-shirt'
print "Test case 5: ", fix_machine('hoi!', 'ik hou van jou') == "Give me something that's not useless next time."
Advertisements

One thought on “Python: Checking whether all characters of one string are found in another

  1. Pingback: riddle 1 (python) | ferretfarmer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s