Skip to content

Instantly share code, notes, and snippets.

@J00MZ
Last active April 28, 2022 00:22
Show Gist options
  • Save J00MZ/93c50e6db8d4f5b0bf51da1eb41dd1ae to your computer and use it in GitHub Desktop.
Save J00MZ/93c50e6db8d4f5b0bf51da1eb41dd1ae to your computer and use it in GitHub Desktop.
SRE Python question

Problem


You have an string including words and characters that describes a boolean expression.
The words in the string may include one of the following four options

1. "true"
2. "false"
3. "&"
4. "|"

Example strings:

"true"  
"false & true & false"  
"true | true & false"  
"false & true"  

Task

Write a function that recieves this type of string and returns the evaluation of the string's boolean expression

@J00MZ
Copy link
Author

J00MZ commented Apr 28, 2022

Solution:

import sys
my_str = sys.argv[1]

def evaluate_expression(expression: str) -> bool:
    """
    Evaluate an expression and return the boolean result.
    """
    def get_word_value(word: str) -> str:
        if word == "true":
            return 'True'
        elif word == "false":
            return 'False'
        elif word == "|":
            return 'or'
        elif word == "&":
            return 'and'
    
    split_exp = expression.split(" ")
    eval_exp = ""
    for word in split_exp:
        eval_exp += get_word_value(word) + " "
    return eval(eval_exp)

print(f"expression is: {evaluate_expression(my_str)}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment