Module 1 - Day 5

Homework problems

%load_problem digit-count
Problem: Digit Count

Write a function digit_count that takes a number and a digit as argument and returns the number of times the digit is present in that number.

>>> digit_count(1231, 1)
2
>>> digit_count(1231, 3)
1
>>> digit_count(1231, 9)
0

Hint

>>> "mathematics".count("mat")
2

You can verify your solution using:

%verify_problem digit-count

# your code here

def digit_count(num, digit):
    numtext = str(num)
    return numtext.count(digit) 
digit_count(1223, 2)
TypeError: must be str, not int
def digit_count(num, digit):
    numtext = str(num)
    textdigit = str(digit)
    return numtext.count(textdigit) 
digit_count(121332434, 3) # test it will different test cases
3
digit_count(1, 3)
0
digit_count(1234, 1)
1
%verify_problem digit-count
βœ“ digit_count(1231, 1)
βœ“ digit_count(1231, 3)
βœ“ digit_count(1231, 9)
βœ“ digit_count(2**1000, 0)
πŸŽ‰ Congratulations! You have successfully solved problem digit-count!!
%load_problem group
Problem: Group

Write a function group that take a list of values and splits into smaller lists of given size.

>>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

You can verify your solution using:

%verify_problem group

# your code here

def group(biggerlist, groupsize):
    groups = []
    start_index = 0
    for item in biggerlist: # best thing about for loop is , it will stop..
        end_index = start_index+groupsize
        group_ = biggerlist[start_index:end_index]
        start_index = end_index
        groups.append(group_)

    return groups
nums = list(range(22))
nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
group(nums, 3)
[[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8],
 [9, 10, 11],
 [12, 13, 14],
 [15, 16, 17],
 [18, 19, 20],
 [21],
 [],
 [],
 [],
 [],
 [],
 [],
 [],
 [],
 [],
 [],
 [],
 [],
 [],
 []]
nums[22:]
[]
nums[25:30]
[]

def group(biggerlist, groupsize):
    groups = []
    start_index = 0
    while start_index < len(biggerlist):
        end_index = start_index+groupsize
        group_ = biggerlist[start_index:end_index]
        start_index = end_index
        groups.append(group_)

    return groups
group(nums, 3)
[[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8],
 [9, 10, 11],
 [12, 13, 14],
 [15, 16, 17],
 [18, 19, 20],
 [21]]
group(nums, 5)
[[0, 1, 2, 3, 4],
 [5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14],
 [15, 16, 17, 18, 19],
 [20, 21]]
%verify_problem group
βœ“ group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
βœ“ group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
βœ“ group([1, 2, 3, 4, 5], 1)
βœ“ group([1, 2, 3, 4, 5], 5)
βœ“ group([1, 2, 3, 4, 5], 10)
βœ“ group([], 10)
πŸŽ‰ Congratulations! You have successfully solved problem group!!
%load_problem reverse-words
Problem: Reverse Words

Write a function reverse_words that takes a sentence and returns a new sentence with all the words in the reserse order.

>>> reverse_words("joy of programming")
'programming of joy'

>>> reverse_words("less is more")
'more is less'

>>> reverse_words("road goes ever on and on")
'on and on ever goes road'

Please note that only the order of the words in the sentence is reversed, not the letters in each word.

You can verify your solution using:

%verify_problem reverse-words

# your code here

def reverse_words(sentence):
    words = sentence.split() # don't give any arguments to split because we want to split on white space
    return words.reverse() # this will return None
    
words = ["one", "two", "three", "four"] # list!
words.reverse() # this will rverse in place
words
['four', 'three', 'two', 'one']
reverse_words("Hello this is some sentence")

def reverse_words(sentence):
    words = sentence.split() # don't give any arguments to split because we want to split on white space
    words.reverse()
    return words
    
reverse_words("road goes ever on and on")
['on', 'and', 'on', 'ever', 'goes', 'road']

def reverse_words(sentence):
    words = sentence.split() # don't give any arguments to split because we want to split on white space
    words.reverse()
    return " ".join(words)
reverse_words("road goes ever on and on")
'on and on ever goes road'
%verify_problem reverse_words
FileNotFoundError: [Errno 2] No such file or directory: '/opt/training/problems/reverse_words/problem.yml'
%verify_problem reverse-words
βœ“ reverse_words("joy of programming")
βœ“ reverse_words("less is more")
βœ“ reverse_words("road goes ever on and on")
πŸŽ‰ Congratulations! You have successfully solved problem reverse-words!!
def make_words(sentence):
    words = []
    word = ""
    for c in sentence:
        if c == " ":
            words.append(word)
            word = ""
        else:
            word = word + c

    return words
    
make_words("This some text data with some words")
['This', 'some', 'text', 'data', 'with', 'some']
def reverse_words(sentence):
    words = make_words(sentence)
    return " ".join(words[::-1])
reverse_words("joy of programming")
'of joy'
if []: will result into false
if "": will result into false
if {}: will result into false
def make_words(sentence):
    words = []
    word = ""
    for c in sentence:
        if c == " ":
            words.append(word)
            word = ""
        else:
            word = word + c

    if word:
        words.append(word)
        
    return words
reverse_words("Hello  now this will work")
'work will this now  Hello'
list(range(5, -1, -1))
[5, 4, 3, 2, 1, 0]
def reverse_words(sentence):
    words = sentence.split()
    rwords = []

    for i in range(len(words) - 1, -1, -1):
        rwords.append(words[i])

    rsentence = ' '.join(rwords)
    return rsentence
reverse_words("Hello reverse these words")
'words these reverse Hello'

built in modules

  1. We learnt about statement
  2. We combined statements togather to from a function
  3. we combined statements and our own functions and built in functions/mehtods to form complicated functions
  4. We will have many functions, objects , constants which are related or do similar jobs with slight difeerent flavour…
  5. Python puts all such things in a module.
  6. We get more organised functions, objects…
import random # this how you import a module
nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
nums.index(5)
5
random.random() # random is a function inside random module which generates a random number between 0 to 1
0.5376317629171143
random.random()
0.07438575668142422
words
['four', 'three', 'two', 'one']
random.choice(words) # choose randomly an item from a list/collection
'three'
random.choice("tlkdjsalkd hjgdsa sahLAHF")
'L'
def greet_fun(name):
    greetings = ["Hello", "Namaskar", "Vanakam", "Guten Nakth", "Good Morning", "Good Night"]
    greeting = random.choice(greetings)
    print(greeting, name.capitalize())
greet_fun("arcesium")
Guten Nakth Arcesium
greet_fun("arcesium")
Good Morning Arcesium
import math # all functionality related to mathematical function
math.pi
3.141592653589793
math.e
2.718281828459045
import math as m # this is also one way of importing a module and giving it some convenient name
m.pi # this actuall yrefers to pi constant from math mondule
3.141592653589793
m.sin(0)
0.0
import os # this will be useful module for working with finding or listing files from some folders/some location on your computer
os.getcwd() # give me current working directory/folder
'/home/jupyter-vikrant/arcesium-python-2024'

The output that you see here is your current working directory on our jupyter server

"-".join(words)
'four-three-two-one'

Path seperator is different on unix/mac/linux and on windows

  1. on unix/mac/linux it is forward slash
  2. on windows/dos it is backword slash
path_for_notebook_day1 = os.path.join("/", "home" , "jupyter-vikrant", "1-1.ipynb")
path_for_notebook_day1 # this is a filepath that I can make use of in case I want to read/write using python
'/home/jupyter-vikrant/1-1.ipynb'
os.path.join("c:","Program Files", "Python", "myprogram.py") # here is will show farward slash but on windows it will back slash
'c:/Program Files/Python/myprogram.py'
"c:\\Program Files\\Python\\myprogram.py"
'c:\\Program Files\\Python\\myprogram.py'
path_for_notebook_day1
'/home/jupyter-vikrant/1-1.ipynb'
os.path.isfile(path_for_notebook_day1) # if it is file?
True
os.path.isfile(os.getcwd()) ##?
False
os.path.isdir(os.getcwd()) #check if the path is folder
True
os.path.exists("/home/jupyter-vikrant")
True
os.path.exists("/home/jupyter-vikrant/1-1.ipynb")
True
os.path.getsize(path_for_notebook_day1) # give size of file in bytes
1563
home_folder = "/home/jupyter-vikrant"
os.path.join(home_folder, "arcesium-python-2024")
'/home/jupyter-vikrant/arcesium-python-2024'
notebook1 = os.path.join(home_folder, "arcesium-python-2024", "1-1.ipynb")
os.path.getsize(notebook1)
76423

Absolute path - Relative Path

os.getlogin() # 
OSError: [Errno 6] No such device or address
def get_downloads_folder():
    username = os.getlogin()
    return os.path.join("/","home", username, "Downloads")

Find out files in some folder


os.listdir(home_folder)
['arcesium-python-2024',
 '1-1.ipynb',
 '.config',
 '.wget-hsts',
 'a.txt',
 '1-5.ipynb',
 '.jupyter',
 '.ipython',
 'sync.py',
 '.profile',
 '1-4.ipynb',
 '.ssh',
 '.gitconfig',
 '.ipynb_checkpoints',
 '.bash_logout',
 '.viminfo',
 '.cache',
 '1-2.ipynb',
 '.lesshst',
 '.local',
 'final',
 '1-3.ipynb',
 '__pycache__',
 '.bashrc',
 'assignments',
 '.bash_history',
 'joy.py',
 'hello.ipynb',
 'users.txt']
for item in os.listdir(home_folder):
    print(os.path.join(home_folder, item))
/home/jupyter-vikrant/arcesium-python-2024
/home/jupyter-vikrant/1-1.ipynb
/home/jupyter-vikrant/.config
/home/jupyter-vikrant/.wget-hsts
/home/jupyter-vikrant/a.txt
/home/jupyter-vikrant/1-5.ipynb
/home/jupyter-vikrant/.jupyter
/home/jupyter-vikrant/.ipython
/home/jupyter-vikrant/sync.py
/home/jupyter-vikrant/.profile
/home/jupyter-vikrant/1-4.ipynb
/home/jupyter-vikrant/.ssh
/home/jupyter-vikrant/.gitconfig
/home/jupyter-vikrant/.ipynb_checkpoints
/home/jupyter-vikrant/.bash_logout
/home/jupyter-vikrant/.viminfo
/home/jupyter-vikrant/.cache
/home/jupyter-vikrant/1-2.ipynb
/home/jupyter-vikrant/.lesshst
/home/jupyter-vikrant/.local
/home/jupyter-vikrant/final
/home/jupyter-vikrant/1-3.ipynb
/home/jupyter-vikrant/__pycache__
/home/jupyter-vikrant/.bashrc
/home/jupyter-vikrant/assignments
/home/jupyter-vikrant/.bash_history
/home/jupyter-vikrant/joy.py
/home/jupyter-vikrant/hello.ipynb
/home/jupyter-vikrant/users.txt

If we refer to a file with respec to current working directory …then we tell only file name .. it is called as relvative path

if we give complete filepath right from the drive(windows) or root (linux) .. called as absoulte path

os.getcwd()
'/home/jupyter-vikrant/arcesium-python-2024'
os.path.getsize("a.txt") # this is relative path 
0
os.path.getsize("1-1.ipynb")
76423
absolute_path = os.path.join(os.getcwd(), "1-1.ipynb")
absolute_path
'/home/jupyter-vikrant/arcesium-python-2024/1-1.ipynb'
os.path.getsize(absolute_path)
76423
for item in os.listdir(): # if you do not give any argument to listdir , it wil ltake current working directory
    print(os.getcwd(), "/" , item) # print has taken three arguments ..it will separate wach argument by space
/home/jupyter-vikrant/arcesium-python-2024 / 1-1.ipynb
/home/jupyter-vikrant/arcesium-python-2024 / index.qmd
/home/jupyter-vikrant/arcesium-python-2024 / syllabus.qmd
/home/jupyter-vikrant/arcesium-python-2024 / manage.py
/home/jupyter-vikrant/arcesium-python-2024 / .gitignore
/home/jupyter-vikrant/arcesium-python-2024 / a.txt
/home/jupyter-vikrant/arcesium-python-2024 / mkdocs.yml
/home/jupyter-vikrant/arcesium-python-2024 / 1-5.ipynb
/home/jupyter-vikrant/arcesium-python-2024 / README.md
/home/jupyter-vikrant/arcesium-python-2024 / session1.ipynb
/home/jupyter-vikrant/arcesium-python-2024 / schedule.qmd
/home/jupyter-vikrant/arcesium-python-2024 / archive
/home/jupyter-vikrant/arcesium-python-2024 / lab.qmd
/home/jupyter-vikrant/arcesium-python-2024 / assignments.yml
/home/jupyter-vikrant/arcesium-python-2024 / 1-4.ipynb
/home/jupyter-vikrant/arcesium-python-2024 / scripts
/home/jupyter-vikrant/arcesium-python-2024 / etc
/home/jupyter-vikrant/arcesium-python-2024 / grades.db.dir
/home/jupyter-vikrant/arcesium-python-2024 / assignment-1.ipynb
/home/jupyter-vikrant/arcesium-python-2024 / .ipynb_checkpoints
/home/jupyter-vikrant/arcesium-python-2024 / .git
/home/jupyter-vikrant/arcesium-python-2024 / pipalhub-magic
/home/jupyter-vikrant/arcesium-python-2024 / python-practice-problems
/home/jupyter-vikrant/arcesium-python-2024 / grades.db.dat
/home/jupyter-vikrant/arcesium-python-2024 / problems
/home/jupyter-vikrant/arcesium-python-2024 / .quarto
/home/jupyter-vikrant/arcesium-python-2024 / about.qmd
/home/jupyter-vikrant/arcesium-python-2024 / .cache
/home/jupyter-vikrant/arcesium-python-2024 / 1-2.ipynb
/home/jupyter-vikrant/arcesium-python-2024 / .gitmodules
/home/jupyter-vikrant/arcesium-python-2024 / requirements.txt
/home/jupyter-vikrant/arcesium-python-2024 / docs
/home/jupyter-vikrant/arcesium-python-2024 / 1-3.ipynb
/home/jupyter-vikrant/arcesium-python-2024 / live-notes.service
/home/jupyter-vikrant/arcesium-python-2024 / _site
/home/jupyter-vikrant/arcesium-python-2024 / sigma
/home/jupyter-vikrant/arcesium-python-2024 / grades.db.bak
/home/jupyter-vikrant/arcesium-python-2024 / _quarto.yml
/home/jupyter-vikrant/arcesium-python-2024 / styles.css
/home/jupyter-vikrant/arcesium-python-2024 / Grading.ipynb
for item in os.listdir(): # if you do not give any argument to listdir , it wil ltake current working directory
    print( os.path.join(os.getcwd(), item)) 
/home/jupyter-vikrant/arcesium-python-2024/1-1.ipynb
/home/jupyter-vikrant/arcesium-python-2024/index.qmd
/home/jupyter-vikrant/arcesium-python-2024/syllabus.qmd
/home/jupyter-vikrant/arcesium-python-2024/manage.py
/home/jupyter-vikrant/arcesium-python-2024/.gitignore
/home/jupyter-vikrant/arcesium-python-2024/a.txt
/home/jupyter-vikrant/arcesium-python-2024/mkdocs.yml
/home/jupyter-vikrant/arcesium-python-2024/1-5.ipynb
/home/jupyter-vikrant/arcesium-python-2024/README.md
/home/jupyter-vikrant/arcesium-python-2024/session1.ipynb
/home/jupyter-vikrant/arcesium-python-2024/schedule.qmd
/home/jupyter-vikrant/arcesium-python-2024/archive
/home/jupyter-vikrant/arcesium-python-2024/lab.qmd
/home/jupyter-vikrant/arcesium-python-2024/assignments.yml
/home/jupyter-vikrant/arcesium-python-2024/1-4.ipynb
/home/jupyter-vikrant/arcesium-python-2024/scripts
/home/jupyter-vikrant/arcesium-python-2024/etc
/home/jupyter-vikrant/arcesium-python-2024/grades.db.dir
/home/jupyter-vikrant/arcesium-python-2024/assignment-1.ipynb
/home/jupyter-vikrant/arcesium-python-2024/.ipynb_checkpoints
/home/jupyter-vikrant/arcesium-python-2024/.git
/home/jupyter-vikrant/arcesium-python-2024/pipalhub-magic
/home/jupyter-vikrant/arcesium-python-2024/python-practice-problems
/home/jupyter-vikrant/arcesium-python-2024/grades.db.dat
/home/jupyter-vikrant/arcesium-python-2024/problems
/home/jupyter-vikrant/arcesium-python-2024/.quarto
/home/jupyter-vikrant/arcesium-python-2024/about.qmd
/home/jupyter-vikrant/arcesium-python-2024/.cache
/home/jupyter-vikrant/arcesium-python-2024/1-2.ipynb
/home/jupyter-vikrant/arcesium-python-2024/.gitmodules
/home/jupyter-vikrant/arcesium-python-2024/requirements.txt
/home/jupyter-vikrant/arcesium-python-2024/docs
/home/jupyter-vikrant/arcesium-python-2024/1-3.ipynb
/home/jupyter-vikrant/arcesium-python-2024/live-notes.service
/home/jupyter-vikrant/arcesium-python-2024/_site
/home/jupyter-vikrant/arcesium-python-2024/sigma
/home/jupyter-vikrant/arcesium-python-2024/grades.db.bak
/home/jupyter-vikrant/arcesium-python-2024/_quarto.yml
/home/jupyter-vikrant/arcesium-python-2024/styles.css
/home/jupyter-vikrant/arcesium-python-2024/Grading.ipynb
os.listdir()
['1-1.ipynb',
 'index.qmd',
 'syllabus.qmd',
 'manage.py',
 '.gitignore',
 'a.txt',
 'mkdocs.yml',
 '1-5.ipynb',
 'README.md',
 'session1.ipynb',
 'schedule.qmd',
 'archive',
 'lab.qmd',
 'assignments.yml',
 '1-4.ipynb',
 'scripts',
 'etc',
 'grades.db.dir',
 'assignment-1.ipynb',
 '.ipynb_checkpoints',
 '.git',
 'pipalhub-magic',
 'python-practice-problems',
 'grades.db.dat',
 'problems',
 '.quarto',
 'about.qmd',
 '.cache',
 '1-2.ipynb',
 '.gitmodules',
 'requirements.txt',
 'docs',
 '1-3.ipynb',
 'live-notes.service',
 '_site',
 'sigma',
 'grades.db.bak',
 '_quarto.yml',
 'styles.css',
 'Grading.ipynb']
os.path.getsize("1-1.ipynb")
76423
files = os.listdir()
max(files, key=os.path.getsize)
'Grading.ipynb'

Python script

%%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))
Writing add.py
%%file hello.txt

hello world
Writing hello.txt
!python add.py 4 5
9
%%file argsexp.py

import sys

print(sys.argv)
Overwriting argsexp.py
!python argsexp.py hello
['argsexp.py', 'hello']
!python argsexp.py 1 1 a b c
['argsexp.py', '1', '1', 'a', 'b', 'c']
!python argsexp.py 656 232 3
['argsexp.py', '656', '232', '3']
  • Arguments passed from command line will be part of this list sys.argv
  • every argument is text by default
%%file hello.py

import sys

print("hello" , sys.argv[1])
Writing hello.py
!python hello.py arcesium.py
hello arcesium.py