+++ /dev/null
-# Author: Jody Foo (2016)
-
-""" Kör med python3 -B pyuppgtest2_3.py <fil att testa>
-
-Var noga med att filen ni vill testa och den här testfilen ligger i samma
-katalog.
-"""
-
-import unittest
-import sys
-import importlib
-import traceback
-import logging
-import logging.handlers
-import re
-import random
-import copy
-import io
-
-
-def list_contents_is_equal(list1, list2):
- if len(list1) != len(list2):
- print("not equal lists:", list1, list2)
- return False
- else:
- for value in list1:
- if value not in list2:
- print("not equal lists:", list1, list2)
- return False
- return True
-
-
-class PyUppgift(unittest.TestCase):
- """Test cases."""
-
- # Default-värde. Ändras via argument till skriptet.
- pass_points = 85
-
- @classmethod
- def setUpClass(cls):
- cls.missing = []
- cls.errors = []
- cls.no_errors = []
- cls.points = []
-
- @classmethod
- def tearDownClass(cls):
- """Skriv ut resultat när vi testat klart."""
- global log
- if len(cls.no_errors) > 0:
- log.info("\n#### KORREKT LÖSTA UPPGIFTER ####\n")
- for message in cls.no_errors:
- log.info(message.rstrip())
-
- if len(cls.errors) > 0:
- log.info("\n\n#### UPPGIFTER MED FEL ####\n")
- log.info("Felsök genom att ha testanrop längst ner i din kodfil och")
- log.info("skriv ut resultaten. Kontrollera också så att du har mellanrum")
- log.info("på rätt ställe och att stora/små bokstäver stämmer överrens.\n")
- for message in cls.errors:
- log.info(message)
-
- if len(cls.missing) > 0:
- log.info("\n\n#### SVAR SAKNAS FÖR NEDANSTÅENDE ####\n")
- for message in cls.missing:
- log.info(message)
- log.info("\nKontrollera stavningen av dina funktioner. Användning av versaler/gemener")
- log.info("har betydelse. \n")
-
- points = sum(cls.points)
- log.info("\n#### SUMMA POÄNG: {}. ({} behövs)".format(points, cls.pass_points))
- # log.info(points)
- if points >= cls.pass_points:
- log.info("#### Du är preliminärt GODKÄND på Pythonuppgift 2.3!")
- log.info(" ")
- else:
- # log.info("#### Du är INTE godkänd på Pythonuppgift 2.3")
- log.info("#### " + str(cls.pass_points - points) + " poäng saknas för att få godkänt.")
- log.info(" ")
-
- def save_error(self, uppg, exception, tb_stack):
- global log
-
- # stringio = io.StringIO()
-
- # self.errors.append("UPPG " + uppg + ": Fel påträffades.")
- exception_string_tokens = str(exception).split(":")
- message = "UPPG " + uppg + ". Fel påträffades: "
- # message += str(exception.__class__.__name__)
- message += exception_string_tokens[-1].strip()
- self.errors.append(message)
- # self.errors.append("UPPG " + uppg + " " +
- # str(exception.__class__.__name__) + ": " +
- # repr(exception) +
- # "")
- # self.errors.append("UPPG " + uppg)
- # tb_list = traceback.format_list(traceback.extract_stack(limit=3))
- # tb_list = traceback.format_list(traceback.extract_stack(limit=3))
- # tb_list = None
- # if sys_traceback != None:
- # tb_list = traceback.format_list(traceback.extract_tb(sys_traceback, limit=3))
- # else:
- # tb_list = traceback.format_list(tb_stack)
- # for line in tb_list:
- # self.errors.append(line)
- # traceback.print_exc(file=stringio, limit=1)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # traceback.print_last(file=stringio)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # traceback.print_stack(file=stringio)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # error_text = "ERROR TEXT: " + stringio.getvalue()
- # stringio.close()
- # print("ERROR STUFF" + error_text)
- # self.errors.append(error_text)
-
- def save_missing(self, uppg, exception):
- global log
- ex_str = str(exception)
- ex_str = re.sub(r".*('.*'$)", r"\1", ex_str)
- self.missing.append("UPPG " + uppg + " Funktion saknas: " + ex_str)
-
- def save_no_errors(self, uppg, points):
- global log
- self.no_errors.append("UPPG " + uppg + ": " + str(points) + " poäng. \n")
- self.points.append(points)
-
-
- ## List- och stränghantering
- def test_uppg_2_3_1(self):
- points = 5
- uppg = "2.3.1"
- try:
- self.assertEqual(mod.replace_periods_with_newlines("hej.jag.heter"),
- "hej\njag\nheter", "Punkter ej rätt utbytta i 'hej.jag.heter'")
- self.assertEqual(mod.replace_periods_with_newlines("..."), "\n\n\n",
- "Punkter ej rätt utbytta i '...'")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_2(self):
- points = 10
- uppg = "2.3.2"
- try:
- self.assertEqual(mod.replace_char_in_string("hej.jag.heter", ".", "\n"), "hej\njag\nheter",
- "Tecknet '.' är ej rätt utbytt till newline i 'hej.jag.heter'")
- self.assertEqual(mod.replace_char_in_string("...", ".", "\n"), "\n\n\n",
- "Tecknet '.' är ej rätt utbytt till newline i '...'")
- self.assertEqual(mod.replace_char_in_string("hej5jag5heter", "5", "9"), "hej9jag9heter",
- "Tecknet '5' är ej rätt utbytt till '9' i 'hej5jag5heter'")
- self.assertEqual(mod.replace_char_in_string("...", " ", "A"), "...",
- "Tecknet ' ' är ej rätt utbytt till 'A' i '...'")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_3_a(self):
- points = 10
- uppg = "2.3.3.a"
- try:
- self.assertEqual(mod.reverse_string_while("hej"), "jeh",
- "Strängen 'hej' returneras ej omvänt")
- self.assertEqual(mod.reverse_string_while(""), "",
- "Den tomma strängen returneras ej som sig själv")
- self.assertEqual(mod.reverse_string_while("banankontakt"), "tkatnoknanab",
- "Strängen 'banankontakt' returneras ej omvänt")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_3_b(self):
- points = 10
- uppg = "2.3.3.b"
- try:
- self.assertEqual(mod.reverse_string_for("hej"), "jeh",
- "Strängen 'hej' returneras ej omvänt")
- self.assertEqual(mod.reverse_string_for(""), "",
- "Den tomma strängen returneras ej som sig själv")
- self.assertEqual(mod.reverse_string_for("banankontakt"), "tkatnoknanab",
- "Strängen 'banankontakt' returneras ej omvänt")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_4(self):
- points = 5
- uppg = "2.3.4"
- try:
- self.assertEqual(mod.get_five_first([1,2,3,4,5,6,7,8,9]), [1,2,3,4,5],
- "Du returnerar ej de fem första från [1,2,3,4,5,6,7,8,9]")
- self.assertEqual(mod.get_five_first(["hej","vad","heter","du","?","jag","heter","python"]),
- ["hej","vad","heter","du","?"],
- "Du returnerar ej de fem första från ['hej','vad','heter','du','?','jag','heter','python']")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_5(self):
- points = 10
- uppg = "2.3.5"
- try:
- self.assertEqual(mod.get_nfirst([1,2,3,4,5,6,7,8,9], 3), [1,2,3],
- "Du returnerar ej de 3 första ur [1,2,3,4,5,6,7,8,9]")
- self.assertEqual(mod.get_nfirst(["hej","vad","heter","du","?","jag","heter","python"],
- 7),
- ["hej","vad","heter","du","?","jag","heter"],
- "Du returnerar ej de 7 första ur ['hej','vad','heter','du','?','jag','heter','python']")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_6(self):
- points = 10
- uppg = "2.3.6"
- try:
- self.assertListEqual(mod.get_all_less_than([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05], 3.3),
- [1.0, 2.0, 3.0, 0.05],
- "Du kan ej returnera de värden mindre än 3.3 i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05]")
- self.assertListEqual(mod.get_all_less_than([0.05, 500.3, 0.1, 30.3], 4.5), [0.05, 0.1],
- "Du kan ej returnera de värden mindre än 4.5 i [0.05, 500.3, 0.1, 30.3]")
- self.assertListEqual(mod.get_all_less_than([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05], 0.05), [],
- "Du kan ej returnera de värden mindre än 0.05 i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05]")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_7(self):
- points = 5
- uppg = "2.3.7"
- try:
- self.assertListEqual(mod.get_all_even([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]), [2.0, 4.0, 6.0, 8.0],
- "Du returnerar ej de jämna värdena i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]")
- self.assertListEqual(mod.get_all_even([0, 2, 3, 4, 5, 6, 7, 8, 9]), [0,2, 4, 6, 8],
- "Du returnerar ej de jämna värdena i [0, 2, 3, 4, 5, 6, 7, 8, 9]")
- self.assertListEqual(mod.get_all_even([1, 3]), [],
- "Du returnerar ej de jämna värdena i [1, 3]")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_8(self):
- points = 5
- uppg = "2.3.8"
- try:
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 3), [3, 6, 9],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 3")
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 2), [2, 4, 6, 8],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 2")
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 5), [5],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 5")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_9(self):
- points = 5
- uppg = "2.3.9"
- try:
- values = [1, 2, 3, 4]
- self.assertListEqual(mod.multiply_for_each(values, 3), [3, 6, 9, 12],
- "Du returnerar ej listan med [1, 2, 3, 4] multiplicerat med 3.")
- self.assertListEqual(values, [3, 6, 9, 12], "Du har ej ändrat den givna listan.")
- values = [0, 2, 4]
- self.assertListEqual(mod.multiply_for_each(values, 2), [0, 4, 8],
- "Du returnerar ej listan med [0, 2, 4] multiplicerat med 2.")
- self.assertListEqual(values, [0, 4, 8], "Du har ej ändrat den givna listan.")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_10(self):
- points = 15
- uppg = "2.3.10"
- try:
- self.assertListEqual(mod.insert_at_asc_place([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], 3.3),
- [1.0, 2.0, 3.0, 3.3, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
- "Du har satt in 3.3 fel i [1.0, 2.0, 3.0, 3.3, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]")
- self.assertListEqual(mod.insert_at_asc_place([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], 10.0),
- [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
- "Du har satt in 10.0 fel i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]")
- self.assertListEqual(mod.insert_at_asc_place([1, 3], 4), [1, 3, 4], "Du har satt in 4 fel i [1, 3]")
- self.assertListEqual(mod.insert_at_asc_place([1, 3], 3), [1, 3, 3], "Du har satt in 3 fel i [1, 3]")
- self.assertListEqual(mod.insert_at_asc_place([], 2), [2], "Du har inte satt in 2 i []")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_11(self):
- points = 10
- uppg = "2.3.11"
- try:
- self.assertListEqual(mod.sort_asc([1, 3, 2, 0, -5, 12, 7]), [-5, 0, 1, 2, 3, 7, 12],
- "Du har sorterat [1, 3, 2, 0, -5, 12, 7] fel")
- self.assertListEqual(mod.sort_asc([1, 3]), [1, 3],
- "Du har sorterat [1, 3] fel")
- self.assertListEqual(mod.sort_asc([73, 2, 9, 0]), [0, 2, 9, 73],
- "Du har sorterat [73, 2, 9, 0] fel")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
-
-if __name__ == '__main__':
-
- if len(sys.argv) > 1:
- module_name = sys.argv[1].replace("/", ".")
-
- if len(sys.argv) > 2 and sys.argv[2].isdigit():
- PyUppgift.pass_points = int(sys.argv[2])
-
- # remove any trailing .py
- if module_name[-3:] == ".py":
- module_name = module_name[:-3]
-
- # load module into mod
- mod = importlib.import_module(module_name)
-
- # filename to minify later
- filename = module_name + ".py"
-
- # set up loggger
- # logging.basicConfig(filename='pyuppg1test.log', format="", filemode='w', level=logging.INFO)
- logfilename = "pyuppgtest2_3.log"
- log = logging.getLogger(__name__)
- log.setLevel(logging.INFO)
- handler = logging.FileHandler(logfilename, mode="w")
- handler.setLevel(logging.INFO)
- handler.setFormatter(logging.Formatter())
- log.addHandler(handler)
-
- # remove elements in sys.argv so that unittest.main does not get
- # confused
- del sys.argv[1:]
- # unittest.main(verbosity=2)
- # unittest.main(verbosity=1)
- unittest.main()
-
- else:
- sys.exit("Ingen mod att testa.")
+++ /dev/null
-# Author: Jody Foo (2016)
-
-""" Kör med python3 -B pyuppgtest2_3.py <fil att testa>
-
-Var noga med att filen ni vill testa och den här testfilen ligger i samma
-katalog.
-"""
-
-import unittest
-import sys
-import importlib
-import traceback
-import logging
-import logging.handlers
-import re
-import random
-import copy
-import io
-
-
-def list_contents_is_equal(list1, list2):
- if len(list1) != len(list2):
- print("not equal lists:", list1, list2)
- return False
- else:
- for value in list1:
- if value not in list2:
- print("not equal lists:", list1, list2)
- return False
- return True
-
-
-class PyUppgift(unittest.TestCase):
- """Test cases."""
-
- # Default-värde. Ändras via argument till skriptet.
- pass_points = 85
-
- @classmethod
- def setUpClass(cls):
- cls.missing = []
- cls.errors = []
- cls.no_errors = []
- cls.points = []
-
- @classmethod
- def tearDownClass(cls):
- """Skriv ut resultat när vi testat klart."""
- global log
- if len(cls.no_errors) > 0:
- log.info("\n#### KORREKT LÖSTA UPPGIFTER ####\n")
- for message in cls.no_errors:
- log.info(message.rstrip())
-
- if len(cls.errors) > 0:
- log.info("\n\n#### UPPGIFTER MED FEL ####\n")
- log.info("Felsök genom att ha testanrop längst ner i din kodfil och")
- log.info("skriv ut resultaten. Kontrollera också så att du har mellanrum")
- log.info("på rätt ställe och att stora/små bokstäver stämmer överrens.\n")
- for message in cls.errors:
- log.info(message)
-
- if len(cls.missing) > 0:
- log.info("\n\n#### SVAR SAKNAS FÖR NEDANSTÅENDE ####\n")
- for message in cls.missing:
- log.info(message)
- log.info("\nKontrollera stavningen av dina funktioner. Användning av versaler/gemener")
- log.info("har betydelse. \n")
-
- points = sum(cls.points)
- log.info("\n#### SUMMA POÄNG: {}. ({} behövs)".format(points, cls.pass_points))
- # log.info(points)
- if points >= cls.pass_points:
- log.info("#### Du är preliminärt GODKÄND på Pythonuppgift 2.3!")
- log.info(" ")
- else:
- # log.info("#### Du är INTE godkänd på Pythonuppgift 2.3")
- log.info("#### " + str(cls.pass_points - points) + " poäng saknas för att få godkänt.")
- log.info(" ")
-
- def save_error(self, uppg, exception, tb_stack):
- global log
-
- # stringio = io.StringIO()
-
- # self.errors.append("UPPG " + uppg + ": Fel påträffades.")
- exception_string_tokens = str(exception).split(":")
- message = "UPPG " + uppg + ". Fel påträffades: "
- # message += str(exception.__class__.__name__)
- message += exception_string_tokens[-1].strip()
- self.errors.append(message)
- # self.errors.append("UPPG " + uppg + " " +
- # str(exception.__class__.__name__) + ": " +
- # repr(exception) +
- # "")
- # self.errors.append("UPPG " + uppg)
- # tb_list = traceback.format_list(traceback.extract_stack(limit=3))
- # tb_list = traceback.format_list(traceback.extract_stack(limit=3))
- # tb_list = None
- # if sys_traceback != None:
- # tb_list = traceback.format_list(traceback.extract_tb(sys_traceback, limit=3))
- # else:
- # tb_list = traceback.format_list(tb_stack)
- # for line in tb_list:
- # self.errors.append(line)
- # traceback.print_exc(file=stringio, limit=1)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # traceback.print_last(file=stringio)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # traceback.print_stack(file=stringio)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # error_text = "ERROR TEXT: " + stringio.getvalue()
- # stringio.close()
- # print("ERROR STUFF" + error_text)
- # self.errors.append(error_text)
-
- def save_missing(self, uppg, exception):
- global log
- ex_str = str(exception)
- ex_str = re.sub(r".*('.*'$)", r"\1", ex_str)
- self.missing.append("UPPG " + uppg + " Funktion saknas: " + ex_str)
-
- def save_no_errors(self, uppg, points):
- global log
- self.no_errors.append("UPPG " + uppg + ": " + str(points) + " poäng. \n")
- self.points.append(points)
-
-
- ## List- och stränghantering
- def test_uppg_2_3_1(self):
- points = 5
- uppg = "2.3.1"
- try:
- self.assertEqual(mod.replace_periods_with_newlines("hej.jag.heter"),
- "hej\njag\nheter", "Punkter ej rätt utbytta i 'hej.jag.heter'")
- self.assertEqual(mod.replace_periods_with_newlines("..."), "\n\n\n",
- "Punkter ej rätt utbytta i '...'")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_2(self):
- points = 10
- uppg = "2.3.2"
- try:
- self.assertEqual(mod.replace_char_in_string("hej.jag.heter", ".", "\n"), "hej\njag\nheter",
- "Tecknet '.' är ej rätt utbytt till newline i 'hej.jag.heter'")
- self.assertEqual(mod.replace_char_in_string("...", ".", "\n"), "\n\n\n",
- "Tecknet '.' är ej rätt utbytt till newline i '...'")
- self.assertEqual(mod.replace_char_in_string("hej5jag5heter", "5", "9"), "hej9jag9heter",
- "Tecknet '5' är ej rätt utbytt till '9' i 'hej5jag5heter'")
- self.assertEqual(mod.replace_char_in_string("...", " ", "A"), "...",
- "Tecknet ' ' är ej rätt utbytt till 'A' i '...'")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_3_a(self):
- points = 10
- uppg = "2.3.3.a"
- try:
- self.assertEqual(mod.reverse_string_while("hej"), "jeh",
- "Strängen 'hej' returneras ej omvänt")
- self.assertEqual(mod.reverse_string_while(""), "",
- "Den tomma strängen returneras ej som sig själv")
- self.assertEqual(mod.reverse_string_while("banankontakt"), "tkatnoknanab",
- "Strängen 'banankontakt' returneras ej omvänt")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_3_b(self):
- points = 10
- uppg = "2.3.3.b"
- try:
- self.assertEqual(mod.reverse_string_for("hej"), "jeh",
- "Strängen 'hej' returneras ej omvänt")
- self.assertEqual(mod.reverse_string_for(""), "",
- "Den tomma strängen returneras ej som sig själv")
- self.assertEqual(mod.reverse_string_for("banankontakt"), "tkatnoknanab",
- "Strängen 'banankontakt' returneras ej omvänt")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_4(self):
- points = 5
- uppg = "2.3.4"
- try:
- self.assertEqual(mod.get_five_first([1,2,3,4,5,6,7,8,9]), [1,2,3,4,5],
- "Du returnerar ej de fem första från [1,2,3,4,5,6,7,8,9]")
- self.assertEqual(mod.get_five_first(["hej","vad","heter","du","?","jag","heter","python"]),
- ["hej","vad","heter","du","?"],
- "Du returnerar ej de fem första från ['hej','vad','heter','du','?','jag','heter','python']")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_5(self):
- points = 10
- uppg = "2.3.5"
- try:
- self.assertEqual(mod.get_nfirst([1,2,3,4,5,6,7,8,9], 3), [1,2,3],
- "Du returnerar ej de 3 första ur [1,2,3,4,5,6,7,8,9]")
- self.assertEqual(mod.get_nfirst(["hej","vad","heter","du","?","jag","heter","python"],
- 7),
- ["hej","vad","heter","du","?","jag","heter"],
- "Du returnerar ej de 7 första ur ['hej','vad','heter','du','?','jag','heter','python']")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_6(self):
- points = 10
- uppg = "2.3.6"
- try:
- self.assertListEqual(mod.get_all_less_than([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05], 3.3),
- [1.0, 2.0, 3.0, 0.05],
- "Du kan ej returnera de värden mindre än 3.3 i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05]")
- self.assertListEqual(mod.get_all_less_than([0.05, 500.3, 0.1, 30.3], 4.5), [0.05, 0.1],
- "Du kan ej returnera de värden mindre än 4.5 i [0.05, 500.3, 0.1, 30.3]")
- self.assertListEqual(mod.get_all_less_than([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05], 0.05), [],
- "Du kan ej returnera de värden mindre än 0.05 i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05]")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_7(self):
- points = 5
- uppg = "2.3.7"
- try:
- self.assertListEqual(mod.get_all_even([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]), [2.0, 4.0, 6.0, 8.0],
- "Du returnerar ej de jämna värdena i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]")
- self.assertListEqual(mod.get_all_even([0, 2, 3, 4, 5, 6, 7, 8, 9]), [0,2, 4, 6, 8],
- "Du returnerar ej de jämna värdena i [0, 2, 3, 4, 5, 6, 7, 8, 9]")
- self.assertListEqual(mod.get_all_even([1, 3]), [],
- "Du returnerar ej de jämna värdena i [1, 3]")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_8(self):
- points = 5
- uppg = "2.3.8"
- try:
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 3), [3, 6, 9],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 3")
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 2), [2, 4, 6, 8],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 2")
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 5), [5],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 5")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_9(self):
- points = 5
- uppg = "2.3.9"
- try:
- values = [1, 2, 3, 4]
- self.assertListEqual(mod.multiply_for_each(values, 3), [3, 6, 9, 12],
- "Du returnerar ej listan med [1, 2, 3, 4] multiplicerat med 3.")
- self.assertListEqual(values, [3, 6, 9, 12], "Du har ej ändrat den givna listan.")
- values = [0, 2, 4]
- self.assertListEqual(mod.multiply_for_each(values, 2), [0, 4, 8],
- "Du returnerar ej listan med [0, 2, 4] multiplicerat med 2.")
- self.assertListEqual(values, [0, 4, 8], "Du har ej ändrat den givna listan.")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_10(self):
- points = 15
- uppg = "2.3.10"
- try:
- self.assertListEqual(mod.insert_at_asc_place([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], 3.3),
- [1.0, 2.0, 3.0, 3.3, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
- "Du har satt in 3.3 fel i [1.0, 2.0, 3.0, 3.3, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]")
- self.assertListEqual(mod.insert_at_asc_place([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], 10.0),
- [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
- "Du har satt in 10.0 fel i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]")
- self.assertListEqual(mod.insert_at_asc_place([1, 3], 4), [1, 3, 4], "Du har satt in 4 fel i [1, 3]")
- self.assertListEqual(mod.insert_at_asc_place([1, 3], 3), [1, 3, 3], "Du har satt in 3 fel i [1, 3]")
- self.assertListEqual(mod.insert_at_asc_place([], 2), [2], "Du har inte satt in 2 i []")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_11(self):
- points = 10
- uppg = "2.3.11"
- try:
- self.assertListEqual(mod.sort_asc([1, 3, 2, 0, -5, 12, 7]), [-5, 0, 1, 2, 3, 7, 12],
- "Du har sorterat [1, 3, 2, 0, -5, 12, 7] fel")
- self.assertListEqual(mod.sort_asc([1, 3]), [1, 3],
- "Du har sorterat [1, 3] fel")
- self.assertListEqual(mod.sort_asc([73, 2, 9, 0]), [0, 2, 9, 73],
- "Du har sorterat [73, 2, 9, 0] fel")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
-
-if __name__ == '__main__':
-
- if len(sys.argv) > 1:
- module_name = sys.argv[1].replace("/", ".")
-
- if len(sys.argv) > 2 and sys.argv[2].isdigit():
- PyUppgift.pass_points = int(sys.argv[2])
-
- # remove any trailing .py
- if module_name[-3:] == ".py":
- module_name = module_name[:-3]
-
- # load module into mod
- mod = importlib.import_module(module_name)
-
- # filename to minify later
- filename = module_name + ".py"
-
- # set up loggger
- # logging.basicConfig(filename='pyuppg1test.log', format="", filemode='w', level=logging.INFO)
- logfilename = "pyuppgtest2_3.log"
- log = logging.getLogger(__name__)
- log.setLevel(logging.INFO)
- handler = logging.FileHandler(logfilename, mode="w")
- handler.setLevel(logging.INFO)
- handler.setFormatter(logging.Formatter())
- log.addHandler(handler)
-
- # remove elements in sys.argv so that unittest.main does not get
- # confused
- del sys.argv[1:]
- # unittest.main(verbosity=2)
- # unittest.main(verbosity=1)
- unittest.main()
-
- else:
- sys.exit("Ingen mod att testa.")
+++ /dev/null
-# Author: Jody Foo (2016)
-
-""" Kör med python3 -B pyuppgtest2_3.py <fil att testa>
-
-Var noga med att filen ni vill testa och den här testfilen ligger i samma
-katalog.
-"""
-
-import unittest
-import sys
-import importlib
-import traceback
-import logging
-import logging.handlers
-import re
-import random
-import copy
-import io
-
-
-def list_contents_is_equal(list1, list2):
- if len(list1) != len(list2):
- print("not equal lists:", list1, list2)
- return False
- else:
- for value in list1:
- if value not in list2:
- print("not equal lists:", list1, list2)
- return False
- return True
-
-
-class PyUppgift(unittest.TestCase):
- """Test cases."""
-
- # Default-värde. Ändras via argument till skriptet.
- pass_points = 85
-
- @classmethod
- def setUpClass(cls):
- cls.missing = []
- cls.errors = []
- cls.no_errors = []
- cls.points = []
-
- @classmethod
- def tearDownClass(cls):
- """Skriv ut resultat när vi testat klart."""
- global log
- if len(cls.no_errors) > 0:
- log.info("\n#### KORREKT LÖSTA UPPGIFTER ####\n")
- for message in cls.no_errors:
- log.info(message.rstrip())
-
- if len(cls.errors) > 0:
- log.info("\n\n#### UPPGIFTER MED FEL ####\n")
- log.info("Felsök genom att ha testanrop längst ner i din kodfil och")
- log.info("skriv ut resultaten. Kontrollera också så att du har mellanrum")
- log.info("på rätt ställe och att stora/små bokstäver stämmer överrens.\n")
- for message in cls.errors:
- log.info(message)
-
- if len(cls.missing) > 0:
- log.info("\n\n#### SVAR SAKNAS FÖR NEDANSTÅENDE ####\n")
- for message in cls.missing:
- log.info(message)
- log.info("\nKontrollera stavningen av dina funktioner. Användning av versaler/gemener")
- log.info("har betydelse. \n")
-
- points = sum(cls.points)
- log.info("\n#### SUMMA POÄNG: {}. ({} behövs)".format(points, cls.pass_points))
- # log.info(points)
- if points >= cls.pass_points:
- log.info("#### Du är preliminärt GODKÄND på Pythonuppgift 2.3!")
- log.info(" ")
- else:
- # log.info("#### Du är INTE godkänd på Pythonuppgift 2.3")
- log.info("#### " + str(cls.pass_points - points) + " poäng saknas för att få godkänt.")
- log.info(" ")
-
- def save_error(self, uppg, exception, tb_stack):
- global log
-
- # stringio = io.StringIO()
-
- # self.errors.append("UPPG " + uppg + ": Fel påträffades.")
- exception_string_tokens = str(exception).split(":")
- message = "UPPG " + uppg + ". Fel påträffades: "
- # message += str(exception.__class__.__name__)
- message += exception_string_tokens[-1].strip()
- self.errors.append(message)
- # self.errors.append("UPPG " + uppg + " " +
- # str(exception.__class__.__name__) + ": " +
- # repr(exception) +
- # "")
- # self.errors.append("UPPG " + uppg)
- # tb_list = traceback.format_list(traceback.extract_stack(limit=3))
- # tb_list = traceback.format_list(traceback.extract_stack(limit=3))
- # tb_list = None
- # if sys_traceback != None:
- # tb_list = traceback.format_list(traceback.extract_tb(sys_traceback, limit=3))
- # else:
- # tb_list = traceback.format_list(tb_stack)
- # for line in tb_list:
- # self.errors.append(line)
- # traceback.print_exc(file=stringio, limit=1)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # traceback.print_last(file=stringio)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # traceback.print_stack(file=stringio)
- # print("-"*60)
- # stringio.write("-"*60 + "\n")
- # error_text = "ERROR TEXT: " + stringio.getvalue()
- # stringio.close()
- # print("ERROR STUFF" + error_text)
- # self.errors.append(error_text)
-
- def save_missing(self, uppg, exception):
- global log
- ex_str = str(exception)
- ex_str = re.sub(r".*('.*'$)", r"\1", ex_str)
- self.missing.append("UPPG " + uppg + " Funktion saknas: " + ex_str)
-
- def save_no_errors(self, uppg, points):
- global log
- self.no_errors.append("UPPG " + uppg + ": " + str(points) + " poäng. \n")
- self.points.append(points)
-
-
- ## List- och stränghantering
- def test_uppg_2_3_1(self):
- points = 5
- uppg = "2.3.1"
- try:
- self.assertEqual(mod.replace_periods_with_newlines("hej.jag.heter"),
- "hej\njag\nheter", "Punkter ej rätt utbytta i 'hej.jag.heter'")
- self.assertEqual(mod.replace_periods_with_newlines("..."), "\n\n\n",
- "Punkter ej rätt utbytta i '...'")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_2(self):
- points = 10
- uppg = "2.3.2"
- try:
- self.assertEqual(mod.replace_char_in_string("hej.jag.heter", ".", "\n"), "hej\njag\nheter",
- "Tecknet '.' är ej rätt utbytt till newline i 'hej.jag.heter'")
- self.assertEqual(mod.replace_char_in_string("...", ".", "\n"), "\n\n\n",
- "Tecknet '.' är ej rätt utbytt till newline i '...'")
- self.assertEqual(mod.replace_char_in_string("hej5jag5heter", "5", "9"), "hej9jag9heter",
- "Tecknet '5' är ej rätt utbytt till '9' i 'hej5jag5heter'")
- self.assertEqual(mod.replace_char_in_string("...", " ", "A"), "...",
- "Tecknet ' ' är ej rätt utbytt till 'A' i '...'")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_3_a(self):
- points = 10
- uppg = "2.3.3.a"
- try:
- self.assertEqual(mod.reverse_string_while("hej"), "jeh",
- "Strängen 'hej' returneras ej omvänt")
- self.assertEqual(mod.reverse_string_while(""), "",
- "Den tomma strängen returneras ej som sig själv")
- self.assertEqual(mod.reverse_string_while("banankontakt"), "tkatnoknanab",
- "Strängen 'banankontakt' returneras ej omvänt")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_3_b(self):
- points = 10
- uppg = "2.3.3.b"
- try:
- self.assertEqual(mod.reverse_string_for("hej"), "jeh",
- "Strängen 'hej' returneras ej omvänt")
- self.assertEqual(mod.reverse_string_for(""), "",
- "Den tomma strängen returneras ej som sig själv")
- self.assertEqual(mod.reverse_string_for("banankontakt"), "tkatnoknanab",
- "Strängen 'banankontakt' returneras ej omvänt")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_4(self):
- points = 5
- uppg = "2.3.4"
- try:
- self.assertEqual(mod.get_five_first([1,2,3,4,5,6,7,8,9]), [1,2,3,4,5],
- "Du returnerar ej de fem första från [1,2,3,4,5,6,7,8,9]")
- self.assertEqual(mod.get_five_first(["hej","vad","heter","du","?","jag","heter","python"]),
- ["hej","vad","heter","du","?"],
- "Du returnerar ej de fem första från ['hej','vad','heter','du','?','jag','heter','python']")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_5(self):
- points = 10
- uppg = "2.3.5"
- try:
- self.assertEqual(mod.get_nfirst([1,2,3,4,5,6,7,8,9], 3), [1,2,3],
- "Du returnerar ej de 3 första ur [1,2,3,4,5,6,7,8,9]")
- self.assertEqual(mod.get_nfirst(["hej","vad","heter","du","?","jag","heter","python"],
- 7),
- ["hej","vad","heter","du","?","jag","heter"],
- "Du returnerar ej de 7 första ur ['hej','vad','heter','du','?','jag','heter','python']")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_6(self):
- points = 10
- uppg = "2.3.6"
- try:
- self.assertListEqual(mod.get_all_less_than([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05], 3.3),
- [1.0, 2.0, 3.0, 0.05],
- "Du kan ej returnera de värden mindre än 3.3 i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05]")
- self.assertListEqual(mod.get_all_less_than([0.05, 500.3, 0.1, 30.3], 4.5), [0.05, 0.1],
- "Du kan ej returnera de värden mindre än 4.5 i [0.05, 500.3, 0.1, 30.3]")
- self.assertListEqual(mod.get_all_less_than([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05], 0.05), [],
- "Du kan ej returnera de värden mindre än 0.05 i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.05]")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_7(self):
- points = 5
- uppg = "2.3.7"
- try:
- self.assertListEqual(mod.get_all_even([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]), [2.0, 4.0, 6.0, 8.0],
- "Du returnerar ej de jämna värdena i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]")
- self.assertListEqual(mod.get_all_even([0, 2, 3, 4, 5, 6, 7, 8, 9]), [0,2, 4, 6, 8],
- "Du returnerar ej de jämna värdena i [0, 2, 3, 4, 5, 6, 7, 8, 9]")
- self.assertListEqual(mod.get_all_even([1, 3]), [],
- "Du returnerar ej de jämna värdena i [1, 3]")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_8(self):
- points = 5
- uppg = "2.3.8"
- try:
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 3), [3, 6, 9],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 3")
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 2), [2, 4, 6, 8],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 2")
- self.assertListEqual(mod.get_all_divisible([2, 3, 4, 5, 6, 7, 8, 9], 5), [5],
- "Du kan ej returnera de värden i [2, 3, 4, 5, 6, 7, 8, 9] som är delbara med 5")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_9(self):
- points = 5
- uppg = "2.3.9"
- try:
- values = [1, 2, 3, 4]
- self.assertListEqual(mod.multiply_for_each(values, 3), [3, 6, 9, 12],
- "Du returnerar ej listan med [1, 2, 3, 4] multiplicerat med 3.")
- self.assertListEqual(values, [3, 6, 9, 12], "Du har ej ändrat den givna listan.")
- values = [0, 2, 4]
- self.assertListEqual(mod.multiply_for_each(values, 2), [0, 4, 8],
- "Du returnerar ej listan med [0, 2, 4] multiplicerat med 2.")
- self.assertListEqual(values, [0, 4, 8], "Du har ej ändrat den givna listan.")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_10(self):
- points = 15
- uppg = "2.3.10"
- try:
- self.assertListEqual(mod.insert_at_asc_place([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], 3.3),
- [1.0, 2.0, 3.0, 3.3, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
- "Du har satt in 3.3 fel i [1.0, 2.0, 3.0, 3.3, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]")
- self.assertListEqual(mod.insert_at_asc_place([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], 10.0),
- [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
- "Du har satt in 10.0 fel i [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]")
- self.assertListEqual(mod.insert_at_asc_place([1, 3], 4), [1, 3, 4], "Du har satt in 4 fel i [1, 3]")
- self.assertListEqual(mod.insert_at_asc_place([1, 3], 3), [1, 3, 3], "Du har satt in 3 fel i [1, 3]")
- self.assertListEqual(mod.insert_at_asc_place([], 2), [2], "Du har inte satt in 2 i []")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
- def test_uppg_2_3_11(self):
- points = 10
- uppg = "2.3.11"
- try:
- self.assertListEqual(mod.sort_asc([1, 3, 2, 0, -5, 12, 7]), [-5, 0, 1, 2, 3, 7, 12],
- "Du har sorterat [1, 3, 2, 0, -5, 12, 7] fel")
- self.assertListEqual(mod.sort_asc([1, 3]), [1, 3],
- "Du har sorterat [1, 3] fel")
- self.assertListEqual(mod.sort_asc([73, 2, 9, 0]), [0, 2, 9, 73],
- "Du har sorterat [73, 2, 9, 0] fel")
- except AttributeError as ae:
- self.save_missing(uppg, ae)
- except Exception as e:
- self.save_error(uppg, e, traceback.extract_stack(limit=1))
- else:
- self.save_no_errors(uppg, points)
-
-
-if __name__ == '__main__':
-
- if len(sys.argv) > 1:
- module_name = sys.argv[1].replace("/", ".")
-
- if len(sys.argv) > 2 and sys.argv[2].isdigit():
- PyUppgift.pass_points = int(sys.argv[2])
-
- # remove any trailing .py
- if module_name[-3:] == ".py":
- module_name = module_name[:-3]
-
- # load module into mod
- mod = importlib.import_module(module_name)
-
- # filename to minify later
- filename = module_name + ".py"
-
- # set up loggger
- # logging.basicConfig(filename='pyuppg1test.log', format="", filemode='w', level=logging.INFO)
- logfilename = "pyuppgtest2_3.log"
- log = logging.getLogger(__name__)
- log.setLevel(logging.INFO)
- handler = logging.FileHandler(logfilename, mode="w")
- handler.setLevel(logging.INFO)
- handler.setFormatter(logging.Formatter())
- log.addHandler(handler)
-
- # remove elements in sys.argv so that unittest.main does not get
- # confused
- del sys.argv[1:]
- # unittest.main(verbosity=2)
- # unittest.main(verbosity=1)
- unittest.main()
-
- else:
- sys.exit("Ingen mod att testa.")
# Autocomplete
from res.med import minimum_edit_distance as med
-WORD_LIST_RPATH = "res\\alphabetical_words"
-WORD_FREQ_LIST_RPATH = "res\\alphabetical.csv"
+WORDS_PATH = "res\\alphabetical_words"
+WORDS_F_PATH = "res\\alphabetical.csv"
def main():
- with_freq = False
+ with_freq = True
word = None
- with open(WORD_LIST_RPATH if not with_freq else WORD_FREQ_LIST_RPATH, 'r') as file:
+
+ # Open relevant file
+ with open(WORDS_PATH if not with_freq else WORDS_F_PATH, 'r') as file:
+
lines = file.readlines()
+ lines = [w.strip() for w in lines]
+
+ # Separate words and frequencies into separate lists
+ if with_freq:
+ words, freq = zip(*[line.split(',') for line in lines])
+ freq = [int(s) for s in freq]
+ else:
+ words = lines
+ freq = None
+
while word != "":
word = input("Type word: ").lower()
- suggestion = autocomplete(word, lines, with_freq)
+ suggestion = autocomplete(word, words, with_freq, freq)
print("Autocomplete finished: ", suggestion)
-def autocomplete(word, all_words, with_freq=False):
- """Returns list of autocomplete suggestions, ordered by relevance (optional) frequency.
+def autocomplete(word, all_words, with_freq=False, all_freq=None):
+ """Returns list of completed suggestions,
+ ordered by relevance and (optional) frequency
Args:
- word (str): incomplete input
+ word (str): input
+ all_words (list): list of words
+ with_freq (opitonal, bool): True if frequency should impact relevance
+ all_freq (optional, list): list of frequency of every word,
+ if param with_freq is given, all_freq must also be given,
+ sorted according to all_words,
+ len(all_words) must equal len(all_freq).
"""
- med_tuple = [(med(word, w.strip()), w.strip()) for w in all_words]
- med_tuple.sort(key=lambda tup: tup[0])
-
- if med_tuple[0][0] == 0:
- med_tuple.pop(0)
-
- suggest_list = [med_tuple[0][1]]
- for idx in range(len(med_tuple) - 1):
- _med, w = med_tuple[idx]
- if _med == 0:
- med_tuple.pop
- next_med, next_w = med_tuple[idx + 1]
+
+ # list of tuple like (frequency of word, word)
+ freq_tup = [(f, w) for w, f in zip(
+ all_words, all_freq if with_freq else [1]*len(all_words))
+ if word in w[:len(word)]]
+
+ # sort the list and reverse it for lowest frequency last
+ if with_freq:
+ freq_tup.sort(key=lambda tup: tup[0])
+ freq_tup.reverse()
+ else:
+ freq_tup.sort(key=lambda tup: tup[1])
+
+ _, suggest_list = zip(*freq_tup)
+
+ if word in suggest_list:
+ suggest_list.remove(word)
+
+ return list(suggest_list)
+
+
+def autocorrect(word, all_words, with_freq=False, all_freq=None):
+ """Returns list of corrected suggestions,
+ ordered by minimum-edit-distance and (optional) frequency
+
+ Args:
+ word (str): input
+ all_words (list): list of words
+ with_freq (opitonal, bool): True if frequency should impact relevance
+ all_freq (optional, list): list of frequency of every word,
+ if param with_freq is given, all_freq must also be given,
+ sorted according to all_words,
+ len(all_words) must equal len(all_freq).
+ """
+
+ # list of tuple like (med, frequency of word, word)
+ med_tup = [(med(word, w), f, w) for w, f in zip(
+ all_words, all_freq if with_freq else [1]*len(all_words))]
+
+ med_tup.sort(key=lambda tup: tup[0])
+
+ if med_tup[0][2] == word:
+ med_tup.pop(0)
+
+ # Only include words all with the same med as the word with the best med
+ freq_tup = [(med_tup[0][1], med_tup[0][2])]
+ for idx in range(len(med_tup) - 1):
+ _med, _, _ = med_tup[idx]
+ next_med, f, next_w = med_tup[idx + 1]
if _med == next_med:
- suggest_list.append(next_w)
+ freq_tup.append((f, next_w))
else:
break
- return suggest_list
+ # sort the list and reverse it for lowest frequency last
+ if with_freq:
+ freq_tup.sort(key=lambda tup: tup[0])
+ freq_tup.reverse()
+ else:
+ freq_tup.sort(lambda tup: tup[1])
+
+ _, suggest_list = zip(*freq_tup)
+
+ return list(suggest_list)
if __name__ == "__main__":