feat(school): dump a-level stuff

This commit is contained in:
newt 2024-10-09 18:02:47 +01:00
parent 1ce7820694
commit 630aea3baa
29 changed files with 486 additions and 0 deletions

View file

@ -0,0 +1,40 @@
from random import randint
class Dice:
def __init__(self, sides: int = 6):
self.__sides = sides
def roll(self):
return randint(1, self.__sides)
DICE_COUNT = 2
DICE_SIDES = 6
ROLL_COUNT = 1000
FORMAT_STRING = ' {: ^10} | {: ^10} | {: ^10}'
dice = Dice(DICE_SIDES)
frequencies = {}
for _ in range(ROLL_COUNT):
totalRoll = 0
for _ in range(DICE_COUNT):
totalRoll += dice.roll()
key = f'{totalRoll}'
if key in frequencies:
frequencies[key] += 1
else:
frequencies[key] = 1
header = FORMAT_STRING.format('Dice Value', 'Frequency', 'Percentage')
print(f'Rolling {DICE_COUNT} dice ({DICE_SIDES} sided) {ROLL_COUNT} times...\n')
print(header)
print('-' * (len(header) + 3))
frequencies = sorted(frequencies.items(), key=lambda k:int(k[0]))
for value, frequency in frequencies:
percentage = (frequency * 100) / ROLL_COUNT
print(FORMAT_STRING.format(value, frequency, f'{percentage:.2f}%'))

View file

@ -0,0 +1,65 @@
import re
def twosComplementToDenary(bitPattern):
value = 0
for i in range(len(bitPattern) - 1, -1, -1):
placeValue = 2 ** (len(bitPattern) - i - 1)
if i == 0: placeValue *= -1
value += int(bitPattern[i]) * placeValue
return value
def twosComplementNormalisedToDenary(bitPattern):
wholePart, fractionalPart = bitPattern[0], bitPattern[-len(bitPattern)+1:]
value = -1 if int(wholePart) == 1 else 0
for i in range(len(fractionalPart), 0, -1):
placeValue = 2 ** -i
value += int(fractionalPart[i - 1]) * placeValue
return value
while True:
try:
binary = input('Please enter the bit pattern you would like to decode: ')
if re.match('[^01]+', binary):
raise ValueError
break
except ValueError:
print('Please ensure that you input a valid binary sequence!')
while True:
try:
while True:
try:
mantissaBits = int(input('Please enter the amount of bits that the mantissa uses: '))
break
except ValueError:
print('Please ensure that you input a valid integer!')
while True:
try:
exponentBits = int(input('Please enter the amount of bits that the exponent uses: '))
break
except ValueError:
print('Please ensure that you input a valid integer!')
if exponentBits + mantissaBits != len(binary):
raise ValueError
break
except ValueError:
print(f'The amount of bits you inputed for the mantissa and exponent do not add up to the length of your sequence - please make sure they span the entire range of the sequence! For reference, your sequence was {binary}')
binary = str(binary)
mantissa = binary[:mantissaBits]
exponent = binary[-exponentBits:]
denaryExponent = twosComplementToDenary(exponent)
denaryMantissa = twosComplementNormalisedToDenary(mantissa)
print(denaryMantissa * (2 ** denaryExponent))

View file

@ -0,0 +1 @@
l,s,m,r,i,z,c,n=len,sum,map,range,int,-1,lambda b:s(m(lambda x:-x[1] if x[0]==0 else x[1],[(k,i(b[k])*2**(l(b)-k-1)) for k in r(l(b)-1,-1,-1)])),lambda b:(f:=b[-l(b)+1:],(s([i(f[k-1])/2**k for k in r(l(f),0,z)]))+(z if i(b[0])==1 else 0))[1]

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View file

@ -0,0 +1,17 @@
from typing import Dict
import re
def letterFrequency(text: str) -> Dict[str, int]:
output = {}
text = re.sub('[^a-zA-Z]+', '', text)
for letter in text:
if letter in output:
output[letter] += 1
else:
output[letter] = 1
return output
frequency = letterFrequency('I wish I wish with all my heart to fly with dragons in a land apart')
print(frequency)

View file

@ -0,0 +1,8 @@
class Item:
# Constructor
def __init__(self, name, description, price, quantity):
self.name = name
self.description = description
self.price = price
self.initialQuantity = quantity
self.quantity = quantity

View file

@ -0,0 +1,82 @@
from Item import Item
class ShoppingBasket:
# Constructor
def __init__(self):
self.items = {} #A dictionary of all the items in the shopping basket: {item:quantity}
self.checkout = False
# A method to add an item to the shopping basket
def addItem(self,item,quantity=1):
if item.quantity < quantity:
print(f'Invalid operation - there is not enough {item.name} in stock!')
elif quantity > 0:
item.quantity -= quantity
#Check if the item is already in the shopping basket
if item in self.items:
self.items[item] += quantity
else:
self.items[item] = quantity
else:
print("Invalid operation - Quantity must be a positive number!")
# A method to remove an item from the shopping basket (or reduce it's quantity)
def removeItem(self,item,quantity=0):
if self.items[item] < quantity:
print(f'Invalid operation - there is not enough {item.name} in the basket!')
elif quantity<=0:
#Remove the item
self.items.pop(item, None)
else:
item.quantity += quantity
if item in self.items:
if quantity<self.items[item]:
#Reduce the required quantity for this item
self.items[item] -= quantity
else:
#Remove the item
self.items.pop(item, None)
# A method to update the quantity of an item from the shopping basket
def updateItem(self,item,quantity):
if quantity > 0:
quantDifference = self.items[item] if item in self.items else 0
quantDifference -= quantity
item.quantity += quantDifference
self.items[item] = quantity
else:
self.removeItem(item)
# A method to view/list the content of the basket.
def view(self):
totalCost = 0
print("---------------------")
for item in self.items:
quantity = self.items[item]
cost = quantity * item.price
print(" + " + item.name + " - " + str(quantity) + " x £" + '{0:.2f}'.format(item.price) + " = £" + '{0:.2f}'.format(cost))
totalCost += cost
print("---------------------")
print(" = £" + '{0:.2f}'.format(totalCost))
print("---------------------")
# A method to calculate the total cost of the basket.
def getTotalCost(self):
totalCost = 0
for item in self.items:
quantity = self.items[item]
cost = quantity * item.price
totalCost += cost
return totalCost
# A method to empty the content of the basket
def reset(self):
for item in self.items:
item.quantity = item.initialQuantity
self.items = {}
# A method to return whether the basket is empty or not:
def isEmpty(self):
return len(self.items)==0

View file

@ -0,0 +1,30 @@
#Shopping Basket Class - www.101computing.net/shopping-basket-class/
from Item import Item
from ShoppingBasket import ShoppingBasket
tomatoSoup = Item("Tomato Soup","200mL can", 0.70, 3)
spaghetti = Item("Spaghetti","500g pack", 1.10, 4)
blackOlives = Item("Black Olives Jar","200g Jar", 2.10, 100)
mozarella = Item("Mozarella","100g", 1.50, 2)
gratedCheese = Item("Grated Cheese","100g",2.20, 1)
myBasket = ShoppingBasket()
myBasket.addItem(tomatoSoup, 4)
myBasket.addItem(blackOlives, 1)
myBasket.addItem(mozarella, 2)
myBasket.addItem(tomatoSoup, 6)
myBasket.view()
myBasket.removeItem(mozarella, 3)
print(mozarella.quantity)
myBasket.reset()
myBasket.view()
print(mozarella.quantity)
myBasket.updateItem(tomatoSoup, 3)
myBasket.view()
myBasket.updateItem(tomatoSoup, 0)
myBasket.view()

View file

@ -0,0 +1,121 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--Created by yFiles for HTML 2.5.0.2-->
<graphml xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml.html/2.0/ygraphml.xsd " xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:demostyle2="http://www.yworks.com/yFilesHTML/demos/FlatDemoStyle/2.0" xmlns:demostyle="http://www.yworks.com/yFilesHTML/demos/FlatDemoStyle/1.0" xmlns:icon-style="http://www.yworks.com/yed-live/icon-style/1.0" xmlns:bpmn="http://www.yworks.com/xml/yfiles-bpmn/2.0" xmlns:demotablestyle="http://www.yworks.com/yFilesHTML/demos/FlatDemoTableStyle/1.0" xmlns:uml="http://www.yworks.com/yFilesHTML/demos/UMLDemoStyle/1.0" xmlns:GraphvizNodeStyle="http://www.yworks.com/yFilesHTML/graphviz-node-style/1.0" xmlns:VuejsNodeStyle="http://www.yworks.com/demos/yfiles-vuejs-node-style/1.0" xmlns:explorer-style="http://www.yworks.com/data-explorer/1.0" xmlns:y="http://www.yworks.com/xml/yfiles-common/3.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/3.0" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:yjs="http://www.yworks.com/xml/yfiles-for-html/2.0/xaml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<key id="d0" for="node" attr.type="int" attr.name="zOrder" y:attr.uri="http://www.yworks.com/xml/yfiles-z-order/1.0/zOrder"/>
<key id="d1" for="node" attr.type="boolean" attr.name="Expanded" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/folding/Expanded">
<default>true</default>
</key>
<key id="d2" for="node" attr.type="string" attr.name="url"/>
<key id="d3" for="node" attr.type="string" attr.name="description"/>
<key id="d4" for="node" attr.name="NodeLabels" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/NodeLabels"/>
<key id="d5" for="node" attr.name="NodeGeometry" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/NodeGeometry"/>
<key id="d6" for="all" attr.name="UserTags" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/UserTags"/>
<key id="d7" for="node" attr.name="NodeStyle" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/NodeStyle"/>
<key id="d8" for="node" attr.name="NodeViewState" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/folding/1.1/NodeViewState"/>
<key id="d9" for="edge" attr.type="string" attr.name="url"/>
<key id="d10" for="edge" attr.type="string" attr.name="description"/>
<key id="d11" for="edge" attr.name="EdgeLabels" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/EdgeLabels"/>
<key id="d12" for="edge" attr.name="EdgeGeometry" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/EdgeGeometry"/>
<key id="d13" for="edge" attr.name="EdgeStyle" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/EdgeStyle"/>
<key id="d14" for="edge" attr.name="EdgeViewState" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/folding/1.1/EdgeViewState"/>
<key id="d15" for="port" attr.name="PortLabels" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/PortLabels"/>
<key id="d16" for="port" attr.name="PortLocationParameter" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/PortLocationParameter">
<default>
<x:Static Member="y:FreeNodePortLocationModel.NodeCenterAnchored"/>
</default>
</key>
<key id="d17" for="port" attr.name="PortStyle" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/PortStyle">
<default>
<x:Static Member="y:VoidPortStyle.Instance"/>
</default>
</key>
<key id="d18" for="port" attr.name="PortViewState" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/folding/1.1/PortViewState"/>
<key id="d19" attr.name="SharedData" y:attr.uri="http://www.yworks.com/xml/yfiles-common/2.0/SharedData"/>
<data key="d19">
<y:SharedData>
<yjs:SolidColorFill x:Key="1" color="#FF607D8B"/>
<yjs:SolidColorFill x:Key="2" color="#FFA3F1BB"/>
</y:SharedData>
</data>
<graph id="G" edgedefault="directed">
<data key="d6">
<y:Json>{"version":"2.0.0","theme":{"name":"light","version":"1.0.0"},"layout":"layout-uml","config":{"p_useDrawingAsSketch":false,"p_selectedElementsIncrementally":false,"p_nodeToNodeDistance":30,"p_automaticEdgeGroupingEnabled":false,"p_considerNodeLabels":true,"p_edgeLabeling":0,"p_orientation":0}}</y:Json>
</data>
<node id="n0">
<data key="d0">1</data>
<data key="d5">
<y:RectD X="35.00025508160647" Y="0" Width="208.50425174154896" Height="140"/>
</data>
<data key="d7">
<uml:UMLNodeStyle fill="{y:GraphMLReference 1}" highlightFill="{y:GraphMLReference 2}">
<uml:UMLNodeStyle.model>
<uml:UMLClassModel stereotype="" constraint="" className="BankAccount" attributesOpen="true" operationsOpen="true">
<uml:UMLClassModel.attributes>
<x:Array Type="sys:Object">
<sys:String><![CDATA[- balance: float]]></sys:String>
</x:Array>
</uml:UMLClassModel.attributes>
<uml:UMLClassModel.operations>
<x:Array Type="sys:Object">
<sys:String><![CDATA[+ getBalance(): float]]></sys:String>
<sys:String><![CDATA[+ setBalance(newBalance): void]]></sys:String>
</x:Array>
</uml:UMLClassModel.operations>
</uml:UMLClassModel>
</uml:UMLNodeStyle.model>
</uml:UMLNodeStyle>
</data>
<port name="p0">
<data key="d16">
<y:FreeNodePortLocationModelParameter Ratio="0.5,1"/>
</data>
</port>
</node>
<node id="n1">
<data key="d0">2</data>
<data key="d5">
<y:RectD X="49.548422274215454" Y="165" Width="179.40791735633098" Height="204"/>
</data>
<data key="d7">
<uml:UMLNodeStyle fill="{y:GraphMLReference 1}" highlightFill="{y:GraphMLReference 2}">
<uml:UMLNodeStyle.model>
<uml:UMLClassModel stereotype="" constraint="" className="Controller" attributesOpen="true" operationsOpen="true">
<uml:UMLClassModel.attributes>
<x:Array Type="sys:Object">
<sys:String><![CDATA[- account: BankAccount]]></sys:String>
<sys:String><![CDATA[+ OVERDRAWN_FEE: int]]></sys:String>
</x:Array>
</uml:UMLClassModel.attributes>
<uml:UMLClassModel.operations>
<x:Array Type="sys:Object">
<sys:String><![CDATA[- overdrawnFee(): bool]]></sys:String>
<sys:String><![CDATA[+ fetchBalance(): float]]></sys:String>
<sys:String><![CDATA[+ formatBalance(): str]]></sys:String>
<sys:String><![CDATA[+ payIn(amount): void]]></sys:String>
<sys:String><![CDATA[+ withdraw(amount): bool]]></sys:String>
</x:Array>
</uml:UMLClassModel.operations>
</uml:UMLClassModel>
</uml:UMLNodeStyle.model>
</uml:UMLNodeStyle>
</data>
<port name="p0">
<data key="d16">
<y:FreeNodePortLocationModelParameter Ratio="0.5,0"/>
</data>
</port>
</node>
<edge id="e0" source="n1" target="n0" sourceport="p0" targetport="p0">
<data key="d13">
<yjs:PolylineEdgeStyle>
<yjs:PolylineEdgeStyle.stroke>
<yjs:Stroke fill="#FF000000" dashStyle="Dash"/>
</yjs:PolylineEdgeStyle.stroke>
<yjs:PolylineEdgeStyle.targetArrow>
<yjs:Arrow stroke="#FF000000" fill="#FF000000"/>
</yjs:PolylineEdgeStyle.targetArrow>
</yjs:PolylineEdgeStyle>
</data>
</edge>
</graph>
</graphml>

Binary file not shown.

After

Width:  |  Height:  |  Size: 826 KiB

View file

@ -0,0 +1,107 @@
CONFIRMATION_VALIDATOR = lambda x: x.lower() not in ['yes', 'y', 'no', 'n']
class BankAccount:
def __init__(self):
self.__balance = 0
def getBalance(self):
return self.__balance
def setBalance(self, newBalance):
self.__balance = newBalance
class Controller:
OVERDRAWN_FEE = 5
def __init__(self, account):
self.__account = account
def __overdrawnFee(self):
balance = self.fetchBalance()
if balance < 0:
self.__account.setBalance(balance - Controller.OVERDRAWN_FEE)
return balance < 0
def fetchBalance(self):
return self.__account.getBalance()
def formatBalance(self):
balance = self.fetchBalance()
sign = '' if balance >= 0 else '-'
return f'{sign}£{abs(balance):.2f}'
def payIn(self, amount):
self.__account.setBalance(self.fetchBalance() + amount)
def withdraw(self, amount):
fee = self.__overdrawnFee()
self.__account.setBalance(self.fetchBalance() - amount)
return fee
account = BankAccount()
controller = Controller(account)
def fetchValue(caster, typeName, prompt, validator = None, validatorFailMessage = None):
while True:
try:
value = caster(input(prompt))
if validator:
if validator(value):
raise ValueError('validator')
return value
except ValueError as e:
if str(e) == 'validator' and validatorFailMessage:
print(validatorFailMessage)
else:
print(f'Please make sure you input a valid {typeName}.')
def displayBalance():
print(f'You currently have a balance of {controller.formatBalance()}!')
def menu():
print("""Welcome to the bank! What would you like to do?
1) View your current balance
2) Pay in money
3) Withdraw money
4) Exit""")
choice = fetchValue(int, 'integer', 'Please make your selection: ', lambda x: (x > 4 or x <= 0))
if choice == 1:
displayBalance()
elif choice == 2:
value = fetchValue(float, 'float', 'Please enter the amount of money you would like to pay in: ')
controller.payIn(value)
displayBalance()
elif choice == 3:
value = fetchValue(float, 'float', 'Please enter the amount of money you would like to withdraw: ')
chargedFee = controller.withdraw(value)
if chargedFee:
print(f'You are currently overdrawn! If you go through with this transaction, you will have to pay a fee of £{Controller.OVERDRAWN_FEE:.2f}, and your balance will become {controller.formatBalance()}.')
confirm = fetchValue(str, 'input', 'Would you like to proceed? (y/n)', CONFIRMATION_VALIDATOR)
if confirm in ['n', 'no']:
controller.payIn(value + Controller.OVERDRAWN_FEE)
print('Your transaction has been cancelled!')
else:
displayBalance()
else:
displayBalance()
elif choice == 4:
exit()
if __name__ == '__main__':
while True:
menu()
again = fetchValue(str, 'input', 'Would you like to go again? (y/n)', CONFIRMATION_VALIDATOR)
if again in ['n', 'no']:
break

View file

@ -0,0 +1,15 @@
class Pest:
def __init__(self, legs, noise):
self.__legs = legs
self.__noise = noise
def getLegs(self):
return self.__legs
def getNoise(self):
return self.__noise
dog = Pest(4, 'woof')
roach = Pest(6, 'click click click')
print(roach.getNoise())