Skip to content

Instantly share code, notes, and snippets.

@bennett39
bennett39 / tree.py
Created March 6, 2024 18:26
Playing around with binary trees
from typing import Optional
from collections import deque
class Node:
def __init__(self, value: int):
self.value = value
self.left = None
self.right = None
import csv
with open('cancel.csv') as f:
reader = csv.DictReader(f)
words = {}
for row in reader:
reason = row['Reason']
if reason == 'System cancelled - non payment':
continue
@bennett39
bennett39 / dice_distribution.py
Last active April 24, 2023 14:34
I was curious about the distribution of results for dice. So, I wrote a few lines of Python.
def dice_distribution(num_sides: int) -> dict[int, float]:
"""
Get the distribution of possible results of two thrown dice
"""
distribution = {}
for x in dice_generator(num_sides):
for y in dice_generator(num_sides):
value = x + y
distribution.setdefault(value, 0)
distribution[value] += 1
@bennett39
bennett39 / fizzbuzz.py
Created March 22, 2023 18:05
An implementation of fizzbuzz
def fizzbuzz(stop: int):
"""On multiples of 3, print 'fizz'
On multiples of 5, print 'buzz'
On multiples of both, print 'fizzbuzz'
For all other numbers, print the number
"""
result = []
for x in range(1, stop+1):
if x % 15 == 0:
result.append('fizzbuzz')
from celery_tutorial.celery import app
from .models import Calculation
def fib(n):
"""Calculate the Nth fibonacci number"""
if n < 0:
raise ValueError('Negative numbers are not supported')
elif n == 0:
return 0
from django.shortcuts import render, redirect
from django.views import View
from .models import Calculation
from .tasks import fibonacci_task
class FibonacciView(View):
def get(self, request):
"""Show a form to start a calculation"""
from django.db import models
class Calculation(models.Model):
"""Track a calculation and its results"""
EQUATION_FIBONACCI = 'FIB'
EQUATIONS = ((EQUATION_FIBONACCI, 'Fibonacci'),)
STATUS_PENDING = 'PENDING'
STATUS_ERROR = 'ERROR'
def fib(n):
"""Calculate the Nth fibonacci number.
Intentionally don't use dynamic programming. Goal is to simulate a long-running task.
"""
if n < 0:
raise ValueError('Negative numbers are not supported')
elif n == 0:
return 0
elif n <= 2:
# Map, filter, and reduce are all operations that we can apply against a list, tuple, or sequence
# These types of operations follow the "functional" approach to programming
# I won't go into too much detail here, but a Google search of "functional vs OOP" will give you a synopsis
# Here are some examples. We can talk more about them when we chat.
# Let's start with a simple list...
>>> my_list = [0, 1, 2, 3, 4, 5]
# Using filter, we can filter values out of the list, returning a new list!
# (If you haven't seen lambdas yet, don't worry! Basically, this filter uses modulo 2 to check if the number is even/odd)
@bennett39
bennett39 / test_my_command.py
Created September 27, 2021 10:54
Testing Django Admin Commands
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
class MyCommandTest(TestCase):
def test_my_command(self):
out = StringIO() # <-- Use StringIO to capture the output of the command from stdout
args = [] # <-- Any command line arguments go here
kwargs = {'stdout': out} # <-- Any named command line options (e.g. --my-option) go here