_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q242500
_clauses
train
def _clauses(lexer, varname, nvars): """Return a tuple of DIMACS CNF clauses.""" tok = next(lexer) toktype = type(tok) if toktype is OP_not or toktype is IntegerToken: lexer.unpop_token(tok) first = _clause(lexer, varname, nvars) rest = _clauses(lexer, varname, nvars) ret...
python
{ "resource": "" }
q242501
_lits
train
def _lits(lexer, varname, nvars): """Return a tuple of DIMACS CNF clause literals.""" tok = _expect_token(lexer, {OP_not, IntegerToken}) if isinstance(tok, IntegerToken) and tok.value == 0: return tuple() else: if isinstance(tok, OP_not): neg = True tok = _expect_...
python
{ "resource": "" }
q242502
parse_sat
train
def parse_sat(s, varname='x'): """ Parse an input string in DIMACS SAT format, and return an expression. """ lexer = iter(SATLexer(s)) try: ast = _sat(lexer, varname) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, ...
python
{ "resource": "" }
q242503
_sat
train
def _sat(lexer, varname): """Return a DIMACS SAT.""" _expect_token(lexer, {KW_p}) fmt = _expect_token(lexer, {KW_sat, KW_satx, KW_sate, KW_satex}).value nvars = _expect_token(lexer, {IntegerToken}).value return _sat_formula(lexer, varname, fmt, nvars)
python
{ "resource": "" }
q242504
_sat_formula
train
def _sat_formula(lexer, varname, fmt, nvars): """Return a DIMACS SAT formula.""" types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt] tok = _expect_token(lexer, types) # INT if isinstance(tok, IntegerToken): index = tok.value if not 0 < index <= nvars: fstr = "formula literal ...
python
{ "resource": "" }
q242505
_formulas
train
def _formulas(lexer, varname, fmt, nvars): """Return a tuple of DIMACS SAT formulas.""" types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt] tok = lexer.peek_token() if any(isinstance(tok, t) for t in types): first = _sat_formula(lexer, varname, fmt, nvars) rest = _formulas(lexer, varname, fm...
python
{ "resource": "" }
q242506
CNFLexer.keyword
train
def keyword(self, text): """Push a keyword onto the token queue.""" cls = self.KEYWORDS[text] self.push_token(cls(text, self.lineno, self.offset))
python
{ "resource": "" }
q242507
CNFLexer.operator
train
def operator(self, text): """Push an operator onto the token queue.""" cls = self.OPERATORS[text] self.push_token(cls(text, self.lineno, self.offset))
python
{ "resource": "" }
q242508
SATLexer.punct
train
def punct(self, text): """Push punctuation onto the token queue.""" cls = self.PUNCTUATION[text] self.push_token(cls(text, self.lineno, self.offset))
python
{ "resource": "" }
q242509
parse
train
def parse(s): """ Parse an input string in PLA format, and return an intermediate representation dict. Parameters ---------- s : str String containing a PLA. Returns ------- A dict with all PLA information: =============== ============ ===========================...
python
{ "resource": "" }
q242510
action
train
def action(toktype): """Return a parser action property.""" def outer(func): """Return a function that pushes a token onto the token queue.""" def inner(lexer, text): """Push a token onto the token queue.""" value = func(lexer, text) lexer.tokens.append(toktyp...
python
{ "resource": "" }
q242511
RegexLexer._compile_rules
train
def _compile_rules(self): """Compile the rules into the internal lexer state.""" for state, table in self.RULES.items(): patterns = list() actions = list() nextstates = list() for i, row in enumerate(table): if len(row) == 2: ...
python
{ "resource": "" }
q242512
RegexLexer._iter_tokens
train
def _iter_tokens(self): """Iterate through all tokens in the input string.""" reobj, actions, nextstates = self._rules[self.states[-1]] mobj = reobj.match(self.string, self.pos) while mobj is not None: text = mobj.group(0) idx = mobj.lastindex - 1 next...
python
{ "resource": "" }
q242513
parity
train
def parity(num: int) -> int: """Return the parity of a non-negative integer. For example, here are the parities of the first ten integers: >>> [parity(n) for n in range(10)] [0, 1, 1, 0, 1, 0, 0, 1, 1, 0] This function is undefined for negative integers: >>> parity(-1) Traceback (most re...
python
{ "resource": "" }
q242514
cached_property
train
def cached_property(func): """Return a cached property calculated by the input function. Unlike the ``property`` decorator builtin, this decorator will cache the return value in order to avoid repeated calculations. This is particularly useful when the property involves some non-trivial computation...
python
{ "resource": "" }
q242515
var
train
def var(name, index=None): """Return a unique Variable instance. .. note:: Do **NOT** call this function directly. Instead, use one of the concrete implementations: * :func:`pyeda.boolalg.bdd.bddvar` * :func:`pyeda.boolalg.expr.exprvar`, * :func:`pyeda.boolalg.table.ttvar`. ...
python
{ "resource": "" }
q242516
Function.iter_cofactors
train
def iter_cofactors(self, vs=None): r"""Iterate through the cofactors of a function over N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`f_{...
python
{ "resource": "" }
q242517
Function.smoothing
train
def smoothing(self, vs=None): r"""Return the smoothing of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *smoothing* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`S_...
python
{ "resource": "" }
q242518
Function.consensus
train
def consensus(self, vs=None): r"""Return the consensus of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *consensus* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:`C_...
python
{ "resource": "" }
q242519
Function.derivative
train
def derivative(self, vs=None): r"""Return the derivative of a function over a sequence of N variables. The *vs* argument is a sequence of :math:`N` Boolean variables. The *derivative* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with respect to variable :math:`x_i` is: :math:...
python
{ "resource": "" }
q242520
Function._expect_vars
train
def _expect_vars(vs=None): """Verify the input type and return a list of Variables.""" if vs is None: return list() elif isinstance(vs, Variable): return [vs] else: checked = list() # Will raise TypeError if vs is not iterable f...
python
{ "resource": "" }
q242521
SudokuSolver.solve
train
def solve(self, grid): """Return a solution point for a Sudoku grid.""" soln = self.S.satisfy_one(assumptions=self._parse_grid(grid)) return self.S.soln2point(soln, self.litmap)
python
{ "resource": "" }
q242522
SudokuSolver._parse_grid
train
def _parse_grid(self, grid): """Return the input constraints for a Sudoku grid.""" chars = [c for c in grid if c in DIGITS or c in "0."] if len(chars) != 9**2: raise ValueError("expected 9x9 grid") return [self.litmap[self.X[i // 9 + 1, i % 9 + 1, int(c)]] for...
python
{ "resource": "" }
q242523
SudokuSolver._soln2str
train
def _soln2str(self, soln, fancy=False): """Convert a Sudoku solution point to a string.""" chars = list() for r in range(1, 10): for c in range(1, 10): if fancy and c in (4, 7): chars.append("|") chars.append(self._get_val(soln, r, ...
python
{ "resource": "" }
q242524
SudokuSolver._get_val
train
def _get_val(self, soln, r, c): """Return the string value for a solution coordinate.""" for v in range(1, 10): if soln[self.X[r, c, v]]: return DIGITS[v-1] return "X"
python
{ "resource": "" }
q242525
ttvar
train
def ttvar(name, index=None): """Return a TruthTable variable. Parameters ---------- name : str The variable's identifier string. index : int or tuple[int], optional One or more integer suffixes for variables that are part of a multi-dimensional bit-vector, eg x[1], x[1][2][3...
python
{ "resource": "" }
q242526
expr2truthtable
train
def expr2truthtable(expr): """Convert an expression into a truth table.""" inputs = [ttvar(v.names, v.indices) for v in expr.inputs] return truthtable(inputs, expr.iter_image())
python
{ "resource": "" }
q242527
truthtable2expr
train
def truthtable2expr(tt, conj=False): """Convert a truth table into an expression.""" if conj: outer, inner = (And, Or) nums = tt.pcdata.iter_zeros() else: outer, inner = (Or, And) nums = tt.pcdata.iter_ones() inputs = [exprvar(v.names, v.indices) for v in tt.inputs] t...
python
{ "resource": "" }
q242528
_bin_zfill
train
def _bin_zfill(num, width=None): """Convert a base-10 number to a binary string. Parameters num: int width: int, optional Zero-extend the string to this width. Examples -------- >>> _bin_zfill(42) '101010' >>> _bin_zfill(42, 8) '00101010' """ s = bin(num)[2:] ...
python
{ "resource": "" }
q242529
PCData.zero_mask
train
def zero_mask(self): """Return a mask to determine whether an array chunk has any zeros.""" accum = 0 for i in range(self.data.itemsize): accum += (0x55 << (i << 3)) return accum
python
{ "resource": "" }
q242530
PCData.one_mask
train
def one_mask(self): """Return a mask to determine whether an array chunk has any ones.""" accum = 0 for i in range(self.data.itemsize): accum += (0xAA << (i << 3)) return accum
python
{ "resource": "" }
q242531
PCData.iter_zeros
train
def iter_zeros(self): """Iterate through the indices of all zero items.""" num = quotient = 0 while num < self._len: chunk = self.data[quotient] if chunk & self.zero_mask: remainder = 0 while remainder < self.width and num < self._len: ...
python
{ "resource": "" }
q242532
PCData.find_one
train
def find_one(self): """ Return the first index of an entry that is either one or DC. If no item is found, return None. """ num = quotient = 0 while num < self._len: chunk = self.data[quotient] if chunk & self.one_mask: remainder = 0...
python
{ "resource": "" }
q242533
TruthTable.is_neg_unate
train
def is_neg_unate(self, vs=None): r"""Return whether a function is negative unate. A function :math:`f(x_1, x_2, ..., x_i, ..., x_n)` is *negative unate* in variable :math:`x_i` if :math:`f_{x_i'} \geq f_{xi}`. """ vs = self._expect_vars(vs) basis = self.support - set(vs)...
python
{ "resource": "" }
q242534
TruthTable._iter_restrict
train
def _iter_restrict(self, zeros, ones): """Iterate through indices of all table entries that vary.""" inputs = list(self.inputs) unmapped = dict() for i, v in enumerate(self.inputs): if v in zeros: inputs[i] = 0 elif v in ones: input...
python
{ "resource": "" }
q242535
bddvar
train
def bddvar(name, index=None): r"""Return a unique BDD variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``bddvar`` function returns a unique Boolean variable instance represented by a binary decision diagram. Variable...
python
{ "resource": "" }
q242536
_expr2bddnode
train
def _expr2bddnode(expr): """Convert an expression into a BDD node.""" if expr.is_zero(): return BDDNODEZERO elif expr.is_one(): return BDDNODEONE else: top = expr.top # Register this variable _ = bddvar(top.names, top.indices) root = top.uniqid l...
python
{ "resource": "" }
q242537
bdd2expr
train
def bdd2expr(bdd, conj=False): """Convert a binary decision diagram into an expression. This function will always return an expression in two-level form. If *conj* is ``False``, return a sum of products (SOP). Otherwise, return a product of sums (POS). For example:: >>> a, b = map(bddvar, ...
python
{ "resource": "" }
q242538
upoint2bddpoint
train
def upoint2bddpoint(upoint): """Convert an untyped point into a BDD point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module. """ point = dict() for uniqid in upoint[0]: point[_VARS[uniqid]] = 0 for uniqid in upoint[1]:...
python
{ "resource": "" }
q242539
_bddnode
train
def _bddnode(root, lo, hi): """Return a unique BDD node.""" if lo is hi: node = lo else: key = (root, lo, hi) try: node = _NODES[key] except KeyError: node = _NODES[key] = BDDNode(*key) return node
python
{ "resource": "" }
q242540
_bdd
train
def _bdd(node): """Return a unique BDD.""" try: bdd = _BDDS[node] except KeyError: bdd = _BDDS[node] = BinaryDecisionDiagram(node) return bdd
python
{ "resource": "" }
q242541
_path2point
train
def _path2point(path): """Convert a BDD path to a BDD point.""" return {_VARS[node.root]: int(node.hi is path[i+1]) for i, node in enumerate(path[:-1])}
python
{ "resource": "" }
q242542
_find_path
train
def _find_path(start, end, path=tuple()): """Return the path from start to end. If no path exists, return None. """ path = path + (start, ) if start is end: return path else: ret = None if start.lo is not None: ret = _find_path(start.lo, end, path) if...
python
{ "resource": "" }
q242543
_iter_all_paths
train
def _iter_all_paths(start, end, rand=False, path=tuple()): """Iterate through all paths from start to end.""" path = path + (start, ) if start is end: yield path else: nodes = [start.lo, start.hi] if rand: # pragma: no cover random.shuffle(nodes) for node in n...
python
{ "resource": "" }
q242544
_dfs_preorder
train
def _dfs_preorder(node, visited): """Iterate through nodes in DFS pre-order.""" if node not in visited: visited.add(node) yield node if node.lo is not None: yield from _dfs_preorder(node.lo, visited) if node.hi is not None: yield from _dfs_preorder(node.hi, visited)
python
{ "resource": "" }
q242545
_dfs_postorder
train
def _dfs_postorder(node, visited): """Iterate through nodes in DFS post-order.""" if node.lo is not None: yield from _dfs_postorder(node.lo, visited) if node.hi is not None: yield from _dfs_postorder(node.hi, visited) if node not in visited: visited.add(node) yield node
python
{ "resource": "" }
q242546
_bfs
train
def _bfs(node, visited): """Iterate through nodes in BFS order.""" queue = collections.deque() queue.appendleft(node) while queue: node = queue.pop() if node not in visited: if node.lo is not None: queue.appendleft(node.lo) if node.hi is not None: ...
python
{ "resource": "" }
q242547
parse
train
def parse(s): """ Parse a Boolean expression string, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a Boolean expression. See ``pyeda.parsing.boolexpr.GRAMMAR`` for details. Examples -------- >>> parse("a | b ^ c & d")...
python
{ "resource": "" }
q242548
_ite
train
def _ite(lexer): """Return an ITE expression.""" s = _impl(lexer) tok = next(lexer) # IMPL '?' ITE ':' ITE if isinstance(tok, OP_question): d1 = _ite(lexer) _expect_token(lexer, {OP_colon}) d0 = _ite(lexer) return ('ite', s, d1, d0) # IMPL else: lexer...
python
{ "resource": "" }
q242549
_impl
train
def _impl(lexer): """Return an Implies expression.""" p = _sumterm(lexer) tok = next(lexer) # SUMTERM '=>' IMPL if isinstance(tok, OP_rarrow): q = _impl(lexer) return ('implies', p, q) # SUMTERM '<=>' IMPL elif isinstance(tok, OP_lrarrow): q = _impl(lexer) re...
python
{ "resource": "" }
q242550
_sumterm
train
def _sumterm(lexer): """Return a sum term expresssion.""" xorterm = _xorterm(lexer) sumterm_prime = _sumterm_prime(lexer) if sumterm_prime is None: return xorterm else: return ('or', xorterm, sumterm_prime)
python
{ "resource": "" }
q242551
_sumterm_prime
train
def _sumterm_prime(lexer): """Return a sum term' expression, eliminates left recursion.""" tok = next(lexer) # '|' XORTERM SUMTERM' if isinstance(tok, OP_or): xorterm = _xorterm(lexer) sumterm_prime = _sumterm_prime(lexer) if sumterm_prime is None: return xorterm ...
python
{ "resource": "" }
q242552
_xorterm
train
def _xorterm(lexer): """Return an xor term expresssion.""" prodterm = _prodterm(lexer) xorterm_prime = _xorterm_prime(lexer) if xorterm_prime is None: return prodterm else: return ('xor', prodterm, xorterm_prime)
python
{ "resource": "" }
q242553
_xorterm_prime
train
def _xorterm_prime(lexer): """Return an xor term' expression, eliminates left recursion.""" tok = next(lexer) # '^' PRODTERM XORTERM' if isinstance(tok, OP_xor): prodterm = _prodterm(lexer) xorterm_prime = _xorterm_prime(lexer) if xorterm_prime is None: return prodter...
python
{ "resource": "" }
q242554
_prodterm
train
def _prodterm(lexer): """Return a product term expression.""" factor = _factor(lexer) prodterm_prime = _prodterm_prime(lexer) if prodterm_prime is None: return factor else: return ('and', factor, prodterm_prime)
python
{ "resource": "" }
q242555
_prodterm_prime
train
def _prodterm_prime(lexer): """Return a product term' expression, eliminates left recursion.""" tok = next(lexer) # '&' FACTOR PRODTERM' if isinstance(tok, OP_and): factor = _factor(lexer) prodterm_prime = _prodterm_prime(lexer) if prodterm_prime is None: return facto...
python
{ "resource": "" }
q242556
_factor
train
def _factor(lexer): """Return a factor expression.""" tok = _expect_token(lexer, FACTOR_TOKS) # '~' F toktype = type(tok) if toktype is OP_not: return ('not', _factor(lexer)) # '(' EXPR ')' elif toktype is LPAREN: expr = _expr(lexer) _expect_token(lexer, {RPAREN}) ...
python
{ "resource": "" }
q242557
_zom_arg
train
def _zom_arg(lexer): """Return zero or more arguments.""" tok = next(lexer) # ',' EXPR ZOM_X if isinstance(tok, COMMA): return (_expr(lexer), ) + _zom_arg(lexer) # null else: lexer.unpop_token(tok) return tuple()
python
{ "resource": "" }
q242558
_variable
train
def _variable(lexer): """Return a variable expression.""" names = _names(lexer) tok = next(lexer) # NAMES '[' ... ']' if isinstance(tok, LBRACK): indices = _indices(lexer) _expect_token(lexer, {RBRACK}) # NAMES else: lexer.unpop_token(tok) indices = tuple() ...
python
{ "resource": "" }
q242559
_names
train
def _names(lexer): """Return a tuple of names.""" first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) rnames = (first, ) + rest return rnames[::-1]
python
{ "resource": "" }
q242560
_zom_name
train
def _zom_name(lexer): """Return zero or more names.""" tok = next(lexer) # '.' NAME ZOM_NAME if isinstance(tok, DOT): first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return...
python
{ "resource": "" }
q242561
_indices
train
def _indices(lexer): """Return a tuple of indices.""" first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest
python
{ "resource": "" }
q242562
_zom_index
train
def _zom_index(lexer): """Return zero or more indices.""" tok = next(lexer) # ',' INT if isinstance(tok, COMMA): first = _expect_token(lexer, {IntegerToken}).value rest = _zom_index(lexer) return (first, ) + rest # null else: lexer.unpop_token(tok) return ...
python
{ "resource": "" }
q242563
subword
train
def subword(w): """ Function used in the Key Expansion routine that takes a four-byte input word and applies an S-box to each of the four bytes to produce an output word. """ w = w.reshape(4, 8) return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]]
python
{ "resource": "" }
q242564
multiply
train
def multiply(a, col): """Multiply a matrix by one column.""" a = a.reshape(4, 4, 4) col = col.reshape(4, 8) return fcat( rowxcol(a[0], col), rowxcol(a[1], col), rowxcol(a[2], col), rowxcol(a[3], col), )
python
{ "resource": "" }
q242565
rowxcol
train
def rowxcol(row, col): """Multiply one row and one column.""" row = row.reshape(4, 4) col = col.reshape(4, 8) ret = uint2exprs(0, 8) for i in range(4): for j in range(4): if row[i, j]: ret ^= xtime(col[i], j) return ret
python
{ "resource": "" }
q242566
shift_rows
train
def shift_rows(state): """ Transformation in the Cipher that processes the State by cyclically shifting the last three rows of the State by different offsets. """ state = state.reshape(4, 4, 8) return fcat( state[0][0], state[1][1], state[2][2], state[3][3], state[1][0], state[2]...
python
{ "resource": "" }
q242567
key_expand
train
def key_expand(key, Nk=4): """Expand the key into the round key.""" assert Nk in {4, 6, 8} Nr = Nk + 6 key = key.reshape(Nk, 32) rkey = exprzeros(4*(Nr+1), 32) for i in range(Nk): rkey[i] = key[i] for i in range(Nk, 4*(Nr+1)): if i % Nk == 0: rkey[i] = rkey[i-N...
python
{ "resource": "" }
q242568
cipher
train
def cipher(rkey, pt, Nk=4): """AES encryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) pt = pt.reshape(128) # first round state = add_round_key(pt, rkey[0:4]) for i in range(1, Nr): state = sub_bytes(state) state = shift_rows(stat...
python
{ "resource": "" }
q242569
inv_cipher
train
def inv_cipher(rkey, ct, Nk=4): """AES decryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) ct = ct.reshape(128) # first round state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)]) for i in range(Nr-1, 0, -1): state = inv_shift_rows(state) ...
python
{ "resource": "" }
q242570
encrypt
train
def encrypt(key, pt, Nk=4): """Encrypt a plain text block.""" assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) ct = cipher(rkey, pt, Nk) return ct
python
{ "resource": "" }
q242571
decrypt
train
def decrypt(key, ct, Nk=4): """Decrypt a plain text block.""" assert Nk in {4, 6, 8} rkey = key_expand(key, Nk) pt = inv_cipher(rkey, ct, Nk) return pt
python
{ "resource": "" }
q242572
gray2bin
train
def gray2bin(G): """Convert a gray-coded vector into a binary-coded vector.""" return farray([G[i:].uxor() for i, _ in enumerate(G)])
python
{ "resource": "" }
q242573
_assume2point
train
def _assume2point(): """Convert global assumptions to a point.""" point = dict() for lit in _ASSUMPTIONS: if isinstance(lit, Complement): point[~lit] = 0 elif isinstance(lit, Variable): point[lit] = 1 return point
python
{ "resource": "" }
q242574
exprvar
train
def exprvar(name, index=None): r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variab...
python
{ "resource": "" }
q242575
_exprcomp
train
def _exprcomp(node): """Return a unique Expression complement.""" try: comp = _LITS[node.data()] except KeyError: comp = _LITS[node.data()] = Complement(node) return comp
python
{ "resource": "" }
q242576
expr
train
def expr(obj, simplify=True): """Convert an arbitrary object into an Expression.""" if isinstance(obj, Expression): return obj # False, True, 0, 1 elif isinstance(obj, int) and obj in {0, 1}: return _CONSTS[obj] elif isinstance(obj, str): ast = pyeda.parsing.boolexpr.parse(ob...
python
{ "resource": "" }
q242577
ast2expr
train
def ast2expr(ast): """Convert an abstract syntax tree to an Expression.""" if ast[0] == 'const': return _CONSTS[ast[1]] elif ast[0] == 'var': return exprvar(ast[1], ast[2]) else: xs = [ast2expr(x) for x in ast[1:]] return ASTOPS[ast[0]](*xs, simplify=False)
python
{ "resource": "" }
q242578
expr2dimacscnf
train
def expr2dimacscnf(ex): """Convert an expression into an equivalent DIMACS CNF.""" litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
python
{ "resource": "" }
q242579
expr2dimacssat
train
def expr2dimacssat(ex): """Convert an expression into an equivalent DIMACS SAT string.""" if not ex.simple: raise ValueError("expected ex to be simplified") litmap, nvars = ex.encode_inputs() formula = _expr2sat(ex, litmap) if 'xor' in formula: if '=' in formula: fmt = ...
python
{ "resource": "" }
q242580
_expr2sat
train
def _expr2sat(ex, litmap): # pragma: no cover """Convert an expression to a DIMACS SAT string.""" if isinstance(ex, Literal): return str(litmap[ex]) elif isinstance(ex, NotOp): return "-(" + _expr2sat(ex.x, litmap) + ")" elif isinstance(ex, OrOp): return "+(" + " ".join(_expr2sat...
python
{ "resource": "" }
q242581
upoint2exprpoint
train
def upoint2exprpoint(upoint): """Convert an untyped point into an Expression point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module. """ point = dict() for uniqid in upoint[0]: point[_LITS[uniqid]] = 0 for uniqid in u...
python
{ "resource": "" }
q242582
Not
train
def Not(x, simplify=True): """Expression negation operator If *simplify* is ``True``, return a simplified expression. """ x = Expression.box(x).node y = exprnode.not_(x) if simplify: y = y.simplify() return _expr(y)
python
{ "resource": "" }
q242583
Equal
train
def Equal(*xs, simplify=True): """Expression equality operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.eq(*xs) if simplify: y = y.simplify() return _expr(y)
python
{ "resource": "" }
q242584
Implies
train
def Implies(p, q, simplify=True): """Expression implication operator If *simplify* is ``True``, return a simplified expression. """ p = Expression.box(p).node q = Expression.box(q).node y = exprnode.impl(p, q) if simplify: y = y.simplify() return _expr(y)
python
{ "resource": "" }
q242585
Unequal
train
def Unequal(*xs, simplify=True): """Expression inequality operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.not_(exprnode.eq(*xs)) if simplify: y = y.simplify() return _expr(y)
python
{ "resource": "" }
q242586
OneHot0
train
def OneHot0(*xs, simplify=True, conj=True): """ Return an expression that means "at most one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] ...
python
{ "resource": "" }
q242587
OneHot
train
def OneHot(*xs, simplify=True, conj=True): """ Return an expression that means "exactly one input function is true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x in xs] ...
python
{ "resource": "" }
q242588
NHot
train
def NHot(n, *xs, simplify=True): """ Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression. """ if not isinstance(n, int): raise TypeError("expected n to be an int") if not 0 <= n <= len(xs): fstr = "e...
python
{ "resource": "" }
q242589
Majority
train
def Majority(*xs, simplify=True, conj=False): """ Return an expression that means "the majority of input functions are true". If *simplify* is ``True``, return a simplified expression. If *conj* is ``True``, return a CNF. Otherwise, return a DNF. """ xs = [Expression.box(x).node for x ...
python
{ "resource": "" }
q242590
Mux
train
def Mux(fs, sel, simplify=True): """ Return an expression that multiplexes a sequence of input functions over a sequence of select functions. """ # convert Mux([a, b], x) to Mux([a, b], [x]) if isinstance(sel, Expression): sel = [sel] if len(sel) < clog2(len(fs)): fstr = "ex...
python
{ "resource": "" }
q242591
_backtrack
train
def _backtrack(ex): """ If this function is satisfiable, return a satisfying input upoint. Otherwise, return None. """ if ex is Zero: return None elif ex is One: return dict() else: v = ex.top points = {v: 0}, {v: 1} for point in points: so...
python
{ "resource": "" }
q242592
_iter_backtrack
train
def _iter_backtrack(ex, rand=False): """Iterate through all satisfying points using backtrack algorithm.""" if ex is One: yield dict() elif ex is not Zero: if rand: v = random.choice(ex.inputs) if rand else ex.top else: v = ex.top points = [{v: 0}, {v:...
python
{ "resource": "" }
q242593
_tseitin
train
def _tseitin(ex, auxvarname, auxvars=None): """ Convert a factored expression to a literal, and a list of constraints. """ if isinstance(ex, Literal): return ex, list() else: if auxvars is None: auxvars = list() lits = list() constraints = list() ...
python
{ "resource": "" }
q242594
Expression.eq
train
def eq(self, other): """Boolean equal operator.""" other_node = self.box(other).node return _expr(exprnode.eq(self.node, other_node))
python
{ "resource": "" }
q242595
Expression.pushdown_not
train
def pushdown_not(self): """Return an expression with NOT operators pushed down thru dual ops. Specifically, perform the following transformations: ~(a | b | c ...) <=> ~a & ~b & ~c ... ~(a & b & c ...) <=> ~a | ~b | ~c ... ~(s ? d1 : d0) <=> s ? ~d1 : ~d0 """...
python
{ "resource": "" }
q242596
Expression.simplify
train
def simplify(self): """Return a simplified expression.""" node = self.node.simplify() if node is self.node: return self else: return _expr(node)
python
{ "resource": "" }
q242597
Expression.to_binary
train
def to_binary(self): """Convert N-ary operators to binary operators.""" node = self.node.to_binary() if node is self.node: return self else: return _expr(node)
python
{ "resource": "" }
q242598
Expression.to_nnf
train
def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
python
{ "resource": "" }
q242599
Expression.to_dnf
train
def to_dnf(self): """Return an equivalent expression in disjunctive normal form.""" node = self.node.to_dnf() if node is self.node: return self else: return _expr(node)
python
{ "resource": "" }