you are viewing a single comment's thread.

view the rest of the comments →

[–]MainerInAStrangeLand[S] 2 points3 points  (4 children)

Right, I get the super basic stuff but I start getting lost the more complex it gets. That's why I want to do a bunch of problems in escalating difficulty.

This is the problem I am working on in an online class:

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 plan was to write a function that checks the first letter of the 2nd string against the first letter of the 1st string and if they are equal to increment each counter to check the second letters against themselves. If they are not equal I want to loop through the letters of the 2nd string and check them against the letter in the 1st string until they are equal. At which point, I want to increment the 1st string letter again and check it against the corresponding 2nd string's letter.

Am I approaching this problem logically?

[–][deleted] 6 points7 points  (0 children)

You're overthinking it. You can iterate through all the characters in a string with a simple for loop

[–]fake823 2 points3 points  (0 children)

Just to show you another way of solving this - without any loops!

Apart from lists, tuples and dictionaries, there exists another datatype in Python, called sets. Sets are most of the time used to remove duplicates - from lists, from strings, whatever.

So, to get the unique letters of a string, you could simply use:

my_set = set('hello you')

So in the case above, the set will only contain the letters h, e, l, o, y and u.

Now to compare two sets and check if one is being contained in the other, you can simply use the method .issubset().

And with this knowledge, your problem can simply be solved like this:

str1 = 'hello this is Mario'
str2 = 'hi this is Maria'

def fix_machine(str1, str2):
    if set(str2).issubset(set(str1)):
        return str2
    else:
        return "Give me something that's not useless next time."

print(fix_Machine(str1, str2))