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)
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
% 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!!
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
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[]]
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
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21]]
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21]]
β 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
['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" )
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'
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
We learnt about statement
We combined statements togather to from a function
we combined statements and our own functions and built in functions/mehtods to form complicated functions
We will have many functions, objects , constants which are related or do similar jobs with slight difeerent flavourβ¦
Python puts all such things in a module.
We get more organised functions, objectsβ¦
import random # this how you import a module
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
random.random() # random is a function inside random module which generates a random number between 0 to 1
['four', 'three', 'two', 'one']
random.choice(words) # choose randomly an item from a list/collection
random.choice("tlkdjsalkd hjgdsa sahLAHF" )
def greet_fun(name):
greetings = ["Hello" , "Namaskar" , "Vanakam" , "Guten Nakth" , "Good Morning" , "Good Night" ]
greeting = random.choice(greetings)
print (greeting, name.capitalize())
import math # all functionality related to mathematical function
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
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
Path seperator is different on unix/mac/linux and on windows
on unix/mac/linux it is forward slash
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'
'/home/jupyter-vikrant/1-1.ipynb'
os.path.isfile(path_for_notebook_day1) # if it is file?
os.path.isfile(os.getcwd()) ##?
os.path.isdir(os.getcwd()) #check if the path is folder
os.path.exists("/home/jupyter-vikrant" )
os.path.exists("/home/jupyter-vikrant/1-1.ipynb" )
os.path.getsize(path_for_notebook_day1) # give size of file in bytes
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)
Absolute path - Relative Path
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
['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
'/home/jupyter-vikrant/arcesium-python-2024'
os.path.getsize("a.txt" ) # this is relative path
os.path.getsize("1-1.ipynb" )
absolute_path = os.path.join(os.getcwd(), "1-1.ipynb" )
'/home/jupyter-vikrant/arcesium-python-2024/1-1.ipynb'
os.path.getsize(absolute_path)
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
['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" )
files = os.listdir()
max (files, key= os.path.getsize)
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))
%% file hello.txt
hello world
%% file argsexp.py
import sys
print (sys.argv)
! 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 ])
! python hello.py arcesium.py