refactor: the big cleanse!
-
1
.gitignore
vendored
|
@ -4,3 +4,4 @@ private
|
|||
__pycache__
|
||||
*.out
|
||||
node_modules
|
||||
*.csv
|
||||
|
|
Before Width: | Height: | Size: 572 KiB After Width: | Height: | Size: 572 KiB |
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 5.3 KiB |
|
@ -1,5 +1,5 @@
|
|||
<div align="center">
|
||||
<img height="256" src="../../assets/dailyprogrammer.gif" alt="">
|
||||
<img height="256" src="../../assets/daily-programmer.gif" alt="">
|
||||
<h1>r/dailyprogrammer</h1>
|
||||
</div>
|
||||
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
{
|
||||
"name": "project-euler",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "gulp build",
|
||||
"start": "node scripts/run",
|
||||
|
|
|
@ -32,7 +32,7 @@ The source code can be found in the [src](src) directory. My thoughts about some
|
|||
- [x] [18 - Maximum path sum I](src/18%20-%20Maximum%20path%20sum%20I.ts)
|
||||
- [x] [19 - Counting Sundays](src/19%20-%20Counting%20Sundays.ts)
|
||||
- [x] [20 - Factorial digit sum](src/20%20-%20Factorial%20digit%20sum.ts)
|
||||
- [x] [21 - Amicable numbers](src/21%20-%20Amicable%20numbers.ts)
|
||||
- [ ] 21 - Amicable numbers
|
||||
- [ ] 22 - Names scores
|
||||
- [ ] 23 - Non-abundant sums
|
||||
- [ ] 24 - Lexicographic permutations
|
||||
|
|
|
@ -4,6 +4,7 @@ const path = require('path');
|
|||
const { root, src, thoughts: thoughtsDir } = require('../constants');
|
||||
const axios = require('axios');
|
||||
const cheerio = require('cheerio');
|
||||
const chalk = require('chalk');
|
||||
|
||||
process.argv.shift();
|
||||
process.argv.shift();
|
||||
|
@ -25,17 +26,13 @@ if (isNaN(process.argv[0]))
|
|||
validate: input => {
|
||||
input = parseInt(input);
|
||||
|
||||
if (input > 100) return 'Please make sure you choose a number between 1 and 100!';
|
||||
else {
|
||||
let alreadyGenerated = false;
|
||||
fs.readdirSync(src).forEach(file => {
|
||||
if (file.startsWith(input)) alreadyGenerated = true;
|
||||
});
|
||||
let alreadyGenerated = false;
|
||||
fs.readdirSync(src).forEach(file => {
|
||||
if (file.startsWith(input)) alreadyGenerated = true;
|
||||
});
|
||||
|
||||
if (alreadyGenerated)
|
||||
return 'Please choose a problem you have not already completed!';
|
||||
else return true;
|
||||
}
|
||||
if (alreadyGenerated) return 'Please choose a problem you have not already completed!';
|
||||
else return true;
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -54,41 +51,69 @@ inquirer
|
|||
const fileName = `${problemNumber} - ${problems[problemNumber - 1]}`;
|
||||
|
||||
// Fetch the problem data off of projecteuler.net
|
||||
axios.get(`https://projecteuler.net/problem=${problemNumber}`).then(({ data }) => {
|
||||
const $ = cheerio.load(data);
|
||||
const problemContent = $('.problem_content')
|
||||
.text()
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(r => `// ${r}`)
|
||||
.join('\n');
|
||||
axios
|
||||
.get(`https://projecteuler.net/problem=${problemNumber}`)
|
||||
.then(({ data }) => {
|
||||
const $ = cheerio.load(data);
|
||||
const problemContent = $('.problem_content')
|
||||
.text()
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(r => `// ${r}`)
|
||||
.join('\n');
|
||||
|
||||
// Generate the source file
|
||||
fs.writeFileSync(
|
||||
path.join(src, `${fileName}.ts`),
|
||||
`${problemContent}
|
||||
// Generate the source file
|
||||
fs.writeFileSync(
|
||||
path.join(src, `${fileName}.ts`),
|
||||
`${problemContent}
|
||||
export = {};
|
||||
|
||||
// Output
|
||||
console.log();`
|
||||
);
|
||||
|
||||
// Generate the thoughts file
|
||||
if (thoughts)
|
||||
fs.writeFileSync(
|
||||
path.join(thoughtsDir, `${fileName}.md`),
|
||||
`<div align="center">
|
||||
|
||||
### ${problems[problemNumber - 1]}
|
||||
</div>`
|
||||
);
|
||||
|
||||
// Check it off in the readme
|
||||
const regex = new RegExp(` \\[.\\] ${problemNumber} - .*`);
|
||||
const match = readmeContent.match(regex);
|
||||
|
||||
let newLine = ` [x] [${match[0]
|
||||
.replace('[ ]', '')
|
||||
.trim()}](src/${encodeURIComponent(fileName)}.ts)`;
|
||||
|
||||
if (thoughts)
|
||||
newLine += `\n - [Thoughts](thoughts/${encodeURIComponent(fileName)}.md)`;
|
||||
|
||||
const newContent = readmeContent.replace(regex, newLine);
|
||||
|
||||
fs.writeFileSync(path.join(root, 'readme.md'), newContent);
|
||||
|
||||
// If the problem's ID is greater than 100, add it to the gitignore
|
||||
if (problemNumber > 100) {
|
||||
const gitignorePath = path.join(root, '.gitignore');
|
||||
const gitignoreContent = fs.readFileSync(gitignorePath).toString();
|
||||
let newContent = `${gitignoreContent}\nsrc/${fileName}.ts`;
|
||||
if (thoughts) newContent += `\nthoughts/${fileName}.md`;
|
||||
|
||||
fs.writeFileSync(gitignorePath, newContent);
|
||||
}
|
||||
})
|
||||
.catch(() =>
|
||||
console.error(
|
||||
chalk.red(
|
||||
chalk.bold(
|
||||
'There was an error generating files for that challenge - please ensure that it exists on Project Euler!'
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
// Generate the thoughts file
|
||||
if (thoughts) fs.writeFileSync(path.join(thoughtsDir, `${fileName}.md`), '');
|
||||
|
||||
// Check it off in the readme
|
||||
const regex = new RegExp(` \\[.\\] ${problemNumber} - .*`);
|
||||
const match = readmeContent.match(regex);
|
||||
|
||||
let newLine = ` [x] [${match[0].replace('[ ]', '').trim()}](src/${encodeURIComponent(
|
||||
fileName
|
||||
)}.ts)`;
|
||||
|
||||
if (thoughts)
|
||||
newLine += `\n - [Thoughts](thoughts/${encodeURIComponent(fileName)}.md)`;
|
||||
|
||||
const newContent = readmeContent.replace(regex, newLine);
|
||||
|
||||
fs.writeFileSync(path.join(root, 'readme.md'), newContent);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
<div align="center">
|
||||
|
||||
### Sieve of Eratosthenes Psuedocode
|
||||
|
||||
[Source](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode)
|
||||
|
@ -17,3 +19,5 @@ algorithm Sieve of Eratosthenes is
|
|||
|
||||
return all i such that A[i] is true.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
|
|
@ -1,9 +1,17 @@
|
|||
<div align="center">
|
||||
|
||||
### Lattice Paths
|
||||
|
||||
For a lattice with dimensions m x n, all paths will have m + n segments. m segments go down, n segments go right. To count m + n slots, count the ways to pick m downward moves - the rest will be rightward moves.
|
||||
|
||||
![](assets/15.svg)
|
||||
<br><br>
|
||||
|
||||
### LaTeX
|
||||
<img src="https://latex.codecogs.com/svg.image?{m&space;+&space;n&space;\choose&space;m}&space;=&space;{m&space;+&space;n&space;\choose&space;n}&space;=&space;\frac{(m+n)!}{m!n!}" height="100">
|
||||
|
||||
#### LaTeX
|
||||
|
||||
```
|
||||
{m + n \choose m} = {m + n \choose n} = \frac{(m+n)!}{m!n!}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
|
|
@ -1,26 +1,24 @@
|
|||
a + b + c = 1000, so what is abc?
|
||||
<div align="center">
|
||||
|
||||
a pythagorean triplet must make a < b < c
|
||||
### Proof
|
||||
|
||||
we know that:
|
||||
> let x be the sum
|
||||
|
||||
![](assets/pythagoras.svg)
|
||||
|
||||
let x be the sum
|
||||
|
||||
![](assets/9.svg)
|
||||
<img src="https://latex.codecogs.com/svg.image?c&space;=&space;x&space;-&space;(a&space;+&space;b)&space;\\a^2&space;+&space;b^2&space;=&space;(x&space;-&space;(a&space;+&space;b))^2&space;\\a^2&space;+&space;b^2&space;=&space;a^2&space;+&space;2ab&space;-&space;2ax&space;+&space;b^2&space;-&space;2bx&space;+&space;x^2&space;\\2ab&space;-&space;2ax&space;-&space;2bx&space;+&space;x^2&space;=&space;0&space;\\\\2bx&space;-&space;2ab&space;=&space;x^2&space;-&space;2ax&space;\\(\frac{x^2}{x})&space;-&space;2a&space;=&space;2b&space;-&space;(\frac{2ab}{x})&space;\\-2a&space;=&space;2b&space;-&space;(\frac{2ab}{x})&space;-&space;(\frac{x^2}{x})&space;\\\\a&space;=&space;\frac{2bx&space;-&space;x^2}{2x&space;-&space;2b}" width="500">
|
||||
|
||||
### LaTeX
|
||||
|
||||
```
|
||||
c = x - (a + b) \newline
|
||||
a^2 + b^2 = (x - (a + b))^2 \newline
|
||||
a^2 + b^2 = a^2 + 2ab - 2ax + b^2 - 2bx + x^2 \newline
|
||||
2ab - 2ax - 2bx + x^2 = 0 \newline
|
||||
\newline
|
||||
2bx - 2ab = x^2 - 2ax \newline
|
||||
(\frac{x^2}{x}) - 2a = 2b - (\frac{2ab}{x}) \newline
|
||||
-2a = 2b - (\frac{2ab}{x}) - (\frac{x^2}{x}) \newline
|
||||
\newline
|
||||
c = x - (a + b) \\
|
||||
a^2 + b^2 = (x - (a + b))^2 \\
|
||||
a^2 + b^2 = a^2 + 2ab - 2ax + b^2 - 2bx + x^2 \\
|
||||
2ab - 2ax - 2bx + x^2 = 0 \\
|
||||
\\
|
||||
2bx - 2ab = x^2 - 2ax \\
|
||||
(\frac{x^2}{x}) - 2a = 2b - (\frac{2ab}{x}) \\
|
||||
-2a = 2b - (\frac{2ab}{x}) - (\frac{x^2}{x}) \\
|
||||
\\
|
||||
a = \frac{2bx - x^2}{2x - 2b}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
|
Before Width: | Height: | Size: 5.1 KiB |
Before Width: | Height: | Size: 11 KiB |
|
@ -1 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="124.217" height="20.344" version="1.1" viewBox="-0.239 -0.228 93.163 15.258"><defs><use id="g5-43" transform="scale(1.439999)" xlink:href="#g3-43"/><use id="g5-61" transform="scale(1.439999)" xlink:href="#g3-61"/><path id="g3-43" d="M7.106601-2.769192V-3.543375H4.466439V-6.193462H3.66248V-3.543375H1.022318V-2.769192H3.66248V-.12903H4.466439V-2.769192H7.106601Z"/><path id="g3-50" d="M5.667415 0V-.82381H1.786576C4.575619-3.195985 5.359727-3.999944 5.359727-5.379578C5.359727-6.600404 4.466439-7.364661 2.987551-7.364661C2.272921-7.364661 1.419335-7.146302 .962766-6.918018V-5.895699H1.012393C1.657545-6.322492 2.382101-6.530926 2.967701-6.530926C3.851063-6.530926 4.367185-6.084282 4.367185-5.32995C4.367185-4.24808 3.731958-3.543375 .784108-1.012393V0H5.667415Z"/><path id="g3-61" d="M6.937868-3.79151V-4.565693H1.19105V-3.79151H6.937868ZM6.937868-1.756799V-2.530982H1.19105V-1.756799H6.937868Z"/><path id="g1-97" d="M6.10294-4.116268L5.588406-1.915208C4.830898-1.386382 3.916172-.957604 3.058616-.957604C2.101012-.957604 1.657941-1.314919 1.657941-1.986671C1.657941-3.401638 2.872812-3.987635 6.10294-4.116268ZM5.345432-.828971L5.145335 0H6.445962L7.675125-5.288261C7.732296-5.545528 7.775174-5.845673 7.775174-6.088647C7.775174-7.403566 6.803277-7.989563 4.873776-7.989563C3.930465-7.989563 2.758471-7.746588 2.229645-7.617955L1.972379-6.303036H2.043842C2.672716-6.54601 3.844709-6.87474 4.630802-6.87474C5.888551-6.87474 6.431669-6.54601 6.431669-5.77421C6.403084-5.488358 6.403084-5.459773 6.331621-5.145335C2.043842-5.016702 .271559-4.01622 .271559-1.743697C.271559-.571704 1.114823 .214389 2.358279 .214389C3.57315 .214389 3.95905-.014293 5.345432-.828971Z"/><path id="g1-98" d="M8.318292-5.331139C8.318292-7.031958 7.489322-8.018148 5.960014-8.018148C4.959532-8.018148 4.173439-7.58937 3.315883-6.974788L4.202024-10.862375H2.901397L.3859 0H1.615064L1.786575-.3859C2.358279-.014293 3.087201 .214389 3.916172 .214389C6.345914 .214389 8.318292-2.272523 8.318292-5.331139ZM6.93191-5.073872C6.93191-2.658423 5.674162-.914726 3.901879-.914726C3.130079-.914726 2.629838-1.10053 2.029549-1.414967L3.058616-5.874258C3.773246-6.360206 4.645094-6.817569 5.416895-6.817569C6.474547-6.817569 6.93191-6.188695 6.93191-5.073872Z"/><path id="g1-99" d="M3.773246 .171511C4.702265 .171511 5.616991-.128633 6.431669-.500241L6.703229-1.929501H6.631766C5.631284-1.243456 4.759435-.914726 3.944757-.914726C2.701301-.914726 2.000964-1.643649 2.000964-2.958568C2.000964-5.145335 3.258712-6.889032 5.05958-6.889032C5.902843-6.889032 6.588888-6.60318 7.332103-5.931428H7.417859L7.703711-7.346396C7.089129-7.689418 6.260158-7.97527 5.345432-7.97527C2.601253-7.97527 .600289-5.77421 .600289-2.744179C.600289-.871849 1.729404 .171511 3.773246 .171511Z"/></defs><g id="page1" transform="matrix(1.13 0 0 1.13 -63.986043 -61.051305)"><use x="56.413" y="67.114" xlink:href="#g1-97"/><use x="65.035" y="61.191" xlink:href="#g3-50"/><use x="75.058" y="67.114" xlink:href="#g5-43"/><use x="89.981" y="67.114" xlink:href="#g1-98"/><use x="98.919" y="61.191" xlink:href="#g3-50"/><use x="109.738" y="67.114" xlink:href="#g5-61"/><use x="125.458" y="67.114" xlink:href="#g1-99"/><use x="133.191" y="61.191" xlink:href="#g3-50"/></g></svg>
|
Before Width: | Height: | Size: 3.2 KiB |
|
@ -1,9 +0,0 @@
|
|||
int factorial(int n) {
|
||||
int ans = 1;
|
||||
|
||||
for (int i = 2; i <= n; i++) {
|
||||
ans *= i;
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
#include <stdio.h>
|
||||
#include "helpers/factorial.c"
|
||||
|
||||
int nCr(int n, int r) {
|
||||
return factorial(n) / factorial(r) * factorial(n - r);
|
||||
}
|
||||
|
||||
void main() {
|
||||
int n;
|
||||
int r;
|
||||
|
||||
printf("Please enter n: ");
|
||||
scanf("%i", &n);
|
||||
|
||||
printf("Please enter r: ");
|
||||
scanf("%i", &r);
|
||||
|
||||
int ans = nCr(n, r);
|
||||
printf("The answer is: %i", ans);
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
package calculators;
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
class CombinationCalculator {
|
||||
private static Scanner scanner = new Scanner(System.in);
|
||||
|
||||
private static int factorial(int n) {
|
||||
int res = 1;
|
||||
|
||||
for (int i = 2; i <= n; i++) {
|
||||
res *= i;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private static int nCr(int n, int r) {
|
||||
return factorial(n) / (factorial(r) * factorial(n - r));
|
||||
}
|
||||
|
||||
private static int intInput(String message) {
|
||||
int value = -1;
|
||||
|
||||
while (value < 0) {
|
||||
try {
|
||||
System.out.print(message);
|
||||
value = scanner.nextInt();
|
||||
} catch (InputMismatchException e) {
|
||||
scanner.next();
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Take inputs
|
||||
int n = intInput("Please input the value for n: ");
|
||||
int r = intInput("Please input the value for r: ");
|
||||
scanner.close();
|
||||
|
||||
// Calculate the result
|
||||
int result = nCr(n, r);
|
||||
System.out.println(result);
|
||||
}
|
||||
}
|
|
@ -5,11 +5,11 @@ Created as a part of my Royal Institute masterclass
|
|||
|
||||
from _helpers import intInput
|
||||
|
||||
def sqrt(x):
|
||||
a = 2
|
||||
while abs((a - (x / a))) > 1:
|
||||
a = (a + (x / a)) / 2
|
||||
return int(a)
|
||||
def sqrt(number):
|
||||
initialGuess = 2
|
||||
while abs(initialGuess - (number / initialGuess)) > 1:
|
||||
initialGuess = (initialGuess + (number / initialGuess)) / 2
|
||||
return int(initialGuess)
|
||||
|
||||
num = intInput('Please input a number! (:')
|
||||
res = sqrt(num)
|
50
languages/python/calculators/Binomial Expansion.py
Normal file
|
@ -0,0 +1,50 @@
|
|||
# (a + b) ^ n
|
||||
superscript = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹']
|
||||
|
||||
def factorial(n):
|
||||
ans = 1
|
||||
for i in range(2, n + 1):
|
||||
ans *= i
|
||||
return ans
|
||||
|
||||
def nCr(n, r):
|
||||
return factorial(n) / (factorial(r) * factorial(n - r))
|
||||
|
||||
while True:
|
||||
try:
|
||||
n = int(input('Please enter a power to put (a + b) to! '))
|
||||
break
|
||||
except ValueError:
|
||||
print('The power must be a valid integer!')
|
||||
continue
|
||||
|
||||
terms = []
|
||||
|
||||
for r in range(n + 1):
|
||||
a = n - r
|
||||
b = r
|
||||
c = int(nCr(n, r))
|
||||
term = ''
|
||||
|
||||
if c != 1:
|
||||
term += str(c)
|
||||
|
||||
if a != 0:
|
||||
term += 'a'
|
||||
if a != 1:
|
||||
power = ''
|
||||
for digit in str(a):
|
||||
power += superscript[int(digit)]
|
||||
term += power
|
||||
|
||||
if b != 0:
|
||||
term += 'b'
|
||||
if b != 1:
|
||||
power = ''
|
||||
for digit in str(b):
|
||||
power += superscript[int(digit)]
|
||||
term += power
|
||||
|
||||
terms.append(term)
|
||||
|
||||
print(' + '.join(terms))
|
|
@ -1,28 +0,0 @@
|
|||
### Useful Links
|
||||
|
||||
- [Wikipedia](https://en.wikipedia.org/wiki/Karatsuba_algorithm)
|
||||
- [An amazing video on the topic](https://youtu.be/cCKOl5li6YM)
|
||||
|
||||
### The Pseudocode
|
||||
|
||||
```
|
||||
function karatsuba (num1, num2)
|
||||
if (num1 < 10) or (num2 < 10)
|
||||
return num1 × num2 /* fall back to traditional multiplication */
|
||||
|
||||
/* Calculates the size of the numbers. */
|
||||
m = min (size_base10(num1), size_base10(num2))
|
||||
m2 = floor (m / 2)
|
||||
/* m2 = ceil (m / 2) will also work */
|
||||
|
||||
/* Split the digit sequences in the middle. */
|
||||
high1, low1 = split_at (num1, m2)
|
||||
high2, low2 = split_at (num2, m2)
|
||||
|
||||
/* 3 recursive calls made to numbers approximately half the size. */
|
||||
z0 = karatsuba (low1, low2)
|
||||
z1 = karatsuba (low1 + high1, low2 + high2)
|
||||
z2 = karatsuba (high1, high2)
|
||||
|
||||
return (z2 × 10 ^ (m2 × 2)) + ((z1 - z2 - z0) × 10 ^ m2) + z0
|
||||
```
|
|
@ -1,27 +0,0 @@
|
|||
import operator
|
||||
from _helpers import listInput
|
||||
|
||||
def diff(a):
|
||||
return list(map(operator.sub, a[1:], a[:-1]))
|
||||
|
||||
def formatNumber(x):
|
||||
if x % 1 == 0:
|
||||
return int(x)
|
||||
else:
|
||||
return x
|
||||
|
||||
sequence = listInput('Please input a sequence of numbers')
|
||||
row1 = diff(sequence)
|
||||
row2 = diff(row1)
|
||||
|
||||
a = formatNumber(row2[0] / 2)
|
||||
b = formatNumber(row1[0] - (3 * a))
|
||||
c = formatNumber(sequence[0] - a - b)
|
||||
|
||||
print('''
|
||||
a = {0}
|
||||
b = {2}
|
||||
c = {4}
|
||||
|
||||
Equation: {0}n²{1}{2}n{3}{4}
|
||||
'''.format(a, '+' if b >= 0 else '', b, '+' if c >= 0 else '', c))
|
|
@ -1,16 +0,0 @@
|
|||
import math
|
||||
from _helpers import listInput
|
||||
|
||||
def sd(x):
|
||||
n = len(x)
|
||||
mean = sum(x) / n
|
||||
squared = [y ** 2 for y in x]
|
||||
|
||||
return math.sqrt(abs((sum(squared) / n) - (mean**2)))
|
||||
|
||||
nums = listInput('Please input a list of numbers')
|
||||
res = sd(nums)
|
||||
|
||||
print()
|
||||
print('The list:', nums)
|
||||
print('Standard Deviation:', res)
|
|
@ -1,15 +1,22 @@
|
|||
# calculators
|
||||
<div align="center">
|
||||
|
||||
Some extra information on the more complex topics (:
|
||||
### Babylonian Square Root
|
||||
|
||||
## Karatsuba Algorithm
|
||||
<img src="https://latex.codecogs.com/svg.image?\dpi{100}%20\%20x_0%20\approx%20\sqrt{S}%20\\x_{n%20+%201}%20=%20\frac{x_n%20+%20\frac{S}{x_n}}{2}%20\\\sqrt{S}%20=%20\displaystyle%20\lim_{n%20\to%20\infty}x_n" height="250" />
|
||||
|
||||
### Useful Links
|
||||
#### LaTeX
|
||||
|
||||
- [Wikipedia](https://en.wikipedia.org/wiki/Karatsuba_algorithm)
|
||||
- [An amazing video on the topic](https://youtu.be/cCKOl5li6YM)
|
||||
```
|
||||
x_0 \approx \sqrt{S} \\
|
||||
x_{n + 1} = \frac{x_n + \frac{S}{x_n}}{2} \\
|
||||
\sqrt{S} = \displaystyle \lim_{n \to \infty}x_n
|
||||
```
|
||||
|
||||
### The Pseudocode
|
||||
### Karatsuba Algorithm
|
||||
|
||||
[Wikipedia](https://en.wikipedia.org/wiki/Karatsuba_algorithm)
|
||||
|
||||
[An amazing video on the topic](https://youtu.be/cCKOl5li6YM)
|
||||
|
||||
```
|
||||
function karatsuba (num1, num2)
|
||||
|
@ -32,3 +39,5 @@ function karatsuba (num1, num2)
|
|||
|
||||
return (z2 × 10 ^ (m2 × 2)) + ((z1 - z2 - z0) × 10 ^ m2) + z0
|
||||
```
|
||||
|
||||
</div>
|
||||
|
|
|
@ -1,45 +0,0 @@
|
|||
import oppaipy
|
||||
import requests
|
||||
import os
|
||||
|
||||
# Request information about the beatmap
|
||||
id = input('Please enter a beatmap ID: ').strip()
|
||||
beatmap = requests.get('https://osu.ppy.sh/osu/{0}'.format(id)) # Fetch the osu file
|
||||
open('{0}.osu'.format(id), 'w').write(beatmap.text.replace('\n', '')) # Write this difficulty to the disk
|
||||
lines = open('{0}.osu'.format(id), 'r').readlines() # Read the lines of the osu file
|
||||
artist = [x[7:len(x)].strip() for x in lines if x.startswith('Artist:')][0] # Figure out the artist of the song
|
||||
name = [x[6:len(x)].strip() for x in lines if x.startswith('Title:')][0] # Figure out the name of the song
|
||||
diff = [x[8:len(x)].strip() for x in lines if x.startswith('Version:')][0] # Figure out the difficulty name
|
||||
name = '{0} - {1} [{2}]'.format(artist, name, diff) # Put these three together into a parseable format by osu
|
||||
|
||||
# Calculate beatmap stats
|
||||
calc = oppaipy.Calculator() # Create an instance of the pp calculator
|
||||
calc.set_beatmap('{0}.osu'.format(id)) # Load the newly written difficulty file
|
||||
calc.calculate() # Calculate the stats
|
||||
calc.close() # Close the calculator to save resources
|
||||
|
||||
# Round beatmap stats to be readable
|
||||
stars = {
|
||||
'total': round(calc.stars, 2),
|
||||
'aim': round(calc.aim_stars, 2),
|
||||
'speed': round(calc.speed_stars, 2)
|
||||
}
|
||||
|
||||
pp = {
|
||||
'total': round(calc.pp, 2),
|
||||
'aim': round(calc.aim_pp, 2),
|
||||
'speed': round(calc.speed_pp, 2),
|
||||
'acc': round(calc.acc_pp, 2)
|
||||
}
|
||||
|
||||
# Output information
|
||||
print("""
|
||||
{0} ({1}*)
|
||||
|
||||
{2}* Aim
|
||||
{3}* Speed
|
||||
{4}pp ({5} aim pp, {6} speed pp, {7} acc pp)
|
||||
""".format(name, stars['total'], stars['aim'], stars['speed'], pp['total'], pp['aim'], pp['speed'], pp['acc']))
|
||||
|
||||
# Cleanup by deleting the written difficulty file afterwards
|
||||
os.remove('{0}.osu'.format(id))
|
|
@ -15,16 +15,16 @@
|
|||
### Calculators
|
||||
|
||||
- [Binomial Distribution](calculators/Binomial%20Distribution.py)
|
||||
- [Binomial Expansion](calculators/Binomial%20Expansion.py)
|
||||
- [Karatsuba Algorithm](calculators/Karatsuba%20Algorithm.py)
|
||||
- [Pearson's Product-Moment Correlation Coefficient](calculators/PMCC.py)
|
||||
- [Quadratic nth Term](calculators/Quadratic%20nth%20Term.py)
|
||||
- [Square Root](calculators/SQRT.py)
|
||||
- [Babylonian Square Root](calculators/Babylonian%20%Sqaure%20Root.py)
|
||||
- [Spearman's Rank Correlation Coefficient](calculators/SRCC.py)
|
||||
- [Standard Deviation](calculators/STDEV.py)
|
||||
- [Trigometric Functions](calculators/Trigometric%20Functions.py)
|
||||
- [Pascal's Triangle](calculators/Pascal's%20Triangle.py)
|
||||
|
||||
### Other
|
||||
|
||||
- [PP Calculator](pp.py)
|
||||
- [2 Stars List](gd-two-star-list)
|
||||
- [Pong (made with Pygame)](pong)
|
||||
- [pythonchallenge.com](pythonchallenge.com)
|
||||
|
|
|
@ -8,8 +8,6 @@
|
|||
### Table of contents
|
||||
|
||||
- [Python](languages/python)
|
||||
- [C](languages/c)
|
||||
- [Java](languages/java)
|
||||
- [Project Euler](challenges/euler)
|
||||
- [r/dailyprogrammer](challenges/daily-programmer)
|
||||
- [GCSE Computer Science](school/gcse)
|
||||
|
|
22
school/gcse/year 10/Pallindrome Checker.py
Normal file
|
@ -0,0 +1,22 @@
|
|||
import re
|
||||
|
||||
word = input('Please enter a word!')
|
||||
|
||||
def isPallindrome(word):
|
||||
# Strip the word of punctuation
|
||||
word = re.sub(r'[^\w\s]', '', word)
|
||||
|
||||
# Check if the word is a pallindrome
|
||||
reverse = ''
|
||||
i = len(word)
|
||||
|
||||
while i > 0:
|
||||
reverse += word[i - 1]
|
||||
i = i - 1
|
||||
|
||||
return word == reverse
|
||||
|
||||
if isPallindrome(word):
|
||||
print('{0} is a pallindrome!'.format(re.sub(r'[^\w\s]', '', word)))
|
||||
else:
|
||||
print('{0} is not a pallindrome!'.format(re.sub(r'[^\w\s]', '', word)))
|
|
@ -1,47 +0,0 @@
|
|||
from random import randint
|
||||
|
||||
class Dice:
|
||||
# Initialise the class - make the default amount of sides 6
|
||||
def __init__(self, sides=6):
|
||||
self.sides = sides
|
||||
|
||||
# Roll the dice once - return an integer
|
||||
def roll(self):
|
||||
return randint(1, self.sides)
|
||||
|
||||
# Roll the dice a specified amount of times - return an array of integers
|
||||
def rollMany(self, times):
|
||||
res = []
|
||||
for i in range(times):
|
||||
num = self.roll()
|
||||
res.append(num)
|
||||
return res
|
||||
|
||||
dice = Dice() # Create an instance of the class Dice
|
||||
|
||||
p1 = dice.rollMany(6) # Roll 6 dice for player 1
|
||||
p2 = dice.rollMany(6) # Roll 6 dice for player 2
|
||||
p1score = sum(p1) # Calculate player 1's score
|
||||
p2score = sum(p2) # Calculate player 2's score
|
||||
|
||||
# Output player 1's rolls and score for the user to see
|
||||
print("Player 1 rolls ({0})".format(p1score))
|
||||
|
||||
for i in p1:
|
||||
pos = p1.index(i) + 1
|
||||
print("{0}. {1}".format(pos, i))
|
||||
|
||||
# Output player 2's rolls and score for the user to see
|
||||
print("\nPlayer 2 rolls ({0})".format(p2score))
|
||||
|
||||
for i in p2:
|
||||
pos = p2.index(i) + 1
|
||||
print("{0}. {1}".format(pos, i))
|
||||
|
||||
# Determine the winner
|
||||
if p1score > p2score:
|
||||
print("\nPlayer 1 ({0}) wins by {1} points!".format(p1score, p1score - p2score))
|
||||
elif p2score > p1score:
|
||||
print("\nPlayer 2 ({0}) wins by {1} points!".format(p2score, p2score - p1score))
|
||||
else:
|
||||
print("\nDraw!")
|
|
@ -1,14 +0,0 @@
|
|||
word = input('Please enter a word!')
|
||||
|
||||
def isPallindrome(x):
|
||||
reverse = ''
|
||||
i = len(x)
|
||||
while i > 0:
|
||||
reverse += x[i - 1]
|
||||
i = i - 1
|
||||
return x == reverse
|
||||
|
||||
if isPallindrome(word):
|
||||
print('{0} is a pallindrome!'.format(word))
|
||||
else:
|
||||
print('{0} is not a pallindrome!'.format(word))
|
|
@ -1,15 +0,0 @@
|
|||
word = input('Please enter a word!')
|
||||
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
|
||||
nopunc = ''
|
||||
|
||||
for i in word:
|
||||
if i not in punctuations:
|
||||
nopunc = nopunc + i
|
||||
|
||||
def isPallindrome(x):
|
||||
return x == x[::-1]
|
||||
|
||||
if isPallindrome(nopunc):
|
||||
print('{0} is a pallindrome!'.format(word))
|
||||
else:
|
||||
print('{0} is not a pallindrome!'.format(word))
|
|
@ -1,9 +0,0 @@
|
|||
word = input('Please enter a word!')
|
||||
|
||||
def isPallindrome(x):
|
||||
return x == x[::-1]
|
||||
|
||||
if isPallindrome(word):
|
||||
print('{0} is a pallindrome!'.format(word))
|
||||
else:
|
||||
print('{0} is not a pallindrome!'.format(word))
|
|
@ -1,13 +0,0 @@
|
|||
<div align="center">
|
||||
<h1>year 10</h1>
|
||||
</div>
|
||||
|
||||
- [Calculator](calculator)
|
||||
- [Cat or Dog](cat%20or%20dog)
|
||||
- [Mark Analyser](mark%20analyser)
|
||||
- [OOP Dice](oop%20dice)
|
||||
- [Pallindromes](pallindromes)
|
||||
- [Password Reset](password%20reset)
|
||||
- [Raspberry Pie Game](raspberry%20pie%20game)
|
||||
- [API Hangman](API%20Hangman.py)
|
||||
- [Temperature Bar Chart](Temperature%20Bar%20Chart.py)
|
15
school/gcse/year 11/8 Ball.py
Normal file
|
@ -0,0 +1,15 @@
|
|||
import random
|
||||
|
||||
class EightBall:
|
||||
def __init__(self):
|
||||
self.responses = ['It is certain.','It is decidedly so.','Without a doubt.','Yes — definitely.','You may rely on it.','As I see it, yes.','Most likely.','Outlook good.','Yes.','Signs point to yes.','Reply hazy, try again.','Ask again later.','Better not tell you now.','Cannot predict now.','Concentrate and ask again.','Don’t count on it.','My reply is no.','My sources say no.','Outlook not so good.','Very doubtful.']
|
||||
def answer(self):
|
||||
return random.choice(self.responses)
|
||||
|
||||
ball = EightBall()
|
||||
question = input('What is your question for the magic 8 ball?')
|
||||
|
||||
print("""
|
||||
Q: %s
|
||||
A: %s
|
||||
""" % (question, ball.answer()))
|
32
school/gcse/year 11/Bubble Sort.py
Normal file
|
@ -0,0 +1,32 @@
|
|||
import random
|
||||
|
||||
def generateList(minimum, maximum, length):
|
||||
res = []
|
||||
for i in range(length):
|
||||
res.append(random.randint(minimum, maximum))
|
||||
return res
|
||||
|
||||
def bubbleSort(data, asc = True):
|
||||
dataClone = data.copy()
|
||||
hasSwapped = True
|
||||
indexToCheck = len(dataClone) - 1
|
||||
while indexToCheck > 0 and hasSwapped:
|
||||
hasSwapped = False
|
||||
for i in range(indexToCheck):
|
||||
if asc and dataClone[i] > dataClone[i + 1] or not asc and dataClone[i] < dataClone[i + 1]:
|
||||
hasSwapped = True
|
||||
a, b = dataClone[i], dataClone[i + 1]
|
||||
dataClone[i] = b
|
||||
dataClone[i + 1] = a
|
||||
indexToCheck -= 1
|
||||
return dataClone
|
||||
|
||||
nums = generateList(0, 100, 15)
|
||||
sortedAsc = bubbleSort(nums, True)
|
||||
sortedDesc = bubbleSort(nums, False)
|
||||
|
||||
print("""
|
||||
Original: %s
|
||||
Ascending: %s
|
||||
Descending: %s
|
||||
""" % (str(nums), str(sortedAsc), str(sortedDesc)))
|
43
school/gcse/year 11/Card Shuffler.py
Normal file
|
@ -0,0 +1,43 @@
|
|||
import random
|
||||
|
||||
class Deck():
|
||||
def __init__(self, suits):
|
||||
self.cards = []
|
||||
self.suits = suits
|
||||
|
||||
def generate(self):
|
||||
for suit in self.suits:
|
||||
for cardType in range(1, 14):
|
||||
formattedCard = ""
|
||||
|
||||
if cardType == 1:
|
||||
formattedCard += "Ace"
|
||||
elif cardType == 11:
|
||||
formattedCard += "Jack"
|
||||
elif cardType == 12:
|
||||
formattedCard += "Queen"
|
||||
elif cardType == 13:
|
||||
formattedCard += 'King'
|
||||
else:
|
||||
formattedCard += str(cardType)
|
||||
|
||||
formattedCard += ' of %s' % (suit)
|
||||
self.cards.append(formattedCard)
|
||||
|
||||
def shuffle(self):
|
||||
currentCards = self.cards
|
||||
shuffledCards = []
|
||||
|
||||
while len(currentCards) > 0:
|
||||
pick = random.randint(0, len(currentCards) - 1)
|
||||
removedCard = currentCards.pop(pick)
|
||||
shuffledCards.append(removedCard)
|
||||
|
||||
self.cards = shuffledCards
|
||||
|
||||
deck = Deck(["Spades", "Hearts", "Diamonds", "Clubs"])
|
||||
print(deck.cards)
|
||||
deck.generate()
|
||||
print(deck.cards)
|
||||
deck.shuffle()
|
||||
print(deck.cards)
|
115
school/gcse/year 11/File Size Estimates.py
Normal file
|
@ -0,0 +1,115 @@
|
|||
import math
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
class NegativeError(Exception):
|
||||
pass
|
||||
|
||||
def estimateTextFileSize(characterCount, bitsPerCharacter):
|
||||
return characterCount * bitsPerCharacter
|
||||
|
||||
def estimatePictureFileSize(width, height, colourDepth):
|
||||
return colourDepth * width * height
|
||||
|
||||
def estimateSoundFileSize(sampleRate, bitDepth, duration, channelCount):
|
||||
return sampleRate * duration * bitDepth * channelCount
|
||||
|
||||
def formatBits(bits):
|
||||
units = ['bits', 'bytes', 'kilobytes', 'megabytes', 'gigabytes', 'terrabytes', 'petabytes']
|
||||
|
||||
for unit in units:
|
||||
if unit == units[0]:
|
||||
bits /= 8
|
||||
elif bits < 1024 or unit == units[len(units) - 1]:
|
||||
break
|
||||
else:
|
||||
bits /= 1024
|
||||
|
||||
return '%i %s' % (math.floor(bits), unit)
|
||||
|
||||
def validateInput(function, inputMessage, errorMessage):
|
||||
while True:
|
||||
try:
|
||||
out = function(input(inputMessage))
|
||||
|
||||
if (function == int or function == float) and out < 0:
|
||||
raise NegativeError
|
||||
|
||||
break
|
||||
except ValueError:
|
||||
print(errorMessage)
|
||||
continue
|
||||
except NegativeError:
|
||||
print('The value you input can not be a negative number! Please try again (:')
|
||||
continue
|
||||
return out
|
||||
|
||||
def saveFile(data, fileType, bits):
|
||||
while True:
|
||||
toSave = input('Would you like to save your file? y/n').lower()
|
||||
|
||||
if toSave == 'y':
|
||||
id = uuid.uuid1()
|
||||
file = open('%s.txt' % (id), 'w')
|
||||
file.write('Date: %s\n' % (datetime.now().strftime('%d/%m/%Y, %I:%M %p')))
|
||||
file.write('ID: %s\n' % (id))
|
||||
|
||||
for set in data:
|
||||
key = set[0]
|
||||
value = set[1]
|
||||
file.write('%s: %s\n' % (key, value))
|
||||
|
||||
file.write('---------------------------------------------\n\n')
|
||||
file.write('Your %s file\'s size is approximately %s' % (fileType, formatBits(bits)))
|
||||
break
|
||||
|
||||
# Menu
|
||||
while True:
|
||||
print("""Welcome to the File Size Estimator! Please choose a function below:
|
||||
|
||||
1) Estimate Text File Size
|
||||
2) Estimate Picture File Size
|
||||
3) Estimate Sound File Size
|
||||
""")
|
||||
|
||||
choice = validateInput(int, 'Please make your choice: ', 'Please make sure you select a valid function!')
|
||||
|
||||
if choice == 1:
|
||||
characterCount = validateInput(int, 'How many characters are in your text file? ', 'Please make sure you enter a valid integer!')
|
||||
bitsPerCharacter = validateInput(int, 'How many bits are used to store a character in your text file? ', 'Please make sure you enter a valid integer!')
|
||||
bits = estimateTextFileSize(characterCount, bitsPerCharacter)
|
||||
|
||||
print('Your text file\'s size is approximately %s' % (formatBits(bits)))
|
||||
saveFile([['Character Count', characterCount], ['Bits Per Character', bitsPerCharacter]], 'text', bits)
|
||||
elif choice == 2:
|
||||
width = validateInput(float, 'What is the width of your image? ', 'Please make sure you enter a valid number!')
|
||||
height = validateInput(float, 'What is the height of your image? ', 'Please make sure you enter a valid number!')
|
||||
colourDepth = validateInput(int, 'What is the colour depth of your image? ', 'Please make sure you enter a valid integer!')
|
||||
bits = estimatePictureFileSize(width, height, colourDepth)
|
||||
|
||||
print('Your image file\'s size is approximately %s' % (formatBits(bits)))
|
||||
saveFile([['Image Width', width], ['Image Height', height], ['Colour Depth', colourDepth]], 'image', bits)
|
||||
elif choice == 3:
|
||||
sampleRate = validateInput(int, 'What is the sample rate of your audio file? ', 'Please make sure you enter a valid integer!')
|
||||
bitDepth = validateInput(int, 'What is the bit depth of your audio file? ', 'Please make sure you enter a valid integer!')
|
||||
duration = validateInput(float, 'What is the duration of your audio file in seconds? ', 'Please make sure you enter a valid number!')
|
||||
channelCount = validateInput(int, 'How many channels does your audio file have? ', 'Please make sure you enter a valid integer!')
|
||||
bits = estimateSoundFileSize(sampleRate, bitDepth, duration, channelCount)
|
||||
|
||||
print('Your audio file\'s size is approximately %s' % (formatBits(bits)))
|
||||
saveFile([['Sample Rate', sampleRate], ['Bit Depth', bitDepth], ['Duration', duration], ['Channel Count', channelCount]], 'text', bits)
|
||||
else:
|
||||
continue
|
||||
|
||||
while True:
|
||||
again = input('Would you like to go again? y/n').lower()
|
||||
|
||||
if again != 'y' and again != 'n':
|
||||
continue
|
||||
else:
|
||||
break
|
||||
|
||||
if choice == 'y':
|
||||
continue
|
||||
else:
|
||||
break
|
74
school/gcse/year 11/If Statement Program Challenge.py
Normal file
|
@ -0,0 +1,74 @@
|
|||
import random
|
||||
import time
|
||||
|
||||
# A class to represent a fair n-sided dice
|
||||
class Dice:
|
||||
def __init__(self, sides):
|
||||
self.sides = sides
|
||||
|
||||
def roll(self):
|
||||
return random.randint(1, self.sides)
|
||||
|
||||
# A class to represent the player
|
||||
class Player:
|
||||
def __init__(self):
|
||||
self.dice = Dice(6)
|
||||
self.score = 0
|
||||
|
||||
def roll(self):
|
||||
return self.dice.roll()
|
||||
|
||||
# Enum to represent the result of the end of the game
|
||||
### 0 - Tie
|
||||
### 1 - Player One wins!
|
||||
### 2 - Player Two wins!
|
||||
class GameResult:
|
||||
Tie = 0
|
||||
PlayerOne = 1
|
||||
PlayerTwo = 2
|
||||
|
||||
# Initialise key variables for the game
|
||||
playerOne = Player()
|
||||
playerTwo = Player()
|
||||
currentRound = 0
|
||||
|
||||
# Play a round of the game
|
||||
def play():
|
||||
global currentRound
|
||||
|
||||
# Increment the round and roll the dice
|
||||
currentRound += 1
|
||||
playerOneRoll = playerOne.roll()
|
||||
playerTwoRoll = playerTwo.roll()
|
||||
|
||||
# Figure out the result of the game
|
||||
if playerOneRoll > playerTwoRoll:
|
||||
playerOne.score += 1
|
||||
state = GameResult.PlayerOne
|
||||
elif playerOneRoll == playerTwoRoll:
|
||||
state = GameResult.Tie
|
||||
else:
|
||||
playerTwo.score += 1
|
||||
state = GameResult.PlayerTwo
|
||||
|
||||
# Turn the result of the game into a string
|
||||
if state == GameResult.Tie:
|
||||
header = 'Round %i was a tie' % (currentRound)
|
||||
elif state == GameResult.PlayerOne:
|
||||
header = 'Player One wins Round %i' % (currentRound)
|
||||
elif state == GameResult.PlayerTwo:
|
||||
header = 'Player Two wins Round %i' % (currentRound)
|
||||
|
||||
# Print a summary of the end of the round
|
||||
print("""
|
||||
|
||||
%s! The current scores are as follows:
|
||||
|
||||
Player One - %i
|
||||
Player Two - %i""" % (header, playerOne.score, playerTwo.score)
|
||||
)
|
||||
|
||||
# Keep playing until someone has won three rounds
|
||||
while playerOne.score != 3 and playerTwo.score != 3:
|
||||
play() # Play the round
|
||||
time.sleep(2) # Pause for two seconds to allow for time for the user to read the summary
|
88
school/gcse/year 11/League Table.py
Normal file
|
@ -0,0 +1,88 @@
|
|||
import csv
|
||||
import os
|
||||
|
||||
path = '%s\league-table.csv' % (os.getcwd())
|
||||
|
||||
def clear():
|
||||
print('\n' * 50)
|
||||
|
||||
def resolveDataType(data):
|
||||
result = data
|
||||
try:
|
||||
result = int(data)
|
||||
except ValueError:
|
||||
try:
|
||||
result = float(data)
|
||||
except ValueError:
|
||||
temp = list(data)
|
||||
if len(temp) > 0:
|
||||
i = 0
|
||||
for value in temp:
|
||||
temp[i] = resolveDataType(value)
|
||||
i += 1
|
||||
if len(temp) > 1:
|
||||
result = temp
|
||||
return result
|
||||
|
||||
def ensureFileExists():
|
||||
doesExist = os.path.isfile(path)
|
||||
|
||||
if not doesExist:
|
||||
with open(path, 'w') as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(['Name', 'Games Played', 'Games Won', 'Games Lost', 'Games Drawn', 'Overall Points', 'GD'])
|
||||
file.close()
|
||||
|
||||
def readTeams():
|
||||
with open(path, 'r') as file:
|
||||
reader = csv.reader(file)
|
||||
headers = next(reader) # get the headers and remove them from the reader
|
||||
|
||||
for row in reader:
|
||||
col = 0
|
||||
for value in row:
|
||||
print('%s: %s' % (headers[col], value))
|
||||
col += 1
|
||||
|
||||
file.close()
|
||||
|
||||
def writeTeam():
|
||||
with open(path, 'r+') as file:
|
||||
reader = csv.reader(file)
|
||||
headers = next(reader)
|
||||
data = []
|
||||
|
||||
for header in headers:
|
||||
response = input('%s?' % (header))
|
||||
data.append(response)
|
||||
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(data)
|
||||
file.close()
|
||||
|
||||
# Menu
|
||||
def displayMenu():
|
||||
print("""Welcome to the League Table! What would you like to do?
|
||||
|
||||
1) View the current state of the League Table
|
||||
2) Write to the League Table
|
||||
3) Remove from the League Table""")
|
||||
|
||||
while True:
|
||||
try:
|
||||
menuOption = int(input('Which option would you like to select? '))
|
||||
break
|
||||
except ValueError:
|
||||
print('Please make sure that your input is a valid integer!')
|
||||
continue
|
||||
|
||||
if menuOption == 1:
|
||||
clear()
|
||||
readTeams()
|
||||
elif menuOption == 2:
|
||||
clear()
|
||||
writeTeam()
|
||||
|
||||
##ensureFileExists()
|
||||
##displayMenu()
|
||||
print(resolveDataType('[1,2,3]'))
|
43
school/gcse/year 11/Linear Search.py
Normal file
|
@ -0,0 +1,43 @@
|
|||
def linearSearch(data, value):
|
||||
for i in range(0, len(data)):
|
||||
if data[i] == value:
|
||||
return i
|
||||
return -1
|
||||
|
||||
class ConfirmationError(Exception):
|
||||
pass
|
||||
|
||||
numbers = []
|
||||
addingStage = True
|
||||
|
||||
while addingStage:
|
||||
try:
|
||||
number = float(input('Please enter a number to add to the list'))
|
||||
numbers.append(number)
|
||||
while True:
|
||||
try:
|
||||
toContinue = input('Would you like to enter another number? (y/n)')
|
||||
if toContinue == 'y':
|
||||
break
|
||||
if toContinue == 'n':
|
||||
addingStage = False
|
||||
break
|
||||
else:
|
||||
raise ConfirmationError
|
||||
except ConfirmationError:
|
||||
print('Please make sure you enter a valid confirmation value!')
|
||||
except ValueError:
|
||||
print('Please make sure you enter a valid number!')
|
||||
|
||||
while True:
|
||||
try:
|
||||
toSearch = float(input('Please enter a number to find the index of'))
|
||||
index = linearSearch(numbers, toSearch)
|
||||
print(numbers)
|
||||
if index == -1:
|
||||
print('%.2f is not in the list' % (toSearch))
|
||||
else:
|
||||
print('%.2f is at index %i in the list' % (toSearch, index))
|
||||
break
|
||||
except ValueError:
|
||||
print('Please make sure you enter a valid number!')
|
|
@ -39,7 +39,7 @@ def generateQuestion():
|
|||
|
||||
'''Generates a fake answer based on the real answer.'''
|
||||
def generateFakeAnswer(answer):
|
||||
r = random.randint(-10, 10)
|
||||
r = random.randint(-11, 11)
|
||||
return answer + r
|
||||
|
||||
'''Asks a question.'''
|
||||
|
@ -57,7 +57,7 @@ def askQuestion():
|
|||
else:
|
||||
while True:
|
||||
generated = generateFakeAnswer(answer)
|
||||
if generated != answer:
|
||||
if generated != answer and generated not in answerList:
|
||||
answerList[i] = generated
|
||||
break
|
||||
|
||||
|
|
52
school/gcse/year 11/Turtle n-gon.py
Normal file
|
@ -0,0 +1,52 @@
|
|||
from turtle import Turtle, Screen, numinput, textinput
|
||||
from random import random
|
||||
|
||||
def generateColour():
|
||||
return (random(), random(), random())
|
||||
|
||||
# Configure the turtle
|
||||
turtle = Turtle()
|
||||
|
||||
while True:
|
||||
# Change the colour of the turtle
|
||||
r, g, b = generateColour()
|
||||
turtle.color(r, g, b)
|
||||
|
||||
# Collect the amount of sides
|
||||
while True:
|
||||
try:
|
||||
sides = int(numinput('Side Count', 'How many sides would you like to render?'))
|
||||
|
||||
if sides < 3:
|
||||
raise ValueError
|
||||
else:
|
||||
break
|
||||
except ValueError:
|
||||
print('A polygon must have a minimum of 3 sides! Try again with a number >= 3')
|
||||
continue
|
||||
|
||||
# Move the turtle
|
||||
for i in range(sides):
|
||||
turtle.forward(100)
|
||||
turtle.left(360 / sides)
|
||||
|
||||
# Ask if the user would like to go again
|
||||
while True:
|
||||
try:
|
||||
again = textinput('Continue?', 'Would you like to run the program again?').lower()
|
||||
|
||||
if not again == 'yes' and not again == 'no' and not again == 'y' and not again == 'n':
|
||||
raise ValueError
|
||||
else:
|
||||
break
|
||||
except ValueError:
|
||||
print('You must answer yes or no to this question')
|
||||
continue
|
||||
|
||||
if again == 'y' or again == 'yes':
|
||||
# Reset the turtle and ask again
|
||||
turtle.reset()
|
||||
else:
|
||||
# Close the turtle
|
||||
Screen().bye()
|
||||
break
|
Before Width: | Height: | Size: 31 KiB |
Before Width: | Height: | Size: 1.1 MiB |
Before Width: | Height: | Size: 707 KiB |
Before Width: | Height: | Size: 731 KiB |
Before Width: | Height: | Size: 737 KiB |
Before Width: | Height: | Size: 737 KiB |
|
@ -1,34 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<!-- CSS and Favicon -->
|
||||
<link rel="stylesheet" type="text/css" href="stylesheet.css">
|
||||
|
||||
<!-- Metadata -->
|
||||
<title>Ecofest</title>
|
||||
</head>
|
||||
<body>
|
||||
<a href="index.html"><img src="./assets/img/arrow.png" alt="" class="back"></a>
|
||||
|
||||
<h1 class="title">Our Acts</h1>
|
||||
|
||||
<div class="acts">
|
||||
<div class="act">
|
||||
<img src="./assets/img/everyones-environment.jpg" alt="Everyone's Environment" />
|
||||
<p>Everyone's Environment</p>
|
||||
</div>
|
||||
<div class="act">
|
||||
<img src="./assets/img/solar-drum.jpg" alt="Solar Drum" />
|
||||
<p>Solar Drum</p>
|
||||
</div>
|
||||
<div class="act">
|
||||
<img src="./assets/img/green-gizmos.jpg" alt="Green Gizmos" />
|
||||
<p>Green Gizmos</p>
|
||||
</div>
|
||||
<div class="act">
|
||||
<img src="./assets/img/john-alfred.jpg" alt="DJ John Alfred" />
|
||||
<p>DJ John Alfred</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
Before Width: | Height: | Size: 13 KiB |
Before Width: | Height: | Size: 937 KiB |
Before Width: | Height: | Size: 512 KiB |
Before Width: | Height: | Size: 5.4 KiB |
Before Width: | Height: | Size: 78 KiB |
Before Width: | Height: | Size: 58 KiB |
Before Width: | Height: | Size: 1 MiB |
|
@ -1,18 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<!-- CSS and Favicon -->
|
||||
<link rel="stylesheet" type="text/css" href="stylesheet.css">
|
||||
|
||||
<!-- Metadata -->
|
||||
<title>Ecofest</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1 class="title home">Ecofest</h1>
|
||||
|
||||
<div class="content">
|
||||
Ecofest is the environmentally-friendly music festival, taking place on the <strong>4-5th April, 2020</strong>.
|
||||
Find out about our acts <a href="acts.html">here</a>, get your tickets <a href="">here</a>, learn about how we're helping the environment <a href="">here</a>, and contact us <a href="">here</a>.
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,80 +0,0 @@
|
|||
/* Import "Bebas Neue" and "Open Sans" fonts from Google Fonts */
|
||||
@import url('https://fonts.googleapis.com/css?family=Bebas+Neue|Open+Sans&display=swap');
|
||||
|
||||
/* Simple browser reset */
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
html {
|
||||
/* Make the background never repeat and be centered at all times */
|
||||
background-image: url("./assets/img/bg.png");
|
||||
background-position: center center;
|
||||
background-repeat: no-repeat;
|
||||
background-attachment: fixed;
|
||||
background-size: cover;
|
||||
|
||||
/* Set a background colour to be displayed whilst the image is loading on slow connections */
|
||||
background-color: #212121;
|
||||
}
|
||||
|
||||
/* Base title styles */
|
||||
.title {
|
||||
color: #7ed957;
|
||||
font-family: 'Bebas Neue', cursive;
|
||||
font-size: 132px;
|
||||
margin-top: 75px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
/* Home page specific styles for the title class */
|
||||
.title.home {
|
||||
margin-left: 1050px;
|
||||
margin-top: 325px;
|
||||
}
|
||||
|
||||
/* Styles for the green content box used on most pages */
|
||||
.content {
|
||||
background-color: #7ed957;
|
||||
color: #212121;
|
||||
font-family: 'Open Sans', sans-serif;
|
||||
font-size: 24px;
|
||||
padding: 20px;
|
||||
margin-right: 50px;
|
||||
}
|
||||
|
||||
/* Styling to make hyperlinks orange and bold */
|
||||
a {
|
||||
color: #FF5722;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
/* Styling to underline hyperlinks when they are hovered over */
|
||||
a:hover {
|
||||
text-decoration: underline
|
||||
}
|
||||
|
||||
/* Styling for the svg of the back button, displayed on all pages
|
||||
exluding the home page */
|
||||
.back {
|
||||
height: 125px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
/* Styling that will get applied to both the back button and the title
|
||||
on every page, except from the home page. */
|
||||
.back && .title && :not(.home) {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
/* Styling for the array of acts displayed on the acts page */
|
||||
.acts {
|
||||
|
||||
}
|
||||
|
||||
/* Styling for each induvidual act within the acts array */
|
||||
.act {
|
||||
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
# [Hosted Version](https://ecofest.newtt.me/)
|
|
@ -1,82 +0,0 @@
|
|||
@import url('https://fonts.googleapis.com/css?family=Open+Sans|Playfair+Display&display=swap');
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
html {
|
||||
background-color: #000000;
|
||||
color: #ffffff;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h1, h2 { font-family: 'Playfair Display', serif; }
|
||||
|
||||
h1 {
|
||||
font-size: 48px;
|
||||
margin-bottom: 50px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 36px;
|
||||
}
|
||||
|
||||
p {
|
||||
font-family: 'Open Sans', sans-serif;
|
||||
font-weight: light;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
nav {
|
||||
list-style-type: none;
|
||||
overflow: hidden;
|
||||
margin-bottom: 50px;
|
||||
}
|
||||
|
||||
nav li {
|
||||
float: right;
|
||||
font-size: 18px;
|
||||
font-family: 'Open Sans', sans-serif;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
nav a {
|
||||
display: block;
|
||||
color: white;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
nav :not(.left) a:hover {
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
}
|
||||
|
||||
nav li.left {
|
||||
float: left;
|
||||
font-size: 36px;
|
||||
font-family: 'Playfair Display', serif;
|
||||
margin-top: 0px;
|
||||
}
|
||||
|
||||
div.images { margin-top: 75px; }
|
||||
|
||||
div.images img {
|
||||
height: 250px;
|
||||
width: 250px;
|
||||
margin-right: 40px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
font-family: 'Open Sans', sans-serif;
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
}
|
Before Width: | Height: | Size: 161 KiB |
Before Width: | Height: | Size: 19 KiB |
Before Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 26 KiB |
Before Width: | Height: | Size: 451 KiB |
|
@ -1,41 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Pet Planet</title>
|
||||
|
||||
<link type="text/css" rel="stylesheet" href="./assets/css/index.css">
|
||||
<link rel="icon" href="./assets/favicon.ico">
|
||||
<style type="text/css">
|
||||
p {
|
||||
margin: 20px 200px 75px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="description" content="Pet Planet is a family-run pet shop located in Ashford Highstreet." />
|
||||
<meta name="keywords" content="pets,dogs,cats,shop,ashford,highstreet" />
|
||||
<meta name="author" content="newt" />
|
||||
<meta name="viewport" content="width=device.width, initial-scale=1.0" />
|
||||
<meta property="og:title" content="Pet Planet" />
|
||||
<meta property="og:description" content="Pet Planet is a family-run pet shop located in Ashford Highstreet." />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://pet-planet.netlify.com/" />
|
||||
<meta property="og:image" content="https://pet-planet.netlify.com/assets/ogp.jpg" />
|
||||
</head>
|
||||
<body>
|
||||
<nav>
|
||||
<li class="left"><a href="index.html">Pet Planet</a></li>
|
||||
<li><a href="care.html">Care</a></li>
|
||||
<li><a href="products.html">Products</a></li>
|
||||
<li><a href="index.html">Home</a></li>
|
||||
</nav>
|
||||
|
||||
<h1>Caring for your pets</h1>
|
||||
|
||||
<h2>Cats</h2>
|
||||
<p>Some essential things you must do to care for your cat include things like getting them micro-chipped, neutering them, getting them a vet plan, keeping their vaccinations up to date, getting pet insurance, and providing plenty of playtime.</p>
|
||||
|
||||
<h2>Dogs</h2>
|
||||
<p>Some essential things you must do to care for your dog includes things like providing a clean living environment for uour dog, keeping fresh water available, giving them a quality diet, having them examined by a vet on a regular basis, provide ample opportunites to exrcise, and training them to follow simple commands.</p>
|
||||
</body>
|
||||
</html>
|
Before Width: | Height: | Size: 27 KiB |
Before Width: | Height: | Size: 39 KiB |
Before Width: | Height: | Size: 179 KiB |
|
@ -1,43 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Pet Planet</title>
|
||||
|
||||
<link type="text/css" rel="stylesheet" href="./assets/css/index.css">
|
||||
<link rel="icon" href="./assets/favicon.ico">
|
||||
<style type="text/css">
|
||||
.check-us-out {
|
||||
margin-top: 50px;
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="description" content="Pet Planet is a family-run pet shop located in Ashford Highstreet." />
|
||||
<meta name="keywords" content="pets,dogs,cats,shop,ashford,highstreet" />
|
||||
<meta name="author" content="newt" />
|
||||
<meta name="viewport" content="width=device.width, initial-scale=1.0" />
|
||||
<meta property="og:title" content="Pet Planet" />
|
||||
<meta property="og:description" content="Pet Planet is a family-run pet shop located in Ashford Highstreet." />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://pet-planet.netlify.com/" />
|
||||
<meta property="og:image" content="https://pet-planet.netlify.com/assets/ogp.jpg" />
|
||||
</head>
|
||||
<body>
|
||||
<nav>
|
||||
<li class="left"><a href="index.html">Pet Planet</a></li>
|
||||
<li><a href="care.html">Care</a></li>
|
||||
<li><a href="products.html">Products</a></li>
|
||||
<li><a href="index.html">Home</a></li>
|
||||
</nav>
|
||||
|
||||
<h1>Welcome to Pet Planet</h1>
|
||||
<p>We are a family-run pet shop located in Ashford Highstreet.</p>
|
||||
|
||||
<h1 class="check-us-out">Check us out</h1>
|
||||
<iframe width='250px' height='250px' id='mapcanvas' src='https://maps.google.com/maps?q=High%20Street,%20Ashford&t=&z=10&ie=UTF8&iwloc=&output=embed' frameborder='0' scrolling='no' marginheight='0' marginwidth='0'><div class="zxos8_gm"><a href="https://www.giantbomb.com/profile/mobilephones/blog/">here</a></div><div style='overflow:hidden;'><div id='gmap_canvas' style='height:100%;width:100%;'></div></div></iframe>
|
||||
|
||||
<br><br><br>
|
||||
<a href="mailto:insertemail@here.xyz" class="contact-us">Contact us.</a>
|
||||
</body>
|
||||
</html>
|
|
@ -1,37 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Pet Planet</title>
|
||||
|
||||
<link type="text/css" rel="stylesheet" href="./assets/css/index.css">
|
||||
<link rel="icon" href="./assets/favicon.ico">
|
||||
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="description" content="Pet Planet is a family-run pet shop located in Ashford Highstreet." />
|
||||
<meta name="keywords" content="pets,dogs,cats,shop,ashford,highstreet" />
|
||||
<meta name="author" content="newt" />
|
||||
<meta name="viewport" content="width=device.width, initial-scale=1.0" />
|
||||
<meta property="og:title" content="Pet Planet" />
|
||||
<meta property="og:description" content="Pet Planet is a family-run pet shop located in Ashford Highstreet." />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://pet-planet.netlify.com/" />
|
||||
<meta property="og:image" content="https://pet-planet.netlify.com/assets/ogp.jpg" />
|
||||
</head>
|
||||
<body>
|
||||
<nav>
|
||||
<li class="left"><a href="index.html">Pet Planet</a></li>
|
||||
<li><a href="care.html">Care</a></li>
|
||||
<li><a href="products.html">Products</a></li>
|
||||
<li><a href="index.html">Home</a></li>
|
||||
</nav>
|
||||
|
||||
<h1>Products</h1>
|
||||
<p>We stock many high quality products in our store.<br>Check them out here.</p>
|
||||
|
||||
<div class="images">
|
||||
<img src="./assets/img/pedigree_dogfood.jpg" alt="Pedigree Dogfood">
|
||||
<img src="./assets/img/splaker_leash.jpg" alt="Splaker Dog Leash">
|
||||
<img src="./assets/img/mouse_toy.jpg" alt="Mouse Toy">
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1 +0,0 @@
|
|||
# [Hosted Version](https://petplanet.newtt.me/)
|
|
@ -1,2 +0,0 @@
|
|||
Name: adhas
|
||||
Quiz result: 0/3
|
|
@ -1,2 +0,0 @@
|
|||
Name: Sam
|
||||
Quiz result: 2/3
|
|
@ -1,2 +0,0 @@
|
|||
Name: newt
|
||||
Quiz result: 3/3
|
|
@ -1,2 +0,0 @@
|
|||
Name: test
|
||||
Quiz result: 1/3
|
|
@ -1 +0,0 @@
|
|||
Name: John DoeGender: MaleForm: 9AA1
|
|
@ -1,16 +0,0 @@
|
|||
<div align="center">
|
||||
<h1>year 9</h1>
|
||||
</div>
|
||||
|
||||
### Python
|
||||
|
||||
- [Encryption](encryption)
|
||||
- [Caesar Cipher Decrypter](encryption/Caesar%20Cipher%20Decrypter.py)
|
||||
- [Caesar Cipher Encrypter](encryption/Caesar%20Cipher%20Encrypter.py)
|
||||
- [Enkodo Cipher (own creation)](encryption/Enkodo%20Cipher.py)
|
||||
- [Python Challenges](python%20challenges)
|
||||
|
||||
### Web
|
||||
|
||||
- [Eco Fest](eco%20fest)
|
||||
- [Pet Planet](pet%20planet)
|
|
@ -1,9 +1,9 @@
|
|||
<div align="center">
|
||||
<img height="256" src="../../assets/ri.jpg" alt="">
|
||||
<img height="256" src="../../assets/royal-institute.jpg" alt="">
|
||||
<h1>royal institute computer science masterclass 2021</h1>
|
||||
</div>
|
||||
|
||||
### Uploaded Lessons
|
||||
|
||||
- [Computer Science and Social Media](computer%20science%20and%20social%20media)
|
||||
- [From Ancient Babylon to Quantum Computing](from%20ancient%20babylon%20to%20quantum%20computing)
|
||||
- [Computer Science and Social Media](computer%20science%20and%20social%20media)
|
||||
- [From Ancient Babylon to Quantum Computing](from%20ancient%20babylon%20to%20quantum%20computing)
|
||||
|
|