Compare commits

...

12 Commits

Author SHA1 Message Date
s45159 8ba0a6d612 commit 2018-01-21 00:47:49 +01:00
s45159 9a66adcef5 commit 2018-01-21 00:03:22 +01:00
s45159 40c98ed400 commit 2018-01-10 23:04:00 +01:00
s45159 d9ee3ccb7a commit 2018-01-03 22:55:16 +01:00
s45159 7e2b88ec35 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017 2017-12-16 09:49:44 +01:00
s45159 1664154717 commit 2017-12-16 09:14:44 +01:00
s45159 4f878a9849 commit 2017-12-16 00:56:43 +01:00
s45159 fdc76696c9 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017 2017-12-02 15:08:20 +01:00
s45159 6b9900253d commit 2017-11-30 10:18:30 +01:00
s45159 9ef7fa16a0 commit 2017-11-29 17:17:57 +01:00
s45159 0f60618960 commit 2017-11-19 15:45:14 +01:00
s45159 a0bb1a220b task01 2017-11-19 14:56:24 +01:00
18 changed files with 252 additions and 44 deletions

View File

@ -7,8 +7,7 @@ która zawiera tylko elementy z list o parzystych indeksach.
"""
def even_elements(lista):
pass
return lista[::2]
def tests(f):
inputs = [[[1, 2, 3, 4, 5, 6]], [[]], [[41]]]
@ -23,3 +22,4 @@ def tests(f):
if __name__ == "__main__":
print(tests(even_elements))

View File

@ -5,8 +5,19 @@
Napisz funkcję days_in_year zwracającą liczbę dni w roku (365 albo 366).
"""
def days_in_year(days):
pass
def days_in_year(year):
if year % 400 == 0:
return 366
elif year % 100 == 0:
return 365
elif year % 4 == 0:
return 366
else:
return 365
def tests(f):
inputs = [[2015], [2012], [1900], [2400], [1977]]
@ -20,3 +31,5 @@ def tests(f):
if __name__ == "__main__":
print(tests(days_in_year))

View File

@ -13,7 +13,11 @@ jak 'set', która przechowuje elementy bez powtórzeń.)
def oov(text, vocab):
pass
text = text.split()
result = [char for char in text if char not in vocab]
result = sorted(set(result))
return result

View File

@ -7,7 +7,10 @@ Jeśli podany argument jest mniejszy od 1 powinna być zwracana wartość 0.
"""
def sum_from_one_to_n(n):
pass
if n < 1 :
return 0
else:
return sum(range(n+1))
def tests(f):

View File

@ -10,7 +10,8 @@ np. odległość pomiędzy punktami (0, 0, 0) i (3, 4, 0) jest równa 5.
"""
def euclidean_distance(x, y):
pass
return sum([(x-y)**2 for (x,y) in zip(x,y)])**(0.5)
def tests(f):
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):
pass
if n >= 5:
return "N"+ n*"O"+"!"
else:
return "It's not a Big 'No!'"
def tests(f):
inputs = [[5], [6], [2]]

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 sum([ord(x) for x in text]) # int nie dziala
def tests(f):
inputs = [["this is a string"], ["this is another string"]]

View File

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

View File

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

View File

@ -9,7 +9,12 @@ na wielką. Np. pokemon_speak('pokemon') powinno zwrócić 'PoKeMoN'.
def pokemon_speak(text):
pass
text = list(text)
for x in range(0, len(text),2):
text[x] = text[x].upper()
x = ''.join(text)
return x
def tests(f):

View File

@ -9,7 +9,12 @@ Oba napisy będą składać się wyłacznie z małych liter.
"""
def common_chars(string1, string2):
pass
string1 = string1.replace(' ','')
string2 = string2.replace(' ','')
wynik = list(sorted(set([char for char in string1 if char in string2])))
return wynik
def tests(f):

7
labs03/task02.py Normal file
View File

@ -0,0 +1,7 @@
def f(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print(f(55))

16
labs03/task05.py Normal file
View File

@ -0,0 +1,16 @@
import glob
path = 'scores/model.iter*.npz.bleu'
for file in glob.glob(path):
with open(file, 'r') as f:
for line in f.readlines():
num = float(line[line.find("=") + 1:line.find(",")])
if num > 0:
max_num = num
max_num_file = file
f.close()
print(max_num_file)

View File

@ -309,13 +309,13 @@
{
"ename": "AttributeError",
"evalue": "'Parser' object has no attribute '__parse'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<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'"
]
],
"output_type": "error"
}
],
"source": [
@ -465,13 +465,13 @@
{
"ename": "FileNotFoundError",
"evalue": "[Errno 2] No such file or directory: 'nieistniejący_plik.txt'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<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[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'nieistniejący_plik.txt'"
]
],
"output_type": "error"
}
],
"source": [
@ -614,13 +614,13 @@
{
"ename": "MyError",
"evalue": "Coś poszło nie tak!",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mMyError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<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[0;31mMyError\u001b[0m: Coś poszło nie tak!"
]
],
"output_type": "error"
}
],
"source": [

View File

@ -1,3 +1,21 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#ćwiczenie 1**
def is_numeric(x):
if isinstance(x, (int,float)):
print('Int')
elif isinstance(x, float):
print('Float')
else:
print('Not numeric')
list = [1,4,5]
is_numeric(list)
#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).

View File

@ -1,3 +1,50 @@
#!/usr/bin/env python2
# -*- 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. Wykorzystaj do tego atrybut statyczny. Napisz metodę ``get_id``, która zwraca identyfikator pracownika.
# * Klasy pochodna: ``Recruiter``, która ma dodatkową mtodę ``recruit``, która jako parament przyjmuje obiekt ``Employee`` i zapisuje jego ``id`` w liście ``self.recruited``.
# * Klasa pochodna ``Programmer``. Klasa ``Programmer`` ma przyjąć w konstruktorze podstawowe informacje (imię i nazwisko) oraz obiekt rekturera. Ponadto stwórz atrybut ``recruiter``, który będzie przechowywać ``id`` rekrutera.
class Employee():
id=0
def __init__(self, firstname, surname):
self.id = Employee.id
self.firstname = firstname
self.surname = surname
Employee.id = Employee.id + 1
def get_id(self):
return self.id
class Recruiter(Employee):
def __init__(self,firstname,surname):
super().__init__(firstname,surname)
self.recruited=[]
def recruite(self,Employee):
self.recruited.append(Employee.get_id())
class Programmer(Employee):
def __init__(self,firstname,surname,Recruiter):
super().__init__(firstname,surname)
self.recruiter = Recruiter.get_id()
E1 = Employee('Karol', 'Kapusta')
E2 = Employee('Jola', 'Kalafior')
print('Employee1', E1.firstname, E1.surname)
print('Employee2', E2.firstname, E2.surname)
R = Recruiter('John','Szef')
print('Recruiter',R.firstname, R.surname)
P = Programmer('Ali','Baba', R)
print('Programmer',P.firstname, P.surname)
R.recruite(E1)
print(R.recruited)

View File

@ -1,3 +1,58 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#ćwiczenie 3 (zadanie domowe) ** Stwórz klasę Point, która będzie reprezentować punkt w przestrzeni wielowymiarowej:
#Konstruktor ma przyjąc tylko 1 parametr: listę współrzednych. Wykorzystaj funkcję z pierwszego zadania, żeby sprawdzić, czy lista zawiera wyłącznie liczby.
#Napisz metodę add, która doda 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.
#funkcja z pierwszego zadania, żeby sprawdzić, czy lista zawiera wyłącznie liczby
def is_numeric(list):
for i in list:
if (isinstance(i, (int, float)) == True):
return True
else:
return False
# wyjątek DimensionError, który zostaje wyrzucony, jeżeli dodawany punkt ma inny wymiar
class DimensionError(Exception):
def __init__(self, text):
self.text = text
# klasa
class Point:
def __init__(self, coordinates):
if len(coordinates) != 3:
raise DimensionError('Wrong coordinates')
else:
self.coordinates = coordinates
# funkcja add, która doda dwa punkty do współrzędnych i zwróci obiekt typu Punkt
def add(c1, c2):
coordinates = []
if len(c1) != len(c2):
for i in range(0, len(c1)):
coordinates.append(c1[i]+c2[i])
return coordinates
# funkcja to_string, która zwróci łancuch znakowy,
def to_string(self):
return '(' + ', '.join(map(str, self.coordinates)) + ')'
# funkcja str, która bedzie działać dokładnie tak samo jak metoda to_string
def __str__(self):
return self.to_string()
# metoda len, która zwróci liczbę współrzędnych punktu
def __len__(self):
return len(self.coordinates)
point = Point([1,5,6])
print(point.coordinates)

View File

@ -1,14 +1,21 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
def wczytaj_dane():
pass
mieszkania = pd.read_csv('mieszkania.csv',
encoding='utf-8',
sep=',',
index_col='Id')
return pd.DataFrame(mieszkania)
def most_common_room_number (dane):
pass
most_common = dane['Rooms'].value_counts().head()
return most_common
def cheapest_flats(dane, n):
pass
cheapest = dane.sort_values('Expected').head(n)
return cheapest
def find_borough(desc):
dzielnice = ['Stare Miasto',
@ -19,36 +26,50 @@ def find_borough(desc):
'Winogrady',
'Miłostowo',
'Dębiec']
pass
for dzielnica in dzielnice:
if dzielnica in desc:
return dzielnica
return 'Inne'
def add_borough(dane):
pass
dane['Borough'] = dane['Location'].apply(find_borough)
return dane
def write_plot(dane, filename):
pass
data = add_borough(dane)
plot_data = data['Borough'].value_counts()
plot_data.plot( Kind = 'bar',title='Mieszkania z podziałem na dzielnice')
figure_data = plot_data.get_figure()
figure_data.savefig ( filename )
def mean_price(dane, room_number):
pass
rooms = dane[ dane['Rooms']==room_number]['Expected'].mean()
return rooms
def find_13(dane):
pass
floor_13 = dane[dane['Floor'] == 13]['Borough'].values
return floor_13
def find_best_flats(dane):
pass
best_flats = dane[(dane['Borough'] == 'Winogrady') & (dane['Rooms'] == 3) & (dane['Floor'] == 1)]
return best_flats
def main ( ):
dane = wczytaj_dane ( )
print(dane[ :5 ])
print("Najpopularniejsza liczba pokoi w mieszkaniu to: {}"
.format(most_common_room_number(dane)))
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("{} to najłądniejsza dzielnica w Poznaniu.".format ( find_borough ( "Grunwald i Jeżyce" ) ))
print("Średnia cena mieszkania 3-pokojowego, to: {:.2f}".format ( mean_price ( dane , 3 ) ))
dane = add_borough(dane)
print("Dzielnice z ofertami na 13 pietrze: {}".format ( find_13 ( dane ) ))
print("Najlepsze oferty: {}".format ( find_best_flats ( dane ) ))
print("Średnia cena mieszkania 3-pokojowego, to: {}"
.format(mean_price(dane, 3)))
if __name__ == "__main__":
main ( )