Question

class Bool(Expr): """A boolean constant literal. === Attributes === b: the value of the constant """...

class Bool(Expr):
"""A boolean constant literal.

=== Attributes ===
b: the value of the constant
"""
b: bool

def __init__(self, b: bool) -> None:
"""Initialize a new boolean constant."""
self.b = b

# TODO: implement this method!
def evaluate(self) -> Any:
"""Return the *value* of this expression.

The returned value should the result of how this expression would be
evaluated by the Python interpreter.

>>> expr = Bool(True)
>>> expr.evaluate()
True
"""
return self.b

def __str__(self) -> str:
"""Return a string representation of this expression.

One feature we'll stick with for all Expr subclasses here is that we'll
want to return a string that is valid Python code representing the same
expression.

>>> str(Bool(True))
'True'
"""
return str(self.b)


class BoolOp(Expr):
"""A boolean operation.

Represents either a sequences of `and`s or a sequence of `or`s.
Unlike BinOp, this expression can contains more than two operands,
each separated by SAME operator:

True and False and True and False
True or False or True or False

=== Attributes ===
op: the name of the boolean operation
values: a list of operands that the operation is applied to

=== Representation invariants ===
- self.op == 'and' or self.op == 'or'
- len(self.values) >= 2
- the expressions in self.values all evaluate to boolean values.
"""
op: str
values: List[Expr]

def __init__(self, op: str, values: List[Expr]) -> None:
"""Initialize a new boolean operation expression.

Precondition: op == 'and' or op == 'or' and the expressions in
self.values all evaluate to boolean values.
"""
self.op = op
self.values = values

# TODO: implement this method!
def evaluate(self) -> Any:
"""Return the *value* of this expression.

The returned value should the result of how this expression would be
evaluated by the Python interpreter.

>>> expr = BoolOp('and', [Bool(True), Bool(True), Bool(False)])
>>> expr.evaluate()
False
"""

help me with evaluate plz

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Summary :

   python code and output are shown as exhibit and also code is pasted text form.

Note : evaluate is implmented in recursive function which closures when there are 2 parameters .

########################## python Code #######################

from typing import Any
from typing import List
from _ast import Expr

class Bool(Expr) :
    def __init__(self, b: bool) -> None:
        self.b = b

    def evaluate(self) -> Any:
        return self.b

    def __str__(self) -> str:
        return str(self.b)

class BoolOp(Expr):

    def __init__(self, op: str, values: List[Expr]) -> None:
        self.op = op
        self.values = values
        #print (" op :" , op )
        #print (" List ", values)
      
      
    def evaluate(self) -> Any:
        str1 =""
        if (len(self.values) == 2) :
            str1 = self.values[0].__str__() + " " + str(self.op) + " " + self.values[1].__str__()
            #print(" Eval0 : ",str1)
            return eval(str1)
        else :
            tmp = BoolOp(self.op,self.values[1:])
            str1 = self.values[0].__str__() + " " + str(self.op) + " " + str(tmp.evaluate())
            #print(" Eval1 : ",str1)
            return eval(str1)
  
if __name__ == '__main__':
    expt = Bool(True)
    expf = Bool(False)
    print(" T ", expt , " Evl ", expt.evaluate() , " STR ", expt.__str__())
    print(" T ", expf , " Evl ", expf.evaluate() , " STR ", expf.__str__())
  
    expr = BoolOp('or', [Bool(True), Bool(True), Bool(False), Bool(False), Bool(True)])
    expr1 = expr.evaluate()
    print("BoolOp OR :", expr1)
  
    expr = BoolOp('and', [Bool(True), Bool(True), Bool(False)])
    expr1 = expr.evaluate()
    print("BoolOp And :", expr1)

#####################End Code #######################

####################### Exhibit ###########################

Add a comment
Know the answer?
Add Answer to:
class Bool(Expr): """A boolean constant literal. === Attributes === b: the value of the constant """...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • class WorkoutClass: """A workout class that can be offered at a gym. === Private Attributes ===...

    class WorkoutClass: """A workout class that can be offered at a gym. === Private Attributes === _name: The name of this WorkoutClass. _required_certificates: The certificates that an instructor must hold to teach this WorkoutClass. """ _name: str _required_certificates: List[str] def __init__(self, name: str, required_certificates: List[str]) -> None: """Initialize a new WorkoutClass called <name> and with the <required_certificates>. >>> workout_class = WorkoutClass('Kickboxing', ['Strength Training']) >>> workout_class.get_name() 'Kickboxing' """ def get_name(self) -> str: """Return the name of this WorkoutClass. >>> workout_class =...

  • COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild):...

    COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild): self.value, self.lchild, self.rchild = value, lchild, rchild def __init__(self): self.treeRoot = None    #utility functions for constructTree def mask(self, s): nestLevel = 0 masked = list(s) for i in range(len(s)): if s[i]==")": nestLevel -=1 elif s[i]=="(": nestLevel += 1 if nestLevel>0 and not (s[i]=="(" and nestLevel==1): masked[i]=" " return "".join(masked) def isNumber(self, expr): mys=s.strip() if len(mys)==0 or not isinstance(mys, str): print("type mismatch error: isNumber")...

  • """ Add_to_front(self, val) and add_to_back(self, val) functions can be used which are already done in python...

    """ Add_to_front(self, val) and add_to_back(self, val) functions can be used which are already done in python class. Name of list is LList class node(object): def __init__(self, data, next=None): self.data = data self.next = next # Note: use the attributes directly; no setters or getters! class LList(object): def __init__(self): self._size = 0 self._head = None self._tail = None """ def set_data_at_index(self, idx, val): """ The value stored at index idx changes to val return True if the index was valid otherwise...

  • Finish each function python 3 LList.py class node(object): """ A version of the Node class with...

    Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class.    Since there are no setters and getters, we use the attributes directly.    This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...

  • from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked...

    from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked list. Note that this is considered a "private class", one which is only meant to be used in this module by the LinkedList class, but not by client code. === Attributes === item: The data stored in this node. next: The next node in the list, or None if there are no more nodes. """ item: Any next: Optional[_Node] def __init__(self, item: Any) ->...

  • Using the following code: store.py from abc import ABC,abstractmethod class Store(ABC): #creating a abstract class name=''...

    Using the following code: store.py from abc import ABC,abstractmethod class Store(ABC): #creating a abstract class name='' #declaring attributes in class address='' status='' sales_tax_percentage=0.0 def __init__(self,name,address,status,sales_tax_percentage): #init method to initialize the class attributes self.name=name self.address=address self.status=status self.sales_tax_percentage=sales_tax_percentage def get_name(self): #Getter and setter methods for variables return self.name def set_name(self,name): self.name=name def get_address(self): return self.address def set_address(self,address): self.address=address def set_status(self,status): self.status=status def get_status(self): return self.status def set_sales_tax_percentage(self,sales_tax_percentage): self.sales_tax_percentage=sales_tax_percentage def get_sales_tax_percentage(self): return self.sales_tax_percentage def is_store_open(self): #check store status or availability if self.status=="open": #Return...

  • Python Activity 05 Boolean Expressions - POGIL (5) - Word Search m Layout References Mailings Review...

    Python Activity 05 Boolean Expressions - POGIL (5) - Word Search m Layout References Mailings Review View Help Critical Thinking Questions Programming Structures Sequence Structure Decision or Branching Structure Looping Structure FALSE Which structure best describes the types of Python programs you have written so far? _sequence structure Which structure allows the programmer to create code that decides what code is executed? FYI: Conditional operators, also known as relational operators, are used to compare the relationship between two operands. Expressions...

  • QUESTION 2 Boolean or "truth-valued" expressions are how we express conditions that control choices and repetition...

    QUESTION 2 Boolean or "truth-valued" expressions are how we express conditions that control choices and repetition in computer languages. Consider the following Python Boolean expression, where variables alpha, beta, and gamma are of type Boolean: alpha and (beta or gamma) In any algebraic notation there are usually several different ways of writing the same expression. For instance, in integer arithmetic the value of expression '4 x (5 + 2)' is numerically equivalent to that of expression '(4 x 5) +...

  • Use your Food class, utilities code, and sample data from Lab 1 to complete the following...

    Use your Food class, utilities code, and sample data from Lab 1 to complete the following Tasks. def average_calories(foods):     """     -------------------------------------------------------     Determines the average calories in a list of foods.     foods is unchanged.     Use: avg = average_calories(foods)     -------------------------------------------------------     Parameters:         foods - a list of Food objects (list of Food)     Returns:         avg - average calories in all Food objects of foods (int)     -------------------------------------------------------     """ your code here is the...

  • In Python class int Set (object): "" "An intSet is a set of integers The value...

    In Python class int Set (object): "" "An intSet is a set of integers The value is represented by a list of ints, self.vals. Each int in the set occurs in self.vals exactly once. """ definit__(self): """Create an empty set of integers""" self.vals = 0 def insert (self, e): """Assumes e is an integer and inserts e into self""" if not e in self.vals: self.vals.append(e) def member (self, e): """Assumes e is an integer Returns True if e is in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT