Precise fractions pt. 1 - basics
Description:
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).
When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!
Your task is to implement class Fraction
that takes care of simple fraction arithmetics. Requirements:
class must have two-parameter constructor
Fraction(numerator, denominator)
; passed values will be non-zero integers, and may be positive or negative.two conversion methods must be supported:
toDecimal()
returns decimal representation of fractiontoString()
returns string with fractional representation of stored value in format:[ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ]
- Note: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4'
The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors).
Four operations need to be implemented:
add
,subtract
,multiply
anddivide
. Each of them may take integers as well as anotherFraction
instance as an argument, and must return a newFraction
instance.Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument.
Python Notes
- If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction.
- You must implement the standard operator overrides
__add__
,__sub__
,__mul__
,__div__
, in each case you should supportother
being anint
or another instance ofFraction
. - Implement
__str__
andto_decimal
in place oftoString
andtoDecimal
as described above.
Similar Kata:
Stats:
Created | Feb 2, 2015 |
Published | Feb 3, 2015 |
Warriors Trained | 985 |
Total Skips | 512 |
Total Code Submissions | 4241 |
Total Times Completed | 231 |
JavaScript Completions | 57 |
Java Completions | 113 |
Python Completions | 78 |
Total Stars | 26 |
% of votes with a positive feedback rating | 93% of 75 |
Total "Very Satisfied" Votes | 66 |
Total "Somewhat Satisfied" Votes | 7 |
Total "Not Satisfied" Votes | 2 |
Total Rank Assessments | 24 |
Average Assessed Rank | 5 kyu |
Highest Assessed Rank | 3 kyu |
Lowest Assessed Rank | 7 kyu |