diff --git a/class05/__init__.py b/class05/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/class05/math/README.md b/class05/math/README.md index 8e0158c..c72e063 100644 --- a/class05/math/README.md +++ b/class05/math/README.md @@ -1,8 +1,10 @@ # Math Practice Test Generator -The python files generate math related practice tests. They are +The python files generate math related practice tests for use at home or in the class room. They are geared towards class 5 students in the CBSE system. The practice tests pertain to: * Practice Mathematics learned in class IV -* Factors, Multiples, LCM, HCF \ No newline at end of file +* Factors, Multiples, LCM, HCF +* Fractions (Simplification, Sorting, Addition, Subtraction, Multiplication, Division,...) +* Decimals (Addition, Subtraction, Multiplication, Division, Percentages, ...) \ No newline at end of file diff --git a/class05/math/__init__.py b/class05/math/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/class05/math/decimals.py b/class05/math/decimals.py new file mode 100644 index 0000000..31369df --- /dev/null +++ b/class05/math/decimals.py @@ -0,0 +1,247 @@ +__author__ = 'Ajay' + +'''Generates questions on fractions''' +'''Usage: python > test.html''' #test.html can be opened in a browser to view the fraction problems +''' Output: Generates a html file, with the questions and answers''' +# references : https://docs.python.org/2/library/decimal.html +# https://docs.python.org/2/library/fractions.html +# http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference + +import random +import logging +import uuid +# from fractions import Fraction +from fractions import Fraction +import decimal +from fraction import printable_fraction, printable_fraction_from_fraction + +questions = [] +answers = [] + +style = r'' +html_pre_context = r' Home Work Problems - Decimals ' + r' ' +\ + style + r' ' +html_post_content = r'' + +'''Generates a fraction ranging from 1...9/2..9''' + +def generate_decimal (integer=999, mantissa=9999): + return decimal.Decimal ('%d.%d' %(random.randint(0, integer), random.randint(0, mantissa))) + +def decimal_to_fraction (number = decimal.Decimal()): + if number == decimal.Decimal(): + number = generate_decimal(0, 999) + number_in_fraction = Fraction(number) + answer = printable_fraction_from_fraction(number_in_fraction) + question = "Convert {} to a fraction. Simplify the fraction, if required.".format(number) + return (question, answer) + +def multiple_decimals_to_fractions (decimal_list = []): + dec_list = [] + if not decimal_list: + i = 0 + if len(decimal_list) <= 4: + dec_list.append (decimal.Decimal(random.randint(1,9)/1000).quantize(decimal.Decimal('0.001'), rounding=decimal.ROUND_DOWN)) + dec_list.append (decimal.Decimal(random.randint(111,999)/1000).quantize(decimal.Decimal('0.001'), rounding=decimal.ROUND_DOWN)) + dec_list.append (decimal.Decimal(random.randint(1,9)/100).quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_DOWN)) + dec_list.append (generate_decimal(0, 9999).quantize(decimal.Decimal('0.001'), rounding=decimal.ROUND_DOWN)) + + decimal_list = dec_list + fraction_list = [] + answer = "" + question = "" + for i in range (0, len (decimal_list)): + fraction_list.append( Fraction(decimal_list[i])) + answer += printable_fraction_from_fraction(fraction_list[i]) + question += " {}".format (decimal_list[i]) + if i != len (decimal_list) -1: + answer += "," + question += "," + question = "Convert the decimals into their equivalent fractions : {}".format (question) + return (question, answer) + +def decimals_sum(): + decimal1 = generate_decimal(0, 99) + decimal2 = generate_decimal(99, 9999) + answer = decimal1 + decimal2 + question = "The sum of {} and {} is __________".format(decimal1, decimal2) + return (question, answer) + +def decimals_mantissa_sum (): + decimal1 = generate_decimal(0, 99) + decimal2 = generate_decimal(0, 9999) + answer = decimal1 + decimal2 + question = "The sum of {} and {} is __________".format(decimal1, decimal2) + return (question, answer) + +def decimals_difference (): + minuend = generate_decimal(99, 99) + subtrahend= generate_decimal(49, 99999) + while (minuend <= subtrahend): + minuend += generate_decimal(10, 9) + question = "The difference between {} and {} is __________".format(minuend, subtrahend) + answer = minuend - subtrahend + return (question, answer) + +def sort_decimals (decimals_list = [], ascending=True): + list = [] + if not decimals_list: + i = 0 + while len (list) < 4: + dec = generate_decimal(1, 9999) + if dec not in list: + list.append(dec) + i+=1 + else: + list = decimals_list + logging.info ("Decimals to be sorted: {}".format(list)) + sorted_decimals_list = sorted(list) + if ascending is not True: + sorted_decimals_list.reverse() + question_sub_text = "" + for i in range (0, len(list)): + question_sub_text += str(list[i]) + if i != len (list)-1: + question_sub_text += ',' + if ascending is True: + order = "ascending" + else: + order = "descending" + question = 'Arrange the decimals {} in {} order'.format (question_sub_text, order ) + logging.info (question) + answer = "" + for i in range (0, len(list)): + answer += str(sorted_decimals_list[i]) + if i != len (list)-1: + answer += ',' + logging.info (answer) + logging.info (sorted_decimals_list) + return (question, answer) + +def sort_decimals_descending (fractions_list = [], ascending=False): + return sort_decimals(fractions_list, ascending) + + +def decimals_multiplication (number1=decimal.Decimal(), number2=decimal.Decimal()): + if number1 == decimal.Decimal() or number2 == decimal.Decimal(): + number1 = generate_decimal(9,99) + number2 = generate_decimal(999,9999) + answer = number1 * number2 + question = "The product of {} and {} is _____. ".format (number1,number2) + return (question, answer) + +def decimals_integers_multiplication (number1=decimal.Decimal(), number2=0): + if number1 == decimal.Decimal() or number2 == 0: + number1 = generate_decimal(0,99) + number2 = random.randint (5,50) + answer = number1 * number2 + question = "{} x {} = ______".format (number1, number2) + return (question, answer) + + +def decimals_division (number1=decimal.Decimal(), number2=decimal.Decimal()): + if number1 == decimal.Decimal() or number2 == decimal.Decimal(): + number1 = generate_decimal(99,9999) + number2 = generate_decimal(9,99) + current_precision = decimal.getcontext().prec + decimal.getcontext().prec = 6 + answer = number1 / number2 + decimal.getcontext().prec = current_precision + question = "Divide {} by {}. Stop the division at 4 places after decimal point.".format (number1, number2) + return (question, answer) + +def decimals_integers_division (number1=decimal.Decimal(), number2=0): + if number1 == decimal.Decimal() or number2 == 0: + number1 = generate_decimal(4,99) + number2 = random.randint (4,9) + original_precision = decimal.getcontext().prec + decimal.getcontext().prec=5 + answer = number1 / number2 + decimal.getcontext().prec = original_precision + question = "{} divided by {} = ______".format (number1, number2) + return (question, answer) + +def integers_decimals_division (number1=0, number2= decimal.Decimal()): + if number1 == 0 or number2 == decimal.Decimal(): + number1 = random.randint (19, 300) + number2 = generate_decimal(9,9) + original_precision = decimal.getcontext().prec + decimal.getcontext().prec=4 + answer = number1 / number2 + decimal.getcontext().prec = original_precision + question = "{} divided by {} = ______".format (number1, number2) + return (question, answer) + + +def percentage_of_whole_numbers (percentage=0, whole_number=0): + if percentage == 0 or whole_number == 0: + percentage = random.randint (2,15)*5 + whole_number = random.randint (2,19) * 5 + answer = whole_number * percentage / 100 + question = "{}% of {} is _______.".format (percentage, whole_number) + return (question, answer) + +def decimal_as_percentage (number1=decimal.Decimal()): + if number1 == decimal.Decimal(): + number1 = generate_decimal(0, 999) + answer = number1 * 100 + answer = float(answer) + question = "{} can be expressed as ____%.".format (number1) + return (question, answer) + +def fraction_as_percentage (number = Fraction ()): + if number == Fraction(): + possible_denominators = [2, 5, 10, 20, 25, 50] + selection = random.randint (0, len (possible_denominators)-1) + denominator = possible_denominators[selection] + numerator = random.randint(2, 15) + while (numerator == denominator and numerator % denominator != 0): + numerator = random.randint (2, 15) + number = Fraction(numerator, denominator) + logging.info ("{} {} {}".format (selection, denominator, printable_fraction_from_fraction(number))) + question = "Express fraction {} as a percentage.".format (printable_fraction_from_fraction(number)) + original_precision = decimal.getcontext().prec + decimal.getcontext().prec = 2 + answer = number.numerator * 100/number.denominator + answer = "{} %".format (answer) + decimal.getcontext().prec = original_precision + return (question, answer) + + +functions = [decimals_sum, decimals_mantissa_sum, decimals_difference, sort_decimals, sort_decimals_descending, decimals_multiplication, \ + decimals_division, decimal_to_fraction, multiple_decimals_to_fractions, decimals_integers_multiplication, decimals_integers_division,\ + integers_decimals_division,percentage_of_whole_numbers, decimal_as_percentage, fraction_as_percentage] + + +def main(): + logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y%m%d %I:%M:%S %p', + filename='class.log', level=logging.INFO) + unique_id = uuid.uuid1(1) + + for i in range(0, len(functions)): + logging.info('Function : %s' % functions[i]) + f = functions[i] + question, answer = f() + questions.append(question) + answers.append(answer) + html_text = "

Decimals & Percentages

\n" + html_text += "

Questions: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (questions[i]) + html_text += html + html_text += r'
' + html_text += r'

' + html_text += "

Answer Key: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (answers[i]) + html_text += html + html_text += r'
' + print ("{} {} {}".format(html_pre_context, html_text, html_post_content)) + + +if __name__ == "__main__": + main() diff --git a/class05/math/factors.py b/class05/math/factors.py index c32e0d7..ceb3a99 100644 --- a/class05/math/factors.py +++ b/class05/math/factors.py @@ -38,7 +38,9 @@ def nearest_primes(): higher_prime = i answer = "Lower prime: {}, Higher prime: {}".format(lower_prime, higher_prime) answers.append(answer) - print("The prime numbers that are just before and after {} are _____ and _____.".format(number)) + question = "The prime numbers that are just before and after {} are _____ and _____.".format(number) + print (question) + return (question, answer) def list_primes(): @@ -49,7 +51,9 @@ def list_primes(): if _is_prime(i) == True: answer.append(i) answers.append(answer) - print("The prime numbers between {} and {} are ________".format(number, number + range_size)) + question = "The prime numbers between {} and {} are ________".format(number, number + range_size) + print (question) + return (question, answer) def twin_primes(): @@ -61,7 +65,9 @@ def twin_primes(): else: answer = "The numbers are not twin primes." answers.append(answer) - print("{} and {} are twin primes. Yes or No?".format(first_prime, first_prime + 2)) + question = "{} and {} are twin primes. Yes or No?".format(first_prime, first_prime + 2) + print (question) + return (question, answer) def factors(number=0): @@ -80,11 +86,8 @@ def factors(number=0): return (factors) # for unit testing -def all_factors(number=0): +def _all_factors(number=0): """Retrieves all the prime factors of a number, even the duplicate prime factors""" - if (number <= 0): - number = random.randint(50, 999) - input = number factor_list = [] if _is_prime(number): factor_list.append(number) @@ -97,10 +100,16 @@ def all_factors(number=0): number //= n n = 1 n = n + 1 + return (factor_list) + +def all_factors (number = 0): + if (number <= 0): + number = random.randint(50, 999) + factor_list = _all_factors (number) question = "___" for i in range(0, len(factor_list) - 1): question = "{} X ___ ".format(question) - question = "{} = {}, where each number is a prime number".format(question, input) + question = "{} = {}, where each number is a prime number".format(question, number) print(question) answers.append(factor_list) return (factor_list) @@ -189,10 +198,18 @@ def _least_common_multiple(number_list=[]): number_list.append(random.randint(11, 50)) greatest = max(number_list) while (True): - if (greatest % number_list[0] == 0) and (greatest % number_list[1] == 0) and (greatest % number_list[2] == 0): + divisible = True + for i in range (0, list_length): + if greatest % number_list[i] == 0: + divisible = divisible and True + else: + greatest += 1 + divisible = False + break #out of for loop + if divisible == True: lcm = greatest break - greatest += 1 + return (number_list, lcm) @@ -252,7 +269,11 @@ def march_past (team_size=[]): if len (team_size) != 2 or 0 in team_size: people_per_row = random.randint(5,9) for i in range (0,2): - team_size.append(people_per_row * random.randint(4,8)) + people = people_per_row * random.randint(4,8) + if i == 1: #ensure that both teams do not have the same number of people + while (people == team_size[0]): + people = people_per_row * random.randint(4,8) + team_size.append(people) print ("Two gymnastic teams are marching at an event. There are {} members on one team and {} on the other"\ .format (team_size[0], team_size[1]), "They are marching in rows of equal size that are as wide as possible.",\ "How many people are in each row?") @@ -273,8 +294,8 @@ def building_age (age_this_year=0): age_last_year = age_this_year - 1 logging.info ("Age this year = {}".format(age_this_year)) - factors_age_this_year = all_factors(age_this_year) - factors_age_last_year = all_factors (age_last_year) + factors_age_this_year = _all_factors(age_this_year) + factors_age_last_year = _all_factors (age_last_year) logging.info ("Factors: {} {}".format (factors_age_this_year, factors_age_last_year)) number_list, lcm = _least_common_multiple([age_this_year, age_last_year]) age_range = random.randint (5, 10) @@ -375,13 +396,15 @@ def main(): # random.seed (os.urandom(5)) for i in range(0, len(functions)): logging.info('Function : %s' % functions[i]) + print ("{i}) ".format(i=i+1), end="") f = functions[i] f() + logging.info ('Answer : %s' % answers[i]) print () print("Answer Key # {}".format(str(unique_id))) - for i in range(0, len(answers)): + for i in range(0, len (functions)): #len(answers)): print(i + 1, answers[i]) #primes = [ _is_prime(x) for x in range (100)] #print (primes) diff --git a/class05/math/fraction.py b/class05/math/fraction.py index 66f8ce4..6d7f1c5 100644 --- a/class05/math/fraction.py +++ b/class05/math/fraction.py @@ -1,66 +1,217 @@ __author__ = 'Ajay' '''Generates questions on fractions''' -'''Usage: python ''' +'''Usage: python > test.html''' #test.html can be opened in a browser to view the fraction problems ''' Output: Generates a html file, with the questions and answers''' +# references : https://docs.python.org/2/library/fractions.html +# http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference import random import logging +import uuid # from fractions import Fraction from fractions import Fraction + questions = [] answers = [] +style = r'' html_pre_context = r' Quiz on fractions ' + r' ' + r'}' + r'})'+ r' ' +\ + style + r' ' html_post_content = r'' +'''Generates a fraction ranging from 1...9/1..9''' +def __generate_fraction (): + f = Fraction(random.randint(1,9),random.randint(2,9) ) + while f.denominator == 1: #eliminates fractions with a denominator of 1frfr + f = Fraction(random.randint(1,9),random.randint(2,9) ) + return f + +def __generate_mixed_fraction (): + frac = __generate_fraction() + while frac.denominator == 1: + frac = __generate_fraction() + return frac + random.randint (1,9) + +'''input: numerator and denominator + output: a string, that appears as a fraction in LaTeX format + ''' +def printable_fraction (numerator: int, denominator: int): + printable = "$\\frac {" + str(numerator) +"}{" + str(denominator) + "}$" + return printable + +'''Takes a Fraction data structure''' +def printable_fraction_from_fraction (fraction: Fraction): + return printable_fraction(fraction.numerator, fraction.denominator) + +def printable_mixed_fraction (fraction: Fraction): + if fraction.numerator <= fraction.denominator: + return printable_fraction_from_fraction(fraction) + else: + whole_number = fraction.numerator // fraction.denominator + fraction = fraction - whole_number + printable = "${}".format(whole_number) +"\\frac {" + str(fraction.numerator) +"}{" + str(fraction.denominator) + "}$" + return printable + def fractions_sum(): fraction1_numerator = random.randint(1, 9) - fraction1_denominator = random.randint(1, 9) + fraction1_numerator + fraction1_denominator = random.randint(2, 9) + fraction1_numerator fraction2_numerator = random.randint(1, 9) - fraction2_denominator = random.randint(1, 9) + fraction2_numerator + fraction2_denominator = random.randint(2, 9) + fraction2_numerator answer = Fraction(fraction1_numerator, fraction1_denominator) + Fraction(fraction2_numerator, fraction2_denominator) - #answers.append (answer) - question = "The sum of {} and {}/{} is __________".format(r'$\frac {2}{9}$', - fraction2_numerator, fraction2_denominator) + question = "The sum of {} and {} is __________".format(printable_fraction(fraction1_numerator, fraction1_denominator), + printable_fraction(fraction2_numerator, fraction2_denominator)) + answer = printable_fraction (answer.numerator, answer.denominator) + return (question, answer) + +def fractions_difference (): + subtrahend= Fraction (random.randint(1, 9), random.randint(2,9)) + difference = Fraction (random.randint(1, 9),random.randint(2, 5)) + minuend = subtrahend + difference + question = "The difference between {} and {} is __________".format(printable_fraction_from_fraction(minuend), + printable_fraction_from_fraction(subtrahend)) + answer = minuend - subtrahend + answer = printable_fraction (answer.numerator, answer.denominator) return (question, answer) -functions = [fractions_sum] + +def sort_unlike_fractions (fractions_list = [], ascending=True): + list = [] + if not fractions_list: + i = 0 + while len (list) < 4: + frac = __generate_fraction() + if frac not in list: + list.append(frac) + i+=1 + else: + list = fractions_list + logging.info ("Fractions to be sorted: {}".format(list)) + sorted_fraction_list = sorted(list) + if ascending is not True: + sorted_fraction_list.reverse() + question_sub_text = "" + for i in range (0, len(list)): + question_sub_text += printable_fraction_from_fraction(list[i]) + if i != len (list)-1: + question_sub_text += ',' + if ascending is True: + order = "ascending" + else: + order = "descending" + question = 'Arrange the fractions {} in {} order'.format (question_sub_text, order ) + logging.info (question) + answer = "" + for i in range (0, len(list)): + answer += printable_fraction_from_fraction(sorted_fraction_list[i]) + if i != len (list)-1: + answer += ',' + logging.info (answer) + logging.info (sorted_fraction_list) + + return (question, answer) + +def sort_unlike_fractions_descending (fractions_list = [], ascending=False): + return sort_unlike_fractions(fractions_list, ascending) + +def mixed_fractions_sum (number1=Fraction(), number2=Fraction()): + if number1 == Fraction() or number2 == Fraction(): + number1 = __generate_mixed_fraction() + number2 = __generate_mixed_fraction() + answer = number1 + number2 + #logging.info (number1, number2, answer) + question = "The sum of {} and {} is _____. Convert any improper fraction into a mixed fraction.".format (printable_mixed_fraction(number1), printable_mixed_fraction(number2)) + return (question, printable_mixed_fraction(answer)) + +def mixed_fractions_difference (number1=Fraction(), number2=Fraction()): + if number1 == Fraction() or number2 == Fraction(): + number1 = __generate_mixed_fraction() + number2 = __generate_mixed_fraction() + while number2 >= number1: + number2 = __generate_mixed_fraction() + answer = number1 - number2 + #logging.info (number1, number2, answer) + question = "The difference of {} and {} is _____. Convert any improper fraction into a mixed fraction.".format (printable_mixed_fraction(number1), printable_mixed_fraction(number2)) + return (question, printable_mixed_fraction(answer)) + +def mixed_fractions_multiplication (number1=Fraction(), number2=Fraction()): + if number1 == Fraction() or number2 == Fraction(): + number1 = __generate_mixed_fraction() + number2 = __generate_fraction() + answer = number1 * number2 + question = "The product of {} and {} is _____. Convert any improper fraction into a mixed fraction.".format (printable_mixed_fraction(number1), printable_fraction_from_fraction(number2)) + return (question, printable_mixed_fraction(answer)) + +def fractions_division (number1=Fraction(), number2=Fraction()): + if number1 == Fraction() or number2 == Fraction(): + number1 = __generate_fraction() + number2 = __generate_fraction() + + answer = number1 / number2 + question = "Divide {} by {}. Convert any improper fraction into a mixed fraction.".format (printable_fraction_from_fraction(number1), printable_fraction_from_fraction(number2)) + return (question, printable_mixed_fraction(answer)) + +def fractions_division_by_whole_number (number1=Fraction(), number2=0): + if number1 == Fraction() or number2 == 0: + number1 = __generate_fraction() + number2 = random.randint (3,9) + answer = number1 / number2 + question = "Divide {} by {}.".format (printable_fraction_from_fraction(number1), number2) + return (question, printable_fraction_from_fraction(answer)) + +def whole_number_by_fractions_division (number1=0, number2=Fraction()): + if number2 == Fraction() or number1 == 0: + number2 = __generate_fraction() + number1 = random.randint (3,9) + answer = number1 / number2 + question = "Divide {} by {}.".format (number1, printable_fraction_from_fraction(number2)) + return (question, printable_fraction_from_fraction(answer)) + +def mixed_fractions_division (number1=Fraction(), number2=Fraction()): + if number1 == Fraction() or number2 == Fraction(): + number1 = __generate_mixed_fraction() + number2 = __generate_mixed_fraction() + answer = number1 / number2 + question = "Divide {} by {}. Convert any improper fraction into a mixed fraction.".format (printable_mixed_fraction(number1), printable_mixed_fraction(number2)) + return (question, printable_mixed_fraction(answer)) + + +functions = [fractions_sum, fractions_difference, sort_unlike_fractions, sort_unlike_fractions_descending, mixed_fractions_sum, \ + mixed_fractions_difference, mixed_fractions_multiplication,fractions_division, fractions_division_by_whole_number, \ + whole_number_by_fractions_division, mixed_fractions_division] def main(): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y%m%d %I:%M:%S %p', filename='class.log', level=logging.INFO) - #random.seed (os.urandom(5)) + unique_id = uuid.uuid1(1) + for i in range(0, len(functions)): logging.info('Function : %s' % functions[i]) f = functions[i] question, answer = f() questions.append(question) answers.append(answer) - - - html_text = r'
    ' + html_text = "

    Fractions

    \n" + html_text += "

    Questions: {}

    \n".format(str(unique_id)[:8]) + html_text += r'
      ' for i in range(0, len(questions)): - html = "
    1. {} is {}
    2. ".format (question, r'$\frac {2}{9}$') + html = "
    3. {}
    4. \n".format (questions[i]) html_text += html - - #print(answer) - #html_text += r'$\frac {2}{9}$' - html_text += r'
' + html_text += r'' + html_text += r'

' + html_text += "

Answer Key: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (answers[i]) + html_text += html + html_text += r'
' print ("{} {} {}".format(html_pre_context, html_text, html_post_content)) - #primes = [ _is_prime(x) for x in range (100)] - #print (primes) - #for i in squat (): - # print (i) - - #for i in range (100, 500): - # print (i, all_factors(i)) if __name__ == "__main__": diff --git a/class05/math/money.py b/class05/math/money.py new file mode 100644 index 0000000..b0c36f2 --- /dev/null +++ b/class05/math/money.py @@ -0,0 +1,156 @@ +__author__ = 'Ajay' + +'''Generates questions on money''' +'''Usage: python > test.html''' #test.html can be opened in a browser to view the fraction problems +''' Output: Generates a html file, with the questions and answers''' +# references : https://docs.python.org/2/library/decimal.html +# https://docs.python.org/2/library/fractions.html +# http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference + +import random +import logging +import uuid +# from fractions import Fraction +from fractions import Fraction +import decimal +from fraction import printable_fraction, printable_fraction_from_fraction +import datetime + +questions = [] +answers = [] + +style = r'' +html_pre_context = r' Home Work Problems - Money ' + r' ' +\ + style + r' ' +today = datetime.date.today() +today = today.strftime("%B %d, %Y") + + + +html_post_content = r'' + +names = ['Rahul', 'Gaurav', 'Rama', 'Utkarsh', 'Govind', 'Akash', 'Anand'] +items = ['soap', 'chocolate', 'ice-cream', 'pant', 'eraser', 'orange'] + +def __get_name (): + i = random.randint(0, len(names)-1) + return names[i] + +def __get_item (): + return items[random.randint(0, len(items)-1)] + +'''returns soaps, if soap is provided to it, ie, returns the plural form''' +def __get_plural (item:str): + if item: + return "{}s".format (item) + +def purchase_costs_input_costs_selling_price (cost_price=0, input_costs=0, selling_price=0): + if not cost_price or not input_costs or not selling_price: + cost_price = random.randint (4000, 5000) + input_costs = random.randint (500, 900) + selling_price = cost_price + input_costs + random.randint (-500, 1500) + answer = selling_price - (cost_price + input_costs) + item = __get_plural(__get_item()) + question = "Some quantity of {} was bought for Rs {}. Rs {} was spent on transportation. The items were sold for Rs {}. What was the profit or loss? Indicate if it was a profit or loss."\ + .format (item, cost_price, input_costs, selling_price) + return (question, answer) + +def cost_input_loss (cost_price=0, input_costs=0, loss=0): + if cost_price == 0 or input_costs ==0 or loss ==0: + cost_price = random.randint (800,850) + input_costs = random.randint (100, 150) + loss = random.randint (200, 300) + answer = cost_price + input_costs - loss + question = "{} were bought for Rs {}. Packing charges were Rs {}. Loss incurred was Rs {}. What was the selling price?".format (__get_plural(__get_item()).title(), \ + cost_price, input_costs, loss) + return (question, answer) + +def selling_price_profit (selling_price=0, profit = 0): + if selling_price == 0 or profit ==0: + selling_price = random.randint (8000, 11000) + profit = random.randint (800, 1100) + answer = selling_price - profit + question = "A set of {items} was sold for Rs {sp} at a profit of Rs {profit}. What was its cost price?".format (items=__get_plural(__get_item()), sp=selling_price, profit=profit) + return (question, answer) + +def bulk_purchase_with_unit_loss (bulk_purchase_price = 0, units = 0, unit_loss = 0): + if bulk_purchase_price == 0 or units == 0 or unit_loss == 0: + units = random.randint (31, 55) + bulk_purchase_price = units * random.randint (31, 55) + unit_loss = random.randint (5, 11) + answer = bulk_purchase_price - unit_loss * units + question = "A wholesaler purchases {} kg of sugar for Rs {} and sells each kilogram of sugar at a loss of Rs {}. Calculate the amount, he would get at the end of the sale."\ + .format (units, bulk_purchase_price, unit_loss) + return (question, answer) + +def bulk_purchase_with_unit_profit (bulk_purchase_price = 0, units = 0, unit_profit = 0): + if bulk_purchase_price == 0 or units == 0 or unit_profit == 0: + units = random.randint (31, 55) + bulk_purchase_price = units * random.randint (31, 55) + unit_profit = random.randint (5, 11) + answer = bulk_purchase_price + unit_profit * units + question = "A wholesaler purchases {} kg of sugar for Rs {} and sells each kilogram of sugar at a profit of Rs {}. Calculate the amount, he would get at the end of the sale."\ + .format (units, bulk_purchase_price, unit_profit) + return (question, answer) + +def unit_profit_on_bulk_sale (bulk_purchase_price=0, bulk_sale_price = 0, units = 0): + if (bulk_purchase_price == 0 or bulk_sale_price == 0 or units == 0): + units = random.randint (12, 19) + unit_cost_price = random.randint (6, 14) + unit_sale_price = unit_cost_price + random.randint (2,6) + bulk_purchase_price = unit_cost_price * units + bulk_sale_price = unit_sale_price * units + answer = (bulk_sale_price - bulk_purchase_price)/units + question = "{} units of {} were bought for Rs {} and sold for Rs {}. Find the profit or loss per unit?".format (units, __get_plural(__get_item()), bulk_purchase_price, bulk_sale_price) + return (question, answer) + +def aggregate_cost_on_unit_sale (unit_sale_price = 0, unit_profit = 0, units = 0): + if unit_sale_price == 0 or unit_profit == 0 or units == 0: + units = random.randint (12,19) + unit_profit = random.randint (4, 9) + unit_sale_price = unit_profit + random.randint (21,29) + item = __get_item() + unit_cost_price = unit_sale_price - unit_profit + aggregate_cost = unit_cost_price * units + question = "{units} {items} were sold for Rs {unit_sale_price} each at a profit of Rs {unit_profit} per item. What was the total cost price for these {items}?"\ + .format (units=units, items = __get_plural(item), unit_sale_price=unit_sale_price, unit_profit=unit_profit) + return (question, aggregate_cost) + + +functions = [purchase_costs_input_costs_selling_price, cost_input_loss, selling_price_profit, bulk_purchase_with_unit_loss, bulk_purchase_with_unit_profit, \ + unit_profit_on_bulk_sale, aggregate_cost_on_unit_sale] + + +def main(): + logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y%m%d %I:%M:%S %p', + filename='class.log', level=logging.INFO) + unique_id = uuid.uuid1(1) + + for i in range(0, len(functions)): + logging.info('Function : %s' % functions[i]) + f = functions[i] + question, answer = f() + questions.append(question) + answers.append(answer) + html_text = "

Money

\n" + html_text += today + html_text += "

Questions: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (questions[i]) + html_text += html + html_text += r'
' + html_text += r'

' + html_text += "

Answer Key: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (answers[i]) + html_text += html + html_text += r'
' + print ("{} {} {}".format(html_pre_context, html_text, html_post_content)) + + +if __name__ == "__main__": + main() diff --git a/class05/math/simplification_of_numerical_expressions.py b/class05/math/simplification_of_numerical_expressions.py new file mode 100644 index 0000000..bb507ba --- /dev/null +++ b/class05/math/simplification_of_numerical_expressions.py @@ -0,0 +1,263 @@ +__author__ = 'Ajay' + +'''Generates questions on money''' +'''Usage: python > test.html''' #test.html can be opened in a browser to view the fraction problems +''' Output: Generates a html file, with the questions and answers''' +# references : https://docs.python.org/2/library/decimal.html +# https://docs.python.org/2/library/fractions.html +# http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference + +import random +import logging +import uuid +import datetime +import re +from factors import is_prime +from decimals import * +from fraction import __generate_fraction,__generate_mixed_fraction, printable_fraction_from_fraction, printable_mixed_fraction +from fractions import Fraction + +chapter = r'Simplification of Numerical Expressions' + +questions = [] +answers = [] + +style = r'' +html_pre_context = r' Home Work Problems - {} ' + r' ' +\ + style + r' '.format (chapter) +today = datetime.date.today() +today = today.strftime("%B %d, %Y") + +html_post_content = r'' + +division_sign = '÷'#u'\N{DIVISION SIGN}' +multiplication_sign = '×'#u'\N{MULTIPLICATION SIGN}' + +def __generate_random_number (min=2, max=25): + number = random.randint (min, max) + while is_prime(number): + number = random.randint (min, max) + return number + +def __generate_operations (num_operations = 4): #num_operations = number of arithmetic operators present in the equation + operations = ["+", "-", "*", "/"] + ops_list = [] #the list of operations to be performed and the order in which they are to be performed + for i in range (0, num_operations): + if i > 0: + if ops_list[i-1] == "/": #eliminates consecutive divisions + ops_list.append (operations[random.randint(0, len(operations)-2)]) + else: + ops_list.append (operations[random.randint(0, len(operations)-1)]) + else: + ops_list.append (operations[random.randint(0, len(operations)-1)]) + return ops_list + +def __generate_expression (numbers_list, ops_list): + if numbers_list == None or len (numbers_list) == 0 or ops_list == None or len (ops_list) == 0: + logging.info ("Invalid parameters passed to function.") + return False + expression = "" + for i in range (0, len (numbers_list)): + expression += "{}".format (numbers_list[i]) + if i <= len (numbers_list) -2: + expression += " {} ".format (ops_list[i]) + return expression + +def __printable_expression (expression:str): #replaces "/" and "*" by the appropriate mathematical signs, using unicode + expression = re.sub ("/", division_sign, expression) + expression = re.sub ("\*", multiplication_sign, expression) + return expression + +def __printable_expression_fractions (fraction_list, ops_list): + if fraction_list == None or len (fraction_list) == 0 or ops_list == None or len (ops_list) == 0: + logging.info ("Invalid parameters passed to function.") + return False + expression = "" + for i in range (0, len (fraction_list)): + if fraction_list[i].numerator > fraction_list[i].denominator: + expression += "{}".format (printable_mixed_fraction(fraction_list[i])) + else: + expression += "{}".format (printable_fraction_from_fraction(fraction_list[i])) + if i <= len (fraction_list) -2: + expression += " {} ".format (ops_list[i]) + return expression + + +def __factors(number=0): + if number <= 0: + number = random.randint(50, 500) + factors = [] + n = 1 + while (n <= number): + if (number % n == 0): + factors.append(n) + # factors.append (number / n) + n += 1 + return (factors[1:-1]) # for unit testing + + + +def bodmas_integers (expression = None, num_operations = 5): + numbers_list = [] + if expression == None: + ops_list = __generate_operations(num_operations) + for i in range (0, num_operations + 1): + if i == 0: + numbers_list.append(__generate_random_number(50, 100)) + elif i < len (ops_list) and ops_list[i] == "/" and ops_list[i]:#ensures that there are no prime numbers before a / sign. Else the divisors are either the number or 1. + numbers_list.append( __generate_random_number(50, 200)) + + else: + if ops_list[i-1] == "/": + + factor_list = __factors (numbers_list[i-1]) + logging.info ("i : {}, numbers_list : {}, factor_list: {}".format (i, numbers_list,factor_list)) + divisor = factor_list[random.randint(0, len(factor_list)-1)] + numbers_list.append(divisor) + else: + numbers_list.append(__generate_random_number()) + #Both numbers and operators are available. Construct the mathematical expression + expression = __generate_expression (numbers_list, ops_list) + answer = eval (expression) + question = __printable_expression(expression) + return (question, answer) + +def bodmas_decimals (expression = None, num_operations = 4): + numbers_list = [] + multiplier = 1 + if expression == None: + ops_list = __generate_operations(num_operations) + for i in range (0, num_operations + 1): + if i == 0: + numbers_list.append(generate_decimal (2, 99)) + elif i < len (ops_list) and ops_list[i] == "/" and ops_list[i]:#ensures that there are no prime numbers before a / sign. Else the divisors are either the number or 1. + multiplier = random.randint (5,9) + numbers_list.append(generate_decimal (2, 99) * multiplier) + else: + if ops_list[i-1] == "/": + orig = decimal.getcontext().prec + decimal.getcontext().prec = 3 + divisor = numbers_list[i-1]/multiplier + decimal.getcontext().prec = orig + numbers_list.append(divisor) + else: + numbers_list.append(generate_decimal (0, 9)) + #Both numbers and operators are available. Construct the mathematical expression + expression = __generate_expression (numbers_list, ops_list) + orig = decimal.getcontext().prec + decimal.getcontext().prec = 3 + answer = round (eval (expression), 3) + decimal.getcontext().prec = orig + question = __printable_expression(expression) + return (question, answer) + + +def bodmas_fractions (expression = None, num_operations = 4):#TODO: expression passed as input is ignored. Add support for inputs, passed as strings + numbers_list = [] + if expression == None: + ops_list = __generate_operations(num_operations) + for i in range (0, num_operations + 1): + numbers_list.append(__generate_fraction ()) + #Both numbers and operators are available. Construct the mathematical expression + expression = __printable_expression(__printable_expression_fractions (numbers_list, ops_list)) + answer = bodmas_fractions_solver(numbers_list, ops_list) + question = expression + return (question, answer) + +'''This function is similar to the built-in eval, but this provides the answer for fractions +This function is called by the bodmas_fractions function. +''' +def bodmas_fractions_solver (fraction_list, operations_list): + if not operations_list or not fraction_list or len (operations_list) == 0 or len (fraction_list) == 0 or \ + len (operations_list) + 1 != len(fraction_list): + return False + ans = Fraction () + #pass 1, solve division problems + while "/" in operations_list: + pos = operations_list.index ("/") + ans = fraction_list[pos] / fraction_list[pos+1] + fraction_list[pos] = ans + operations_list.remove("/") + fraction_list.remove(fraction_list[pos+1]) + while "*" in operations_list: #pass 2, all multiplication operations are done + pos = operations_list.index ("*") + ans = fraction_list[pos] * fraction_list[pos+1] + fraction_list[pos] = ans + operations_list.remove("*") + fraction_list.remove(fraction_list[pos+1]) + while "+" in operations_list: #pass 3 for addition operations + pos = operations_list.index ("+") + ans = fraction_list[pos] + fraction_list[pos+1] + fraction_list[pos] = ans + operations_list.remove("+") + fraction_list.remove(fraction_list[pos+1]) + while "-" in operations_list: #pass 4 for subtraction + pos = operations_list.index ("-") + ans = fraction_list[pos] - fraction_list[pos+1] + fraction_list[pos] = ans + operations_list.remove("-") + fraction_list.remove(fraction_list[pos+1]) + return ans + + + +def bodmas_mixed_fractions (num_operations = 3): + numbers_list = [] + expression = None + if expression == None: + ops_list = __generate_operations(num_operations) + for i in range (0, num_operations + 1): + numbers_list.append(__generate_mixed_fraction ()) + #Both numbers and operators are available. Construct the mathematical expression + expression = __printable_expression(__printable_expression_fractions (numbers_list, ops_list)) + answer = bodmas_fractions_solver(numbers_list, ops_list) + question = expression + return (question, answer) + + + +functions = [bodmas_integers, bodmas_decimals, bodmas_fractions, bodmas_mixed_fractions] + + +def main(): + logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y%m%d %I:%M:%S %p', + filename='class.log', level=logging.INFO) + unique_id = uuid.uuid1(1) + + f_list = [Fraction (200, 2),Fraction (1,4),Fraction (2,3),Fraction (1,3),Fraction (2,3)] + ops_list = ["/", "*", "+", "-"] + bodmas_fractions_solver(f_list, ops_list) + + num_problems = 0 + while num_problems < 20: + for i in range(0, len(functions)): + logging.info('Function : %s' % functions[i]) + f = functions[i] + question, answer = f() + if answer > 0 and answer < 5000: + questions.append(question) + answers.append(answer) + num_problems += 1 + + html_text = "

{}

\n".format(chapter) + html_text += today + html_text += "

Questions: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (questions[i]) + html_text += html + html_text += r'
' + html_text += r'

' + html_text += "

Answer Key: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (answers[i]) + html_text += html + html_text += r'
' + print ("{} {} {}".format(html_pre_context, html_text, html_post_content)) + + +if __name__ == "__main__": + main() diff --git a/class05/math/temperature.py b/class05/math/temperature.py new file mode 100644 index 0000000..412f4ca --- /dev/null +++ b/class05/math/temperature.py @@ -0,0 +1,95 @@ +__author__ = 'Ajay' + +'''Generates questions on money''' +'''Usage: python > test.html''' #test.html can be opened in a browser to view the fraction problems +''' Output: Generates a html file, with the questions and answers''' +# references : https://docs.python.org/2/library/decimal.html +# https://docs.python.org/2/library/fractions.html +# http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference + +import random +import logging +import uuid +import datetime + +chapter = r'Temperature' + +questions = [] +answers = [] + +style = r'' +html_pre_context = r' Home Work Problems - {} ' + r' ' +\ + style + r' '.format (chapter) +today = datetime.date.today() +today = today.strftime("%B %d, %Y") + + + +html_post_content = r'' + + +def __get_random_temperature_in_fahrenheit (): + return random.randint (32, 212) + +def __get_random_temperature_in_celsius (): + return random.randint (1, 100) + +celsius = lambda fahrenheit : (fahrenheit - 32) * 5/9 + +fahrenheit = lambda celsius: (9/5)* celsius + 32 + +def celsius_from_fahrenheit (temperature = None ): + if temperature == None: + temperature = __get_random_temperature_in_fahrenheit() + answer = "{}{}C".format (round (celsius (temperature), 1), u'\N{DEGREE SIGN}') + question = "Convert {}{}F into Celsius.".format(temperature, u'\N{DEGREE SIGN}') + return (question, answer) + +def fahrenheit_from_celsius (temperature = None): + if temperature == None: + temperature = __get_random_temperature_in_celsius() + answer = "{}{}F".format (round (fahrenheit (temperature), 1), u'\N{DEGREE SIGN}') + question = "Convert {}{}C into Fahrenheit.".format(temperature, u'\N{DEGREE SIGN}') + return (question, answer) + + + + + +functions = [celsius_from_fahrenheit, fahrenheit_from_celsius] + + +def main(): + logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y%m%d %I:%M:%S %p', + filename='class.log', level=logging.INFO) + unique_id = uuid.uuid1(1) + + for i in range (0, 4): + for i in range(0, len(functions)): + logging.info('Function : %s' % functions[i]) + f = functions[i] + question, answer = f() + questions.append(question) + answers.append(answer) + html_text = "

{}

\n".format(chapter) + html_text += today + html_text += "

Questions: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (questions[i]) + html_text += html + html_text += r'
' + html_text += r'

' + html_text += "

Answer Key: {}

\n".format(str(unique_id)[:8]) + html_text += r'
    ' + for i in range(0, len(questions)): + html = "
  1. {}
  2. \n".format (answers[i]) + html_text += html + html_text += r'
' + print ("{} {} {}".format(html_pre_context, html_text, html_post_content)) + + +if __name__ == "__main__": + main() diff --git a/class05/math/tests/test_decimals.py b/class05/math/tests/test_decimals.py new file mode 100644 index 0000000..0c297df --- /dev/null +++ b/class05/math/tests/test_decimals.py @@ -0,0 +1,91 @@ +# ..\tests>python test_fraction.py + +import unittest +from unittest import TestCase +__author__ = 'Ajay' +import sys +from decimal import ROUND_HALF_UP, Decimal + +sys.path.append('..\\') +from decimals import * + + +class TestDecimals(TestCase): + + def test_sort_decimals(self): + question, answer = sort_decimals ([decimal.Decimal('1.3014'),decimal.Decimal('0.9286'),decimal.Decimal('1.1868'), decimal.Decimal('0.9887')]) + self.assertEqual(r'0.9286,0.9887,1.1868,1.3014', answer) + question, answer = sort_decimals ([decimal.Decimal('1.3573'),decimal.Decimal('0.237'),decimal.Decimal('.1087'), decimal.Decimal('.1673')]) + self.assertEqual(r'0.1087,0.1673,0.237,1.3573', answer) + + def test_sort_decimals_descending (self): + question, answer = sort_decimals_descending ([decimal.Decimal('1.5322'),decimal.Decimal('0.3238'),decimal.Decimal('0.160'),decimal.Decimal('1.9656')]) + self.assertEqual(r'1.9656,1.5322,0.3238,0.160', answer) + question, answer = sort_decimals_descending ([decimal.Decimal('0.2400'),decimal.Decimal('0.3625'),decimal.Decimal('0.4785'),decimal.Decimal('1.6537')]) + self.assertEqual(r'1.6537,0.4785,0.3625,0.2400', answer) + + def test_decimals_multiplication (self): + __, answer = decimals_multiplication (decimal.Decimal('2.60'), decimal.Decimal('251.647')) + self.assertEqual(decimal.Decimal('654.28220'), answer) + + def test_decimals_division (self): + __, answer = decimals_division (decimal.Decimal('22.7665'), decimal.Decimal('8.79')) + self.assertEqual(decimal.Decimal('2.59005'), answer) + __, answer = decimals_division (decimal.Decimal('14.6643'), decimal.Decimal('3.87')) + self.assertEqual(decimal.Decimal('3.78922'), answer) + + def test_decimal_to_fraction (self): + __, answer = decimal_to_fraction (decimal.Decimal('0.009')) + self.assertEqual (r'$\frac {9}{1000}$', answer) + __, answer = decimal_to_fraction (decimal.Decimal('0.039')) + self.assertEqual (r'$\frac {39}{1000}$', answer) + __, answer = decimal_to_fraction (decimal.Decimal('0.39')) + self.assertEqual (r'$\frac {39}{100}$', answer) + __, answer = decimal_to_fraction (decimal.Decimal('3.9')) + self.assertEqual (r'$\frac {39}{10}$', answer) + + def test_multiple_decimals_to_fractions (self): + __, answer = multiple_decimals_to_fractions ([decimal.Decimal('0.008'), decimal.Decimal('0.945'), decimal.Decimal('0.01'), decimal.Decimal('0.831')]) + self.assertEqual(r'$\frac {1}{125}$,$\frac {189}{200}$,$\frac {1}{100}$,$\frac {831}{1000}$', answer) + __, answer = multiple_decimals_to_fractions ([decimal.Decimal('0.004'), decimal.Decimal('0.326'), decimal.Decimal('0.02'), decimal.Decimal('0.144')]) + self.assertEqual(r'$\frac {1}{250}$,$\frac {163}{500}$,$\frac {1}{50}$,$\frac {18}{125}$', answer) + + def test_decimals_integers_multiplication (self): + __, answer = decimals_integers_multiplication (decimal.Decimal('0.75'), 36) + self.assertEqual(decimal.Decimal('27.00'), answer) + + def test_decimals_integers_division (self): + __, answer = decimals_integers_division (decimal.Decimal('3.39'), 8) + self.assertEqual(decimal.Decimal('0.42375'), answer) + __, answer = decimals_integers_division (decimal.Decimal('0.26'), 5) + self.assertEqual(decimal.Decimal('0.052'), answer) + + def test_integers_decimals_division (self): + __, answer = integers_decimals_division (81, decimal.Decimal('0.4')) + self.assertEqual(decimal.Decimal('202.5'), answer) + __, answer = integers_decimals_division (171, decimal.Decimal('1.9')) + self.assertEqual(decimal.Decimal('90'), answer) + + def test_percentage_of_whole_numbers (self): + __, answer = percentage_of_whole_numbers (70, 55) + self.assertEqual(38.5, answer) + + def test_decimal_as_percentage (self): + __, answer = decimal_as_percentage (decimal.Decimal('0.948')) + self.assertEqual(94.8, answer) + + def test_fraction_as_percentage (self): + __, answer = fraction_as_percentage (Fraction (11, 25)) + self.assertEqual(str(44.0) + " %", answer) + __, answer = fraction_as_percentage (Fraction (13, 25)) + self.assertEqual(str (52.0) + " %", answer) + + + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/class05/math/tests/test_factors.py b/class05/math/tests/test_factors.py index 4853ed0..acaeede 100644 --- a/class05/math/tests/test_factors.py +++ b/class05/math/tests/test_factors.py @@ -1,6 +1,10 @@ +import unittest from unittest import TestCase +import sys __author__ = 'Ajay' + +sys.path.append ('..\\') from factors import * @@ -26,6 +30,8 @@ def test_factors(self): self.assertEqual(1440, least_common_multiple([45,32,16])) self.assertEqual(5208, least_common_multiple([31,24,14])) self.assertEqual(46512, least_common_multiple([323,272,153])) + self.assertEqual(1260, least_common_multiple([4,5,7,9])) + self.assertEqual(26180, least_common_multiple([4,5,7,11,17])) self.assertEqual((1530, 34), lcm_and_hcf([306, 170, 170])) self.assertEqual((6930, 9), lcm_and_hcf([90, 126, 99])) self.assertEqual(12, pole_spacing([60,36,84])) @@ -39,3 +45,6 @@ def test_factors(self): self.assertEqual((60, [5,4]), students_running_circles([12, 15])) self.assertEqual((7, [3,5,7] ), journey_time_minimum_hours([21, 35, 49])) self.assertEqual((2, [3,4,5]), journey_time_minimum_hours([6, 8, 10])) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/class05/math/tests/test_fraction.py b/class05/math/tests/test_fraction.py new file mode 100644 index 0000000..2be23a3 --- /dev/null +++ b/class05/math/tests/test_fraction.py @@ -0,0 +1,97 @@ +# ..\tests>python test_fraction.py + +import unittest +from unittest import TestCase +__author__ = 'Ajay' +import sys + +sys.path.append('..\\') +from fraction import * + + +class TestFraction(TestCase): + def test_printable_fraction(self): + self.assertEqual(r'$\frac {2}{3}$', printable_fraction(2, 3)) + self.assertEqual(r'$\frac {12}{3}$', printable_fraction(12, 3)) + self.assertEqual(r'$\frac {2}{403}$', printable_fraction(2, 403)) + + def test_printable_fraction_from_fraction (self): + self.assertEqual(r'$\frac {2}{403}$', printable_fraction_from_fraction(Fraction(2, 403))) + + def test_sort_unlike_fractions(self): + question, answer = sort_unlike_fractions ([Fraction(1,2), Fraction (3,4), Fraction (2,3), Fraction (15,16)]) + self.assertEqual(r'$\frac {1}{2}$,$\frac {2}{3}$,$\frac {3}{4}$,$\frac {15}{16}$', answer) + question, answer = sort_unlike_fractions ([Fraction(1,2), Fraction (3,4), Fraction (2,3), Fraction (15,16)], ascending=False) + self.assertEqual(r'$\frac {15}{16}$,$\frac {3}{4}$,$\frac {2}{3}$,$\frac {1}{2}$', answer) + + def test_fractions_sum (self): + self.assertEqual(3, 2+1) + pass + + def test_mixed_fraction_sum (self): + number1 = Fraction(25,3) + number2 = Fraction (33,4) + question, answer = mixed_fractions_sum(number1, number2) + self.assertEqual(r'$16\frac {7}{12}$', answer ) + number1 = Fraction (25,3) + number2 = Fraction (47,5) + question, answer = mixed_fractions_sum(number1, number2) + self.assertEqual(r'$17\frac {11}{15}$', answer ) + + def test_mixed_fraction_difference (self): + number1 = Fraction(77,9) + number2 = Fraction (43,7) + question, answer = mixed_fractions_difference(number1, number2) + self.assertEqual(r'$2\frac {26}{63}$', answer ) + number1 = Fraction (23,6) + number2 = Fraction (7,3) + question, answer = mixed_fractions_difference(number1, number2) + self.assertEqual(r'$1\frac {1}{2}$', answer ) + + def test_mixed_fraction_multiplication (self): + number1 = Fraction(65,8) + number2 = Fraction (2,1) + question, answer = mixed_fractions_multiplication(number1, number2) + self.assertEqual(r'$16\frac {1}{4}$', answer ) + number1 = Fraction (29,3) + number2 = Fraction (1,6) + question, answer = mixed_fractions_multiplication(number1, number2) + self.assertEqual(r'$1\frac {11}{18}$', answer ) + + def test_fractions_division (self): + number1 = Fraction(8,7) + number2 = Fraction (9,8) + question, answer = fractions_division(number1, number2) + self.assertEqual(r'$1\frac {1}{63}$', answer ) + number1 = Fraction (2,1) + number2 = Fraction (7,9) + question, answer = fractions_division(number1, number2) + self.assertEqual(r'$2\frac {4}{7}$', answer ) + + def test_fractions_division_by_whole_number (self): + number1 = Fraction(1,1) + number2 = 4 + question, answer = fractions_division_by_whole_number(number1, number2) + self.assertEqual(r'$\frac {1}{4}$', answer ) + number1 = Fraction (2,1) + number2 = Fraction (9) + question, answer = fractions_division_by_whole_number(number1, number2) + self.assertEqual(r'$\frac {2}{9}$', answer ) + + def test_whole_number_by_fractions_division (self): + question, answer = whole_number_by_fractions_division (5, Fraction (5,2)) + self.assertEqual(r'$\frac {2}{1}$', answer ) + question, answer = whole_number_by_fractions_division (3, Fraction (5,9)) + self.assertEqual(r'$\frac {27}{5}$', answer ) + + def test_mixed_fractions_division (self): + question, answer = mixed_fractions_division (Fraction(16,3), Fraction (7,2)) + self.assertEqual(r'$1\frac {11}{21}$', answer ) + question, answer = mixed_fractions_division (Fraction(17,4), Fraction (5,2)) + self.assertEqual(r'$1\frac {7}{10}$', answer ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/class05/math/tests/test_money.py b/class05/math/tests/test_money.py new file mode 100644 index 0000000..88b328b --- /dev/null +++ b/class05/math/tests/test_money.py @@ -0,0 +1,47 @@ +# ..\tests>python test_fraction.py + +import unittest +from unittest import TestCase +__author__ = 'Ajay' +import sys +from decimal import ROUND_HALF_UP, Decimal + +sys.path.append('..\\') +from money import * + + +class TestMoney(TestCase): + + def test_purchase_costs_input_costs_selling_price(self): + question, answer = purchase_costs_input_costs_selling_price (4864, 964, 7398) + self.assertEqual(1570, answer) + + def test_cost_input_loss (self): + question, answer = cost_input_loss (840, 160, 150) + self.assertEqual(850, answer) + + def test_selling_price_profit (self): + q, a = selling_price_profit (9104, 1051) + self.assertEqual(8053, a) + + def test_bulk_purchase_with_unit_loss (self): + q, a = bulk_purchase_with_unit_loss (1344, 48, 2) + self.assertEqual(1248, a) + q, a = bulk_purchase_with_unit_loss (1295, 37, 9) + self.assertEqual(962, a) + + def test_bulk_purchase_with_unit_profit (self): + q, a = bulk_purchase_with_unit_profit (1872, 36, 11) + self.assertEqual(2268, a) + + def test_unit_profit_on_bulk_sale (self): + q, a = unit_profit_on_bulk_sale (162, 216, 18) + self.assertEqual(3.0, a) + + def test_aggregate_cost_on_unit_sale (self): + q, a = aggregate_cost_on_unit_sale (35, 7, 15) + self.assertEqual(420, a) + + +if __name__ == '__main__': + unittest.main() diff --git a/class05/math/tests/test_simplification_of_numerical_expressions.py b/class05/math/tests/test_simplification_of_numerical_expressions.py new file mode 100644 index 0000000..f5937af --- /dev/null +++ b/class05/math/tests/test_simplification_of_numerical_expressions.py @@ -0,0 +1,38 @@ +# ..\tests>python test_fraction.py + +import unittest +from unittest import TestCase +__author__ = 'Ajay' +import sys + +sys.path.append('..\\') +from simplification_of_numerical_expressions import * + + +class TestSimplification(TestCase): + + def test_bodmas_integers(self): + question, answer = bodmas_integers ("72 + 22 / 22 * 5 + 6 + 13") + self.assertEqual(96.0, answer) + question, answer = bodmas_integers ("92 - 15 * 15 - 6 / 2 * 14") + self.assertEqual(-175, answer) + + def test_bodmas_decimals (self): + question, answer = bodmas_decimals ("0.14 * 11.90 / 1.70 * 0.7 - 0.2") + self.assertEqual(0.486, answer) + question, answer = bodmas_decimals ("0.43 + 0.2 * 0.4 + 0.6 * 0.2") + self.assertEqual(0.63, answer) + question, answer = bodmas_decimals ("2.9 + 0.7 * 1.60 / 0.32 - 0.9") + self.assertEqual(5.5, answer) + + def test__bodmas_fractions_solver (self): + a = bodmas_fractions_solver([Fraction (200, 2),Fraction (1,4),Fraction (2,3),Fraction (1,3),Fraction (2,3)], ["/", "*", "+", "-"]) + self.assertEqual(Fraction (799, 3), a) + a = bodmas_fractions_solver([Fraction (2,3),Fraction (5,4),Fraction (2,3),Fraction (5, 12),Fraction (7,8)], ["*", "/", "+", "-"]) + self.assertEqual(Fraction (19, 24), a) + a = bodmas_fractions_solver([Fraction (9,7),Fraction (5,3),Fraction (8,5),Fraction (7,3),Fraction (1,2)], ["/", "+", "/", "+"]) + self.assertEqual(Fraction (137, 70), a) + + +if __name__ == '__main__': + unittest.main() diff --git a/class05/math/tests/test_temperature.py b/class05/math/tests/test_temperature.py new file mode 100644 index 0000000..c88401a --- /dev/null +++ b/class05/math/tests/test_temperature.py @@ -0,0 +1,29 @@ +# ..\tests>python test_fraction.py + +import unittest +from unittest import TestCase +__author__ = 'Ajay' +import sys + +sys.path.append('..\\') +from temperature import * + + +class TestTemperature(TestCase): + + def test_celsius_from_fahrenheit(self): + question, answer = celsius_from_fahrenheit (60) + self.assertEqual("{}{}C".format (15.6, u'\N{DEGREE SIGN}'), answer) + question, answer = celsius_from_fahrenheit (80) + self.assertEqual("{}{}C".format (26.7,u'\N{DEGREE SIGN}'), answer) + + def test_fahrenheit_from_celsius (self): + q, a = fahrenheit_from_celsius (60) + self.assertEqual("140.0{}F".format (u'\N{DEGREE SIGN}'), a) + q, a = fahrenheit_from_celsius (80) + self.assertEqual("176.0{}F".format (u'\N{DEGREE SIGN}'), a) + + + +if __name__ == '__main__': + unittest.main() diff --git a/class06/__init__.py b/class06/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/class06/math/__init__.py b/class06/math/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/class06/math/factors06.py b/class06/math/factors06.py new file mode 100644 index 0000000..ba0e58b --- /dev/null +++ b/class06/math/factors06.py @@ -0,0 +1,84 @@ +__author__ = 'Ajay' +'''factors.py: Generates fractions related mathematical problems''' +'''python will print all the questions, followed by a list of answers''' + +import random +import logging +import os +import uuid +from fractions import gcd +import sys + +sys.path.append ('..\\..\\') +from class05.math.factors import _is_prime, _highest_common_factor, _least_common_multiple, _generate_unique_random_numbers, answers #all private functions +from class05.math.factors import * #public functions + + +names = ['Rahul', 'Ganpat', 'Gaurav', 'Gautam','Girish'] + + +def containers_hcf (capacity=[]): + container_list = ["tubs", "tankers", "water tanks", "oil-ships"] + if (len (capacity) != 2): + capacity = [] + hcf = random.randint (12,29) + capacity.append (hcf * random.randint (20, 40)) + capacity.append (hcf * random.randint (20, 40)) + #_,hcf = _highest_common_factor([capacity[0], capacity[1]]) + while (capacity[0] == capacity[1] or hcf == 1): + capacity[0] = random.randint(20, 40) + _,hcf = _highest_common_factor([capacity[0], capacity[1]]) + container = container_list[random.randint(0, len(container_list)-1)] + print ("Two {} contain {} liters and {} liters of liquid respectively. Find the maximum capacity of a container which can measure the liquid of both tanks when used".format(container, capacity[0], capacity[1]),\ + " an exact number of times.") + _,answer = _highest_common_factor([capacity[0], capacity[1]]) + answers.append (answer) + return (answer) + + + +functions = [nearest_primes, list_primes, twin_primes, factors, multiples, all_factors, consecutive_primes, \ + highest_common_factor, least_common_multiple, lcm_and_hcf, pole_spacing, stamp_distribution,\ + march_past, building_age, chocolate_distribution, students_in_class, students_running_circles, journey_time_minimum_hours, containers_hcf] + + +def squat(): + print("hello world") + for i in range(5): + yield (i ** 2) + + +def main(): + logging.basicConfig(format='%(asctime)s:%(levelname)s:%(funcName)s:%(message)s', datefmt='%Y%m%d %I:%M:%S %p', + filename='class.log', level=logging.INFO) + unique_id = uuid.uuid1(1) + html_text = "

Fractions

\n" + html_text += "

Question Paper # {}

\n".format(str(unique_id)) + html_text += r'
    ' + print("Question Paper # {}".format(str(unique_id))) + # random.seed (os.urandom(5)) + for i in range(0, len(functions)): + logging.info('Function : %s' % functions[i]) + + print ("{i}) ".format(i=i+1), end="") + f = functions[i] + html_text += "
  1. " + f() + html_text += "
  2. \n" + logging.info ('Answer : %s' % answers[i]) + html_text += r'
' + print () + print("Answer Key # {}".format(str(unique_id))) + for i in range(0, len (functions)): #len(answers)): + print(i + 1, answers[i]) + #primes = [ _is_prime(x) for x in range (100)] + #print (primes) + #for i in squat (): + # print (i) + + #for i in range (100, 500): + # print (i, all_factors(i)) + + +if __name__ == "__main__": + main() diff --git a/class06/math/tests/test_factors06.py b/class06/math/tests/test_factors06.py new file mode 100644 index 0000000..8f07d78 --- /dev/null +++ b/class06/math/tests/test_factors06.py @@ -0,0 +1,52 @@ +import unittest +from unittest import TestCase +import sys + +__author__ = 'Ajay' +sys.path.append ('..\\..\\') #path, if this tests are executed as python tests/test_factors.py +sys.path.append ('..\\..\\..\\') # path, if these tests are executed from tests directory as python test_factors.py +from class06.math.factors06 import * + + +class TestFactors(TestCase): + def test_factors(self): + self.assertEqual([673], factors (673)) + self.assertEqual([3,11,13], factors (429)) + self.assertEqual([167, 334, 501, 668, 835], multiples (167, 5)) + self.assertEqual([150, 300, 450, 600], multiples (150, 4)) + self.assertEqual(False, is_prime(6)) + self.assertEqual(True, is_prime(11)) + self.assertEqual(False, is_prime(4)) + self.assertEqual([2, 19, 23], all_factors(874)) + self.assertEqual([2, 2, 103], all_factors(412)) + self.assertEqual(("Factors = [17, 19, 23, 29]. Product = 215441"), consecutive_primes(17, 4)) + self.assertEqual(("Factors = [11, 13]. Product = 143"), consecutive_primes(11, 2)) + self.assertEqual(12, highest_common_factor([36, 48])) + self.assertEqual(6, highest_common_factor([24, 30, 90])) + self.assertEqual(1, highest_common_factor([13, 21, 17])) + self.assertEqual(4, highest_common_factor([72, 104, 92])) + + self.assertEqual(4290, least_common_multiple([330, 65, 15])) + self.assertEqual(1440, least_common_multiple([45,32,16])) + self.assertEqual(5208, least_common_multiple([31,24,14])) + self.assertEqual(46512, least_common_multiple([323,272,153])) + self.assertEqual(1260, least_common_multiple([4,5,7,9])) + self.assertEqual(26180, least_common_multiple([4,5,7,11,17])) + self.assertEqual((1530, 34), lcm_and_hcf([306, 170, 170])) + self.assertEqual((6930, 9), lcm_and_hcf([90, 126, 99])) + self.assertEqual(12, pole_spacing([60,36,84])) + self.assertEqual((8,3,2), stamp_distribution([24,16])) + self.assertEqual((6,3,5), stamp_distribution([18,30])) + self.assertEqual(8, march_past([32, 40])) + self.assertEqual (50, building_age(50)) + self.assertEqual((123, [6,8,10]), chocolate_distribution ([6, 8, 10], 3)) + self.assertEqual(36, students_in_class([6, 9, 12, 18])) + self.assertEqual((120, [4,3]), students_running_circles([30, 40])) + self.assertEqual((60, [5,4]), students_running_circles([12, 15])) + self.assertEqual((7, [3,5,7] ), journey_time_minimum_hours([21, 35, 49])) + self.assertEqual((2, [3,4,5]), journey_time_minimum_hours([6, 8, 10])) + self.assertEqual(2, containers_hcf([38, 1160])) + self.assertEqual(16, containers_hcf([144, 176])) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..d3c7f8e --- /dev/null +++ b/setup.py @@ -0,0 +1,12 @@ +from distutils.core import setup + +setup( + name='study', + version='0.1', + packages=['class05', 'class05.math'], + url='', + license='MIT License', + author='Ajay', + author_email='', + description='CBSE Class 5 Homework Generator' +)