Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion documenting-python-code/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ say_hello(name)
A dog says woof
```

Print the column headers of an Excel spreadsheet:
Print the column headers of a CSV or Excel spreadsheet:

```sh
$ python spreadsheet_columns.py people.xlsx
Expand Down
2 changes: 1 addition & 1 deletion documenting-python-code/animal.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def __init__(self, name, sound, num_legs=4):
sound : str
The sound the animal makes
num_legs : int, optional
The number of legs the animal (default is 4)
The number of legs the animal has (default is 4)
"""

self.name = name
Expand Down
20 changes: 16 additions & 4 deletions documenting-python-code/docstring_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ def get_spreadsheet_cols_google(file_loc, print_cols=False):
list: a list of strings representing the header columns
"""

file_data = pd.read_excel(file_loc)
if file_loc.lower().endswith(".csv"):
file_data = pd.read_csv(file_loc)
else:
file_data = pd.read_excel(file_loc)
col_headers = list(file_data.columns.values)

if print_cols:
Expand All @@ -40,7 +43,10 @@ def get_spreadsheet_cols_rest(file_loc, print_cols=False):
:rtype: list
"""

file_data = pd.read_excel(file_loc)
if file_loc.lower().endswith(".csv"):
file_data = pd.read_csv(file_loc)
else:
file_data = pd.read_excel(file_loc)
col_headers = list(file_data.columns.values)

if print_cols:
Expand All @@ -65,7 +71,10 @@ def get_spreadsheet_cols_numpy(file_loc, print_cols=False):
a list of strings representing the header columns
"""

file_data = pd.read_excel(file_loc)
if file_loc.lower().endswith(".csv"):
file_data = pd.read_csv(file_loc)
else:
file_data = pd.read_excel(file_loc)
col_headers = list(file_data.columns.values)

if print_cols:
Expand All @@ -86,7 +95,10 @@ def get_spreadsheet_cols_epytext(file_loc, print_cols=False):
@returns: a list of strings representing the header columns
"""

file_data = pd.read_excel(file_loc)
if file_loc.lower().endswith(".csv"):
file_data = pd.read_csv(file_loc)
else:
file_data = pd.read_excel(file_loc)
col_headers = list(file_data.columns.values)

if print_cols:
Expand Down
15 changes: 11 additions & 4 deletions documenting-python-code/spreadsheet_columns.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
(.xls, .xlsx) files.

This script requires that `pandas` be installed within the Python
environment you are running this script in.
environment you are running this script in, along with `openpyxl` for
.xlsx files and `xlrd` for .xls files.

This file can also be imported as a module and contains the following
functions:
Expand Down Expand Up @@ -36,10 +37,13 @@ def get_spreadsheet_cols(file_loc, print_cols=False):
Returns
-------
list
a list of strings used that are the header columns
a list of strings that are the header columns
"""

file_data = pd.read_excel(file_loc)
if file_loc.lower().endswith(".csv"):
file_data = pd.read_csv(file_loc)
else:
file_data = pd.read_excel(file_loc)
col_headers = list(file_data.columns.values)

if print_cols:
Expand All @@ -49,7 +53,10 @@ def get_spreadsheet_cols(file_loc, print_cols=False):


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"input_file",
type=str,
Expand Down
57 changes: 33 additions & 24 deletions operator-function-overloading/custom_complex.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from math import hypot, atan, sin, cos
from math import hypot, atan2, sin, cos


class CustomComplex:
"""
A class to represent a complex number, a+bj.
Attributes:
real - int, representing the real part
imag - int, representing the imaginary part
real - int or float, representing the real part
imag - int or float, representing the imaginary part

Implements the following:

Expand Down Expand Up @@ -41,17 +41,17 @@ def conjugate(self):
Return:
CustomComplex instance
"""
return CustomComplex(self.real, -self.imag)
return self.__class__(self.real, -self.imag)

def argz(self):
"""
Returns the argument of a complex number
The argument is given by:
atan(imag_part/real_part)
atan2(imag_part, real_part)
Return:
float
"""
return atan(self.imag / self.real)
return atan2(self.imag, self.real)

def __abs__(self):
"""
Expand All @@ -69,7 +69,7 @@ def __repr__(self):
Return:
str
"""
return f"CustomComplex({self.real}, {self.imag})"
return f"{self.__class__.__name__}({self.real}, {self.imag})"

def __str__(self):
"""
Expand All @@ -87,15 +87,16 @@ def __add__(self, other):
Return:
CustomComplex instance
"""
if isinstance(other, float) or isinstance(other, int):
if isinstance(other, (int, float)):
real_part = self.real + other
imag_part = self.imag

if isinstance(other, CustomComplex):
elif isinstance(other, CustomComplex):
real_part = self.real + other.real
imag_part = self.imag + other.imag
else:
return NotImplemented

return CustomComplex(real_part, imag_part)
return self.__class__(real_part, imag_part)

def __sub__(self, other):
"""
Expand All @@ -104,15 +105,16 @@ def __sub__(self, other):
Return:
CustomComplex instance
"""
if isinstance(other, float) or isinstance(other, int):
if isinstance(other, (int, float)):
real_part = self.real - other
imag_part = self.imag

if isinstance(other, CustomComplex):
elif isinstance(other, CustomComplex):
real_part = self.real - other.real
imag_part = self.imag - other.imag
else:
return NotImplemented

return CustomComplex(real_part, imag_part)
return self.__class__(real_part, imag_part)

def __mul__(self, other):
"""
Expand All @@ -121,26 +123,27 @@ def __mul__(self, other):
Return:
CustomComplex instance
"""
if isinstance(other, int) or isinstance(other, float):
if isinstance(other, (int, float)):
real_part = self.real * other
imag_part = self.imag * other

if isinstance(other, CustomComplex):
elif isinstance(other, CustomComplex):
real_part = (self.real * other.real) - (self.imag * other.imag)
imag_part = (self.real * other.imag) + (self.imag * other.real)
else:
return NotImplemented

return CustomComplex(real_part, imag_part)
return self.__class__(real_part, imag_part)

def __radd__(self, other):
"""
Same as __add__; allows 1 + CustomComplex('x+yj')
Same as __add__; allows 1 + CustomComplex(x, y)
x + y == y + x
"""
return self.__add__(other)

def __rmul__(self, other):
"""
Same as __mul__; allows 2 * CustomComplex('x+yj')
Same as __mul__; allows 2 * CustomComplex(x, y)
x * y == y * x
"""
return self.__mul__(other)
Expand All @@ -156,11 +159,13 @@ def __rsub__(self, other):
Return:
CustomComplex instance
"""
if isinstance(other, float) or isinstance(other, int):
if isinstance(other, (int, float)):
real_part = other - self.real
imag_part = -self.imag
else:
return NotImplemented

return CustomComplex(real_part, imag_part)
return self.__class__(real_part, imag_part)

def __eq__(self, other):
"""
Expand All @@ -171,6 +176,8 @@ def __eq__(self, other):
Return:
bool
"""
if not isinstance(other, (int, float, CustomComplex)):
return NotImplemented
# Note: comparing floats directly is not a good idea in general
# due to floating-point precision
return (self.real == other.real) and (self.imag == other.imag)
Expand All @@ -184,6 +191,8 @@ def __ne__(self, other):
Return:
bool
"""
if not isinstance(other, (int, float, CustomComplex)):
return NotImplemented
return (self.real != other.real) or (self.imag != other.imag)

def __pow__(self, other):
Expand All @@ -204,4 +213,4 @@ def __pow__(self, other):
real_part = round(r_raised * cos(argz_multiplied))
imag_part = round(r_raised * sin(argz_multiplied))

return CustomComplex(real_part, imag_part)
return self.__class__(real_part, imag_part)
2 changes: 1 addition & 1 deletion python-data-classes/position_make_dataclass.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from dataclasses import make_dataclass

Position = make_dataclass("Position", ["name", "lat", "lon"])
Position = make_dataclass("Position", ["name", "lon", "lat"])
2 changes: 1 addition & 1 deletion python-sql-libraries/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,4 @@ Query executed successfully
Query executed successfully
```

The script stops with a `DuplicateDatabase` error if `sm_app` already exists, so drop it before running the script again with `sudo -u postgres psql -c "DROP DATABASE sm_app"`.
If `sm_app` already exists, the script reports the error and carries on, so the records are inserted a second time. To start over, drop the database with `sudo -u postgres psql -c "DROP DATABASE sm_app"`.
2 changes: 1 addition & 1 deletion python-sql-libraries/mysql_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def execute_read_query(connection, query):
UPDATE
posts
SET
description = "The weather has become pleasant now"
description = 'The weather has become pleasant now'
WHERE
id = 2
"""
Expand Down
8 changes: 4 additions & 4 deletions python-sql-libraries/postgresql_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def create_database(connection, query):
try:
cursor.execute(query)
print("Query executed successfully")
except OperationalError as e:
except psycopg2.Error as e:
print(f"The error '{e}' occurred")


Expand All @@ -40,7 +40,7 @@ def execute_query(connection, query):
try:
cursor.execute(query)
print("Query executed successfully")
except OperationalError as e:
except psycopg2.Error as e:
print(f"The error '{e}' occurred")


Expand All @@ -51,7 +51,7 @@ def execute_read_query(connection, query):
cursor.execute(query)
result = cursor.fetchall()
return result
except OperationalError as e:
except psycopg2.Error as e:
print(f"The error '{e}' occurred")


Expand Down Expand Up @@ -180,7 +180,7 @@ def execute_read_query(connection, query):
for user in users:
print(user)

# Updating table records (PostgreSQL needs single quotes for strings)
# Updating table records
update_post_description = """
UPDATE
posts
Expand Down
18 changes: 9 additions & 9 deletions python-sql-libraries/sqlite_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def execute_read_query(connection, query):
text TEXT NOT NULL,
user_id INTEGER NOT NULL,
post_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (post_id) REFERENCES posts (id)
);
"""
Expand All @@ -79,7 +79,7 @@ def execute_read_query(connection, query):
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
post_id integer NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (post_id) REFERENCES posts (id)
);
"""
Expand All @@ -105,12 +105,12 @@ def execute_read_query(connection, query):
INSERT INTO
posts (title, description, user_id)
VALUES
("Happy", "I am feeling very happy today", 1),
("Hot Weather", "The weather is very hot today", 2),
("Help", "I need some help with my work", 2),
("Great News", "I am getting married", 1),
("Interesting Game", "It was a fantastic game of tennis", 5),
("Party", "Anyone up for a late-night party today?", 3);
('Happy', 'I am feeling very happy today', 1),
('Hot Weather', 'The weather is very hot today', 2),
('Help', 'I need some help with my work', 2),
('Great News', 'I am getting married', 1),
('Interesting Game', 'It was a fantastic game of tennis', 5),
('Party', 'Anyone up for a late-night party today?', 3);
"""

execute_query(connection, create_posts)
Expand Down Expand Up @@ -228,7 +228,7 @@ def execute_read_query(connection, query):
UPDATE
posts
SET
description = "The weather has become pleasant now"
description = 'The weather has become pleasant now'
WHERE
id = 2
"""
Expand Down
Loading