2

I'm super new to python, and trying to create a very simple function to be used in a larger map coloring program.

The idea of the function is to have a set of variables attributed to different regions (string1) with colors assigned to them, (r,g,b) and then test if the regions touch another region of the same color by recursively looking through a set of region borders (string2) to find variables+colors that match.

The input format would look like this: ("Ar, Bg, Cb", "AB,CB,CA") Would return True, meaning no two regions of the same color touch.

Here's my code segment so far:

def finding_double_char_function(string1, string2): 
    if string2=="":
        return True
    elif string2[0]+"r" and string2[1]+"r" in string1 or string1[::-1]:
        return False
    elif string2[0]+"g" and string2[1]+"g" in string1 or string1[::-1]:
        return False
    elif string2[0]+"b" and string2[1]+"b" in string1 or string1[::-1]:
        return False
    else:
        return finding_double_char_function(string1, (string2[3:]))

I keep getting false when I expected True. Can anyone help? Thanks a lot.

1
  • Assuming that string1 and string2 are not empty then your first elif condition will always be True, or string1[::-1] reversing a string will always return a string and anything but the empty string evaluates to True. Not exactly sure why you are reversing string1 and it is very hard to follow your logic to help any further. Is there a reason this must be recursive?
    – AChampion
    Oct 1, 2015 at 1:14

2 Answers 2

1

You have several problems in this, but your main problem is that you don't seem to know the order of bindings in an expression. What you've written is a little more readable like this:

elif string2[0]+"r" and 
    ((string2[1]+"r" in string1) or
      string1[::-1])                 :

In other words, you've used strings as boolean values. The value you get from this is not what you expected. I think what you're trying to do is to see whether either constructed string (such as "Ar") is in string 1, either forward or backward.

"in" can join only one pair of strings; there's no distributive property of "and" and "or" over "in".

Here's the first part rewritten properly:

elif (string2[0]+"r" in string1) and 
     (string2[1]+"r" in string1)

Does this get you going?

Also, stick in print statements to trace your execution and print out useful values along the way.

0

If I undestood correctly your problem could be solved like this:

def intersect(str1, str2):
    if (not str2):
        return True

    if (str1[str1.find(str2[0]) + 1] == str1[str1.find(str2[1]) + 1]):
        return False
    else:
        return intersect(str1, str2[3:])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.