Esempio n. 1
0
def polyroots(q, p, pol):
    """
    Finds all of the roots of polynomial @pol, with the constant of highest
    degree @q and the constant of x**0 @p. Returns a set of all the roots.

    >>> polyroots(1, 2, 'x**3 - 2*x**2 - x + 2')
    set([1, 2, -1])

    TODO: Add ability to find @q and @p from @pol

    AUTHORS:
    v0.5.1+             --> pydsigner
    v1.1.0+             --> pydsigner
    """
    # First a set of fractions is generated from the factors of @q and @p;
    # These fractions are every possible (x/y equaling -x/-y and
    # -x/y equaling x/-y) combination of these factors (the factors of @p being
    # in the denominator) that makes the polynomial equal 0
    S = set(x for x in set(
        flatten((frac(pv, qv), frac(-pv, qv)) for qv in factors(abs(q))
                for pv in factors(abs(p))))
            if eval(pol.replace('x', 'frac("%s")' % x)) == 0)

    # Make new set where whole numbers are changed to int()s and any lossless
    # conversions to float()s are made
    nset = set()
    for n in S:
        if n.denominator == 1:
            nset.add(n.numerator)
        elif frac(float(n)) == n:
            nset.add(float(n))
        else:
            nset.add(n)
    return nset
Esempio n. 2
0
def solve_test_case():
    line = sys.stdin.readline().rstrip().split(' ')
    n_points = int(line[0])
    dice_sets = [DiceSet(*d_str.split('d')) for d_str in line[1].split('+')]
    dices = [ds.n_sides for ds in dice_sets for _ in range(ds.n_dices)]

    dices = sorted(dices)
    probs = None
    for idx, n_sides in enumerate(dices):
        # If first dice
        if idx == 0:
            # Probability of obtaining i points is 1 / n_sides
            probs = {p: frac(1, n_sides) for p in range(1, n_sides + 1)}
            continue

        # Remaining dices
        new_probs = defaultdict(lambda: frac(0, 1))
        for points in range(1, n_sides + 1):
            for old_points, old_prob in probs.items():
                new_probs[old_points + points] += old_prob * frac(1, n_sides)

        probs = new_probs

    # Calculate probability of getting more than n points
    goal_prob = frac(0, 1)
    for points, prob in probs.items():
        if points >= n_points:
            goal_prob += prob

    return \
        '0/1' if goal_prob.numerator == 0 else \
        '1/1' if goal_prob.denominator == 1 else \
        str(goal_prob)
Esempio n. 3
0
def standardForm(matrix):
    i = 0
    terminatingRows, nonTerminatingRows = [], []
    for idx, row in enumerate(matrix):
        if all([val == 0 for val in row]):
            terminatingRows.append(idx)
        else:
            nonTerminatingRows.append(idx)

    standardRows = terminatingRows + nonTerminatingRows
    standardMatrix = [[0 for _ in range(len(matrix[0]))]
                      for _ in range(len(matrix))]
    for i in range(len(terminatingRows)):
        standardMatrix[i][i] = 1

    for i in range(len(terminatingRows), len(standardMatrix)):
        for j in range(len(matrix[0])):
            standardMatrix[i][j] = matrix[standardRows[i]][standardRows[j]]

    R, Q = [], []
    for i in range(len(terminatingRows), len(standardMatrix)):
        deno = sum(standardMatrix[i])
        rRow, qRow = [], []
        for j in range(len(standardMatrix[0])):
            if j < len(terminatingRows):
                rRow.append(frac(standardMatrix[i][j], deno))
            else:
                qRow.append(frac(standardMatrix[i][j], deno))
        R.append(rRow)
        Q.append(qRow)

    return R, Q
Esempio n. 4
0
        def visit_node(node):
            assert self._repetition_vector[node] is not None

            # look at all edges
            for channel in graph.sdf.channel:
                if channel.srcActor == node:  # outgoing connections
                    production_rate = rates[channel.srcActor][channel.srcPort]
                    consumption_rate = rates[channel.dstActor][channel.dstPort]
                    factor = frac(production_rate, consumption_rate)
                    src_rate = self._repetition_vector[channel.srcActor]
                    dst_rate = src_rate * factor
                    if self._repetition_vector[channel.dstActor] is None:
                        self._repetition_vector[channel.dstActor] = dst_rate
                        # recursive traversal
                        visit_node(channel.dstActor)
                    elif self._repetition_vector[channel.dstActor] != dst_rate:
                        raise RuntimeError("SDF graph is not consistent!")
                elif channel.dstActor == node:  # incoming connections
                    production_rate = rates[channel.srcActor][channel.srcPort]
                    consumption_rate = rates[channel.dstActor][channel.dstPort]
                    factor = frac(production_rate, consumption_rate)
                    dst_rate = self._repetition_vector[channel.dstActor]
                    src_rate = dst_rate / factor
                    if self._repetition_vector[channel.srcActor] is None:
                        self._repetition_vector[channel.srcActor] = src_rate
                        # recursive traversal
                        visit_node(channel.srcActor)
                    elif self._repetition_vector[channel.srcActor] != src_rate:
                        raise RuntimeError("SDF graph is not consistent!")
Esempio n. 5
0
def PerChordSymbolAndPosition(PCTX, SIGTRE):
    Y = []
    for ChordsInEveryPart in ChordListGetter(PartsContainsChord(PCTX)):
        X = []
        for DictItemWhichKeyIsPartName in ChordsInEveryPart:
            ListOfChordWithEveryPartContent = []
            for i in ChordsInEveryPart[DictItemWhichKeyIsPartName]:
                ListOfChordWithEveryPartContent.append(
                    (i[0], 1 / int(i[1].rstrip('*>').lstrip('<')), i[2]))
            SpaceBeforeChord = 0
            WholePartLength = 0
            for i in range(len(ListOfChordWithEveryPartContent)):
                WholePartLength += ListOfChordWithEveryPartContent[i][1] * \
                    ListOfChordWithEveryPartContent[i][2] * \
                    frac(str(SIGTRE[1]) + '/' + str(SIGTRE[0]))
                if i == 0:
                    X.append((0.0, [
                        m.groupdict() for m in re.finditer(
                            PerChordPattern, ListOfChordWithEveryPartContent[i]
                            [0])
                    ][0]))
                else:
                    SpaceBeforeChord += frac(ListOfChordWithEveryPartContent[i - 1][1]) * \
                        frac(ListOfChordWithEveryPartContent[i - 1][2]) * \
                        frac(str(SIGTRE[1]) + '/' + str(SIGTRE[0]))
                    X.append((SpaceBeforeChord, [
                        m.groupdict() for m in re.finditer(
                            PerChordPattern, ListOfChordWithEveryPartContent[i]
                            [0])
                    ][0]))
            Y.append(({DictItemWhichKeyIsPartName: X}, WholePartLength))
    return Y
Esempio n. 6
0
def niceprint(matrix, ij=[None, None]):
    sp = ' ' * 50
    print(f'{bcolors.X}{sp}{bcolors.ENDC}\n')
    ki = 0
    for irow, row in enumerate(matrix):
        pp = []
        for icol, rr in enumerate(row):
            if abs(rr) > 1.e-8:
                r = frac(rr)
                if r.numerator > 1.e3 or r.denominator > 1.e3:
                    r = f'{rr:7.3f}'
                else:
                    r = str(frac(rr))
                if (ij[0] == irow) and (ij[1] == icol):
                    r = f'{bcolors.OKGREEN}{r}{bcolors.ENDC}'
            else:
                r = '0'
            pp.append(r)
        p = pp[:-1]
        p.append(f'{bcolors.WARNING}:{bcolors.ENDC}')
        p.append(f'{bcolors.TST}{pp[-1]}{bcolors.ENDC}')
        msg = "\t".join(p)
        print(msg)
        print("\u001b[0m")  # reset
    return 0
    def test_points_on_different_curves(self):
        C1 = EllipticCurve(3,4)
        C2 = EllipticCurve(5,4)
        self.assertFalse(C1 == C2)
        P1 = Point(C1,frac(0), frac(2))
        P2 = Point(C2,frac(0), frac(2))

        with self.assertRaises(Exception):
            #I don't think it makes sense to compare points on different curves
            #but correct me if I'm wrong.
            P1 == P2

        with self.assertRaises(Exception):
            P1 < P2

        with self.assertRaises(Exception):
            P1 > P2

        with self.assertRaises(Exception):
            P1 <= P2

        with self.assertRaises(Exception):
            P1 >= P2

        with self.assertRaises(Exception):
            P1 + P2

        with self.assertRaises(Exception):
            P1 - P2
Esempio n. 8
0
def fractran(n, prog, giveup=100):

    states = []
    states.append(n)

    count = 0
    while True:
        count+=1
        if count>giveup:
            return(states)
        if prog == []:
            return(states)
        i = 0
        while True:

            try:
                dif = abs(n*(frac(prog[i][0],prog[i][1])) - int(n*(frac(prog[i][0],prog[i][1]))))

                if  (dif<=0.000001) |(round(dif,4)==1):
                    states.append(int(n*(frac(prog[i][0],prog[i][1]))))
                    n = int(n*(frac(prog[i][0],prog[i][1])))

                    break

                    n = int(n)
                else:
                    n = int(n)
                    i+=1
                    if i>len(prog):
                        return(states)
            except:
                return(states)
    return(states)
Esempio n. 9
0
def csanky(input_matrix):
    A = input_matrix
    n,m = A.shape
    if n!=m:
        raise ValueError(n,'by',m,'matrix input. Input must be square.')
    
    # get traces
    M = Id(n)
    trace = dict()
    i = 1
    while i <= n:
        M = M*A
        trace[i] = tr(M)
        i += 1
    
    # and the core of the algorithm...
    b = matrix([[frac((-1)**(i+1)*trace[i],i) for i in range(1,n+1)]],dtype=object).transpose()
    T = matrix([[0 for i in range(n)] for j in range(n)],dtype=object)
    i = 0
    while i<n:
        j = 0
        while j<i:
            c = (-1)**(i-j+1)
            T[i,j] = frac(c*frac(1,i+1)*trace[i-j])
            j += 1
        i += 1
    T = Id(n)-T
    T = rec_lt_block_invert(T)
    return T*b # note: returns s1 through sn; s0 is 1 and is not in the result
Esempio n. 10
0
def rec_lt_block_invert(input_matrix): # recursive inverse for lower triangular
    M = input_matrix # also assumes that there are no 0s on diagonal, which
    n,m = M.shape # works in this context (diagonal will be 1's)
    
    # make sure it's square...
    if n!=m:
        raise ValueError('Inverse of non-square matrix.')
    
    # base case...
    if n==1:
        return matrix([[frac(1,frac(M[0,0]))]])
    
    # make sure it's lower triangular...
    for i in range(n):
        for j in range(i+1,n):
            if M[i,j]!=0:
                raise ValueError('Inversion method is for lower triangular matrices only.')
    
    # split into blocks for recursion
    l = int(n/2) # size of smaller block
    A = M[:l,:l] # upper left
    B = M[l:,l:] # lower right
    E = M[l:,:l] # lower left
    O = M[:l,l:] # upper right, should be all zeros
    A = rec_lt_block_invert(A) # invert A
    B = rec_lt_block_invert(B) # invert B
    E = -B*E*A # "invert" E
    R = concatenate((concatenate((A,E),axis=0),concatenate((O,B),axis=0)),axis=1)
    return matrix(R)
Esempio n. 11
0
def solution(pegs):
    lst = []
    for i in range(len(pegs) - 1):
        lst.append(pegs[i + 1] - pegs[i])

    last_gear = 0
    for i, ele in enumerate(lst):
        if i % 2 == 0:
            last_gear += ele
        else:
            last_gear -= ele

    if len(pegs) % 2 == 0:
        last_gear = frac(last_gear, 3)

    first_gear = frac(last_gear) * 2

    if first_gear <= 0 or last_gear <= 0:
        return [-1, -1]

    ss = [first_gear]
    cur_gear = first_gear
    for element in lst:
        check = element - cur_gear
        if check <= 1:
            return [-1, -1]
        ss.append(check)
        cur_gear = check

    for i in range(len(ss) - 1):
        klo = ss[i] + ss[i + 1]
        if klo != lst[i]:
            return [-1, -1]

    return [first_gear.numerator, first_gear.denominator]
Esempio n. 12
0
def polyroots(q, p, pol):
    """
    Finds all of the roots of polynomial @pol, with the constant of highest
    degree @q and the constant of x**0 @p. Returns a set of all the roots.

    >>> polyroots(1, 2, 'x**3 - 2*x**2 - x + 2')
    set([1, 2, -1])

    TODO: Add ability to find @q and @p from @pol

    AUTHORS:
    v0.5.1+             --> pydsigner
    v1.1.0+             --> pydsigner
    """
    # First a set of fractions is generated from the factors of @q and @p;
    # These fractions are every possible (x/y equaling -x/-y and
    # -x/y equaling x/-y) combination of these factors (the factors of @p being
    # in the denominator) that makes the polynomial equal 0
    S = set(x for x in
      set(flatten((frac(pv, qv), frac(-pv, qv)) for qv in factors(abs(q))
                   for pv in factors(abs(p))))
      if eval(pol.replace('x', 'frac("%s")' % x)) == 0)

    # Make new set where whole numbers are changed to int()s and any lossless
    # conversions to float()s are made
    nset = set()
    for n in S:
        if n.denominator == 1:
            nset.add(n.numerator)
        elif frac(float(n)) == n:
            nset.add(float(n))
        else:
            nset.add(n)
    return nset
Esempio n. 13
0
def main():
    print("یه اینتر اضافه آخرش بزنید")
    print("insirt A")
    satr = [frac(x) for x in input().split()]
    matrix = np.array(satr)
    loghat = []
    satr = [frac(x) for x in input().split()]
    while len(satr) != 0:
        matrix = np.vstack((matrix, satr))
        satr = [frac(x) for x in input().split()]
    matrix_reduce, p, p_r, p_c = echelon(matrix)
    print("ماتریس کاهش یافته ی سطری")
    print(matrix_reduce.astype(str))
    free_c = [c for c in range(matrix.shape[1]) if c not in p_c]
    null = []
    for col in free_c:
        v = np.zeros((matrix.shape[1], 1))
        v[col] = 1
        for piv in p:
            v[piv[1], 0] = -1 * matrix_reduce[piv[0], col]
        null.append(v)
    print("پایه های فضای پوچ")
    for b in null:
        print(b)
        print("#####")
    print("مختصات بقیه ی بردار ها بر اساس بردار پایه")
    for free in free_c:
        zarib = np.zeros((len(p_r), 1))
        for row in p_r:
            zarib[row] = matrix_reduce[row, free]
        print(zarib)
        print("====")
Esempio n. 14
0
def solver_results(x, s, m, c, w, order=False, verbose=True):
    """
    solves the optimization equation
    :param s: speeds
    :param m: gekko model
    :param c: completion times
    :param verbose: boolean to print or not
    :param order: optional order to print or not
    :return: task_process_time, ending times, intervals, speeds, objective value
    """

    #m.Obj(O) # Objective

    try:
        m.options.IMODE = 3  # Steady state optimization
        m.solve(disp=verbose)  # Solve

    except:
        # print("Did not work")
        # if order!=False:
        # print("Order is ", order)
        return [], [-1] * len(s), [-1] * len(s), [-1, -1] * len(s), [
            -1
        ] * len(s), 10000000

    task_process_time = [
        frac(w[i] / frac(s[i].value[0])) for i in range(len(s))
    ]
    ending_time = [frac(c[i].value[0]) for i in range(len(c))]
    intervals = [[end - process_time, end]
                 for (process_time, end) in zip(task_process_time, ending_time)
                 ]
    speeds = [frac(s[i].value[0]) for i in range(len(s))]

    task_process_time = [
        float(process_time.__round__(5)) for process_time in task_process_time
    ]
    ending_time = [float(end_time.__round__(5)) for end_time in ending_time]
    intervals = [[
        float(interval[0].__round__(5)),
        float(interval[1].__round__(5))
    ] for interval in intervals]
    speeds = [float(speed.__round__(5)) for speed in speeds]

    if verbose:
        print('Results')
        for i in range(len(s)):
            print(
                str(i) + " Speed: " + str(s[i].value) + " Ending Time: " +
                str(c[i].value) + " Interval: " + str(intervals[i]) +
                " Task process time: " + str(task_process_time[i]))
        print('Objective: ' + str(m.options.objfcnval))

    if x != None:
        order = create_order(x, c)
    else:
        order = None

    return order, task_process_time, ending_time, intervals, speeds, float(
        frac(m.options.objfcnval).__round__(5))
Esempio n. 15
0
def answer(m):
    denominators = get_denominators(m)

    absorbing_states = []
    non_absorbing_states = []
    for state in range(len(denominators)):
        if denominators[state] == 0:
            absorbing_states.append(state)
        else:
            non_absorbing_states.append(state)

    # handle 1x1 nad 2x2 matricies
    if len(denominators) <= 2:
        return [1, 1]

    # handle absorbing state 0
    if 0 in absorbing_states:
        return [1 if s == 0 else 0 for s in range(len(m))] + [1]

    # setup standard for matricies
    q_matrix = [[frac(m[n][q], denominators[n]) for q in non_absorbing_states]
                for n in non_absorbing_states]
    i_matrix = get_identity_matrix(q_matrix)

    r_matrix = [[frac(m[n][a], denominators[n]) for a in absorbing_states]
                for n in non_absorbing_states]

    # calculate
    iq_matrix = subtract_matricies(i_matrix, q_matrix)
    f_matrix = invert_matrix(subtract_matricies(i_matrix, q_matrix))
    result_matrix = multiply_matricies(f_matrix, r_matrix)

    # get probabilities from s0
    return get_int_array_for_fractions(result_matrix[0])
Esempio n. 16
0
 def __compute_left_to_sale(self) -> frac:
     left_to_sale = frac("1")
     for item in self.processing.order_by(Processing.id):
         if left_to_sale < frac(str(item.done)):
             return frac("0.0")
         left_to_sale -= frac(str(item.done))
     return left_to_sale
Esempio n. 17
0
 def f(k):
     global cache
     n = frac(1, k)
     nx = [str(1), str(k)]
     alist = []
     if k == 1:
         return 1
     while True:
         if nx[0] == "1" and len(nx) != 1:
             alist += [nx[1]]
         if len(nx) == 1 or int(nx[1]) == 1:
             for i in alist:
                 cache[i] = int(nx[0])
             return int(nx[0])
         else:
             x = nx[0]
             y = nx[1]
         x = int(x) + 1
         y = int(y) - 1
         n = frac(x, y)
         nx = str(n).split("/")
         if nx[0] == "1" and len(nx) != 1 and cache.get(nx[1]):
             global count
             count += 1
             for i in alist:
                 cache[i] = cache.get(nx[1])
             return cache.get(nx[1])
Esempio n. 18
0
 def __compute_wall_area_to_sale(self) -> frac:
     wall_area_to_sale = self.__compute_gross_wall_area()
     for hole in self.holes:
         if not hole.below_3m2:
             wall_area_to_sale -= frac(str(hole.total_area)) - frac(
                 str(hole.amount))
     return wall_area_to_sale
Esempio n. 19
0
def polyroots(q, p, pol):
    '''
    Finds all of the roots of polynomial @pol, with the constant of highest 
    degree @q and the constant of x**0 @p. Returns a set of all the roots.
    
    >>> polyroots(1, 2, 'x**3 - 2*x**2 - x + 2')
    set([1, 2, -1])
    
    TODO: Add ability to find @q and @p from @pol
    
    AUTHORS:
    v0.5.1+         --> pydsigner
    '''
    s = set((x for x in set(iter_utils.flatten((((frac(up, uq) for uq, up in [
                    (-qv, -pv), (-qv, pv), (qv, -pv), (qv, pv)]) 
                for qv in factors(abs(q))) for pv in factors(abs(p))))) 
            if eval(pol.replace('x', 'frac("%s")' % x)) == 0))
    
    nset = set()
    for n in s:
        if n.denominator == 1:
            nset.add(n.numerator)
        elif frac(float(n)) == n:
            nset.add(float(n))
        else:
            nset.add(n)
    return nset
Esempio n. 20
0
def victory_chance(current_board, tqdm_nesting=0):
    if count_ones(current_board.state) == 15:
        return frac(1, 1)

    hash = current_board.hash()

    with ENV.begin() as txn:
        stored = txn.get(hash + b"_chance")

    if stored is not None:
        return frac(*struct.unpack(">2Q", stored))

    total_chance = frac(0, 1)
    weights = zip(*get_weights(current_board.remaining_pieces))

    best_positions = {}

    if tqdm_nesting > 0:
        weights = pbar(weights,
                       leave=False,
                       total=len(PIECES),
                       desc=f"Weights {tqdm_nesting-1}")

    for weight, last_legal in weights:
        if weight == 0:
            continue

        boards = [(current_board.place(last_legal, x, y), x, y)
                  for x in range(current_board.w)
                  for y in range(current_board.h)]
        boards = [i for i in boards if i[0] is not None]

        if tqdm_nesting > 0:
            boards = pbar(boards,
                          desc=f"Victory {tqdm_nesting-1}",
                          leave=False)

        chances = [(victory_chance(board, tqdm_nesting - 1), x, y)
                   for board, x, y in boards]
        chances.sort(reverse=True)

        total_chance += 0 if len(chances) == 0 else chances[0][0] * weight
        chances = [{
            "numerator": chance._numerator,
            "denominator": chance.denominator,
            "x": x,
            "y": y
        } for chance, x, y in chances]
        best_positions[last_legal] = chances

    chance_packed = struct.pack(">2Q", total_chance._numerator,
                                total_chance.denominator)
    moves_dumped = json.dumps(best_positions).encode()

    with ENV.begin(write=True) as txn:
        txn.put(hash + b"_chance", chance_packed)
        txn.put(hash + b"_moves", moves_dumped)

    return total_chance
Esempio n. 21
0
def A(prof):
    if prof == 0:
        return frac(2)
    else:
        a = frac(2 + (1 / 2))
        for i in range(prof - 1):
            a = frac(2 + 1 / a)
        return frac(a)
def convert_to_1(row, value):
    try:
        value = frac(value)
        inverse_of_value = value**-1
        for index, i in enumerate(row):
            row[index] = frac(i) * inverse_of_value
    except ZeroDivisionError:
        print("This system of equations cant be solved")
        exit()
Esempio n. 23
0
def getConstant(x,y):
	n = np.shape(y)[0]
	pyramid = np.zeros([n,n])
	pyramid = pyramid.astype('object')
	pyramid[::,0] = y
	for j in range(1,n):
		for i in range(n-j):
		  pyramid[i][j] = frac((frac(pyramid[i+1][j-1]) - frac(pyramid[i][j-1])),(frac(x[i+j]) - frac(x[i])))
	return pyramid[0]
def probabilify_matrix(m):
    for row in m:
        denominator = sum(row)
        if not denominator == 0:
            for i in range(len(row)):
                row[i] = frac(row[i], denominator)
        else:
            for i in range(len(row)):
                row[i] = frac(0)
Esempio n. 25
0
def validate_done_attr_while_editing(wall: db.Model, processing: db.Model,
                                     data: Dict) -> Dict:
    done = data.get("done")
    if done:
        left_to_sale = frac(str(wall.left_to_sale))
        left_to_sale += frac(str(processing.done))
        if float(left_to_sale) < float(done):
            data["done"] = float(left_to_sale)
    return data
Esempio n. 26
0
def addArray(arr,new_value):
  try:
			if '/' in new_value:
			  new_value = frac(new_value)
			else:
			  new_value = int(new_value)
  except:
    new_value = frac(new_value).limit_denominator()
  return np.append(arr,  new_value)
 def test_equals(self):
     self.assertTrue(zero == Ideal(C))
     self.assertTrue(P == Point(C, frac(3), frac(5)))
     self.assertTrue(Q == Point(C, frac(-2), frac(0)))
     self.assertFalse(zero == P)
     self.assertFalse(zero == Q)
     self.assertFalse(P == zero)
     self.assertFalse(P == Q)
     self.assertFalse(Q == zero)
     self.assertFalse(Q == P)
Esempio n. 28
0
def reduce(v1, v2):
    v1 = [frac(v) for v in v1]
    v2 = [frac(v) for v in v2]
    while True:
        if norm(v2) < norm(v1):
            v1, v2 = v2, v1
        m = round(dot(v1, v2) / norm(v1), 0)
        if m == 0:
            return ([float(v) for v in v1], [float(v) for v in v2])
        v2 = [u2 - m * u1 for u2, u1 in zip(v2, v1)]
Esempio n. 29
0
 def __init__(self, s):
     """
     :param s: string notation of the units. there should be whitespace around quantities and '/' dividing quantities
     """
     if isinstance(s, OSUnits):
         self.power = cp.deepcopy(s.power)
     else:
         self.power = np.array(
             [frac(0), frac(0), frac(0),
              frac(0), frac(0)])
         if isinstance(s, bytes):
             s = s.decode("utf-8")
         if 'a.u.' != s:
             sl = s.split()
             nominator = True
             while sl:
                 ss = sl.pop(0)
                 if ss == '/':
                     nominator = False
                     continue
                 for p, n in enumerate(OSUnits.name):
                     if n == ss[0:len(n)]:
                         res = OSUnits.xtrnum.findall(ss)  # extract numbers
                         if res:
                             self.power[p] = frac(
                                 res[0]) if nominator else -frac(res[0])
                         else:
                             self.power[p] = frac(
                                 1, 1) if nominator else frac(-1, 1)
                         break
                     elif ss in ['1', '2', '\pi', '2\pi']:
                         break
                 else:
                     raise ValueError('Unknown unit: ' +
                                      re.findall(r'\w+', ss)[0])
def get_I(m):
    I = []
    for i in range(len(m)):
        temp = []
        for j in range(len(m)):
            if j == i:
                temp.append(frac(1))
            else:
                temp.append(frac(0))
        I.append(temp)
    return I
Esempio n. 31
0
def identity_matrix(transit_len):
    I = []

    for r in range(transit_len):
        I.append([])
        for c in range(transit_len):
            if r == c:
                I[r].append(frac(1, 1))
            else:
                I[r].append(frac(0, 1))
    return I
Esempio n. 32
0
def cast_to_probability_matrix(m):
    """Takes the input matrix and casts each row to a probabilistic representation with fractions
    where the total of each row is calculated and each entry in the row represents it's fraction of the total"""
    m_new = []
    for i in range(len(m)):
        row_sum = reduce((lambda x, y: x + y), m[i])
        if row_sum > 0:
            m_new.append(map((lambda x: frac(x, row_sum)), m[i]))
        else:
            m_new.append(map((lambda x: frac(x, 1)), m[i]))

    return matrix(m_new)
Esempio n. 33
0
def displayResult():
    ## Get Constant Vector
  start_time = time.time()
  constant_vector = getConstant(x,y)
  print('The Constant Vector = ',constant_vector)

  # Get value Y from X based on Polynomial Equation
  formula = getFormula(constant_vector)
  print('')
  print(f"Excecution Time: {time.time()-start_time} seconds ")
  test1 = ''.join(formula).replace('(','*(').replace('x','a').replace('c*','c')
  print(' ')

  # expression to be evaluated
  expr = test1
  while True:
      # variable used in expression
      selection = input("Enter '1' for value of X, '2' for location of x, 'f' for skip: ")
      print(selection)
      if selection == '1':
          a = input("Enter the value of x:")
          try:
              if '/' in a:
                a=frac(a)
              else:
                a = int(a)
          except:
              a = frac(a).limit_denominator()
      elif selection == '2':
          loc = float(input("Enter the location of x:"))
          a = findnewX(loc)
          try:
              if '/' in a:
                a=frac(a)
              else:
                a = int(a)
          except:
              a = frac(a).limit_denominator()
      elif selection == 'f':
        break;
      # evaluating expression
      Y = eval(expr)

      print('Y =', Y)

      ans = input("Do you want to test with other value of x or other location of x? y/n : ")
      if ans =='y':
          continue
      else:
          break
Esempio n. 34
0
def eulerphi(d):
    '''return euler's phi for the input'''
    factors=factor(d)
    primes=(f for f in factors if isprime(f)) #generator expression
    invprimes=map(lambda x: frac(x-1,x),primes)
    phi=d*reduce(lambda x,y: x*y,invprimes) #formula from http://en.wikipedia.org/wiki/Euler%27s_totient_function
    return phi
 def b(self, i):
     if i == 1:
         return 1;
     numer = factorial( i-1 ) * factorial(i)
     denom = factorial(2*i-1)
     if (i-1)&1 == 1:
         numer = -numer
     return frac(numer, denom)
def checkio(*data):
    xw1 = frac(data[0][0])
    yw1 = frac(data[0][1])
    xw2 = frac(data[1][0])
    yw2 = frac(data[1][1])
    xa = frac(data[2][0])
    ya = frac(data[2][1])
    xb = frac(data[3][0])
    yb = frac(data[3][1])
    if data[2] == data[3]:
        return -1
 
    #Ax+By+C=0
    dxw, dyw = xw2 - xw1, yw2 - yw1
    awall, bwall, cwall = dyw, -dxw, dxw * yw1 - dyw * xw1
    dxba, dyba = xb - xa, yb - ya
    abull, bbull, cbull = dyba, -dxba, dxba * ya - dyba * xa
    try:
        if bwall:
            x = (bbull * cwall / bwall - cbull) / (abull - bbull * awall / bwall)
            y = -1 * (awall * x + cwall) / bwall
        else:
            x = -1 * cwall / awall
            y = -1 * (abull * x + cbull) / bbull
    except ZeroDivisionError: #parallel
        #check if bullet line and wall line is same
        if bwall and bbull:
            cwall = cwall / bwall
            cbull = cbull / bbull
        else:
            cwall = cwall / awall
            cbull = cbull / abull
        if cwall == cbull:
            if min(xw1, xw2) <= xa <= max(xw1, xw2) and min(yw1, yw2) <= ya <= max(yw1, yw2):
                return True
 
            x, y = xw1, yw1 #shoot in end of wall
        else:
            return -1, None #parallell
        #check if x,y in wall
    mx, my = (xw1 + xw2) / 2, (yw1 + yw2) / 2
    dist = ((mx - x) ** 2 + (my - y) ** 2) ** 0.5
    wdist = ((mx - xw1) ** 2 + (my - yw1) ** 2) ** 0.5
    if min(xw1, xw2) <= x <= max(xw1, xw2) and min(yw1, yw2) <= y <= max(yw1, yw2):
        #check direction
        if min(x, xa) <= xb <= max(x, xa) and min(y, ya) <= yb <= max(y, ya):
            pass
        elif min(xa, xb) <= x <= max(xb, xa) and min(yb, ya) <= y <= max(yb, ya):
            pass
        else:
            return -1, None
    if dist > wdist:
        return -1, [float(x), float(y)]
    else:
        return 100 - round((dist / wdist) * 100), [float(x), float(y)]
Esempio n. 37
0
def solve(n):
 '''
 Solves PE problem 152.
 Finds all representations of 1/2 as the sum of distinct inverse squares with denominator at most n.
 For n = 45, the representations are: {2,3,4,6,7,9,10,20,28,35,36,45} and {2,3,4,6,7,9,12,15,28,30,35,36,45}, {2,3,4,5,7,12,15,20,28,35}
 '''

 excluded_primes = []
 cand_psets = []
  #HACK (sorry about this)
 sets = [5,7,13]
 for s in sets:
  cand_psets.append([])
  for st in find_feasible(n,s):
   if 13 not in st and 11 not in st:
    cand_psets[-1].append(set([s*el for el in st]))
 fdict1 = {}
  
 for set_comb in product(*cand_psets):
   finit = frac(0,1)
   for el in set_comb[0].union(set_comb[1].union(set_comb[2])):
      finit += frac(1,el*el)
   if finit in fdict1:
    fdict1[finit] += 1
   else:
    fdict1[finit] = 1
 total = 0
 rems = list(HarshadGen([2,3],n,exact=False))[2:]
 rems.remove(3)
 rems.remove(64)
 rems.remove(32)
 rems.remove(27)
 rems.remove(2*27)
 sf=frac(1,4)-frac(1,9)
 fracs = [sf]
 for el in rems:
  cfrac = frac(1,el*el)
  tf = []
  for f in fracs:
   t2 = f-cfrac
   if t2 in fdict1:
    total += fdict1[t2]
   tf.append(t2)
  fracs.extend(tf)
 return total 
 def b(self, i):
     """Calculate the b matrix"""
     if i == 1:
         return 1;
     numer = factorial( i-1 ) * factorial(i)
     denom = factorial(2*i-1)
     if (i-1)&1 == 1:
         numer = -numer
     return frac(numer, denom)
Esempio n. 39
0
def sq2(n):
  "Estimate square root of two by continued fractions"
  # Format: [1;(2)]
  base = 1
  repeater = 2
  def helper(n):
    if n==0: return repeater
    return repeater + frac(1, helper(n-1))
  return base + frac(1, helper(n-1))
    def a(self, i, j):
        """Calculate the A[i][j].

        Args:
            i: row number.
            j: column number.
        """
        numer = i * factorial(j+i-1)
        denom = j * factorial(2*i-1) * factorial(j-i)
        return frac(numer, denom)
Esempio n. 41
0
 def f1(k):
     if k == 1:
         return 1
     if cache.get(k):
         return cache.get(k)
     n = frac(1, int(k))
     nx = [str(1), str(k)]
     alist = []
     while True:
         if len(nx) == 1 or nx[1] == 1:
             return int(nx[0])
         else:
             x = nx[0]
             y = nx[1]
         x = int(x) + 1
         y = int(y) - 1
         n = frac(x, y)
         nx = str(n).split("/")
         if nx[0] == "1":
             return f1(nx[1])
    def b(self, i):
        """Calculate the b[i].

        Args:
            i: row number.
        """
        if i == 1:
            return 1;
        numer = factorial( i-1 ) * factorial(i)
        denom = factorial(2*i-1)
        if (i-1)&1 == 1: #just even or odd
            numer = -numer
        return frac(numer, denom)
Esempio n. 43
0
    def intersection(self, other):
        # l1*a + (1-l1) *b = l2 * oa + (1-l2) * ob
        try:

            A = np.array([self.a - self.b, other.b - other.a]).T
            b = other.b - self.b
            d = int(A[0, 0] * A[1, 1] - A[1, 0] * A[0, 1])

            if not d:
                return None

            l1 = int(b[0] * A[1, 1] - b[1] * A[0, 1])
            l2 = int(b[1] * A[0, 0] - b[0] * A[1, 0])
            l1 = frac(l1, d)
            l2 = frac(l2, d)

            if l1 <= 0 or l1 >= 1 or l2 <= 0 or l2 >= 1:
                return None

            return (int(self.a[0] - self.b[0]) * l1 + self.b[0], int(self.a[1] - self.b[1]) * l1 + self.b[1])

        except:
            return None
	def matrix_b(self,i):
		"""Calculate the b(i) of matrix b
		"""
		#For numerator
		numer = (-1)**(i-1)
		for i1 in range(2*i-3, 1, -2):
			numer = numer * i1**2
		#For denominator
		denom = 1
		i2 = (2*i-1)**2
		for i3 in range(2*i-3, -1, -2):
			denom = denom * (i2- i3**2)
		b = frac(numer, denom)
		return b
Esempio n. 45
0
def solve_eq(d):
    x, y = 0, 0
    seq_size = 2
    reduced_sequence = continued_fraction(d)
    while x**2 - d * y ** 2 != 1:
        generalized_sequence = generate_development(reduced_sequence)
        sequence = [generalized_sequence.send(None) for _ in range(seq_size)]
        current = 0
        for i in range(len(sequence) - 1, 0, -1):
            current = frac(1, sequence[i] + current)
        current += sequence[0]
        x = current.numerator
        y = current.denominator
        seq_size += 1
    return x, y
Esempio n. 46
0
File: mm.py Progetto: MaiTiano/zhseg
def fenci(s):
    l = len(s)
    p = [1 for i in range(l + 1)]
    t = [None for i in range(l)]

    for i in range(l - 1, -1, -1):
        p[i], t[i] = max((frac(prob(s[i:i + k]), total) * p[i + k], k)
                          for k in range(1, l - i + 1))
        p[i] = simplify(p[i])

    print 'sum:', p[0]
    i = 0
    while i < l:
        yield s[i:i + t[i]]
        i = i + t[i]
	def matrix_a(self, i, j):
		"""Calculate the a(i,j) of matrix A
		"""
		#For numerator
		numer = 1
		j1 = (2*j-1)**2
		for i1 in range(2*i-3, -1, -2):
			numer = numer * (j1 - i1**2)
		#For denominator
		denom = 1
		i2 = (2*i-1)**2
		for i3 in range(2*i-3, -1, -2):
			denom = denom * (i2- i3**2)
		#print( frac(numer, denom) )
		return frac(numer, denom)
Esempio n. 48
0
def divPoly(N,D):
	N, D = map(frac,trim(N)), map(frac,trim(D))
	degN, degD = len(N)-1, len(D)-1
	if(degN>=degD):
		q=[0]*(degN-degD+1)
		while(degN>=degD and N!=[0]):
			d=list(D)
			[d.insert(0,frac(0,1)) for i in range(degN-degD)]
			q[degN-degD]=N[degN]/d[len(d)-1]
			d=map(lambda x: x*q[degN-degD],d)
			N=subPoly(N,d)
			degN=len(N)-1
		r=N	
	else:
		q=[0]
		r=N
	return [trim(q),trim(r)]
Esempio n. 49
0
def slow_rep_positive(rep):

        a,b,c = int(rep[0]), int(rep[1]), int(rep[2])
        if a == 0:
            if b == 0:
                return c >= 0
            else:
                return r_less(0, frac(c, b))

        d = b*b - 4*a*c
#        print "disc ",d
        #then the polynomial is always positive or negative for r real, with sign given by the leading coefficient
        if d < 0:
            return a >= 0
#        D = frac(d, 4*a*a)
#        C = frac(-b, 2*a)
        r1, r2 = None, None
#        m1 = (D + 3*C*C - 2*C)
        #m1 = frac(d+3*b*b+4*a*b, 4*a*a)
        #m2 = (3*D*C - D + C**3 - C*C - 1)
        #m2 = frac(-3*d*b-2*a*d-b**3-2*a*b*b-8*a**3, 8*a**3)
        m2 = -3*d*b-2*a*d-b**3-2*a*b*b-8*a**3
        m1 = d+3*b*b+4*a*b
        mag_comp = d*m1*m1 >= m2*m2
        if m1 >= 0:
            if m2 >= 0:
                r1 = True
                r2 = not mag_comp
            else:
                r1 = mag_comp
                r2 = False
        else:
            if m2 < 0:
                r1 = False
                r2 = mag_comp
            else:
                r1 = not mag_comp
                r2 = True
        if a > 0:
            return (r1 and r2) or (not r1 and not r2)
        else:
            return (r1 and not r2) or (r2 and not r1)
Esempio n. 50
0
def e(n):
  "Estimate e by continued fractions"
  # Format: [2; 1,2,1, 1,4,1, 1,6,1, ..., 1,2k,1 ...]
  base = 2

  def repeater():
    k=1
    while True:
      yield 1
      yield 2*k
      k+=1
      yield 1

  R = repeater()

  def helper(n, depth=1):
    if n==0: return R.next()
    return R.next() + frac(1, helper(n-1, depth+1))

  if n==0: return base
  return base + frac(1, helper(n-1))
Esempio n. 51
0
def test_ds():
    ref = [[1.0], [1.0]]
    h = frac(1,2)
    ds = cg.CG(h, 0, h)
    assert_cg(ref, ds)
Esempio n. 52
0
def test_sd():
    ref = [[1.0, 1.0]]
    h = frac(1, 2)
    sd = cg.CG(0, h, h)
    assert_cg(ref, sd)
Esempio n. 53
0
__author__ = '보운'

# 20113259 컴퓨터공학부 3학년 김보운
# 알고리즘 과제 - Henry

from fractions import Fraction as frac

with open('input.txt', 'r') as f:
    testCase = int(f.readline())

    for x in range(testCase):
        data = f.readline().split(' ')

        henry = frac(int(data[0]), int(data[1]))

        while henry.numerator > 1:
            henry -= frac(1, int(((henry.denominator - 1) / henry.numerator + 1)))

        print(henry.denominator)
Esempio n. 54
0
def test_score_rest():
    rest = score.Rest(frac(1, 4))
    assert isinstance(rest, score.Rest)
Esempio n. 55
0
def test_score_note():
    note = score.Note("c##", frac(1, 4))
    assert isinstance(note, score.Note)
Esempio n. 56
0
def expandSqrt2(n):
    ls = [frac(3,2)]
    for i in range(1, n):
        ls.append(1+frac(1,1+ls[i-1]))
    return ls
Esempio n. 57
0
def test_dds():
    isq2 = sqrt(0.5)
    ref = [[0.0, -isq2], [isq2, 0.0]]
    h = frac(1, 2)
    dds = cg.CG(h, h, 0)
    assert_cg(ref, dds)
Esempio n. 58
0
def test_ddt():
    isq2 = sqrt(0.5)
    ref = [[1.0, isq2], [isq2, 1.0]]
    h = frac(1,2)
    ddt = cg.CG(h, h, 1)
    assert_cg(ref, ddt)