Compare commits

...

31 Commits

Author SHA1 Message Date
Ewelina c440fa5c25 task02 **dodatkowe (labs06) done 2017-12-27 12:55:29 +01:00
Ewelina 8424251b3c task02 (labs06) done 2017-12-27 12:54:08 +01:00
Ewelina 98aac33f0b task04 (labs05) done 2017-12-26 15:37:41 +01:00
Ewelina 5cac77a2e5 task03 (labs05) done 2017-12-26 15:36:46 +01:00
Ewelina 788d3e4cbf task02 (labs05) done 2017-12-26 15:36:05 +01:00
Ewelina 66424dbd84 task01 (labs05) done 2017-12-26 15:35:49 +01:00
Ewelina c1ef828bc4 task00 an task02 (labs05) done 2017-12-26 15:35:06 +01:00
Ewelina 672cf0b6ba task00 (labs05) done 2017-12-25 13:54:44 +01:00
Ewelina f81cb81738 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017 2017-12-25 13:44:21 +01:00
Ewelina e98581c644 task03 (labs04) done 2017-12-10 16:26:15 +01:00
Ewelina 86c8cf7c0c task03 (labs04) done 2017-12-10 16:20:52 +01:00
Ewelina 2ce58cac05 task01 (labs04) done 2017-12-10 15:44:41 +01:00
Ewelina 84f0d5479f task02 (labs04) done 2017-12-10 11:42:45 +01:00
Ewelina 9c0e6ccc52 task05 (labs03) done 2017-12-10 10:43:26 +01:00
Ewelina 71e742cb4c task04 (labs03) done 2017-12-10 10:42:47 +01:00
Ewelina ff73957b3c task03 (labs03) done 2017-12-10 10:41:58 +01:00
Ewelina 4d960a7cc0 task02 (labs03) done 2017-12-10 10:40:47 +01:00
Ewelina 2b44ac6ffc task01 (labs03) done 2017-12-10 10:39:16 +01:00
Ewelina fbbf379b04 task01 2017-12-08 21:33:11 +01:00
Ewelina 5ee5fe8c60 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017 2017-12-08 21:24:53 +01:00
Ewelina 111f6b336d task10 passed 2017-11-27 20:42:58 +01:00
Ewelina cd3004f071 task09 passed 2017-11-27 20:42:03 +01:00
Ewelina 3f9c87d72a task11 passed 2017-11-27 20:39:58 +01:00
Ewelina 787b15d0a4 task08 passed 2017-11-27 01:11:39 +01:00
Ewelina 63739e6968 task07 passed 2017-11-27 00:43:52 +01:00
Ewelina 53c2cb3f5f task06 passed 2017-11-27 00:29:45 +01:00
Ewelina fea63c37b7 task06 passed 2017-11-26 23:56:35 +01:00
Ewelina d790e85a09 task05 passed 2017-11-26 23:42:10 +01:00
Ewelina 841880258b task04 passed 2017-11-26 22:57:48 +01:00
Ewelina 117bd4cb90 task03 passed 2017-11-26 21:57:09 +01:00
Ewelina c9b8a28f10 task01 and task02 passed 2017-11-26 19:31:21 +01:00
27 changed files with 822 additions and 32 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="VcsDirectoryMappings"> <component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" /> <mapping directory="" vcs="Git" />
</component> </component>
</project> </project>

View File

@ -30,6 +30,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -43,6 +44,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -76,6 +78,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -110,6 +113,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -130,6 +134,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -146,6 +151,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -177,6 +183,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
@ -207,6 +214,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -221,6 +229,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -235,6 +244,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -260,6 +270,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -291,6 +302,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -320,6 +332,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -348,6 +361,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -362,6 +376,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -387,6 +402,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -415,6 +431,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -433,6 +450,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -458,6 +476,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -472,6 +491,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -509,6 +529,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -526,6 +547,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -553,6 +575,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -570,6 +593,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -595,13 +619,21 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 2,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
}, },
"outputs": [], "outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Wiadomość\n"
]
}
],
"source": [ "source": [
"napis = \"Wiadomość\"\n", "napis = \"Wiadomość\"\n",
"print(napis)" "print(napis)"
@ -609,13 +641,29 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 3,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [], "outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"W 87\n",
"i 105\n",
"a 97\n",
"d 100\n",
"o 111\n",
"m 109\n",
"o 111\n",
"ś 347\n",
"ć 263\n"
]
}
],
"source": [ "source": [
"for znak in napis:\n", "for znak in napis:\n",
" print(znak, ord(znak))" " print(znak, ord(znak))"
@ -625,6 +673,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
@ -641,6 +690,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
@ -655,6 +705,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
@ -669,6 +720,7 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"collapsed": true,
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }

View File

@ -7,8 +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):
inputs = [[[1, 2, 3, 4, 5, 6]], [[]], [[41]]] inputs = [[[1, 2, 3, 4, 5, 6]], [[]], [[41]]]

View File

@ -6,7 +6,10 @@
""" """
def days_in_year(days): def days_in_year(days):
pass if ((days%4 == 0) and (days%100 != 0)) or (days%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,7 +13,10 @@ jak 'set', która przechowuje elementy bez powtórzeń.)
def oov(text, vocab): def oov(text, vocab):
pass text = text.split(" ")
return(set(text) - set(vocab))

View File

@ -7,7 +7,11 @@ 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 >= 1:
return(sum(range(1,n+1)))
if n < 1:
return (0)
def tests(f): def tests(f):

View File

@ -8,9 +8,11 @@ dwoma punktami przestrzeni trójwymiarowej. Punkty są dane jako
trzyelementowe listy liczb zmiennoprzecinkowych. 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((x[0] - y[0])**2) + math.sqrt((x[1]-y[1])**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)+'!')
if n <5:
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 element in text:
suma += ord(element)
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):
if (i%3 == 0 or i%5 == 0):
suma += i
return (suma)
def tests(f): def tests(f):
inputs = [[10], [100], [3845]] inputs = [[10], [100], [3845]]

View File

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

View File

@ -7,9 +7,19 @@ Napisz funkcję pokemon_speak, która zamienia w podanym napisie co drugą liter
na wielką. Np. pokemon_speak('pokemon') powinno zwrócić 'PoKeMoN'. na wielką. Np. pokemon_speak('pokemon') powinno zwrócić 'PoKeMoN'.
""" """
def pokemon_speak(text): def pokemon_speak(text):
pass txtstr= ''
if text.isupper():
return(text)
else:
for i in range (len(text)):
if (i % 2 == 0):
txtstr +=text[i].upper()
else:
txtstr += text[i]
return(txtstr)
def tests(f): def tests(f):

View File

@ -9,7 +9,20 @@ Oba napisy będą składać się wyłacznie z małych liter.
""" """
def common_chars(string1, string2): def common_chars(string1, string2):
lista1 = list(string1)
lista2 =list(string2)
unique_val = set()
for i in lista1:
for x in lista2:
if i == x:
if i.isspace():
pass pass
else:
unique_val.add(i)
lista = list(unique_val)
lista.sort()
return(lista)
def tests(f): def tests(f):

21
labs03/task2.py Normal file
View File

@ -0,0 +1,21 @@
"""**ćwiczenie 2**
Napisz generator, który będzie zwracać ``n`` kolejnych liczb ciągu Fibonacciego (``F(0)=1, F(1)=1, FN=F(N-1) + F(N-2)``)."""
def Fibonacci(n):
x = 0
print(x)
y = 1
print(y)
z = 0
z = x + y
print (z)
for i in range(2, n):
x = y
y = z
z = x + y
print(z)
Fibonacci(19)

19
labs03/task3.py Normal file
View File

@ -0,0 +1,19 @@
""""**ćwiczenie 3**
Strona ``https://api.fixer.io/latest`` udostępnia kursy różnych walut w stosunku do euro. Napisz skrypt, który:
* pobierze zawartość JSONa. Wykorzystaj bibliotekę ``requests`` (http://docs.python-requests.org/en/master/).
* korzystając z biblioteki ``json`` przekształć go do obiketu typu JSON.
* Wyświetl wartość kursu EUR do PLN."""
import requests
url = 'https://api.fixer.io/latest'
response = requests.get(url)
content = response.json()
rates = content['rates']
for key , value in rates.items():
if key == 'PLN':
print (value)

121
labs03/task4.py Normal file
View File

@ -0,0 +1,121 @@
"""**ćwiczenie 4**
Zainstaluj bibliotekę ``weather-api`` (https://pypi.python.org/pypi/weather-api). Korzystając z niej:
* Wypisz informacje o aktualnej pogodzie.
* Napisz funkcję, która zamieni stopnie ``F`` na ``C``.
* Korzystając z prognozy, znajdź dzień, w którym będzie najzimniej.Wypisz nazwę tygodnia (w języku polskim) i temperaturę w C."""
from weather import Weather
weather = Weather()
miasto ='Gdynia'
location = weather.lookup_by_location(miasto)
condition = location.condition()
data = condition.date()
dzien_slownie = data[0:3]
dzien = data[5:7]
miesiac = data[8:11]
rok = data[12:16]
def day_to_dzien_conv(n):
if n == 'Mon':
n = n.replace('Mon','Poniedzialek')
return n
if n == 'Tue':
n = n.replace('Tue', 'Wtorek')
return n
if n == 'Wed':
n = n.replace('Wed', 'Sroda')
return n
if n== "Thu":
n = n.replace('Thu','Czwartek')
return n
if n == 'Fri':
n = n.replace('Fri', 'Piątek')
return n
if n == 'Sat':
n = n.replace('Sat', 'Sobota')
return n
if n == 'Sun':
n = n.replace('Sun', 'Niedziela')
return n
dzien_slownie = day_to_dzien_conv(dzien_slownie)
def month_to_miesiac_conv(z):
if z == 'Jan':
z = z.replace('Jan','Styczen')
return z
if z == 'Feb':
z = z.replace('Feb', 'Luty')
return z
if z == 'Mar':
z = z.replace('Mar', 'Marzec')
return z
if z== "Apr":
z = z.replace('Apr','Kwiecien')
return z
if z == 'May':
z = z.replace('May', 'Maj')
return z
if z == 'Jun':
z = z.replace('Jun', 'Czerwiec')
return z
if z == 'Jul':
z = z.replace('Jul', 'Lipiec')
return z
if z == 'Aug':
z = z.replace('Aug', 'Sierpien')
return z
if z == 'Sep':
z = z.replace('Sep', 'Wrzesien')
return z
if z == 'Oct':
z = z.replace('Oct', 'Pazdziernik')
return z
if z == 'Nov':
z = z.replace('Nov', 'Listopad')
return z
if z == 'Dec':
z = z.replace('Dec', 'Grudzien')
return z
miesiac = month_to_miesiac_conv(miesiac)
print(f"Aktualna pogoda w mieście: {miasto}")
print(f'Data: {dzien_slownie}, {dzien}-{miesiac}-{rok}')
print(f'Warunki (ang.): {condition.text()}')
fahrenhait = condition.temp()
def temp_conversion(fahrenhait):
celsius = round(((int(fahrenhait) - 32) * 5/9),1)
return (f'Temperatura: {celsius} C')
print(temp_conversion(fahrenhait))
temp_min = []
date_temp_min = []
forecasts = location.forecast()
for forecast in forecasts:
temp_min.append(forecast.low())
date_temp_min.append(forecast.date())
minimum = min(temp_min)
indeks = temp_min.index(minimum)
data_miminum = date_temp_min.pop(indeks)
dzien_przew = data_miminum[0:2]
miesiac_przew = data_miminum[3:6]
rok_przew = data_miminum[7:11]
miesiac_przew = month_to_miesiac_conv(miesiac_przew)
print(f'Przewidywalna minimalna {temp_conversion(minimum)} nastąpi dnia {dzien_przew}-{miesiac_przew}-{rok_przew}')

39
labs03/task5.py Normal file
View File

@ -0,0 +1,39 @@
"""**ć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
import os
path = '\scores'
path = os.getcwd()+ path
file_list = glob.glob(path+'\*npz.bleu')
list_all = []
#key_list = []
value_list =[]
for file in file_list:
with open(file, 'r') as f:
linijki = f.readlines()
for line in linijki:
list_all.append(line)
for i in list_all:
i = i.split(',')
#a = i[0][0:4]
b = i[0][7:]
b = float(b)
#key_list.append(a)
value_list.append(b)
max_bleau = (max(value_list))
index_max_bleu = value_list.index(max_bleau)
print(file_list[index_max_bleu])

View File

@ -1,3 +1,16 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#**ć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):
for i in x:
if (isinstance(i, (int, float)) == True):
return True
else:
return False
print(is_numeric([5.62,7,8]))

View File

@ -1,3 +1,91 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#**ć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 - atrybut statyczny - counter.
#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(object):
id = 0
lista_id = []
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.id = Employee.id
Employee.id += 1
self.lista_id.append(self.id)
def get_id(self):
return(self.id)
class Recruiter(Employee):
def __init__(self, name, surname):
Employee.__init__(self, name, surname)
self.recruited = []
def recruit(self, id):
if id != self.id:
if id in Employee.lista_id:
self.recruited.append(id)
else:
print('Nie ma takiego pracownika!')
else:
print('Rekruter nie może zrekrutować samego siebie!')
def __str__(self):
return (f'Rekruter {self.name} {self.surname} zrekrutowal pracownikow o nastepujacych id: {self.recruited}')
class Programmer(Recruiter):
def __init__(self, name, surname, recruiter):
Recruiter.__init__(self, name, surname)
Recruiter.id = recruiter
def recruited_by_who(self):
print (f'Programista {self.name} {self.surname} zostal zrekrutowany przez rekrutera o nastepujacym id: {Recruiter.id}')
print('-------------------------')
pracownik1 = Employee('Stefan', 'Stefanski')
print(pracownik1.name)
print(pracownik1.surname)
print(pracownik1.get_id())
print(pracownik1.id)
pracownik2 = Employee('Karol', 'Karolinski')
print(pracownik2.name)
print(pracownik2.surname)
print(pracownik2.get_id())
print(pracownik2.id)
pracownik3 =Recruiter('Kasia', 'Kasinska')
print(pracownik3.name)
print(pracownik3.surname)
print(pracownik3.id)
pracownik3.recruit(5)
pracownik3.recruit(0)
pracownik3.recruit(1)
print(pracownik3)
pracownik4 = Programmer('Bozena','Bozeniasta', 2)
print(pracownik4.name)
print(pracownik4.surname)
print(pracownik4.id)
print(pracownik4.get_id())
pracownik4.recruited_by_who()
print('-------------------------')
print(Employee.id)
print(Employee.lista_id)
print('-------------------------')

View File

@ -1,3 +1,111 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- 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 wyjątku, który zostaje wyrzucony, jeżeli dodawany punkt ma inny wymiar niż 3."""
pass
def is_numeric(x):
"""funkcja sprawdzajca czy każdy element z przekazanej listy zawiera tylko liczby"""
for i in x:
if (isinstance(i, (int, float)) == True):
return True
else:
return False
class Point(object):
"""Klasa reprezentujaca punkt"""
lista_pktow = []
def __init__(self, coordinates=list):
"""Inicjalizator punktu przyjmuje jako parametr 3-elementowa liste koordynatow"""
if isinstance(coordinates, list):
if len(coordinates) == 3:
if not is_numeric(coordinates):
#jesli koordynaty nie zawieraja wartosci liczbowych zostaje wyrzucony wyjatek
raise Exception('Lista zawiera wartosci nieliczbowe')
else:
#atrybuty klasy Punkt: coordinates (lista wspolrzednych [x,y,z]); x ; y; z
self.coordinates = coordinates
self.x = coordinates[0]
self.y = coordinates[1]
self.z = coordinates[2]
self.lista_pktow.append(self.coordinates)
else:
# jesli punkt ma inny wymiar zostaje wyrzucony wyjatek
raise DimensionError('Wspolrzedne musza miec 3 wymiary!')
else:
print('parametrem musi byc lista!')
def add(punkt1, punkt2):
"""metoda add dodaje wspolrzedne obiektow typu punkt i dodaje nowy obiekt punkt"""
punkt3 = []
if not isinstance(punkt1, Point):
if not isinstance(punkt2, Point):
#jesli parametry metody add nie sa obiektami typu punkt zostaje wyrzucony komunikat
print('zly typ parametru! - parametrem musi byc obiekt typu Punkt')
else:
print('zly typ parametru! - parametrem musi byc obiekt typu Punkt')
else:
if punkt1.coordinates and punkt2.coordinates in Point.lista_pktow:
#jesli parametry metody add sa obiektami typu punkt - wspolrzedne x,y,z sa sumowane i zostaje zwracany nowy obiekt typu punkt
punkt3.append(punkt1.x+punkt2.x)
punkt3.append(punkt1.y+punkt2.y)
punkt3.append(punkt1.z+punkt2.z)
return Point(punkt3)
else:
print('Nie ma takich punktow!')
def __len__(self):
"""metoda len zwraca liczbe wspolrzednych - zawsze bedzie 3 bo tak zostalo zdefiniowane w inicjalizatorze"""
return len(self.coordinates)
def to_string(self):
"""metoda to_strng przedstawia wspolrzedne w czytelnej postaci"""
return (f'Koordynaty punktu: [{self.x}, {self.y}, {self.z}]')
def __str__(self):
"""Wyświetla obiekt typy Point korzystając z funkcji print"""
return self.to_string()
print('-------')
punkta = Point([1,5,6])
print(punkta.coordinates)
print(Point.lista_pktow)
punktb =Point([1,-3,-2])
print(punktb.coordinates)
print(Point.lista_pktow)
print(punkta.__len__())
print(punkta.z)
print('-------')
punkt3 = Point.add(punkta,punktb)
print(punkt3.coordinates)
print(punkt3.z)
print(Point.add(punkta,punktb))
print('-------')
print(Point.lista_pktow)
print(punkta.to_string())
print(punktb)
print(punkta)

View File

@ -1,11 +1,28 @@
#!/usr/bin/env python2 """** zad. 0 **
Napisz funkcję ``suma``, która przyjmnie jeden argument: listę liczb i zwróci ich sumę.
zad.2 Uodpornoj program z zad. 1 w następujący sposób: do programu mogą zostać przekazane argumenty,
które nie mają wartości liczbowej (przyjmijmy, że ich wartość to 0).
Skorzystaj z mechanizmu wyjątków: złap wyjątek, jeżeli argumenty nie da się skonwertować 
na liczbę zmiennoprzecinkową."""
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
def suma(liczby): def suma(liczby):
pass wynik = 0
for i in range(len(liczby)):
try:
wynik += float(liczby[i])
except:
wynik += 0
return wynik
def main(): def main():
print(summa([1, 2, 3, 4])) print(suma([1, 2, 3, 4]))
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -0,0 +1,14 @@
""""** zad. 1 **
Zaimportuj z zadania 0 fukcje ``suma``. Korzystając z tej fukcji i tablicy ``sys.argv``
oblicz i wyświetl sumę argumentów, jakie zostały przekazane do programu.
Załóź, że argumentami do programu będą tylko liczby zmiennoprzecinkowe."""
import task00
import sys
def main():
print(task00.suma(sys.argv[1:]))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,16 @@
"""* zad. 2 **
Uodpornoj program z zad. 1 w następujący sposób: do programu mogą zostać przekazane argumenty,
które nie mają wartości liczbowej (przyjmijmy, że ich wartość to 0).
Skorzystaj z mechanizmu wyjątków: złap wyjątek, jeżeli argumenty nie da się skonwertować na
liczbę zmiennoprzecinkową."""
import task00
import sys
def main():
print(task00.suma(sys.argv[1:]))
#print(task00.suma(['blabla',35.42,24.5]))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,23 @@
"""** zad. 3 **
Przekształć rozwiązanie zadania drugiego w taki sposob, żeby korzystało z biblioteki ``argparse``
zamiast z z listy ``sys.argv``."""
import task00
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument("float", help="liczby zmiennoprzecinkowe", nargs = '+')
args = parser.parse_args()
liczby = args.float
print(task00.suma(liczby))
# print(task00.suma(sys.argv[1:]))
if __name__ == "__main__":
main()

View File

@ -7,6 +7,7 @@ Zwraca liczbę słów, znaków i linii.
""" """
import sys import sys
import argparse
def count_lines(text): def count_lines(text):
@ -32,7 +33,32 @@ def wc(text):
def main(): def main():
""" main """ """ main """
print(wc(sys.stdin.read())) #print(wc(sys.stdin.read()))
parser = argparse.ArgumentParser()
parser.add_argument("--l", help="liczba linii", action = 'store_true')
parser.add_argument("--w", help="liczba slow", action = 'store_true')
parser.add_argument("--c", help="liczba znakow", action = 'store_true')
parser.add_argument("file", help="sciezka do pliku", type = argparse.FileType('r'), nargs = '?')
args = parser.parse_args()
if args.file is None:
fh_lines = sys.stdin.read()
else:
fh_lines = args.file.read()
if args.l:
output = count_lines(fh_lines)
elif args.w:
output = count_words(fh_lines)
elif args.c:
output = count_chars(fh_lines)
elif not (args.l and args.w and args.c):
output = wc(fh_lines)
print(output)
if __name__ == "__main__": if __name__ == "__main__":

87
labs06/model.py Normal file
View File

@ -0,0 +1,87 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""*(dodatkowe)*: Korzystając z pakietu *sklearn* zbuduj model regresji liniowej,
która będzie wyznaczać cenę mieszkania na podstawie wielkości mieszkania i liczby pokoi."""
#import bibliotek
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import math
#wczytanie danych
dane = pd.read_csv('mieszkania.csv', sep = ',', encoding = 'utf-8')
dane = pd.DataFrame(dane)
#analiza korelacji
print(dane.corr())
#korelacja niewielka dodatnia pomiedzy SqrMeters, a Expected = 0.109640
#korelacja niewielka dodatnia pomiedzy Rooms, a Expected = 0.081177
#niska korelaje pokazuje wykres rozrzutu
dane.plot.scatter(x='SqrMeters', y='Expected')
plt.show()
#data preparation
#X -independent variables
#Y -dependent variable
X = dane[['SqrMeters', 'Rooms' ]]
X= pd.DataFrame(X)
Y = dane['Expected']
#splitting data into a training and test set:
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.20, random_state=1)
#train LinearRegression model using the training set of data
lm = linear_model.LinearRegression()
lm.fit(X_train, Y_train)
# coefficients of the model
for idx, col_name in enumerate(X_train.columns):
print("The coefficient for {} is {}".format(col_name, lm.coef_[idx]))
# intercept of the model
intercept = lm.intercept_
print("The intercept for our model is {}".format(intercept))
#linear model : 123969.05-34261.86*X1+5299.47*X2
#R^2 proportion of variability in Y that is explained by X in model = accuracy of regression models
#It seems that 0.78% of the variability in Y can be explained using X
print(lm.score(X_test, Y_test))
#predykcja
#comparing the prediction for the test data set (data not used for training) with the ground truth for the data test set
y_predict = lm.predict(X_test)
lm_mse = mean_squared_error(y_predict, Y_test)
#It seems that we are an average of 1148825.67 away from the ground truth when making predictions on our test set.
print(lm_mse)
print(math.sqrt(lm_mse))
print('--------')
#print(X_test['SqrMeters'])
#linear model plot - how our model plots against our test data.
plt.scatter(X_test['SqrMeters'], Y_test, color='black')
plt.plot(X_test['SqrMeters'], y_predict, color='blue', linewidth=2)
plt.scatter(X_test['SqrMeters'], Y_test, color='black')
plt.plot(X_test['SqrMeters'], y_predict, color='blue', linewidth=2)
plt.xticks(())
plt.yticks(())
plt.show()
#prediction using made up data
# SqrMeters:45
# Rooms: 3
print(lm.predict([[45, 3]]))
# Expected price: 259659.47

View File

@ -1,16 +1,45 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import sklearn
from sklearn import linear_model
def wczytaj_dane(): def wczytaj_dane():
pass """Napisz funkcje, która wczyta zestaw danych z pliku *mieszkania.csv* i zwróci obiekt typu *DataFrame*.
Jeżeli wszystko zostało zrobione poprawnie,powinno się wyśtwietlić 5 pierwszych wierszy."""
flat_data = pd.read_csv('mieszkania.csv', sep = ',', encoding = 'utf-8')
flat_data = pd.DataFrame(flat_data)
return flat_data
def most_common_room_number(dane): def most_common_room_number(dane):
pass """Uzupełnij funkcję ``most_common_room_number``, która zwróci jaka jest najpopularniejsza liczba pokoi w ogłoszeniach.
Funkcji powinna zwrócić liczbę całkowitą."""
pokoje = dane['Rooms']
return(pokoje.value_counts(sort=True).index[0])
def cheapest_flats(dane, n): def cheapest_flats(dane, n):
pass """Uzupełnij kod w funkcji ``cheapest_flats(dane, n)``, która wzróci *n* najtańszych ofert mieszkań.
Wzrócony obiekt typu ``DataFrame``"""
posortowane = dane.sort_values(by='Expected')
ceny = posortowane['Expected']
return(ceny.head(n).to_frame())
def find_borough(desc): def find_borough(desc):
"""Napisz funkcje ``find_borough(desc)``, która przyjmuje 1 argument typu *string*
i zwróci jedną z dzielnic zdefiniowaną w liście ``dzielnice``.
Funkcja ma zwrócić pierwszą (wzgledem kolejności) nazwę dzielnicy, która jest zawarta w ``desc``.
Jeżeli żadna nazwa nie została odnaleziona, zwróć *Inne*."""
dzielnice = ['Stare Miasto', dzielnice = ['Stare Miasto',
'Wilda', 'Wilda',
'Jeżyce', 'Jeżyce',
@ -19,23 +48,69 @@ def find_borough(desc):
'Winogrady', 'Winogrady',
'Miłostowo', 'Miłostowo',
'Dębiec'] 'Dębiec']
pass for i in dzielnice:
if i in desc:
return(i)
return 'Inne'
def add_borough(dane): def add_borough(dane):
pass """Dodaj kolumnę ``Borough``, która będzie zawierać informacje o dzielnicach i powstanie z kolumny ``Localization``.
Wykorzystaj do tego funkcję ``find_borough``"""
lokacja= dane['Location']
dzielnice = []
for rekord in dane['Location']:
new_col = find_borough(rekord)
dzielnice.append(new_col)
dane['Borough'] = dzielnice
def write_plot(dane, filename): def write_plot(dane, filename):
pass """Uzupełnił funkcje ``write_plot``, która zapisze do pliku ``filename`` wykres słupkowy przedstawiający liczbę ogłoszeń
mieszkań z podziałem na dzielnice."""
add_borough(dane)
hist_data = dane['Borough'].value_counts()
#plt.figure()
wyplot = hist_data.plot(kind='bar',alpha=0.5, title="Liczba ogłoszeń mieszkań z podziałem na dzielnice", fontsize=5, figsize=(7, 5))
wyplot.set_xlabel("Dzielnice")
wyplot.set_ylabel("Liczba ogłoszeń")
#plt.show()
fig = wyplot.get_figure()
fig.savefig(filename)
def mean_price(dane, room_number): def mean_price(dane, room_number):
pass """Napisz funkcje ``mean_price``, która zwróci średnią cenę mieszkania ``room_numer``-pokojowego."""
pokoj = dane.loc[dane['Rooms'] == room_number]
return(pokoj['Expected'].agg('mean'))
def find_13(dane): def find_13(dane):
pass """Uzupełnij funkcje ``find_13``, która zwróci listę dzielnic, które zawierają ofertę mieszkanie na 13 piętrze."""
add_borough(dane)
lista13pietra = []
finded = dane['Borough'].loc[dane['Floor'] == 13]
for j in finded:
lista13pietra.append(j)
return lista13pietra
def find_best_flats(dane): def find_best_flats(dane):
pass """Napisz funkcje ``find_best_flats``, która zwróci wszystkie ogłoszenia mieszkań, które znajdują się na Winogradach,
mają 3 pokoje i położone na 1 piętrze."""
add_borough(dane)
finded_best = dane.loc[(dane['Floor'] == 1) & (dane['Rooms'] == 3) & (dane['Borough'] == 'Winogrady')]
return finded_best
def main(): def main():
dane = wczytaj_dane() dane = wczytaj_dane()
@ -45,10 +120,26 @@ def main():
.format(most_common_room_number(dane))) .format(most_common_room_number(dane)))
print("{} to najłądniejsza dzielnica w Poznaniu." print("{} to najłądniejsza dzielnica w Poznaniu."
.format(find_borough("Grunwald i Jeżyce")))) .format(find_borough("Grunwald i Jeżyce")))
print("Średnia cena mieszkania 3-pokojowego, to: {}" print("Średnia cena mieszkania 3-pokojowego, to: {}"
.format(mean_price(dane, 3))) .format(mean_price(dane, 3)))
find_borough("Grunwald i Jeżyce")
print(cheapest_flats(dane, 5))
print(add_borough(dane))
write_plot(dane, 'liczbaogloszen.png')
print(mean_price(dane, 7))
print(find_13(dane))
print(find_best_flats(dane))
if __name__ == "__main__": if __name__ == "__main__":
main() main()