Python,递归:给出满足布尔表达式的所有可能的元组组合

问题描述 投票:0回答:2

因此,在学校里,我进行了递归练习,其内容如下:我得到了一个字符串和一个随机的int值'N'。该字符串是布尔表达式,例如'3 * x-2 * y <0'。结果必须是满足表达式的所有可能的元组组合的元组(x,y),(-N 递归地编写,并且我不能将函数用作“ 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)






python recursion tuples
2个回答
0
投票

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

更新:我已将此表达式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))

0
投票

基于获取列表的排列并最终检查表达式的方式略有不同。不是最漂亮的代码,但能完成任务。

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)
© www.soinside.com 2019 - 2024. All rights reserved.