#1440
Medium Database Evaluate boolean expression
Database
71.7% acceptance
Mar 31, 2026
231
41
No description available.
Solution
Pandas
Time O(1)
Space O(1)
# Table Variables:
#
# +---------------+---------+
# | Column Name | Type |
# +---------------+---------+
# | name | varchar |
# | value | int |
# +---------------+---------+
# In SQL, name is the primary key for this table.
# This table contains the stored variables and their values.
#
#
#
# Table Expressions:
#
# +---------------+---------+
# | Column Name | Type |
# +---------------+---------+
# | left_operand | varchar |
# | operator | enum |
# | right_operand | varchar |
# +---------------+---------+
# In SQL, (left_operand, operator, right_operand) is the primary key for this table.
# This table contains a boolean expression that should be evaluated.
# operator is an enum that takes one of the values ('<', '>', '=')
# The values of left_operand and right_operand are guaranteed to be in the Variables table.
#
#
#
# Evaluate the boolean expressions in Expressions table.
#
# Return the result table in any order.
#
# The result format is in the following example.
#
# Example 1:
# Input:
# Variables table:
# +------+-------+
# | name | value |
# +------+-------+
# | x | 66 |
# | y | 77 |
# +------+-------+
# Expressions table:
# +--------------+----------+---------------+
# | left_operand | operator | right_operand |
# +--------------+----------+---------------+
# | x | > | y |
# | x | < | y |
# | x | = | y |
# | y | > | x |
# | y | < | x |
# | x | = | x |
# +--------------+----------+---------------+
# Output:
# +--------------+----------+---------------+-------+
# | left_operand | operator | right_operand | value |
# +--------------+----------+---------------+-------+
# | x | > | y | false |
# | x | < | y | true |
# | x | = | y | false |
# | y | > | x | true |
# | y | < | x | false |
# | x | = | x | true |
# +--------------+----------+---------------+-------+
# Explanation:
# As shown, you need to find the value of each boolean expression in the table using the variables table.
import pandas as pd
def eval_expression(variables: pd.DataFrame, expressions: pd.DataFrame) -> pd.DataFrame:
var_map = dict(zip(variables['name'], variables['value']))
expressions['left_val'] = expressions['left_operand'].map(var_map)
expressions['right_val'] = expressions['right_operand'].map(var_map)
def evaluate(row):
if row['operator'] == '>':
return 'true' if row['left_val'] > row['right_val'] else 'false'
elif row['operator'] == '<':
return 'true' if row['left_val'] < row['right_val'] else 'false'
else:
return 'true' if row['left_val'] == row['right_val'] else 'false'
expressions['value'] = expressions.apply(evaluate, axis=1)
return expressions[['left_operand', 'operator', 'right_operand', 'value']]