Python Virtual Training For Arcesium - Module I - Day 5

Aug 17-21, 2020 Vikrant Patil

These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch2/module1-day5.html

© Pipal Academy LLP

Day 1 | Day 2 | Day 3 | Day 4 | Day 5

We will be using jupyter hub from http://lab2.pipal.in for this training. Use notebook with name module1-day5.ipynb for today's session.

problem Write a function rearrange_max to rearrange digits of an integer so as to make maximum integer from it.

In [3]:
intvalue = 34656
strnum = str(intvalue)
In [4]:
strnum
Out[4]:
'34656'
In [5]:
for c in strnum:
    print(c, end=",")
3,4,6,5,6,
In [6]:
digits = []
for c in strnum:
    digits.append(c)
digits
Out[6]:
['3', '4', '6', '5', '6']
In [7]:
list(strnum)
Out[7]:
['3', '4', '6', '5', '6']
In [8]:
sorted(digits)
Out[8]:
['3', '4', '5', '6', '6']
In [9]:
sorted(digits, reverse=True)
Out[9]:
['6', '6', '5', '4', '3']
In [10]:
"".join(sorted(digits, reverse=True))
Out[10]:
'66543'
In [11]:
int("".join(sorted(digits, reverse=True)))
Out[11]:
66543
In [12]:
digits.sort(reverse=True)
digits
Out[12]:
['6', '6', '5', '4', '3']
In [15]:
def rearrangemax(intvalue):
    strnum = str(intvalue)
    digits = list(strnum)
    digits.sort(reverse=True)
    return int("".join(digits))
rearrangemax(346556)
In [17]:
strnum = list(str(232324))
In [18]:
def rearrangemax(intvalue):
    digits = list(str(intvalue))
    digits.sort(reverse=True)
    return int("".join(digits))
In [19]:
rearrangemax(45465)
Out[19]:
65544
In [20]:
num = 3452
a = list(str(num))
lista  = []
for i in a:
    lista.append(a[i])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-c0ed1b3aa860> in <module>
      3 lista  = []
      4 for i in a:
----> 5     lista.append(a[i])

TypeError: list indices must be integers or slices, not str
In [21]:
for i in a:
    print(i, type(i))
3 <class 'str'>
4 <class 'str'>
5 <class 'str'>
2 <class 'str'>
In [22]:
a = ['3', '4','5','2']
In [23]:
a['3']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-addeee7d9965> in <module>
----> 1 a['3']

TypeError: list indices must be integers or slices, not str
In [24]:
a[0]
Out[24]:
'3'
In [29]:
digits = list(str(num))
lista = []
for digit in digits: ## i itself 
    lista.append(digit)
In [30]:
lista
Out[30]:
['3', '4', '5', '2']

List indexing

In [32]:
nums = [2, 3, 4, 56, 6]
In [33]:
for n in nums:
    print(n, end=",")
2,3,4,56,6,
In [34]:
sorted(nums)
Out[34]:
[2, 3, 4, 6, 56]
In [35]:
digits = list(str(5465))
In [36]:
digits
Out[36]:
['5', '4', '6', '5']
In [37]:
sorted(digits, reverse=True) # this function returns new sorted list
Out[37]:
['6', '5', '5', '4']
In [38]:
digits.sort(reverse=True) ## does not return anything. it sorts the list inplace
In [39]:
digits
Out[39]:
['6', '5', '5', '4']
In [40]:
x = digits.sort(reverse=True)
In [41]:
print(x)
None
In [42]:
digits
Out[42]:
['6', '5', '5', '4']
In [43]:
x = sorted(digits, reverse=True)
In [44]:
print(x)
['6', '5', '5', '4']
In [45]:
int('6,6,5,4,3')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-45-cf66282f1a14> in <module>
----> 1 int('6,6,5,4,3')

ValueError: invalid literal for int() with base 10: '6,6,5,4,3'
In [46]:
int('6643')
Out[46]:
6643
In [47]:
",".join(digits)
Out[47]:
'6,5,5,4'
In [48]:
"".join(digits)
Out[48]:
'6554'
In [49]:
def fib(n): # recursion
    if n == 1 or n == 0:
        return 1
    
    return fib(n-1) + fib(n-2)
In [50]:
fib(5)
Out[50]:
8
fib(5)
   fib(4)           +         fib(3)
      fib(3)+fib(2)         fib(2) + fib(1)
                          fib(1)+fib(0)

Modules

In [51]:
import os
In [52]:
import math
In [53]:
import math as m
In [54]:
math.sqrt(45)
Out[54]:
6.708203932499369
In [55]:
m.sqrt(45)
Out[55]:
6.708203932499369
In [58]:
from math import pi 
In [57]:
pi
Out[57]:
3.141592653589793
In [59]:
math
Out[59]:
<module 'math' from '/home/vikrant/anaconda3/lib/python3.8/lib-dynload/math.cpython-38-x86_64-linux-gnu.so'>
In [60]:
m
Out[60]:
<module 'math' from '/home/vikrant/anaconda3/lib/python3.8/lib-dynload/math.cpython-38-x86_64-linux-gnu.so'>
In [61]:
mathematics
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-61-1cd801a2cb1f> in <module>
----> 1 mathematics

NameError: name 'mathematics' is not defined
In [62]:
import math as mathematics
In [63]:
mathematics
Out[63]:
<module 'math' from '/home/vikrant/anaconda3/lib/python3.8/lib-dynload/math.cpython-38-x86_64-linux-gnu.so'>
In [64]:
mathematics.sqrt(34)
Out[64]:
5.830951894845301
In [65]:
def call_sqrt_from_module(module, n):
    return module.sqrt(n)
In [66]:
call_sqrt_from_module(math, 45)
Out[66]:
6.708203932499369
In [67]:
call_sqrt_from_module(mathematics, 45)
Out[67]:
6.708203932499369
In [1]:
import math
m = math
In [2]:
import math as m
In [3]:
import os
In [4]:
from os import listdir
In [5]:
os.getcwd()
Out[5]:
'/home/vikrant/trainings/2020/arcesium_finop_batch2'
In [6]:
cwd = os.getcwd()
In [7]:
os.listdir() # if no paramters are passed then it will return files in curret directory
Out[7]:
['module1-day5.html',
 'push',
 'module1-day5.ipynb',
 'Untitled.html',
 'test',
 'module1-day1.html',
 'module1-day1.ipynb',
 'module1-day2.ipynb',
 'module1-day3.html',
 'module1-day2.html',
 'module1-day3.ipynb',
 'module1-day4.html',
 'Makefile',
 '.ipynb_checkpoints',
 'module1-day4.ipynb']
In [8]:
os.listdir("/tmp/") # if folder path is passed, it will return list files in the folder
Out[8]:
['.org.chromium.Chromium.K7AHHz',
 '.X11-unix',
 'skype-1714',
 'systemd-private-14e4f159005c46ebb9aa0b7906ca4360-systemd-timesyncd.service-ivRrZl',
 'skypeforlinux Crashes',
 'systemd-private-14e4f159005c46ebb9aa0b7906ca4360-bolt.service-LkCsuu',
 '.bubblewrap-0',
 'net-export',
 'Temp-19e8c0b6-caf8-49eb-ba05-b23f10768176',
 'bluejeans-v2 Crashes',
 'ssh-syPlPpw6zFPk',
 'Temp-4ed6d016-d3f1-4fdc-811a-ac3f96fba48e',
 'systemd-private-14e4f159005c46ebb9aa0b7906ca4360-systemd-resolved.service-GudtQd',
 '.org.chromium.Chromium.FBJMJS',
 '.org.chromium.Chromium.DhntxE',
 '.XIM-unix',
 'systemd-private-14e4f159005c46ebb9aa0b7906ca4360-ModemManager.service-GtWzlD',
 'systemd-private-14e4f159005c46ebb9aa0b7906ca4360-colord.service-6K5MZG',
 '.org.chromium.Chromium.tQRlPe',
 '.Test-unix',
 '.font-unix',
 '.X0-lock',
 'systemd-private-14e4f159005c46ebb9aa0b7906ca4360-rtkit-daemon.service-swLrf8',
 '.ICE-unix',
 '.org.chromium.Chromium.q4c91M',
 'config-err-OiSuWi',
 'mintUpdate',
 '.org.chromium.Chromium.ztLNMj']
In [9]:
os.mkdir("test")
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-9-90ba2ceae59e> in <module>
----> 1 os.mkdir("test")

FileExistsError: [Errno 17] File exists: 'test'
In [ ]:
os.listdir()
In [10]:
os.path.isfile("test")
Out[10]:
False
In [11]:
os.path.isdir("test")
Out[11]:
True
In [12]:
os.path.getsize("module1-day1.ipynb") # gives size in bytes
Out[12]:
79674
In [13]:
os.path.getsize(cwd)
Out[13]:
4096
In [14]:
os.path.getsize("test/")
Out[14]:
4096
In [15]:
os.listdir()
Out[15]:
['module1-day5.html',
 'push',
 'module1-day5.ipynb',
 'Untitled.html',
 'test',
 'module1-day1.html',
 'module1-day1.ipynb',
 'module1-day2.ipynb',
 'module1-day3.html',
 'module1-day2.html',
 'module1-day3.ipynb',
 'module1-day4.html',
 'Makefile',
 '.ipynb_checkpoints',
 'module1-day4.ipynb']
In [16]:
os.path.join("home", "vikrant", "training")
Out[16]:
'home/vikrant/training'
In [17]:
os.path.isfile("/home/vikrant/trainings/") # not a good style! 
Out[17]:
False
In [18]:
path = os.path.join("/", "home", "vikrant" "trainings")
os.path.isfile(path)
Out[18]:
False
In [19]:
os.mkdir(os.path.join(cwd, "test", "test2"))
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-19-2adba2cf255d> in <module>
----> 1 os.mkdir(os.path.join(cwd, "test", "test2"))

FileExistsError: [Errno 17] File exists: '/home/vikrant/trainings/2020/arcesium_finop_batch2/test/test2'
In [20]:
os.listdir()
Out[20]:
['module1-day5.html',
 'push',
 'module1-day5.ipynb',
 'Untitled.html',
 'test',
 'module1-day1.html',
 'module1-day1.ipynb',
 'module1-day2.ipynb',
 'module1-day3.html',
 'module1-day2.html',
 'module1-day3.ipynb',
 'module1-day4.html',
 'Makefile',
 '.ipynb_checkpoints',
 'module1-day4.ipynb']
In [21]:
data = {"x":1, "y":2, "z":3}
for k, v in data.items():
    print(k, v)
x 1
y 2
z 3
In [22]:
for path, dirs, files in os.walk(cwd):
    for f in files:
        print(f)
module1-day5.html
push
module1-day5.ipynb
Untitled.html
module1-day1.html
module1-day1.ipynb
module1-day2.ipynb
module1-day3.html
module1-day2.html
module1-day3.ipynb
module1-day4.html
Makefile
module1-day4.ipynb
module1-day4-checkpoint.ipynb
module1-day4-checkpoint.html
module1-day2-checkpoint.ipynb
module1-day3-checkpoint.ipynb
module1-day5-checkpoint.ipynb
module1-day1-checkpoint.ipynb
In [23]:
for path, dirs, files in os.walk(cwd):
    for f in files:
        print(os.path.join(path, f))
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day5.html
/home/vikrant/trainings/2020/arcesium_finop_batch2/push
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day5.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/Untitled.html
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day1.html
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day1.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day2.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day3.html
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day2.html
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day3.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day4.html
/home/vikrant/trainings/2020/arcesium_finop_batch2/Makefile
/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day4.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day4-checkpoint.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day4-checkpoint.html
/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day2-checkpoint.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day3-checkpoint.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day5-checkpoint.ipynb
/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day1-checkpoint.ipynb
In [24]:
os.getcwd() # wheree the interpreter is running
Out[24]:
'/home/vikrant/trainings/2020/arcesium_finop_batch2'
In [25]:
folderpath = "/home/vikrant/trainings/2020"
os.listdir(folderpath)
Out[25]:
['arcesium_finop_batch2',
 'arcesium_advanced_feb',
 'arcesium_finop_batch1_module1']
In [26]:
folderpath = "/home/vikrant/trainings/2020"
for item in os.listdir(folderpath):
    path = os.path.join(folderpath, item)
    print(path)
/home/vikrant/trainings/2020/arcesium_finop_batch2
/home/vikrant/trainings/2020/arcesium_advanced_feb
/home/vikrant/trainings/2020/arcesium_finop_batch1_module1

Usecases

We want to find files with extension ".ipynb" from given folder

In [27]:
def findfiles(folderpath, ext):
    files = []
    for item in os.listdir(folderpath):
        if os.path.isfile(item) and item.endswith(ext):
            files.append(os.path.join(folderpath, item))
    return files
            
In [28]:
findfiles(cwd, ".ipynb")
Out[28]:
['/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day5.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day1.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day2.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day3.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day4.ipynb']
In [29]:
findfiles(cwd, ".html")
Out[29]:
['/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day5.html',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/Untitled.html',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day1.html',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day3.html',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day2.html',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day4.html']
In [30]:
def findfiles(folderpath, ext):
    files = []
    for item in os.listdir(folderpath):
        path = os.path.join(folderpath, item)
        if os.path.isfile(path) and item.endswith(ext):
            files.append(path)
    return files
            
In [31]:
findfiles("/home/vikrant/Downloads/", ".pdf")
Out[31]:
['/home/vikrant/Downloads/RenewalPremium_9986696.pdf',
 '/home/vikrant/Downloads/Cleartrip Hotel Voucher.pdf',
 '/home/vikrant/Downloads/NITI-Directory041219.pdf',
 '/home/vikrant/Downloads/All About Love_ New Visions.pdf',
 '/home/vikrant/Downloads/Pippi Longstocking by Astrid Lindgren Lauren Child (illus) Tiina Nunnally (transl) (z-lib.org).pdf',
 '/home/vikrant/Downloads/Fuelling_the_Transition-Report.pdf',
 '/home/vikrant/Downloads/Data Visualisation- Session Plan.pdf',
 '/home/vikrant/Downloads/UAM Workshop 4 & 5 October.pdf',
 '/home/vikrant/Downloads/Adam (Marathi) by RATNAKAR MATKARI (z-lib.org).pdf',
 '/home/vikrant/Downloads/TaxInvoiceMH1171811BU11822.pdf',
 '/home/vikrant/Downloads/17.गहू .pdf',
 '/home/vikrant/Downloads/t480s_ug_en.pdf',
 '/home/vikrant/Downloads/33861365_DOC1.pdf',
 '/home/vikrant/Downloads/conda-cheatsheet.pdf',
 '/home/vikrant/Downloads/Vikrant-profile (1).pdf',
 '/home/vikrant/Downloads/000000001.pdf',
 '/home/vikrant/Downloads/AccountStatement.pdf',
 '/home/vikrant/Downloads/TaxInvoiceMH1181902CF09686.pdf',
 '/home/vikrant/Downloads/BasicPythonPostAssessment-Solutions.pdf',
 '/home/vikrant/Downloads/Invoice.pdf',
 "/home/vikrant/Downloads/[Paul_Hoffman]_Archimedes'_Revenge__The_Joys_and_P(z-lib.org).pdf",
 '/home/vikrant/Downloads/VIKRANT PATIL.pdf',
 '/home/vikrant/Downloads/adventures_in_iterations (5).pdf',
 '/home/vikrant/Downloads/Katta Members.pdf',
 '/home/vikrant/Downloads/De-mystifying AI_v2.pdf',
 '/home/vikrant/Downloads/TaxInvoiceDL1181903CM65353.pdf',
 '/home/vikrant/Downloads/intimacyinventory.pdf',
 '/home/vikrant/Downloads/Manasollasa vol 2 pdf.pdf',
 '/home/vikrant/Downloads/Ticket(s)_For_PyCon_India_2019.pdf',
 '/home/vikrant/Downloads/Build Free- How to build your home with net-zero investment_AGP Version.pdf',
 '/home/vikrant/Downloads/ibm-machine-learning-for-dummies-ibm-limited-edition_IMM14209USEN.pdf',
 '/home/vikrant/Downloads/Pune_Serosurvey_Technical_report-16_08_2020.pdf',
 '/home/vikrant/Downloads/107577899-20190209.pdf',
 '/home/vikrant/Downloads/TaxInvoiceAS1181903AK32800.pdf',
 '/home/vikrant/Downloads/6326323_TDSInquiry.pdf',
 '/home/vikrant/Downloads/9_MIDI_code.pdf',
 '/home/vikrant/Downloads/GridPath.pdf',
 '/home/vikrant/Downloads/Good-Will .pdf',
 '/home/vikrant/Downloads/16. पिकलेला आंबा .pdf',
 '/home/vikrant/Downloads/Vikrant-profile.pdf',
 '/home/vikrant/Downloads/Emotional-Vocabulary-List-Color.pdf',
 '/home/vikrant/Downloads/BasicPythonPostAssessment.pdf',
 '/home/vikrant/Downloads/problem-solving-with-python.pdf',
 '/home/vikrant/Downloads/Arcesium_FOP_Training_Modules.pdf',
 '/home/vikrant/Downloads/W Template.pdf',
 '/home/vikrant/Downloads/Invoice(1).pdf',
 '/home/vikrant/Downloads/हनुमान ग्रामीण नगर पोलादपूर Containment zon आदेश क्र.246.pdf',
 '/home/vikrant/Downloads/12918_0000406430.pdf',
 '/home/vikrant/Downloads/InitiateSingleEntryPaymentSummaryUX510-04-2020.pdf',
 '/home/vikrant/Downloads/Springer Ebooks.pdf',
 '/home/vikrant/Downloads/Mastering Pandas for Finance.pdf',
 '/home/vikrant/Downloads/Handbook_Final_WebVersion.pdf',
 '/home/vikrant/Downloads/Corona Regulation Notification (Eng).pdf.pdf',
 '/home/vikrant/Downloads/FHO_2017.pdf',
 '/home/vikrant/Downloads/1927IA0200012877_signed.pdf',
 '/home/vikrant/Downloads/161602_31_2019_12507.pdf',
 '/home/vikrant/Downloads/Lele_Environment and Well Being_NLR 123_May June 2020.pdf',
 '/home/vikrant/Downloads/ArtAtivitiesByAbhaBhagwat.pdf',
 '/home/vikrant/Downloads/kutch-kutch-annsayre.pdf',
 '/home/vikrant/Downloads/Paytm_Wallet_Txn_HistoryJun2019_8552969377.pdf',
 '/home/vikrant/Downloads/12918_0000478298.pdf',
 '/home/vikrant/Downloads/27061900049609.pdf',
 '/home/vikrant/Downloads/InitiateSingleEntryPaymentSummaryUX512-06-2020.pdf',
 '/home/vikrant/Downloads/Ragabot.pdf',
 '/home/vikrant/Downloads/english_18.0.pdf',
 '/home/vikrant/Downloads/Learning Web Concept Note V0.1  pdf.pdf',
 '/home/vikrant/Downloads/Ticket(s)_For_PyCon_India_2020_Online.pdf']
In [32]:
def findfiles(folderpath, ext):
    files_ext = []
    for path, dirs, files in os.walk(folderpath):
        for file in files:
            if file.endswith(ext):
                files_ext.append(os.path.join(path, file))
        
    return files_ext
In [51]:
findfiles(os.getcwd(), ".ipynb")
Out[51]:
['/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day5.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day1.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day2.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day3.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/module1-day4.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day4-checkpoint.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day2-checkpoint.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day3-checkpoint.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day5-checkpoint.ipynb',
 '/home/vikrant/trainings/2020/arcesium_finop_batch2/.ipynb_checkpoints/module1-day1-checkpoint.ipynb']
In [34]:
pdffiles = findfiles("/home/vikrant/Downloads/", ".pdf")
In [35]:
max([1, 2,3, 4, 5])
Out[35]:
5
In [36]:
max(["one", "two", "three", "four", "six"], )
Out[36]:
'two'
In [37]:
pdffiles[0]
Out[37]:
'/home/vikrant/Downloads/RenewalPremium_9986696.pdf'
In [38]:
os.path.getsize(pdffiles[0])
Out[38]:
134257
In [39]:
def findfiles(folderpath, ext):
    files_ext = []
    for path, dirs, files in os.walk(folderpath):
        for file in files:
            if file.endswith(ext):
                files_ext.append(os.path.join(path, file))
        
    return files_ext

``` path dirs files

  • root root [folder1, folder4] [f3.txt, f4.txt] |
    +---folder1 root/folder1 [folder] [f1.txt, f2.txt] | | | +-----f1.txt | +-----f2.txt | | | +-----folder root/folder1/folder [] [x.txt] | | | +---x.txt | +---f3.txt +---f4.txt +---folder4 root/folder4 [] []
In [40]:
x, y = 2, 3
In [41]:
for x, y in zip([1, 2, 3, 4], ['a','b','c','d']):
    print(x, y)
1 a
2 b
3 c
4 d
In [49]:
for k, v in data.items():
    print(k, v)
x 1
y 2
z 3
In [43]:
list(zip([1, 2, 3, 4], ['a','b','c','d']))
Out[43]:
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
In [44]:
list(data.items())
Out[44]:
[('x', 1), ('y', 2), ('z', 3)]
In [45]:
data
Out[45]:
{'x': 1, 'y': 2, 'z': 3}
In [48]:
list(os.walk("test"))
Out[48]:
[('test', ['test2'], []), ('test/test2', [], [])]

Problem

can you modify above function to compute real size of a folder findsize(folder)

In [50]:
def findfiles(folderpath, ext):
    files_ext = []
    for path, dirs, files in os.walk(folderpath):
        for file in files:
            if file.endswith(ext):
                files_ext.append(os.path.join(path, file))
        
    return files_ext
In [61]:
def findsize(folderpath):
    size = 0
    for path, dirs, files in os.walk(folderpath):
        for file in files:
            filepath = os.path.join(path, file)
            size += os.path.getsize(filepath)
        
        for dir_ in dirs:
            dirpath = os.path.join(path, dir_)
            size += os.path.getsize(dirpath)
            
    return size/1024/1024 # make it in MB 
In [57]:
findsize(".")
Out[57]:
2.924649238586426
In [58]:
max(pdffiles, key=os.path.getsize)
Out[58]:
'/home/vikrant/Downloads/Handbook_Final_WebVersion.pdf'
In [59]:
os.path.getsize("Handbook_Final_WebVersion.pdf")
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-59-8a9b9417d255> in <module>
----> 1 os.path.getsize("Handbook_Final_WebVersion.pdf")

~/anaconda3/lib/python3.8/genericpath.py in getsize(filename)
     48 def getsize(filename):
     49     """Return the size of a file, reported by os.stat()."""
---> 50     return os.stat(filename).st_size
     51 
     52 

FileNotFoundError: [Errno 2] No such file or directory: 'Handbook_Final_WebVersion.pdf'
In [60]:
os.path.getsize('/home/vikrant/Downloads/Handbook_Final_WebVersion.pdf')
Out[60]:
395592106

Writing your own modules

In [64]:
%%file stats.py

def mean(nums):
    return sum(nums)/len(nums)

def median(nums):
    n = len(nums)
    c = n//2
    if n%2 ==0:
        return (num[c] + num[c-1])/2.0
    else:
        return num[c]
Overwriting stats.py
In [65]:
import stats
In [66]:
stats.mean([3, 4, 5, 6,7 ])
Out[66]:
5.0

Writing scripts

In [67]:
%%file hello.py
import sys

def hello(name):
    print("Hello", name + "!")
    
def welcome(name):
    hello(name)
    print("Welcome to python programming!")
    
    
name = sys.argv[1] 
welcome(name)
Writing hello.py
In [68]:
!python3 hello.py arcesium
Hello arcesium!
Welcome to python programming!
In [69]:
%%file hello1.py
import sys

def hello(name):
    print("Hello", name + "!")
    
def welcome(name):
    hello(name)
    print("Welcome to python programming!")
    
    
print(sys.argv)
name = sys.argv[1] 
welcome(name)
Writing hello1.py
In [70]:
!python3 hello1.py arcesium 
['hello1.py', 'arcesium']
Hello arcesium!
Welcome to python programming!
In [71]:
!python3 hello1.py arcesium  dhfjdsh kfjdhsf ds ksdhfkdsj  kjhkjhg kjhkjhgkjf kjhgkjhf kjhgkjfh kjfhgkjfh
['hello1.py', 'arcesium', 'dhfjdsh', 'kfjdhsf', 'ds', 'ksdhfkdsj', 'kjhkjhg', 'kjhkjhgkjf', 'kjhgkjhf', 'kjhgkjfh', 'kjfhgkjfh']
Hello arcesium!
Welcome to python programming!
In [72]:
!python3 hello1.py arcesium 34 3434 456
['hello1.py', 'arcesium', '34', '3434', '456']
Hello arcesium!
Welcome to python programming!
In [75]:
%%file add.py
import sys

def add(x, y):
    return x+y


a = int(sys.argv[1])
b = int(sys.argv[2])
print(add(a, b)) ## unless print statement is there nothing will be printed
Overwriting add.py
In [76]:
!python3 add.py 34 56
90
In [77]:
!python3 add.py sdfdsf dfdsfds
Traceback (most recent call last):
  File "add.py", line 7, in <module>
    a = int(sys.argv[1])
ValueError: invalid literal for int() with base 10: 'sdfdsf'
In [78]:
import add
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-78-81459ef23ada> in <module>
----> 1 import add

~/trainings/2020/arcesium_finop_batch2/add.py in <module>
      5 
      6 
----> 7 a = int(sys.argv[1])
      8 b = int(sys.argv[2])
      9 print(add(a, b)) ## unless print statement is there nothing will be printed

ValueError: invalid literal for int() with base 10: '-f'
In [87]:
%%file add1.py
import sys

def add(x, y):
    return x+y



print(__name__) ## dunder name
a = int(sys.argv[1])
b = int(sys.argv[2])
print(add(a, b))
Overwriting add1.py
In [80]:
!python3 add1.py 34 45
__main__
79
In [81]:
import add1
add1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-81-5ffa442179a0> in <module>
----> 1 import add1

~/trainings/2020/arcesium_finop_batch2/add1.py in <module>
      7 
      8 print(__name__) ## dunder name
----> 9 a = int(sys.argv[1])
     10 b = int(sys.argv[2])
     11 print(add(a, b))

ValueError: invalid literal for int() with base 10: '-f'

When you call a script from commandline the variable __name__ will have values of "__main__". When you import same module, it takes value as module name

In [82]:
%%file add2.py
import sys

def add(x, y):
    return x+y


print(__name__) ## dunder name
if __name__ == "__main__":
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    print(add(a, b))
Writing add2.py
In [84]:
!python3 add2.py 34 56
__main__
90
In [85]:
import add2
add2
In [86]:
add2.add(2, 3)
Out[86]:
5

if the script is not in current directory one should give complete path for commandline execution. but for module you must add the folderepath in a sytem variable called PYHTHONPATH

In [ ]: