Compare commits

...

11 Commits

Author SHA1 Message Date
f3e7e6f696 lab 3 filled 2018-01-20 19:56:37 +01:00
3fa9c4f31f lab 6 filled 2018-01-20 19:02:56 +01:00
bd731bbc44 Merge remote-tracking branch 'origin/master' 2017-12-16 11:07:33 +01:00
1f7ff179fa p 2017-12-16 11:02:48 +01:00
e3ef2766de Merge remote-tracking branch 'origin/master' 2017-12-03 15:39:43 +01:00
3c04e0fda5 python_04 2017-12-03 15:37:48 +01:00
e9092b8a9b python_04 2017-12-03 15:34:43 +01:00
62e9ec6016 Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017 2017-12-03 15:02:13 +01:00
b1299c5c49 python_01 2017-12-02 09:30:37 +01:00
54f08133aa python_01 2017-12-01 23:41:35 +01:00
9e02e59892 test 2017-11-19 14:56:01 +01:00
22 changed files with 368 additions and 64 deletions

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component>
</module>

4
.idea/misc.xml Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6.2 (C:\software\python3\python.exe)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Python2017_45163.iml" filepath="$PROJECT_DIR$/.idea/Python2017_45163.iml" />
</modules>
</component>
</project>

6
.idea/preferred-vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PreferredVcsStorage">
<preferredVcsName>ApexVCS</preferredVcsName>
</component>
</project>

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

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

View File

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

View File

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

View File

@ -8,9 +8,15 @@ 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.
"""
from math import sqrt
def euclidean_distance(x, y):
pass
return sqrt(sum((x-y)**2 for x, y in zip(x,y)))
# return np.sqrt(np.sum((x-y)**2))
def tests(f):
inputs = [[(2.3, 4.3, -7.5), (2.3, 8.5, -7.5)]]

View File

@ -10,7 +10,11 @@ ma być zwracany napis "It's not a Big 'No!'".
"""
def big_no(n):
pass
n_first = 'N'
if n < 5:
return "It's not a Big 'No!'"
else:
return n_first+n*'O'+'!'
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(char) for char in text)
def tests(f):
inputs = [["this is a string"], ["this is another string"]]

View File

@ -5,9 +5,13 @@
Napisz funkcję sum_div35(n), która zwraca sumę wszystkich liczb podzielnych
przez 3 lub 5 mniejszych niż n.
"""
def sum_div35(n):
pass
sum = 0
for n in range(n):
if (n % 3 == 0 or n % 5 == 0):
sum = sum + n
return(sum)
def tests(f):
inputs = [[10], [100], [3845]]

View File

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

View File

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

View File

@ -9,8 +9,25 @@ Oba napisy będą składać się wyłacznie z małych liter.
"""
def common_chars(string1, string2):
pass
string1 = set(string1.replace(" ",""))
string2 = set(string2.replace(" ",""))
common = []
for c1 in string1:
for c2 in string2:
if c1 == c2:
common.append(c1)
common.sort()
return common
# slowo = sum( c1 == c2 for c1, c2 in zip(string1, string2))
# print(slowo)
# return slowo
def tests(f):
inputs = [["this is a string", "ala ma kota"]]

View File

@ -232,13 +232,13 @@
{
"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'"
]
],
"output_type": "error"
}
],
"source": [
@ -398,13 +398,13 @@
{
"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."
]
],
"output_type": "error"
}
],
"source": [

89
labs03/lab3.py Normal file
View File

@ -0,0 +1,89 @@
import requests
from weather import Weather
import glob
import re
def fibb(n):
liczby = [0,1]
for i in range(1,n):
liczby.append(liczby[-1]+liczby[-2])
return liczby
def EUR_PLN_rate():
value = requests.get('https://api.fixer.io/latest')
asJson = value.json()
return asJson['rates']['PLN']
def niezmiennosc():
lista = ['a', 'b', 'c']
idPrzed = id(lista)
lista.append('d')
idPo = id(lista)
lista2 = lista.append('e')
idPoZPrzypisaniem = id(lista2)
print(
'Lista przed modyfikacja: {}, po modyfikacji: {}, obiekt niezmienny: {}, po przypisaniu nowy obiekt: {}'.format(
idPrzed, idPo, idPrzed != idPo, idPrzed != idPoZPrzypisaniem))
napis = 'To jest napis'
idPrzed = id(napis)
napis = napis + 'zmieniony'
idPo = id(napis)
print(
'Napis przed modyfikacja: {}, po modyfikacji: {}, obiekt niezmienny: {}'.format(idPrzed, idPo, idPrzed != idPo))
numerek = 0.123
idPrzed = id(numerek)
numerek = numerek + 0.1
idPo = id(numerek)
print('Numerek przed modyfikacja: {}, po modyfikacji: {}, obiekt niezmienny: {}'.format(idPrzed, idPo,
idPrzed != idPo))
def toCelsius(tempF):
return ((tempF-32)*5/9)
def weatherApi():
weather = Weather()
location = weather.lookup_by_location('poznan')
condition = location.condition()
tempF = int(condition.temp())
tempC = (tempF-32)*5/9
print(tempC)
lowest = location.forecast()[0]
for forecast in location.forecast():
if forecast.low() < lowest.low():
lowest = forecast
print(lowest.date())
print(toCelsius(int(lowest.low())))
def highestTrained():
highest_bleu = 0
higlest_file = ''
for file in glob.glob('./scores/*.bleu'):
with open(file) as f:
bleu = re.match(r'BLEU\s=\s(?P<bleu_val>\d{1,2}\.\d{1,2})', f.readline(12))
if bleu:
potential_highest = float(bleu.group('bleu_val'))
if potential_highest > highest_bleu:
highest_bleu = potential_highest
higlest_file = f.name
print(higlest_file)
if __name__ == '__main__':
# cwiczenie 1
niezmiennosc()
# cwiczenie 2
print(fibb(19))
# cwiczenie 3
print(EUR_PLN_rate())
# cwiczenie 4
weatherApi()
# cwiczenie 5
highestTrained()

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,10 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def is_numeric(a):
if isinstance(a, int):
print ("integer")
if isinstance(a, float):
print("float")
is_numeric(1.2)

View File

@ -1,3 +1,49 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from random import randint
class Employee:
def __init__(self, imie, nazwisko):
self.imie = imie
self.nazwisko = nazwisko
self.id = randint(0, 1000) # pole nie jest statyczne, nie rozumiem, dlaczego milo by byc
def get_id(self):
return self.id
class Recruiter(Employee):
def __init__(self, imie, nazwisko):
super(Recruiter,self).__init__(imie, nazwisko)
self.recruited = []
def recruit(self, employee):
if isinstance(employee, Employee):
self.recruited.append(employee.get_id())
class Programmer(Employee):
def __init__(self, imie, nazwisko, recruiter):
super(Programmer, self).__init__(imie, nazwisko)
if isinstance(recruiter, Recruiter):
self.recruiter = recruiter.get_id()
if __name__ == '__main__':
employee = Employee("Agnieszka", "Wisniewska")
print(employee.get_id())
recruiter = Recruiter("Krzysztof", "Wisniewski")
recruiter.recruit(employee)
print(recruiter.get_id())
print(recruiter.recruited)
programmer = Programmer("Ksawery", "Wisniewski", recruiter)
print(programmer.recruiter)

View File

@ -1,3 +1,49 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
class Point:
def __init__(self, coords):
if is_numeric(coords):
self.coords = coords
print(self.coords)
def to_string(self):
print("coords:")
print(self.coords)
def __len__(self):
return len(self.coords)
def __str__(self):
return "coords: [" + ','.join([str(c) for c in self.coords]) + "]"
class DimensionError(Exception):
def __init__(self, message):
super(DimensionError, self).__init__(message)
def add(point1, point2):
if len(point1.coords) != len(point2.coords) or len(point1.coords) == 0 or len(point2.coords) == 0:
raise DimensionError('Wrong dimensions!')
newCoords = []
for dim in zip(point1.coords, point2.coords):
newCoords.append(sum(dim))
return Point(newCoords)
def is_numeric(coords):
for el in coords:
if not isinstance(el, (int, float)):
return False
return True
if __name__ == '__main__':
point1 = Point([1,2,3,4,5])
point2 = Point([1,2,3,4,5])
point = add(point1, point2)
# point.to_string()
print(len(point))
print(point)

View File

@ -1,54 +1,77 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def wczytaj_dane():
pass
def most_common_room_number(dane):
pass
def cheapest_flats(dane, n):
pass
def find_borough(desc):
dzielnice = ['Stare Miasto',
'Wilda',
'Jeżyce',
'Rataje',
'Piątkowo',
'Winogrady',
'Miłostowo',
'Dębiec']
pass
import pandas as pd
import matplotlib.pyplot as plt
def add_borough(dane):
pass
def wczytaj_dane ( ):
return pd.read_csv ( 'mieszkania.csv' )
def write_plot(dane, filename):
pass
def mean_price(dane, room_number):
pass
def most_common_room_number ( dane ):
return dane[ 'Rooms' ].value_counts ( )
def find_13(dane):
pass
def find_best_flats(dane):
pass
def cheapest_flats ( dane , n ):
cheapest = dane[ [ 'Expected' , 'Location' ] ].sort_values ( by=[ "Expected" ] , ascending=False )
return cheapest[ :n ]
def main():
dane = wczytaj_dane()
print(dane[:5])
print("Najpopularniejsza liczba pokoi w mieszkaniu to: {}"
.format(most_common_room_number(dane)))
def find_borough ( desc ):
dzielnice = [ 'Stare Miasto' , 'Wilda' , 'Jeżyce' , 'Rataje' , 'Piątkowo' , 'Winogrady' , 'Miłostowo' , 'Dębiec' ]
print("{} to najłądniejsza dzielnica w Poznaniu."
.format(find_borough("Grunwald i Jeżyce"))))
descSplit = desc.split ( ' ' )
dzielnica = [ ds for ds in descSplit if ds in dzielnice ]
return dzielnica[ 0 ] if len ( dzielnica ) > 0 else 'Inne'
def add_borough ( dane ):
dane[ 'Borough' ] = dane.apply ( lambda row: find_borough ( row[ 'Location' ] ) , axis=1 )
return dane
def write_plot ( dane , filename ):
dane2 = add_borough ( dane )
do_plota = dane2[ 'Borough' ].value_counts ( )
do_plota.plot ( kind='bar' )
# plt.show()
plt.savefig ( filename )
def mean_price ( dane , room_number ):
pokoje = dane[ dane[ 'Rooms' ] == room_number ]
return pokoje[ 'Expected' ].mean ( )
def find_13 ( dane ):
dane2 = add_borough ( dane )
pietro = dane2[ dane2[ 'Floor' ] == 13 ]
return ' '.join ( set ( pietro[ 'Borough' ].tolist ( ) ) )
def find_best_flats ( dane ):
dane2 = add_borough ( dane )
isWinogrady = dane2[ 'Borough' ] == 'Winogrady'
isPierwsze = dane2[ 'Floor' ] == 1
isTrzypokojowe = dane2[ 'Rooms' ] == 3
best = dane2[ isWinogrady & isPierwsze & isTrzypokojowe ]
return best
def main ( ):
dane = wczytaj_dane ( )
print(dane[ :5 ])
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("Średnia cena mieszkania 3-pokojowego, to: {:.2f}".format ( mean_price ( dane , 3 ) ))
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()
main ( )