Basic Python Training at Arcesium - Day 2

Jun 03-04, 2019 Vikrant Patil

These notes are available online at http://notes.pipal.in/2019/arcesium_basic_jun/day2.html

© Pipal Academy LLP

Day 1 | Day 2

We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from

https://www.anaconda.com/download/

problems

  • Write a function factors using list comprehension which finds all factors of given number.
  • write a function is_prime which tells whether given number is prime or not
  • write a function primes which generates all primes less than n

bonus

  • generate a unit matrix of size 5x5 using list comprehension. a unit matrix has all elements zero except diagonal. diagonal is 1.
  • find sum of all multiples of 7 or 11 below 1000.
  • generate multiplication tables from 1 to 5.
In [4]:
def factors(n):
    return [i for i in range(1,n+1) if n%i==0]

def test_factors():
    assert factors(2) == [1,2]
    assert factors(5) == [1,5]
    assert factors(6) == [1,2,3,6]
    assert factors(10) == [1,10]
In [5]:
test_factors()
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-5-e910a19b2ce4> in <module>
----> 1 test_factors()

<ipython-input-4-35f9d20aabbc> in test_factors()
      6     assert factors(5) == [1,5]
      7     assert factors(6) == [1,2,3,6]
----> 8     assert factors(10) == [1,10]

AssertionError: 
In [6]:
factors(10)
Out[6]:
[1, 2, 5, 10]
In [8]:
def is_prime(p):
    return factors(p) == [1,p]

def prime_check(p):
    if len(factors(p))==2:
        return True
    else:
        return False
In [9]:
is_prime(12)
Out[9]:
False
In [10]:
is_prime(13)
Out[10]:
True
In [11]:
def primes(n):
    return [p for p in range(2,n) if is_prime(p)]
In [14]:
primes(50)
Out[14]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In [15]:
x = [[1, 0, 0],
     [0, 1, 0],
     [0, 0, 1]]
In [16]:
[[(i,j) for i in range(5)] for j in range(5)]
Out[16]:
[[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)],
 [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1)],
 [(0, 2), (1, 2), (2, 2), (3, 2), (4, 2)],
 [(0, 3), (1, 3), (2, 3), (3, 3), (4, 3)],
 [(0, 4), (1, 4), (2, 4), (3, 4), (4, 4)]]
In [17]:
def diagonal(i, j):
    if i==j:
        return 1
    else:
        return 0
In [18]:
[[diagonal(i, j) for i in range(5)] for j in range(5)]
Out[18]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
In [20]:
[[1 if i==j else 0 for i in range(5)] for j in range(5)]
Out[20]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
In [21]:
d = {True:1, False:0}
In [22]:
[[d[i==j] for i in range(5)] for j in range(5)]
Out[22]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
In [23]:
sum([i for i in range(1000) if i%7==0 or i%11==0])
Out[23]:
110110
In [25]:
tables = [[i*j for i in range(1,6)] for j in range(1,11)]
In [26]:
tables
Out[26]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [29]:
[tables[i][2] for i in range(10)]
Out[29]:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
In [30]:
def column(data, colnum):
    return [data[i][colnum] for i in range(len(data))]
In [31]:
column(tables, 2)
Out[31]:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
In [32]:
column(tables, 3)
Out[32]:
[4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
In [35]:
def transpose(matrix):
    colcount = len(matrix[0])
    return [column(matrix, i) for i in range(colcount)]
In [36]:
transpose(tables)
Out[36]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
In [37]:
tables
Out[37]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]

Iteration patterns

In [38]:
primes_ = primes(50)
In [39]:
primes_
Out[39]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In [40]:
for p in primes_:
    print(p, end=" ")
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 
In [41]:
for p in reversed(primes_):
    print(p, end=" ")
47 43 41 37 31 29 23 19 17 13 11 7 5 3 2 
In [42]:
rprimes = reversed(primes_)
In [43]:
for i in rprimes:
    print(i, end=" ")
47 43 41 37 31 29 23 19 17 13 11 7 5 3 2 
In [44]:
for i in rprimes:
    print(i, end=" ")
In [45]:
rprimes
Out[45]:
<list_reverseiterator at 0x7f53ded4c1d0>
In [47]:
for i, item in enumerate(primes_):
    print(i+1, item)
1 2
2 3
3 5
4 7
5 11
6 13
7 17
8 19
9 23
10 29
11 31
12 37
13 41
14 43
15 47
In [48]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [49]:
poem = """The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

"""
In [52]:
lines = poem.strip().split("\n")
In [53]:
for i, l in enumerate(lines):
    print(i+1, l)
1 The Zen of Python, by Tim Peters
2 
3 Beautiful is better than ugly.
4 Explicit is better than implicit.
5 Simple is better than complex.
6 Complex is better than complicated.
7 Flat is better than nested.
8 Sparse is better than dense.
9 Readability counts.
10 Special cases aren't special enough to break the rules.
11 Although practicality beats purity.
12 Errors should never pass silently.
13 Unless explicitly silenced.
14 In the face of ambiguity, refuse the temptation to guess.
15 There should be one-- and preferably only one --obvious way to do it.
16 Although that way may not be obvious at first unless you're Dutch.
17 Now is better than never.
18 Although never is often better than *right* now.
19 If the implementation is hard to explain, it's a bad idea.
20 If the implementation is easy to explain, it may be a good idea.
21 Namespaces are one honking great idea -- let's do more of those!
In [55]:
enumitr = enumerate(lines)
In [56]:
enumitr
Out[56]:
<enumerate at 0x7f53deeefb40>
In [57]:
next(enumitr)
Out[57]:
(0, 'The Zen of Python, by Tim Peters')
In [58]:
next(enumitr)
Out[58]:
(1, '')
In [78]:
next(enumitr)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-78-d0ec4d345dbe> in <module>
----> 1 next(enumitr)

StopIteration: 
In [79]:
for i, l in enumitr:
    print(i, l)
In [80]:
nums = [1, 2, 3, 4, 5]
words = ["one", "two", "three", "four", "five"]
In [81]:
for x,y in zip(nums, words):
    print(x, y)
1 one
2 two
3 three
4 four
5 five
In [86]:
zipped = zip(nums, words)
In [87]:
for i, j in zipped:
    print(i, j)
1 one
2 two
3 three
4 four
5 five
In [89]:
list(zip(*tables))
Out[89]:
[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
 (2, 4, 6, 8, 10, 12, 14, 16, 18, 20),
 (3, 6, 9, 12, 15, 18, 21, 24, 27, 30),
 (4, 8, 12, 16, 20, 24, 28, 32, 36, 40),
 (5, 10, 15, 20, 25, 30, 35, 40, 45, 50)]
In [90]:
range(5)
Out[90]:
range(0, 5)
In [91]:
reversed(primes_)
Out[91]:
<list_reverseiterator at 0x7f53dedeebe0>
In [92]:
list(reversed(primes_))
Out[92]:
[47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2]

String formatting

In [95]:
for i in range(1,11):
    print(i, i*i, i*i*i)
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
In [96]:
for i in range(1,11):
    print(str(i).rjust(2), str(i*i).rjust(3), str(i*i*i).rjust(4))
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
In [100]:
template = """
<html>
<header>
{header}
</header>
<body>
<p>
{contents}
</p>
</body>
</html>
"""
In [99]:
print(template.format(header="HEADER", contents=poem))
<html>
<header>
HEADER
</header>
<body>
<p>
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


</p>
</body>
</html>

problem

  • Write a function to genearate pascal traingle of base n.
    >>> pascal(4)
    [[1],[1,1],[1,2,1],[1,3,3,1]]
  • Write function to pretty print a traingle of *
        *
       * *
      * * *
     * * * *
    * * * * *
  • Write a function to pretty print pascal triangle
In [102]:
"{} of oz is {}".format("wizard", "python")
Out[102]:
'wizard of oz is python'
In [103]:
"{1} of oz is {0}".format("wizard", "python")
Out[103]:
'python of oz is wizard'
In [104]:
"{char} of oz is {name}".format(char="wizard", name="python")
Out[104]:
'wizard of oz is python'
In [105]:
for i in range(1,11):
    print("{unit:2d} {sqr:3d} {cube:4d}".format(unit=i, sqr=i*i, cube=i**3))
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
In [106]:
row = [1, 2, 1]
def nextrow(row):
    r1 = row[:] + [0]
    r2 = [0] + row[:]
    return [x+y for x,y in zip(r1, r2)]
In [108]:
r = nextrow(row)
In [109]:
r
Out[109]:
[1, 3, 3, 1]
In [110]:
nextrow(r)
Out[110]:
[1, 4, 6, 4, 1]
In [111]:
nextrow(nextrow(r))
Out[111]:
[1, 5, 10, 10, 5, 1]
In [113]:
def pascal(n):
    tr = [[1]]
    for i in range(n-1):
        r = tr[-1]
        nr = nextrow(r)
        tr.append(nr)
    return tr
In [114]:
pascal(4)
Out[114]:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]
In [119]:
def triangle(n):
    return ["*"*j  for j in range(1, n+1)]
In [120]:
triangle(5)
Out[120]:
['*', '**', '***', '****', '*****']
In [ ]:
for item in triangle(7):
    print(item.center(7))
In [138]:
def pretty_triangle(t):
    pt = []
    size = len(t)
    for row in t:
        formatedrow = ""
        for item in row:
            formatedrow += " {}".format(item)
        pt.append(formatedrow.center(size*2))
    return pt
In [139]:
pretty_triangle(triangle(7))
Out[139]:
['       *      ',
 '      * *     ',
 '     * * *    ',
 '    * * * *   ',
 '   * * * * *  ',
 '  * * * * * * ',
 ' * * * * * * *']
In [140]:
def test_printtraingle():
    t = pretty_triangle(triangle(10))
    l = len(t[0])
    for i, item in enumerate(t):
        assert l == len(item)
        assert i+1 == item.count("*")
        assert len(item.strip().split()) == i+1
In [141]:
 test_printtraingle()
In [142]:
def print_triangle(t):
    for row in t:
        print(row)
In [144]:
t = pretty_triangle(triangle(3))
In [145]:
print_triangle(t)
   *  
  * * 
 * * *
In [146]:
print_triangle(pretty_triangle(triangle(50)))
                                                  *                                                 
                                                 * *                                                
                                                * * *                                               
                                               * * * *                                              
                                              * * * * *                                             
                                             * * * * * *                                            
                                            * * * * * * *                                           
                                           * * * * * * * *                                          
                                          * * * * * * * * *                                         
                                         * * * * * * * * * *                                        
                                        * * * * * * * * * * *                                       
                                       * * * * * * * * * * * *                                      
                                      * * * * * * * * * * * * *                                     
                                     * * * * * * * * * * * * * *                                    
                                    * * * * * * * * * * * * * * *                                   
                                   * * * * * * * * * * * * * * * *                                  
                                  * * * * * * * * * * * * * * * * *                                 
                                 * * * * * * * * * * * * * * * * * *                                
                                * * * * * * * * * * * * * * * * * * *                               
                               * * * * * * * * * * * * * * * * * * * *                              
                              * * * * * * * * * * * * * * * * * * * * *                             
                             * * * * * * * * * * * * * * * * * * * * * *                            
                            * * * * * * * * * * * * * * * * * * * * * * *                           
                           * * * * * * * * * * * * * * * * * * * * * * * *                          
                          * * * * * * * * * * * * * * * * * * * * * * * * *                         
                         * * * * * * * * * * * * * * * * * * * * * * * * * *                        
                        * * * * * * * * * * * * * * * * * * * * * * * * * * *                       
                       * * * * * * * * * * * * * * * * * * * * * * * * * * * *                      
                      * * * * * * * * * * * * * * * * * * * * * * * * * * * * *                     
                     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *                    
                    * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *                   
                   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *                  
                  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *                 
                 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *                
                * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *               
               * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *              
              * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *             
             * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *            
            * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *           
           * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *          
          * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *         
         * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *        
        * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *       
       * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *      
      * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *     
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *    
    * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *   
   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *  
  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Working with files

In [148]:
print(poem)
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


In [149]:
%%file poem.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Writing poem.txt
In [150]:
with open("poem.txt") as f:
    print(f.read())
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

In [151]:
f = open("poem.txt")
In [152]:
f.read()
Out[152]:
"The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n"
In [153]:
f.close()
In [155]:
with open("poem.txt", "r") as f:
    print(f.readline(), end="")
    print(f.readline(), end="")
    
    for line in f.readlines():
        print("*", line, end="")
The Zen of Python, by Tim Peters

* Beautiful is better than ugly.
* Explicit is better than implicit.
* Simple is better than complex.
* Complex is better than complicated.
* Flat is better than nested.
* Sparse is better than dense.
* Readability counts.
* Special cases aren't special enough to break the rules.
* Although practicality beats purity.
* Errors should never pass silently.
* Unless explicitly silenced.
* In the face of ambiguity, refuse the temptation to guess.
* There should be one-- and preferably only one --obvious way to do it.
* Although that way may not be obvious at first unless you're Dutch.
* Now is better than never.
* Although never is often better than *right* now.
* If the implementation is hard to explain, it's a bad idea.
* If the implementation is easy to explain, it may be a good idea.
* Namespaces are one honking great idea -- let's do more of those!
In [156]:
with open("poem.txt") as f:
    for i, line in enumerate(f):
        print(i+1, line, end="")
1 The Zen of Python, by Tim Peters
2 
3 Beautiful is better than ugly.
4 Explicit is better than implicit.
5 Simple is better than complex.
6 Complex is better than complicated.
7 Flat is better than nested.
8 Sparse is better than dense.
9 Readability counts.
10 Special cases aren't special enough to break the rules.
11 Although practicality beats purity.
12 Errors should never pass silently.
13 Unless explicitly silenced.
14 In the face of ambiguity, refuse the temptation to guess.
15 There should be one-- and preferably only one --obvious way to do it.
16 Although that way may not be obvious at first unless you're Dutch.
17 Now is better than never.
18 Although never is often better than *right* now.
19 If the implementation is hard to explain, it's a bad idea.
20 If the implementation is easy to explain, it may be a good idea.
21 Namespaces are one honking great idea -- let's do more of those!
In [157]:
with open("poem.txt") as f:
    for i, line in enumerate(f):
        print(i+1, line.strip())
1 The Zen of Python, by Tim Peters
2 
3 Beautiful is better than ugly.
4 Explicit is better than implicit.
5 Simple is better than complex.
6 Complex is better than complicated.
7 Flat is better than nested.
8 Sparse is better than dense.
9 Readability counts.
10 Special cases aren't special enough to break the rules.
11 Although practicality beats purity.
12 Errors should never pass silently.
13 Unless explicitly silenced.
14 In the face of ambiguity, refuse the temptation to guess.
15 There should be one-- and preferably only one --obvious way to do it.
16 Although that way may not be obvious at first unless you're Dutch.
17 Now is better than never.
18 Although never is often better than *right* now.
19 If the implementation is hard to explain, it's a bad idea.
20 If the implementation is easy to explain, it may be a good idea.
21 Namespaces are one honking great idea -- let's do more of those!
In [158]:
with open("poem.txt") as f:
    lines = f.readlines()
    print(max(lines, key=len))
There should be one-- and preferably only one --obvious way to do it.

In [159]:
with open("poem.txt") as f:
    print(max(f, key=len))
There should be one-- and preferably only one --obvious way to do it.

In [160]:
f = open("poem.txt")
In [161]:
next(f)
Out[161]:
'The Zen of Python, by Tim Peters\n'
In [162]:
l = [1, 2, 3, 4, 5,6]
In [163]:
r = reversed(l)
In [165]:
f.close()

Writing

In [166]:
with open("numbers.txt", "w") as f:
    f.write("one\n")
    f.write("two\n")
    f.write("three\n")
    f.write("four\n")
    

problems

  • Write a python script cat.py which mimics unix commans cat. it prints contents of file to standard output.
    python cat.py numbers.txt
    one
    two
    three
    four
  • Write a python script head.py which prints initial few lines from the file
    python head.py 3 numbers.txt
    one
    two
    three
In [169]:
%%file cat.py
import sys

def cat(filename):
    with open(filename) as f:
        print(f.read(), end="")

if __name__ == "__main__":
    cat(sys.argv[1])
Overwriting cat.py
In [170]:
!python cat.py numbers.txt
one
two
three
four
In [173]:
%%file head.py
import sys

def head(filename, n):
    with open(filename) as f:
        for i in range(n):
            print(f.readline(), end="")

if __name__ == "__main__":
    if len(sys.argv)==4 and sys.argv[1] == "-n":
        n = int(sys.argv[2])
        filename = sys.argv[3]
        head(filename, n)
    elif len(sys.argv)==2:
        head(filename, 5)
    else:
        help_ = """
        Usage:
        python head.py -n 5 filename
        or
        python head.py filename
        """
        print(help_)
        
Overwriting head.py
In [174]:
!python head.py
        Usage:
        python head.py -n 5 filename
        or
        python head.py filename
        
In [175]:
!python head.py -n 3 poem.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
In [176]:
with open("numbers.txt", "a") as f:
    f.write("\n")
    f.write("two\n")
    f.write("three\n")
    f.write("four\n")
    
In [177]:
!python cat.py numbers.txt
one
two
three
four

two
three
four

problems

  • Write a function to write 2d matrix to a file in csv format
  • Write a function to parse numeric data from csv file
  • Write a python script "wc.py" which mimics unix command wc. it prints line count, word count and charecter count for given file
In [178]:
tables
Out[178]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [181]:
",".join([str(p) for p in primes_])
Out[181]:
'2,3,5,7,11,13,17,19,23,29,31,37,41,43,47'
In [186]:
def writecsv(data, filename):
    with open(filename, "w") as f:
        for row in data:
            f.write(",".join([str(item) for item in row]))
            f.write("\n")
        
In [187]:
writecsv(tables, "table.csv")
In [188]:
!python cat.py table.csv
1,2,3,4,5
2,4,6,8,10
3,6,9,12,15
4,8,12,16,20
5,10,15,20,25
6,12,18,24,30
7,14,21,28,35
8,16,24,32,40
9,18,27,36,45
10,20,30,40,50
In [189]:
def parseCSV(filename):
    with open(filename) as f:
        d = []
        for line in f:
            row = line.strip().split(",")
            d.append(row)
    return d
In [190]:
parseCSV("table.csv")
Out[190]:
[['1', '2', '3', '4', '5'],
 ['2', '4', '6', '8', '10'],
 ['3', '6', '9', '12', '15'],
 ['4', '8', '12', '16', '20'],
 ['5', '10', '15', '20', '25'],
 ['6', '12', '18', '24', '30'],
 ['7', '14', '21', '28', '35'],
 ['8', '16', '24', '32', '40'],
 ['9', '18', '27', '36', '45'],
 ['10', '20', '30', '40', '50']]
In [191]:
def parseCSV(filename):
    with open(filename) as f:
        return [line.strip().split(",") for line in f]
In [192]:
parseCSV("table.csv")
Out[192]:
[['1', '2', '3', '4', '5'],
 ['2', '4', '6', '8', '10'],
 ['3', '6', '9', '12', '15'],
 ['4', '8', '12', '16', '20'],
 ['5', '10', '15', '20', '25'],
 ['6', '12', '18', '24', '30'],
 ['7', '14', '21', '28', '35'],
 ['8', '16', '24', '32', '40'],
 ['9', '18', '27', '36', '45'],
 ['10', '20', '30', '40', '50']]
In [193]:
def parseCSV(filename):
    with open(filename) as f:
        return [[int(i) for i in line.strip().split(",")] for line in f]
In [194]:
parseCSV("table.csv")
Out[194]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [201]:
%%file wc.py
import sys

def linecount(filename):
    with open(filename) as f:
        return len(f.readlines())
    
def wordcount(filename):
    with open(filename) as f:
        return len(f.read().split())

def charcount(filename):
    with open(filename) as f:
        return len(f.read())
    
if __name__ == "__main__":
    f = sys.argv[1]
    print(linecount(f), wordcount(f), charcount(f), f)
Overwriting wc.py
In [202]:
!python wc.py poem.txt
21 144 857 poem.txt
In [207]:
f = open("poem.txt")
In [208]:
f.read().split()
Out[208]:
['The',
 'Zen',
 'of',
 'Python,',
 'by',
 'Tim',
 'Peters',
 'Beautiful',
 'is',
 'better',
 'than',
 'ugly.',
 'Explicit',
 'is',
 'better',
 'than',
 'implicit.',
 'Simple',
 'is',
 'better',
 'than',
 'complex.',
 'Complex',
 'is',
 'better',
 'than',
 'complicated.',
 'Flat',
 'is',
 'better',
 'than',
 'nested.',
 'Sparse',
 'is',
 'better',
 'than',
 'dense.',
 'Readability',
 'counts.',
 'Special',
 'cases',
 "aren't",
 'special',
 'enough',
 'to',
 'break',
 'the',
 'rules.',
 'Although',
 'practicality',
 'beats',
 'purity.',
 'Errors',
 'should',
 'never',
 'pass',
 'silently.',
 'Unless',
 'explicitly',
 'silenced.',
 'In',
 'the',
 'face',
 'of',
 'ambiguity,',
 'refuse',
 'the',
 'temptation',
 'to',
 'guess.',
 'There',
 'should',
 'be',
 'one--',
 'and',
 'preferably',
 'only',
 'one',
 '--obvious',
 'way',
 'to',
 'do',
 'it.',
 'Although',
 'that',
 'way',
 'may',
 'not',
 'be',
 'obvious',
 'at',
 'first',
 'unless',
 "you're",
 'Dutch.',
 'Now',
 'is',
 'better',
 'than',
 'never.',
 'Although',
 'never',
 'is',
 'often',
 'better',
 'than',
 '*right*',
 'now.',
 'If',
 'the',
 'implementation',
 'is',
 'hard',
 'to',
 'explain,',
 "it's",
 'a',
 'bad',
 'idea.',
 'If',
 'the',
 'implementation',
 'is',
 'easy',
 'to',
 'explain,',
 'it',
 'may',
 'be',
 'a',
 'good',
 'idea.',
 'Namespaces',
 'are',
 'one',
 'honking',
 'great',
 'idea',
 '--',
 "let's",
 'do',
 'more',
 'of',
 'those!']
In [209]:
f.close()

modes

"w"  -> write
"a"  -> append
"b"  -> binary
"rb" -> read binary
"wb" -> write binary

Working with dictionary

In [210]:
keys = ["processor", "os", "memory", "brand"]
values = ["Corei5", "mint", "4GB", "Acer"]
specs = dict(zip(keys, values))
In [211]:
specs
Out[211]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '4GB', 'brand': 'Acer'}
In [212]:
specs['processor']
Out[212]:
'Corei5'
In [214]:
specs['cache']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-214-3ba43597a10e> in <module>
----> 1 specs['cache']

KeyError: 'cache'
In [215]:
specs.get("cache", "2MB")
Out[215]:
'2MB'
In [216]:
specs
Out[216]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '4GB', 'brand': 'Acer'}
In [218]:
specs['cache']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-218-3ba43597a10e> in <module>
----> 1 specs['cache']

KeyError: 'cache'
In [219]:
specs.get("cache", "2MB")
Out[219]:
'2MB'
In [221]:
specs.get("os", "windows")
Out[221]:
'mint'
In [222]:
specs.get("cache", None)
In [223]:
list = [1, 2, 3, 4, 5]
In [224]:
list(reversed(primes_))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-224-d8d5607e97cb> in <module>
----> 1 list(reversed(primes_))

TypeError: 'list' object is not callable
In [225]:
del list
In [226]:
list(range(5))
Out[226]:
[0, 1, 2, 3, 4]
In [227]:
del specs['processor']
In [228]:
specs
Out[228]:
{'os': 'mint', 'memory': '4GB', 'brand': 'Acer'}
In [229]:
specs['processor'] = "corei3"
In [230]:
specs
Out[230]:
{'os': 'mint', 'memory': '4GB', 'brand': 'Acer', 'processor': 'corei3'}

Examples : word frequency

In [231]:
%%file words.txt
one
one two
one two three
one two three four
one two three four five
one two three four five six
one two three seven six
one two eight seven six 
one nine eight seven six
ten nine eight seven
ten nine eight
ten nine
ten
Writing words.txt
In [232]:
def getwords(filename):
    with open(filename) as f:
        return f.read().split()
In [233]:
words = getwords("words.txt")
In [234]:
len(words)
Out[234]:
46
In [237]:
def wordfreq(words):
    freq = {}
    for w in words:
        if w in freq:
            freq[w] += 1
        else:
            freq[w] = 1
            
    return freq
In [238]:
wordfreq(words)
Out[238]:
{'one': 9,
 'two': 7,
 'three': 5,
 'four': 3,
 'five': 2,
 'six': 4,
 'seven': 4,
 'eight': 4,
 'nine': 4,
 'ten': 4}
In [239]:
def wordfreq(words):
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return freq
In [240]:
wordfreq(words)
Out[240]:
{'one': 9,
 'two': 7,
 'three': 5,
 'four': 3,
 'five': 2,
 'six': 4,
 'seven': 4,
 'eight': 4,
 'nine': 4,
 'ten': 4}
In [241]:
def wordfreq(words):
    freq = {}
    uniq = set(words)
    for w in uniq:
        freq[w] = words.count(w)
    return freq
In [242]:
wordfreq(words)
Out[242]:
{'five': 2,
 'two': 7,
 'four': 3,
 'one': 9,
 'ten': 4,
 'eight': 4,
 'three': 5,
 'seven': 4,
 'nine': 4,
 'six': 4}
In [243]:
freq = wordfreq(words)
In [245]:
freq.get("one")
Out[245]:
9
In [246]:
freq
Out[246]:
{'five': 2,
 'two': 7,
 'four': 3,
 'one': 9,
 'ten': 4,
 'eight': 4,
 'three': 5,
 'seven': 4,
 'nine': 4,
 'six': 4}
In [247]:
for item in freq:
    print(item)
five
two
four
one
ten
eight
three
seven
nine
six
In [248]:
for item in freq:
    print(item, freq[item])
five 2
two 7
four 3
one 9
ten 4
eight 4
three 5
seven 4
nine 4
six 4
In [249]:
def getfreq(w):
    return freq[w]

for item in sorted(freq, key=getfreq):
    print(item, freq[item])
five 2
four 3
ten 4
eight 4
seven 4
nine 4
six 4
three 5
two 7
one 9
In [250]:
for item in sorted(freq, key=getfreq, reverse=True):
    print(item, freq[item])
one 9
two 7
three 5
ten 4
eight 4
seven 4
nine 4
six 4
four 3
five 2
In [251]:
for item in sorted(freq, key=getfreq, reverse=True):
    print(item, freq[item], "*"*freq[item])
one 9 *********
two 7 *******
three 5 *****
ten 4 ****
eight 4 ****
seven 4 ****
nine 4 ****
six 4 ****
four 3 ***
five 2 **
In [252]:
for item in sorted(freq, key=getfreq, reverse=True):
    print(item.rjust(5), freq[item], "*"*freq[item])
  one 9 *********
  two 7 *******
three 5 *****
  ten 4 ****
eight 4 ****
seven 4 ****
 nine 4 ****
  six 4 ****
 four 3 ***
 five 2 **
In [253]:
dict(zip(keys, values))
Out[253]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '4GB', 'brand': 'Acer'}
In [254]:
freq
Out[254]:
{'five': 2,
 'two': 7,
 'four': 3,
 'one': 9,
 'ten': 4,
 'eight': 4,
 'three': 5,
 'seven': 4,
 'nine': 4,
 'six': 4}
In [255]:
freq.keys()
Out[255]:
dict_keys(['five', 'two', 'four', 'one', 'ten', 'eight', 'three', 'seven', 'nine', 'six'])
In [256]:
freq.values()
Out[256]:
dict_values([2, 7, 3, 9, 4, 4, 5, 4, 4, 4])
In [257]:
keys= [k for k in freq]
In [258]:
keys
Out[258]:
['five', 'two', 'four', 'one', 'ten', 'eight', 'three', 'seven', 'nine', 'six']
In [259]:
values = [freq[k] for k in keys]
In [260]:
values
Out[260]:
[2, 7, 3, 9, 4, 4, 5, 4, 4, 4]
In [263]:
[(k, freq[k]) for k in freq]
Out[263]:
[('five', 2),
 ('two', 7),
 ('four', 3),
 ('one', 9),
 ('ten', 4),
 ('eight', 4),
 ('three', 5),
 ('seven', 4),
 ('nine', 4),
 ('six', 4)]
In [264]:
players = {"Player1":"India","Player2":"USA","PLAYER3":"India", "Player4":"USA", "Player5":"UK"}
In [265]:
players
Out[265]:
{'Player1': 'India',
 'Player2': 'USA',
 'PLAYER3': 'India',
 'Player4': 'USA',
 'Player5': 'UK'}
In [266]:
[p for p in players if players[p]=="India"]
Out[266]:
['Player1', 'PLAYER3']

Interating over dictionary

In [268]:
for item in specs:
    print(item)
os
memory
brand
processor
In [270]:
for item in specs.keys():
    print(item)
os
memory
brand
processor
In [269]:
for item in specs.values():
    print(item)
mint
4GB
Acer
corei3
In [271]:
for k, v in specs.items():
    print(k, v)
os mint
memory 4GB
brand Acer
processor corei3

Classes

In [273]:
%%file bank0.py

balance = 0

def withdraw(amount):
    global balance
    balance -= amount
    
def deposit(amount):
    global balance
    balance += amount
    
def get_balance():
    return balance
    
Overwriting bank0.py
In [274]:
import bank0
In [275]:
bank0.get_balance()
Out[275]:
0
In [276]:
bank0.deposit(1000)
In [277]:
bank0.get_balance()
Out[277]:
1000
In [278]:
%%file bank1.py

def make_account():
    return {"balance":0}

def withdraw(account, amount):
    account['balance'] -= amount
    
def deposit(account, amount):
    account['balance'] += amount
    
def get_balance(account):
    return account['balance']
Writing bank1.py
In [279]:
import bank1
In [280]:
a1 = bank1.make_account()
a2 = bank1.make_account()
In [282]:
print("a1 :", bank1.get_balance(a1))
print("a2 :", bank1.get_balance(a2))
a1 : 0
a2 : 0
In [284]:
bank1.deposit(a1, 20120)
In [285]:
print("a1 :", bank1.get_balance(a1))
print("a2 :", bank1.get_balance(a2))
a1 : 20120
a2 : 0
In [286]:
bank1.deposit(a2, 12320)
In [287]:
print("a1 :", bank1.get_balance(a1))
print("a2 :", bank1.get_balance(a2))
a1 : 20120
a2 : 12320
In [288]:
class BankAccount:
    
    def __init__(self):
        self.balance = 0
        
    def deposit(self, amount):
        self.balance += amount
        
    def withdraw(self, amount):
        self.balance -= amount
        
    def get_balance(self):
        return self.balance
In [289]:
def foo():
    pass
In [290]:
foo
Out[290]:
<function __main__.foo()>
In [291]:
class Foo:
    pass
In [292]:
Foo
Out[292]:
__main__.Foo
In [293]:
type(2)
Out[293]:
int
In [294]:
a3 = BankAccount()
In [295]:
type(a3)
Out[295]:
__main__.BankAccount
In [296]:
a3
Out[296]:
<__main__.BankAccount at 0x7f53decc9978>
In [297]:
BankAccount
Out[297]:
__main__.BankAccount
In [298]:
a3
Out[298]:
<__main__.BankAccount at 0x7f53decc9978>
In [299]:
a3.get_balance()
Out[299]:
0
In [300]:
a3.deposit(200)
In [301]:
a3.get_balance()
Out[301]:
200
In [305]:
class Point:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
class RedPoint(Point):
    color = "red"
    
In [306]:
p1 = Point(0, 0)
In [307]:
p1.x
Out[307]:
0
In [309]:
p1.y
Out[309]:
0
In [310]:
r1  = RedPoint(2, 3)
In [311]:
r1.x
Out[311]:
2
In [312]:
r1.y
Out[312]:
3
In [313]:
r1.color
Out[313]:
'red'
In [314]:
p1.color
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-314-4a10185c0908> in <module>
----> 1 p1.color

AttributeError: 'Point' object has no attribute 'color'
In [315]:
Point
Out[315]:
__main__.Point
In [316]:
RedPoint
Out[316]:
__main__.RedPoint
In [317]:
RedPoint.color
Out[317]:
'red'
In [318]:
r2 = RedPoint(2, 3)
In [319]:
RedPoint.color = "RED"
In [320]:
r1.color
Out[320]:
'RED'
In [321]:
r2.color
Out[321]:
'RED'
In [322]:
r1.__dict__
Out[322]:
{'x': 2, 'y': 3}
In [323]:
a3.__dict__
Out[323]:
{'balance': 200}
In [324]:
a3.__dict__['aadhar'] = 800048882323
In [325]:
a3.aadhar
Out[325]:
800048882323
In [326]:
p1.x
Out[326]:
0
In [327]:
class Point:
    
    def __init__(self, x, y):
        self._x = x
        self._y = y
In [328]:
p2 = Point(3,4)
In [329]:
p2._x
Out[329]:
3

problem

  • Write a class Timer which has methods, start, stop, elapsed_time
    t = Timer()
    t.start()
    task()
    t.stop()
    print("time taken :", t.elapsed_time())
In [330]:
import time
In [331]:
time.time()
Out[331]:
1559646991.1891901
In [332]:
def task():
    time.sleep(2)
In [333]:
class Timer:

    def __init__(self):
        self._start = 0
        self._end = 0
        
    def start(self):
        self._start = time.time()
        
    def stop(self):
        self._end = time.time()
        
    def elapsed_time(self):
        return self._end - self._start
In [334]:
t = Timer()
In [336]:
t.start()
time.sleep(5)
t.stop()
print("Time taken:", t.elapsed_time())
Time taken: 5.003036260604858
In [337]:
def timeit(task, args):
    t = Timer()
    t.start()
    task(*args)
    t.stop()
    return t.elapsed_time()
In [338]:
timeit(time.sleep, (5,))
Out[338]:
5.002501010894775
In [339]:
class Pair:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
In [340]:
p1 = Pair(0,1)
In [341]:
p1
Out[341]:
<__main__.Pair at 0x7f53ded821d0>
In [342]:
l = [1,2]
In [343]:
l
Out[343]:
[1, 2]
In [351]:
class Pair:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def __repr__(self):
        return "Pair({},{})".format(self.x, self.y)
    
    def __str__(self):
        return "<{},{}>".format(self.x, self.y)
In [352]:
p = Pair(2,3)
In [353]:
p
Out[353]:
Pair(2,3)
In [354]:
print(p)
<2,3>
In [355]:
s = "hello"
In [356]:
s
Out[356]:
'hello'
In [357]:
print(s)
hello
In [358]:
str(p)
Out[358]:
'<2,3>'
In [362]:
class Pair:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def __repr__(self):
        return "Pair({},{})".format(self.x, self.y)
    
    def __str__(self):
        return "<{},{}>".format(self.x, self.y)
    
    def __add__(self, p):
        return Pair(self.x+p.x, self.y+p.y)
    
    def __eq__(self,  p):
        return self.x==p.x and self.y==p.y
In [360]:
p1 = Pair(2,3)
p2 = Pair(5,4)
In [363]:
p1 + p2
Out[363]:
Pair(7,7)
In [364]:
p1 == p2
Out[364]:
False
In [365]:
2*"*"
Out[365]:
'**'
In [366]:
class Pair:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def __repr__(self):
        return "Pair({},{})".format(self.x, self.y)
    
    def __str__(self):
        return "<{},{}>".format(self.x, self.y)
    
    def __add__(self, p):
        return Pair(self.x+p.x, self.y+p.y)
    
    def __eq__(self,  p):
        return self.x==p.x and self.y==p.y
    
    def __getitem__(self, name):
        if name=="x":
            return self.x
        elif name=="y":
            return self.y
        else:
            raise KeyError("No such item", name)
In [367]:
p = Pair(5,6)
In [369]:
p['x']
Out[369]:
5
In [370]:
p.x
Out[370]:
5
In [371]:
p['x']
Out[371]:
5
In [372]:
specs
Out[372]:
{'os': 'mint', 'memory': '4GB', 'brand': 'Acer', 'processor': 'corei3'}
In [374]:
specs['os']
Out[374]:
'mint'
In [375]:
parseCSV("table.csv")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-375-9acdcda18aa1> in <module>
----> 1 parseCSV("table.csv")

<ipython-input-193-ab431bf61b8d> in parseCSV(filename)
      1 def parseCSV(filename):
      2     with open(filename) as f:
----> 3         return [[int(i) for i in line.strip().split(",")] for line in f]

<ipython-input-193-ab431bf61b8d> in <listcomp>(.0)
      1 def parseCSV(filename):
      2     with open(filename) as f:
----> 3         return [[int(i) for i in line.strip().split(",")] for line in f]

<ipython-input-193-ab431bf61b8d> in <listcomp>(.0)
      1 def parseCSV(filename):
      2     with open(filename) as f:
----> 3         return [[int(i) for i in line.strip().split(",")] for line in f]

ValueError: invalid literal for int() with base 10: ''
In [382]:
def myint(sn):
    try:
        return int(sn)
    except ValueError as e:
        print(e)
        return 0

def csvParser(filename):
    with open(filename) as f:
        return [[myint(i) for i in line.strip().split(",")] for line in f]
In [383]:
csvParser("table.csv")
invalid literal for int() with base 10: ''
invalid literal for int() with base 10: ''
Out[383]:
[[1, 0, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 0, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]

Example shape modelling

In [512]:
from functools import reduce
from matplotlib.pyplot import imshow

class Shape:
    
    def contains(self, p):
        pass
    
class Point:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    
class Rectangle(Shape):
    
    def __init__(self,width, length):
        self.w = width
        self.l = length
        
    def contains(self, p):
        return p.x <= self.w//2 and p.y <= self.l//2
    
    
class Circle(Shape):
    
    def __init__(self, radius):
        self.r = radius
        
        
    def contains(self, p):
        return (p.x**2 + p.y**2)**0.5 <= self.r
    

def test_shapes():
    c = Circle(5)
    assert c.contains(Point(0, 3))
    assert not c.contains(Point(6,6))
    
    r = Rectangle(50, 300)
    assert r.contains(Point(24, 120))
    assert not r.contains(Point(30, 160))
    
test_shapes()
    
class Union(Shape):
    
    def __init__(self, shapes):
        self.shapes = shapes
        
    def contains(self, p):
        conds = [s.contains(p) for s in self.shapes]
        return reduce(lambda x, y: x or y, conds, False)
    
class Intersection(Shape):
    
    def __init__(self, shapes):
        self.shapes = shapes
        
    def contains(self, p):
        conds = [s.contains(p) for s in self.shapes]
        return reduce(lambda x, y: x and y, conds, True)
    
    
class Canvas:
    
    def __init__(self, w=1000, l=1000):
        self.w = w
        self.l = l
        
        self.display = [[False for i in range(w)] for j in range(l)]
        
    def draw(self, shape):
        def translate(p):
            #return p
            return Point(self.w//2 - p.x, self.l//2 - p.y)
        
        self.display = [[shape.contains(translate(Point(i, j))) for i in range(self.w)] for j in range(self.l)]
        
    def plot(self):
        imshow(self.display)
In [487]:
reduce(lambda x,y: x and y , [True, True, False, True], True)
Out[487]:
False
In [488]:
reduce(lambda x,y: x and y , [True, True, True, True], True)
Out[488]:
True
In [489]:
%matplotlib inline
In [490]:
from matplotlib.pyplot import imshow
In [491]:
imshow(tables)
Out[491]:
<matplotlib.image.AxesImage at 0x7f53c2ec6400>
In [513]:
c = Circle(50)
In [514]:
canvas = Canvas(100, 100)
In [515]:
canvas.draw(c)
In [516]:
canvas.plot()
In [517]:
c1 = Circle(50)
r1 = Rectangle(10, 120)
u = Union([c1, r1])
inter = Intersection([c1, r1])
In [518]:
canvas = Canvas(100, 100)
canvas.draw(u)
canvas.plot()
In [519]:
canvas = Canvas(100, 100)
canvas.draw(inter)
canvas.plot()

references

In [520]:
import requests
In [521]:
import requests
url = "https://api.github.com/orgs/google/repos"
repos = requests.get(url).json()
In [522]:
type(repos)
Out[522]:
list
In [523]:
repos[0]
Out[523]:
{'id': 1936771,
 'node_id': 'MDEwOlJlcG9zaXRvcnkxOTM2Nzcx',
 'name': 'truth',
 'full_name': 'google/truth',
 'private': False,
 'owner': {'login': 'google',
  'id': 1342004,
  'node_id': 'MDEyOk9yZ2FuaXphdGlvbjEzNDIwMDQ=',
  'avatar_url': 'https://avatars1.githubusercontent.com/u/1342004?v=4',
  'gravatar_id': '',
  'url': 'https://api.github.com/users/google',
  'html_url': 'https://github.com/google',
  'followers_url': 'https://api.github.com/users/google/followers',
  'following_url': 'https://api.github.com/users/google/following{/other_user}',
  'gists_url': 'https://api.github.com/users/google/gists{/gist_id}',
  'starred_url': 'https://api.github.com/users/google/starred{/owner}{/repo}',
  'subscriptions_url': 'https://api.github.com/users/google/subscriptions',
  'organizations_url': 'https://api.github.com/users/google/orgs',
  'repos_url': 'https://api.github.com/users/google/repos',
  'events_url': 'https://api.github.com/users/google/events{/privacy}',
  'received_events_url': 'https://api.github.com/users/google/received_events',
  'type': 'Organization',
  'site_admin': False},
 'html_url': 'https://github.com/google/truth',
 'description': 'Fluent assertions for Java and Android',
 'fork': False,
 'url': 'https://api.github.com/repos/google/truth',
 'forks_url': 'https://api.github.com/repos/google/truth/forks',
 'keys_url': 'https://api.github.com/repos/google/truth/keys{/key_id}',
 'collaborators_url': 'https://api.github.com/repos/google/truth/collaborators{/collaborator}',
 'teams_url': 'https://api.github.com/repos/google/truth/teams',
 'hooks_url': 'https://api.github.com/repos/google/truth/hooks',
 'issue_events_url': 'https://api.github.com/repos/google/truth/issues/events{/number}',
 'events_url': 'https://api.github.com/repos/google/truth/events',
 'assignees_url': 'https://api.github.com/repos/google/truth/assignees{/user}',
 'branches_url': 'https://api.github.com/repos/google/truth/branches{/branch}',
 'tags_url': 'https://api.github.com/repos/google/truth/tags',
 'blobs_url': 'https://api.github.com/repos/google/truth/git/blobs{/sha}',
 'git_tags_url': 'https://api.github.com/repos/google/truth/git/tags{/sha}',
 'git_refs_url': 'https://api.github.com/repos/google/truth/git/refs{/sha}',
 'trees_url': 'https://api.github.com/repos/google/truth/git/trees{/sha}',
 'statuses_url': 'https://api.github.com/repos/google/truth/statuses/{sha}',
 'languages_url': 'https://api.github.com/repos/google/truth/languages',
 'stargazers_url': 'https://api.github.com/repos/google/truth/stargazers',
 'contributors_url': 'https://api.github.com/repos/google/truth/contributors',
 'subscribers_url': 'https://api.github.com/repos/google/truth/subscribers',
 'subscription_url': 'https://api.github.com/repos/google/truth/subscription',
 'commits_url': 'https://api.github.com/repos/google/truth/commits{/sha}',
 'git_commits_url': 'https://api.github.com/repos/google/truth/git/commits{/sha}',
 'comments_url': 'https://api.github.com/repos/google/truth/comments{/number}',
 'issue_comment_url': 'https://api.github.com/repos/google/truth/issues/comments{/number}',
 'contents_url': 'https://api.github.com/repos/google/truth/contents/{+path}',
 'compare_url': 'https://api.github.com/repos/google/truth/compare/{base}...{head}',
 'merges_url': 'https://api.github.com/repos/google/truth/merges',
 'archive_url': 'https://api.github.com/repos/google/truth/{archive_format}{/ref}',
 'downloads_url': 'https://api.github.com/repos/google/truth/downloads',
 'issues_url': 'https://api.github.com/repos/google/truth/issues{/number}',
 'pulls_url': 'https://api.github.com/repos/google/truth/pulls{/number}',
 'milestones_url': 'https://api.github.com/repos/google/truth/milestones{/number}',
 'notifications_url': 'https://api.github.com/repos/google/truth/notifications{?since,all,participating}',
 'labels_url': 'https://api.github.com/repos/google/truth/labels{/name}',
 'releases_url': 'https://api.github.com/repos/google/truth/releases{/id}',
 'deployments_url': 'https://api.github.com/repos/google/truth/deployments',
 'created_at': '2011-06-22T18:55:12Z',
 'updated_at': '2019-06-03T13:14:54Z',
 'pushed_at': '2019-05-30T00:13:42Z',
 'git_url': 'git://github.com/google/truth.git',
 'ssh_url': 'git@github.com:google/truth.git',
 'clone_url': 'https://github.com/google/truth.git',
 'svn_url': 'https://github.com/google/truth',
 'homepage': 'https://truth.dev/',
 'size': 27612,
 'stargazers_count': 1708,
 'watchers_count': 1708,
 'language': 'Java',
 'has_issues': True,
 'has_projects': True,
 'has_downloads': True,
 'has_wiki': True,
 'has_pages': True,
 'forks_count': 183,
 'mirror_url': None,
 'archived': False,
 'disabled': False,
 'open_issues_count': 58,
 'license': {'key': 'apache-2.0',
  'name': 'Apache License 2.0',
  'spdx_id': 'Apache-2.0',
  'url': 'https://api.github.com/licenses/apache-2.0',
  'node_id': 'MDc6TGljZW5zZTI='},
 'forks': 183,
 'open_issues': 58,
 'watchers': 1708,
 'default_branch': 'master',
 'permissions': {'admin': False, 'push': False, 'pull': True}}
In [524]:
for repo in repos[:5]:
    print(repo['full_name'], repo['forks'])
google/truth 183
google/ruby-openid-apps-discovery 17
google/autoparse 34
google/gitkit-ruby 0
google/anvil-build 17
In [525]:
for repo in sorted(repos, reverse=True, key=lambda r: r['forks'])[:5]:
    print(repo['full_name'], repo['forks'])
google/dagger 1646
google/traceur-compiler 598
google/ios-webkit-debug-proxy 363
google/tracing-framework 220
google/truth 183
In [526]:
url = "https://www.moneycontrol.com/india/stockpricequote/foodprocessing/apisindia/AI65"
resp = requests.get(url)
In [528]:
resp.status_code
Out[528]:
200
In [530]:
text = resp.content
In [532]:
text = resp.text
In [533]:
print(text[:500])
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Apis India Ltd. Stock Price, Share Price, Live BSE/NSE, Apis India Ltd. Bids Offers. Buy/Sell Apis India Ltd. news & tips, & F&O Quotes, NSE/BSE Forecast News and Live Quotes</title>
	<meta name="description" content="Apis India Ltd. Stoc
In [534]:
from bs4 import BeautifulSoup
soup = BeautifulSoup(text, 'html.parser')
In [ ]: