Compare commits

...

17 Commits

Author SHA1 Message Date
s45157 d4ba49aa16 Enhancement to predict function 2018-01-21 19:11:37 +01:00
s45157 e20007b2df Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017
# Conflicts:
    #	labs02/test_task.py
2018-01-02 15:54:46 +01:00
s45157 4197571375 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017
# Conflicts:
    #	labs02/test_task.py
2018-01-02 15:52:55 +01:00
s45157 8b57f5b1cf Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017
# Conflicts:
    #	labs02/test_task.py
2018-01-02 15:51:05 +01:00
s45157 a6c2e3af77 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017
# Conflicts:
    #	labs02/test_task.py
2018-01-02 02:45:14 +01:00
s45157 c5e0d8dddf __init__.py file added to git tracking 2017-12-16 09:48:51 +01:00
s45157 ab3b1358ec Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017 2017-12-16 09:23:48 +01:00
s45157 8fd6d60ac2 labs04/task03 - applying len function to Point object 2017-12-16 02:51:57 +01:00
s45157 2d220e69c6 labs04 - after review 2017-12-16 02:44:01 +01:00
s45157 932a6637e0 labs03 - after review 2017-12-16 02:41:43 +01:00
s45157 9f8ecbfdb6 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017 2017-12-03 13:35:10 +01:00
s45157 f1ed9dbaad Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017
# Conflicts:
#	labs02/test_task.py
2017-12-02 15:48:24 +01:00
s45157 453ffd0687 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017
# Conflicts:
#	labs02/test_task.py
2017-12-02 15:47:25 +01:00
Paweł 1da1277733 Change functions to oneliners. 2017-11-27 01:06:55 +01:00
s45157 a1a1a85482 tasks2-10 2017-11-19 15:42:27 +01:00
s45157 df3a24d5fd Zadanie 4 (task 3) 2017-11-19 15:02:45 +01:00
s45157 9a92abc8c0 First commit 2017-11-19 14:55:47 +01:00
29 changed files with 280 additions and 57 deletions

View File

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

View File

@ -6,7 +6,7 @@
"""
def days_in_year(days):
pass
return 366 if ((days % 4 == 0) and (days % 100 != 0)) or (days % 400 == 0) else 365
def tests(f):
inputs = [[2015], [2012], [1900], [2400], [1977]]

View File

@ -13,8 +13,7 @@ jak 'set', która przechowuje elementy bez powtórzeń.)
def oov(text, vocab):
pass
return set(text.split(' ')).difference(vocab)
def tests(f):
@ -28,5 +27,6 @@ def tests(f):
break
return "TESTS PASSED"
if __name__ == "__main__":
print(tests(oov))

View File

@ -7,8 +7,7 @@ Jeśli podany argument jest mniejszy od 1 powinna być zwracana wartość 0.
"""
def sum_from_one_to_n(n):
pass
return 0 if n < 1 else reduce(lambda x, y: (x+y), range(1,n+1))
def tests(f):
inputs = [[999], [-100]]

View File

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

View File

@ -9,8 +9,10 @@ równa podanemu argumentem, przy czym jeśli argument jest mniejszy niż 5,
ma być zwracany napis "It's not a Big 'No!'".
"""
def big_no(n):
pass
return "It's not a Big 'No!'" if n < 5 else "N" + n * "O" + "!"
def tests(f):
inputs = [[5], [6], [2]]
@ -22,5 +24,6 @@ def tests(f):
break
return "TESTS PASSED"
if __name__ == "__main__":
print(tests(big_no))

View File

@ -6,7 +6,7 @@ Napisz funkcję char_sum, która dla zadanego łańcucha zwraca
sumę kodów ASCII znaków.
"""
def char_sum(text):
pass
return reduce(lambda x, y: (x + y), map(lambda ch: ord(ch), text))
def tests(f):
inputs = [["this is a string"], ["this is another string"]]

View File

@ -7,7 +7,7 @@ przez 3 lub 5 mniejszych niż n.
"""
def sum_div35(n):
pass
return reduce(lambda x, y: (x + y), filter(lambda x: (x%3==0 or x%5==0), range(1,n)))
def tests(f):
inputs = [[10], [100], [3845]]

View File

@ -9,7 +9,7 @@ Np. leet('leet') powinno zwrócić '1337'.
def leet_speak(text):
pass
return ''.join(map( lambda ch: {'e': '3', 'l': '1', 'o': '0', 't': '7'}.get(ch, ch), text))
def tests(f):

View File

@ -9,7 +9,7 @@ na wielką. Np. pokemon_speak('pokemon') powinno zwrócić 'PoKeMoN'.
def pokemon_speak(text):
pass
return ''.join([a if idx%2==1 else a.upper() for idx, a in enumerate(text)])
def tests(f):

View File

@ -9,7 +9,7 @@ Oba napisy będą składać się wyłacznie z małych liter.
"""
def common_chars(string1, string2):
pass
return sorted( set(filter(lambda ch: ch.islower(), string1)).intersection(filter(lambda ch: ch.islower(), string2)) )
def tests(f):

View File

@ -3,9 +3,6 @@
def suma(a, b):
"""
Napisz funkcję, która zwraca sumę elementów.
"""
return a + b
def tests(f):
@ -18,4 +15,5 @@ def tests(f):
break
return "TESTS PASSED"
print(tests(suma))
if __name__ == "__main__":
print(tests(suma))

View File

@ -6,7 +6,9 @@
Sklonuj repozytorium ``https://github.com/realpython/python-scripts``, które różne, przydatne skrypty. Przejrzyj je i zobacz na ile jesteś w stanie zrozumieć co i jak robią. Uruchom kilka z nich, np. ``27_send_sms.py``.
**ćwiczenie 1**
Każdy obiekt w Pythonie na wbudowaną funkcję ``id()``, która zwraca liczbę, która jest unikatowa i stała dla obiektu. Pozwala ona w prosty sposób sprawdzić, który obiekt jest *mutable*a, który *immutable*: jeżeli po wykonaniu operacji, zwracana liczba jest stała, to oznacza, że obiekt jest *mutable*. Sprawdź zachowanie funkcji na obiektach typy:
Każdy obiekt w Pythonie na wbudowaną funkcję ``id()``, która zwraca liczbę, która jest unikatowa i stała dla obiektu.
Pozwala ona w prosty sposób sprawdzić, który obiekt jest *mutable*a, który *immutable*: jeżeli po wykonaniu operacji,
zwracana liczba jest stała, to oznacza, że obiekt jest *mutable*. Sprawdź zachowanie funkcji na obiektach typy:
* lista,
* napis (string),
* liczba zmiennoprzecinkowa.

8
labs03/task01.py Normal file
View File

@ -0,0 +1,8 @@
#lab03 task01
#Returns mutable type names
[t for t, oldid, newid in map( lambda (t, obj, objid): (t, id(obj*1), objid), map(lambda x : (type(x), x, id(x)), [[], '', 3.141592]) ) if oldid == newid]
for type_name, type_mutable in map( lambda t: (type(t), id(t)==id(t*1)), [[], '', 3.141592] ):
print("%s is %s" % (str(type_name), 'mutable' if type_mutable else 'immutable') )

7
labs03/task02.py Normal file
View File

@ -0,0 +1,7 @@
# lab03, task02
def fibN(n):
prev, current = 1, 1
for n in range(n):
yield prev
prev, current = current, prev + current

15
labs03/task03.py Normal file
View File

@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
import requests, json
# try:
# print('EUR:PLN %3.4f' % (requests.get('https://api.fixer.io/latest').json()['rates']['PLN']))
# except:
# print("Something went wrong. Couldn't display EUR:PLN exchange rate.")
#
# Niestety nie znalazłem w pakiecie json dla pythona 2.7 operacji zwracającej wspomniany w treści zadania
# 'obiekt typu JSON' -czytanie streamu zamienia dane na zwykłe pythonowe słowniki. Nie wnosi to więc wartości dodanej
# do powyższego kodu, który w metodzie.json() zwraca obiekt typu dict, podobnie jak przyjmująca łańcuch znaków
# funkcja json.loads.
print(json.loads(requests.get('https://api.fixer.io/latest').text))['rates']['PLN']
# assert type(json.loads(requests.get('https://api.fixer.io/latest').text)) == type(dict())
#

22
labs03/task04.py Normal file
View File

@ -0,0 +1,22 @@
# -*- coding: utf-8 -*-
from weather import Weather
import datetime
weather = Weather()
loc = weather.lookup_by_location('Poznan')
print('Informacja o aktualnej pogodzie: %s' % loc.condition().text())
def ftoc(f):
return (f-32.0)*5.0/9.0
def date_to_pl_weekday(date_string):
"""
input: string of form '10 Dec 2017'
output: weekday in polish language
"""
idx = datetime.datetime.strptime(date_string, '%d %b %Y').weekday()
return [u'poniedziałek', u'wtorek', u'środa', u'czwartek', u'piątek', u'sobota', u'niedziela'][idx]
min_day = min(loc.forecast(), key = lambda f: f.low())
print(u'Najbliższy najzimniejszy dzień to %s. Będzie %s\u00B0C. ' % (date_to_pl_weekday(min_day.date()), ftoc(int(min_day.low()))))

18
labs03/task05.py Normal file
View File

@ -0,0 +1,18 @@
import glob, os
# print(glob.glob('./scores/model.iter[0-9][0-9][0-9][0-9][0-9][0-9][0-9].npz.bleu'))
def extract_BLEU_score(fn):
'''
:param fn - path to file with :
:return:
'''
with open(fn, 'r') as fd:
line = fd.readline()
return (os.path.abspath(fn), float(line[6:line.index(',')]))
print max([ t for t in map(extract_BLEU_score, glob.iglob('./scores/model.iter[0-9][0-9][0-9][0-9][0-9]*.npz.bleu'))], key = lambda tpl: tpl[1])[0]

0
labs04/__init__.py Normal file
View File

View File

@ -1,3 +1,19 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def is_numeric(xs):
return all(isinstance(x, (int, float)) for x in xs)
assert is_numeric([1,2,3,4,5,6,6])
assert is_numeric([1.0,2.0,3.0,4.0,5.0,6.0])
assert is_numeric([1])
assert is_numeric([1.0])
assert is_numeric([1.0, 1])
assert is_numeric([1, 1.0])
assert is_numeric([]) #zgodnie z ustaleniami z zajęć
assert not is_numeric([1,2,3,'a',4,5,6,6])
assert not is_numeric([1.0,2.0,3.0,'a',4.0,5.0,6.0])
assert not is_numeric([1, 'a'])
assert not is_numeric([1.0, 'a'])
assert not is_numeric(['a', 1.0, 1])
assert not is_numeric([1, 1.0, 'a'])
assert not is_numeric(['a'])

View File

@ -1,3 +1,38 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
class Employee(object):
NEXT_ID = 0
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.id = Employee.NEXT_ID
Employee.NEXT_ID = Employee.NEXT_ID + 1
def get_id(self):
return self.id
class Recruiter(Employee):
def __init__(self, name, surname):
super(Recruiter, self).__init__(name, surname)
self.recruited = []
def recruit(self, employee):
self.recruited.append(employee.get_id())
class Programmer(Employee):
def __init__(self, name, surname, recruiter):
super(Programmer, self).__init__(name, surname)
self.recruiter = recruiter.get_id()
empl1 = Employee('a', 'a')
empl2 = Employee('b', 'b')
rec1 = Recruiter('c', 'c')
prog1 = Programmer('d', 'd', rec1)
rec1.recruit(prog1)
assert prog1.recruiter == rec1.get_id()
assert any( recruitee_id == prog1.get_id() for recruitee_id in rec1.recruited )

View File

@ -1,3 +1,42 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
class Point(object):
def __init__(self, coords):
from labs04.task01 import is_numeric
assert is_numeric(coords)
self.coords = coords
def add(self, that):
if len(self.coords) != len(that.coords):
raise DimensionError('Niezgodne wymiary')
else:
pass
return Point(map(lambda(a,b): a+b, zip(self.coords, that.coords)))
def to_string(self):
return type(self).__name__+'('+((',').join(map(str, self.coords)))+')'
def len(self):
return len(self.coords)
def __len__(self):
return len(self.coords)
def __str__(self):
return self.to_string()
def __add__(self, other):
return self.add(other)
class DimensionError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
pt1 = Point([1,2,3.0,4.0])
pt2 = Point([-1, -2.0, -3, -4.0])
print('len(%s + %s) = %d' %(pt1, pt2, len(pt1 + pt2)))
print(pt1 + pt2)

View File

@ -2,10 +2,11 @@
# -*- coding: utf-8 -*-
def suma(liczby):
pass
assert len(liczby) > 0
return reduce(lambda a, b: a+b, liczby)
def main():
print(summa([1, 2, 3, 4]))
print(suma([1, 2, 3, 4]))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,7 @@
import task00, sys
def main():
print('%f' % (task00.suma(map(lambda x: float(x), sys.argv[1:]))))
if __name__ == '__main__':
main()

View File

@ -0,0 +1,12 @@
import task00, sys
def main():
def a_to_f(a):
try:
return float(a)
except:
return 0
print('%f' % (task00.suma(map(a_to_f, sys.argv[1:]))))
if __name__ == '__main__':
main()

View File

@ -0,0 +1,15 @@
import task00, argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("numbers", nargs="+")
args = parser.parse_args()
def a_to_f(a):
try:
return float(a)
except:
return 0
print('%f' % (task00.suma(map(a_to_f, args.numbers))))
if __name__ == '__main__':
main()

View File

@ -6,7 +6,7 @@ Implementacja narzedzia ``wc`` z linuksa (word counter).
Zwraca liczbę słów, znaków i linii.
"""
import sys
import sys, argparse
def count_lines(text):
@ -19,7 +19,7 @@ def count_words(text):
for line in text.split('\n')])
def count_chars(text):
""" return number of words. """
""" return number of characters. """
return len(text)
def wc(text):
@ -32,7 +32,22 @@ def wc(text):
def main():
""" main """
print(wc(sys.stdin.read()))
parser = argparse.ArgumentParser()
parser.add_argument('-l', help="number of lines", action="store_true")
parser.add_argument('-w', help="number of words", action="store_true")
parser.add_argument('-c', help="number of characters", action="store_true")
parser.add_argument('fn', nargs='?', type=file, default=sys.stdin, help='optional filename to read from')
args = parser.parse_args()
lines, words, chars = wc(args.fn.read())
if( args.l or args.w or args.c ):
if(args.l):
print(lines)
if(args.w):
print(words)
if(args.c):
print(chars)
else:
print(lines, words, chars)
if __name__ == "__main__":

View File

@ -28,7 +28,7 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": null,
"metadata": {
"collapsed": true,
"slideshow": {
@ -299,30 +299,12 @@
]
},
{
"cell_type": "code",
"execution_count": 16,
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"count 26.000000\n",
"mean 8.576923\n",
"std 5.375300\n",
"min 1.000000\n",
"25% 4.250000\n",
"50% 8.000000\n",
"75% 12.000000\n",
"max 18.000000\n",
"dtype: float64\n"
]
}
],
"source": [
"print(dane.describe())"
]

View File

@ -1,14 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
def wczytaj_dane():
pass
return pd.read_csv('mieszkania.csv')
def most_common_room_number(dane):
pass
return dane['Rooms'].mode()[0]
def cheapest_flats(dane, n):
pass
return dane.sort_values(by=[u'Expected'], na_position='last').head(n)
def find_borough(desc):
dzielnice = ['Stare Miasto',
@ -19,23 +20,37 @@ def find_borough(desc):
'Winogrady',
'Miłostowo',
'Dębiec']
pass
histogram = {districtName: desc.find(districtName) for districtName in dzielnice if desc.find(districtName) != -1}
return 'Inne' if not histogram else min(histogram, key=histogram.get)
def add_borough(dane):
pass
dane['Borough'] = dane.apply( lambda row: find_borough( row['Location']), axis = 1)
def write_plot(dane, filename):
pass
dane['Borough'].value_counts().plot.bar().get_figure().savefig(filename)
def mean_price(dane, room_number):
pass
return dane.loc[ dane['Rooms'] == room_number ].mean()[1]
def find_13(dane):
pass
return dane.loc[dane['Floor'] == 13]['Borough'].unique()
def find_best_flats(dane):
pass
return dane.loc[(dane['Borough'] == 'Winogrady') & (dane['Rooms'] == 3) & (dane['Floor'] == 1)]
def predict(dane, rooms, sqrMeters):
from sklearn import linear_model
import numpy as np
data = dane
df = pd.DataFrame(data, columns=np.array(['Rooms','SqrMeters']))
target = pd.DataFrame(data, columns=["Expected"])
X = df
y = target["Expected"]
lm = linear_model.LinearRegression()
model = lm.fit(X, y)
inData = pd.DataFrame.from_records([(rooms, sqrMeters)], columns=['Rooms', 'SqrMeters'])
return lm.predict(inData)[0]
def main():
dane = wczytaj_dane()
@ -44,11 +59,21 @@ def main():
print("Najpopularniejsza liczba pokoi w mieszkaniu to: {}"
.format(most_common_room_number(dane)))
print("{} to najłądniejsza dzielnica w Poznaniu."
.format(find_borough("Grunwald i Jeżyce"))))
print("7 najtańszych mieszkań to: ")
print(cheapest_flats(dane, 7))
print("{} to najłądniejsza dzielnica w Poznaniu.".format(find_borough("Grunwald i Jeżyce")))
add_borough(dane)
write_plot(dane, 'tmp_borough_hist.png')
for i in dane['Rooms'].unique():
print("Średnia cena mieszkania {}-pokojowego, to: {}".format(i, mean_price(dane, i)))
print('Dzielnice z mieszkaniami na 13 piętrze: {}'.format(find_13(dane)))
print('"Najlepsze" mieszkania: ')
print(find_best_flats(dane))
print('Predicted price(actual 146000): ', predict(dane,1,31.21))
print("Średnia cena mieszkania 3-pokojowego, to: {}"
.format(mean_price(dane, 3)))
if __name__ == "__main__":
main()
main()