Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
972 liner solution in Uncategorized category for Funny Addition by Juge_Ti
try:
from itertools import combinations, permutations, filterfalse, dropwhile
import collections as collections
from collections.abc import MutableMapping
from functools import total_ordering
import json as newsted
from netrc import NetrcParseError
from platform import system_alias
import crypt as draculashouse
from random import getrandbits
import math as mathematics
from hmac import compare_digest
import curses as women
from hashlib import algorithms_guaranteed, algorithms_available
import imp as gremlin
from ctypes import Structure, c_double
import operator
import errno as wouldyouliketodance
import re
from multiprocessing import Process, Lock
from multiprocessing.managers import BaseManager
from multiprocessing.sharedctypes import Value, Array
from multiprocessing.connection import wait
import distutils.archive_util
import distutils.bcppcompiler
import distutils.ccompiler
import distutils.cmd
import distutils.command
import distutils.command.bdist
import distutils.command.bdist_dumb
import distutils.command.bdist_msi
import distutils.command.bdist_rpm
import distutils.command.bdist_wininst
import distutils.command.build
import distutils.command.build_clib
import distutils.command.build_ext
import distutils.command.build_py
import distutils.command.build_scripts
import distutils.command.check
import distutils.command.clean
import distutils.command.config
import distutils.command.install
import distutils.command.install_data
import distutils.command.install_headers
import distutils.command.install_lib
import distutils.command.install_scripts
import distutils.command.register
import distutils.command.sdist
import distutils.core
import distutils.cygwinccompiler
import distutils.debug
import distutils.dep_util
import distutils.dir_util
import distutils.dist
import distutils.emxccompiler
import distutils.errors
import distutils.extension
import distutils.fancy_getopt
import distutils.file_util
import distutils.filelist
import distutils.log
import distutils.msvccompiler
import distutils.spawn
import distutils.sysconfig
import distutils.text_file
import distutils.unixccompiler
import distutils.util
import distutils.version
import distutils.command.bdist_msi
import distutils.command.build_scripts
import this
except:
pass
#from __future__ import braces
class ListBasedSet(collections.Set):
''' Alternate set implementation favoring space over speed
and not requiring the set elements to be hashable. '''
def __init__(self, iterable):
self.elements = lst = []
for value in iterable:
if value not in lst:
lst.append(value)
def __iter__(self):
return iter(self.elements)
def __contains__(self, value):
return value in self.elements
def __len__(self):
return len(self.elements)
class Foo:
def f(self):
print('you called Foo.f()')
def g(self):
print('you called Foo.g()')
def _h(self):
print('you called Foo._h()')
def get_pep(num):
resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
try:
with urllib.request.urlopen(resource) as s:
return s.read()
except urllib.error.HTTPError:
return 'Not Found'
# A simple generator function
def baz():
for i in range(10):
yield i*i
# Function to return the operator module
def get_operator_module():
return operator
def test():
manager = MyManager()
manager.start()
print('-' * 20)
f1 = manager.Foo1()
f1.f()
f1.g()
assert not hasattr(f1, '_h')
assert sorted(f1._exposed_) == sorted(['f', 'g'])
print('-' * 20)
f2 = manager.Foo2()
f2.g()
f2._h()
assert not hasattr(f2, 'f')
assert sorted(f2._exposed_) == sorted(['g', '_h'])
print('-' * 20)
it = manager.baz()
for i in it:
print('<%d>' % i, end=' ')
print()
print('-' * 20)
op = manager.operator()
print('op.add(23, 45) =', op.add(23, 45))
print('op.pow(2, 94) =', op.pow(2, 94))
print('op.getslice(range(10), 2, 6) =', op.getslice(list(range(10)), 2, 6))
print('op.repeat(range(5), 3) =', op.repeat(list(range(5)), 3))
print('op._exposed_ =', op._exposed_)
def modify(n, x, s, A):
n.value **= 2
x.value **= 2
s.value = s.value.upper()
for a in A:
a.x **= 2
a.y **= 2
def othertest():
print('cpu_count() = %d\n' % multiprocessing.cpu_count())
#
# Create pool
#
PROCESSES = 4
print('Creating pool with %d processes\n' % PROCESSES)
pool = multiprocessing.Pool(PROCESSES)
print('pool = %s' % pool)
print()
#
# Tests
#
TASKS = [(mul, (i, 7)) for i in range(10)] + \
[(plus, (i, 8)) for i in range(10)]
results = [pool.apply_async(calculate, t) for t in TASKS]
imap_it = pool.imap(calculatestar, TASKS)
imap_unordered_it = pool.imap_unordered(calculatestar, TASKS)
print('Ordered results using pool.apply_async():')
for r in results:
print('\t', r.get())
print()
print('Ordered results using pool.imap():')
for x in imap_it:
print('\t', x)
print()
print('Unordered results using pool.imap_unordered():')
for x in imap_unordered_it:
print('\t', x)
print()
print('Ordered results using pool.map() --- will block till complete:')
for x in pool.map(calculatestar, TASKS):
print('\t', x)
print()
#
# Simple benchmarks
#
N = 100000
print('def pow3(x): return x**3')
t = time.time()
A = list(map(pow3, range(N)))
print('\tmap(pow3, range(%d)):\n\t\t%s seconds' % \
(N, time.time() - t))
t = time.time()
B = pool.map(pow3, range(N))
print('\tpool.map(pow3, range(%d)):\n\t\t%s seconds' % \
(N, time.time() - t))
t = time.time()
C = list(pool.imap(pow3, range(N), chunksize=N//8))
print('\tlist(pool.imap(pow3, range(%d), chunksize=%d)):\n\t\t%s' \
' seconds' % (N, N//8, time.time() - t))
assert A == B == C, (len(A), len(B), len(C))
print()
L = [None] * 1000000
print('def noop(x): pass')
print('L = [None] * 1000000')
t = time.time()
A = list(map(noop, L))
print('\tmap(noop, L):\n\t\t%s seconds' % \
(time.time() - t))
t = time.time()
B = pool.map(noop, L)
print('\tpool.map(noop, L):\n\t\t%s seconds' % \
(time.time() - t))
t = time.time()
C = list(pool.imap(noop, L, chunksize=len(L)//8))
print('\tlist(pool.imap(noop, L, chunksize=%d)):\n\t\t%s seconds' % \
(len(L)//8, time.time() - t))
assert A == B == C, (len(A), len(B), len(C))
print()
del A, B, C, L
#
# Test error handling
#
print('Testing error handling:')
try:
print(pool.apply(f, (5,)))
except ZeroDivisionError:
print('\tGot ZeroDivisionError as expected from pool.apply()')
else:
raise AssertionError('expected ZeroDivisionError')
try:
print(pool.map(f, list(range(10))))
except ZeroDivisionError:
print('\tGot ZeroDivisionError as expected from pool.map()')
else:
raise AssertionError('expected ZeroDivisionError')
try:
print(list(pool.imap(f, list(range(10)))))
except ZeroDivisionError:
print('\tGot ZeroDivisionError as expected from list(pool.imap())')
else:
raise AssertionError('expected ZeroDivisionError')
it = pool.imap(f, list(range(10)))
for i in range(10):
try:
x = next(it)
except ZeroDivisionError:
if i == 5:
pass
except StopIteration:
break
else:
if i == 5:
raise AssertionError('expected ZeroDivisionError')
assert i == 9
print('\tGot ZeroDivisionError as expected from IMapIterator.next()')
print()
#
# Testing timeouts
#
print('Testing ApplyResult.get() with timeout:', end=' ')
res = pool.apply_async(calculate, TASKS[0])
while 1:
sys.stdout.flush()
try:
sys.stdout.write('\n\t%s' % res.get(0.02))
break
except multiprocessing.TimeoutError:
sys.stdout.write('.')
print()
print()
print('Testing IMapIterator.next() with timeout:', end=' ')
it = pool.imap(calculatestar, TASKS)
while 1:
sys.stdout.flush()
try:
sys.stdout.write('\n\t%s' % it.next(0.02))
except StopIteration:
break
except multiprocessing.TimeoutError:
sys.stdout.write('.')
print()
print()
#
# Testing callback
#
print('Testing callback:')
A = []
B = [56, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
r = pool.apply_async(mul, (7, 8), callback=A.append)
r.wait()
r = pool.map_async(pow3, list(range(10)), callback=A.extend)
r.wait()
if A == B:
print('\tcallbacks succeeded\n')
else:
print('\t*** callbacks failed\n\t\t%s != %s\n' % (A, B))
#
# Check there are no outstanding tasks
#
assert not pool._cache, 'cache = %r' % pool._cache
#
# Check close() methods
#
print('Testing close():')
for worker in pool._pool:
assert worker.is_alive()
result = pool.apply_async(time.sleep, [0.5])
pool.close()
pool.join()
assert result.get() is None
for worker in pool._pool:
assert not worker.is_alive()
print('\tclose() succeeded\n')
#
# Check terminate() method
#
print('Testing terminate():')
pool = multiprocessing.Pool(2)
DELTA = 0.1
ignore = pool.apply(pow3, [2])
results = [pool.apply_async(time.sleep, [DELTA]) for i in range(100)]
pool.terminate()
pool.join()
for worker in pool._pool:
assert not worker.is_alive()
print('\tterminate() succeeded\n')
#
# Check garbage collection
#
print('Testing garbage collection:')
pool = multiprocessing.Pool(2)
DELTA = 0.1
processes = pool._pool
ignore = pool.apply(pow3, [2])
results = [pool.apply_async(time.sleep, [DELTA]) for i in range(100)]
results = pool = None
time.sleep(DELTA * 2)
for worker in processes:
assert not worker.is_alive()
print('\tgarbage collection succeeded\n')
class Term:
"""
A term consists of a coefficient and some number of variables.
Examples: 1, 4*x, x*x*y*z, 22*y*y*y*y
"""
def __init__(self, coeff, symbols):
"""
Construct a term from a coefficient and symbols.
coeff: An integer value, the coefficient of this term.
symbols: A string of concatenated symbols (not joined by '*')
"""
self.coeff = coeff
self.symbols = sort_letters(symbols)
@property
def terms(self):
"""Return a sequence of terms in this term, i.e., self."""
return (self,)
def __add__(self, other):
"""
Add two terms.
Return either a Term or a Series depending on whether the symbols match.
Adding to a Series is handled in Series.
"""
if isinstance(other, Term):
return simplify((self, other))
return NotImplemented
def __sub__(self, other):
"""
Subtract two terms.
Return either a Term or a Series depending on whether the symbols match.
Subtracting Series is handled in Series.
"""
if isinstance(other, Term):
return simplify((self, -other))
return NotImplemented
def __mul__(self, other):
"""
Multiply two terms.
Return a new Term.
Multiplying by a Series is handled in Series.
"""
if isinstance(other, Term):
return Term(self.coeff * other.coeff, self.symbols + other.symbols)
return NotImplemented
def __neg__(self):
"""Unary minus."""
return Term(-self.coeff, self.symbols)
def __eq__(self, other):
"""Return whether self is equal to other."""
return self.coeff == other.coeff and self.symbols == other.symbols
def __le__(self, other):
"""
Return whether self is less than or equal to other.
>>> Term(1, 'x') <= Term(4, 'x')
True
>>> Term(1, 'xx') <= Term(4, 'x')
False
>>> Term(1, 'xz') <= Term(3, 'xy')
False
"""
# Sorting priority: Quantity of symbols (more first), symbols,
# The sorting rules for terms ensure that terms with more symbols
# are smaller.
if self.symbols == other.symbols:
return self.coeff <= other.coeff
lens, leno = len(self.symbols), len(other.symbols)
if lens == leno:
return self.symbols <= other.symbols
return leno < lens
def __bool__(self):
return True if self.coeff else False
def __str__(self):
"""
Return term as a string, following several special case rules.
The coefficient never appears if it has value one, unless there
are no symbols.
The result will never have a leading '+', but if coefficient
is negative it will have a leading '-'.
"""
if not self.symbols:
return '{}'.format(self.coeff)
# Handle the special case of a coefficient of +- 1.
if abs(self.coeff) != 1:
head = '{}*'.format(self.coeff)
elif self.coeff == -1:
head = '-'
else:
head = ''
if self.symbols:
return head + '*'.join(self.symbols)
def __repr__(self):
return "Term({}, '{}')".format(self.coeff, self.symbols)
class Series:
"""
An expression consisting of a sum of terms.
"""
def __init__(self, terms):
terms = list(terms)
if not all(isinstance(item, Term) for item in terms):
raise AssertionError("All series arguments must be terms,\
not {}".format(terms))
self.terms = terms
def __len__(self):
return len(self.terms)
def __bool__(self):
return True if self.terms else False
def __iter__(self):
return iter(self.terms)
def __getitem__(self, key):
return self.terms[key]
def __add__(self, other):
"""
Add a Series to either another Series or a Term.
Return a Series or Term.
The result is simplified.
"""
if not isinstance(other, (Term, Series)):
return NotImplemented
return simplify(itertools.chain(self.terms, other.terms))
# Addition is commutative.
__radd__ = __add__
def __sub__(self, other):
"""
Subtract either another Series or a Term from series.
Return a Series or Term.
The result is simplified.
"""
if not isinstance(other, (Term, Series)):
return NotImplemented
return simplify(itertools.chain(self.terms, (-other).terms))
def __rsub__(self, other):
"""
Subtract self from either another Series or a Term.
Return a Series or Term.
The result is simplified.
"""
if not isinstance(other, (Term, Series)):
return NotImplemented
return simplify(itertools.chain((-self).terms, other.terms))
def __mul__(self, other):
"""
Multiply a Series by either another Series or a Term.
Return a Series or Term.
The result is simplified.
"""
if not isinstance(other, (Term, Series)):
return NotImplemented
components = itertools.product(self.terms, other.terms)
multiplied = itertools.starmap(operator.mul, components)
return simplify(multiplied)
# Multiplication is commutative.
__rmul__ = __mul__
def __neg__(self):
"""Unary minus for a series."""
return Series(-term for term in self.terms)
def __str__(self):
if not(any(self.terms)):
return '0'
result = ''
for term in sorted(self.terms):
ts = str(term)
if result and ts[0] != '-':
result += '+'
result += ts
return result
def __repr__(self):
return "Series([{}])".format(", ".join(repr(x) for x in sorted(self)))
def checkio(data):
a, b = data
return a + b
def simplify(terms):
"""
Return a Series or Term consisting of the unification of terms.
Terms with the same symbols are combined, and if there is exactly
one term remaining it is returned as a Term. Otherwise, it is returned
as a Series.
"""
counts = collections.Counter()
for term in terms:
counts[term.symbols] += term.coeff
coeffs = list((coeff, symbols) for symbols, coeff in counts.items()\
if coeff != 0)
if len(coeffs) == 1:
coeff, symbols = coeffs[0]
return Term(coeff, symbols)
return Series(itertools.starmap(Term, coeffs))
def sort_letters(text):
"""Return the letters in text, sorted."""
return ''.join(sorted(text))
# Polynomial expressions will be parsed using a generic lexer and parser.
#
# A lexer converts a character stream into a stream of logical tokens.
# A parser consumes these tokens and generates parsed data.
# The following parser is not very efficient, and only supports a simplistic
# grammar, but is suitable for relatively small polynomial expressions.
class Lexer:
"""
Tokenize a stream of characters.
"""
def __init__(self, rules):
"""
Initialize a Lexer.
rules: A list of token id, regular expression, data function tuples.
Rules will be matched in order, with the first match taking precedence.
"""
self.rules = [(token, re.compile(re_text), data_fn)\
for token, re_text, data_fn in rules]
def tokenize(self, text):
"""
Generate a sequence of (token, data) pairs.
"""
ix = 0
while ix < len(text):
for token, rex, data_fn in self.rules:
m = rex.match(text, ix)
if not m:
continue
data = None
if data_fn is not None:
data = data_fn(m.group(0))
yield token, data
ix = m.end()
break
else:
raise RuntimeError("Could not tokenize '{}'\
at position {}".format(text, ix))
class Parser:
"""
Parse a stream of tokens.
"""
def __init__(self, rules=(), brackets=()):
"""
Initialize a parser.
brackets: A sequence of tuples of open, close bracket pairs.
rules: A sequence of lists of rules, organized into precedence groups.
Each rule is a production from input tokens to output tokens.
"""
self.rules = rules
for group in self.rules:
if not all(len(group[0][0]) == len(rule[0]) for rule in group):
raise AssertionError("All rules in the same group\
must have the same token pattern length.")
self.open_brackets = {}
self.close_brackets = {}
for (lb, rb) in brackets:
self.open_brackets[lb] = rb
self.close_brackets[rb] = lb
def parse(self, tokens):
"""Parse a tream of tokens and return the result."""
stack = [[]]
for token, data in tokens:
if token in self.open_brackets:
# If an open bracket is encountered, push a substack
stack.append(token)
stack.append([])
elif token in self.close_brackets:
# If a close bracket is encountered, simplify the expression
# and then hoist it up to the enclosing stack.
if stack[-2] != self.close_brackets[token]:
raise RuntimeError("Mismatched bracket {}".format(token))
current = stack.pop()
stack.pop()
stack[-1].extend(self.simplify(current))
else:
# Otherwise, append the token to the current stack.
stack[-1].append((token, data))
if len(stack) != 1:
raise RuntimeError("Not enough closing brackets.")
# At this point, we have one stack, which we still need to simplify.
return self.simplify(stack[0])[0][1]
def simplify(self, tokens):
"""
Return a simplified version of tokens by applying rules.
Rules are applied repeatedly until no rules match.
"""
match = True
while match:
# Continue applying rules as long as one matches.
match = False
for group in self.rules:
# Go through the groups in precedence order
count = len(group[0][0])
for i in range(len(tokens) - count + 1):
# Find the first match starting from the left. This treats
# each operator as left-associative.
ix = slice(i, i + count)
sub = tuple(x[0] for x in tokens[ix])
for lhs, rhs, fn in group:
if lhs == sub:
match = True
data = tuple(x[1] for x in tokens[ix])
result = fn(data)
tokens[ix] = zip(rhs, result)
break
if match:
break
if match:
break
return tokens
class PolyNoomClass: # define PolyNoom PolyTerm(1) --- PolyTerm(n)
def __init__(self):
self.PolyNoom = []
self.PolyNoom.append(PolyTermClass(0, 0))
def __str__(self):
return self.PolyNoomToString()
def __repr__(self):
return self.PolyNoomToString()
def __iter__(self):
self.index = -1
return self
def __next__(self):
if self.index == len(self.PolyNoom)-1:
raise StopIteration
self.index += 1
return self.PolyNoom[self.index]
def __type__(self):
return "PolyNoomClass"
def AddAPolyNoom(self,PolyNoom):
for PolyTermTemp in PolyNoom:
self.AddAPolyTerm(PolyTermTemp)
def AddAPolyTerm(self, PolyTerm):
if PolyTerm.Exponent > self.PolyNoom[-1].Exponent:
for Expo in range(self.PolyNoom[-1].Exponent + 1,
PolyTerm.Exponent):
self.PolyNoom.append(PolyTermClass(0, Expo))
self.PolyNoom.append(PolyTerm)
else:
self.PolyNoom[PolyTerm.Exponent].Factor += PolyTerm.Factor
def MultiplyByPolyNoom(self, Right):
Result=PolyNoomClass()
for PolyTerm in Right:
Base=copy.deepcopy(self)
Base.MultiplyByPolyTerm(PolyTerm)
Result.AddAPolyNoom(Base)
self.__init__()
self.AddAPolyNoom(Result)
def MultiplyByPolyTerm(self,PolyTerm):
#Factor
for PolyTermTemp in self.PolyNoom:
PolyTermTemp.Factor *= PolyTerm.Factor
#Exponent
for PolyTermTemp in self.PolyNoom:
PolyTermTemp.Exponent += PolyTerm.Exponent
for Insert in range(PolyTerm.Exponent):
self.PolyNoom.append(PolyTermClass(0, Insert))
self.Sort()
def PolyNoomToString(self):
self.Sort(Order="Desc") # factor to int for this probem
PolyTermString =[format(int(self.PolyNoom[i].Factor)) +\
"*x" * (self.PolyNoom[i].Exponent) for i in range(len(self.PolyNoom))\
if self.PolyNoom[i].Factor != 0]
self.Sort()
PolyNoomString=""
if len(PolyTermString) != 0:
for PolyTerm in PolyTermString:
PolyTermTemp=PolyTerm.replace("1*x", "x")
if PolyTermTemp[0] != "-":
PolyTermTemp="+"+PolyTermTemp
PolyNoomString += PolyTermTemp
if PolyNoomString[0] == "+":
PolyNoomString=PolyNoomString[1:]
return PolyNoomString
def Sort(self, *, Order="Ascending"):
if Order != "Desc":
self.PolyNoom.sort(key=lambda PolyTerm: PolyTerm.Exponent)
else:
self.PolyNoom.sort(key=lambda PolyTerm: PolyTerm.Exponent,
reverse=True)
def UseResult(self, Result, Token):
if Token == "*":
self.MultiplyByPolyNoom(Result)
elif Token == "+":
self.AddAPolyNoom(Result)
elif Token == "-":
self.MultiplyByPolyTerm(PolyTermClass(-1, 0))
self.AddAPolyNoom(Result)
class PolyTermClass: # define PolyTerm [Factor, Exponent]
def __init__(self, Factor, Exponent):
self.Factor = float(Factor)
self.Exponent = int(Exponent)
if Exponent <0:
raise "Exponent must be Positive"
def __str__(self):
return "Factor =" + format(self.Factor) + ", Exponent ="\
+ format(self.Exponent)
def __repr__(self):
return repr([self.Factor, self.Exponent])
def MultiplyByFactor(self, Factor):
if self.Factor == 0:
self.Factor = float(1)
self.Factor *= float(Factor)
def RaiseExponentByExponent(self, Exponent):
if self.Factor == 0:
self.Factor = float(1)
self.Exponent += int(Exponent)
def RemoveUnWantedAsterix(Formula):
Formula=Formula.replace("*(", "&")
Formula=Formula.replace(")*", "#")
Formula=Formula.replace("*","")
Formula=Formula.replace("&","*(")
Formula=Formula.replace("#",")*")
return Formula
def BuildTermsAsPolyNoom(Formula):
# replace individual term by PolyNooms
TermsAsPolyNoom=[]
PolyNoom=PolyNoomClass()
for Term in Formula:
if Term in ("+-*()"):
if not (PolyNoom.PolyNoom[-1].Exponent == 0 and\
PolyNoom.PolyNoom[-1].Factor == 0):
TermsAsPolyNoom.append(PolyNoom)
PolyNoom = PolyNoomClass()
TermsAsPolyNoom.append(Term)
else:
if Term == "x":
PolyNoom.PolyNoom[-1].RaiseExponentByExponent(1)
else:
PolyNoom.PolyNoom[-1].MultiplyByFactor(Term)
if not (PolyNoom.PolyNoom[-1].Exponent == 0 and\
PolyNoom.PolyNoom[-1].Factor == 0):
TermsAsPolyNoom.append(PolyNoom)
return TermsAsPolyNoom
def GetDeepestBracketPair(Formula):
for LastOpen in range(len(Formula)-1,-1,-1):
if Formula[LastOpen] == "(":
break
for EndBracked in range(LastOpen +1,len(Formula)):
if Formula[EndBracked] == ")":
break
return LastOpen, EndBracked
def BuildPolyNoomNonBrackets(Formula):
print("nonbracket in =")
print(Formula)
PolyNoom = PolyNoomClass()
MultiplyToken=PolyNoomClass()
NotUsedPolyNoom = PolyNoomClass()
NotUsedToken = "+"
for Token in Formula:
if Token == "*" :
if NotUsedToken == "-":
NotUsedPolyNoom.MultiplyByPolyTerm(PolyTermClass(-1,0))
MultiplyToken.AddAPolyNoom(NotUsedPolyNoom)
elif NotUsedToken == "+":
MultiplyToken.AddAPolyNoom(NotUsedPolyNoom)
elif NotUsedToken =="*":
MultiplyToken.MultiplyByPolyNoom(NotUsedPolyNoom)
NotUsedPolyNoom = PolyNoomClass()
NotUsedToken =Token
elif Token == "+" or Token =="-":
if NotUsedToken == "-":
NotUsedPolyNoom.MultiplyByPolyTerm(PolyTermClass(-1,0))
MultiplyToken.AddAPolyNoom(NotUsedPolyNoom)
elif NotUsedToken == "+":
MultiplyToken.AddAPolyNoom(NotUsedPolyNoom)
elif NotUsedToken =="*":
MultiplyToken.MultiplyByPolyNoom(NotUsedPolyNoom)
PolyNoom.AddAPolyNoom(MultiplyToken)
MultiplyToken= PolyNoomClass()
NotUsedPolyNoom = PolyNoomClass()
NotUsedToken = Token
else:
NotUsedPolyNoom.AddAPolyNoom(Token)
if NotUsedToken == "-":
NotUsedPolyNoom.MultiplyByPolyTerm(PolyTermClass(-1,0))
MultiplyToken.AddAPolyNoom(NotUsedPolyNoom)
elif NotUsedToken == "+":
MultiplyToken.AddAPolyNoom(NotUsedPolyNoom)
elif NotUsedToken =="*":
MultiplyToken.MultiplyByPolyNoom(NotUsedPolyNoom)
PolyNoom.AddAPolyNoom(MultiplyToken)
print("nonbracket uit =")
print(Formula)
return PolyNoom
def BuildPolyNoom(Formula):
LastOpen, EndBracked = GetDeepestBracketPair(Formula)
while Formula[LastOpen] == "(":
PolyNoomNonBrackets = BuildPolyNoomNonBrackets(Formula[LastOpen+1:EndBracked])
Temp=Formula[:LastOpen]
Temp.append(PolyNoomNonBrackets)
Temp+=Formula[EndBracked+1:]
Formula = Temp
LastOpen, EndBracked = GetDeepestBracketPair(Formula)
return BuildPolyNoomNonBrackets(Formula)
if __name__ == '__naim__':
lock = Lock()
n = Value('i', 7)
x = Value(c_double, 1.0/3.0, lock=False)
s = Array('c', 'hello world', lock=lock)
A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
p = Process(target=modify, args=(n, x, s, A))
p.start()
p.join()
Sept. 26, 2013
Comments: