简体   繁体   中英

Boolean logic with Python

I've the following JSON:

{
  "condition": "AND",
  "rules": [
    {
      "condition": "OR",
      "rules": [
        {
          "id": "u.url",
          "operator": "contains",
          "value": "URL_A"
        },
        {
          "id": "u.url",
          "operator": "contains",
          "value": "URL_B"
        }
      ]
    },
    {
      "condition": "OR",
      "rules": [
        {
          "id": "u.url",
          "operator": "contains",
          "value": "URL_C"
        },
        {
          "id": "u.url",
          "operator": "contains",
          "value": "URL_D"
        }
      ]
    }
  ]

representing the boolean formula: (A or B) and (C or D) where A , for example, is this JSON object:

{
   "id": "u.url",
   "operator": "contains",
   "value": "URL_A"
}

In general, the JSON file could represent any boolean logic with (only) AND and OR operators.

The problems is to return a string representing the Sum Of Product of the original formula. That is: (A or C) and (A or D) and (B or C) and (B or D) . For example the result would be:

(u.url contains URL_A) OR (u.url contains URL_C) AND
(u.url contains URL_A) OR (u.url contains URL_D) AND
(u.url contains URL_B) OR (u.url contains URL_C) AND
(u.url contains URL_B) OR (u.url contains URL_D)

Python has a json library that will convert your Json data into a list of dictionaries. You could implement a recursive function that would be able to output the SOP.

So for example:

>>> import json
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'

If you recurse to the base using a DFS you can find the base expressions and work your way back up.

So go through the list of dictionaries until you hit a base state (ie the dict doesn't have a condition field.

Then back up and take the two rules and apply the operation to it. This could be done via a function that takes two dictionaries and returns the string for those.

Since you're doing DFS you would then go into the next branch and find that you return 'C or D'.

Then you'd be left with the root which would be those two branches ANDed together.

This all said, if you aren't familiar with recursion and DFS and how to implement that in Python the question basically just becomes, "Hey, someone implement a full fledged python implementation for me"

To help you further, post code that can be reviewed. I doubt anyone is going to post fully implemented code for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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