Jimtuv

Least Common Denominator

Feb 11th, 2012
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.81 KB | None | 0 0
  1. #This program give the least commond denominator
  2. #and equivalent fractions for n number of fractions
  3. #James Tuvell
  4. # This is revision 2.0
  5. # 2-11-12
  6. """
  7. * change log
  8. * adding support for fraction class 2-11-02
  9. * simplifying functions
  10. """
  11.  
  12. import math
  13. import fractions
  14.  
  15.  
  16.  
  17. #========== Begining defs =======================
  18. def is_number(string):
  19.     try:
  20.         float(string)
  21.         return True
  22.     except ValueError:
  23.         print  "This is not a number"          
  24.         return False
  25.        
  26. def is_fraction(string, pattern):
  27.    
  28.     beforeslash = ""
  29.     afterslash = ""
  30.    
  31.     if in_string(string, pattern) != True:
  32.         print "Incorrect format numerator/denominator"
  33.         return False   
  34.     if string.count(pattern) > 1:
  35.         print "To many // in fraction."
  36.         return False
  37.     beforeslash = string[:string.find(pattern)]
  38.     afterslash = string[string.find(pattern)+1:]
  39.     if is_number(beforeslash) == False:
  40.         return False   
  41.     if is_number(afterslash) == False:
  42.         return False
  43.     if beforeslash.count(".") > 0:
  44.         print "do not put decimal in numerator"
  45.         return False
  46.     if afterslash.count(".") > 0:
  47.         print "do not put decimal in denominator"
  48.         return False
  49.     if int(afterslash) == 0:
  50.         print "Zero in denominator error"
  51.         return False
  52.     if int(beforeslash) == 0:
  53.         print "Did you really want a Zero there?"
  54.         print "Oh well wont hurt anything"
  55.         print "letting error slip"
  56.    
  57.     return True
  58.    
  59. def in_string(string, pattern):
  60.     if string.count(pattern) == 0:
  61.         return False
  62.     return True
  63.        
  64. def validator(validation_type = "string", string = "", pattern = ""):
  65.     """Redirects to the validator for each type
  66.         valid types are
  67.        
  68.         "number"
  69.         "string"
  70.         "fraction"
  71.     """
  72.        
  73.     if validation_type == "number":
  74.         return is_number(string)
  75.     if validation_type == "string":
  76.         return in_string(string, pattern)
  77.     if validation_type == "fraction":
  78.         return is_fraction(string, pattern)
  79.     print "Invalid validation type :",validation_type
  80.     return False       
  81.    
  82. def getstring(prompt, maxlength):
  83.    
  84.     emptystring = ""
  85.     try:
  86.         inputstring = raw_input(prompt)
  87.         if len(inputstring) > maxlength:
  88.             print "Too long max size is ",maxlength," characters"
  89.             return emptystring
  90.         return inputstring
  91.     except ValueError:
  92.         print "Invalid input!"
  93.         return emptystring
  94.     except:
  95.          print "This is a unexpected : ",Exception
  96.          print "Thowing out exception"
  97.          return emptystring  
  98.            
  99.    
  100.     return
  101.  
  102. def getfractionlist(prompt, terminator):
  103.    
  104.     doneflag = False
  105.     maxlength = 30
  106.     string = ""
  107.     fractionlist = []
  108.     cfraction = fractions.Fraction(1,1)
  109.    
  110.     while doneflag == False :
  111.         string = ""
  112.         string = getstring(prompt, maxlength)
  113.         if string == terminator:
  114.             return fractionlist
  115.         else:
  116.             validation_type = "fraction"
  117.             pattern = "/"
  118.             if validator(validation_type, string, pattern) == True:
  119.                 cfraction = fractions.Fraction(string)
  120.                 fractionlist.append(cfraction)
  121.             else:
  122.                 doneflag == False  
  123.    
  124.     return fractionlist
  125.    
  126. def dupli(the_list):
  127.    
  128.     donelist=[]
  129.  
  130.     for item in sorted(set(the_list)):
  131.         donelist = donelist + [(item, the_list.count(item)),]
  132.  
  133.     return donelist
  134.  
  135. #  
  136. #  name: primetest
  137. #  @param positive integer
  138. #  @return boolean true or false
  139. #  Test to see if the number is prime
  140. def primetest(num):
  141.     """Test primeness return boolean True or False"""
  142.     prime=True         
  143.    
  144.     if num == 1:       
  145.         prime=False    
  146.         return prime               
  147.     i = 2
  148.     while i <= math.sqrt(num):
  149.         if num % i == 0:       
  150.             prime = False
  151.             break
  152.         i=i+1  
  153.            
  154.     return prime
  155.    
  156. #  
  157. #  name: nextPrime
  158. #  @param positive integer prime number
  159. #  @return next positive prime integer
  160. #  Find the next prime up from the one given
  161. def nextPrime(num):
  162.     """Find next prime from current number"""
  163.     nextone = num + 1
  164.    
  165.     while primetest(nextone) == False:
  166.        
  167.         nextone = nextone + 1
  168.        
  169.     return nextone     
  170.  
  171. #  
  172. #  name: iter_prime
  173. #  @param positive integer
  174. #  @return list of prime integers
  175. #  Create a list of prime factors for the number given
  176. def iter_prime_factors(intnumber):
  177.     """Make a list of prime factors from number [2,2,2,3,3,5]"""
  178.    
  179.     factor_list = []           
  180.     factored_number = intnumber  
  181.    
  182.     if primetest(intnumber) != False:      
  183.         factor_list.append(intnumber)      
  184.     else:
  185.         primefactor = 2                
  186.         while factored_number != 1:    
  187.             while factored_number % primefactor == 0:                              
  188.                 factored_number = factored_number / primefactor            
  189.                 factor_list.append(primefactor)            
  190.             primefactor = nextPrime(primefactor)
  191.            
  192.     return factor_list
  193.    
  194.  
  195. def factor_denominator(denominator_list):
  196.    
  197.     lcd = 1
  198.     prime_factor_list = []
  199.     combinedlist = []
  200.    
  201.     for i in range(len(denominator_list)):
  202.         prime_factor_list.append(iter_prime_factors(denominator_list[i]))
  203.    
  204.     for i in range(len(prime_factor_list)):        
  205.         for item in prime_factor_list[i]:
  206.             if combinedlist.count(item) < prime_factor_list[i].count(item):                
  207.                 combinedlist.append(item)
  208.        
  209.     for item in combinedlist:
  210.         lcd = lcd * item
  211.    
  212.     return lcd 
  213.    
  214.    
  215. def lcd(fractionlist):
  216.    
  217.     lcd = 0
  218.     denomlist =[]
  219.     denominator = 1
  220.    
  221.     for item in fractionlist:
  222.         denominator = item.denominator 
  223.         denomlist.append(denominator)  
  224.    
  225.     lcd = factor_denominator(denomlist)
  226.    
  227.     return lcd
  228.    
  229. def print_equivalent_Fractions(fractionlist, lcd):
  230.    
  231.     formatter = "    %d/%d    ---------->    %d/%d"
  232.    
  233.     print
  234.     print "The least common denominator for this group is :",lcd
  235.     print
  236.     for i in range(0,len(fractionlist)):
  237.         numerator = fractionlist[i].numerator
  238.         denominator = fractionlist[i].denominator
  239.        
  240.         print formatter % (numerator,denominator,numerator*(lcd/denominator),lcd)
  241.  
  242. #========== End of defs =========================
  243.  
  244. prompt = "Enter a fraction or q to quit :"
  245. terminator = "q"
  246. myfraction = fractions.Fraction()
  247. fractionlist =[]
  248.  
  249.  
  250. fractionlist = getfractionlist(prompt,terminator)
  251.  
  252. lcd = lcd(fractionlist)
  253.  
  254. print_equivalent_Fractions(fractionlist, lcd)
  255.  
  256. print "Thank you!"
Advertisement
Add Comment
Please, Sign In to add comment