Wprowadzenie część 2


In [1]:
help([1, 2, 3])


Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __delitem__(...)
 |      x.__delitem__(y) <==> del x[y]
 |  
 |  __delslice__(...)
 |      x.__delslice__(i, j) <==> del x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __iadd__(...)
 |      x.__iadd__(y) <==> x+=y
 |  
 |  __imul__(...)
 |      x.__imul__(y) <==> x*=y
 |  
 |  __init__(...)
 |      x.__init__(...) initializes x; see help(type(x)) for signature
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  __setitem__(...)
 |      x.__setitem__(i, y) <==> x[i]=y
 |  
 |  __setslice__(...)
 |      x.__setslice__(i, j, y) <==> x[i:j]=y
 |      
 |      Use  of negative indices is not supported.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -- append object to end
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
 |      cmp(x, y) -> -1, 0, 1
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T


In [2]:
dir([1, 2, 3])


Out[2]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__delslice__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__setslice__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

In [3]:
sum??

Funkcje wbudowane


In [3]:
all([1==1, True, 10, -1, False, 3*5==1]), all([1==5, True, 10, -1])


Out[3]:
(False, False)

In [5]:
any([False, True]), any([False, False])


Out[5]:
(True, False)

In [4]:
bin(12), oct(12), hex(12), int('12'), float(12.)


Out[4]:
('0b1100', '014', '0xc', 12, 12.0)

In [5]:
ord('A'), chr(65)


Out[5]:
(65, 'A')

In [8]:
raw_input(u"Podaj liczbę: ")


Podaj liczbę: 24
Out[8]:
'24'

In [7]:
zip([1,2,3, 3], [2, 3, 4, 10])


Out[7]:
[(1, 2), (2, 3), (3, 4), (3, 10)]

In [10]:
sorted([8, 3, 12, 9, 3]), reversed(range(10)), list(reversed(range(10)))


Out[10]:
([3, 3, 8, 9, 12],
 <listreverseiterator at 0x108878650>,
 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

In [11]:
len([3, 2, 1]), len([[1, 2], [3, 4, 5]])


Out[11]:
(3, 2)

In [12]:
list(), dict(), set(), tuple()


Out[12]:
([], {}, set(), ())

Tuple (krotka)


In [13]:
A = (1, 2, 3)
B = [1, 2, 3]
A == B


Out[13]:
False

Czym się różni krotka od listy?

Set (zbiory)


In [14]:
A = set()
A.add(2)
A.add(3)
A.add(4)
A


Out[14]:
{2, 3, 4}

In [15]:
A.add(3)
A


Out[15]:
{2, 3, 4}

In [16]:
B = set((4, 5, 6))
A.difference(B)


Out[16]:
{2, 3}

In [17]:
A.symmetric_difference(B)


Out[17]:
{2, 3, 5, 6}

In [18]:
A.intersection(B)


Out[18]:
{4}

In [19]:
A.union(B)


Out[19]:
{2, 3, 4, 5, 6}

Prosta matematyka


In [20]:
pow(2, 10), divmod(10, 3), sum([1, 2, 3])


Out[20]:
(1024, (3, 1), 6)

In [21]:
round(0.5), round(0.2), round(0.9)


Out[21]:
(1.0, 0.0, 1.0)

In [22]:
min([1, 2, 3]), max([1, 2, 3])


Out[22]:
(1, 3)

In [23]:
abs(10), abs(-10)


Out[23]:
(10, 10)

In [24]:
24 % 5, 24 % 2


Out[24]:
(4, 0)

Trochę programowania funkcyjnego

map, filter, reduce

wyrażenie lambda $\lambda$


In [25]:
f = lambda x: x+1
f(3)


Out[25]:
4

In [26]:
f = lambda a, b: a+b**3

In [27]:
f(2, 3)


Out[27]:
29

In [28]:
map(lambda x: x+10, [0, 2, 5, 234])


Out[28]:
[10, 12, 15, 244]

In [29]:
[x+10 for x in [0, 2]]


Out[29]:
[10, 12]

In [30]:
map(chr, [80, 121, 67, 105, 114, 99, 108, 101])


Out[30]:
['P', 'y', 'C', 'i', 'r', 'c', 'l', 'e']

In [31]:
[chr(x) for x in  [80, 121, 67, 105, 114, 99, 108, 101]]


Out[31]:
['P', 'y', 'C', 'i', 'r', 'c', 'l', 'e']

In [32]:
filter(lambda x: x > 0, [-1, 0, 4, -3, 2])


Out[32]:
[4, 2]

In [33]:
[x for x in [-1, 0, 4, -3, 2] if x > 0]


Out[33]:
[4, 2]

In [34]:
reduce(lambda a, b: a - b, [2, 3, 4])


Out[34]:
-5

In [35]:
2 - 3 - 4


Out[35]:
-5

Więcej informacji temat funkcji wbudowanych na https://docs.python.org/2/library/functions.html

Zadania 1

1 . Napisz kod tworzący listę z przedziału $[0, 100]$ liczb podzielnych przez 3 ale nie podzielnych przez 9


In [ ]:

2 . Napisz kod który zwraca unikalne elementy z podanej listy


In [ ]:

3 . Napisz kod który znajdzie maksimum wartości słownika


In [ ]:

Pliki


In [39]:
%ls -l


total 152
-rw-r--r--  1 nozdi  staff  11358 Oct 31 21:42 LICENSE
-rw-r--r--  1 nozdi  staff  24463 Oct 31 21:42 pycircle_wprowadzenie_1.ipynb
-rw-r--r--  1 nozdi  staff  38260 Nov  3 11:00 wprowadzenie_2.ipynb

In [40]:
fp = open("pycircle.txt", "w")

In [41]:
%ls -l


total 152
-rw-r--r--  1 nozdi  staff  11358 Oct 31 21:42 LICENSE
-rw-r--r--  1 nozdi  staff      0 Nov  3 14:21 pycircle.txt
-rw-r--r--  1 nozdi  staff  24463 Oct 31 21:42 pycircle_wprowadzenie_1.ipynb
-rw-r--r--  1 nozdi  staff  38260 Nov  3 11:00 wprowadzenie_2.ipynb

In [42]:
fp.write("Hello world\n")
fp.close()

In [43]:
%cat pycircle.txt


Hello world

In [44]:
with open("pycircle.txt") as fp:
    print fp.read(),


Hello world

Funkcje


In [45]:
def fun1(a):
    a.append(9)
    return a
    
def fun2(a=[]):
    a.append(9)
    return a

In [46]:
lista1 = [1, 2, 3]
lista2 = [3, 4, 5]
fun1(lista1), fun2(lista2)


Out[46]:
([1, 2, 3, 9], [3, 4, 5, 9])

In [47]:
def fun2(a=[]):
    a.append(9)
    return a
fun2()


Out[47]:
[9]

In [48]:
fun2()


Out[48]:
[9, 9]

In [49]:
fun2()


Out[49]:
[9, 9, 9]

LEGB


In [50]:
def show_local():
    x = 23
    print("Local: %s" % x)
show_local()


Local: 23

In [51]:
def show_enclosing(a):
    def enclosing():
        print("Enclosing: %s" % a)
    enclosing()
show_enclosing(5)


Enclosing: 5

In [52]:
x = 43
def show_global():
    print("Global %s" % x)
show_global()


Global 43

In [53]:
def show_built():
    print("Built-in: %s" % abs)
show_built()


Built-in: <built-in function abs>

In [54]:
x = 43
def what_x():
    print(x)
    x = 4

In [55]:
what_x()


---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-55-f061f9c5a837> in <module>()
----> 1 what_x()

<ipython-input-54-45c519b87497> in what_x()
      1 x = 43
      2 def what_x():
----> 3     print(x)
      4     x = 4

UnboundLocalError: local variable 'x' referenced before assignment

In [56]:
x = 43
def encl_x():
    x = 23
    def enclosing():
        print("Enclosing: %s" % x)
    enclosing()

In [57]:
encl_x()


Enclosing: 23

In [59]:
x = 43
def what_about_globals():
    global x
    x = 37
    print("In function %s" % x)

In [60]:
what_about_globals()
print("After function %s" % x)


In function 37
After function 37

Funkcje to też obiekty!


In [61]:
def f(x):
    f.l += x
    print "x: ", x
    print "f.l: ", f.l
f.l = 10

In [62]:
f(2)
f(14)


x:  2
f.l:  12
x:  14
f.l:  26

Fabryki funkcji


In [63]:
def powerer(power):
    def nested(number):
        return number ** power
    return nested

In [64]:
f = powerer(3)
f(2), f(10)


Out[64]:
(8, 1000)

In [65]:
def licznik(start):
    def nested(label):
        print(label, nested.state)
        nested.state += 1
    nested.state = start
    return nested

In [66]:
f = licznik(0)
f('a')
f('b')
f('c')


('a', 0)
('b', 1)
('c', 2)

Zadania 2

1 . Napisz funkcję która stworzy plik z pierwiastkami liczb z zakresu $[0, 100]$ (całkowite), każdy w osobnej linii


In [ ]:

2 . Napisz funkcję wczytująca pierwiastki z pliku z poprzedniego zadania, oblicz ich sumę i dopisz do pliku


In [ ]:

3 . Napisz funkcję która będzie działała jak ''.join() za pomocą reduce


In [1]:
' '.join(['a', 'b', 'c'])


Out[1]:
'a b c'

In [6]:
def my_join(joining_str, list_of_str):
    return reduce

In [7]:
my_join(" ", ['a', 'b', 'c'])


Out[7]:
<function reduce>

In [8]:
' '.join(['a', 'b', 'c'])


Out[8]:
'a b c'

In [ ]: