Unsorted 2
autotrump.py
import random
#1mb of text data taken from speeches made by Donald Trump
#at various points in his 2016 campaign for President of the United States:
#https://github.com/ryanmcdermott/trump-speeches
trump = open('trump.txt', encoding='utf8').read()
everyWordSaid = trump.split()
def make_pairs(listOfAllWordsSaid):
#for all the words said, stopping at second last:
for i in range(len(listOfAllWordsSaid)-1):
#yield = stream results on the fly, without waiting
#for the function to complete, then return the values:
yield (listOfAllWordsSaid[i], listOfAllWordsSaid[i+1])
#^^this will get the next word that follows.. i.e. i+1!
pairs = make_pairs(everyWordSaid)
####got my pairs, now put them into a dictionary, joining 'like' words:
word_dict = {}
for word_1, word_2 in pairs:
if word_1 in word_dict.keys():
word_dict[word_1].append(word_2)
else:
word_dict[word_1] = [word_2]
#job done. now lets make a sentence, starting with a capital:
first_word = random.choice(list(word_dict.keys()))
while first_word.islower():
first_word = first_word = random.choice(list(word_dict.keys()))
sentence = [first_word]
word_length = 10
#for the rest of the sentence, take a value from the previous word key:
for i in range(word_length):
sentence.append(random.choice(word_dict[sentence[-1]]))
print(' '.join(sentence))
block chain.py
import hashlib
import uuid
#--------------------------------BLOCK:
class Block(object):
def __init__(self, data=None, previous_hash=None):
self.identifier = uuid.uuid4().hex
self.nonce = None
self.data = data
self.previous_hash = previous_hash
def hash(self, nonce=None):
nonce = nonce or self.nonce
message = hashlib.sha256()
message.update(self.identifier.encode('utf-8'))
message.update(str(nonce).encode('utf-8'))
message.update(str(self.data).encode('utf-8'))
message.update(str(self.previous_hash).encode('utf-8'))
return message.hexdigest()
@staticmethod
def hash_is_valid(the_hash):
return the_hash.startswith('0000')
@property
def mined(self):
return self.nonce is not None
def mine(self):
the_nonce = self.nonce or 0
while True:
the_hash = self.hash(nonce=the_nonce)
if self.hash_is_valid(the_hash):
self.nonce = the_nonce
return
else:
the_nonce += 1
def update_data(self, data):
self.data = data
self.nonce = None
def __repr__(self):
return 'Block<Hash: {}, Nonce: {}>'.format(self.hash(), self.nonce)
#--------------------------------BLOCKCHAIN:
class Blockchain(object):
def __init__(self):
self.head = None
self.blocks = {}
def add_block(self, new_block):
previous_hash = self.head.hash() if self.head else None
new_block.previous_hash = previous_hash
self.blocks[new_block.identifier] = {
'block': new_block,
'previous_hash': previous_hash,
'previous': self.head,
}
self.head = new_block
@property
def broken(self):
return self.block_is_broken(self.head)
def block_is_broken(self, block):
previous = self[block.identifier]['previous']
previous_hash = self[block.identifier]['previous_hash']
previous_is_broken = (previous_hash != previous.hash() or self.block_is_broken(previous)) if previous else False
return previous_is_broken or not block.mined
def repair(self):
print('Repairing blockchain starting from head: {}'.format(self.head.identifier))
self.repair_block(self.head)
def repair_block(self, block):
previous = self[block.identifier]['previous']
if previous and self.block_is_broken(previous):
print('When trying to repair block {}, found that previous block {} also needed repair'.format(
block.identifier,
previous.identifier,
))
self.repair_block(previous)
self[block.identifier]['previous_hash'] = previous.hash()
if self.block_is_broken(block):
print('Repairing block {}'.format(block.identifier))
block.mine()
def __len__(self):
return len(self.blocks)
def __repr__(self):
num_existing_blocks = len(self)
return 'Blockchain<{} Blocks, Head: {}>'.format(
num_existing_blocks,
self.head.identifier if self.head else None
)
def __getitem__(self, identifier):
return self.blocks[identifier]
#--------------------------------MAIN:
chain = Blockchain()
first = Block('first')
second = Block('second')
third = Block('third')
chain.add_block(first)
chain.add_block(second)
chain.add_block(third)
first.update_data('so broke')
print("Chain broken? " + str(chain.broken)) # True
chain.repair()
print("Chain broken? " + str(chain.broken)) # False
drawing in tkinter.py
from tkinter import *
import random
import time
window = Tk()
window.title = "Ball"
canvas = Canvas(width=640, height=480)
canvas.pack()
class Ball:
def __init__(self, canvas):
self.canvas = canvas
#create_oval (x,y in top left.. x,y in bottom right):
self.id = canvas.create_oval(10, 10, 25, 25, fill="salmon")
self.canvas.move(self.id, 320, 240) #middle
def shift_right(self):
self.canvas.move(self.id, +1, 0)
ball = Ball(canvas)
#mainloop() blocks / halts execution of python program.
#update_idletasks() and update() do not block -
#execution continues after those methods.
#therefore, tk.mainloop() can be thought of as:
#while True:
# tk.update_idletasks()
# tk.update()
while True:
ball.shift_right()
window.update_idletasks()
window.update()
time.sleep(0.01)
genetic algorithm.py
from random import randint, random
GLOBAL_PERCENT = 100
def individual(length, min, max):
'Create a member of the population.'
return [ randint(min,max) for x in range(length) ]
def population(count, length, min, max):
"""
Create a number of individuals (i.e. a population).
count: the number of individuals in the population
length: the number of values per individual
min: the minimum possible value in an individual's list of values
max: the maximum possible value in an individual's list of values
"""
return [ individual(length, min, max) for x in range(count) ]
def fitness(individual, target):
"""
Determine the fitness of an individual. Higher is better.
individual: the individual to evaluate
target: the target number individuals are aiming for
"""
sumTotal = 0
for x in individual:
sumTotal = sumTotal + x
return abs(target-sumTotal)
def grade(pop, target):
'Find average fitness for a population.'
summed = 0
for y in (fitness(x, target) for x in pop):
summed = summed + y
return abs(GLOBAL_PERCENT - (summed / len(pop) * 1.0))
def evolve(pop, target, retain=0.2, random_select=0.05, mutate=0.01):
graded = [ (fitness(x, target), x) for x in pop]
graded = [ x[1] for x in sorted(graded)]
retain_length = int(len(graded)*retain)
parents = graded[:retain_length]
# randomly add other individuals to
# promote genetic diversity
for individual in graded[retain_length:]:
if random_select > random():
parents.append(individual)
# mutate some individuals
for individual in parents:
if mutate > random():
pos_to_mutate = randint(0, len(individual)-1)
# this mutation is not ideal, because it
# restricts the range of possible values,
# but the function is unaware of the min/max
# values used to create the individuals,
individual[pos_to_mutate] = randint(
min(individual), max(individual))
# crossover parents to create children
parents_length = len(parents)
desired_length = len(pop) - parents_length
children = []
while len(children) < desired_length:
male = randint(0, parents_length-1)
female = randint(0, parents_length-1)
if male != female:
male = parents[male]
female = parents[female]
half = len(male) // 2
child = male[:half] + female[half:]
children.append(child)
parents.extend(children)
return parents
#-------------------------------------------------------------------
#--------set constants:
#what we want the values in our individual lists to add up to, default 371:
target = 371
#number of individuals in a population, default 100:
p_count = 100
#number of values per individual, default 6:
i_length = 6
#min vaule in an individuals list, default: 0
i_min = 0
#max vaule in an individuals list, default: 100
i_max = 100
#passes in evolution, default: 100
evolution_passes = 100
#--------create population:
p = population(p_count, i_length, i_min, i_max)
#--------parent history:
population_history = [p]
#--------determines starting fitness of population:
fitness_history = [grade(p, target)]
#--------loop through evolution cycle, evolving and grading fitness each pass:
for i in range(evolution_passes):
p = evolve(p, target)
population_history.append(p)
fitness_history.append(grade(p, target))
#--------print fitness history:
for data in fitness_history:
print("Health: " + str(data) + "%")
#for data in population_history:
# print(data)
power ball.py
import random
#--------------------------------------------------
stop_on_jackpot = True
powerplay = True
reset_max = True
print_every = 1 #assuming 1 dollar per round
jackpot_value = 1300000000
#--------------------------------------------------
cash_to_spend = 1000
#THESE NEED ADJUSTING TO BE MORE REALISTIC!
#PLACEHOLDERS ONLY ATM
prizes = {(0, False):0,
(1, False):0,
(2, False):0,
(3, False):7,
(4, False):100,
(5, False):1000000,
(0, True):4,
(1, True):4,
(2, True):7,
(3, True):100,
(4, True):50000,
(5, True):jackpot_value}
ticket_numbers = set(range(5))
ticket_powerball = 0
balls = tuple(range(40))
powerballs = tuple(range(40))
winnings = 0
spent = 0
max_prize = 0
jackpot = False
powerplay_draw = 0
powerplay_multiplier = 0
iterations = 0
while not jackpot or not stop_on_jackpot:
chosen_balls = random.sample(balls, 5)
chosen_powerball = random.choice(powerballs)
numbers_hit = sum(1 for x in chosen_balls if x in ticket_numbers)
powerball_hit = chosen_powerball == ticket_powerball
matches = (numbers_hit, powerball_hit)
jackpot = matches == (5, True)
if powerplay:
if jackpot_value > 150000000:
powerplay_draw = random.randint(1,42)
else:
powerplay_draw = random.randint(1,43)
if powerplay_draw <= 24:
powerplay_multiplier = 2
elif powerplay_draw <= 24+13:
powerplay_multiplier = 3
elif powerplay_draw <= 24+13+3:
powerplay_multiplier = 4
elif powerplay_draw <= 24+13+3+2:
powerplay_multiplier = 5
else:
powerplay_multiplier = 10
if jackpot:
powerplay_multiplier = 1
elif matches == (5,False):
powerplay_multiplier = 2
spent += 3
else:
powerplay_multiplier = 1
spent += 2
prize = prizes[matches] * powerplay_multiplier
winnings += prize
max_prize = max(prize, max_prize)
iterations += 1
if iterations % print_every == 0 or jackpot:
stats = 'spent:{:,}, winnings:{:,}, net:{:,} max_win:{:,}'.format(
spent, winnings, winnings-spent, max_prize
)
print(stats)
if reset_max:
max_prize = 0
if spent > cash_to_spend:
break
prime numba gen.py
#Using terminal: Python36-32\Scripts\pip install numba
from numba import vectorize
from math import sqrt
#http://numba.pydata.org/numba-doc/latest/user/vectorize.html
@vectorize(["int32(int32)"], target = "parallel")
def is_prime(n):
for i in range(3,round(sqrt(n))+1,2):
if n % i == 0:
return 0
return 1
def main():
f = open("prime.html","a")
f.write("2\n") #file write
f.write("3\n") #file write
n = 6 #..or can skip ahead here if you wish
while True:
if is_prime(n-1):
f.write(str(n-1)+"\n")
if is_prime(n+1):
f.write(str(n+1)+"\n")
n+=6
main()
#check prime.html in same folder for list of prime numbers
py_game.py
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
is_blue = True
x = 30
y = 30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_blue = not is_blue
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 3
if pressed[pygame.K_DOWN]: y += 3
if pressed[pygame.K_LEFT]: x -= 3
if pressed[pygame.K_RIGHT]: x += 3
screen.fill((0, 0, 0))
if is_blue:
color = (0, 128, 255)
else:
color = (255, 100, 0)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.display.flip()
clock.tick(60)