Module II - Day 4

Python Foundation

Nov-Jan 2025 batch, Vikrant Patil

Date: 20 Jan 2026

Click here for All Notes

login to https://traininghub.vikrant.dev/ with your username and create a notebook with name module2-day4.ipynb

© Vikrant Patil

problem - Write a function to generate pascal traingle in list format given the size of base - Write a function to pretty print pascal triangle print_pascal given the traingle

      1
    1   1
  1   2   1
1   3   3   1
a = [1, 2, 3, 4, 5]
b = ['1','2','3','4']
for x,y in zip(a,b):
    print(x, y)
1 1
2 2
3 3
4 4

1 3 3 1 1 3 3 1 ——————– 1 4 6 4 1

row = [1  , 3,   3 ,  1]
row
[1, 3, 3, 1]
row[1:]
[3, 3, 1]
for x,y in zip(row, row[1:]):
    print(x, y, x+y)
1 3 4
3 3 6
3 1 4
def generate_next(row):
    return [1] + [x+y for x,y in zip(row, row[1:])] + [1]
    
def pascal(n):
    tr = [[1]]
    for i in range(n):
        lastrow = tr[-1]
        tr.append(generate_next(lastrow))
    return tr
    
pascal(6)
[[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1]]
def triangle(n):
    return [["*"]*i for i in range(1, n+1)]
triangle(5)
[['*'],
 ['*', '*'],
 ['*', '*', '*'],
 ['*', '*', '*', '*'],
 ['*', '*', '*', '*', '*']]
def pretty_print(t):
    base = len(t[-1])
    maxsize = base + base - 1
    for row in t:
        print(" ".join(row).center(maxsize))
pretty_print(triangle(5))
    *    
   * *   
  * * *  
 * * * * 
* * * * *
def format_line(row, rowsize, maxsize):
    print(" ".join([f"{i:{maxsize}d}" for i in row]).center(rowsize))
        
def get_size_max_int(lastrow):
    return len(str(max(lastrow)))
    
def get_maxsize(lastrow):
    n = len(lastrow)
    maxdigits = get_size_max_int(lastrow)
    rowsize = n*maxdigits + n-1
    return rowsize, maxdigits
    
def pretty_print(t):
    lastrow = t[-1]
    rowsize, maxsize = get_maxsize(lastrow)
    for row in t:
        format_line(row, rowsize, maxsize)
pretty_print(pascal(5))
         1       
       1  1      
      1  2  1    
    1  3  3  1   
   1  4  6  4  1 
 1  5 10 10  5  1
pretty_print(pascal(10))
                      1                    
                    1   1                  
                  1   2   1                
                1   3   3   1              
              1   4   6   4   1            
            1   5  10  10   5   1          
          1   6  15  20  15   6   1        
        1   7  21  35  35  21   7   1      
      1   8  28  56  70  56  28   8   1    
    1   9  36  84 126 126  84  36   9   1  
  1  10  45 120 210 252 210 120  45  10   1
x = 100
f"{x:5d}"
'  100'
pretty_print(pascal(15))
                                         1                                     
                                      1    1                                   
                                    1    2    1                                
                                 1    3    3    1                              
                               1    4    6    4    1                           
                            1    5   10   10    5    1                         
                          1    6   15   20   15    6    1                      
                       1    7   21   35   35   21    7    1                    
                     1    8   28   56   70   56   28    8    1                 
                  1    9   36   84  126  126   84   36    9    1               
                1   10   45  120  210  252  210  120   45   10    1            
             1   11   55  165  330  462  462  330  165   55   11    1          
           1   12   66  220  495  792  924  792  495  220   66   12    1       
        1   13   78  286  715 1287 1716 1716 1287  715  286   78   13    1     
      1   14   91  364 1001 2002 3003 3432 3003 2002 1001  364   91   14    1  
   1   15  105  455 1365 3003 5005 6435 6435 5005 3003 1365  455  105   15    1
pretty_print(pascal(18))
                                                          1                                                      
                                                       1     1                                                   
                                                    1     2     1                                                
                                                 1     3     3     1                                             
                                              1     4     6     4     1                                          
                                           1     5    10    10     5     1                                       
                                        1     6    15    20    15     6     1                                    
                                     1     7    21    35    35    21     7     1                                 
                                  1     8    28    56    70    56    28     8     1                              
                               1     9    36    84   126   126    84    36     9     1                           
                            1    10    45   120   210   252   210   120    45    10     1                        
                         1    11    55   165   330   462   462   330   165    55    11     1                     
                      1    12    66   220   495   792   924   792   495   220    66    12     1                  
                   1    13    78   286   715  1287  1716  1716  1287   715   286    78    13     1               
                1    14    91   364  1001  2002  3003  3432  3003  2002  1001   364    91    14     1            
             1    15   105   455  1365  3003  5005  6435  6435  5005  3003  1365   455   105    15     1         
          1    16   120   560  1820  4368  8008 11440 12870 11440  8008  4368  1820   560   120    16     1      
       1    17   136   680  2380  6188 12376 19448 24310 24310 19448 12376  6188  2380   680   136    17     1   
    1    18   153   816  3060  8568 18564 31824 43758 48620 43758 31824 18564  8568  3060   816   153    18     1
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(30))
[0,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13,
 14,
 15,
 16,
 17,
 18,
 19,
 20,
 21,
 22,
 23,
 24,
 25,
 26,
 27,
 28,
 29]
pretty_print(triangle(10))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[45], line 1
----> 1 pretty_print(triangle(10))

Cell In[32], line 18, in pretty_print(t)
     16 rowsize, maxsize = get_maxsize(lastrow)
     17 for row in t:
---> 18     format_line(row, rowsize, maxsize)

Cell In[32], line 2, in format_line(row, rowsize, maxsize)
      1 def format_line(row, rowsize, maxsize):
----> 2     print(" ".join([f"{i:{maxsize}d}" for i in row]).center(rowsize))

ValueError: Unknown format code 'd' for object of type 'str'
f"{x:5d}"
'  100'
str(x).rjust(5)
'  100'
def format_line(row, rowsize, maxsize):
    print(" ".join([str(i).rjust(maxsize) for i in row]).center(rowsize))
        
def get_size_max_int(lastrow):
    def mylen(x):
        return len(str(x))
    return mylen(max(lastrow, key=mylen))
    
def get_maxsize(lastrow):
    n = len(lastrow)
    maxdigits = get_size_max_int(lastrow)
    rowsize = maxdigits*n + n-1
    print(rowsize, maxdigits)
    return rowsize, maxdigits
    
def pretty_print(t):
    lastrow = t[-1]
    rowsize, maxsize = get_maxsize(lastrow)
    for row in t:
        format_line(row, rowsize, maxsize)
pretty_print(pascal(10))
43 3
                      1                    
                    1   1                  
                  1   2   1                
                1   3   3   1              
              1   4   6   4   1            
            1   5  10  10   5   1          
          1   6  15  20  15   6   1        
        1   7  21  35  35  21   7   1      
      1   8  28  56  70  56  28   8   1    
    1   9  36  84 126 126  84  36   9   1  
  1  10  45 120 210 252 210 120  45  10   1
pretty_print(triangle(10))
19 1
         *         
        * *        
       * * *       
      * * * *      
     * * * * *     
    * * * * * *    
   * * * * * * *   
  * * * * * * * *  
 * * * * * * * * * 
* * * * * * * * * *

Classes

Bank Account - deposit - withdraw - check balance

%%file bank0.py

balance = 0

def deposit(amount):
    global balance
    balance += amount

def withdraw(amount):
    global balance # global keyword is put here because we want to modify global variable!
    balance -= amount

def get_balance():
    return balance
Writing bank0.py
import bank0
bank0.get_balance()
0
bank0.deposit(10000)
bank0.get_balance()
10000
bank0.withdraw(4200)
bank0.get_balance()
5800
%%file bank1.py

def create_account(name, amount):
    return {'balance':amount,
            'name':name}

def deposit(account, amount):
    account['balance'] += amount

def withdraw(account, amount):
    account['balance'] -= amount

def get_balance(account):
    return account['balance']
    
Writing bank1.py
import bank1
acc_v = bank1.create_account("Vikrant", 4500)
bank1.get_balance(acc_v)
4500
bank1.deposit(acc_v, 2000)
bank1.get_balance(acc_v)
6500
bank1.withdraw(acc_v, 3434)
bank1.get_balance(acc_v)
3066
acc_t = bank1.create_account("Tushar", 57090)
bank1.get_balance(acc_t)
57090
class BankAccount:

    def __init__(self, name, amount): # dunder init
        self.name = name
        self.balance = amount

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if self.balance < amount:
            raise Exception(f"Balance is low, can not withdraw {amount}!")
        self.balance -= amount

    def get_balance(self):
        return self.balance
acc1 = BankAccount("Pallvi", 10000)
acc1.get_balance()
10000
acc1.deposit(5660) # you don't self here.. it will be passed automatically
acc1.get_balance()
15660
acc1.withdraw(4500)
acc1.get_balance()
11160
acc1.withdraw(20000)
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
Cell In[122], line 1
----> 1 acc1.withdraw(20000)

Cell In[112], line 12, in BankAccount.withdraw(self, amount)
     10 def withdraw(self, amount):
     11     if self.balance < amount:
---> 12         raise Exception(f"Balance is low, can not withdraw {amount}!")
     13     self.balance -= amount

Exception: Balance is low, can not withdraw 20000!
acc2 = BankAccount("Abid", 54500)
acc2.get_balance()
54500
x = 100
text = "Hello"
f = 45.7
nums = [1, 2, 3, 4]
t = (1, 2, 3)
type(x)
int
type(text)
str
type(nums)
list
list("hello")
['h', 'e', 'l', 'l', 'o']
type(t)
tuple
tuple([1, 2, 3, 4])
(1, 2, 3, 4)
type(acc1)
__main__.BankAccount
isinstance(x, int)
True
isinstance(nums, list)
True
isinstance(acc1, BankAccount)
True
class A:

    def foo():
        return 10
a = A()
a.foo() # python passed self as first argument here!
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[111], line 1
----> 1 a.foo() # python passed self as first argument here!

TypeError: A.foo() takes 0 positional arguments but 1 was given
class SalaryAccount(BankAccount):

    def withdraw(self, amount): #over ridden method
        self.balance -=amount
v = SalaryAccount("Vikrant", 5000)
v.withdraw(10000)
v.get_balance()
-5000
v.deposit(10000)
v.get_balance()
5000