Compare commits

..

34 Commits

Author SHA1 Message Date
Przemysław Kaczmarek
2cc5813593 resolved 2018-01-12 18:30:33 +01:00
Przemysław Kaczmarek
2203a269d5 resolved 2018-01-12 18:03:53 +01:00
Przemysław Kaczmarek
83f27fc1a9 resolved 2018-01-12 17:54:03 +01:00
Przemysław Kaczmarek
b987dc0cc0 resolved 2018-01-12 17:37:46 +01:00
Przemysław Kaczmarek
ad873598bb resolved 2018-01-12 16:55:14 +01:00
Przemysław Kaczmarek
dce7564e23 resolved 2018-01-11 21:14:43 +01:00
Przemysław Kaczmarek
c1259d2d03 resolved 2018-01-11 19:59:37 +01:00
Przemysław Kaczmarek
aac65580c0 resolved 2018-01-11 19:48:24 +01:00
Przemysław Kaczmarek
0ec6182dde resolved 2018-01-11 19:23:47 +01:00
Przemysław Kaczmarek
8343e028b0 resolved 2018-01-11 18:28:31 +01:00
Przemysław Kaczmarek
91ba66165d resolved 2018-01-11 18:20:25 +01:00
Przemysław Kaczmarek
e0beb9d336 resolved 2017-12-14 20:31:14 +01:00
Przemysław Kaczmarek
aed06ae658 in progress 2017-12-14 20:02:17 +01:00
Przemysław Kaczmarek
8d38a7ddb4 in progress 2017-12-14 18:44:10 +01:00
Przemysław Kaczmarek
cf0d9945b9 Resolved 2017-12-14 18:09:05 +01:00
s45151
a37ec78f22 resolve2 2017-12-03 15:36:13 +01:00
s45151
66223f51c8 resolve2 2017-12-03 15:22:45 +01:00
s45151
f841b1e161 resolve2 2017-12-03 13:44:41 +01:00
s45151
c7c39c177c resolve 2017-12-03 13:42:49 +01:00
s45151
3be168820c Merge branch 'master' of https://git.wmi.amu.edu.pl/tdwojak/Python2017 2017-12-03 13:21:55 +01:00
s45151
72bb0119a7 resolve 2017-12-02 15:33:12 +01:00
s45151
30a30cb566 resolve 2017-12-02 15:32:00 +01:00
Przemysław Kaczmarek
ccd03ece50 Resolved 2017-11-28 19:47:40 +01:00
Przemysław Kaczmarek
4e8b83e4f2 Resolved 2017-11-28 19:46:52 +01:00
Przemysław Kaczmarek
d9564f3b1a Resolved 2017-11-28 19:38:07 +01:00
Przemysław Kaczmarek
4f6c4e9062 Resolved 2017-11-28 19:12:03 +01:00
Przemysław Kaczmarek
02728e80a3 Resolved 2017-11-28 18:50:00 +01:00
Przemysław Kaczmarek
9115943f9c Resolved 2017-11-28 18:44:32 +01:00
Przemysław Kaczmarek
2438b456f4 Resolved 2017-11-28 18:42:38 +01:00
Przemysław Kaczmarek
d2dfa3bfce Resolved 2017-11-28 18:38:06 +01:00
Przemysław Kaczmarek
92127f821f Resolved 2017-11-28 18:37:51 +01:00
Przemysław Kaczmarek
b195295736 Resolved 2017-11-28 18:31:17 +01:00
Przemysław Kaczmarek
87b7b6d675 Resolved 2017-11-28 18:27:00 +01:00
s45151
76f3b5ba55 First commit 2017-11-19 15:43:25 +01:00
30 changed files with 861 additions and 700 deletions

11
.idea/Python2017.iml Normal file
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.4.3 (C:\Python34\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.iml" filepath="$PROJECT_DIR$/.idea/Python2017.iml" />
</modules>
</component>
</project>

View File

@ -1,124 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
import git
import os
import importlib
import collections
import csv
logger = logging.getLogger('Homeworks')
logger.setLevel(logging.DEBUG)
fm = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch = logging.StreamHandler()
ch.setFormatter(fm)
logger.addHandler(ch)
def arg_parse():
parser = argparse.ArgumentParser(description='Framework for checking homeworks.')
parser.add_argument('-i', '--ids', type=str,
help='path to a file with student ids.')
return parser.parse_args()
def get_ids(path):
ids = []
with open(path) as _file:
for line in _file:
ids.append(line.strip().split(' ')[::2])
return ids
def clone_repo(username, repo_name):
repo = "https://git.wmi.amu.edu.pl/{}/{}.git".format(username, repo_name)
dest = "./Python2017-{}".format(username)
if os.path.exists(dest):
logger.debug("{}: repo exests.".format(username))
else:
try:
git.Repo.clone_from(repo, dest)
except git.GitCommandError:
logger.info("Repository '{}' does not exist".format(repo))
return False
return True
def check_tasks(username, repo_name, tasks):
logger.debug("Marking user: {}".format(username))
scores = collections.defaultdict(dict)
for lab in tasks:
path = os.path.realpath("./Python2017-{}/{}".format(username, lab))
for task, fun in tasks[lab]:
task_file = path + "/{}". format(task)
logger.debug(task_file)
package = 'Python2017-{}.{}.{}'.format(username, lab, task)
lib = importlib.import_module(package)
tested_fun = getattr(lib, fun)
tests = getattr(lib, 'tests')
try:
test_result = tests(tested_fun)
except Exception:
test_result = "FAILED"
if test_result == 'TESTS PASSED':
scores[lab][task] = 1
else:
scores[lab][task] = 0
return scores
def get_fieldnames(tasks):
fieldnames = ['ID']
for lab in tasks:
for task, _ in tasks[lab]:
fieldnames.append('{}:{}'.format(lab, task))
return fieldnames
def parse_scores(fieldnames, uname, scores):
out = {}
for name in fieldnames:
if name == 'ID':
out[name] = uname
continue
lab, task = name.split(':')
out[name] = scores[lab][task]
return out
def write_scores(scores, filename, tasks):
fieldnames = get_fieldnames(tasks)
with open(filename, 'w') as results:
writer = csv.DictWriter(results, fieldnames, restval=0)
writer.writeheader()
for student in scores:
writer.writerow(parse_scores(fieldnames, student, scores[student]))
def main():
""" main """
options = arg_parse()
ids = get_ids(options.ids)
logger.info("Liczba studentów: {}".format(len(ids)))
scores = {}
tasks = {
'labs02' : [
('task07', 'char_sum'),
('task08', 'sum_div35'),
('task09', 'leet_speak'),
('task10', 'pokemon_speak'),
('task11', 'common_chars')
]
}
for repo_id in ids:
st_uname = repo_id[0]
repo_name = repo_id[-1]
if clone_repo(st_uname, repo_name):
scores[st_uname] = check_tasks(st_uname, repo_name, tasks)
write_scores(scores, 'results.csv', tasks)
if __name__ == "__main__":
main()

View File

@ -1,38 +0,0 @@
ID | labs02:task07 | labs02:task08 | labs02:task09 | labs02:task10 | labs02:task11 | labs03 | labs04 | labs06 | Punkty | Ocena |
---------|-----------------|-----------------|-----------------|-----------------|-----------------|----------|----------|----------|--------|-------|
s45146 | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 8 | 22 | 5 |
s45147 | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 8 | 22 | 5 |
s45148 | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 8 | 22 | 5 |
s45150 | 1 | 1 | 1 | 1 | 1 | 2 | 1 | 8 | 16 | 4 |
s45151 | 1 | 1 | 1 | 1 | 1 | 0 | 5 | 8 | 18 | 4.5 |
s45152 | 1 | 1 | 1 | 0 | 1 | 0 | 5 | 8 | 17 | 4 |
s45153 | 0 | 1 | 1 | 1 | 1 | 4 | 0 | 8 | 16 | 4 |
s45155 | 1 | 1 | 1 | 1 | 1 | 1 | 5 | 8 | 19 | 4.5 |
s45156 | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 8 | 22 | 5 |
s45157 | 1 | 1 | 1 | 1 | 1 | 4 | 4 | 8 | 21 | 5 |
s45158 | 1 | 1 | 0 | 0 | 1 | 4 | 5 | 8 | 19 | 4.5 |
s45159 | 1 | 1 | 1 | 1 | 1 | 2 | 3 | 8 | 18 | 4.5 |
s45160 | 1 | 1 | 1 | 1 | 1 | 4 | 4 | 8 | 21 | 5 |
s45161 | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 8 | 22 | 5 |
s45162 | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 8 | 22 | 5 |
s45163 | 1 | 1 | 1 | 1 | 1 | 4 | 4 | 8 | 21 | 5 |
s45164 | 1 | 1 | 0 | 1 | 0 | 0 | 5 | 8 | 16 | 4 |
s45165 | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 8 | 22 | 5 |
s45166 | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 8 | 22 | 5 |
s45167 | 1 | 1 | 1 | 1 | 1 | 0 | 5 | 8 | 17 | 4 |
s45168 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
s45452 | 1 | 1 | 1 | 1 | 1 | 4 | 4 | 8 | 21 | 5 |
szwedek | 1 | 1 | 1 | 1 | 1 | 4 | 5 | 10 | 24 | 5 |
Skala:
Punkty | Ocena |
-------|-------|
24-20 | 5 |
19-18 | 4.5 |
17-16 | 4 |
15-13 | 3 |
12-0 | 2 |
Max: 22

View File

@ -6,8 +6,14 @@ Zad 2. Napisz funkcję even_elements zwracającą listę,
która zawiera tylko elementy z list o parzystych indeksach. która zawiera tylko elementy z list o parzystych indeksach.
""" """
def even_elements(lista): def even_elements(lista):
pass newlist=[]
for element in lista:
if lista.index(element)%2==0:
newlist.append(element)
return newlist
def tests(f): def tests(f):

View File

@ -5,8 +5,11 @@
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(year):
pass if (year%4 == 0 and year%100 != 0) or year%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,14 @@ jak 'set', która przechowuje elementy bez powtórzeń.)
def oov(text, vocab): def oov(text, vocab):
text_words=text.split()
oov_list=[]
for word in text_words:
if word in vocab:
pass pass
else:
oov_list.append(word)
return oov_list
def tests(f): def tests(f):
@ -30,3 +36,5 @@ def tests(f):
if __name__ == "__main__": if __name__ == "__main__":
print(tests(oov)) print(tests(oov))

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): def sum_from_one_to_n(n):
pass results=0
if n<1:
return results
else:
for i in range(n+1):
results+=i
return results
def tests(f): def tests(f):

View File

@ -8,9 +8,14 @@ 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 value=0
for i in range(3):
value+=math.pow((y[i]-x[i]),2)
return math.sqrt(value)
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,14 @@ ma być zwracany napis "It's not a Big 'No!'".
""" """
def big_no(n): def big_no(n):
pass string="N"
if n<5:
return "It's not a Big 'No!'"
else:
for i in range(n):
string+="O"
return string+"!"
def tests(f): def tests(f):
inputs = [[5], [6], [2]] inputs = [[5], [6], [2]]

View File

@ -6,7 +6,10 @@ 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 results=0
for letter in text:
results+=ord(letter)
return results
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 results=0
for i in range(n):
if i%3==0 or i%5==0:
results+=i
return results
def tests(f): def tests(f):
inputs = [[10], [100], [3845]] inputs = [[10], [100], [3845]]
@ -21,4 +25,3 @@ def tests(f):
if __name__ == "__main__": if __name__ == "__main__":
print(tests(sum_div35)) print(tests(sum_div35))

View File

@ -9,7 +9,20 @@ Np. leet('leet') powinno zwrócić '1337'.
def leet_speak(text): def leet_speak(text):
pass new_text=[]
for i in range(len(text)):
if text[i] == 'e':
new_text.append('3')
elif text[i] == 'l':
new_text.append('1')
elif text[i] == 'o':
new_text.append('0')
elif text[i] == 't':
new_text.append('7')
else:
new_text.append(text[i])
return ("".join(new_text))
def tests(f): def tests(f):
@ -24,3 +37,5 @@ def tests(f):
if __name__ == "__main__": if __name__ == "__main__":
print(tests(leet_speak)) print(tests(leet_speak))

View File

@ -9,8 +9,13 @@ na wielką. Np. pokemon_speak('pokemon') powinno zwrócić 'PoKeMoN'.
def pokemon_speak(text): def pokemon_speak(text):
pass pokemon_text=[]
for i in range(len(text)):
if i%2==0 and ord(text[i])>=97 and ord(text[i])<=122:
pokemon_text.append(str(chr(ord(text[i])-32)))
else:
pokemon_text.append((text[i]))
return "".join(pokemon_text)
def tests(f): def tests(f):
inputs = [['pokemon'], ['do not want'], ['POKEMON']] inputs = [['pokemon'], ['do not want'], ['POKEMON']]

View File

@ -8,8 +8,18 @@ uporządkowaną listę wspólnych liter z lańcuchów string1 i string2.
Oba napisy będą składać się wyłacznie z małych liter. Oba napisy będą składać się wyłacznie z małych liter.
""" """
def common_chars(string1, string2): def common_chars(string1, string2):
pass common_letters=[]
results=[]
for letter in string1:
if letter in string2 and ord(letter)<=122 and ord(letter)>=97:
common_letters.append(ord(letter))
common_letters=set(common_letters)
print(common_letters)
for letter in common_letters:
results.append(chr(letter))
return results
def tests(f): def tests(f):

View File

@ -6,7 +6,7 @@ def suma(a, b):
""" """
Napisz funkcję, która zwraca sumę elementów. Napisz funkcję, która zwraca sumę elementów.
""" """
return a + b pass
def tests(f): def tests(f):
inputs = [(2, 3), (0, 0), (1, 1)] inputs = [(2, 3), (0, 0), (1, 1)]
@ -18,4 +18,5 @@ def tests(f):
break break
return "TESTS PASSED" return "TESTS PASSED"
if __name__ == "__main__":
print(tests(suma)) print(tests(suma))

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,28 +104,16 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 11, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 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,47 +126,29 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 17, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3]\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": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1], [1], [1]]\n"
]
}
],
"source": [ "source": [
"e = []\n", "e = []\n",
"f = [e for i in range(3)]\n", "f = [e for i in range(3)]\n",
@ -214,39 +172,18 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 25, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "slide" "slide_type": "slide"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"(1, 'napis', [0])\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,29 +199,19 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 36, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"15\n",
"a == 1\n",
"b == (3, 4)\n"
]
}
],
"source": [ "source": [
"def suma(*args):\n", "def suma(*args):\n",
" 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,32 +231,16 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 38, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"97\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,74 +260,40 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 45, "execution_count": null,
"metadata": { "metadata": {
"slideshow": { "slideshow": {
"slide_type": "fragment" "slide_type": "fragment"
} }
}, },
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"W Paryżu najlepsze kasztany są na placu Pigalle\n",
"Zuzanna lubi je tylko jesienią.\n",
"\n",
">>\n"
]
}
],
"source": [ "source": [
"plik = open(\"haslo.txt\", 'r')\n", "plik = open(\"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())\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 +334,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 +351,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 +394,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))"

32
labs03/zadanie 1.py Normal file
View File

@ -0,0 +1,32 @@
"""
**ć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:
* lista,
* napis (string),
* liczba zmiennoprzecinkowa.
"""
def f(typ):
return id(typ)
def tests():
lista=[1,2,3]
napis='1234'
float=1.42
id_table_back = [f(lista),f(napis),f(float)]
typ = ['lista','napis','liczba zmiennoprzecinkowa']
lista.append(5)
napis='1234'+'5'
float*=2
id_table_now = [f(lista), f(napis), f(float)]
for i in range(len(id_table_back)):
if id_table_back[i]==id_table_now[i]:
print(typ[i],'jest mutable')
else:
print(typ[i],'jest immutable')
tests()

25
labs03/zadanie 2.py Normal file
View File

@ -0,0 +1,25 @@
"""
**ć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 FiboGenerator(n):
for i in range(n):
if n==0:
return 1
elif n==1:
return 1
else:
return FiboGenerator(n-1)+FiboGenerator(n-2)
"""
def tests(f):
inputs = [0,1,2,3,4,5,6,7,8]
for input in zip(inputs):
print(f(2))
if __name__ == "__main__":
print(tests(FiboGenerator))
"""
print(FiboGenerator(1))

19
labs03/zadanie 3.py Normal file
View File

@ -0,0 +1,19 @@
"""
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
import json
def script():
page='https://api.fixer.io/latest'
r=requests.get(page)
r.status_code
r.encoding
r.text
data_json=r.json()
print(data_json['rates'],data_json['rates'].values())
script()

View File

@ -1,3 +1,34 @@
#!/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(n):
if isinstance(n,int):
return 'type int'
elif isinstance(n,float):
return 'type float'
elif isinstance(n,str):
return 'type string'
else:
return 'type unavailable'
def tests(f):
inputs = [1,2,5,'test',2,4.32423]
outputs = ['type int','type int','type int','type string','type int','type float']
for input, output in zip(inputs, outputs):
if f(input) != (output):
return "ERROR: {}!={}".format(f(input), output)
break
return "TESTS PASSED"
if __name__ == "__main__":
print(tests(is_numeric))

View File

@ -1,3 +1,82 @@
#!/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. 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
@staticmethod
def add_id():
Employee.id+=1
return id
def __init__(self, name, surname):
Employee.add_id()
self.id = Employee.id
self.name = name
self.surname = surname
def get_id(self):
return self.id
def __repr__(self):
return '<Employee, %s, %s %s>' % (self.id,self.name,self.surname)
class Recruiter(Employee):
def __init__(self,name,surname):
super().__init__(name,surname)
self.recruited=[]
def recruite(self,Employee):
self.recruited.append(Employee.get_id())
def __repr__(self):
return '<Recruiter, %s, %s %s>' % (self.id, self.name, self.surname)
class Programmer(Employee):
def __init__(self,name,surname,Recruiter):
super().__init__(name,surname)
self.recruiter = Recruiter.get_id()
def __repr__(self):
return '<Programmer, %s, %s %s>' % (self.id, self.name, self.surname)
def TestFunction():
pracownik_przemek=Employee('Przemyslaw','Kaczmarek')
print(pracownik_przemek.name,pracownik_przemek.surname)
pracownik_michal=Employee('Michał','Kowalski')
rekruter_mariusz=Recruiter('Mariusz','Małysz')
programista_adam=Programmer('Adam','Kowalski',rekruter_mariusz)
rekruter_maciej=Recruiter('Maciej','Fisko')
rekruter_maciej.recruite(pracownik_przemek)
rekruter_maciej.recruite(rekruter_mariusz)
rekruter_mariusz.recruite(programista_adam)
rekruter_mariusz.recruite(pracownik_michal)
print('Maciej zrekrutowal: ',rekruter_maciej.recruited)
print('Mariusz zrekrutowal: ',rekruter_mariusz.recruited)
print('Adam zostal zrekrutowany przez: ',programista_adam.recruiter)
print('Liczba pracownikow: ',Employee.id)
print(pracownik_przemek)
print(pracownik_michal)
print(rekruter_mariusz)
print(programista_adam)
print(rekruter_maciej)
TestFunction()

View File

@ -1,3 +1,89 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
class DimensionError(Exception):
"""Discreapncies in dimensions. We cannot add points from different dimension"""
def __init__(self):
super().__init__(self)
self.msg='Discreapncies in dimensions. We cannot add points from different dimension'
class IsNumericError(Exception):
"""Point contains other chars than numbers"""
def __init__(self):
super().__init__(self)
self.msg='Point contains other chars than numbers'
class Point():
def __init__(self,list):
try:
if Point.is_numeric(list)!=len(list):
self.points=[]
self.isnumeric = False
raise IsNumericError()
else:
self.points=list
self.isnumeric=True
except IsNumericError as e:
print(e.msg)
def __repr__(self):
return '<Point %s, is numeric: %s>' %(self.points,self.isnumeric)
def __add__(self, other):
try:
new = []
if self.isnumeric==False or other.isnumeric==False:
raise IsNumericError()
elif len(self.points) != len(other.points):
raise DimensionError()
else:
for index in range(len(self.points)):
new.append(self.points[index]+other.points[index])
except IsNumericError as e:
print(e.msg)
except DimensionError as e:
print(e.msg)
return new
def __len__(self):
len=0
try:
if self.isnumeric==False:
raise IsNumericError()
else:
for element in self.points:
len+=1
except IsNumericError as e:
print(e.msg)
return len
@staticmethod
def is_numeric(point):
value=0
for element in point:
if isinstance(element, int) or isinstance(element, float):
value+=1
return value
def to_string(self):
point_tuple = tuple(self.points)
return str(point_tuple)
def __str__(self):
return (self.to_string())
def TestFunction():
punkt1=Point([1,2,2])
punkt2=Point([1,7,25])
print('Ilosc wymiarow: ', len(punkt1))
print('Ilość wymiarów: ', len(punkt2))
punkt3=punkt1+punkt2
print('punkt1 + punkt2 = ',punkt3)
print(punkt1.to_string(),punkt1)
print(punkt2.to_string(),punkt2)
#punkt1.__str__()
TestFunction()

View File

@ -1,11 +1,15 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""
Napisz funkcję ``suma``, która przyjmnie jeden argument: listę liczb i zwróci ich sumę.
"""
def suma(liczby): def suma(liczby):
pass return sum(liczby)
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,22 @@
"""
** 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 proramu. Załóź, że argumentami do programu będą tylko liczby zmiennoprzecinkowe.
"""
from task00 import suma
import sys
def main():
arguments=sys.argv[1:]
float_arguments=[]
for arg in arguments:
float_arguments.append(float(arg))
print(suma(float_arguments))
if __name__ == '__main__':
main()

View File

@ -0,0 +1,25 @@
"""
** 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ą.
"""
from task00 import suma
import sys
def main():
arg_list = sys.argv[1:]
float_arg_list = []
for arg in arg_list:
try:
float_arg=float(arg)
float_arg_list.append(float_arg)
except:
float_arg_list.append(0)
print(suma(float_arg_list))
if __name__ == '__main__':
main()

View File

@ -4,9 +4,19 @@
""" """
Implementacja narzedzia ``wc`` z linuksa (word counter). Implementacja narzedzia ``wc`` z linuksa (word counter).
Zwraca liczbę słów, znaków i linii. Zwraca liczbę słów, znaków i linii.
** zad. 4 (Domowe) **
Plik ``task04.py`` zawiera kod prorgamu, który działa jak popularne narzędzie unixowe ``wc`` (Word Counter): zlicza liczbę linii, wyrazów i znaków.
Aktualnie program potrafi działać wyłącznie na wejściu podanym z klawiatury. Dodaj do niego opcje programu:
* domyślnie program ma zliczać na wejściu z klawiatury (stdin) i wyświetlać wszystkie 3 liczby.
* Jeżeli został podany przełącznik `-l`, to to ma zostać zwrócona tylko liczba linii.
* Jeżeli został podany przełącznik `-w`, to to ma zostać zwrócona tylko liczba słów.
* Jeżeli został podany przełącznik `-c`, to to ma zostać zwrócona tylko liczba znaków.
* Jeżeli został podany inny argument, to należy założyć że jest to nazwa pliku i potraktować ten plik jako wejście do programu.
""" """
import sys import sys
import argparse
def count_lines(text): def count_lines(text):
@ -19,7 +29,7 @@ def count_words(text):
for line in text.split('\n')]) for line in text.split('\n')])
def count_chars(text): def count_chars(text):
""" return number of words. """ """ return number of characters. """
return len(text) return len(text)
def wc(text): def wc(text):
@ -32,7 +42,28 @@ def wc(text):
def main(): def main():
""" 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 chars", action="store_true")
parser.add_argument('-filename', type=argparse.FileType('r'), default='-', help='filename to read from')
args = parser.parse_args()
if args.filename:
lines, words, chars = wc(args.filename.read())
elif not sys.stdin.isatty():
lines, words, chars = wc(args.stdin.read())
else:
pass
if(args.l):
print(lines)
elif(args.w):
print(words)
elif(args.c):
print(chars)
else:
print(lines, words, chars)
if __name__ == "__main__": if __name__ == "__main__":

54
labs06/task02.py Executable file → Normal file
View File

@ -1,14 +1,22 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pandas as pd
import statistics
def wczytaj_dane(): def wczytaj_dane():
pass raw_data = pd.read_csv('mieszkania.csv',sep=',')
data = pd.DataFrame(raw_data)
return data
def most_common_room_number(dane): def most_common_room_number(dane):
pass rooms=dane['Rooms']
return(int(statistics.mode(rooms)))
def cheapest_flats(dane, n): def cheapest_flats(dane, n):
pass cheapest=pd.DataFrame(dane['Expected'])
cheapest.sort=cheapest.sort_values(by=['Expected'])
return cheapest.sort[:n]
def find_borough(desc): def find_borough(desc):
dzielnice = ['Stare Miasto', dzielnice = ['Stare Miasto',
@ -19,23 +27,46 @@ def find_borough(desc):
'Winogrady', 'Winogrady',
'Miłostowo', 'Miłostowo',
'Dębiec'] 'Dębiec']
pass for dzielnica in dzielnice:
if desc.find(dzielnica)!=-1:
return dzielnica
return 'Inne'
def add_borough(dane): def add_borough(dane):
pass borough_list=[]
for data in dane['Location']:
borough_list.append(find_borough(data))
borough_series = pd.Series(borough_list,name='Borough')
dane['Borough']=borough_series
return dane
def write_plot(dane, filename): def write_plot(dane, filename):
pass data = add_borough(dane)
plot_data = data.groupby(dane['Borough']).size()
plt = plot_data.plot.bar()
fig = plt.get_figure()
fig.savefig('{}.png'.format(filename))
return 0
def mean_price(dane, room_number): def mean_price(dane, room_number):
pass data=dane.loc[dane['Rooms'] == room_number]
return round(statistics.mean(data['Expected']),2)
def find_13(dane): def find_13(dane):
pass data = add_borough(dane)
boroughs = data.loc[data['Floor'] == 13]
return set(boroughs['Borough'])
def find_best_flats(dane): def find_best_flats(dane):
pass data = add_borough(dane)
best_flats = data.loc[(data['Borough'] == 'Winogrady') & (data['Floor'] == 1) & (data['Rooms'] == 3)]
return best_flats
def main(): def main():
dane = wczytaj_dane() dane = wczytaj_dane()
@ -45,10 +76,13 @@ 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)))
if __name__ == "__main__": if __name__ == "__main__":
main() main()