Formatting

This commit is contained in:
Roland Thomas Jr 2023-08-23 12:02:52 -04:00
parent 32bdc6a287
commit c69e9801e9
Signed by: roland
GPG Key ID: 7C3C2B085A4C2872
9 changed files with 125 additions and 40 deletions

40
coupon_code.py Executable file
View File

@ -0,0 +1,40 @@
#!/usr/bin/env python3
def check_coupon(entered_code, correct_code, current_date, expiration_date):
if entered_code != correct_code:
return False
c_month, c_day, c_year = current_date.split()
e_month, e_day, e_year = expiration_date.split()
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
if int(c_year) < int(e_year):
return True
elif int(c_year) == int(e_year):
print(months.index(c_month), months.index(e_month))
if months.index(c_month) < months.index(e_month):
return True
elif months.index(c_month) == months.index(e_month):
return int(c_day) <= int(e_day)
else:
return False
else:
return False
if __name__ == "__main__":
print(check_coupon("123", "123", "September 5, 2014", "October 1, 2014"))
print(check_coupon("123a", "123", "September 5, 2014", "October 1, 2014"))

View File

@ -3,7 +3,8 @@ import smtplib
# Import the email modules we'll need # Import the email modules we'll need
from email.message import EmailMessage from email.message import EmailMessage
textfile = 'textfile'
textfile = "textfile"
# Open the plain text file whose name is in textfile for reading. # Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp: with open(textfile) as fp:
# Create a text/plain message # Create a text/plain message
@ -12,11 +13,11 @@ with open(textfile) as fp:
# me == the sender's email address # me == the sender's email address
# you == the recipient's email address # you == the recipient's email address
msg['Subject'] = f'The contents of {textfile}' msg["Subject"] = f"The contents of {textfile}"
msg['From'] = 'roland@rtj.dev' msg["From"] = "roland@rtj.dev"
msg['To'] = 'roland@rtj.dev' msg["To"] = "roland@rtj.dev"
# Send the message via our own SMTP server. # Send the message via our own SMTP server.
s = smtplib.SMTP('localhost') s = smtplib.SMTP("localhost")
s.send_message(msg) s.send_message(msg)
s.quit() s.quit()

12
freq.py
View File

@ -3,22 +3,24 @@
from collections import Counter from collections import Counter
from string import ascii_letters from string import ascii_letters
def top_3_words(text): def top_3_words(text):
letters = set([x for x in ascii_letters]) letters = set([x for x in ascii_letters])
letters.add('\'') letters.add("'")
letters.add(' ') letters.add(" ")
cleaned_text = ''.join([x.lower() for x in text if x in letters]) cleaned_text = "".join([x.lower() for x in text if x in letters])
text_counter = Counter([word for word in cleaned_text.split()]) text_counter = Counter([word for word in cleaned_text.split()])
del text_counter["\'"] del text_counter["'"]
keys_to_delete = [] keys_to_delete = []
for key in text_counter: for key in text_counter:
new = Counter(key) new = Counter(key)
if new['\''] > 1: if new["'"] > 1:
keys_to_delete.append(key) keys_to_delete.append(key)
for key in keys_to_delete: for key in keys_to_delete:
del text_counter[key] del text_counter[key]
return sorted(text_counter, key=text_counter.get, reverse=True)[:3] return sorted(text_counter, key=text_counter.get, reverse=True)[:3]
print(top_3_words("a a a b c c d d d d e e e e e")) print(top_3_words("a a a b c c d d d d e e e e e"))
print(top_3_words(" //wont won't won't ")) print(top_3_words(" //wont won't won't "))
print(top_3_words("e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e")) print(top_3_words("e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e"))

View File

@ -5,18 +5,19 @@ from io import StringIO
from unittest.mock import patch from unittest.mock import patch
import print_things # import the module containing the function with print statements import print_things # import the module containing the function with print statements
class TestPrintFunction(unittest.TestCase):
class TestPrintFunction(unittest.TestCase):
def test_print_example(self): def test_print_example(self):
# The expected output of the print statement # The expected output of the print statement
expected_output = "the world\n" expected_output = "the world\n"
# Using a context manager to temporarily replace sys.stdout with a StringIO object # Using a context manager to temporarily replace sys.stdout with a StringIO object
with patch('sys.stdout', new=StringIO()) as captured_output: with patch("sys.stdout", new=StringIO()) as captured_output:
print_things.print_the_world() # Call the function that has the print statement print_things.print_the_world() # Call the function that has the print statement
# Assert the captured output is equal to the expected output # Assert the captured output is equal to the expected output
self.assertEqual(captured_output.getvalue(), expected_output) self.assertEqual(captured_output.getvalue(), expected_output)
if __name__ == '__main__':
if __name__ == "__main__":
unittest.main() unittest.main()

View File

@ -1,3 +1,2 @@
def print_the_world(): def print_the_world():
print("the world") print("the world")

View File

@ -1,5 +1,13 @@
import sys import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QWidget, QGridLayout, QLabel from PyQt5.QtWidgets import (
QApplication,
QMainWindow,
QTabWidget,
QWidget,
QGridLayout,
QLabel,
)
class TabbedWindow(QMainWindow): class TabbedWindow(QMainWindow):
def __init__(self): def __init__(self):
@ -51,9 +59,9 @@ class TabbedWindow(QMainWindow):
# Set the layout for the second tab # Set the layout for the second tab
self.tab2.setLayout(layout2) self.tab2.setLayout(layout2)
if __name__ == '__main__':
if __name__ == "__main__":
app = QApplication(sys.argv) app = QApplication(sys.argv)
window = TabbedWindow() window = TabbedWindow()
window.show() window.show()
sys.exit(app.exec_()) sys.exit(app.exec_())

51
rand_char.py Normal file → Executable file
View File

@ -1,9 +1,48 @@
#!/usr/bin/env python3
"""
Generate and Print Random Unicode Characters
This module generates a string of random Unicode characters, specifically avoiding the
surrogate pair range (0xD800 to 0xDFFF). The generated string has a default length of
5000 characters.
Usage:
Run the script with an argument to specify the length of the string to be generated:
`python script_name.py 5000`
"""
import random import random
from argparse import ArgumentParser
characters = ''
try:
characters = ''.join([chr(random.choice([i for i in range(0x0, 0xD7FF + 1) if i < 0xD800 or i > 0xDFFF])) for _ in range(5000)])
except UnicodeEncodeError as e:
print(f"Error encoding character: {e}")
print(characters) def generate_string(length):
characters = ""
try:
characters = "".join(
[
chr(
random.choice(
[i for i in range(0x0, 0xD7FF + 1) if i < 0xD800 or i > 0xDFFF]
)
)
for _ in range(length)
]
)
except UnicodeEncodeError as e:
print(f"Error encoding character: {e}")
return(characters)
if __name__ == "__main__":
parser = ArgumentParser(
description="Generate a string of random Unicode characters."
)
parser.add_argument(
"length",
type=int,
default=5000,
help="Length of the string to be generated.",
)
args = parser.parse_args()
print(generate_string(args.length))

View File

@ -1,4 +1,3 @@
class Number: class Number:
def __init__(self, number): def __init__(self, number):
self._number = number self._number = number
@ -11,21 +10,21 @@ class Number:
def __setattr__(self, name, value): def __setattr__(self, name, value):
# print(name, type(name), value, type(value)) # print(name, type(name), value, type(value))
super().__setattr__('_number', 0) super().__setattr__("_number", 0)
try: try:
if isinstance(value, int): if isinstance(value, int):
super().__setattr__('_number', value) super().__setattr__("_number", value)
elif isinstance(value, str): elif isinstance(value, str):
super().__setattr__('_number', int(value)) super().__setattr__("_number", int(value))
except ValueError: except ValueError:
return return
def __getattribute__(self, name): def __getattribute__(self, name):
options = ['power', 'another_func', '__class__'] options = ["power", "another_func", "__class__"]
if name in options: if name in options:
return super().__getattribute__(name) return super().__getattribute__(name)
else: else:
return super().__getattribute__('_number') return super().__getattribute__("_number")
def __str__(self): def __str__(self):
return str(self._number) return str(self._number)

12
test.py
View File

@ -1,19 +1,15 @@
import unittest import unittest
class Yest(unittest.TestCase): class Yest(unittest.TestCase):
def test_int(self): def test_int(self):
n1 = 5 n1 = 5
self.assertIsInstance(n1, int, "n1 should be an int"), "asldfkjalsdfjsld" self.assertIsInstance(n1, int, "n1 should be an int")
int("124124"), "Another string here", "You can do that" int("124124")
a = 5 a = 5
self.assertIsInstance(a, int) self.assertIsInstance(a, int)
asdf = "I know you can do this.","","","",(55,55),[124,4124],1242142 assert isinstance(n1, int)
print(type(asdf), asdf)
assert isinstance(n1, int),235235252
words = ['asdf', '124']
words.sort( key=lambda an_elem: an_elem[1] )
print(words)
unittest.main() unittest.main()