Compare commits

...

6 Commits

25 changed files with 644 additions and 272 deletions

View File

@ -54,7 +54,7 @@
"print(3.14)\n", "print(3.14)\n",
"print(123456789 * 987654321)\n", "print(123456789 * 987654321)\n",
"print(10 ** 20)\n", "print(10 ** 20)\n",
"print(12 ** (3 + 4 *(567 % 8) / 9))\n", "print(12 ** (3 + 4 *(567 % 8) / 9)) # % modulo\n",
"print(\"PI\", \"jest równe \", 3.1415)" "print(\"PI\", \"jest równe \", 3.1415)"
] ]
}, },
@ -159,6 +159,27 @@
"print(type(czy_lubie_pythona))" "print(type(czy_lubie_pythona))"
] ]
}, },
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
@ -621,6 +642,13 @@
" print(znak, ord(znak))" " print(znak, ord(znak))"
] ]
}, },
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,

View File

@ -31,21 +31,6 @@
" * Prawie 10-letnia przygoda z Pythonem" " * Prawie 10-letnia przygoda z Pythonem"
] ]
}, },
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Warunki zaliczenia\n",
" * Od tej edycji zajęcia z Pythona są osobnym przedmiotem.\n",
" * Ocena na podstawie zadań domowych.\n",
" * Termin na zadania domowe to prawie 2 tygodnie.\n",
" * Więcej na drugiej godzinie zajęć."
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
@ -113,6 +98,31 @@
" Motywacje zaczerpnięte m.in. z [5 Reasons why Python is Powerful Enough for Google](https://www.codefellows.org/blog/5-reasons-why-python-is-powerful-enough-for-google)." " Motywacje zaczerpnięte m.in. z [5 Reasons why Python is Powerful Enough for Google](https://www.codefellows.org/blog/5-reasons-why-python-is-powerful-enough-for-google)."
] ]
}, },
{
"cell_type": "markdown",
"metadata": {},
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Warunki zaliczenia\n",
" * Od tej edycji zajęcia z Pythona są osobnym przedmiotem.\n",
" * Ocena na podstawie zadań domowych.\n",
" * Termin na zadania domowe to prawie 2 tygodnie.\n",
" * Więcej na drugiej godzinie zajęć."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
},
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,

View File

@ -7,7 +7,7 @@ która zawiera tylko elementy z list o parzystych indeksach.
""" """
def even_elements(lista): def even_elements(lista):
pass return lista[::2]
def tests(f): def tests(f):

View File

@ -5,8 +5,12 @@
Napisz funkcję days_in_year zwracającą liczbę dni w roku (365 albo 366). Napisz funkcję days_in_year zwracającą liczbę dni w roku (365 albo 366).
""" """
def days_in_year(days): def days_in_year(years):
pass if years % 4 == 0 and years % 100 != 0 or years % 400 == 0:
return 366
else:
return 365
def tests(f): def tests(f):
inputs = [[2015], [2012], [1900], [2400], [1977]] inputs = [[2015], [2012], [1900], [2400], [1977]]

View File

@ -13,8 +13,13 @@ jak 'set', która przechowuje elementy bez powtórzeń.)
def oov(text, vocab): def oov(text, vocab):
pass text_list = text.casefold().replace("(", "").replace(",", "").replace("[", "").replace(" "," ").split(" ")
set_text = set(text_list)
string_vocab = str()
for i in vocab:
string_vocab +=i.lower()+" "
vocab_list = string_vocab.replace(",", "").split(" ")
return list(set(text_list) - set(vocab_list))
def tests(f): def tests(f):

View File

@ -6,8 +6,23 @@ Napisz funkcję sum_from_one_to_n zwracającą sume liczb od 1 do n.
Jeśli podany argument jest mniejszy od 1 powinna być zwracana wartość 0. Jeśli podany argument jest mniejszy od 1 powinna być zwracana wartość 0.
""" """
"""
def sum_from_one_to_n(n): def sum_from_one_to_n(n):
pass if n>=0:
return n*(n+1)/2
else:
return 0
"""
def sum_from_one_to_n(n):
if n>=0:
suma = 0
for i in range(n):
suma+=i+1
return suma
else:
return 0
def tests(f): def tests(f):

View File

@ -9,8 +9,10 @@ trzyelementowe listy liczb zmiennoprzecinkowych.
np. odległość pomiędzy punktami (0, 0, 0) i (3, 4, 0) jest równa 5. np. odległość pomiędzy punktami (0, 0, 0) i (3, 4, 0) jest równa 5.
""" """
import math
def euclidean_distance(x, y): def euclidean_distance(x, y):
pass return math.sqrt(pow(x[0]-y[0],2)+pow(x[1]-y[1],2)+pow(x[2]-y[2],2))
def tests(f): def tests(f):
inputs = [[(2.3, 4.3, -7.5), (2.3, 8.5, -7.5)]] inputs = [[(2.3, 4.3, -7.5), (2.3, 8.5, -7.5)]]

View File

@ -10,7 +10,10 @@ ma być zwracany napis "It's not a Big 'No!'".
""" """
def big_no(n): def big_no(n):
pass if n>=5:
return "N"+"O"*n+"!"
else:
return "It's not a Big 'No!'"
def tests(f): def tests(f):
inputs = [[5], [6], [2]] inputs = [[5], [6], [2]]

View File

@ -6,7 +6,11 @@ Napisz funkcję char_sum, która dla zadanego łańcucha zwraca
sumę kodów ASCII znaków. sumę kodów ASCII znaków.
""" """
def char_sum(text): def char_sum(text):
pass suma = 0
for i in text:
suma+=ord(i)
return suma
def tests(f): def tests(f):
inputs = [["this is a string"], ["this is another string"]] inputs = [["this is a string"], ["this is another string"]]

View File

@ -7,7 +7,11 @@ przez 3 lub 5 mniejszych niż n.
""" """
def sum_div35(n): def sum_div35(n):
pass suma = 0
for i in range(n-1):
if (i+1) % 3 == 0 or (i+1) % 5 == 0:
suma+=i+1
return suma
def tests(f): def tests(f):
inputs = [[10], [100], [3845]] inputs = [[10], [100], [3845]]

View File

@ -9,7 +9,7 @@ Np. leet('leet') powinno zwrócić '1337'.
def leet_speak(text): def leet_speak(text):
pass return text.replace("e","3").replace("l","1").replace("o","0").replace("t","7")
def tests(f): def tests(f):

View File

@ -9,7 +9,13 @@ na wielką. Np. pokemon_speak('pokemon') powinno zwrócić 'PoKeMoN'.
def pokemon_speak(text): def pokemon_speak(text):
pass text2= str()
for i, t in enumerate(text):
if i % 2 == 0:
text2 += t.upper()
else:
text2 += t
return text2
def tests(f): def tests(f):

View File

@ -9,8 +9,7 @@ Oba napisy będą składać się wyłacznie z małych liter.
""" """
def common_chars(string1, string2): def common_chars(string1, string2):
pass return sorted(list(set(string1).intersection(set(string2)).difference(set(" "))))
def tests(f): def tests(f):
inputs = [["this is a string", "ala ma kota"]] inputs = [["this is a string", "ala ma kota"]]

View File

@ -3,9 +3,6 @@
def suma(a, b): def suma(a, b):
"""
Napisz funkcję, która zwraca sumę elementów.
"""
return a + b return a + b
def tests(f): def tests(f):

View File

@ -49,34 +49,22 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 9, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"[1, 2, 3, 1, 2, 3]\n",
"123\n"
]
}
],
"source": [ "source": [
"def dwojak(x): \n", "def dwojak(x): x *= 2\n",
" x *= 2\n",
" return x\n",
" \n", " \n",
"l = [1, 2, 3]\n", "l = [1, 2, 3]\n",
"s = \"123\"\n", "s = \"123\"\n",
"\n", "\n",
"dwojak(l)\n", "dwojak(l)\n",
"dwojak(s)\n", "dwojak(s)\n",
"print(dwojak(1))\n", "\n",
"print(l)\n", "print(l)\n",
"print(s)" "print(s)"
] ]
@ -116,7 +104,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 11, "execution_count": 2,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -127,17 +115,13 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"[1, 2, 3, 1, 2, 3]\n", "[1, 2, 3, 1, 2, 3]\n[1, 2, 3]\n"
"F: [1, 2, 3, 1, 2, 3]\n",
"[1, 2, 3]\n"
] ]
} }
], ],
"source": [ "source": [
"def dwojak1(x): x *= 2\n", "def dwojak1(x): x *= 2\n",
"def dwojak2(x): \n", "def dwojak2(x): x = x * 2\n",
" x = x * 2\n",
" print(\"F:\", x)\n",
"\n", "\n",
"l = [1,2, 3]\n", "l = [1,2, 3]\n",
"dwojak1(l)\n", "dwojak1(l)\n",
@ -150,7 +134,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 17, "execution_count": 3,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -161,22 +145,20 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"[1, 2, 3]\n",
"[1, 2, 3, 4]\n" "[1, 2, 3, 4]\n"
] ]
} }
], ],
"source": [ "source": [
"l = [1, 2, 3]\n", "l = [1, 2, 3]\n",
"e = l[:]\n", "e = l\n",
"e.append(4)\n", "e.append(4)\n",
"print(l)\n", "print(l)"
"print(e)"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 19, "execution_count": 4,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -214,7 +196,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 25, "execution_count": 5,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -225,28 +207,15 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"(1, 'napis', [0])\n", "(1, 'napis', None)\n3\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<ipython-input-25-2bd2fa17fbf5>\u001b[0m in \u001b[0;36m<module>\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'"
] ]
} }
], ],
"source": [ "source": [
"t = (1, \"napis\", [])\n", "t = (1, \"napis\", None)\n",
"t[-1].append(0)\n", "elem = t[0]\n",
"print(t)\n", "print(t)\n",
"print(len(t))\n", "print(len(t))"
"print({t: None})"
] ]
}, },
{ {
@ -262,7 +231,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 36, "execution_count": 6,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -273,9 +242,7 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"15\n", "15\na == 1\nb == (3, 4)\n"
"a == 1\n",
"b == (3, 4)\n"
] ]
} }
], ],
@ -284,7 +251,7 @@
" return sum(args)\n", " return sum(args)\n",
"print(suma(1,2,3,4,5))\n", "print(suma(1,2,3,4,5))\n",
"\n", "\n",
"def greet_me(z=None,**kwargs):\n", "def greet_me(**kwargs):\n",
" if kwargs is not None:\n", " if kwargs is not None:\n",
" for key, value in kwargs.items():\n", " for key, value in kwargs.items():\n",
" print(\"%s == %s\" %(key,value))\n", " print(\"%s == %s\" %(key,value))\n",
@ -304,7 +271,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 38, "execution_count": 7,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -315,21 +282,13 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"97\n", "a\nb\nc\nd\n"
"a\n",
"98\n",
"b\n",
"99\n",
"c\n",
"100\n",
"d\n"
] ]
} }
], ],
"source": [ "source": [
"def alfaRange(x, y):\n", "def alfaRange(x, y):\n",
" for i in range(ord(x), ord(y)):\n", " for i in range(ord(x), ord(y)):\n",
" print(i)\n",
" yield chr(i)\n", " yield chr(i)\n",
"\n", "\n",
"for c in alfaRange('a', 'e'):\n", "for c in alfaRange('a', 'e'):\n",
@ -349,7 +308,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 45, "execution_count": 8,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -360,63 +319,37 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"W Paryżu najlepsze kasztany są na placu Pigalle\n", "W Paryżu najlepsze kasztany są na placu Pigalle\nZuzanna lubi je tylko jesienią.\n\n"
"Zuzanna lubi je tylko jesienią.\n",
"\n",
">>\n"
] ]
} }
], ],
"source": [ "source": [
"plik = open(\"haslo.txt\", 'r')\n", "plik = open(\"J:\\PycharmProjects\\Python2017\\labs03\\haslo.txt\", 'r')\n",
"for linia in plik.readlines():\n", "for linia in plik.readlines():\n",
" print(linia.strip())\n", " print(linia.strip())\n",
"print(plik.read())\n", "print(plik.read()) # odczytuje \n",
"print(\">>\")\n",
"plik.close()" "plik.close()"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 47, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [ "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<ipython-input-47-f06513c1bbec>\u001b[0m in \u001b[0;36m<module>\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."
]
}
],
"source": [ "source": [
"with open(\"haslo.txt\", 'r') as plik:\n", "with open(\"haslo.txt\", 'r') as plik:\n",
" for linia in plik.readlines():\n", " for linia in plik.readlines():\n",
" print(linia)\n", " print(linia)\n",
"print(plik.read())" "# print(plik.read())"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 48, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true, "collapsed": true,
"slideshow": { "slideshow": {
@ -457,22 +390,13 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 49, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"posix\n",
"Nazwa uzytkownika: tomaszd\n"
]
}
],
"source": [ "source": [
"import os\n", "import os\n",
"print(os.name)\n", "print(os.name)\n",
@ -483,31 +407,13 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 50, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [ "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"
}
],
"source": [ "source": [
"from collections import *\n", "from collections import *\n",
"print(Counter(\"konstantynopolitańczykowianeczka\"))\n", "print(Counter(\"konstantynopolitańczykowianeczka\"))\n",
@ -544,23 +450,13 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 51, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"What's your name?\n",
"Tomasz\n",
"Welcome home, Tomasz.\n"
]
}
],
"source": [ "source": [
"name = input(\"What's your name?\\n\")\n", "name = input(\"What's your name?\\n\")\n",
"print(\"Welcome home, {}.\".format(name))" "print(\"Welcome home, {}.\".format(name))"

23
labs03/task01.py Normal file
View File

@ -0,0 +1,23 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
lista = [1,2,3,4,5]
print("lista ma id: {}".format(id(lista)))
lista *= 10
lista.append(6)
print("lista ma id: {}".format(id(lista)))
lista.pop(2)
print("lista ma id: {}".format(id(lista)))
lancuch = "a string"
print("lancuch ma id: {}".format(id(lancuch)))
lancuch.capitalize()
print("lancuch ma id: {}".format(id(lancuch)))
lancuch += "!"
print("lancuch ma id: {}".format(id(lancuch)))
liczba = 5.2
print("liczba ma id: {}".format(id(liczba)))
liczba += 2.3
print("liczba ma id: {}".format(id(liczba)))

14
labs03/task02.py Normal file
View File

@ -0,0 +1,14 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def Fibb(n):
f_1 = 1
f_2 = 1
for i in range(0, n):
f_3 = f_1 + f_2
yield f_1
f_1 = f_2
f_2 = f_3
for c in Fibb(10):
print(c)

13
labs03/task03.py Normal file
View File

@ -0,0 +1,13 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests,json
# pobieram zawartość JSON wykorzystując bibliotekę 'requests'
r = requests.get('https://api.fixer.io/latest')
if r.status_code == 200:
# korzystając z biblioteki ``json`` przekształcamy go do obiektu typu JSON.
decoded_js = json.loads(r.text)
print('Kurs EUR do PLN wynosi {}'.format(decoded_js['rates']['PLN']))

70
labs03/task04.py Normal file
View File

@ -0,0 +1,70 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import weather,datetime
def FahrenheitToCelsius(fahrenheit):
return (fahrenheit - 32) / 1.8
#return round((fahrenheit - 32) / 1.8, 1)
def dzien_tygodnia(data):
dni_tygodnia = ["poniedziałek",
"wtorek",
"środa",
"czwartek",
"piatek",
"sobotę",
"niedzielę"]
return dni_tygodnia[data.weekday()]
def miesiaca(data):
miesiace = ["stycznia",
"lutego",
"marca",
"kwietnia",
"maja",
"czerwca",
"lipca",
"śierpnia",
"września",
"października",
"listopada",
"grudnia"]
return miesiace[data.month-1]
pogoda = weather.Weather()
# Yahoo! WOEID dla miasta Poznań 514048
#miejsce = pogoda.lookup(514048)
#stan = miejsce.condition()
#print(stan.text())
# Lookup poprzez podanie nazwy miasta
miejsce = pogoda.lookup_by_location('Poznań')
stan = miejsce.condition()
#print(stan.text())
# prognozy na nadchodzące dni
prognozy = miejsce.forecast()
#print(prognozy)
# wybieram dzień z prognozy pogody w którym bedzie najzimniej
najzimniejszy = min(prognozy, key = lambda prognozy : prognozy.low())
# konwerstuję string na format czasu
datetime_object = datetime.datetime.strptime(najzimniejszy.date(), '%d %b %Y')
#print(datetime_object.get_weekday())
#print(FahrenheitToCelsius(float(najzimniejszy.high())))
#print(FahrenheitToCelsius(float(najzimniejszy.low())))
# korzystając z prognozy, wypisuję dzień, w którym będzie najzimniej.
#
#print 'W {}'.format(dzien_tygodnia(datetime_object))+ ' ' + str(datetime_object.day) + ' ' + miesiaca(datetime_object) + ' ' + str(datetime_object.year) + ' będzie najchłodniej, najniższa możliwa temperatura może wynieść {}'.format(round(FahrenheitToCelsius(float(najzimniejszy.low())),1)) + ' °C'
wydruk = 'W {dt} {d} {m} {r} będzie najchłodniej, najniższa możliwa temperatura może wynieść {t:.1f} °C'
print wydruk.format(dt=dzien_tygodnia(datetime_object),d=str(datetime_object.day), m=miesiaca(datetime_object), r=str(datetime_object.year), t=FahrenheitToCelsius(float(najzimniejszy.low())))

20
labs03/task05.py Normal file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import glob
# funkcja, która wydobywa wartości miary BLEU z pliku o podanej ścieżce
def BLEU(sciezka):
with open(sciezka, 'r') as plik:
for linia in plik.readlines():
lancuch = linia.strip()
#print sciezka + lancuch
return float(lancuch.partition(',')[0].partition('=')[2])
# znajduję nazwę pliku z maksymalną wartościa miary BLEU korzystając z iteratora ścieżek
# do plików o podanej postaci oraz funkcji BLEU
#
#print max(glob.iglob('scores/model.iter*.npz.bleu'), key = BLEU).partition('\\')[2]
#
sciezka = max(glob.iglob('scores/model.iter*.npz.bleu'), key = BLEU)
print 'Największa wartość mary BLEU wynosząca {1} znajduje się w pliku {0}'.format(sciezka.partition('\\')[2],BLEU(sciezka))

View File

@ -43,7 +43,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 11, "execution_count": 1,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -54,8 +54,7 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"0\n", "0\nPython da się lubić !\n"
"Python da się lubić !\n"
] ]
} }
], ],
@ -77,7 +76,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 18, "execution_count": 6,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -88,7 +87,7 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"<class '__main__.NajprostszaKlasa'>\n" "<type 'instance'>\n<type 'instance'>\n"
] ]
} }
], ],
@ -97,7 +96,10 @@
" pass\n", " pass\n",
"\n", "\n",
"nasza_klasa = NajprostszaKlasa() # Uwaga na nawiasy na końcu!\n", "nasza_klasa = NajprostszaKlasa() # Uwaga na nawiasy na końcu!\n",
"print(type(nasza_klasa))" "print(type(nasza_klasa))\n",
"\n",
"nasza_klasa = NajprostszaKlasa # Uwaga na nawiasy na końcu!\n",
"print(type(nasza_klasa()))"
] ]
}, },
{ {
@ -114,7 +116,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 30, "execution_count": 14,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -125,23 +127,26 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"2\n" "2\n<__main__.Punkt instance at 0x00000000049B3CC8>\n"
] ]
} }
], ],
"source": [ "source": [
"class Punkt:\n", "class Punkt:\n",
" def __init__(self, x, y):\n", " def __init__(self, x, y=0):\n",
" self.x = x\n", " self.x = x\n",
" self.y = y\n", " self.y = y\n",
" \n", " \n",
"punkt = Punkt(2, 3)\n", "# self jak this w C\n",
"print(punkt.x)" "\n",
"punkt = Punkt(2)\n",
"print(punkt.x)\n",
"print(punkt)"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 25, "execution_count": 20,
"metadata": { "metadata": {
"collapsed": true, "collapsed": true,
"slideshow": { "slideshow": {
@ -157,13 +162,16 @@
" def liczba_wierzcholkow(self):\n", " def liczba_wierzcholkow(self):\n",
" return len(self.vertexes)\n", " return len(self.vertexes)\n",
" \n", " \n",
" #metoda - jedynym argumentem jest self\n",
" #funkcja - \n",
" \n",
" def dodaj_wierzcholek(self, x):\n", " def dodaj_wierzcholek(self, x):\n",
" self.vertexes.append(x)" " self.vertexes.append(x)"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 26, "execution_count": 22,
"metadata": { "metadata": {
"collapsed": true, "collapsed": true,
"slideshow": { "slideshow": {
@ -172,10 +180,12 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"#dziedziczenie\n",
"\n",
"class Prostokat(Figura):\n", "class Prostokat(Figura):\n",
" def __init__(self, vertexes):\n", " def __init__(self, vertexes):\n",
" super().__init__(vertexes)\n", " super().__init__(vertexes)\n",
" \n", " #lub self.vertexes = vertexes\n",
" def czy_jestem_kwadratem(self):\n", " def czy_jestem_kwadratem(self):\n",
" pass\n", " pass\n",
" " " "
@ -183,7 +193,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 28, "execution_count": 41,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -196,7 +206,7 @@
"3" "3"
] ]
}, },
"execution_count": 28, "execution_count": 41,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
@ -212,7 +222,11 @@
" def __len__(self):\n", " def __len__(self):\n",
" return self.liczba_wierzcholkow()\n", " return self.liczba_wierzcholkow()\n",
" \n", " \n",
"len(Figura([Punkt(2,3), Punkt(3,4), Punkt(0, 0)]))" "len(Figura([Punkt(2,3), Punkt(3,4), Punkt(0, 0)]))\n",
"o = Figura([Punkt(2,3), Punkt(3,4), Punkt(0, 0)])\n",
"len(o)\n",
"o.__len__()\n",
"o.liczba_wierzcholkow()"
] ]
}, },
{ {
@ -228,7 +242,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 4, "execution_count": 33,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -246,7 +260,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 5, "execution_count": 34,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -257,25 +271,7 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"Help on class Punkt in module __main__:\n", "Help on class Punkt in module __main__:\n\nclass Punkt(__builtin__.object)\n | Klasa reprezentująca punkt w 2D.\n | \n | Methods defined here:\n | \n | __init__(self, x, y)\n | opis argumentów x i y.\n | \n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n\n"
"\n",
"class Punkt(builtins.object)\n",
" | Klasa reprezentująca punkt w 2D.\n",
" | \n",
" | Methods defined here:\n",
" | \n",
" | __init__(self, x, y)\n",
" | opis argumentów x i y.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data descriptors defined here:\n",
" | \n",
" | __dict__\n",
" | dictionary for instance variables (if defined)\n",
" | \n",
" | __weakref__\n",
" | list of weak references to the object (if defined)\n",
"\n"
] ]
} }
], ],
@ -309,13 +305,13 @@
{ {
"ename": "AttributeError", "ename": "AttributeError",
"evalue": "'Parser' object has no attribute '__parse'", "evalue": "'Parser' object has no attribute '__parse'",
"output_type": "error",
"traceback": [ "traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-6-80ee186598d3>\u001b[0m in \u001b[0;36m<module>\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;32m<ipython-input-6-80ee186598d3>\u001b[0m in \u001b[0;36m<module>\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'" "\u001b[0;31mAttributeError\u001b[0m: 'Parser' object has no attribute '__parse'"
] ],
"output_type": "error"
} }
], ],
"source": [ "source": [
@ -340,7 +336,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 7, "execution_count": 42,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -348,13 +344,15 @@
}, },
"outputs": [ "outputs": [
{ {
"name": "stdout", "ename": "TypeError",
"output_type": "stream", "evalue": "instance has no next() method",
"text": [ "traceback": [
"<__main__.Punkt object at 0x7f728015b358>\n", "\u001b[1;31m\u001b[0m",
"<__main__.Punkt object at 0x7f728015b4a8>\n", "\u001b[1;31mTypeError\u001b[0mTraceback (most recent call last)",
"<__main__.Punkt object at 0x7f728015b438>\n" "\u001b[1;32m<ipython-input-42-c424f51c19dc>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 13\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvertexes\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 14\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 15\u001b[1;33m \u001b[1;32mfor\u001b[0m \u001b[0mv\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mFigura\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mPunkt\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mPunkt\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mPunkt\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 16\u001b[0m \u001b[1;32mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mv\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
] "\u001b[1;31mTypeError\u001b[0m: instance has no next() method"
],
"output_type": "error"
} }
], ],
"source": [ "source": [
@ -390,7 +388,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 16, "execution_count": 1,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -401,8 +399,7 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"0\n", "79384200\n48959560\n0\n0\n"
"0\n"
] ]
} }
], ],
@ -411,13 +408,23 @@
" atrybut = 0\n", " atrybut = 0\n",
"\n", "\n",
"klasa = Klasa()\n", "klasa = Klasa()\n",
"#klasa2 = Klasa\n",
"#klasa2.atrybut=1\n",
"print(id(Klasa))\n",
"klasa2 = Klasa()\n",
"print(id(klasa2))\n",
"klasa2.atrybut=1\n",
"\n",
"print(Klasa.atrybut) \n", "print(Klasa.atrybut) \n",
"print(klasa.atrybut)" "#atrybut wspólny dla wszystkich instancji\n",
"print(klasa.atrybut)\n",
"\n",
"klasa.temp = []"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 19, "execution_count": 62,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -425,11 +432,15 @@
}, },
"outputs": [ "outputs": [
{ {
"name": "stdout", "ename": "TypeError",
"output_type": "stream", "evalue": "unbound method metoda() must be called with Klasa instance as first argument (got nothing instead)",
"text": [ "traceback": [
"Jestem statyczna!\n" "\u001b[1;31m\u001b[0m",
] "\u001b[1;31mTypeError\u001b[0mTraceback (most recent call last)",
"\u001b[1;32m<ipython-input-62-63152cc2cac6>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;32mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Jestem statyczna!\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 8\u001b[1;33m \u001b[0mKlasa\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmetoda\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: unbound method metoda() must be called with Klasa instance as first argument (got nothing instead)"
],
"output_type": "error"
} }
], ],
"source": [ "source": [
@ -437,6 +448,7 @@
" def __init__(self):\n", " def __init__(self):\n",
" self.t = 0\n", " self.t = 0\n",
" def metoda():\n", " def metoda():\n",
" # nie będzie działać self.t = 0\n",
" print(\"Jestem statyczna!\")\n", " print(\"Jestem statyczna!\")\n",
"\n", "\n",
"Klasa.metoda()" "Klasa.metoda()"
@ -455,7 +467,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 20, "execution_count": 1,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -463,15 +475,15 @@
}, },
"outputs": [ "outputs": [
{ {
"ename": "FileNotFoundError", "ename": "IOError",
"evalue": "[Errno 2] No such file or directory: 'nieistniejący_plik.txt'", "evalue": "[Errno 2] No such file or directory: 'nieistniej\\xc4\\x85cy_plik.txt'",
"output_type": "error",
"traceback": [ "traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31m\u001b[0m",
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[1;31mIOError\u001b[0mTraceback (most recent call last)",
"\u001b[0;32m<ipython-input-20-41928d542bef>\u001b[0m in \u001b[0;36m<module>\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[1;32m<ipython-input-1-1bebecf2f5c5>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"nieistniejący_plik.txt\"\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mplik\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0mcontent\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mplik\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'nieistniejący_plik.txt'" "\u001b[1;31mIOError\u001b[0m: [Errno 2] No such file or directory: 'nieistniej\\xc4\\x85cy_plik.txt'"
] ],
"output_type": "error"
} }
], ],
"source": [ "source": [
@ -481,7 +493,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 23, "execution_count": 31,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -489,6 +501,8 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"from pandas.compat import FileNotFoundError\n",
"\n",
"try:\n", "try:\n",
" with open(\"nieistniejący_plik.txt\") as plik:\n", " with open(\"nieistniejący_plik.txt\") as plik:\n",
" content = plik.read()\n", " content = plik.read()\n",
@ -498,7 +512,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 27, "execution_count": 32,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -509,7 +523,7 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"Warning [Errno 2] No such file or directory: 'nieistniejący_plik.txt'\n" "Warning [Errno 2] No such file or directory: 'nieistniej\\xc4\\x85cy_plik.txt'\n"
] ]
} }
], ],
@ -524,7 +538,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 28, "execution_count": 13,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
@ -535,7 +549,7 @@
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"Warning [Errno 2] No such file or directory: 'nieistniejący_plik.txt'\n" "Warning [Errno 2] No such file or directory: 'nieistniej\\xc4\\x85cy_plik.txt'\n"
] ]
} }
], ],
@ -550,7 +564,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 29, "execution_count": 14,
"metadata": { "metadata": {
"collapsed": true, "collapsed": true,
"slideshow": { "slideshow": {
@ -568,25 +582,40 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 30, "execution_count": 19,
"metadata": { "metadata": {
"collapsed": true, "collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [], "outputs": [
{
"ename": "Exception",
"evalue": "Empty list of vertexes",
"traceback": [
"\u001b[1;31m\u001b[0m",
"\u001b[1;31mException\u001b[0mTraceback (most recent call last)",
"\u001b[1;32m<ipython-input-19-0884e4d4e2f2>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvertexes\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mvertexes\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m \u001b[0mfigura\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mFigura\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;32m<ipython-input-19-0884e4d4e2f2>\u001b[0m in \u001b[0;36m__init__\u001b[1;34m(self, vertexes)\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m__init__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mvertexes\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mlen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mvertexes\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Empty list of vertexes\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvertexes\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mvertexes\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mException\u001b[0m: Empty list of vertexes"
],
"output_type": "error"
}
],
"source": [ "source": [
"class Figura:\n", "class Figura:\n",
" def __init__(self, vertexes):\n", " def __init__(self, vertexes):\n",
" if len(vertexes) == 0:\n", " if len(vertexes) == 0:\n",
" raise Exception(\"Empty list of vertexes\")\n", " raise Exception(\"Empty list of vertexes\")\n",
" self.vertexes = vertexes" " self.vertexes = vertexes\n",
" \n",
"figura = Figura([])"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 35, "execution_count": 27,
"metadata": { "metadata": {
"collapsed": true, "collapsed": true,
"slideshow": { "slideshow": {
@ -604,7 +633,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 36, "execution_count": 34,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
@ -614,13 +643,13 @@
{ {
"ename": "MyError", "ename": "MyError",
"evalue": "Coś poszło nie tak!", "evalue": "Coś poszło nie tak!",
"output_type": "error",
"traceback": [ "traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31m\u001b[0m",
"\u001b[0;31mMyError\u001b[0m Traceback (most recent call last)", "\u001b[1;31mMyError\u001b[0mTraceback (most recent call last)",
"\u001b[0;32m<ipython-input-36-4fb306b42ebc>\u001b[0m in \u001b[0;36m<module>\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[1;32m<ipython-input-34-99f654d8334c>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mMyError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Coś poszło nie tak!\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mMyError\u001b[0m: Coś poszło nie tak!" "\u001b[1;31mMyError\u001b[0m: Coś poszło nie tak!"
] ],
"output_type": "error"
} }
], ],
"source": [ "source": [

View File

@ -1,3 +1,21 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import math
def is_numeric(lista):
bool = False
for i in lista:
bool = isinstance(i, int) or isinstance(i, float)
if not bool:
return False
return bool
print(is_numeric([-1,2.1,3]))
print(is_numeric([-1,2.1, '3',3]))
print(is_numeric(['2']))
print(is_numeric([None]))

View File

@ -1,3 +1,57 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import random
random.seed(a=0)
# Klasa bazowa, która zawiera informacje o imieniu i nazwisku pracownika.
# Każdy pracownik posiada unikatowy numer 'id'.
class Employee:
# atrybut statyczny
id = 0
def __init__(self, firstname = 'Anonim', lastname = 'Gal'):
self.firstname = firstname
self.lastname = lastname
self.id = random.randrange(10000000, 50000000, 1)
# Metodę 'get_id', która zwraca identyfikator pracownika.
def get_id(self):
return self.id
# Klasy pochodna posiadająca dodatkową metodę 'recruit', która jako parament przyjmuje
# obiekt 'Employee' i zapisuje jego 'id' w liście 'self.recruited'.
class Recruiter(Employee):
def recruit(self, employee):
self.recruited = employee.get_id()
# Klasa pochodna przyjmuje w konstruktorze podstawowe informacje (imię i nazwisko)
# oraz obiekt rekturera. Ponadto posiada ona atrybut 'recruiter', który będzie
# przechowywał 'id' rekrutera.
class Programmer(Recruiter):
def __init__(self, firstname, lastname, recruiter_obj):
self.firstname = firstname
self.lastname = lastname
self.recruiter = recruiter_obj
recruiter = recruiter_obj.recruited
self.id = random.randrange(50000000, 100000000, 1)
pracownik = Employee('Jurek', 'P')
print pracownik.get_id()
rekruter = Recruiter('Kasia', 'P')
print rekruter.get_id()
rekruter.recruit(pracownik)
print rekruter.get_id()
programista = Programmer('Maciej', 'W', rekruter)
print programista.get_id()
rekruter.recruit(programista)
print rekruter.get_id()
print Employee.id

View File

@ -1,3 +1,75 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import math
# klasa, która reprezentuje punkt w przestrzeni wielowymiarowej.
class Point:
# konstruktor, który ma przyjmyje tylko 1 parametr: listę współrzednych.
def __init__(self,coordinates=[]):
if self.is_numeric(coordinates):
self.coordinates = coordinates
else:
self.coordinates = None
# funkcja sprawdzająca czy lista składa się z samych liczb.
def is_numeric(self, lista):
bool = False
for i in lista:
bool = isinstance(i, int) or isinstance(i, float)
if not bool:
return False
return bool
# metoda, która dodaje dwa punkty po współrzędnych i zwróci obiekt typu 'Punkt'.
def __add__(self, other):
if len(self) == len(other):
return Point(map((lambda x,y: x+y), self.coordinates, other.coordinates))
else:
raise DimensionError("Dodawany punkt ma inny wymiar!")
# metoda zwracająca łancuch znakowy, który w czytelny sposób przedstawi punkt.
def to_string(self):
if self.coordinates == None:
return "()"
else:
return "(" + ", ".join(str(c) for c in self.coordinates) + ")"
# metoda, która zwróci liczbę współrzędnych punktu.
def __len__(self):
if self.coordinates is not None:
return len(self.coordinates)
else:
return 0
# metoda, która działa dokładnie tak samo jak metoda `to_string`.
def __str__(self):
return self.to_string()
# wyjątek `DimensionError`, który zostaje wyrzucony, jeżeli dodawany punkt ma inny wymiar.
class DimensionError(Exception):
def __init__(self, text="Błąd wymiaru!"):
self.text = text
def __str__(self):
return self.text
p_0 = Point([])
print(str(p_0))
print(len(p_0))
p_1 = Point([ 1, 3, 5])
print(p_1)
print(len(p_1))
p_2 = Point([ 1, 2, 4])
print(p_2)
print(len(p_2))
try:
p_sum = p_1.__add__(p_2)
print(p_sum)
print(len(p_sum))
#print(len(str(p_1.__add__(p_2))))
p_sum = p_0.__add__(p_1)
except Exception as ex:
print("Warning: {}".format(ex))

View File

@ -1,14 +1,37 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
plt.rcParams['figure.figsize'] = (10, 7)
import pandas as pd
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from mpl_toolkits.mplot3d import Axes3D
from sklearn.metrics import mean_squared_error, r2_score
# funkcja, która wczyta zestaw danych z pliku *mieszkania.csv* i zwróci obiekt typu *DataFrame*.
def wczytaj_dane(): def wczytaj_dane():
pass dane = pd.read_csv('mieszkania.csv', # ścieżka do pliku
sep=',', # separator
index_col='Id') # ustawienie indeksu na kolumnę Id
return (dane)
def most_common_room_number(dane): def most_common_room_number(dane):
pass return (dane['Rooms'].mode()[0])
def cheapest_flats(dane, n): def cheapest_flats(dane, n):
pass return (dane.nsmallest(n, 'Expected'))
def find_borough(desc): def find_borough(desc):
dzielnice = ['Stare Miasto', dzielnice = ['Stare Miasto',
@ -19,36 +42,99 @@ def find_borough(desc):
'Winogrady', 'Winogrady',
'Miłostowo', 'Miłostowo',
'Dębiec'] 'Dębiec']
pass for i in dzielnice:
if desc.find(i) + 1:
return (i)
return ('Inne')
def add_borough(dane): def add_borough(dane):
pass dane['Borough'] = dane['Location'].apply(find_borough)
return (dane)
def write_plot(dane, filename): def write_plot(dane, filename):
pass fig = plt.figure()
dane.plot(kind='bar')
plt.savefig(filename)
plt.close(fig)
def mean_price(dane, room_number): def mean_price(dane, room_number):
pass return (dane.groupby(['Rooms']).mean()['Expected'][room_number])
def find_13(dane): def find_13(dane):
pass return (dane[dane['Floor'] == 13]['Borough'].tolist())
def find_best_flats(dane, borough='Winogrady', rooms=3, floor=1):
return (dane[(dane['Borough'] == borough) & (dane['Rooms'] == rooms) & (dane['Floor'] == floor)])
def find_best_flats(dane):
pass
def main(): def main():
dane = wczytaj_dane() dane = wczytaj_dane()
print(dane[:5]) print(dane[:5])
print("Najpopularniejsza liczba pokoi w mieszkaniu to: {}" print("Najpopularniejsza liczba pokoi w mieszkaniu to: {}."
.format(most_common_room_number(dane))) .format(most_common_room_number(dane)))
print("{} to najłądniejsza dzielnica w Poznaniu." print('Pięć najtańszych ofert sprzedaży mieszkań: \n{}'
.format(find_borough("Grunwald i Jeżyce")))) .format(cheapest_flats(dane, 5)))
print("{} to najładniejsza dzielnica w Poznaniu."
.format(find_borough("Grunwald i Jeżyce")))
# dane['Borough'] = dane['Location'].apply(find_borough)
dane = add_borough(dane)
write_plot(dane.groupby(['Borough']).count()['Expected'], 'filename')
print('Dzielnice, które zawierają ofertę mieszkanie na 13 piętrze to: {}.'.format(', '.join(find_13(dane))))
print('Średnia cena mieszkania {0}-pokojowego z ofert sprzedaży mieszkań wynosi: {1:.0f} zł.'
.format(3, mean_price(dane, 3)))
# print(find_best_flats(dane))
# Dzielimy dane na dwie części - jedną do uczenia 80% oraz drugą do testowania 20%
dane_X = dane[['SqrMeters', 'Rooms']]
dane_Y = dane[['Expected']]
dane_X_train, dane_X_test, dane_Y_train, dane_Y_test = train_test_split(dane_X,
dane_Y,
test_size=0.2,
random_state=2)
# Tworzymy model regresji wielorakiej, zmienną wyjaśnianą będzie cena
# mieszkania, zmiennymi wyjaśniającymi będą: wielkość mieszkania i liczba
# pokoi
regr = linear_model.LinearRegression()
# Uczymy model korzystając ze zbioru uczącego
regr.fit(dane_X_train, dane_Y_train)
# Współczynniki modelu
print('Współczynniki: {0:.4f} (SqrMeters) {1:.4f} (Rooms)'.format(regr.coef_[0,0],
regr.coef_[0,1]))
# Dokonujemy predykcji korzystając ze zbioru testującego
dane_Y_pred = regr.predict(dane_X_test)
# Test
print('Dopasowanie modelu: {:.4f}'.format(regr.score(dane_X_test, dane_Y_test)))
# Błąd średniokwadratowy
print('Błąd średniokwadratowy: {:.4f}'.format(mean_squared_error(dane_Y_test, dane_Y_pred)))
# Explained variance score: 1 is perfect prediction
print('Variance score: {:.4f}'.format(r2_score(dane_Y_test, dane_Y_pred)))
print("Średnia cena mieszkania 3-pokojowego, to: {}"
.format(mean_price(dane, 3)))
if __name__ == "__main__": if __name__ == "__main__":
main() main()