【问题标题】:Python, recursion : give all possible tuple combinations who meet a boolean expressionPython,递归:给出满足布尔表达式的所有可能的元组组合
【发布时间】:2020-01-24 08:04:59
【问题描述】:

所以,在学校,我做了一个关于递归的练习,内容如下: 我得到了一个字符串和一个随机的 int 值“N”。该字符串是一个布尔表达式,例如 '3*x - 2* y 递归编写,而且我不能将函数用作“itertools”等,这在我们学校是不允许的。

**MY CODE:**
def solution(expression, N,x=None,y=None):
  if x is None: x = -N + 1
  if y is None: y = -N + 1
  res = []
  if x >= N and y >= N:
      return []

  if eval(expression) == True:
      res.append((x, y))

  return res + solution(expression, N, x+1, y+1)






【问题讨论】:

  • 请将代码和数据发布为文本,而不是图像。
  • 好的!生病改变它
  • 你应该使用“if x is None”而不是“if x == None”。这可能不是您的代码的问题,但知道它很有用。
  • 我改了,还以为不一样了..

标签: python recursion tuples


【解决方案1】:

我已经修改了你的代码,我认为它现在可以工作了:

更新:我已将此表达式 if x < N - 1 : 更正为 if x < N - 1 or y < N - 1:

def solution(expression, N, x=None, y=None):
  if x is None: x = -N + 1
  if y is None: y = -N + 1
  res = []

  if eval(expression) == True:
    res.append((x, y))

  # if x < N - 1 :
  if x < N - 1 or y < N - 1:
    if y < N - 1:
      y += 1
    else:
      x += 1
      y = - N + 1
    return res + solution(expression, N, x, y)
  else:
    return res

print(solution('3*x - 2* y <0', 4))

【讨论】:

    【解决方案2】:

    在获取列表的排列并最终检查表达式的基础上构建的方法略有不同。不是最漂亮的代码,但可以完成工作。

    results = []
    
    
    def check(expression, items):
        x = y = None
    
        if len(items) == 1:
            x = y = items[0]
            if eval(expression) and (x, y) not in results:
                results.append((x, y))
    
        if len(items) == 2:
            x = items[0]
            y = items[1]
            if eval(expression) and (x, y) not in results:
                results.append((x, y))
            x = items[1]
            y = items[0]
            if eval(expression) and (x, y) not in results:
                results.append((x, y))
    
        if len(items) > 2:
            for i in items:
                remaining_elements = [x for x in items if x != i]
                check(expression, remaining_elements)
    
    
    expression = "3*x - 2*y < 0"
    N = 4
    items = range(-N + 1, N)
    check(expression, items)
    print(results)
    

    【讨论】:

    • 但它带有“for”循环,并且在我的学校中不允许它们进行递归..
    猜你喜欢
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多