In [1]:
a = 1
a
Out[1]:
In [2]:
a = "ciao"
a
Out[2]:
In [3]:
a = []
a.append(1)
a
Out[3]:
In [4]:
print(dir(__builtins__))
In [5]:
t = (1,2,3,4,5)
t
Out[5]:
In [6]:
xs = [1,2,3,4,5]
xs
Out[6]:
In [7]:
xs[2] = 10
xs
Out[7]:
In [8]:
dir(xs)
Out[8]:
In [9]:
help(xs)
In [10]:
s = "ciao"
s[1]
Out[10]:
In [11]:
for x in xs:
print(x)
In [12]:
for c in s:
print(c)
In [13]:
t[1:3]
Out[13]:
In [14]:
t[-1]
Out[14]:
In [15]:
t[::2]
Out[15]:
In [16]:
t[1::2]
Out[16]:
In [17]:
t1, t2 = t[::2], t[1::2]
In [18]:
t1
Out[18]:
In [19]:
t2
Out[19]:
In [20]:
integers, strings = 1, "ciao"
In [21]:
integers
Out[21]:
In [22]:
strings
Out[22]:
In [23]:
xs[::2]
Out[23]:
In [24]:
xs
Out[24]:
In [25]:
len(xs)
Out[25]:
In [26]:
tuple("ciao")
Out[26]:
In [27]:
tuple(xs)
Out[27]:
In [28]:
list("ciao")
Out[28]:
In [29]:
ys = [1,2,3,4,5,6,7,8,9,10]
In [30]:
yh1, yh2 = ys[:5], ys[5:]
In [31]:
yh1
Out[31]:
In [32]:
yh2
Out[32]:
In [33]:
t1 = 1,2,3
t2 = 4,5
t1 * 2
Out[33]:
In [34]:
tt = (1, 10.0, "ciao")
tt[2]
Out[34]:
In [35]:
i, f, s = tt
f
Out[35]:
Open a file
In [36]:
with open("input.txt") as a_file:
for line in a_file:
print(line.strip())
Calculate permutations
In [37]:
from itertools import permutations
for p in permutations([1,2,3]):
print(p)
Sorting a list "inplace"
In [38]:
r = [3,5,2,1,0]
r.sort()
r
Out[38]:
In [39]:
r.sort(reverse=True)
r
Out[39]:
Split a string and transform to integer
In [40]:
x = "1 2 3"
In [41]:
ints = [int(xi) for xi in x.split()]
ints
Out[41]:
Iterate on two lists
In [42]:
for x, y in zip([1,2,3], [4,5,6]):
print(x, y)
Prinf a formatted text
In [43]:
s = "Case#{}: {}".format(1, -25)
s
Out[43]:
In [44]:
myset = set([1,1,1,3,3,4,5,6,6])
myset
Out[44]:
In [45]:
for elem in myset:
print(elem)
In [46]:
3 in myset
Out[46]:
In [47]:
7 in myset
Out[47]:
In [48]:
another_set = set([1,2,8,9,7])
In [49]:
myset | another_set
Out[49]:
In [50]:
myset & another_set
Out[50]:
In [51]:
myset - another_set
Out[51]:
In [52]:
another_set - myset
Out[52]:
In [53]:
myset ^ another_set
Out[53]:
In [54]:
myset > another_set
Out[54]:
In [55]:
ss = "L'uno"
ss
Out[55]:
In [56]:
ss = '"virgolettato"'
ss
Out[56]:
In [57]:
ss = """ Si puo' mettere "tutto" """
ss
Out[57]:
In [58]:
ss[3]
Out[58]:
In [59]:
ss * 3
Out[59]:
In [60]:
ss.split()
Out[60]:
In [61]:
','.join(ss.split())
Out[61]:
In [62]:
d = {}
help(d.setdefault)
In [63]:
for n, elem in enumerate([1,5,6,7,2,3]):
print(n, elem)
In [64]:
for a,b in zip([1,2,3], ["a", "b", "c"]):
print(a, b)
In [65]:
enu = enumerate([1,5,6,7,2,3])
type(enu)
Out[65]:
In [66]:
import collections
def mydefval():
return "a default"
def_dict = collections.defaultdict(mydefval)
def_dict['hello']
def_dict
Out[66]:
In [67]:
range(10)
Out[67]:
In [68]:
sorted('abracadabra')
Out[68]:
In [69]:
reversed('abracadabra')
Out[69]:
In [70]:
d = {'a': 1, 'b':2}
d.items()
Out[70]:
In [71]:
for k, v in d.items():
print((k, v))
If we want a dict where insertion order holds, is necessary to use a OrderedDict
In [72]:
d = collections.OrderedDict()
d['a'] = 1
d['b'] = 2
for k, v in d.items():
print(k ,v)
From Python 3.7 built-in dict is insertion ordered
Question: what if I want to navigate a dict sorted in some way?
Use sorted
In [73]:
stocks = {"CSCO": 45, "APPL": 104, "IBM": 89}
sorted(stocks.items())
Out[73]:
In [74]:
sorted(stocks.items(), key=lambda x: x[1])
Out[74]:
In [75]:
sorted(stocks.items(), key=lambda x: -x[1])
Out[75]:
In [76]:
try:
1/0
except ZeroDivisionError:
print("Zero")
except Exception:
print("Base")
Private access modifier is __
(double underscore), protected is _
but is only a convention.
In [77]:
class Person:
def __init__(self, name, alias):
self.name = name
self.__alias = alias
def who(self):
"Public"
return self.name + " " + self.__alias
def _who(self):
"Protected. Is only a convention."
return self.who() + " is a superhero!"
def __who(self):
"Private"
return self._who() + " His girl friend is Mary Jane!!"
peter = Person("peter", "spiderman")
print(peter.name)
print(peter.who())
# peter.__alias
# AttributeError: 'Person' object has no attribute '__alias'
print(peter._who())
# peter.__who()
# AttributeError: 'Person' object has no attribute '__who'
# If you really want to call a private field/attribute
peter._Person__who()
Out[77]: