HW Python Basic & pathlib
#
Problem Set 1 [45 points]#
Please use Python 3.6+ (never Python 2).
For other packages: Although I didn’t run all the tests, there will likely be no problem if you use decently recent versions of any packages used in the homework (any version released after 2020).
If you want, you can increase the number of input parameters, make subfunctions, etc., to realize more general functionalities, unless the “instructions” say not to.
This is a set to make you familiar with Python. I had to design this problem set because we mostly do not look at the references and/or do not try to use Google. You may refer to Think Python chapters, and if you cannot find the answer, you must use the Internet.
Problems#
Warn: Be aware not to miss any period (
.
) or quotation marks ('
or"
).
Write down the results of the following, i.e., write down the results when you
print()
each of these. [22 point]a1 = 3 + 4
a2 = 3 + 4.
b = 4 - 2
c = 9 * 8
d = 22 / 3
e = 22 // 3
f = 22 % 3
g1 = 2**2
g2 = 2.**2
g3 = 2**2.
h = "hello"
a1t = type(a1)
a2t = type(a2)
bt = type(b)
ct = type(c)
dt = type(d)
et = type(e)
ft = type(f)
g1t = type(g1)
g2t = type(g2)
g3t = type(g3)
ht = type(h)
Using
assert
, write a one-line code that [4 point]checks whether
22
is equal to3*e + f
.checks whether
g2
is equal tog3
Write a one-line code which will define
str_quotation
, such thatprint(str_quotation)
givesHello, World! It's me "Hi"
. (Hint: use the escape charater\
, e.g.,\"
.) [4 point]Write down the results of the following, i.e., write down the results when you
print()
each of these. [10 point]L_str = ["a", "b", "c"]
L_num = [1, 2, 3.]
tLs = type(L_str)
tLs0 = type(L_str[0])
tLn2 = type(L_num[-1])
d1 = {'name': ['Halpha', '[Mg II]', '[O III]'], 'intensities': [1, 0.1, 0.2]}
d1_k = list(d1.keys())
d1_e = list(d1.items())
d1_lines = d1['names']
d1_inHa = d1['intensities'][0]
Problem Set 2 [50 points]#
Please use Python 3.6+ (never Python 2).
For other packages: Although I didn’t run all the tests, there will likely be no problem if you use decently recent versions of any packages used in the homework (any version released after 2020).
Here, we will learn how to code in pythonic way. Open your terminal (or Jupyter Notebook) in an empty directory. Start solving the problems after running the code below:
from pathlib import Path
TOPPATH = Path('.')
Problems#
Answer the following questions with a one-line code. [2 points each]
Make a directory named
class_01
.Hint:
newdir = TOPPATH/'class_01'
andnewdir.mkdir()
Try to make a directory named
class_01
again. What error do you see?How can you avoid this error?
Hint: Try using
.mkdir(exist_ok=True)
.
Make a subdirectory
assignment_01
insideclass_01
.Hint:
hw01 = newdir/'assignment_01'
and do.mkdir()
.
Make the following directory using one line of code:
class_01_appendix/code_snippets
.Hint: Use
.mkdir(parents=True)
Make a list of all the files and directories in the current directory.
Hint:
flist = list(TOPPATH.glob('*'))
Find how many files and directories are in the current directory.
Hint:
len(flist)
Check whether
newdir
is an existing path.Hint: try
newdir.exists()
Check whether
newdir
is a file or directory.Hint: try
newdir.is_file()
andnewdir.is_dir()
Find the absolute path of
newdir
.Hint:
newdir.resolve()
Answer the following problems [2 points each]
Make an empty file named
test00.txt
.Hint: set
filepath = TOPPATH/'test00.txt'
, and usefilepath.touch()
.
Make a simple code that does
filepath.touch()
iffilepath
does not exist. Useif
.Hint: You can use
if filepath.exists(): ...
Make a list that contains the path objects for the 10 files:
test01.txt
,test02.txt
, …,test10.txt
.Hint: Initiate a list
filelist = []
.Hint: use for loop like this
for i in range(1, 11): filelist.append(TOPPATH / f"test{i:02d}.txt")
(You will learn what
f"{02:d}"
means later. If you want, google “python format string leading zeros”.)
Make 10 files with empty contents, named
test01.txt
,test02.txt
, …,test10.txt
.Hint:
for fpath in filelist:
and usefpath.touch()
.
Make
filelist2
which containstest08.txt
,test09.txt
, …,test12.txt
.Hint: Do as
filelist
, but change therange
part.
Iterate through the paths in
filelist2
, and make an empty file of that path if it does not exist.Hint: Use a for loop such as
for fpath in filelist2
.Hint: Use
if fpath.exists():
inside the for loop.
Make a list
filelist3
, which is the union set (list) offilelist
andfilelist2
.There are several ways to do this. One possibility is to use a for loop and
append
as you did infilelist
andfilelist2
.Another possiblility is to use
for fpath in filelist:
and useif fpath in filelist2:
etc.A simpler pythonic way is to use
list(set(filelist).union(filelist2))
.Tip: If you want the union of more than 2 lists, you should do
list(set().union(a, b, c, d))
.
Make a list
allfiles
of all the txt file paths in yourTOPPATH
.Hint:
allfiles = list(TOPPATH.glob('*.txt'))
Append a fake path
tttt00.txt
toallfiles
.Hint:
allfiles.append(TOPPATH/'tttt00.txt')
Sort the list
allfiles
and print it.Hint: use
.sort()
appropriately, and justprint(allfiles)
Delete
allfiles[0]
.Hint:
allfiles[0].unlink()
Delete all the files you created.
Hint: Use for loop. Then
if fpath.exists():
andfpath.unlink()
.
Advanced [6 points]
Python has a very useful try-except-finally
clause.
Do touch
on all the paths in filelist3
again.
Then use
for fpath in filelist3:
try:
fpath.unlink()
except FileNotFoundError:
continue
Does it run correctly? Are all the files removed?
Think about what each line means. (No answer is required)