class TestFraction(unittest.TestCase): f1 = Fraction(5, 6) f2 = Fraction(1, 2) def test_sub(self): self.assertEqual(self.f1 - self.f2, Fraction(1, 3)) def test_add(self): self.assertEqual(self.f1 + self.f2, Fraction(4, 3)) def test_equal(self): f1 = Fraction(1, 2) f2 = Fraction(2, 4) self.assertEqual(f1 == f2, True) def test_mul(self): self.assertEqual(self.f1 * self.f2, Fraction(5, 12)) def test_div(self): self.assertEqual(self.f1 // self.f2, Fraction(5, 3)) def test_ne(self): self.assertEqual(self.f1 != self.f2, True) def test_lt(self): self.assertEqual(self.f1 < self.f2, False) def test_le(self): self.assertEqual(self.f1 <= self.f2, False) def test_gt(self): self.assertEqual(self.f1 > self.f2, True) def test_ge(self): self.assertEqual(self.f1 >= self.f2, True)
def __init__(self, size): self.size = size self.ground_objects = {} self.fraction1 = Fraction("T", 1, 1) self.fraction4 = Fraction("W", 1, self.size) self.fraction3 = Fraction("A", self.size, self.size) self.fraction2 = Fraction("B", self.size, 1)
def main(): fraction_list = [] mixed_fraction_list = [] for line in open('fractions.dat', 'r'): line = Fraction.from_string(line) if line != Fraction(0): fraction_list.append(line) fraction_sum = Fraction(0) for item in fraction_list: fraction_sum += item mixed_sum = MixedFraction(0) for line in open('MixedFractions.dat', 'r'): line = MixedFraction.from_string(line) if line != MixedFraction(0): mixed_fraction_list.append(line) for item in mixed_fraction_list: mixed_sum += item holder = '{:} = {:}'.format( ' + '.join('{:}'.format(f) for f in fraction_list), fraction_sum) print(holder) holder = '{:} = {:}'.format(' + '.join('{:}'.format(f) for f in mixed_fraction_list), mixed_sum) print(holder) mixed_plus = mixed_sum + fraction_sum print(mixed_sum, '+', fraction_sum, '=', mixed_plus, '\n') for item in fraction_list: print(mixed_plus, '-', item, '=', mixed_plus - item) mixed_plus -= item
def resolve_higher_precedence_operations(operations: list) -> list: index = 2 jump_to_operand = 2 #I move in spaces of 2 because the operands are in pair directions as args starts in 1 # maybe can use an additional stack to avoid the cost of the pop intermediate while index < len(operations) - 1: fraction1 = Fraction(operations[index - 1]) fraction2 = Fraction(operations[index + 1]) operand = operations[index] solved = Calculator(fraction1, fraction2) if operand == "*": result = solved.multiplication() operations[index - 1] = result.convert_to_string() operations.pop(index) operations.pop(index) index -= jump_to_operand if operand == "/": result = solved.division() operations[index - 1] = result.convert_to_string() operations.pop(index) operations.pop(index) index -= jump_to_operand index += jump_to_operand return operations
def main(): # Caminho Feliz f1 = Fraction(1, 5) # print(f1.numerador) # 1 # print(f1.numerador == 1) # print(f1.denominador) # 5 # print(f1.denominador == 5) f2 = Fraction(1, 0) print(f2.numerador == 1) print(f2.denominador) # f2.mais(1, 2) # +2/5 # print(f2.numerador == 6) # print(f2.denominador == 8) # f2.mais(f1.numerador, f2.denominador) # print(f2.numerador == 4) # print(f2.denominador == 5) # f3 = Fraction(3, 7) # print(f3.numerador == 3) # print(f3.denominador == 7) # f3.mais(f2.numerador, f2.denominador) # print(f3.numerador==43) # print(f3.denominador == 35) # # # Começando com as alternativas # f4 = Fraction(6) # denominador padrão 1 # print(f4.numerador == 6) # print(f4.denominador == 1) # f5 = Fraction() # numerador padrão 0 # print(f5.numerador == 0) # print(f5.denominador == 1) # # # Fração inválida # # # denominador 0 deve lançar IllegalArgumentException # print("here") # f6 = Fraction(2, 0) # deve quebrar aqui # print(f6.denominador == 0) # não deve chegar aqui # # # comente as linhas após fazer quebrar # # # Operações não suportadas # # # não lidaremos com frações negativas # # # deve lançar UnsupportedOperationException # # #f7 = Fraction(2, -5) # # #f8 = Fraction(-2, 5) # # #f9 = Fraction(-2, -5) # # # comente as linhas após fazer quebrar # # # desafio: especificar e implementar as outras operações (opcional) input('Press ENTER to exit')
def H(n): counter = 1 finalFraction = Fraction(0, 1) for x in range(n): newFraction = Fraction(1, counter) finalFraction = finalFraction + newFraction counter += 1 return finalFraction
def Z(n): fraction1 = Fraction(0, 1) for x in range(n + 1): newFraction = Fraction(1, 2) fraction1 = fraction1 + (newFraction ** x) fraction2 = Fraction(2, 1) finalFraction = fraction2 - fraction1 return finalFraction
def R(n, b): counter = 1 finalFraction = Fraction(0, 1) for x in range(n): newFraction = Fraction(1, counter) newFraction2 = newFraction ** b finalFraction = finalFraction + newFraction2 counter += 1 return finalFraction
def test_calculations(self): self.assertEqual(self.mf1 * self.mf1, Fraction(625, 25)) self.assertEqual(self.mf1 * self.mf1, MixedFraction(625, 25)) self.assertEqual(self.mf1 * self.f0, Fraction(25, 40)) self.assertEqual(self.mf1 * self.f0, MixedFraction(25, 40)) self.assertEqual(self.mf1 / self.mf3, Fraction(50, 75)) self.assertEqual(self.mf1 / self.mf3, MixedFraction(50, 75)) self.assertEqual(self.mf2 / self.f0, Fraction(160, 4)) self.assertEqual(self.mf2 / self.f0, MixedFraction(160, 4))
def ncr(n, r): if n == r: return Fraction.value_of(1) if n == 0: return Fraction.value_of(0) if r == 0: return Fraction.value_of(1) numerator = math.factorial(n) denominator = math.factorial(r) * math.factorial(n - r) return Fraction(numerator, denominator)
class TestFractionMethods(unittest.TestCase): '''Testing class Fraction''' def setUp(self): '''Setting up''' self.frac1 = Fraction(1, 3) self.frac2 = Fraction(4, 6) self.frac3 = Fraction(6, 4) def test_init(self): '''Testing init''' self.assertEqual(self.frac1, Fraction(1, 3)) def test_init_simplification(self): '''Testing init with gcd''' self.assertEqual(self.frac2, Fraction(2, 3)) def test_init_numer_error(self): '''Testing TypeError''' self.assertRaises(TypeError, Fraction, *(1.5, 2)) def test_init_denom_error(self): '''Testing TypeError''' self.assertRaises(TypeError, Fraction, *(1, 2.5)) def test_get_numer(self): '''Testing numerator getter''' self.assertEqual(self.frac1.get_numer(), 1) def test_get_denom(self): '''Testing denominator getter''' self.assertEqual(self.frac1.get_denom(), 3) def test_fractions_add(self): '''Testing __add__ method''' self.assertEqual(self.frac1 + self.frac2, Fraction(1, 1)) def test_fractions_sub(self): '''Testing __sub__ method''' self.assertEqual(self.frac1 - self.frac2, Fraction(-1, 3)) def test_fractions_mult(self): '''Testing __mult__ method''' self.assertEqual(self.frac1 * self.frac2, Fraction(2, 9)) def test_fractions_truediv(self): '''Testing __truediv__ method''' self.assertEqual(self.frac1 / self.frac2, Fraction(1, 2)) def test_str(self): '''Testing __str__method''' with patch('sys.stdout', new=StringIO()) as output: print(self.frac3) self.assertEqual(output.getvalue().strip(), '3/2')
def main(): fractList = [] fractFile = open('Fractions.dat','r') for eachLine in fractFile: top, bottom = eachLine.split('/') fractList += fract f0 = Fraction(2) f1 = Fraction(1, 3) f2 = MixedFraction(12, 3) print(f0, '+', f1, '+', f2, '=', f0 + f1 + f2) f3 = f1 ** 3 print('({})**3 = {}'.format(f1, f3)) print('({})**3 = {}'.format(f2, f2**3))
def cutTop(threshold): maxVotes = 0 for canadite in canadites: if canadite[1] > maxVotes: maxVotes = canadite[1] while maxVotes >= threshold + Fraction(1, 10000): toDistribute = [] for canadite in canadites: if canadite[1] > threshold: amountStaying = threshold / canadite[1] for vote in partyVoters[canadite[0]]: var = vote[1] * amountStaying newVote = [vote[0], vote[1] - var] vote[1] = var canadite[1] -= newVote[1] toDistribute.append(newVote) for item in toDistribute: distributeNewVotes(item[0], item[1]) maxVotes = 0 for canadite in canadites: if canadite[1] > maxVotes: maxVotes = canadite[1] print(canadites)
def removeLowest(): minVotes = -1 for person in canadites: # Need other qualifiers for who to eliminate if the canadites are tied if (minVotes == -1 or person[1] < canadites[minVotes][1]) and person[2]: minVotes = canadites.index(person) canadites[minVotes][2] = False canadites[minVotes][1] = Fraction(0, 1) canaditeCount = 0 for canadite in partyVoters: if canaditeCount != minVotes: for vote in partyVoters[canaditeCount]: emptyList = 0 for rank in vote[0]: pos = 0 for item in rank: if item == minVotes: rank.pop(pos) if len(vote[0][emptyList]) == 0: vote[0].pop(emptyList) pos += 1 emptyList += 1 canaditeCount += 1 for vote in partyVoters[minVotes]: distributeNewVotes(vote[0], vote[1])
def meekSTV(self, numOfSeats): seats = numOfSeats additionalQuota = Fraction(1, 1000) accuracy = Fraction(1, 100) threshold = Fraction(len(self.votes), seats + 1) + additionalQuota candidatesLeft = len(self.candidates) while candidatesLeft > seats + 1: cutTopAgain = True while cutTopAgain: cutTopAgain = False for person in self.candidates: if person.getCount() > threshold + accuracy: cutTopAgain = True if cutTopAgain: self.cutTop(threshold) self.removeLowest() candidatesLeft -= 1 # print("one down") lastRemoval = -1 for person in self.candidates: if person.getAccp() > 0 and ( lastRemoval == -1 or person.getCount() < lastRemoval.getCount()): lastRemoval = person self.output.insert(0, lastRemoval.getIdent()) top = 0 val = 0 selected = [] for person in self.candidates: if person.getCount() >= top and person != lastRemoval: top = person.getCount() val = person selected.append(val.getIdent()) val.finalRemoval() lastRemoval.finalRemoval() if len(selected) == 1: self.output.insert(0, selected[0]) else: self.output.insert(0, selected)
def Ex1(): frac = Fraction(7, 2) print(frac) print(-frac) # выводит -7/2 print(~frac) # выводит 2/7 print(frac**2) # выводит 49/4 print(float(frac)) # выводит 3.5 print(int(frac)) # выводит 3
def bernoulli(n): if n < 0 or n != int(n): raise ValueError if n == 0: return Fraction.value_of(1) if n != 1 and n % 2 != 0: return Fraction.value_of(0) if len(Utilities.bernoullis) > n: return Utilities.bernoullis[n] result = Fraction.value_of(0) for k in range(0, n): result = result.add( Utilities.ncr( n, k).negate().multiply(Utilities.bernoulli(k)).divide( Fraction.value_of(n - k + 1))).simplify() Utilities.bernoullis.append(result) return result
def elimination(): Seats = 5 electionDone = False threshold = Fraction(len(votes), Seats) canaditesLeft = len(canadites) while canaditesLeft > Seats: cutTop(threshold) removeLowest() canaditesLeft -= 1 print(canadites)
def run(self, input, validWinners=None): votes = input i = 0 candidates = [] for tie in input[0].list: for option in tie: candidates.append(Candidate(i)) i += 1 voteCounts = [1] while (len(voteCounts) < len(candidates)): voteCounts.append(0) for vote in votes: curVote = 0 for tie in vote.getList(): toSplit = 0 numOfTie = 0 for vote in tie: if validWinners == None or vote in validWinners: toSplit += voteCounts[curVote] curVote += 1 numOfTie += 1 if numOfTie > 0: amountGiven = Fraction(toSplit, len(tie)) for vote in tie: candidates[vote].addCount(amountGiven) output = [] prev = 100000000000000 for i in candidates: max = -1 maxPer = 0 for candidate in candidates: if candidate.getCount() > max: max = candidate.getCount() maxPer = candidate.getIdent() candidates[maxPer].setCount(-1) if max < prev: output.append(maxPer) else: if isinstance(output[len(output) - 1], int): output[len(output) - 1] = [output[len(output) - 1], maxPer] else: output[len(output) - 1].append(maxPer) prev = max return output
def resolve_lower_precedence_operations(operations: list) -> str: index = 2 jump_to_operand = 2 # I move in spaces of 2 because the operands are in pair directions as args starts in 1 while index < len(operations) - 1: fraction1 = Fraction(operations[index - 1]) fraction2 = Fraction(operations[index + 1]) operand = operations[index] solved = Calculator(fraction1, fraction2) if operand == "+": result = solved.addition() operations[index - 1] = result.convert_to_string() operations.pop(index) operations.pop(index) index -= jump_to_operand if operand == "-": result = solved.subtraction() operations[index - 1] = result.convert_to_string() operations.pop(index) operations.pop(index) index -= jump_to_operand index += jump_to_operand return operations[1]
def __init__(self, voteData, w=None): if isinstance(voteData, list): self.list = voteData if w != None: self.weight = w else: self.weight = Fraction(1, 1) else: self.list = [] for tie in voteData.getList(): newTie = [] for item in tie: newTie.append(item) self.list.append(newTie) self.weight = voteData.weight
def run(self, input): Thisvotes = input i = 0 candidates = [] for tie in input[0].list: for option in tie: candidates.append(Candidate(i)) i += 1 firstVote = len(candidates) - 1 for vote in Thisvotes: curVote = firstVote for tie in vote.getList(): toSplit = 0 for vote in tie: toSplit += curVote curVote -= 1 amountGiven = Fraction(toSplit, len(tie)) for vote in tie: candidates[vote].addCount(amountGiven) output = [] prev = 100000000000000 for i in candidates: max = -1 maxPer = 0 for candidate in candidates: if candidate.getCount() > max: max = candidate.getCount() maxPer = candidate.getIdent() candidates[maxPer].setCount(-1) if max < prev: output.append(maxPer) else: if isinstance(output[len(output) - 1], int): output[len(output) - 1] = [output[len(output) - 1], maxPer] else: output[len(output) - 1].append(maxPer) prev = max return output
def main(): f0 = MixedFraction(18, 9) f1 = MixedFraction(12, 3) f2 = MixedFraction(4, 2) print(f0, '+', f1, '+', f2, '=', f0 + f1 + f2) f0 = MixedFraction(10, 9) f1 = MixedFraction(4, 3) f2 = MixedFraction(3, 2) print(f0, '+', f1, '+', f2, '=', f0 + f1 + f2) f3 = f1**3 print('({})**3 = {}'.format(f1, f3)) print('({})**3 = {}'.format(f2, f2**3)) f5 = Fraction(2, 9) print(f1, '+', f5, '=', f1 + f5) print(f5, '+', f1, '+', f0, '=', f5 + f1 + f0) print(f0, '+', f1, '+', f5, '=', f0 + f1 + f5)
def distributeNewVotes(self, voter): for vote in voter.getList()[0]: newVote = voter.makeCopy() divs = len(newVote.getList()[0]) newVote.getList()[0].pop(newVote.getList()[0].index(vote)) if len(newVote.getList()[0]) == 0: newVote.getList().pop(0) newVote.cutWeight(Fraction(1, divs)) if self.candidates[vote].getAccp() < 1: nextIter = newVote.makeCopy() newVote.cutWeight(self.candidates[vote].getAccp()) nextIter.setWeight(nextIter.getWeight() - newVote.getWeight()) self.distributeNewVotes(nextIter) if newVote.getWeight() > 0: self.candidates[vote].addNewVoter(newVote)
class FractionTests(unittest.TestCase): def setUp(self): self.a = Fraction(2, 3) self.b = Fraction(4, 5) def test_init(self): self.assertEqual(2, self.a._Fraction__nominator) self.assertEqual(3, self.a._Fraction__denominator) def test_eq_not_true(self): self.assertFalse(self.a == self.b) def test_eq_true(self): self.a._Fraction__nominator = 4 self.a._Fraction__denominator = 5 self.assertTrue(self.a == self.b) def test_lt_not_true(self): self.assertFalse(self.b < self.a) def test_lt_true(self): self.assertTrue(self.a < self.b) def test_gt_not_true(self): self.assertFalse(self.a > self.b) def test_gt_true(self): self.assertTrue(self.b > self.a) def test_add(self): fraction = self.a + self.b self.assertEqual("(22, 15)", fraction.__str__()) self.assertEqual("(2, 3)", self.a.__str__()) self.assertEqual("(4, 5)", self.b.__str__()) def test_sub(self): fraction = self.a - self.b self.assertEqual("(-2, 15)", fraction.__str__()) self.assertEqual("(2, 3)", self.a.__str__()) self.assertEqual("(4, 5)", self.b.__str__()) def test_lcm(self): self.assertEqual(15, self.a._Fraction__lcm( self.b._Fraction__denominator)) def test_str(self): self.assertEqual("(2, 3)", self.a.__str__())
class FractionTests(unittest.TestCase): def setUp(self): self.a = Fraction(2, 3) self.b = Fraction(4, 5) def test_init(self): self.assertEqual(2, self.a._Fraction__nominator) self.assertEqual(3, self.a._Fraction__denominator) def test_eq_not_true(self): self.assertFalse(self.a == self.b) def test_eq_true(self): self.a._Fraction__nominator = 4 self.a._Fraction__denominator = 5 self.assertTrue(self.a == self.b) def test_lt_not_true(self): self.assertFalse(self.b < self.a) def test_lt_true(self): self.assertTrue(self.a < self.b) def test_gt_not_true(self): self.assertFalse(self.a > self.b) def test_gt_true(self): self.assertTrue(self.b > self.a) def test_add(self): fraction = self.a + self.b self.assertEqual("(22, 15)", fraction.__str__()) self.assertEqual("(2, 3)", self.a.__str__()) self.assertEqual("(4, 5)", self.b.__str__()) def test_sub(self): fraction = self.a - self.b self.assertEqual("(-2, 15)", fraction.__str__()) self.assertEqual("(2, 3)", self.a.__str__()) self.assertEqual("(4, 5)", self.b.__str__()) def test_lcm(self): self.assertEqual(15, self.a._Fraction__lcm(self.b._Fraction__denominator)) def test_str(self): self.assertEqual("(2, 3)", self.a.__str__())
from Fraction import Fraction import pytest ###validate parsing and simplication ##class with integer part and fractional part that can be simplified sol = Fraction("3_2/4") assert 14, 4 == (sol.numerator, sol.denominator) assert "3_1/2" == sol.convert_to_string() ##simple fraction sol = Fraction("2/4") assert (2, 4) == (sol.numerator, sol.denominator) assert "1/2" == sol.convert_to_string() ##improper fraction that results in just an integer part sol = Fraction("16/4") assert 16, 4 == (sol.numerator, sol.denominator) assert "4" == sol.convert_to_string() ##improper fraction that results in an integer part with a fractional part that can be simplified sol = Fraction("18/8") assert 18, 8 == (sol.numerator, sol.denominator) assert "2_1/4" == sol.convert_to_string() ##integer alone sol = Fraction("6") assert 6, 1 == (sol.numerator, sol.denominator) assert "6" == sol.convert_to_string()
""" Created on: 15-Mar-2018 Created by: Maneesh D """ from Fraction import Fraction f1 = Fraction(-2, 3) f2 = Fraction(7, 6) print("f1 + f2:") print(f1 + f2, "\n") print("f1 - f2:") print(f1 - f2, "\n") print("f1 * f2::") print(f1 * f2, "\n") print("f1 / f2::") print(f1 / f2, "\n") print("f1 // f2::") print(f1 // f2, "\n") print("f1 == f2?") print(f1 == f2, "\n") print("f1 < f2?") print(f1 < f2, "\n")
def setUp(self): self.a = Fraction(2, 3) self.b = Fraction(4, 5)
def test_gcdMethodWorks(self): self.assertEqual(Fraction.gcd(4,8), 4)
print(canadites) from sys import stdin inputFile = open("votes.txt", "r") votes = [] for line in inputFile: vote = line.strip('\n').split(" ") votes.append(vote) i = 0 canadites = [] for vote in votes[0]: canadite = [i, Fraction(0, 1), True] i += 1 canadites.append(canadite) ranks = [] for voter in votes: thisRank = [] added = 0 previous = 0 while added < len(canadites): minChoice = 100000000 for vote in voter: if int(vote) < minChoice and int(vote) > previous: minChoice = int(vote) tied = []
def readFraction(): n = readInt('numerator') d = readInt('denominator') return Fraction(n, d)
from Fraction import Fraction fraction = Fraction(7,2) print(-fraction) #выводит -7/2 print(~fraction) #выводит 2/7 print(fraction ** 2) #выводит 49/4 print(float(fraction)) #выводит 3.5 print(int(fraction)) #выводит 3