示例#1
0
def test_curry_call():
    @curry
    def add(x, y):
        return x + y
    assert raises(TypeError, lambda: add.call(1))
    assert add(1)(2) == add.call(1, 2)
    assert add(1)(2) == add(1).call(2)
示例#2
0
def pout(gen, indi) :
    print name(indi)
    cols("",10)
    ndots = 0
    while lt(ndots, gen) :
        out(". ")
        ndots = add(1,ndots)
    out("* "+name(indi))
    e = birth(indi)
    if e : out(", b. "+long(e))
    nl()
    (sp,fam,num,iter) = spouses(indi)
    while sp :
        cols("",10)
        ndots = 0
        while lt(ndots, gen) :
            out("  ")
            ndots = add(1,ndots)
        out("    m. "+name(sp))
        nl()
        (sp,fam,num) = spouses(iter)
    next = add(1,gen)
    if lt(next,15) :
        (fam,sp,num,iter) = families(indi)
        while fam :
            for (no0,child) in children(fam) :
                pout(next, child)
            (fam,sp,num) = families(iter)
示例#3
0
文件: lab01.py 项目: icring/CS-61A
def twenty_fourteen():
    """Come up with the most creative expression that evaluates to 2014, 
    using only numbers and the functions add(. . .) and mul(. . .).

    >>> twenty_fourteen()
    2014
    """
    "*** YOUR CODE HERE ***"
    return add(mul(20, mul(10,10)), add(mul(5,2), 4))
示例#4
0
def pedout(indi, gen, max, top, bot) :
    if indi and le(gen,max) :
        gen = add(1,gen)
        fath = father(indi)
        moth = mother(indi)
        height = add(1,sub(bot,top))
        offset = div(sub(height,8),2)
        block(indi,add(top,offset),mul(10,sub(gen,2)))
        half = div(height,2)
        pedout(fath,gen,max,top,sub(add(top,half),1))
        pedout(moth,gen,max,add(top,half),bot)
示例#5
0
def a_plus_b(a,b):
	"""Return a+abs(b),but without calling abs.
	>>> a_plus_b(2,3)
	5
	>>>a_plus_b(2,-3)
	5
	"""
	if b < 0:
		sub(a,b)
	else:
		add(a,b)
示例#6
0
def sort_(list1, list2, sorted_=None):
    if not list1 and not list2:
        return sorted_
    elif not list1:
        return sort_(list1, list2[1:], add(sorted_, list2[:1]))
    elif not list2:
        return sort_(list1[1:], list2, add(sorted_, list1[:1]))
    else:
        return (sort_(list1[1:], list2, add(sorted_, list1[:1]))
                if list1[0] < list2[0] else
                sort_(list1, list2[1:], add(sorted_, list2[:1])))
示例#7
0
文件: camera.py 项目: coallaoh/manim
 def adjusted_thickness(self, thickness):
     # TODO: This seems...unsystematic
     big_sum = op.add(
         PRODUCTION_QUALITY_CAMERA_CONFIG["pixel_height"],
         PRODUCTION_QUALITY_CAMERA_CONFIG["pixel_width"],
     )
     this_sum = op.add(
         self.get_pixel_height(),
         self.get_pixel_width(),
     )
     factor = fdiv(big_sum, this_sum)
     return 1 + (thickness - 1) / factor
示例#8
0
def pout(gen, indi) :
    message(name(indi)+"\n")
    cols("",add(5,mul(4,gen)),d(add(gen,1))+"-- ")
    outp(indi)
    next = add(1,gen)
    (fam,sp,num,iter) = families(indi)
    while fam :
        cols("",add(5,mul(4,gen))," sp-")
        outp(sp)
        if lt(next,15) :
            for (no0,child) in children(fam) :
                pout(next,child)
        (fam,sp,num) = families(iter)
示例#9
0
def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    """
    if b < 0:
        f = lambda a,b: add(a,-b)
    else:
        f = lambda a,b: add(a,b)
    return f(a, b)
示例#10
0
 def test_addition(self, input_tuple, expected):
     self.ureg.autoconvert_offset_to_baseunit = False
     qin1, qin2 = input_tuple
     q1, q2 = self.Q_(*qin1), self.Q_(*qin2)
     # update input tuple with new values to have correct values on failure
     input_tuple = q1, q2
     if expected == 'error':
         self.assertRaises(OffsetUnitCalculusError, op.add, q1, q2)
     else:
         expected = self.Q_(*expected)
         self.assertEqual(op.add(q1, q2).units, expected.units)
         self.assertQuantityAlmostEqual(op.add(q1, q2), expected,
                                        atol=0.01)
示例#11
0
def test_curry_subclassable():
    class mycurry(curry):
        pass

    add = mycurry(lambda x, y: x+y)
    assert isinstance(add, curry)
    assert isinstance(add, mycurry)
    assert isinstance(add(1), mycurry)
    assert isinstance(add()(1), mycurry)
    assert add(1)(2) == 3

    # Should we make `_should_curry` public?
    """
示例#12
0
def _lis(seq, subseqs=None):
    if not seq:
        return max(subseqs, key=len)
    else:
        head, tail = seq[0], seq[1:]
        if lt_all(subseqs, head):
            return _lis(tail, add(subseqs, [[head]]))
        elif gt_all(subseqs, head):
            expanded = largest_seq(subseqs) + [head]
            return _lis(tail, add(subseqs, [expanded]))
        else:
            expanded = largest_end_seq(subseqs, head) + [head]
            return _lis(tail, add(filter_seqs(subseqs, len(expanded)),
                                  [expanded]))
示例#13
0
文件: hw1.py 项目: lmorales17/cs61a
def two_of_three(a, b, c):
    """Return x*x + y*y, where x and y are the two largest of a, b, c.

    >>> two_of_three(1, 2, 3)
    13
    >>> two_of_three(5, 3, 1)
    34
    >>> two_of_three(10, 2, 8)
    164
    >>> two_of_three(5, 5, 5)
    50
    """
    
    return add(add(a*a, b*b), (c*c))-min(a*a, b*b, c*c)
示例#14
0
 def new_value():
     av, bv, cv = [connector['has_val']() for connector in (a, b, c)]  #关键还是在于这一句看不懂!!!!
     # connector['has_val']()是一句调用那个dict中的匿名函数的call expression.
     # 所以它们三个的值要么是True,要么是False
     print("....")
     print(av)
     print(bv)
     print(cv)
     if av and bv:
         c['set_val'](constraint, add(a['val'], b['val']))
     elif av and cv:
         b['set_val'](constraint, add(c['val'], a['val']))
     elif bv and cv:
         a['set_val'](constraint, add(c['val'], b['val']))
示例#15
0
def block(indi, row, col) :
    print ".",
    row = add(3,row)
    col = add(3,col)
    pos(row,col)
    out(name(indi))
    row = add(row,1)
    pos(row,col)
    e = birth(indi)
    out(" b. ")
    if e and date(e) : out(date(e))
    row = add(row,1)
    pos(row,col)
    out(" bp. ")
    if e and place(e) : out(place(e))
示例#16
0
def filtered_accumulate(combiner, base, pred, n, term):
    """Return the result of combining the terms in a sequence of N terms
    that satisfy the predicate PRED.  COMBINER is a two-argument function.
    If v1, v2, ..., vk are the values in TERM(1), TERM(2), ..., TERM(N)
    that satisfy PRED, then the result is
         BASE COMBINER v1 COMBINER v2 ... COMBINER vk
    (treating COMBINER as if it were a binary operator, like +). The
    implementation uses accumulate.

    >>> filtered_accumulate(add, 0, lambda x: True, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5
    15
    >>> filtered_accumulate(add, 11, lambda x: False, 5, identity) # 11
    11
    >>> filtered_accumulate(add, 0, odd, 5, identity)   # 0 + 1 + 3 + 5
    9
    >>> filtered_accumulate(mul, 1, greater_than_5, 5, square)  # 1 * 9 * 16 * 25
    3600
    >>> # Do not use while/for loops or recursion
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'filtered_accumulate',
    ...       ['While', 'For', 'Recursion', 'FunctionDef'])
    True
    """
    # x if C else y
    modify_combiner = lambda x,y : combiner(x,y) if pred(y) else add(x,0)
    return accumulate(modify_combiner, base, n, term)
示例#17
0
def _phonewords(numbers):
    if not numbers:
        return [[]]
    else:
        return [add([n], x)
                for n in DIGIT_TO_WORDS.get(numbers[0], [numbers[0]])
                for x in _phonewords(numbers[1:])]
示例#18
0
def index_view(request):
    print(request.POST)
    try:
        if request.POST:
            first_number_input = float(request.POST['first_number_input'])
            second_number_input = float(request.POST['second_number_input'])
            operation = request.POST["operator"]

            if operation == "+ (add)":
                answer = operator.add(first_number_input, second_number_input)
                operation = "+"
            elif operation == "- (subtract)":
                answer = operator.sub(first_number_input, second_number_input)
                operation = "-"
            elif operation == "x (multiply)":
                answer = operator.mul(first_number_input, second_number_input)
                operation = "x"
            else:
                try:
                    answer = operator.truediv(first_number_input, second_number_input)
                except ZeroDivisionError:
                    answer = "Answer is Undefined (You can't divide by zero)"
                operation = "/"
            return render(request, 'index.html', {'answer': answer,
                                                  'operation': operation,
                                                  'first_number': first_number_input,
                                                  'second_number': second_number_input})
        else:
            return render(request,'index.html',{})
    except (ValueError, TypeError):
        answer = "INVALID ENTRY"
        return render(request, "index.html",{'answer':answer})
示例#19
0
def updateFunction(newValues, oldValues):
    # for the first time, initialize with newValues
    if oldValues is None:
       return newValues
      
    # return a list of elements
    return add(newValues, oldValues)
示例#20
0
    def generate_message(cj, cij, incoming):
        ''' Compute max-sum message from xi to xj. '''

        # Compute max over xj for the message to xi.

        if cj.names[0] == cij.names[0]:
            edge = lambda xi, xj: (xj, xi)
        else:
            edge = lambda xi, xj: (xi, xj)

        incoming_tab = np.array([
            add(cj((xj,)), reduce(add, (m(xj) for m in incoming), 0.))
            for xj in range(cj.nstates[0])])

        # Memoize message.
        cache = dict()

        def message(xi):
            if xi not in cache:
                cache[xi] = max(
                        add(cij(edge(xi, xj)), incoming_tab[xj])
                        for xj in range(cj.nstates[0]))
            return cache[xi]

        return message
示例#21
0
    def declare_policies(self, _policies, pi_p, matrix_nd):
        """
        this function receives dictionary of state action pairs an related vector value improvements
        and returns back dictionary of policies related to given pairs and the same vector value improvement
        :param _policies: dictionary of this form : {0: ((1, 0), (0, 1)), [ 1.20030463,  0.        ])
        :param pi: the given policy without counting improvement in accounts
        :return: dictionary of new policies and related improved vector values
        """

        _pi_p = pi_p.copy()
        V_append_d = np.zeros(self.mdp.d, dtype= ftype)

        new_policies = {}
        _pi_old = copy.deepcopy(_pi_p)

        for k, policy in _policies.iteritems():
            for key, val in _pi_p.iteritems():
                tempo = [item[1] for item in policy[0] if item[0] == key]
                if tempo:
                    _pi_p[key] = tempo
                #else:
                #    adv_d = self.get_initial_distribution()[key]*(self.mdp.get_vec_Q(key, _pi_old[key][0],  matrix_nd)-matrix_nd[key])
                #    V_append_d = operator.add(V_append_d, adv_d)

            #V_append_d = np.zeros(self.mdp.d, dtype=ftype)

            new_policies[k] = (_pi_p,np.float32(operator.add(policy[1], V_append_d)) ) #np.float32(policy[1]))
            _pi_p = copy.deepcopy(_pi_old)

        return new_policies
示例#22
0
def condition_no(name):
    from math import sqrt
    h=0.001
    f=[]
    fh=[]
    ab=[]
    conditi=[]
    x=list
    for x in nup.arange(-1,1.1,0.1):
        for y in nup.arange(-1,1.1,0.1):
            try:
                f.append(eval(name))
                ab.append(sqrt(add(x**2,y**2)))
            except ValueError:
                pass
    for x in nup.arange(-1,1.1,0.1):
        try:
            x=x+h
            for y in nup.arange(-1,1.1,0.1):
                try:
                    y=y+h
                    fh.append(eval(name))
                except ValueError:
                    pass
        except ValueError:
            pass
    for num in range(0,len(f)):
        if f[num]!=0:
            D=abs(f[num])*sqrt(2)*h
            N=abs(fh[num]-f[num])*ab[num]
            conditi.append(N/D)
        else:
            conditi.append(None)
    return conditi
示例#23
0
文件: app.py 项目: dingchaoz/ML
def main(sc):

    # Load the airlines lookup dictionary
    airlines = dict(sc.textFile("ontime/airlines.csv").map(split).collect())

    # Broadcast the lookup dictionary to the cluster
    airline_lookup = sc.broadcast(airlines)

    # Read the CSV Data into an RDD
    flights = sc.textFile("ontime/flights.csv").map(split).map(parse)

    # Map the total delay to the airline (joined using the broadcast value)
    delays  = flights.map(lambda f: (airline_lookup.value[f.airline],
                                     add(f.dep_delay, f.arv_delay)))

    # Reduce the total delay for the month to the airline
    delays  = delays.reduceByKey(add).collect()
    delays  = sorted(delays, key=itemgetter(1))

    # Provide output from the driver
    for d in delays:
        print ("%0.0f minutes delayed\t%s" % (d[1], d[0]))

    # Show a bar chart of the delays
    plot(delays)
示例#24
0
def run():
    primes = prime_reader.read_primes_default()
    last_prime = primes.next()

    prime_count = 0
    diag_total = 1
    current = 1
    for ring in eu.numbers(2):
        incr = (ring - 1) * 2

        for corner in xrange(3):
            current = op.iadd(current, incr)
            while current > last_prime:
                last_prime = primes.next()
            if current == last_prime:
                prime_count = op.iadd(prime_count, 1)
            
        current = op.add(current, incr)
        
        diag_total = op.iadd(diag_total, 4)
        
        perc = op.div(float(prime_count), diag_total)

        # print ring, side_length(ring), last_prime, diag_total, perc
        
        if op.lt(perc, 0.1):
            return side_length(ring)
示例#25
0
文件: stacie.py 项目: lavabit/magma
def CalculateHashRounds(password, bonus):
    # Accepts a user password and bonus value, and calculates
    # the number of iterative rounds required. This function will
    # always return a value between 8 and 16,777,216.

    # Identify the number of Unicode characters.
    characters = len(password.decode("utf-8"))

    # Calculate the difficulty exponent by subtracting 1
    # for each Unicode character in a password.
    dynamic = operator.sub(24, characters)

    # Use a minimum exponent value of 1 for passwords
    # equal to, or greater than, 24 characters.
    dynamic = max(1, dynamic)

    # Derive the variable number of rounds based on the length.
    # Raise 2 using the dynamic exponent determined above.
    variable = pow(2, dynamic)

    # If applicable, add the fixed number of bonus rounds.
    total = operator.add(variable, bonus)

    # If the value of rounds is smaller than 8, reset
    # the value to 8.
    total = max(8, total)

    # If the value of rounds is larger than 16,777,216, reset
    # the value to 16,777,216.
    total = min(pow(2, 24), total)

    return total
示例#26
0
 def getSum(self, a, b):
     """
     :type a: int
     :type b: int
     :rtype: int
     """
     return operator.add(a,b)
示例#27
0
文件: nodes.py 项目: guyjacks/jeap
    def evaluate(self):
        result = None
        left = self.left.evaluate()
        right = self.right.evaluate()

        if self.operation == '+':
            result = operator.add(left, right)
        elif self.operation == '-':
            result = operator.sub(left, right)
        elif self.operation == '*':
            result = operator.mul(left, right)
        elif self.operation == '/':
            result = operator.div(left, right)
        elif self.operation == '^':
            result = operator.pow(left, right)
        elif self.operation == 'and':
            result = left and right
        elif self.operation == 'or':
            result = left or right
        elif self.operation == '<':
            result = operator.lt(left, right)
        elif self.operation == '<=':
            result = operator.le(left, right)
        elif self.operation == '==':
            result = operator.eq(left, right)
        elif self.operation == '!=':
            result = operator.ne(left, right)
        elif self.operation == '>':
            result = operator.gt(left, right)
        elif self.operation == '>=':
            result = operator.ge(left, right)
        elif self.operation == 'in':
            result = (left in right)
        return result
示例#28
0
    def _call(self, arguments, delta_time, computing_context):
        try:
            result = OperatorComputingResult(add(*arguments), NoneComputingContext())
        except:
            result = NoneComputingResult()

        return result
示例#29
0
    def _build_paths(files, system_bitness):
        """Build paths of the files based on the system bitness.

        Chooses different directories depending on the value of the
        system_bitness. If the bitness is neither 32 nor 64 then the
        USER_DIR directory will be used.

        Args:
            files (list): The names of the files themselves.
            system_bitness (int): The system bitness.
        """
        file_paths = ["" for file in files]

        file_paths = Classifier._extend_paths(file_paths, DATA_PATH)
        if system_bitness == SYSTEM_BITNESS_32:
            file_paths = Classifier._extend_paths(file_paths,
                                                  HARDCODED_32BIT_DIR)
        elif system_bitness == SYSTEM_BITNESS_64:
            file_paths = Classifier._extend_paths(file_paths,
                                                  HARDCODED_64BIT_DIR)
        else:
            file_paths = Classifier._extend_paths(file_paths, USER_DIR)

        file_paths = [operator.add(l, r)
                      for l, r in zip(file_paths, files)]

        return file_paths
示例#30
0
    def p_expression_binop(self, p):
        """expression : expression PLUS expression
                      | expression MINUS expression
                      | expression TIMES expression
                      | expression DIVIDE expression
                      | expression MODULUS expression
                      | expression EXPONENT expression"""

        op = p[2]
        left = self._sumDiceRolls(p[1])
        right = self._sumDiceRolls(p[3])

        if op == '+':
            p[0] = operator.add(left, right)
        elif op == '-':
            p[0] = operator.sub(left, right)
        elif op == '*':
            p[0] = operator.mul(left, right)
        elif op == '/':
            p[0] = operator.floordiv(left, right)
        elif op == '%':
            p[0] = operator.mod(left, right)
        elif op == '^':
            if -self._MAX_EXPONENT <= left <= self._MAX_EXPONENT and -self._MAX_EXPONENT <= right <= self._MAX_EXPONENT:
                p[0] = operator.pow(left, right)
            else:
                raise InvalidOperandsException(u'operand or exponent is larger than the maximum {}'
                                               .format(self._MAX_EXPONENT))
def topla(ilk_sayi, ikinci_sayi):
    return add(ilk_sayi, ikinci_sayi)
示例#32
0
    def generate(self, gen_cat=True):
        print('--Beginning Fast build--')
        # Drawing causes
        self.causes = [i for i in range(np.random.randint(
            2, self.nodes / np.floor(np.sqrt(self.nodes))))]
        self.causes = list(set(self.causes))
        self.data = pd.DataFrame(None)
        layer = [[]]
        for i in self.causes:
            self.data['V' + str(i)] = cause(self.n_points)
            layer[0].append(i)

        generated_nodes = len(self.causes)

        links = []
        while generated_nodes < self.nodes:
            print(
                '--Generating nodes : {} out of ~{}'.format(generated_nodes, self.nodes))
            layer.append([])  # new layer

            num_nodes_layer = np.random.randint(2, len(layer[-2]) + 2)
            for i in range(num_nodes_layer):
                layer[-1].append(generated_nodes)
                # draw causes
                last_idx = layer[-2][-1]
                parents = list(set([np.random.randint(0, last_idx)
                                    for i in range(
                    self.num_max_parents)]))  # np.random.randint(self.num_max_parents - 1, self.num_max_parents))]))
                child = []
                # Compute each cause's contribution
                for par in parents:
                    links.append(['V' + str(par), 'V' + str(generated_nodes)])
                    child.append(
                        effect(self.data['V' + str(par)], self.n_points, self.noise))
                # Combine contributions
                shuffle(child)
                result = child[0]
                for i in child[1:]:
                    rd_func = self.joint_functions[np.random.randint(
                        0, len(self.joint_functions))]
                    result = op.add(result, i)
                # Add a final noise
                rd_func = self.joint_functions[np.random.randint(
                    0, len(self.joint_functions))]
                if rd_func == op.mul:
                    noise_var = noise(self.n_points, self.noise).flatten()
                    result = rd_func(result + abs(min(result)),
                                     noise_var + abs(min(noise_var)))
                    # +abs(min(result))
                else:
                    result = rd_func(result, noise(
                        self.n_points, self.noise).flatten())
                result = scale(result)

                self.data['V' + str(generated_nodes)] = result

                generated_nodes += 1
        self.result_links = pd.DataFrame(links, columns=["Cause", "Effect"])
        print('--Dataset Generated--')
        if gen_cat:
            print('--Converting variables to categorical--')
            actual_cat_rate = 0.0
            self.cat_var = []
            self.cat_data = self.data.copy()
            while actual_cat_rate < self.cat_rate:
                print(
                    '--Converting, Actual rate: {:3.3f}/{}--'.format(actual_cat_rate, self.cat_rate))
                var = np.random.randint(0, self.nodes)
                while var in self.cat_var:
                    var = np.random.randint(0, self.nodes)
                self.cat_var.append(var)
                self.cat_data['V' + str(var)] = rand_bin(
                    list(self.cat_data['V' + str(var)]))
                actual_cat_rate = float(len(self.cat_var)) / self.nodes

            self.cat_var = pd.DataFrame(self.cat_var)
        print('Build Directed Graph')
        self.graph = DirectedGraph()
        self.graph.add_multiple_edges(
            [list(i) + [1] for i in self.result_links.as_matrix()])

        print('--Done !--')
        return self.get_data()
 def __add__(self, y):
     return NonStandardInteger(operator.add(self.val, y))
 def __radd__(self, y):
     return NonStandardInteger(operator.add(y, self.val))
示例#35
0
 def __add__(self, other: Any) -> Any:
     return operator.add(*self._get_operands(other))
示例#36
0
 def add(self, a, b):
     return operator.add(a, b)
示例#37
0
#https://docs.python.org/3/library/operator.html

import operator

a,b,c,d,e,f=1,3,7,'hello','world',' '
h=['a','b','c']
g=operator.iadd(d,f)
print(operator.iadd(h,g))
print(operator.add(a,b))
print(operator.iadd(g,e))
示例#38
0
#
# primitive expressions and statements, which represent the simplest building blocks that the language provides,
# means of combination, by which compound elements are built from simpler ones, and
# means of abstraction, by which compound elements can be named and manipulated as units.

x = max(min(1, -2), min(pow(3, 5), -4))
print(x)

from math import sqrt, pi

print('square of 256:', sqrt(256))
print('100 * pi:', pi * 100)

from operator import add, sub, mul

print('14 + 28:', add(14, 28))
print('100 - 7 * (8 + 4) = ', sub(100, mul(7, add(8, 4))))

print(max)
f = max
print(f)
print(f(2, 3, 4))
f = 2
print(f)

max = 5
print(max)
# max(2, 3, 4), bind built-in names to new values
# TypeError: 'int' object is not callable

x = 2
示例#39
0
 def test_not_numerical_offset(self):
     u = Unit('meter')
     with self.assertRaisesRegexp(TypeError, 'unsupported operand type'):
         operator.add(u, 'not_a_number')
示例#40
0
 def test_no_unit(self):
     u = Unit('no unit')
     with self.assertRaisesRegexp(ValueError, 'Cannot offset'):
         operator.add(u, 10)
示例#41
0
def join(one, two):
    """
    Join two objects owning the same inner representation.
    """
    return list(map(lambda z: operator.add(*z), zip(one, two)))
示例#42
0
# -*- coding: utf-8 -*-
# Programación funcional
# Lección 4
# Módulo operator

import operator

operator.add(1, 2)
operator.sub(1, 2)
operator.mul(1, 2)
operator.pow(1, 2)

operator.mod(1, 2)

operator.eq(1, 2)
operator.lt(1, 2)
operator.gt(1, 2)
示例#43
0
 def test_add(self):
     self.failUnlessRaises(TypeError, operator.add)
     self.failUnlessRaises(TypeError, operator.add, None, None)
     self.failUnless(operator.add(3, 4) == 7)
示例#44
0
def test_operator():
    print(operator.add(1, 2))
    print(operator.mul(3, 10))
    print(operator.pow(2, 3))
    print(operator.itemgetter(1)([1, 2, 3]))
示例#45
0
文件: lambda.py 项目: wvangeit/scoop
#    published by the Free Software Foundation, either version 3 of
#    the License, or (at your option) any later version.
#
#    SCOOP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with SCOOP. If not, see <http://www.gnu.org/licenses/>.
#
"""
SCOOP also works on lambda functions even if they aren't picklable by default.
"""
from scoop import futures, shared
from math import cos
import operator

if __name__ == "__main__":
    # Standard lambda function
    myFunc = lambda x: x * 2
    # Lambda function using a globally defined function
    myFunc2 = lambda x: cos(x)
    # Lambda function using a function through a module definition
    myFunc3 = lambda x: operator.add(x, 1)

    # Calls to SCOOP
    print(list(futures.map(myFunc, range(10))))
    print(list(futures.map(myFunc2, range(10))))
    print(list(futures.map(myFunc3, range(10))))
示例#46
0
import operator 

num1 = 10
num2 = 3

operator.add(num1, num2) #  num1 + num2

operator.sub(num1, num2) # num1 - num2

operator.mul(num1, num2) # num1 * num2

operator.truediv(num1, num2) # num1 / num2

operator.mod(num1, num2) # num1 % num2

operator.floordiv(num1, num2) # num1 // num2

operator.pow(num1, num2) # num1 ** num2

示例#47
0
    :param x: euro/dollar/shekel
    :param y: euro/dollar/shekel
    :return: amount in shekels.
    """
    return x + y


type_tags = {Dollar: "dollar", Euro: "euro", Shekel: "nis"}
rates = {("dollar", "nis"): 3.82, ("euro", "nis"): 4.07}
s = Shekel(50)
d = Dollar(50)
e = Euro(50)
print(d.amount())
print(e.amount())
print(d + s)
print(add(e, d))
z = eval(repr(d))
print(z)
print(s)
print(e)


def apply(func_name, x, y):
    """
      generic func that gets an opertion name and do the operation on x and y uses implementation to choose the necessary
       func and operate it on x and y
      :param func_name: add,sub
      :param x: euro/dollar/shekel
      :param y: euro/dollar/shekel
      :return: x+y,x-y in the type of x
      """
示例#48
0
# Numeric expressions
2016
2000 + 16
1 + 2 * ((3 * 4 * 5 // 6)**3) + 7 + 8

# Call expressions
max(3, 4.5)
pow(100, 2)
pow(2, 100)
max(1, -2, 3, -4)
max(pow(10, 2), pow(2, 10), 1010)

# Importing and arithmetic with call expressions
from operator import add, mul

add(1, 2)
mul(4, 6)
mul(add(4, mul(4, 6)), add(3, 5))
mul(9, mul(add(4, mul(4, 6)), add(3, 5)))

from math import sqrt

sqrt(169)

# Objects
# Note: Download from http://composingprograms.com/shakespeare.txt
shakes = open('shakespeare.txt')
text = shakes.read().split()
len(text)
text[:25]
text.count('the')