예제 #1
0
def inversecalc(l):
    n = len(l[0])
    a = [[0 for temp in range(2 * n)] for temp1 in range(n)]

    for i in range(n):
        for j in range(n):
            a[i][j] = f(l[i][j])
    for i in range(n):
        for j in range(n):
            if i == j:
                a[i][j + n] = f(1, 1)
            else:
                a[i][j + n] = f(0, 1)
    for i in range(n):
        for j in range(n):
            if i != j:
                r = f(a[j][i]) / f(a[i][i])
                for k in range(2 * n):
                    a[j][k] = a[j][k] - r * a[i][k]

    for i in range(n):
        d = a[i][i]
        for j in range(2 * n):
            a[i][j] = a[i][j] / d

    inversematrix = [[] for temp2 in range(n)]
    for i in range(n):
        for j in range(n, 2 * n):
            inversematrix[i].append(a[i][j])
    return inversematrix
예제 #2
0
def my_solution(marbles, step):
    from fractions import Fraction as f

    sequences = [
        [{
            marbles: f(1, 1)
        }],
    ]

    for i in xrange(step):
        curr_step = []

        for seq in sequences[i]:
            k, v = seq.keys()[0], seq.values()[0]

            if 'w' in k:
                new_seq = k.replace('w', 'b', 1)
                curr_step.append({new_seq: f(k.count('w'), len(k)) * v})

            if 'b' in k and i < step - 1:  # Ignore black pearls in last iteration
                new_seq = k.replace('b', 'w', 1)
                curr_step.append({new_seq: f(k.count('b'), len(k)) * v})

        sequences.append(curr_step)

    return round(float(sum(s.values()[0] for s in sequences[-1])), 2)
예제 #3
0
def main():
    # basic numeric data types in python
    print(type(6))
    print(type(6.5))
    print(type(6 + 7j))
    num = 6 + 7j
    print(isinstance(num, complex))
    #operations using binary, octal, hexadecimal
    print(0b100010010)
    print(0b100010010 + 0o15)
    print(0b100010010 + 0xFB)

    #python casting
    print(int(63.7))
    print(float(63))
    print(float('63.26'))

    #using Decimal module to get more precise values
    print(0.1)
    print(d(0.1))
    print(d(202.5624) * d(1235.984316))

    #using fractions module
    print(f('1.1') + f(12, 10))
    print(f(-3, 5) > 0)

    #using math module
    print(math.pi)
    print(math.cos(math.pi))
    print(math.factorial(26))
    print(math.cos(math.pi) + math.sin(math.pi))
 def __init__(self,max_numb,max_depth,grouping,depth = 0):
     """Recursively build an arithematic equation, using only
        the operations given in OPS. Note that the expression is
        given by fractional numbers, and expects a fractional 
        response. However, currently there is an 80% chance 
        of any given fractional number being an integer."""
     if (depth < max_depth and
         random.randint(0,max_depth) > depth):
         self.left = Expression(max_numb,max_depth,
                                grouping,depth + 1)
     else:
         p = random.random()
         if p < .4:
             den = 1
         else:
             den = random.randint(1,max_numb)
         self.left = f(random.randint(1,max_numb),den)
     if (depth < max_depth
         and random.randint(0,max_depth) > depth):
         self.right = Expression(max_numb,
                                 max_depth,grouping,depth + 1)
     else:
         p = random.random()
         if p < .8:
             d = 1
         else:
             d = random.randint(1,max_numb)
         self.right = f(random.randint(1,max_numb),d)
     self.grouped = random.random() < grouping
     self.operator = random.choice(Expression.OPS)
예제 #5
0
def compute_probabilies(m):
    res = [f(0, 1)] * len(m)
    terminal_states = []
    for i, row in enumerate(m):
        if sum(row) == 0:
            # It is a terminal state
            terminal_states.append(i)
            continue

        total = sum(row)
        p_past = []
        for j, element in enumerate(row):
            res[j] = f(element, total)
            if i == 0:
                continue

            if j < i and m[j][i]:
                p_past.append(f(m[j][i], (1 - res[j] * m[j][i])))
                continue

            last = 0
            ii = 0
            while ii < i:
                last += f(m[ii][j], (1 - (res[ii] * m[ii][ii + 1])))
                ii += 1

            res[j] = (res[j] * sum(p_past)) + last

        print('partial res {}: '.format(res[:]))
        m[i] = res[:]

    print(terminal_states)
    return [e for i, e in enumerate(res) if i in terminal_states]
예제 #6
0
def prob(n, k):
    if k == 0:
        return f(1, n + 1)
    elif n == k:
        return f(1, factorial(n + 1))
    else:
        return prob(n - 1, k) * f(n, n + 1) + prob(n - 1, k - 1) * f(1, n + 1)
예제 #7
0
 def calculaX(self, mA, x, j, k):
     if (j == k):
         k -= 1
     if (k < 0):
         return 0
     if (k < j):
         return 0
     return f(mA[j][k]) * f(x[k]) + self.calculaX(mA, x, j, k - 1)
	def calculaX(self, mA,x,j,k):
		if (j == k):
			k -= 1
		if (k < 0):
			return 0	
		if (k < j):
			return 0
		return f(mA[j][k])*f(x[k]) + self.calculaX(mA,x,j,k-1)
예제 #9
0
 def _bin2interval(self, enc):
     a = f(0)
     b = f(1)
     for bit in enc:
         if bit == '0':
             b = (a + b) / 2
         else:
             a = (a + b) / 2
     return a, b
예제 #10
0
def Upper_Triangle_Solver(U, b, n):
    x = np.zeros((n, 1), dtype=int)
    x = x + f()
    for i in range(n - 1, -1, -1):
        rhs = f(b[i], U[i][i])
        for j in range(n - 1, i, -1):
            rhs -= U[i][j] * x[j] / U[i][i]
        x[i] = rhs
    return x
예제 #11
0
파일: PRDRG.py 프로젝트: candyer/codechef
def pre_compute(array):
	d = {1: '1 2', 2: '1 4'}
	tmp = f(1, 4)
	for i in range(2, 25):
		if i % 2 == 0: # new R
			tmp += f(1, pow(2, i + 1))
		else: # new L
			tmp -= f(1, pow(2, i + 1))
		d[i + 1] = ' '.join([str(tmp.numerator), str(tmp.denominator)])
	return d
예제 #12
0
파일: 243.py 프로젝트: sorrowise/euler
def main(a=15499, b=94744):
    fy = lambda n: prod([prime(i) for i in range(1, n + 1)])
    fx = lambda n: prod([prime(i) - 1 for i in range(1, n + 1)])
    n = 1
    while True:
        if f(fy(n), fx(n)) > f(b, a):
            break
        n = n + 1
    k = int(a / (a * fy(n) - b * fx(n))) + 1
    return k * fy(n)
예제 #13
0
def sqrtconvergents(n):
    a0,period = sqrtperiod(n)
    p = len(period)
    yield f(a0,1)
    if p==0:
        return
    for terms in count():
        frac = f(1,period[terms%p])
        for t in range(terms-1,-1,-1):
            frac = f(1,period[t%p]+frac)
        yield a0 + frac
예제 #14
0
    def _decode_len(self, enc, length):
        a, b = self._bin2interval(enc)

        decoded = ""
        u = f(0)
        v = f(1)
        for _ in range(length):
            u, v, c = self._interval2char(u, v, a, b)
            decoded += c

        return decoded
	def calculaXMetodoEliminacao(self):
		self.matrizIncognitas = self.defineMatrizIcognitas()
		c = 0
		k = self.ordem-1
		while c < self.ordem:
			termo = self.calculaX(self.matrizFinal,self.matrizIncognitas[0],k-c,k)
			if (f(self.matrizFinal[k-c][k-c]) == 0):
				self.setErro(1)
				break
			else:
				self.matrizIncognitas[0][k-c] = (f(self.matrizIndependentesFinal[0][k-c]) - f(termo))/f(self.matrizFinal[k-c][k-c])
				c += 1
예제 #16
0
    def _decode_eof(self, enc):
        a, b = self._bin2interval(enc)

        decoded = ""
        u = f(0)
        v = f(1)
        c = None
        while c != '.':
            u, v, c = self._interval2char(u, v, a, b)
            decoded += c

        return decoded
예제 #17
0
    def decode(self, enc):
        a, b = self._bin2interval(enc)
        center = (a + b) / 2

        decoded = ""
        u = f(0)
        v = f(1)
        c = None
        while c != '.':
            u, v, c = self._interval2char(u, v, center)
            decoded += c

        return decoded
예제 #18
0
def is_unique(nominator, denominator):

	common_digit = digits(nominator) & digits(denominator)
	#print common_digit
	if common_digit:
		common_digit = list(common_digit)[0]
		if common_digit > 0:
			new_nominator = eliminate_digit(nominator, common_digit)
			new_denominator = eliminate_digit(denominator, common_digit)
			if new_denominator and f(nominator, denominator) == f(new_nominator, new_denominator):
				#print f(nominator, denominator)
				return True
	return False
예제 #19
0
def compute(i, exp):

    num_1 = ""
    x = i - 2

    # puts together first number

    while (exp[x] in string.digits or exp[x] == "-") and x >= 0:
        num_1 += exp[x]
        x -= 1
    first_ins = x + 1
    num_1 = int(num_1[::-1])
    if exp[x] == "/":
        numer = ""
        x -= 1
        while (exp[x] in string.digits or exp[x] == "-") and x >= 0:
            numer += exp[x]
            x -= 1
        first_ins = x + 1
        numer = numer[::-1]
        num_1 = f(int(numer), int(num_1))

    f_possible = 1
    num_2 = ""
    x = i + 2

    # puts together second number

    while (exp[x] in string.digits or exp[x] == "-") and x < len(exp):
        num_2 += exp[x]
        if x + 1 < len(exp):
            x += 1
        else:
            f_possible = 0
            break
    last_ins = x - 1
    if not f_possible:
        last_ins += 1
    num_2 = int(num_2)
    if exp[x] == "/" and f_possible == 1:
        denom = ""
        x += 1
        while x < len(exp) and (exp[x] in string.digits or exp[x] == "-"):
            denom += exp[x]
            x += 1
        last_ins = x - 1
        num_2 = f(int(num_2), int(denom))
    a = exp[first_ins:last_ins + 1]
    b = str(calc(num_1, exp[i], num_2))
    exp = exp.replace(a, b)
    return (exp)
예제 #20
0
 def calculaXMetodoEliminacao(self):
     self.matrizIncognitas = self.defineMatrizIcognitas()
     c = 0
     k = self.ordem - 1
     while c < self.ordem:
         termo = self.calculaX(self.matrizFinal, self.matrizIncognitas[0],
                               k - c, k)
         if (f(self.matrizFinal[k - c][k - c]) == 0):
             self.setErro(1)
             break
         else:
             self.matrizIncognitas[0][
                 k - c] = (f(self.matrizIndependentesFinal[0][k - c]) -
                           f(termo)) / f(self.matrizFinal[k - c][k - c])
             c += 1
예제 #21
0
    def _f4(self):
        from random import randint as r  # 直接导入randint函数,更名为r
        from random import uniform as ru  # 直接导入uniform函数,更名为ru,用于生成指定范围内的随机浮点数
        from fractions import Fraction as f  # 直接导入fractions函数,更名为f
        ops = ['+', '-', '*', '/']  # 存储操作符
        kuohao = ['(', '', ')']  # 存储括号,下标为0,1,2

        left1 = r(0, 1)
        left2 = r(0, 1)
        left3 = r(0, 1)
        right1 = r(1, 2)
        right2 = r(1, 2)
        right3 = r(1, 2)
        if left1 == 0:
            left2 = 1
            left3 = 1
            if right1 == 2:
                right2 = 1
                right3 = 1
            else:
                right2 = 2
                right3 = 1
        else:
            if left2 == 0:
                left3 = 1
                right1 = 1
                if right2 == 2:
                    right3 = 1
                else:
                    right3 = 2
            else:
                left3 = 0
                right1 = 1
                right2 = 1
                right3 = 2
        add_1 = ru(0, 1)
        add_1 = f(add_1).limit_denominator(10)  # 限制最大分母值,小数变分数
        add_2 = ru(0, 1)
        add_2 = f(add_2).limit_denominator(10)
        add_3 = r(1, 10)
        add_4 = r(1, 10)
        ops1 = r(0, 2)
        ops2 = r(0, 3)
        ops3 = r(0, 3)
        # 由上述操作,随机生成表达式
        eq = kuohao[left1] + str(add_1) + ops[ops1] + kuohao[left2] + str(add_2) + kuohao[right1] + ops[ops2] + kuohao[
            left3] + str(add_3) + kuohao[right2] + ops[ops3] + str(add_4) + kuohao[right3]
        return (eq)
예제 #22
0
def t_NUMBER(t):
    r'-?[0-9]+/[0-9]+|-?[0-9]+'
    parts = re.split('/',t.value)
    if len(parts) == 1:
        parts.append(1)
    t.value = f(*map(int,parts))
    return t
예제 #23
0
def invOfMat(mat):
    t = transpose(mat)
    inverseOfMatrix = []
    for i in range(len(t)):
        list1 = [f(int(i == j), 1) for j in range(len(mat))]
        inverseOfMatrix.append(GE(t, list1))
    return inverseOfMatrix
예제 #24
0
def transform(arr):
    listOfSums = list(map(sum, arr))
    booleanIndices = list(map(lambda x: x == 0, listOfSums))
    indices = set([i for i, x in enumerate(booleanIndices) if x])
    currentMatrix = []
    for i in range(len(arr)):
        currentMatrix.append(
            list(
                map(
                    lambda x: f(0, 1)
                    if (listOfSums[i] == 0) else reduce(x, listOfSums[i]),
                    arr[i])))
    replaceMatrix = []
    replaceZeros = []
    for i in range(len(currentMatrix)):
        if i not in indices:
            replaceMatrix.append(currentMatrix[i])
        else:
            replaceZeros.append(currentMatrix[i])
    replaceMatrix.extend(replaceZeros)
    t = []
    for i in range(len(replaceMatrix)):
        t.append([])
        copyMatrix = []
        for j in range(len(replaceMatrix)):
            if j not in indices:
                t[i].append(replaceMatrix[i][j])
            else:
                copyMatrix.append(replaceMatrix[i][j])
        t[i].extend(copyMatrix)
    return [t, len(replaceZeros)]
예제 #25
0
def retMatrix(mat):
    cmat = []
    for i in range(len(mat)):
        cmat.append([])
        for j in range(len(mat[i])):
            cmat[i].append(f(mat[i][j].numerator, mat[i][j].denominator))
    return cmat
예제 #26
0
def lerMatrix(m):
    file_obj = open("matrix" + m + ".txt")
    matrix = []
    ordem = 0
    matrix_append = matrix.append
    for line in file_obj:
        ordem = ordem + 1
        matrix_append([f(x) for x in line.split() if x])

    file_obj = open("matrixIndependente" + m + ".txt")
    data = []
    data_append = data.append
    for line in file_obj:
        data_append([f(x) for x in line.split() if x])

    return [matrix, data, ordem]
예제 #27
0
def lerMatrix(m):
    file_obj = open("matrix" + m +  ".txt") 
    matrix = [] 
    ordem = 0
    matrix_append = matrix.append 
    for line in file_obj:
      ordem = ordem + 1
      matrix_append([f(x) for x in line.split() if x]) 
   
    file_obj = open("matrixIndependente" + m + ".txt") 
    data = [] 
    data_append = data.append 
    for line in file_obj:
      data_append([f(x) for x in line.split() if x]) 
      
    return [matrix, data, ordem]
예제 #28
0
 def _qr(self, symbol):
     q = f(0)
     for a, p in self.e.tuples():
         if a == symbol:
             r = q + p
             break
         q += p
     return q, r
예제 #29
0
def answer(m):
    probabilities = compute_probabilies(m)
    print(probabilities)
    denominator = reduce(gcd, probabilities)
    print(denominator)
    return [
        (f(p, denominator)).numerator for p in probabilities
    ] + [denominator.denominator]
예제 #30
0
def e033():
    alist = []
    for y in range(1,10):
        for z in range(y,10):
            x=float(9)*y*z/(10*y-z)
            if int(x) == x and y/z < 1 and x<10:
                #print(x, y, z, str(10*y+x)+'/'+str(z+10*x), str(y)+'/'+str(z))
                alist+=[f(y,z)]
    return str(reduce(mul,alist)).split('/')[1]
예제 #31
0
	def calculate_entropy(self, freqs):
		entropy = 0
		total_freq = sum(freqs)
		p = [f(x, total_freq) for x in freqs]
		for i in range(len(p)):
			if p[i] > 0:
				entropy = entropy - p[i]*log2(p[i])

		return entropy
예제 #32
0
def multiplyMatrices(arr1, arr2):
    answer = []
    for x in range(len(arr1)):
        answer.append([])
        for y in range(len(arr2[0])):
            answer[x].append(f(0, 1))
            for z in range(len(arr1[0])):
                answer[x][y] += arr1[x][z] * arr2[z][y]
    return answer
예제 #33
0
def solve():
    s, sg, fg, d, t = map(int, input().split())

    actual = s + f(d * 50 * 60 * 60, t * 1000)

    asg = abs(sg - actual)
    afg = abs(fg - actual)

    return 'SEBI' if asg < afg else 'FATHER' if asg > afg else 'DRAW'
예제 #34
0
def can_simplify( fr ):
    a = str( fr[ 0 ] )
    b = str( fr[ 1 ] )

    if '0' in a and '0' in b:
        return False
    for i in a:
        if b.find( i ) > -1:
            if len( a.replace( i, '' ) ) == 0 \
                or len( b.replace( i, '' ) ) == 0:
                continue
            newa = int( a.replace( i, '' ) )
            newb = int( b.replace( i, '' ) )
            if newb == 0:
                continue
            if f( newa, newb ) == f( fr[ 0 ], fr[ 1 ] ):
                return True
    return False
예제 #35
0
 def dfs():
     probability = f(1)
     visited = [False for i in range(len(l[0]))]
     util(0, visited, probability, recur,
          realprob)  #main cauclation starter
     visited = [False for i in range(len(l[0]))]
     for i in range(len(l[0])):
         visited = [False for j in range(len(l[0]))]
         dfs2(i, i, visited)
예제 #36
0
 def util(start, visited, probability, recur, realprob):
     visited[start] = True
     realprob[start] += probability
     for i in range(len(l[start])):
         if visited[i] == False and l[start][i] != 0:
             recur, realprob = util(
                 i, visited,
                 probability * (f(l[start][i], sumofrow[start])), recur,
                 realprob)
         elif visited[i] == True and l[start][i] != 0:
             if terminalstate[i]:
                 realprob[i] += probability * f(l[start][i],
                                                sumofrow[start])
             else:
                 recur[i] += probability * f(l[start][i], sumofrow[start])
     #print(probability, start)
     #print(recur, realprob)
     return recur, realprob
예제 #37
0
def main():
    lst = [0] * 1000
    lst[0] = f(1, 1)
    num = 0
    for i in range(1, 1000):
        lst[i] = 1 + 1 / (1 + lst[i - 1])
        n_digits = int(log10(lst[i].numerator)) + 1
        d_digits = int(log10(lst[i].denominator)) + 1
        if n_digits > d_digits:
            num += 1
    return num
예제 #38
0
def validate(answer,sol):
    """Validate the users answer (answer) against the solution stored
       in the datastore. Note that since fractional types are not allowed
       in the datastore, it is necessary to parse both the user answer
       and the stored solution. Further, sets are used since order of
       roots (in the case of algebraic expressions) may be arbitrary."""
    solution = set()
    answers = set()
    for s,ans in zip(answer.split(),sol):
        ans = map(int,ans.split('/'))
        s = map(int,s.split('/'))
        if len(s) == 1:
            solution.add(f(s[0],1))
        else:
            solution.add(f(*s))
        if len(ans) == 1:
            answers.add(f(ans[0],1))
        else:
            answers.add(f(*ans))
    return solution == answers
예제 #39
0
파일: rhythmgen.py 프로젝트: qweeze/rbox
def get_values(params):
    '''
    >>> for i in range(100):
    ...        params = get_random();
    ...        length = f(int(params["nBeats"]),int(params["beat"]));
    ...        values = get_values(params);
    ...        length2 = sum([f(i[0],i[1]) for i in zip(values["nums"],values["dens"])]);
    ...        assert(length2 == length);
     
    >>> 
    '''
    length = f(int(params["nBeats"]),int(params["beat"]))
    unevenness = int(params["unevenness"])
    velocity = int(params["velocity"])
    nNotes = int(round(length/min_value*velocity*0.01))
    nBars = int(nNotes/8.)+1
    for i in range(nBars,0,-1):
        if length.numerator % i == 0:
            break
    nBars = i
    barLength = length/nBars
    k = round(unevenness*0.04)+1
    res = []

    bar_1 = get_bar_values(barLength,unevenness,velocity)
    if k == 1:
        for i in range(nBars):
            res.extend(bar_1)
    elif k == 2:
        bar_2 = alter_values(bar_1)
        for i in range(nBars):
            if i % 2:
                res.extend(bar_1)
            else:
                res.extend(bar_2)
    elif k == 3:
        res.extend(bar_1)
        for i in range(nBars-1):
            res.extend(alter_values(bar_1))
    elif k == 4:
        bar_2 = get_bar_values(barLength,unevenness,velocity)
        for i in range(nBars):
            if i % 2:
                res.extend(bar_1)
            else:
                res.extend(bar_2)
    else:
        res.extend(bar_1)
        for i in range(nBars-1):
            res.extend(get_bar_values(barLength,unevenness,velocity))
    rhythm = {}
    rhythm["nums"],rhythm["dens"] = zip(*[(i.numerator,i.denominator) for i in res])
    return rhythm
예제 #40
0
 def get_solution(self,p = .75):
     """Build the solution set. p represents the probability of
        a random root being an integer.  Currently the 
        probability breakdown of a Linear (L), Quadratic (Q) 
        and Cubic (C) equation is given by 
            -L : 20%
            -Q : 70%
            -C : 10%
     """
     x = random.random()
     if x < .2:
         num_roots = 1
     elif .2 < x < .9:
         num_roots = 2
     else:
         num_roots = 3
     roots = set()
     for _ in range(num_roots):
         if random.random() < p:
             den = 1
         else:
             den = random.randint(1,self.number_range[1])
         roots.add(f(random.randint(*self.number_range),den))
     return roots
	def calculaMatrizMetodoEliminacao(self):
		self.matrizFinal = self.defineMatrizFinal()
		self.matrizIndependentesFinal = self.defineMatrizAuxiliar()
		self.matrizIndependentesFinal[0][0] = self.matrizIndependentesFinal[0][0]
		k = self.ordem
		lista = []
		nI = 0
		while k > 0:
			i = self.ordem - k
			den = f(self.matrizFinal[self.ordem-k][self.ordem-k])
			#Verifica elemento e permuta a linha
			if (den == 0):
				if (i == 0):
					self.setErro(1)
					break
				else:
					lista = self.matrizFinal[i+1]
					self.matrizFinal[i+1] = self.matrizFinal[i]
					self.matrizFinal[i] = lista
					nI = self.matrizIndependentesFinal[0][i+1]
					self.matrizIndependentesFinal[0][i+1] = self.matrizIndependentesFinal[0][i]
					self.matrizIndependentesFinal[0][i] = nI
			den = f(self.matrizFinal[self.ordem-k][self.ordem-k])
			if (den == 0):
				self.setErro(1)
				break
			while i+1 < self.ordem:
				contador = 0
				j = self.ordem - k + 1
				num = f(self.matrizFinal[i+1][self.ordem-k])
				divisor = num/den
				while contador < self.ordem:
					if (j > self.ordem):
						break
					self.matrizFinal[i+1][j-1] = f(self.matrizFinal[i+1][j-1]) - f(self.matrizFinal[self.ordem-k][j-1]) * divisor
					j += 1
					contador += 1
				self.matrizIndependentesFinal[0][i+1] = f(self.matrizIndependentesFinal[0][i+1]) - f(self.matrizIndependentesFinal[0][self.ordem-k]) * divisor
				i += 1
			k -= 1
		else:
			self.calculaXMetodoEliminacao()
예제 #42
0
파일: 10288.py 프로젝트: dibery/UVa
from fractions import Fraction as f
import fileinput

ans = [ f() ]
for i in range( 1, 34 ):
    ans += [ ans[ -1 ] + f( 1, i ) ]
ans = [ i * ans[ i ] for i in range( len( ans ) ) ]

def proc( n ):
    if int( n ) == n:
        print( n )
    else:
        i, n, d = str( int( n ) ), str( n.numerator % n.denominator ), str( n.denominator )
        print( ' ' * len( i ) + ' ' + n )
        print( str( i ) + ' ' + '-' * len( d ) )
        print( ' ' * len( i ) + ' ' + d )

for i in fileinput.input():
    proc( ans[ int( i ) ] )
예제 #43
0
def calculaX(mA,x,j,k):
    if (j == k):
        k -= 1
    if (k < 0):
        return 0
    return f(mA[j][k])*f(x[k]) + calculaX(mA,x,j,k-1)
예제 #44
0
from fractions import Fraction as f
import sys

# strange patterns by looking at pythagorean triples

def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
blueqlimit=1000000
xs,ys=[],[]
for m in range(-20,20):
	for n in range(-20,20):
		if (m*m-n*n==0): continue
		if (m == 0 or n == 0): continue
		x = f(redq(0,0,m,n),m+blueq(0,0,m,n))
		y = f(greenq(0,0,m,n),n+blueq(0,0,m,n))
		xs += [x]
		ys += [y]

max=max(xs+ys)

for i in range(0,len(xs)):
	xs[i] = f( xs[i], max )
	ys[i] = f( ys[i], max )

print len(xs), 'points'
import numpy as np
import matplotlib.pylab as plt
fig,ax = plt.subplots(figsize=(8,8))
예제 #45
0
파일: e243.py 프로젝트: gtmanfred/Euler
def test(top=12):
    res = 0
    for x in range(1,top):
        if x == getnumer(f(x,top)):
            res+=1
    return res/(top-1)
예제 #46
0
from fractions import Fraction as f
from fractions import gcd

ans = 0
os = f( 1, 2 )
ot = f( 1, 3 )
for d in xrange( 1, 12001 ):
    for n in xrange( d / 3, d ):
        if f( n, d ) >= os:
            break
        if f( n, d ) <= ot:
            continue
        if gcd( n, d ) == 1:
            ans += 1

print ans
예제 #47
0
파일: fiborec.py 프로젝트: donbright/piliko
	p2 = [cursor.position[0],cursor.position[1]]
	cursor.turnleft()
	cursor.forward(rabbits[-1])
	p3 = [cursor.position[0],cursor.position[1]]
	xs += [p1[0]]
	ys += [p1[1]]
	xs += [p2[0]]
	ys += [p2[1]]
	xs += [p3[0]]
	ys += [p3[1]]
	xs += [p1[0]]
	ys += [p1[1]]

	rabbits+=[rabbits[-1]+rabbits[-2]]

max=max(xs+ys)

for i in range(0,len(xs)):
	xs[i] = f(xs[i], max )
	ys[i] = f(ys[i], max )

print len(xs), 'points'
import numpy as np
import matplotlib.pylab as plt
fig,ax = plt.subplots(figsize=(8,8))
ax.set_ylim([-1.2,1.2])
ax.set_xlim([-1.2,1.2])
#ax.scatter(xs,ys)
ax.plot(xs,ys)
plt.show()
예제 #48
0
	return new_i

def is_unique(nominator, denominator):

	common_digit = digits(nominator) & digits(denominator)
	#print common_digit
	if common_digit:
		common_digit = list(common_digit)[0]
		if common_digit > 0:
			new_nominator = eliminate_digit(nominator, common_digit)
			new_denominator = eliminate_digit(denominator, common_digit)
			if new_denominator and f(nominator, denominator) == f(new_nominator, new_denominator):
				#print f(nominator, denominator)
				return True
	return False



#print is_unique(49, 98)

prod = 1
for i in xrange(10, 100):
	for j in xrange(i+1, 100):
		if is_unique(i, j):
			prod *= f(i, j)

print prod.denominator

				

예제 #49
0
#!/usr/bin/python
#
# problem 57: http://projecteuler.net/problem=57
#

from fractions import Fraction as f

iter = lambda x: f(1,2 + x)

counter = 0
loop_counter = 1

whole = f(1)
frac = f(1,2)
while loop_counter < 10**3:
  loop_counter += 1
  frac = iter(frac)
  num = whole + frac
  if len(str(num.numerator)) > len(str(num.denominator)):
    counter += 1
print '\nAnswer:', counter
예제 #50
0
# note - blue, red, and green quadrance are from Norman Wildberger's 
# Chromogeometry

def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
xs,ys=[],[]
xs2,ys2=[],[]
r=24
for m in range(-r,r):
	for n in range(-r,r):
		if blueq(0,0,m,n)==0: continue
		if blueq(0,0,m,n)+m+n==0: continue
		x = m*f(redq(0,0,m,n),blueq(0,0,m,n))
		y = m*f(greenq(0,0,m,n),blueq(0,0,m,n))
		xs += [x]
		ys += [y]

max=max(xs+ys)

for i in range(0,len(xs)):
	xs[i] = f(xs[i], max )
	ys[i] = f(ys[i], max )

print len(xs), 'points'
import numpy as np
import matplotlib.pylab as plt
fig,ax = plt.subplots(figsize=(8,8))
ax.set_ylim([-1.2,1.2])
예제 #51
0
from fractions import Fraction as f
import sys

# strange patterns by looking at pythagorean triples

def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
blueqlimit=1000000
xs,ys=[],[]
for m in range(-20,20):
	for n in range(-20,20):
		if (m*m-n*n==0): continue
		if (m == 0 or n == 0): continue
		x = f(redq(0,0,m,n),blueq(0,0,m,n)/m)
		y = f(greenq(0,0,m,n),blueq(0,0,m,n)/m)
		xs += [x]
		ys += [y]

max=max(xs+ys)

for i in range(0,len(xs)):
	xs[i] = f( xs[i], max )
	ys[i] = f( ys[i], max )

print len(xs), 'points'
import numpy as np
import matplotlib.pylab as plt
fig,ax = plt.subplots(figsize=(8,8))
예제 #52
0
# -*- coding: utf-8 -*-
#!/bin/python
"""
P=VI
I=P/V

I=V/R
RI=V
R=V/I

R=V/(P/V)
R=V**2/P
"""
from fractions import Fraction as f
import sys

if __name__ == '__main__':
    p = f(sys.argv[1])
    print "%.0fW:" % p
    for vin in range(3, 13):
        i = p/vin
        r = vin/i
        assert r == vin/(p/vin) == (vin**2)/p
        print u"%dV %.2fA %.1fΩ" % (vin, i, r)
예제 #53
0
def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
xs,ys=[],[]
xs2,ys2=[],[]

depth=15
layers=[[]]
for j in range(0,depth):
	layer=layers[j]
	layers+=[[]]
	for i in range(2*j):
		num = i
		denom = 2*j
		layers[j] += [f(num,denom)]
	layers[j+1]+=[f(1,1)]

#for i in layers:
#	print i,'\n'

for layer in layers:
	for t in layer:
		if blueq(0,0,1,t)==0: continue
		x = len(layer)*f(redq(0,0,1,t),blueq(0,0,1,t))
		y = len(layer)*f(greenq(0,0,1,t),blueq(0,0,1,t))
		xs += [x]
		ys += [y]
		xs += [-x]
		ys += [y]
		xs += [-x]
예제 #54
0
from fractions import Fraction as f
from pe_utils import sieve
max_cycle = 1
max_d = 0

primes = sieve(1000)

for d in primes:
	for c in xrange(1, 1000):
		x = f(1, d)
		y = x * (10 ** c) - x
		z = x * (10 ** c)
		if z.denominator == 1: # no cycle
			break
		if y.denominator == 1: # got cycle
			if c > max_cycle:
				max_cycle = c
				max_d = d
			break

print max_d, max_cycle
예제 #55
0
from fractions import Fraction as f

if __name__ == '__main__':
    for _ in xrange(input()):
        n, m = map(int, raw_input().split())
        num = f(m, n) * f(1, 4)
        den = f(n - m, n) * f(2, 9)
        ans = num / (num + den)
        print '%d/%d' % (ans.numerator, ans.denominator)
예제 #56
0
def p_expression_binop(p):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression'''
    if p[2]   == '+': p[0] = p[1] + p[3]
    elif p[2] == '-': p[0] = p[1] - p[3]
    elif p[2] == '*': p[0] = p[1] * p[3]

def p_expression_group(p):
    'expression : LPAREN expression RPAREN'
    p[0] = p[2]

parser = yacc.yacc(debug = 0, optimize = 1,
                   write_tables = 0)

if __name__ == "__main__":
    assert parser.parse("9 - 3/7 + 3/7 + 1") == 10
    assert parser.parse("7 + 3/2 - 3/2") == 7
    assert parser.parse("4 + 4") == 8
    assert parser.parse("3/4 + 4/4") == f(7,4)
    assert parser.parse("2 - 3") == -1
    assert parser.parse("2 * 4") == 8
    assert parser.parse("2 + 4 * 7") == 30
    assert parser.parse("(2 + 3) * 5") == 25
    assert parser.parse("3/4 - 1/4") == f(1,2)
    assert parser.parse("0/4 * 9") == 0




예제 #57
0
def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
xs,ys=[],[]
xs2,ys2=[],[]

depth=30
layers=[[]]
for j in range(0,depth):
	layer=layers[j]
	layers+=[[]]
	for i in range(j):
		num = i
		denom = j
		layers[j] += [f(num,denom)]
#	layers[j+1]+=[f(1,1)]

for i in layers:
	print i,'\n'

for layer in layers:
	for t in layer:
		if greenq(0,0,1,t)==0: continue
		if redq(0,0,1,t)==0: continue
		x = len(layer)*f(greenq(0,0,1,t),redq(0,0,1,t))
		y = len(layer)*f(redq(0,0,1,t),greenq(0,0,1,t))
		xs += [x]
		ys += [y]

max=max(xs+ys)
예제 #58
0
#!/usr/bin/env python

from fractions import Fraction as f

ls = list()
for i in range(0,101):
    if i % 3 == 0:
        ls.append(i/3*2)
    else:
        ls.append(1)

ls[1] = 2
ls1 = ls[1:]

x = f(ls1.pop())
print ls1, len(ls1)
for i in range(0, len(ls1)):
    x = ls1.pop() + 1 / x
    print x
n = x.numerator
print sum(map(int, str(n)))