diff --git a/labs02/task01.py b/labs02/task01.py index 7c08c56..2b07ff2 100644 --- a/labs02/task01.py +++ b/labs02/task01.py @@ -6,8 +6,10 @@ Zad 2. Napisz funkcję even_elements zwracającą listę, która zawiera tylko elementy z list o parzystych indeksach. """ -def even_elements(lista): - pass + +def even_elements(elements): + return elements[::2] + def tests(f): diff --git a/labs02/task02.py b/labs02/task02.py index a6d6321..1001b07 100644 --- a/labs02/task02.py +++ b/labs02/task02.py @@ -5,8 +5,19 @@ Napisz funkcję days_in_year zwracającą liczbę dni w roku (365 albo 366). """ -def days_in_year(days): - pass +def days_in_year(year): + if ((year % 400) == 0): + return 366 + + elif ((year % 100) == 0): + return 365 + + elif not ((year % 4) == 0): + return 365 + + elif ((year % 4 ) == 0): + return 366 + def tests(f): inputs = [[2015], [2012], [1900], [2400], [1977]] diff --git a/labs02/task03.py b/labs02/task03.py index a1c3a85..3524bb2 100644 --- a/labs02/task03.py +++ b/labs02/task03.py @@ -13,7 +13,13 @@ jak 'set', która przechowuje elementy bez powtórzeń.) def oov(text, vocab): - pass + def test(self): + """Prosty test.""" + text = "This is a string , which I will use for string testing" + vocab = [',', 'this', 'is', 'a', 'which', 'for', 'will', 'I'] + oo_voc = ['string', 'testing', 'use'] + + self.assertEqual(set(oov(text, vocab)), set(oo_voc)) diff --git a/labs02/task04.py b/labs02/task04.py index 37413f1..299b143 100644 --- a/labs02/task04.py +++ b/labs02/task04.py @@ -7,7 +7,28 @@ Jeśli podany argument jest mniejszy od 1 powinna być zwracana wartość 0. """ def sum_from_one_to_n(n): - pass + suma=0 + if n > 0: + for i in range(1,n+1): + suma += i + return suma + + + + +def sum_from_one_to_n(n): + def test_special_cases(self): + """Testy przypadków szczególnych.""" + self.assertEqual(sum_from_one_to_n(-100), 0) + self.assertEqual(sum_from_one_to_n(-1), 0) + self.assertEqual(sum_from_one_to_n(0), 0) + self.assertEqual(sum_from_one_to_n(1), 1) + self.assertEqual(sum_from_one_to_n(2), 5) + + def test_regular(self): + """Testy dla kilku liczb""" + self.assertEqual(sum_from_one_to_n(3), 14) + self.assertEqual(sum_from_one_to_n(4), 385) def tests(f): diff --git a/labs02/task05.py b/labs02/task05.py index f59268a..51eba86 100644 --- a/labs02/task05.py +++ b/labs02/task05.py @@ -10,7 +10,21 @@ np. odległość pomiędzy punktami (0, 0, 0) i (3, 4, 0) jest równa 5. """ def euclidean_distance(x, y): - pass + def test_special_cases(self): + """Testy przypadków szczególnych.""" + self.assertAlmostEqual( + euclidean_distance((0.0, 0.0, 0.0), (0.0, 0.0, 0.0)), 0.0) + self.assertAlmostEqual( + euclidean_distance((3.6, -1.7, 0.3), (3.6, -1.7, 0.3)), 0.0) + self.assertAlmostEqual( + euclidean_distance((2.3, 4.3, -7.5), (2.3, 8.5, -7.5)), 4.2) + + def test_regular_cases(self): + """Testy dla zwykłych przypadków""" + self.assertAlmostEqual( + euclidean_distance((0.0, 0.0, 0.0), (0.0, 4.0, 3.0)), 5.0) + self.assertAlmostEqual( + euclidean_distance((2.4, -5.1, 3.0), (5.3, 2.1, 10.0)), 10.4523, 3) def tests(f): inputs = [[(2.3, 4.3, -7.5), (2.3, 8.5, -7.5)]] diff --git a/labs02/task06.py b/labs02/task06.py index ff4a9d3..bdadb73 100644 --- a/labs02/task06.py +++ b/labs02/task06.py @@ -10,7 +10,21 @@ ma być zwracany napis "It's not a Big 'No!'". """ def big_no(n): - pass + def test_special_cases(self): + """Testy przypadków szczególnych.""" + self.assertEqual(big_no(0), "It's not a Big 'No!'") + self.assertEqual(big_no(1), "It's not a Big 'No!'") + self.assertEqual(big_no(2), "It's not a Big 'No!'") + self.assertEqual(big_no(4), "It's not a Big 'No!'") + self.assertEqual(big_no(5), "NOOOOO!") + + def test_regular_cases(self): + """Testy dla zwykłych przypadków""" + self.assertEqual(big_no(6), "NOOOOOO!") + self.assertEqual(big_no(33), "N" + ("O" * 33) + "!") + + + def tests(f): inputs = [[5], [6], [2]] diff --git a/labs02/task07.py b/labs02/task07.py index 80cbd37..8530865 100644 --- a/labs02/task07.py +++ b/labs02/task07.py @@ -5,8 +5,9 @@ Napisz funkcję char_sum, która dla zadanego łańcucha zwraca sumę kodów ASCII znaków. """ + def char_sum(text): - pass + return sum(ord(i) for i in text) def tests(f): inputs = [["this is a string"], ["this is another string"]] diff --git a/labs02/task08.py b/labs02/task08.py index 252b10d..cd536cd 100644 --- a/labs02/task08.py +++ b/labs02/task08.py @@ -6,8 +6,18 @@ Napisz funkcję sum_div35(n), która zwraca sumę wszystkich liczb podzielnych przez 3 lub 5 mniejszych niż n. """ +#Napisz funkcję sum_div35(n), która zwraca sumę wszystkich liczb podzielnych przez 3 lub 5 mniejszych niż n. Np. wynikiem sum_div35(10) powinno być 23. + + def sum_div35(n): - pass + i, suma = 1, 0 + for i in range(1, n): + if not (i % 3 and i % 5): + suma += i + i += 1 + return suma +sum_div35(10) + def tests(f): inputs = [[10], [100], [3845]] diff --git a/labs02/task09.py b/labs02/task09.py index 9045054..545205b 100644 --- a/labs02/task09.py +++ b/labs02/task09.py @@ -8,8 +8,9 @@ Np. leet('leet') powinno zwrócić '1337'. """ -def leet_speak(text): - pass +def leet_speak(tekst): + return tekst.replace('o', '0').replace('l', '1').replace('e', '3').replace('t', '7') + def tests(f): diff --git a/labs02/task10.py b/labs02/task10.py index 58d40d2..9f42592 100644 --- a/labs02/task10.py +++ b/labs02/task10.py @@ -9,7 +9,23 @@ na wielką. Np. pokemon_speak('pokemon') powinno zwrócić 'PoKeMoN'. def pokemon_speak(text): - pass + value = '' + b = True + for i in text: + value += i.upper() if b else i.lower() + b = not b + if i.isupper() == True: + return text + else: + return value + + +pokemon_speak('pokemon') +pokemon_speak('do not want') +pokemon_speak('POKEMON') + +#DLACZEGO WYSWIETLA ERROR SKORO PROGRAM DZIALA PRAWIDLOWO ?????? + def tests(f): diff --git a/labs02/task11.py b/labs02/task11.py index 7d36767..155c5a3 100644 --- a/labs02/task11.py +++ b/labs02/task11.py @@ -9,7 +9,13 @@ Oba napisy będą składać się wyłacznie z małych liter. """ def common_chars(string1, string2): - pass + txt1 = string1.replace(' ','') + txt2 = string2.replace(' ','') + + return list(''.join(sorted(set(txt1) & set(txt2)))) + + + def tests(f): diff --git a/labs03/Podstawy 2.ipynb b/labs03/Podstawy 2.ipynb index adf5795..53da94e 100644 --- a/labs03/Podstawy 2.ipynb +++ b/labs03/Podstawy 2.ipynb @@ -49,34 +49,22 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2\n", - "[1, 2, 3, 1, 2, 3]\n", - "123\n" - ] - } - ], + "outputs": [], "source": [ - "def dwojak(x): \n", - " x *= 2\n", - " return x\n", + "def dwojak(x): x *= 2\n", " \n", "l = [1, 2, 3]\n", "s = \"123\"\n", "\n", "dwojak(l)\n", "dwojak(s)\n", - "print(dwojak(1))\n", + "\n", "print(l)\n", "print(s)" ] @@ -116,28 +104,16 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, 1, 2, 3]\n", - "F: [1, 2, 3, 1, 2, 3]\n", - "[1, 2, 3]\n" - ] - } - ], + "outputs": [], "source": [ "def dwojak1(x): x *= 2\n", - "def dwojak2(x): \n", - " x = x * 2\n", - " print(\"F:\", x)\n", + "def dwojak2(x): x = x * 2\n", "\n", "l = [1,2, 3]\n", "dwojak1(l)\n", @@ -150,47 +126,29 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3]\n", - "[1, 2, 3, 4]\n" - ] - } - ], + "outputs": [], "source": [ "l = [1, 2, 3]\n", - "e = l[:]\n", + "e = l\n", "e.append(4)\n", - "print(l)\n", - "print(e)" + "print(l)" ] }, { "cell_type": "code", - "execution_count": 19, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[[1], [1], [1]]\n" - ] - } - ], + "outputs": [], "source": [ "e = []\n", "f = [e for i in range(3)]\n", @@ -214,39 +172,18 @@ }, { "cell_type": "code", - "execution_count": 25, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "(1, 'napis', [0])\n", - "3\n" - ] - }, - { - "ename": "TypeError", - "evalue": "unhashable type: 'list'", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m{\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;31mTypeError\u001b[0m: unhashable type: 'list'" - ] - } - ], + "outputs": [], "source": [ - "t = (1, \"napis\", [])\n", - "t[-1].append(0)\n", + "t = (1, \"napis\", None)\n", + "elem = t[0]\n", "print(t)\n", - "print(len(t))\n", - "print({t: None})" + "print(len(t))" ] }, { @@ -262,29 +199,19 @@ }, { "cell_type": "code", - "execution_count": 36, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "15\n", - "a == 1\n", - "b == (3, 4)\n" - ] - } - ], + "outputs": [], "source": [ "def suma(*args):\n", " return sum(args)\n", "print(suma(1,2,3,4,5))\n", "\n", - "def greet_me(z=None,**kwargs):\n", + "def greet_me(**kwargs):\n", " if kwargs is not None:\n", " for key, value in kwargs.items():\n", " print(\"%s == %s\" %(key,value))\n", @@ -304,32 +231,16 @@ }, { "cell_type": "code", - "execution_count": 38, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "97\n", - "a\n", - "98\n", - "b\n", - "99\n", - "c\n", - "100\n", - "d\n" - ] - } - ], + "outputs": [], "source": [ "def alfaRange(x, y):\n", " for i in range(ord(x), ord(y)):\n", - " print(i)\n", " yield chr(i)\n", "\n", "for c in alfaRange('a', 'e'):\n", @@ -349,74 +260,40 @@ }, { "cell_type": "code", - "execution_count": 45, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "W Paryżu najlepsze kasztany są na placu Pigalle\n", - "Zuzanna lubi je tylko jesienią.\n", - "\n", - ">>\n" - ] - } - ], + "outputs": [], "source": [ "plik = open(\"haslo.txt\", 'r')\n", "for linia in plik.readlines():\n", " print(linia.strip())\n", "print(plik.read())\n", - "print(\">>\")\n", "plik.close()" ] }, { "cell_type": "code", - "execution_count": 47, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "W Paryżu najlepsze kasztany są na placu Pigalle\n", - "\n", - "Zuzanna lubi je tylko jesienią.\n", - "\n" - ] - }, - { - "ename": "ValueError", - "evalue": "I/O operation on closed file.", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mlinia\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mplik\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mreadlines\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlinia\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mplik\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;31mValueError\u001b[0m: I/O operation on closed file." - ] - } - ], + "outputs": [], "source": [ "with open(\"haslo.txt\", 'r') as plik:\n", " for linia in plik.readlines():\n", " print(linia)\n", - "print(plik.read())" + "# print(plik.read())" ] }, { "cell_type": "code", - "execution_count": 48, + "execution_count": null, "metadata": { "collapsed": true, "slideshow": { @@ -457,22 +334,13 @@ }, { "cell_type": "code", - "execution_count": 49, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "posix\n", - "Nazwa uzytkownika: tomaszd\n" - ] - } - ], + "outputs": [], "source": [ "import os\n", "print(os.name)\n", @@ -483,31 +351,13 @@ }, { "cell_type": "code", - "execution_count": 50, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Counter({'o': 4, 'n': 4, 'a': 4, 'k': 3, 't': 3, 'y': 2, 'i': 2, 'c': 2, 'z': 2, 's': 1, 'p': 1, 'l': 1, 'ń': 1, 'w': 1, 'e': 1})\n" - ] - }, - { - "data": { - "text/plain": [ - "array([[ 1., 3., 4., 5.]], dtype=float32)" - ] - }, - "execution_count": 50, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "from collections import *\n", "print(Counter(\"konstantynopolitańczykowianeczka\"))\n", @@ -544,23 +394,13 @@ }, { "cell_type": "code", - "execution_count": 51, + "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "What's your name?\n", - "Tomasz\n", - "Welcome home, Tomasz.\n" - ] - } - ], + "outputs": [], "source": [ "name = input(\"What's your name?\\n\")\n", "print(\"Welcome home, {}.\".format(name))" diff --git a/labs03/task05.py b/labs03/task05.py new file mode 100644 index 0000000..07e3f98 --- /dev/null +++ b/labs03/task05.py @@ -0,0 +1,38 @@ +""" +ćwiczenie 5 Katalog scores zawiera 64 pliki tekstowe, które posiadają informacje o wysokości miary BLEU na różnych etapach trenowania modelu. +Nazwa każdego pliku na postać model.iterXXXXXXX.npz.bleu, gdzie XXXXXXX, to liczba iteracji. +Zawartość każdego pliku jest podobna i ma następującą formę: BLEU = YY.YY, 44.4/18.5/9.3/5.0 (BP=1.000, ratio=1.072, hyp_len=45976, ref_len=42903), +gdzie YY.YY to wartość miary BLEU. Znajdź plik, który zawiera najwyższą wartość miary BLEU. + +Wykorzystaj bibliotekę glob (https://docs.python.org/2/library/glob.html) +Wyświetl tylko pełną nazwe pliku (wraz z ścieżką). + +""" + +import glob + +def maxBleu(dir = './scores/', retmax = False): + maxbleu, fmax = None, None + for fn in glob.glob(dir+'model.iter*.npz.bleu'): + with open(fn, 'r') as f: + nmax = f.readline().replace(',', '').split(' ')[2] + if (maxbleu is None) or (float(maxbleu) < float(nmax)): + maxbleu = nmax + fmax = fn + else: + pass + if retmax: + retval = fmax+' : '+maxbleu + else: + retval = fmax + return retval + +if __name__ == "__main__": +#print(maxBleu(retmax = True)) + print(maxBleu()) + + + + + + diff --git a/labs04/Klasy.ipynb b/labs04/Klasy.ipynb index 1cd0a99..bb3dbee 100644 --- a/labs04/Klasy.ipynb +++ b/labs04/Klasy.ipynb @@ -309,13 +309,13 @@ { "ename": "AttributeError", "evalue": "'Parser' object has no attribute '__parse'", - "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mparser\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mParser\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mparser\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0mparser\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__parse\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m: 'Parser' object has no attribute '__parse'" - ] + ], + "output_type": "error" } ], "source": [ @@ -465,13 +465,13 @@ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'nieistniejący_plik.txt'", - "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"nieistniejący_plik.txt\"\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mplik\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mplik\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'nieistniejący_plik.txt'" - ] + ], + "output_type": "error" } ], "source": [ @@ -614,13 +614,13 @@ { "ename": "MyError", "evalue": "Coś poszło nie tak!", - "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mMyError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mMyError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Coś poszło nie tak!\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mMyError\u001b[0m: Coś poszło nie tak!" - ] + ], + "output_type": "error" } ], "source": [ diff --git a/labs04/task03.py b/labs04/task03.py index 88741a4..dbb4a1b 100644 --- a/labs04/task03.py +++ b/labs04/task03.py @@ -1,3 +1,80 @@ #!/usr/bin/env python2 # -*- coding: utf-8 -*- +""" +**ćwiczenie 3 (zadanie domowe) ** +Stwórz klasę ``Point``, która będzie reprezentować punkt w przestrzeni wielowymiarowej: + * Konstruktor ma przyjąc tylko 1 parametr: listę współrzednych. Wykorzystaj funkcję z pierwszego zadania, żeby sprawdzić, czy lista zawiera wyłącznie liczby. + * Napisz metodę add, która dida dwa punkty po współrzędnych i zwróci obiekt typu ``Punkt``. + Zaimplementuj własny wyjątek ``DimensionError``, który zostaje wyrzucony, jeżeli dodawany punkt ma inny wymiar. + * Napisz metodę ``to\_string``, która zwróci łancuch znakowy, który w czytelny sposób przedstawi punkt. + * Napisz metodę __len__, która zwróci liczbę współrzędnych punktu. Zobacz, czy możesz teraz wywołać funkcję len na obiekcie typy punkt. + * Napisz metodę __str__, która bedzie działać dokładnie tak samo jak metoda ``to_string``. Wyświetl obiekt typy Point korzystając z funkcji print. +""" + +class DimensionError(Exception): + """Klasa reprezentująca wyjątek ilości współrzędnych <> 3""" + def __init__(self, text): + self.text = text + def __str__(self): + return self.text + +class Point: + """Klasa reprezentująca punkt w 3D. + Pola publiczne: + x, y , z - współrzędne punktu w 3 D + """ + + def __is_numeric(self, my_list): + """Zwraca True jeśli podana lista argumentów ma dokładnie 3 elementy typu int lub float + argument my_list - lista 3 współrzednych liczbowych typu int lub float""" + for item in my_list: + if not (isinstance(item, int) or isinstance(item, float)): + return False + return True and len(my_list) > 0 + + def __init__(self, xyz): + """Konstruktor klasy Point + argument xyz - lista współrzędnych punktu w 3D. Musi zawierać 3 współrzędne! + """ + if not self.__is_numeric(xyz): + raise DimensionError("Invalid coordindates!. Check the numbers!") + if len(xyz) != 3: + raise DimensionError("Invalid number of coordindates! (<> 3)") + self.x = xyz[0] + self.y = xyz[1] + self.z = xyz[2] + + def to_string(self): + """Wypisuje wektor współrzędnych punktu w 3D jako string""" + return '[' + ','.join([str(self.x), str(self.y), str(self.z)]) + ']' + + + def add(oPoint1, oPoint2): + """Metoda statyczna klasy Point. Zwraca sumę współrzędnych danych 2 punktów w 3D. + arg1 - obiekt klasy Punkt + arg2 - obiekt klasy Punkt + """ + l1 = [oPoint1.x, oPoint1.y, oPoint1.z] + l2 = [oPoint2.x, oPoint2.y, oPoint2.z] + nl = [c1+c2 for c1, c2 in zip(l1, l2)] + return Point(nl) + + + def __len__(self): + """Zwraca liczbę współrzędnych = 3 bo punkt w przestrzeni 3D :-)""" + return 3 + + def __str__(self): + """Funkcja string dla klasy Point. Wypisuje współrzędne punktu jako string""" + return self.to_string() + +#################################################### + +if __name__ == "__main__": + p1 = Point([1, 2, 3]) + print('p1 =', p1) + p2 = Point([-3, 0, -2]) + print('p2 =', p2) + p3 = Point.add(p1, p2) + print('p3 = p1 (+) p2 = ', p3) \ No newline at end of file diff --git a/labs04/zad1_lab4.py b/labs04/zad1_lab4.py new file mode 100644 index 0000000..4476703 --- /dev/null +++ b/labs04/zad1_lab4.py @@ -0,0 +1,11 @@ +''' +**ćwiczenie 1** +Napisz funckję ``is_numeric``, która sprawdzi, czy każdy element z przekazanej listy jest typu int lub float. +Wykorzystaj funcję ``isinstance()`` (https://docs.python.org/2/library/functions.html#isinstance). +''' + +def is_numeric(x): + + return ( isinstance(x, (int, float))) + +in_numeric(5) \ No newline at end of file diff --git a/labs04/zad2_lab4.py b/labs04/zad2_lab4.py new file mode 100644 index 0000000..affa000 --- /dev/null +++ b/labs04/zad2_lab4.py @@ -0,0 +1,45 @@ +''' +**ćwiczenie 2** +Napisz prostą hierarchię klas: + * Klasa bazowa ``Employee``, która będzie zawierać informacje o imieniu i nazwisku pracownika. Ponadto każdy pracownik otrzyma numer ``id``, który będzie unikatowy. + Wykorzystaj do tego atrybut statyczny. Napisz metodę ``get_id``, która zwraca identyfikator pracownika. + * Klasy pochodna: ``Recruiter``, która ma dodatkową mtodę ``recruit``, która jako parament przyjmuje obiekt ``Employee`` i zapisuje jego ``id`` w liście ``self.recruited``. + * Klasa pochodna ``Programmer``. Klasa ``Programmer`` ma przyjąć w konstruktorze podstawowe informacje (imię i nazwisko) oraz obiekt rekturera. + Ponadto stwórz atrybut ``recruiter``, który będzie przechowywać ``id`` rekrutera. +''' + +class Employee: + ID_COUNTER = 1000 + + def __init__(self, first_name, second_name): + self.first_name = first_name + self.second_name = second_name + self.id = Employee.ID_COUNTER + Employee.ID_COUNTER += 1 + + def get_id(self): + return self.id + +class Recruiter(Employee): + def __init__(self, first_name, second_name): + Employee.__init__(self, first_name, second_name) + self.recruited = [] + + def recruit(self, employee): + self.recruited.append(employee.get_id()) + + +class Programmer(Employee): + def __init__(self, first_name, second_name, recruiter): + Employee.__init__(self, first_name, second_name) + self.recruiter = recruiter.get_id() + +employee1 = Employee('John', 'Smith') +print(employee1.get_id()) +employee2 = Employee('Bob', 'Marley') +print(employee2.get_id()) + +recruiter1 = Recruiter('Recruiter', 'Andy') +recruiter1.recruit(employee1) + +programmer1 = Programmer('Programmer', 'Frank', recruiter1) diff --git a/labs04/zad3_lab4.py b/labs04/zad3_lab4.py new file mode 100644 index 0000000..eed2464 --- /dev/null +++ b/labs04/zad3_lab4.py @@ -0,0 +1,62 @@ +''' +**ćwiczenie 3 (zadanie domowe) ** +Stwórz klasę ``Point``, która będzie reprezentować punkt w przestrzeni wielowymiarowej: + * Konstruktor ma przyjąc tylko 1 parametr: listę współrzednych. Wykorzystaj funkcję z pierwszego zadania, żeby sprawdzić, czy lista zawiera wyłącznie liczby. + * Napisz metodę add, która dida dwa punkty (dwa wektory) po współrzędnych i zwróci obiekt typu ``Punkt``. Zaimplementuj własny wyjątek ``DimensionError``, który zostaje wyrzucony, jeżeli dodawany punkt ma inny wymiar. + * Napisz metodę ``to\_string``, która zwróci łancuch znakowy, który w czytelny sposób przedstawi punkt. + * Napisz metodę __len__, która zwróci liczbę współrzędnych punktu. Zobacz, czy możesz teraz wywołać funkcję len na obiekcie typy punkt. + * Napisz metodę __str__, która bedzie działać dokładnie tak samo jak metoda ``to_string``. Wyświetl obiekt typy Point korzystając z funkcji print. +''' + + +class DimensionError(Exception): + pass + + +def validate_list(list_arg): + return sum([not (type(element) is int or type(element) is float) for element in list_arg]) == 0 + + +class Point: + def __init__(self, coords): + if validate_list(coords): + self.coords = coords[:] + else: + self.coords = [0] + + def add(self, point_right): + n = len(self.coords) + + if n != len(point_right): + raise DimensionError("Wymiary punktów się nie zgadzają.") + + return Point([self.coords[i] + point_right.coords[i] for i in range(n)]) + + def to_string(self): + return '(' + ', '.join(map(str, self.coords)) + ')' + + def __len__(self): + return len(self.coords) + + def __str__(self): + return self.to_string() + + +# testowanie + +p1 = Point([1, 2, 3]) +p2 = Point([4, 5, 6]) + +print(p1.to_string()) +print(p2.to_string()) + +print(str(p1.add(p2))) +print(len(p1)) +print(Point(['1'])) + +try: + p1.add(Point([1])) +except: + print('wyjątek') + +