简体   繁体   English

处理基本递归 - 尝试递归查看字符串中的两个字符

[英]Working on basic recursion- trying to recursively look through a string for two characters

I'm super new to python, and trying to create a very simple function to be used in a larger map coloring program.我对 python 非常陌生,并试图创建一个非常简单的函数以用于更大的地图着色程序。

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.该函数的思想是将一组变量分配给不同区域(string1)并为其分配颜色(r,g,b),然后通过递归查看一组区域边界(string2)以查找匹配的变量+颜色。

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.输入格式如下: ("Ar, Bg, Cb", "AB,CB,CA") 将返回 True,这意味着没有两个相同颜色的区域触摸。

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.当我期望为 True 时,我一直在出错。 Can anyone help?任何人都可以帮忙吗? Thanks a lot.非常感谢。

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.认为您要做的是查看构造的字符串(例如“Ar”)是否在字符串 1 中,向前或向后。

"in" can join only one pair of strings; “in”只能连接一对字符串; there's no distributive property of "and" and "or" over "in".在“in”之上没有“and”和“or”的分配属性。

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.此外,坚持使用打印语句来跟踪您的执行并在此过程中打印出有用的值。

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:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM