text stringlengths 37 1.41M |
|---|
import random,sys
from io import StringIO
def mazeGen(rows,cols):
try :
rows -= 1
cols -= 1
except (ValueError, IndexError) :
print("2 command line arguments expected...")
print("Usage: python maze.py rows cols")
print(" minimum rows >= 10 minimum cols >= 20")
quit( )
try :
assert rows >= 9 and cols >= 19
except AssertionError :
print("Error: maze dimensions must be at least 20 x 10...")
print("Usage: python maze.py rows cols")
print(" minimum rows >= 10 minimum cols >= 20")
quit( )
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
(blank, roof, wall, corner) = ' -|+'
M = str(roof * int(cols / 2))
n = random.randint(1, (int(cols / 2)) * (int(rows / 2) - 1))
for i in range(int(rows / 2)) :
e = s = t = ''
N = wall
if i == 0 :
t = '@' # add entry marker '@' on first row first col only
# end if
for j in range(int(cols / 2)) :
if i and(random.randint(0, 1) or j == 0) :
s += N + blank
t += wall
N = wall
M = M[1 : ] + corner
else :
s += M[0] + roof
if i or j :
t += blank # add blank to compensate for '@' on first row only
# end if
N = corner
M = M[1 : ] + roof
# end if / else
n -= 1
t += ' #' [n == 0]
# end for
if cols & 1 :
s += s[-1]
t += blank
e = roof
# end if
print(s + N + '\n' + t + wall)
# end for
if rows & 1 :
print(t + wall)
# end if
print(roof.join(M) + e + roof + corner)
sys.stdout = old_stdout
strn = str(mystdout.getvalue())
return strn
rows = 35
cols = 50
mazestring = mazeGen(rows,cols)
print(mazestring) |
import sqlite3
def create_database():
sqlite_file= 'databases.db'
table_name= 'users'
id_column= 'id_column'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
# c.execute('''DROP TABLE IF EXISTS users''')
c.execute('''CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY AUTOINCREMENT , username TEXT NOT NULL , password TEXT NOT NULL )''')
"""
c.execute('''CREATE TABLE IF NOT EXISTS {tn}({nf}{ft})'''.format(tn = table_name, nf = id_column, ft ='INTEGER PRIMARY KEY ' ))
#ADD NEXT COULUMN
new_column = 'username'
columnType = 'TEXT'
c.execute('''ALTER TABLE {tn} ADD COLUMN "{cn}" {ct}'''.format(tn= table_name, cn= new_column, ct= columnType))
new_column = 'password'
columnType = 'TEXT'
c.execute('''ALTER TABLE {tn} ADD COLUMN "{cn}"{ct}'''.format(tn = table_name, cn = new_column, ct = columnType))
#c.execute('''Select name from table_name''')
"""
conn.execute('''CREATE TABLE IF NOT EXISTS usersaves(id_column INTEGER , key_word TEXT, timeStap DATE,FOREIGN KEY(id_column) REFERENCES users(id_column));''')
print('Database and table(s) created!')
conn.commit()
conn.close()
def showEntries():
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute('''SELECT * FROM users''')
print(c.fetchall())
create_database() |
import pandas as pd
if __name__ == "__main__":
data = pd.read_csv("data/CRDC2013_14.csv", encoding="Latin-1")
races = ["HI", "AM", "AS", "HP", "BL", "WH", "TR"]
genders = ["F", "M"]
data["total_enrollment"] = data["TOT_ENR_M"] + data["TOT_ENR_F"]
all_enrollment = data["total_enrollment"].sum()
totals = {}
for race in races:
race_f = "SCH_ENR_" + race + "_" + genders[0]
race_m = "SCH_ENR_" + race + "_" + genders[1]
total_race = "total_" + race
totals[total_race] = 100*(data[race_m].sum() + data[race_f].sum()) / all_enrollment
for k, v in totals.items():
print (str(k) + " => " + str(v)) |
#Made on May 27th, 2017
#Made by SlimxShadyx
#Editted by CaptMcTavish, June 17th, 2017
#Dice Rolling Simulator
import random
global user_exit_checker
user_exit_checker="exit"
def start():
print "Welcome to dice rolling simulator: \nPress Enter to proceed"
raw_input(">")
result()
def bye():
print "Thanks for using the Dice Rolling Simulator! Have a great day! =)"
def result():
#user_dice_chooser No idea how this got in here, thanks EroMonsterSanji.
print "\r\nGreat! Begin by choosing a die! [6] [8] [12]?\r\n"
user_dice_chooser = raw_input(">")
user_dice_chooser = int(user_dice_chooser)
if user_dice_chooser == 6:
dice6()
elif user_dice_chooser == 8:
dice8()
elif user_dice_chooser == 12:
dice12()
else:
print "\r\nPlease choose one of the applicable options!\r\n"
result()
def dice6():
dice_6 = random.randint(1,6)
print "\r\nYou rolled a " + str(dice_6) + "!\r\n"
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker=="roll":
start()
else:
bye()
def dice8():
dice_8 = random.randint(1,8)
print "\r\nYou rolled a " + str(dice_8) + "!"
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker=="roll":
start()
else:
bye()
def dice12():
dice_12 = random.randint(1,12)
print "\r\nYou rolled a " + str(dice_12) + "!"
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker=="roll":
start()
else:
bye()
start()
|
from os.path import join, isfile
from os import listdir
src_dir_ = 'original_size'
def count_files(src_dir):
dirs = [folder for folder in listdir(src_dir) if not isfile(join(src_dir, folder))]
count = 0
for dir_ in dirs:
dir_ = join(src_dir, dir_)
classes = listdir(dir_)
for class_ in classes:
file_dir = join(dir_, class_)
# print(file_dir)
files = listdir(file_dir)
# print(files)
count = count + len(files)
return count
print(count_files(src_dir_))
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 09:39:43 2019
@author: HP
"""
def swap(a,b):
temp=arr[a]
arr[a]=arr[b]
arr[b]=temp
def InsertionSort():
for i in range(1,len(arr)):
j=i
while(arr[j-1]>arr[j] and j-1>=0):
swap(j-1,j)
j=j-1
arr=[5,7,8,2,1,7,10,13]
InsertionSort()
print(arr) |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 17:19:11 2019
@author: HP
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 16:50:16 2019
@author: HP
"""
#class Node1:
# def __init__(self,data):
# self.key=data
# self.next=None
#
class Node:
def __init__(self,data):
self.key=data
self.left_child=None
self.right_child=None
#class LinkedList:
#
# def __init__(self):
# self.head=None
# self.len=0
#
# def push(self,data):
# new_node=Node1(data)
# self.len+=1
# new_node.next=self.head
# self.head=new_node
#
# def pop(self):
# if self.head!=None:
# self.len-=1
# self.head=self.head.next
class Tree:
def __init__(self):
self.root=None
def BuildTree(self,node,i,c):
new_node=Node(arr[i])
if self.root==None:
self.root=new_node
if c=='l':
node.left_child=new_node
elif c=='r':
node.right_child=new_node
else:
new_node=Node(arr[i])
if c=='l':
node.left_child=new_node
elif c=='r':
node.right_child=new_node
if 2*i+1<len(arr):
list.BuildTree(new_node,2*i+1,'l')
if 2*i+2<len(arr):
list.BuildTree(new_node,2*i+2,'r')
def Print(self,node):
if node==None:
return
print(node.key)
list.Print(node.left_child)
list.Print(node.right_child)
list=Tree()
arr=[1,2,3,4,5,6,7,8,9]
list.BuildTree(None,0,None)
#lst=LinkedList()
#lst.push(list.root)
#while lst.len!=0:
# print(lst.head.key.key)
# node=lst.head
# lst.pop()
# if node.key.right_child!=None:
# lst.push(node.key.right_child)
# if node.key.left_child!=None:
# lst.push(node.key.left_child)
list.Print(list.root)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 12:12:41 2019
@author: HP
"""
x=[3,4,5,2,1]
print(zip(x,range(len(x)))) |
# Dictionaries - a dictionary is an unordered set of key-value pairs
dict1 = {} # creating an empty dictionary
dict1 = {"Vendor": "Cisco", "Model": "2600", "IOS": "12.4", "Ports": "4"}
dict1["IOS"] # returns "12.4"; extracting a value for a specified key
dict1["IOS"] = "12.3" # modifies an existing key-value pair
dict1["RAM"] = "128" # adds a new key-value pair to the dictionary
del dict1["Ports"] # deleting a key-value pair from the dictionary
len(dict1) # returns the number of key-value pairs in the dictionary
"IOS" in dict1 # verifies if "IOS" is a key in the dictionary
"IOS2" not in dict1 # verifies if "IOS2" is not a key in the dictionary
# Dictionaries - methods
dict1.keys() # returns a list having the keys in the dictionary as elements
dict1.values() # returns a list having the values in the dictionary as elements
dict1.items() # returns a list of tuples, each tuple containing the key and value of each dictionary pair
|
# Todo: Use ABC to do proper abstract classes
class Sync:
"""Defines a process with synchronous characteristics"""
def __init__(self):
# List of modules to clock with this module
self.submodules = []
def clock(self):
"""Handle clocking to define new outputs"""
# By definition on_clock for this module must be handled before submodules
# May change to pre_submodule and post_submodule if necessary since on_clock
# being after submodules somewhat also makes more sense
self.on_clock()
for module in self.submodules:
module.clock()
def on_clock(self):
"""Default implementation just does nothing"""
pass
class Register(Sync):
"""Defines a helper for defining a pipeline stage register"""
def __init__(self, reset=None, hack=False):
super().__init__()
self.hack = hack
self.next = None
self.value = reset
self.already_set = False
def set(self, value):
if self.hack:
raise RuntimeError("Finding hack")
if self.already_set:
raise RuntimeError("Multiple writes to same reg attempted")
self.already_set = True
self.next = value
def get(self):
return self.value
def on_clock(self):
"""Clocks the pipeline register sending input to output value"""
if self.already_set:
# Only update regs that get set
self.value = self.next
# Allow a new value to be set
self.already_set = False
def __str__(self):
return f"{{value = {self.value}, next={self.next}}}"
class Fifo(Sync):
# TODO: Write a memory implementation and make this use that since that will have more
# real memory like semantics (reads are "instant", writes are at least 1 cycle later)
"""A buffer that allows filling and reading sequentially at different rates"""
def __init__(self, capacity=1024):
super().__init__()
# HACK: We use this to allow setting initial state and capacity
if isinstance(capacity, int):
self.capacity = capacity
# Don't think this needs to be registered for now (if reads and writes to a single location need)
# to be double pumped this will change...
self.items = [0] * capacity
self.wptr = Register(0)
self.rptr = Register(0)
self.size = Register(0)
elif isinstance(capacity, list):
self.capacity = len(capacity)
self.items = capacity.copy()
# Start full so write pointer has "wrapped around" in theory
self.wptr = Register(0)
# Start full and unread so reads start at 0 too
self.rptr = Register(0)
# Full so size == capacity
self.size = Register(capacity)
# Goes up +1 for writes, -1 for reads, decides how size changes
# during a clock
self.incr = 0
# Make sure all our submodules update properly
#self.submodules += self.items
self.submodules += [self.wptr, self.rptr, self.size]
def read(self):
# Todo: Handle forwarding somehow...
if self.size.get() == 0:
raise RuntimeError("Fifo was empty on read")
# We will lose an entry during reads (space should be free immediately, but will be delayed)
# a clock because no forwarding or whatever
self.incr -= 1
# We need multiple writes so cache it locally
rptr = self.rptr.get()
# read the actual value
result = self.items[rptr]
# Attempt to increment
rptr += 1
# Handle overflow wraparound
if rptr >= self.capacity:
rptr = 0
# Store the read pointer location back
self.rptr.set(rptr)
return result
def write(self, value):
# TODO: Handle forwarding somehow...
if self.size.get() == self.capacity:
raise RuntimeError("Fifo was full on write")
# We will gain an entry during writes (valid next clock since no forwarding)
self.incr += 1
# Store locally for same reason as read
wptr = self.wptr.get()
self.items[wptr] = value
wptr += 1
if wptr >= self.capacity:
wptr = 0
self.wptr.set(wptr)
def is_full(self):
return self.size.get() == self.capacity
def is_empty(self):
return self.size.get() == 0
def flush(self):
# Checking to make sure flush isn't attempted after read/write is done by rptr and wptr themselves!
self.rptr.set(0)
self.wptr.set(0)
# HACK: We really should handle this more like actual RTL sim stuff
self.incr = -self.size.get()
def on_clock(self):
# Handle the fact that we want multiple write detection but size would be updated based on which combination of read and write enables were high
self.size.set(self.size.get() + self.incr)
# Make sure self.incr is reset so it doesn't fill if nothing happens
self.incr = 0
class Instr:
def __init__(self):
self.in_registers = []
self.out_registers = []
def __str__(self) -> str:
# Print the class name and registers
return f"{type(self).__name__}(in_registers={self.in_registers}, out_registers={self.out_registers})"
class Nop(Instr):
def __init__(self):
"""No operation"""
super().__init__()
class Load(Instr):
def __init__(self, target):
"""Create a 'load' into target"""
super().__init__()
self.out_registers += target,
class Store(Instr):
def __init__(self, source):
"""Create a 'store' from source"""
super().__init__()
self.in_registers += source,
class Add(Instr):
def __init__(self, r1, r2):
"""Stores r1+r2 in r1"""
super().__init__()
self.in_registers = [r1, r2]
self.out_registers = [r1]
class Abort(Instr):
def __init__(self):
"""Forces fetch to only return Nops after this"""
super().__init__()
class FetchStage(Sync):
def __init__(self, memory):
super().__init__()
# Store a reference to "instruction memory"
self.memory = memory
# Keep track of local PC for stuff
self.pc = Register(reset=0)
# TODO: If the PC is changed we need to flush the fifo
# self.pc_set = False
# Fifo for holding instructions ready for decode phase
self.fifo = Fifo()
# "Exported" signal to signify we need to wait because next stage not ready
self.stall = Register(False)
self.submodules += [self.pc, self.fifo, self.stall]
def eval(self):
"""Eval performs the brunt of the work of a stage in the pipeline"""
# If we're not stalled (because say decoder needs more words for current instruction)
if not self.stall.get():
if not self.fifo.is_full():
# Check pc for validity
if self.pc.get() < len(self.memory):
# Read the next entry from "instruction memory" while there's space and pc is valid
self.fifo.write(self.memory[self.pc.get()])
# If there's space we can increment the "PC" which for now is just a "fetch" pointer
self.pc.set(self.pc.get()+1)
else:
# Fill the buffer with noops because we don't want to keep reporting stalls
self.fifo.write(Nop())
class RegisterSlot(Sync):
"""Represents a register slot in a renamable file"""
def __init__(self):
super().__init__()
# The register itself
self.reg = Register(0)
# Flag set when register is allocated during decode (indicating it cannot be used)
self.allocated = Register(False)
# Flag set when register is written by EU (indicating dependents can dispatch)
self.valid = Register(False)
# Index of real register that this one is mapped to
# self.index = Register(0)
self.submodules += [self.reg, self.allocated, self.valid]
def set_valid(self, value):
if self.allocated.get() == False:
raise RuntimeError("Cannot make an unallocated register valid")
# TODO: This is probably dumb since in reality you might not constantly be churning to a new allocation? idk maybe you have to be to make any of this work?
if self.valid.get() == True:
raise RuntimeError("Tried to set a value for a register that's already been written")
self.reg.set(value)
self.valid.set(True)
def is_valid(self):
return self.valid.get()
def is_allocated(self):
return self.allocated.get()
def allocate(self):
self.allocated.set(True)
self.valid.set(False)
def get(self):
if not self.is_allocated():
raise RuntimeError("Tried to read unallocated register value")
if not self.is_valid():
raise RuntimeError("Tried to read unset register value (non-valid)")
return self.reg.get()
def __str__(self):
return f"RegisterSlot(reg = {self.reg}, allocated = {self.allocated}, valid = {self.valid})"
class DecodeStage(Sync):
"""Decode just handles performing register renaming and filling the dispatch queue for the dispatch unit"""
def __init__(self, fetch):
super().__init__()
# Store reference to the fetch stage so we can fetch and fill up the queue in eval
self.fetch = fetch
# TODO: Support changing dispatch queue capacity
# Dispatch queue holds instructions from fetch after register renaming has been performed
self.dispatch_queue = Fifo(4)
# Holds our collection of rename backing registers
# (in real hardware this would probably be some sort of fifo with random access or something) but this is far easier to integrate with our Sync
# submodule system (since RegisterSlots being shoved into a fifo at reset can't be easily clocked for now)
self.register_file = [RegisterSlot() for _ in range(32)]
# "Fifo" used to hold indexes of unallocated registers to use in future mappings (starts with all but the initial mapping)
self.unallocated = list(range(8, 32))
# Mark allocated and valid the initial register mappings
for i in range(8):
# Hack to overwrite without clock (instead of making reset valid)
register = self.register_file[i]
register.allocated.value = True
register.valid.value = True
#register.index.value = i
# Mapping of "named" register to their actual slot
self.name_map = list(range(8))
# Update dispatch queue during clocks
self.submodules += self.dispatch_queue,
# Update each register in the register file on clock
self.submodules += self.register_file
def eval(self):
# We have to stall ourselves if we run out of target registers to use as renaming targets, since we cannot clear this until downstream loads free up the allocation
# otherwise we will pull the next instruction to "decode" and rename, but there will be no registers to use anymore
# I think real hardware has a saner idea of how to free up registers to avoid this (pushing stalls to later stages and using unrenamed registers), however if we don't
# always assume that a rename target after decode is free, I cannot think of a good solution to solve the interdependency right now
if len(self.unallocated) > 0:
# We cannot dispatch so do not fetch
if not self.dispatch_queue.is_full():
# We cannot fetch new instructions when the fetch fifo is empty
if not self.fetch.fifo.is_empty():
# Read an instruction
next_inst = self.fetch.fifo.read()
# store original print for output later
inst_orig_debug = str(next_inst)
# Rename the inputs first since the output renaming will screw up our map
for (i, unrenamed_input) in enumerate(next_inst.in_registers):
next_inst.in_registers[i] = self.name_map[unrenamed_input]
# Theoretically loads "free up" a previously allocated register, since future instructions will not be able to name the previous register anymore to access it
# however the next load in a real processor (and likely even here) can easily be decoded before the previous instructions depending on it have finished dispatching
# meaning that the "allocated+valid" combination we need to free up a register will not be possible
# For now we assume that we will never run without enough allocatable registers (in this case we only have self modifying instructions so that number is just 1)
for (i,unrenamed_output) in enumerate(next_inst.out_registers):
# Loads pull a new register free and change our name target
new_name = self.unallocated.pop()
# Get the register and set it as allocated and invalid
reg = self.register_file[new_name]
print(f"Attempting to allocate register #{new_name}, reg {reg}")
reg.allocate()
print(f"Allocated register #{new_name}, reg {reg}")
# Rename the register for future uses
self.name_map[unrenamed_output] = new_name
# Rename the output of the instruction
next_inst.out_registers[i] = new_name
# HACK: Make aborts depend on every value before them that's been allocated
# TODO: Above
# Now that the instruction has had inputs and outputs renamed properly we can send it for dispatch
self.dispatch_queue.write(next_inst)
print(f"Decoded {inst_orig_debug} to {next_inst}")
else:
print("Decode is stalled on fetch queue being empty")
else:
print("Decode is stalled on dispatch queue being full")
else:
print("Decode is stalled on no unallocated registers")
class ExecutionUnit(Sync):
"""Represents an execution unit that can process inputs when dependencies are valid and mark outputs as valid"""
def __init__(self, decode, name="Unnamed"):
super().__init__()
# Store decode stage to access register file
self.decode = decode
self.name = name
# Stores current inputs and outputs, updated on fetch from queue which happens when non-empty and output gets written
self.inputs = []
self.outputs = []
# Queue of instructions to potentially execute
self.queue = Fifo(4)
self.submodules += [self.queue]
def eval(self):
# When the inputs are empty we know that this is fresh after reset and we should try to execute more instructions
if len(self.inputs) == 0:
# Cannot execute if nothing has been dispatched to us yet
if not self.queue.is_empty():
# Read a dispatched instruction
instr = self.queue.read()
# Fill our inputs and outputs
self.inputs = instr.in_registers
self.outputs = instr.out_registers
else:
print(f"Execution unit {self.name} is stalled on dispatch")
return
# Keep track of failures and stop trying if we hit one
has_failed = False
# Cannot execute if our input registers are not valid yet
for input in self.inputs:
if self.decode.register_file[input].is_valid() == False:
print(f"Execution unit {self.name} (writing to {self.outputs}) is stalled on input reg {input} becoming valid")
has_failed = True
break
# Theoretically we should check if we can write our output yet somehow to allow future support for stalling in EUs instead of decode
if not has_failed:
# If all of our inputs are valid we can now write to our outputs
print(f"Execution unit {self.name} is writing to {self.outputs}")
for output in self.outputs:
# We don't actually write a value (which is what the argument takes), but set_valid(0) looks like setting invalid
# TODO: Rename method or something so above doesn't happen
self.decode.register_file[output].set_valid(1)
print(f"Register written to is {self.decode.register_file[output]}")
# At this point we can say the instruction has been "executed" and the EU's resources are freed up to handle another
# Clear inputs and outputs which represent not having anything yet and needing to fetch the next
self.inputs.clear()
self.outputs.clear()
class DispatchStage(Sync):
"""Dispatches instructions to execution units"""
def __init__(self, decode):
"""decode is a module that provides the instruction with it's list of input and output registers (corrected after register renaming)"""
super().__init__()
# Store decode to pull instructions in eval
self.decode = decode
# TODO: Move ExecutionUnits to a seperate argument or something
self.load_store_units = [ExecutionUnit(decode, "Load_Store_0")]
self.arithmetic_units = [ExecutionUnit(decode, "ALU_0")]
# We have to potentially hold an instruction since if we get stalled we cannot put it back in the dispatch queue to try again
self.stall_hold = None
self.submodules += self.load_store_units
self.submodules += self.arithmetic_units
def eval(self):
# Try to pull a new instruction or use our current stall instruction if it exists
next_inst = self.stall_hold
# If no stall instruction exists we have to try and pull a new one from the dispatch queue
if next_inst is None:
# Must not be empty first though
if not self.decode.dispatch_queue.is_empty():
next_inst = self.decode.dispatch_queue.read()
else:
print("Dispatch stage stalled on empty dispatch queue")
if next_inst is not None:
self.have_inst(next_inst)
self.post_eval()
def have_inst(self, next_inst):
# We have a valid instruction to try and dispatch
# Dispatch to different EUs depending on what type of instruction it is
eu_type = None
if isinstance(next_inst, (Load, Store)):
eu_list = self.load_store_units
eu_type = "LoadStore"
elif isinstance(next_inst, (Add,)):
eu_list = self.arithmetic_units
eu_type = "Alu"
elif isinstance(next_inst, (Nop, Abort)):
# Nops don't need to be dispatched
eu_list = None
else:
raise RuntimeError(f"Instruction {next_inst} did not match a type with a valid queue")
if eu_list is not None:
# Try to dispatch to an EU with space
found_eu = False
for eu in eu_list:
if not eu.queue.is_full():
found_eu = True
# Actually do the dispatch
eu.queue.write(next_inst)
print(f"Dispatched {next_inst} to EU {eu.name}")
break
if not found_eu:
self.stall_hold = next_inst
print(f"Dispatch stalled because no free EUs existed to handle type {eu_type}")
else:
print(f"Dispatched f{next_inst} as a nop")
def post_eval(self):
# Eval all our execution units at the end since this would really then jump into the execution phase
for unit in self.load_store_units:
unit.eval()
for unit in self.arithmetic_units:
unit.eval()
memory = [
Load(0), # allocate register for 0
Load(1), # allocate register for 1
Add(0,1), # allocate register for result, 0 is now safe to write over since new register has been allocated
Store(0), #
Load(2), # allocate register for 2
Add(2,1), # allocate register for result, 2 is now safe to write over since new register has been allocated
Store(2), #
Add(2,0), # allocate register for result, 2 is now safe to write over since new register has been allocated
Store(2), #
Abort(), # Ender
]
# Unallocated - Unused register
# Allocated but invalid - location has been allocated for a result but result has not been placed there yet
# Allocated and valid - location has been allocated for a result and the result is valid for use by dependencies
# Allocated and valid is the stating value of the initial mappings for the named registers
# After Load(0)
# Named idx - Backing idx
# 0 - 0 (allocated,invalid) - 0 has been reallocated (since a load allows us to clear dependencies) but isn't valid since load hasn't completed
# 1 - 1 (allocated, valid) - initial allocation
# 2 - 2 (allocated, valid) - initial allocation
# After Load(1)
# 0 - 0 (allocated,?) - we don't know yet but we know it's still allocated
# ...
fetch = FetchStage(memory)
decode = DecodeStage(fetch)
dispatch = DispatchStage(decode)
stages = [fetch, decode, dispatch]
cycle_count = 0
while True:
print(f"Cycle {cycle_count}")
for stage in stages:
stage.eval()
for stage in stages:
stage.clock()
print()
cycle_count += 1
|
from inky import InkyPHAT
inky_display = InkyPHAT("black")
inky_display.set_border(inky_display.WHITE)
from PIL import Image, ImageFont, ImageDraw
img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
draw = ImageDraw.Draw(img)
questions = [
["What sweet food made by bees using nectar from flowers?", "honey"],
["Name the school that Harry Potter attended?", "hogwarts"],
["Which country is home to the kangaroo?", "australia"],
["Which country sent an Armada to attack Britain in 1588?", "spain"],
["Saint Patrick is the Patron Saint of which country?", "ireland"],
["From what tree do acorns come?", "oak"],
["What is the top colour in a rainbow?", "red"],
["In the nursery rhyme, who sat on a wall before having a great fall?", "humpty dumpty"],
["What is the capital of Germany?", "berlin"],
["Where in Scotland is there supposedly a lake monster called Nessie?", "loch ness"]
]
def title():
i = 1
while i < 2:
img = Image.open("/home/pi/mm/pictures/title1.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/title2.png")
inky_display.set_image(img)
inky_display.show()
i += 1
img = Image.open("/home/pi/mm/pictures/cutscene1.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/cutscene2.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/intro1.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/intro2.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/intro3.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/skull.png")
inky_display.set_image(img)
inky_display.show()
#title()
def game():
score = 0
for x in range(len(questions)):
print(questions[x][0])
answer = input()
answer = answer.lower()
if answer == questions[x][1]:
score = score+1
img = Image.open("/home/pi/mm/pictures/correct4.png")
inky_display.set_image(img)
inky_display.show()
else:
img = Image.open("/home/pi/mm/pictures/fail4.png")
inky_display.set_image(img)
inky_display.show()
if score < 7:
img = Image.open("/home/pi/mm/pictures/lessthan1.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/lessthan2.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/youlose.png")
inky_display.set_image(img)
inky_display.show()
retry()
else:
img = Image.open("/home/pi/mm/pictures/morethan1.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/morethan2.png")
inky_display.set_image(img)
inky_display.show()
img = Image.open("/home/pi/mm/pictures/youwin.png")
inky_display.set_image(img)
inky_display.show()
retry()
def retry():
print("Arr, another try? y/n")
img = Image.open("/home/pi/mm/pictures/restart.png")
inky_display.set_image(img)
inky_display.show()
retry = input()
if retry == "y":
game()
else:
exit()
game()
|
# dictionary comprehension
square_value_dict = { x:x**2 for x in range(10) }
# expected output:
'''
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
'''
print( square_value_dict ) |
sec_per_min = 60
min_per_hour = 60
hour_per_day = 24
seconds_per_hour = sec_per_min*min_per_hour
# How many seconds are there in one hour?
print( seconds_per_hour ) |
total = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five']
print(len(total))
str1 = '联系'
print(str1)
print(str1 + "您好")
import sys
x = 'runoob'
sys.stdout.write(x + '\n')
x="a"
y="b"
print(x, end=".")
def a():
'''这是注释'''
pass
print(a.__doc__)
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print(x)
var2 = 10
if var2:
print("2 - if 表达式条件为 true")
print(var2)
'''
age = int(input("请输入你家狗狗的年龄: "))
print("")
if age <= 0:
print("你是在逗我吧!")
elif age == 1:
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age - 2) * 5
print("对应人类年龄: ", human)
### 退出提示
input("点击 enter 键退出")
'''
list = [1, 2, 3, 4, 5]
it = iter(list)
print(next(it))
print(next(it))
print(list[1])
a = [66.25, 333, 333, 1, 1234.5]
print(a)
a.pop()
print(a)
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
print([weapon for weapon in freshfruit])
for weapon in freshfruit:
print(weapon, end=" ")
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
import re
print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配
print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def count(self, search_for):
current = self.head
count = 0
while(current is not None):
if current.data == search_for:
count += 1
current = current.next
return count
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
llist = LinkedList()
llist.push(1)
llist.push(2)
llist.push(3)
llist.push(2)
llist.push(1)
print("Number of ones -", llist.count(1))
print("Number of twos -",llist.count(2))
print("Number of threes -",llist.count(3))
|
# engrjepmanzanillo
class Solution:
def __init__(self, string):
self.string = []
for i in range(len(string)):
self.string.append(string[i])
self.reversed_string = self.string[::-1]
def isPalindrome(self):
if self.string == self.reversed_string:
if len(self.string) == 0:
return False
else:
return True
else:
return False
s = ''
obj = Solution(s)
if obj.isPalindrome():
print('The string, ' + s + ' is a palindrome.')
else:
print('The string, ' + s + ' is not a palindrome.')
|
#Async code
#Async runs in the same thread
'''
Async uses CoRoutines which run on the same thread
"async" and "await"
'''
import logging
import multiprocessing
import threading
import time
import asyncio
import random
logging.basicConfig(format='%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG)
# Functions
def display(msg):
threadname = threading.current_thread().name
procname = multiprocessing.current_process().name
logging.info(f'{procname}/{threadname} : {msg}')
async def work(name):
display(name + ' starting')
#do something
await asyncio.sleep(random.randint(1,10))
display(name + ' finished')
async def run_async(max):
tasks = []
for x in range(max):
name = 'Item ' + str(x)
tasks.append(asyncio.ensure_future(work(name)))
await asyncio.gather(*tasks)
def main():
display('Main started')
loop = asyncio.get_event_loop()
loop.run_until_complete(run_async(50))
# loop.run_forever()
loop.close()
display('Main Finished')
if __name__ == '__main__':
main()
|
# Multiple Inheritance
# inherit from multiple classes
class Vehicle:
speed = 0
def drive(self, speed):
self.speed = speed
print(f'Driving')
def stop(self):
self.speed = 0
print(f'Stopped!')
def display(self):
print(f'Driving at {self.speed} speed')
class Freezer:
temp = 0
def freeze(self, temp):
self.temp = 0;
print('Freezing')
def display(self):
print(f'Freezing at {self.temp} temp')
class FreezerTruck(Freezer, Vehicle): # Method Resolution Order (MRO)
def display(self):
print(f'Is a Freezer: {issubclass(FreezerTruck, Freezer)}')
print(f'Is a Vehicle: {issubclass(FreezerTruck, Vehicle)}')
# super(Freezer,self).display()
# super(Vehicle,self).display()
Freezer.display(self)
Vehicle.display(self)
t = FreezerTruck()
t.drive(50)
t.freeze(-20)
print('*'*20)
t.display() |
# imports:
import json
import os.path
# Inventory Class:
class Inventory:
pets ={}
def __init__(self):
self.load()
def add(self, key, qty):
q = 0;
if key in self.pets:
v = self.pets[key]
q = v + qty
else:
q = qty
self.pets[key] = q
print(f'Added {qty} {key} : total = {self.pets[key]}')
def remove(self, key, qty):
q = 0;
if key in self.pets:
v = self.pets[key]
q = v - qty
if q < 0:
q = 0
self.pets[key] = q
print(f'Removed {qty} {key} : total = {self.pets[key]}')
def display(self):
for key, value in self.pets.items():
print(f'{key} = {value}')
def save(self):
print(f'Saving inventory...')
with open('inventory.txt', 'w') as f:
json.dump(self.pets,f)
print(f'Saved..')
def load(self):
print(f'Loading inventory...')
if not os.path.exists('inventory.txt'):
print(f'Skipping, nothing to load !')
return
with open('inventory.txt', 'r') as f:
self.pets = json.load(f)
print(f'Loaded..')
def main():
inv = Inventory()
while True:
action = input('Action: add, remove, save, list, save, exit: ')
if action == 'exit':
break
if action == 'add' or action == 'remove':
key = input('Enter the animal : ')
qty = int(input('Enter the quantity : '))
if action == 'add':
inv.add(key, qty)
if action == 'remove':
inv.remove(key, qty)
if action == 'list':
inv.display()
if action == 'save':
inv.save()
inv.save()
if __name__ == '__main__':
main()
|
import random
def rolldice(): #this function generates three random numbers and returns them in an array
values = []
i = 0
while i < 3:
values.append(random.randrange(1,6))
i = i + 1
return values
#This is a mess off booleans that keeps calling rolldice() until a pair is noticed then returns the third number or tripples
def clo():
roll = rolldice()
n = 1
while n < 2:
#Here a 4,5,6 and a 1,2,3 are given huge and null values to make them game-dominant rolls
if sorted(roll) == [4,5,6]:
return 999
n = n + 1
elif sorted(roll) == [1,2,3]:
return 0
n = n + 1
#Here is a likely inneficient combination of checks for a matching pair which returns the other number unless a triple is noticed
elif roll[0] == roll[1]:
if roll[0] == roll[2]:
return roll[0]*111
else:
return roll[2]
n = n + 1
elif roll[0] == roll[2]:
if roll[0] == roll[1]:
return roll[0]*111
else:
return roll[1]
n = n + 1
elif roll[1] == roll[2]:
if roll[1] == roll[0]:
return roll[0]*111
else:
return roll[0]
n = n + 1
else:
roll = rolldice()
p1 = clo()
p2 = clo()
print("You get :"+str(p1))
print("The computer gets :"+str(p2))
if p1 == 999:
print ("You win with high straight!")
elif p2 == 999:
print ("Computer wins with high straight!")
elif p1 == 0:
print ("You lose with low straight.")
elif p2 == 0:
print ("Computer loses with low straight!")
elif p1 > p2:
print ("You win!")
elif p2 == p1:
print("It's a tie.")
else:
print ("The computer wins.") |
# WRITE YOUR FUNCTIONS HERE
def get_pet_shop_name(pet_shop):
return pet_shop["name"]
def get_total_cash(pet_shop):
return pet_shop["admin"]["total_cash"]
def add_or_remove_cash(pet_shop, num):
pet_shop["admin"]["total_cash"] += num
def get_pets_sold(pet_shop):
return pet_shop["admin"]["pets_sold"]
def increase_pets_sold(pet_shop, num):
pet_shop["admin"]["pets_sold"] += num
def get_stock_count(pet_shop):
return len(pet_shop["pets"])
def get_pets_by_breed(pet_shop, pet_breed):
num_of_breed = []
for pet in pet_shop["pets"]:
if pet["breed"] == pet_breed:
num_of_breed.append(pet)
return num_of_breed
def find_pet_by_name(pet_shop, pet_name):
for pet in pet_shop["pets"]:
if pet["name"] == pet_name:
return pet
return None
def remove_pet_by_name(pet_shop, pet_name):
for pet in pet_shop["pets"]:
if pet["name"] == pet_name:
pet_shop["pets"].remove(pet)
def add_pet_to_stock(pet_shop, new_pet):
pet_shop["pets"].append(new_pet)
def get_customer_cash(customer):
return customer["cash"]
def remove_customer_cash(customer, cash):
customer["cash"] -= cash
def get_customer_pet_count(customer):
return len(customer["pets"])
def add_pet_to_customer(customer, new_pet):
customer["pets"].append(new_pet)
def customer_can_afford_pet(customer, pet):
return customer["cash"] >= pet["price"]
def sell_pet_to_customer(pet_shop, pet, customer):
if pet == None or customer["cash"] < pet["price"]:
return
else:
customer["pets"].append(pet)
customer["cash"] -= pet["price"]
pet_shop["admin"]["total_cash"] += pet["price"]
pet_shop["admin"]["pets_sold"] += 1 |
"""This file defines a simple framework for hyper-parameter tuning.
It takes the input as a json fine which has a dictionary of hyper-parameters
to be tuned along with the list of values for that hyper-parameter.
All combinations of the hyperparameter values are run and result and checkpoints
are stored in a separate folder for each run. Additionally, a config.json
file will be created in each directory which stores the parameters with which
the training for a given experiment was done.
"""
import json
import os
import itertools
import numpy as np
class HyperParamTuning():
"""Defines the hyper-parameter tuning class.
Attributes:
config_file: The name of the config file for the hyperparameters.
"""
def __init__(self, config_file='hyperparam_tuning.json'):
super().__init__()
with open(config_file) as f:
self.param_dict = json.load(f)
def run(self):
"""Does the hyper-parameter tuning over all combinations
of hyper-parameters in the config file.
"""
hyperparameters, values = zip(*self.param_dict.items())
configurations = [dict(zip(hyperparameters, v)) for v in itertools.product(*values)]
num_runs = 1
for config in configurations:
print('{} run:'.format(num_runs))
print('Training model with following configuration:')
for hparam, value in config.items():
print('Hyperparameter : {}, Value : {}'.format(hparam, value))
run_log_directory = '/hyperparam_tuning/tuning_run_' + str(num_runs)
print('Training logs saved in {}'.format(run_log_directory))
execute_command = 'python train_model.py --chkdir=' + run_log_directory
for hparam, value in config.items():
execute_command += (" --" + hparam + " " + str(value))
os.system(execute_command)
num_runs += 1
if __name__ == '__main__':
hparams_class = HyperParamTuning()
hparams_class.run()
|
# if Statement
# if 10 > 5:
# print('10 greather then 5')
# print('if scope finished')
# print('Close Program')
# nested if
# if 10 > 5: condition True
# print('10 greather then 5')
# if 8 > 5: condition True
# print('8 greather then 5')
# print('Program closed')
# if 10 > 5: Condition True
# print('10 greather then 5')
# if 8 < 5: Condition False
# print('8 greather then 5')
# print('Program closed')
# else Statement
# if 10 < 5:
# print('10 greather then 10')
# else:
# print('5 less then 10')
# if else chain
# num = 7
# if num == 6:
# print('Num is 6')
# else:
# if num == 5:
# print('num is 5')
# else:
# if num == 4:
# print('num is 4')
# else:
# if num == 7:
# print('num is 7')
# else:
# print('Rong Number')
# elif
# num = 5
# if num == 7:
# print('Number is 7')
# elif num == 6:
# print('Number is 6')
# elif num == 5:
# print('Number is 5')
# else:
# print('Rong Number')
# Ternary operator
# a = 100
# b = 200 if (a >= 100 and a < 200) else 300
# print(b)
# a = 300
# b = 400 if (a >= 200 or a >= 500) else 300
# print(b)
# status = 0
# message = 'True' if (status > 0) else 'False'
# print(message)
for i in range(10):
print(i)
else:
print('done')
|
# exception
# user_number_a = int(input('Enter Number of A : '))
# user_number_b = int(input('Enter Number of B : '))
# result = user_number_a/user_number_b
# print(result)
# try:
# user_number_a = int(input('Enter Number of A : '))
# user_number_b = int(input('Enter Number of B : '))
# result = user_number_a/user_number_b
# print(result)
# except (ZeroDivisionError, ValueError): # exception handling
# print('Sorry Input Type Error')
# try:
# user_number_a = int(input('Enter Number of A : '))
# user_number_b = int(input('Enter Number of B : '))
# result = user_number_a/user_number_b
# print(result)
# except ZeroDivisionError: # exception handling
# print('Sorry Input Zero has not supported')
# except ValueError:
# print('Sorry Value Error')
# try:
# a = 'abc'
# b = 20
# result = a/b
# print(result)
# except:
# print("sorry you are rong")
# finally
# try:
# user_number_a = int(input('Enter Number of A : '))
# user_number_b = int(input('Enter Number of B : '))
# result = user_number_a/user_number_b
# print(result)
# except ZeroDivisionError: # exception handling
# print('Sorry Input Zero has not supported')
# except ValueError:
# print('Sorry Value Error')
# finally:
# print("Finally Code execute") # finally is all error execution after run
# try:
# print('Joy')
# result = 10/0
# print(result)
# except:
# print('Yes')
# finally:
# print('Finally code done')
# manually custom exception create
# print('Hello Joy')
# raise NameError('Hello Bangladesh')
# raise ValueError('Joy')
# try:
# user_number_a = int(input('Enter Number of A : '))
# user_number_b = int(input('Enter Number of B : '))
# result = user_number_a/user_number_b
# print(result)
# except ZeroDivisionError: # exception handling
# print('Sorry Input Zero has not supported')
# except ValueError:
# print('Sorry Value Error')
# raise
# print('a')
# assert 11 == 11
# print('b')
# assert 'b' == 'b'
# print('c')
# assert 'c' == 'u', 'c not equal u'
# print('d')
# def KelvinToFahrenheit(Temperature):
# assert (Temperature >= 0), "Colder than absolute zero!"
# return (((Temperature-273)*1.8)+32)
#
# print(KelvinToFahrenheit(144))
# print(KelvinToFahrenheit(244))
# print(KelvinToFahrenheit(-5))
|
from random import randint
games = {}
winners = {}
player = {'name': 'name', 'health': 100, 'heal': 2}
monster = {'name': 'Learning-to-Code', 'health': 100}
print(' ')
print('>' * 28 + ' STARTING THE GAME ' + '<' * 28)
print('Welcome to the Learning-to-Code Monster Game')
print('... based on real life events of a Redi School student and migrant in Germany')
print(' ')
print('Instructions')
print('1. Your goal is to beat the monster that keeps you from learning to code')
print('2. When the game starts, you and the monster have 100 points each')
print('3. You attack the monster, and the monster loses points')
print('4. The monster always counterattacks')
print('5. The attacks -and the strength- are a bit "random", as some life events')
print('6. You can try the healing option to recover some points')
print('7. The game ends when you or the monster reach 0 points')
print('8. The best players are registered in the winners table')
print('The game is starting...')
print(' ')
remain_health_m = 0
remain_health_p = 0
remain_heal_p = 0
def game(remain_health_m, remain_health_p, remain_heal_p, monster, player, winners, games):
player['name'] = str(input('What is your name?: ').upper())
print('Are you ready, ' + player['name'] + '?')
while monster['health'] > 0 and player['health'] > 0:
print('='*31 + ' ACTION ' + '='*32)
print('What do you want to do?')
action = input('[1] Attack; [2] Heal; [3] Winners; [4] Exit game: ')
print('-'*71)
if action == '1' or action == '2':
if action == '1':
# player attacks monster, randomly from 6 options, and damages the monster
attack_p = randint(1, 6)
if attack_p == 1:
damage_m = randint(1, 5)
print('You did your homework from last Redis class')
elif attack_p == 2:
damage_m = randint(5, 10)
print('You asked/looked for support to understand something')
elif attack_p == 3:
damage_m = randint(10, 15)
print('You attended a Redi class!')
elif attack_p == 4:
damage_m = randint(15, 20)
print('You found new sources to learn besides the Redi classes')
elif attack_p == 5:
damage_m = randint(20, 25)
print('You debugged something in your code! Uhuuu!')
else:
damage_m = randint(25, 30)
print('You coded! As simple as that!')
remain_health_m = monster['health'] - damage_m
monster['health'] = remain_health_m
print(':) The monster lost [' + str(damage_m) + '] points')
print(' ')
# the monster attacks back, randomly from 6 options, and damages the player
attack_m = randint(1, 6)
if attack_m == 1:
damage_p = randint(1, 5)
print('Your head is full and you keep confusing the coding syntax')
elif attack_m == 2:
damage_p = randint(5, 10)
print('Self-doubt kicked in, and you wonder if you will ever learn how to code')
elif attack_m == 3:
damage_p = randint(10, 15)
print('Concerned about your future and learning success, you procrastinate')
elif attack_m == 4:
damage_p = randint(15, 20)
print('Grrrrr! Your code is not working! Waruuuuuuuuuuuuum!?')
elif attack_m == 5:
damage_p = randint(20, 25)
print('You need to take several tiring-underpaid jobs to cover your expenses')
print('No coding for a while')
else:
damage_p = randint(25, 30)
print('You need to deal with Deutsche Bürokratie or you will lose your permit!')
print('No coding for a while')
remain_health_p = player['health'] - damage_p
player['health'] = remain_health_p
print(':( You lost [' + str(damage_p) + '] points')
else:
# player tries to heal, from 5 random options
if player['heal'] >= 1:
remain_heal_p = player['heal'] - 1
player['heal'] = remain_heal_p
healing = randint(1, 5)
if healing == 1:
healing_p = 5
print('You took a break and did something you truly enjoy!')
elif healing == 2:
healing_p = 10
print('You talked to a friend and had an amazing time')
elif healing == 3:
healing_p = 15
print('You had a therapy session')
print('No self-doubt or procrastination for a while!')
elif healing == 4:
healing_p = 20
print('After networking with Redi School Community, you are feeling motivated!')
else:
healing_p = 0
print('Life is not that easy! No healing for you in this round')
remain_health_p = player['health'] + healing_p
player['health'] = remain_health_p
else:
healing_p = 0
print('You used all your healing options')
print('You recovered ' + str(healing_p) + ' points!')
print(' ')
print('Current score: ' + player['name'] + ' [' + str(player['health']) + '] x [' + str(
monster['health']) + '] MONSTER')
elif action == '3':
# option to see the winners chart
print('WINNERS')
# if the winners dictionary is empty
if len(winners) == 0:
print('So far there is no winner')
# if it is not empty, iterating to print the winners keys and values and the effectiveness rate
else:
for key, value in winners.items():
rate = int(100 * value / games[key])
print(str(key) + ' won ' + str(value) + ' of ' + str(games[key]) + ' game(s) -> ' + str(rate) + '% effective')
elif action == '4':
# option to exit the game
print('='*71)
print('Schade Marmelade! But do not forget:')
print('You can play again the Learning-to-Code Monster Game in the future')
print('GOOD BYE!')
print('='*71)
quit()
else:
# in case of an invalid input by the user
print('Invalid input. Type 1, 2, 3 or 4')
# there is a winner
if monster['health'] <= 0 or player['health'] <= 0:
# adding new players names (keys) in the games dictionary
if player['name'] not in games.keys():
games[player['name']] = 1
# updating how many games the player played (values) in the games dictionary
else:
games[player['name']] = games[player['name']] + 1
print('-' * 71)
# message when monster wins
if monster['health'] > player['health']:
print('OH NO! The Monster won! :(')
print('But you can always try again!')
# message when player wins
else:
print('UHUUUUUUUUU! You won!')
print('Learning to code IS possible!')
# adding new players names (keys) in the winners dictionary
if player['name'] not in winners.keys():
winners[player['name']] = 1
# updating when the players wins (values) in the winners dictionary
else:
winners[player['name']] = winners[player['name']] + 1
print('=' * 71)
print(' ')
print('>'*25 + ' RESTARTING THE GAME ' + '<'*25)
# reset the values to a new game
monster['health'] = 100
player['health'] = 100
player['heal'] = 2
# calling the game function to start a new game automatically
game(remain_health_m, remain_health_p, monster, player, winners, games, remain_heal_p)
game(remain_health_m, remain_health_p, remain_heal_p, monster, player, winners, games)
|
# implement of renderers
#
# renderer solves if in any case that you want to show the string in a box.
class Renderer:
def __init__(self, height, width, **render_styles):
# in order to access the attributes of the instance
# which this renderer belong to.
self._render_styles = render_styles
self._render_styles['height'] = height
self._render_styles['width'] = width
def render(self, mode):
raise NotImplementedError(
"%s is an abstract class, you should either use ContentDivision or ContainerDivision to make it work."
% type(self)
)
def _derived_string_block_size(self) -> dict:
# TODO: i might want to deal with if this Render wants a "box"
# the box means something like this:
# +---------+
# | box |
# +---------+
# thus the actual size of string block might be less than the div.
d = dict()
d['height'] = int(self._render_styles['height'])
d['width'] = int(self._render_styles['width'])
return d
|
from datetime import datetime
import time
def partition(limit):
u_limit_list = []
l_limit_list = []
for i in range(1,limit):
mid = limit/2
if(i >= mid):
u_limit_list.append(i)
elif(i < mid):
l_limit_list.append(i)
return (u_limit_list,l_limit_list)
def printRandU(ul):
# get the time in microsecond and generate the random index using mod
now = datetime.now()
now = int(now.microsecond)
uIndex = now % len(ul)
print("Upper Range Value "+ str(ul[uIndex]))
def printRandL(ll):
# get the time in microsecond and generate the random index using mod
now = datetime.now()
now = int(now.microsecond)
lIndex = now % len(ll)
print("Lower Range Value " + str(ll[lIndex]))
if __name__ == "__main__":
uFactor = 0.73 # upper limit bias
lFactor = 0.27 # lower limit bias
rangeW,times = input().split() # input range limit and no of times you want the numbers to printed
times = int(times)
rangeW = int(rangeW)
ul, ll = partition(rangeW+1) # split the range of number in upper and lower half
ucount = 0
lcount = 0
for i in range(int(times*uFactor)+1): # print the random number from upper list using upper limit bias
time.sleep(1) # added a sleep of 1 second to get the different value of microsecond
printRandU(ul)
for j in range(int(times*lFactor)+1): # print the random number from lower list using lower limit bias
time.sleep(1) # added a sleep of 1 second to get the different value of microsecond
printRandL(ll)
|
import re
import os
# Author: Huang Jian Wei
# Date Created: 08/11/2019
# Date Last Modified: 11/11/2019
result_file = open("result.txt", "a+")
def main():
while 1:
user_input = input("(1) for single file, (2) for directory,"
"(3) to exit:""\n1.) File\n2.) Directory\n3.) Exit\n")
if user_input == '3':
print("Exiting program...")
break
# Relative path
elif user_input == '1':
try:
filename = input("Input name of file:")
print(filename)
except Exception:
print("Cannot find file or invalid file! Please try again.")
elif user_input == '2':
directory_path = input("Input name of directory:")
list_of_files = getListOfFiles(directory_path)
for elem in list_of_files:
sconcat(elem)
# Get the list of all files in directory tree at given path
else:
print("Invalid input. Please try again.")
def sconcat(filename):
match_pattern = re.compile(r'(<Insert your pattern here>)')
result_arr =[]
with open(filename) as blf:
for line in blf:
if(match_pattern.search(line)):
result_arr.append(line)
for arr in result_arr:
result_file.write(arr+"\n")
def getListOfFiles(dirName):
# create a list of file and sub directories
# names in the given directory
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
# Create full path
fullPath = os.path.join(dirName, entry)
# If entry is a directory then get the list of files in this directory
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath)
else:
allFiles.append(fullPath)
return allFiles
if __name__ == "__main__":
main()
# log_file.close()
|
# Even though there are multiple objects, we still only need one class.
# No matter how many cookies we make, only one cookie cutter is needed.
class Car(object):
# The Constructor is defined with arguments.
def __init__(self, c, xpos, ypos, xspeed):
self.c = c
self.xpos = xpos
self.ypos = ypos
self.xspeed = xspeed
def display(self):
stroke(0)
fill(self.c)
rectMode(CENTER)
rect(self.xpos, self.ypos, 20, 10);
def drive(self):
self.xpos = self.xpos + self.xspeed;
if self.xpos > width:
self.xpos = 0
class Tree(object):
def __init__(self, xpos, ypos, tallness):
self.xpos = xpos
self.ypos = ypos
self.tallness = tallness
def display(self):
# trunk
stroke(0)
fill(color(165, 42, 42)) # brown
rectMode(CENTER)
rect(self.xpos, self.ypos, 6, self.tallness)
# leaves
fill(color(0,100,0)) # dark green
ellipse(self.xpos, self.ypos-self.tallness, 20, self.tallness)
class Road(object):
def __init__(self, xpos, ypos):
self.xpos = xpos
self.ypos = ypos
def display(self):
stroke(0)
fill(color(100,100,100)) # dark gray
rectMode(CENTER)
rect(self.xpos, self.ypos, 25, 25)
fill(color(255, 255, 0)) # yellow
rect(self.xpos, self.ypos, 20, 5)
class Crosswalk(object):
def __init__(self, xpos, ypos):
self.xpos = xpos
self.ypos = ypos
def display(self):
stroke(0)
fill(color(100,100,100)) # dark gray
rectMode(CENTER)
rect(self.xpos, self.ypos, 25, 25)
fill(color(255, 255, 0)) # yellow
rect(self.xpos, self.ypos, 20, 5)
fill(color(255,255,255)) #white
rect(self.xpos, self.ypos-9, 15, 3)
rect(self.xpos, self.ypos-3, 15, 3)
rect(self.xpos, self.ypos+3, 15, 3)
rect(self.xpos, self.ypos+9, 15, 3)
import random
myCar1 = Car(color(255, 0, 0), 0, 100, 2)
myCar2 = Car(color(0, 255, 255), 0, 10, 1)
# trees array
trees = []
for i in range(5):
trees.append(Tree((30*i)+30, 70, random.randint(12,36)))
# roads array
roads = []
roadtype = 0
def setup():
size(200,200)
def draw():
background(255)
for i in range(len(roads)):
roads[i].display()
myCar1.drive()
myCar1.display()
myCar2.drive()
myCar2.display()
for i in range(len(trees)):
trees[i].display()
if (roadtype == 0):
instruction = "Click to place road. Press C to switch to crosswalk."
if (roadtype == 1):
instruction = "Click to place crosswalk. Press R to switch to road."
text(instruction, 100, 160, 180, 30)
# this function returns a random color
def newcolor():
c = color(random.randint(0,255),random.randint(0,255),random.randint(0,255))
return c
# change car color when car's number is pressed
def keyPressed():
global roadtype
if (key == '1'):
myCar1.c = newcolor()
if (key == '2'):
myCar2.c = newcolor()
if (key == 'r'):
roadtype = 0
if (key == 'c'):
roadtype = 1
# creates a road object at mouse click
def mousePressed():
if (roadtype == 0):
roads.append(Road(mouseX, mouseY))
if (roadtype == 1):
roads.append(Crosswalk(mouseX, mouseY))
|
# Определение количества различных подстрок с использованием хеш-функции. Пусть дана строка S длиной N. Например,
# состоящая только из маленьких латинских букв. Требуется найти количество различных подстрок в этой строке. Для решения
# задачи рекомендую воспользоваться алгоритмом sha1 из модуля hashlib или встроенную функцию hash()
a = str(input('Введите строку: '))
def substring_counter(string):
hash_lst = []
for i in range(1, len(string)):
for j in range(len(string)-i + 1):
if hash(string[j:j+i]) not in hash_lst:
hash_lst.append(hash(string[j:j+i]))
return len(hash_lst)
print(substring_counter(a))
|
# В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
import random
start = int(input('Введите начало диапазона,из которого необходимо генерировать числа: '))
finish = int(input('Введите конец этого диапазона: '))
quantity = int(input('Введите количество чисел,которые необходимо сгенерировать: '))
main_list = []
random_number = 0
max_number = start
min_number = finish
max_number_index = 0
min_number_index = 0
for i in range(0, quantity):
random_number = random.randint(start, finish)
main_list.append(random_number)
if random_number > max_number:
max_number = random_number
max_number_index = i
elif random_number < min_number:
min_number = random_number
min_number_index = i
print(f'{main_list} ')
print(f'Максимальное число: {max_number} с индексом {max_number_index} ')
print(f'Минимальное число: {min_number} с индексом {min_number_index} ')
main_list[max_number_index] = min_number
main_list[min_number_index] = max_number
print(main_list)
|
x1 = float(input('Введите координату х первой точки : '))
y1 = float(input('Введите координату y первой точки : '))
x2 = float(input('Введите координату x второй точки : '))
y2 = float(input('Введите координату y второй точки : '))
if x1 != x2:
k = (y1-y2)/(x1-x2)
b = y2-k*x2
print(f'y = {k:.3f}*x +{b:.3f}')
elif y1 != y2:
print('Прямая параллельна оси ординат. Не является функцией')
else:
print('Дважды введены координаты одной точки')
|
from PIL import Image, ImageDraw, ImageFont
import math
#this turns polar coordinates to cartesian form
def polar_to_cartesian(angle,radius):
angle_radians = math.radians(angle)
x_coord = radius*math.cos(angle_radians)
y_coord = radius*math.sin(angle_radians)
if angle == 0:
y_coord = 0
elif angle == 90:
x_coord = 0
elif angle == 180:
y_coord = 0
elif angle == 270:
x_coord = 0
x =x_coord+213.5
y = 213.5-y_coord
return x,y
#this draws the background of the board
img = Image.new("RGB",(451,451),'black')
dr = ImageDraw.Draw(img)
dr.ellipse((0,0,451,451),'black','white')
dr.ellipse((55.5,55.5,395.5,395.5),'white','grey')
#these are the angles of the start of each sector
angles = [18*i-9 for i in range(1,21)]
# this list with 20 elements is alternating between the RGB values for the red, then the green of the dartboard.
colours = [(227,41,46),(48,159,106)]*10
#This draws twenty red/green sectors with radii equal to the part of the board where a score can be achieved.
for i in range(len(angles)):
if i != 19:
dr.pieslice((55.5,55.5,395.5,395.5), angles[i], angles[i+1], fill=colours[i], outline='grey')
else:
dr.pieslice((55.5,55.5,395.5,395.5), angles[i], 369, fill=colours[i], outline='grey')
# this list with 20 elements is alternating between the RGB values for the black, then the white of the dartboard.
colours_2 = [(0,0,0),(255,255,255)]*10
#This draws twenty black/white sectors which over the red/green sectors and extend to until the double score area. Leaving only the double score area left green/red from the previous sectors.
for i in range(len(angles)):
if i != 19:
dr.pieslice((63.5,63.5,387.5,387.5), angles[i], angles[i+1], fill=colours_2[i], outline='grey')
else:
dr.pieslice((63.5,63.5,387.5,387.5), angles[i], 369, fill=colours_2[i], outline='grey')
#This draws twenty red/green sectors that will end up being the triple score areas.
for i in range(len(angles)):
if i != 19:
dr.pieslice((110.5,110.5,340.5,340.5), angles[i], angles[i+1], fill=colours[i], outline='grey')
else:
dr.pieslice((110.5,110.5,340.5,340.5), angles[i], 369, fill=colours[i], outline='grey')
#This draws twenty black/white sectors that will end up being the lower single score areas.
for i in range(len(angles)):
if i != 19:
dr.pieslice((118.5,118.5,332.5,332.5), angles[i], angles[i+1], fill=colours_2[i], outline='grey')
else:
dr.pieslice((118.5,118.5,332.5,332.5), angles[i], 369, fill=colours_2[i], outline='grey')
#this draws the outer-bull
dr.ellipse((209.6,209.6,241.4,241.4),(48,159,106),'grey')
#this draws the inner bull
dr.ellipse((219.5,219.5,231.85,231.85),(227,41,46),'grey')
# this places the numbers evenly (radially) around the dart board.
fontPath = "C:/Users/zoegriffiths/Library/Fonts/Cooper Black Regular.ttf"
font_to_use = ImageFont.truetype (fontPath, 24)
angles_for_text = [18*i for i in range(20)]
numbers = [6,13,4,18,1,20,5,12,9,14,11,8,16,7,19,3,17,2,15,10]
for i in range(len(numbers)):
coords = polar_to_cartesian(angles_for_text[i],197.75)
dr.text(coords, '{0}'.format(numbers[i]), fill="white", font=font_to_use, anchor=None)
img.save("dartboard.png")
|
# dict
mystuff = {'apple': "I AM APPLES!"}
print(mystuff['apple'])
# this goes in mystuff.py
def apple():
print("I AM APPLES!")
# so I can 'import mystuff.py' and use 'apple' function
import mystuff
mystuff.apple()
# put a variable named tangerine
def apple():
print("I AM APPLES!")
tangerine = "Living reflection of a dream"
# 调用
import mystuff
mystuff.apple()
print(mystuff.tangerine) # 知识点1:.(dot) -> mystuff.apple()
# 调用dict和mystuff.xx的异同,[key]和.key 其实本质是一样的
mystuff['apple']
mystuff.apple()
mystuff.tangerine
# class的一个例子
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print("I AM CLASSy APPLES!")
# class 类似下面三行
thing = MyStuff()
thing.apple()
print(thing.tangerine)
# three ways to get things from things
# dict style
mystuff['apple']
# module style
mystuff.apples()
print(mystuff.tangerine)
# class style
thing = MyStuff()
thing.apples()
print(thing.tangerine)
|
from sys import argv # 没有这行语句
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ') # 此处有改动,漏了右半边)
weight = input()
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
print() #为了美观,我加上了这行空格
script, filename = argv
txt = open(filename) # filename 写成了filenme
print(f"Here's your file {filename}:") #f" "漏了个f
print(txt.read()) # 此处漏了个t
print() #为了美观,我加上了这行空格
print("Type the filename again:")
file_again = input("> ")
print() #为了美观,我加上了这行空格
txt_again = open(file_again)
print(txt_again.read()) # 此处有改动,_改为.
print() #为了美观,我加上了这行空格
print('Let\'s practice everything.') # 此处本全为单引号' ,现将中间加上转义符\
print('You\'d need to know \'bout escapes \n with \\ that do \n newlines and \t tabs.')
# 原来分为两行,应在第一行末尾,即escapes后加上换行符 \n
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print("--------------") #没有右半边 "
print(poem)
print("--------------") # 没有左半边"
print() #为了美观,我加上了这行空格
five = 10 - 2 + 3 - 6 # 此处有改动,-后漏了数字,补上了6
print(f"This should be five: {five}") # 此处有改动,漏了右半边)
def secret_formula(started): #此处有改动,漏了冒号:
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100 # 此处有改动,漏了符号,加上了 /
return jelly_beans, jars, crates
start_point = 10000
beans, jars , crates = secret_formula(start_point) # 此处有改动,漏了crates
# remember that this is another way to format a string
print("With a starting point of: {}".format(start_point))
# it's just like with an f"" string
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
start_point = start_point / 10
print("We can also do that this way:")
formula = secret_formula(start_point) # 此处有改动,漏了下划线_ ,补齐为secret_point
# this is an easy way to apply a list to a format string
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
print() #为了美观,我加上了这行空格
people = 20
cats = 30 # 输入错误,将cates改为cats
dogs = 15
if people < cats:
print ("Too many cats! The world is doomed!" )# printy语句后没有打()
if people < cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs: # 函数后没有冒号:
print("The world is dry!")
print() #为了美观,我加上了这行空格
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs: # 函数后没有冒号:
print("People are less than or equal to dogs.")#缺少右半边引号"
if people == dogs: # == 写成了 =
print("People are dogs.")
print() #为了美观,我加上了这行空格 |
#这里有一张重要的图片要记,a.test("hello"),Type error ->只需要1个argument,但是给了2个
# 实际上python经常将mystuff.append('hello')转换成append(mystuff,'hello')
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_sutff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_sutff.pop() #从程序来看stuff.pop() 是将列表的最后一个字符‘剪切’下来
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1]) #此处‘剪切’了stuff最后一个字符,所以少了一个
print(' '.join(stuff))
print('#'.join(stuff[3:5]))# 大多数stuff.join(x)这种格式,其实都是join(stuff,x)
# 一个概念:data structure 数据结构?
# list 就像 一叠卡片一样,作者说:
# Every concept in programming usually has some relationship to the real world
# 关于class 的教程: http://www.runoob.com/python3/python3-class.html |
from evaluate import evaluate_line
from copy import deepcopy
import random
class branch():
def __init__(self, chess, level, color,x,y):
self.chess = chess
self.color = color
self.level = level
self.length = len(self.chess)
self.width = len(self.chess[0])
self.i = x
self.j = y
def move(self, i, j, color):
self.chess[i][j] = color
def traverse(self):
#for i in range(0, self.length):
# for j in range(0, self.width):
q = 6
m = self.i -q
n = self.i +q
x = self.j -q
y = self.j +q
if self.i-q < 0:
m = 0
if self.i+q > self.length:
n = self.length
if self.j-q < 0:
x = 0
if self.j+q > self.length:
y = self.length
for i in range(m,n):
for j in range(x,y):
if self.chess[i][j] == 0:
if self.color == "black":
nextcolor = "white"
elif self.color == "white":
nextcolor = "black"
new_branch = branch(deepcopy(self.chess), self.level-1, nextcolor,i,j)
new_branch.move(i, j, self.color)
yield new_branch, i, j
def real_traverse(self):
lst = []
lst1 = []
for i in self.traverse():
lst.append(i[0].evaluateNega())
lst.sort()
lst = lst[-10::-1]
for i in self.traverse():
if i[0].evaluateNega() in lst:
lst1.append(i)
#print(lst)
return lst1
def evaluateNega(self):
return -self.evaluate(self.chess,self.color)
#return -self.evaluate(self.narrow(self.i,self.j),self.color)
def evaluate(self,chess,color):
vecs = []
# shu hang
length = len(chess)
width = len(chess[0])
for i in range(length):
vecs.append(chess[i])
# heng hang
for j in range(width):
vecs.append([chess[i][j] for i in range(0,length)])
# \
vecs.append([chess[x][x] for x in range(0,length)])
for i in range(1, length-4):
vec = [chess[x][x-i] for x in range(i, length)]
vecs.append(vec)
vec = [chess[y-i][y] for y in range(i, width)]
vecs.append(vec)
# /
for i in range(4, length-1):
vec = [chess[x][i-x] for x in range(i, -1, -1)]
vecs.append(vec)
vec = [chess[x][width-x+length-i-2] for x in range(length-i-1, length)]
vecs.append(vec)
table_score = 0
for vec in vecs:
score = evaluate_line(vec)
if color == "black":
#table_score += score['white'][0] - score['black'][0] - score['black'][1]
score["white"][1] += 100
table_score += score['white'][0] - score['black'][0] + score['white'][1]
elif color == "white":
score["black"][1] += 100
#table_score += score['black'][0]- score['white'][0] - score['white'][1]
table_score += score['black'][0]-score['white'][0] + score['black'][1]
for i in range(15):
for j in range(15):
stone = chess[i][j]
if color == "black":
if stone == "black":
table_score -= 7 - max(abs(i-7),abs(j-7))
elif stone == "white":
table_score += 7 - max(abs(i-7),abs(j-7))
if color == "white":
if stone == "white":
table_score -= 7 - max(abs(i-7),abs(j-7))
elif stone == "black":
table_score += 7 - max(abs(i-7),abs(j-7))
return table_score
def alphaBeta(branch, alpha= -99999, beta=99999):
if branch.level <= 0:
score = branch.evaluateNega()
return score
for new_branch, i, j in branch.traverse():
new_score = -alphaBeta(new_branch, -beta, -alpha)
if new_score > beta:
return new_score
if new_score > alpha:
alpha = new_score
branch.i, branch.j = i, j
return alpha
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import itertools
import random
from collections import Counter
sym = 10 # number of symbols
spc = 4 # symbols per card
class Solution:
def __init__(self):
self.ok = []
self.n = []
self.rnd = [x for x in itertools.combinations(list(range(sym)),spc)]
random.shuffle(self.rnd)
random.shuffle(self.rnd)
for i in self.rnd:
self.__add(i)
def __add(self, k):
for i in self.ok:
if set(i).isdisjoint(k):
self.n.append(k)
return
self.ok.append(k)
def __hist(self):
return Counter(list(itertools.chain(*self.ok))).values()
def __hist_full(self):
return Counter(list(itertools.chain(*self.ok)))
def score(self):
return max(self.__hist()) - min(self.__hist())
def print_header(self):
print("number of symbols: {}".format(sym))
print("number of used symbols: {}".format(len(self.__hist())))
print("symbols per card: {}".format(spc))
print("number of cards: {}".format(len(self.ok)))
print("number of A4 papers: {} (8 cards in one paper)".format(len(self.ok) / 8))
print("histogram with indexes: {}".format(self.__hist_full()))
print("histogram: {}".format(self.__hist()))
print("hist min: {}".format(min(self.__hist()) ))
print("hist max: {}".format(max(self.__hist()) ))
print("hist dif: {}".format(max(self.__hist()) - min(self.__hist()) ))
print("score: {}".format(self.score()))
def print_solution(self):
for i in self.ok:
print(i)
def main():
best = Solution()
for _ in range(1000):
temp = Solution()
if best.score() > temp.score():
best = temp
best.print_header()
best.print_solution()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import truth_table
import numpy
import math
'''
Gets the corresponding byte array for an x vector for given [i,j] in the Karnough table.
This function is called in every iteration of the Rosenblatt perceptron learning algorithm.
Also inserts a -1 for biaz and handles the zeros in the byte array - swaps them for a -1.
'''
def next_vec_x(truth_table, i, j):
tt_element = truth_table.get_truth_index(i, j)
elem_as_str = tt_element.decode('utf-8')
vec_x = [int(element) for element in elem_as_str]
vec_x.insert(0, -1)
vec_x = [-1 if x == 0 else x for x in vec_x]
vec_x = numpy.array(vec_x)
return vec_x
'''
Picks the weight vector corresponding to a '1' in the result table for [i,j] Karnough indexes.
The weight vector is appended by a 1 (biaz weight)
'''
def get_ones(tt, i, j):
tt_element = tt.get_truth_index(i, j)
elem_as_str = tt_element.decode('utf-8')
vec_x = [int(element) for element in elem_as_str]
vec_x.append(1)
vec_x = numpy.array(vec_x)
vec_x = [-1 if x == 0 else x for x in vec_x]
return vec_x
'''
Gets the starting weight vector (all ones!)
'''
def get_starting_weight(tt):
weight_len = tt.get_dim() + 1
vec_weight = []
for i in range(weight_len):
vec_weight.append(1)
vec_weight = numpy.array(vec_weight)
return vec_weight
'''
Gets a starting weight vector and a next x vector for given [i,j] coordinates.
Also gets the result (a d scalar, which may be -1 or 1).
From this the algorithm calculates the y output vector (with sum and sign operations).
Next it calculates scalar e and lastly the next weight vector.
Memorizes the last weight vector to compare with the fresh weight vector.
If weight remains unchanged less than x times (now x is 10),
it recommends the weights for first layer neurons and an OR neuron.
'''
def rosenblatt_algorithm(tt):
vec_weight = get_starting_weight(tt)
unchanged_weights = 0
for k in range(10):
for i in range(tt.get_i() + 1):
for j in range(tt.get_j() + 1):
last_weight = vec_weight
vec_x = next_vec_x(tt, i, j)
print('vec_x:', vec_x)
scalar_d = numpy.array(tt.get_res_index(i,j))
vec_y = numpy.multiply(vec_x, vec_weight)
summed = numpy.sum(vec_y)
sgn_y = math.copysign(1, summed)
scalar_e = scalar_d - sgn_y
vec_weight = vec_weight + numpy.multiply(scalar_e, vec_x)
print('new_weight:', vec_weight, '-\n')
if numpy.array_equal(last_weight, vec_weight):
unchanged_weights += 1
else:
unchanged_weights = 0
print('{0} unchanged weight vectors in 10*{1}*{2} attempts'.
format(unchanged_weights, tt.get_i() + 1, tt.get_j() + 1))
if unchanged_weights < 10:
print('This function with given Karnough/truth table is not realizable.')
for i in range(tt.get_i() + 1):
for j in range(tt.get_j() + 1):
if tt.get_res_index(i,j) == 1:
print('Recommended first layer perceptron with weights', get_ones(tt, i, j))
or_weight = get_starting_weight(tt)
or_weight[-1] = -1
print('Recommended second layer perceptron with weights', or_weight, ' + a -1 biaz')
if __name__ == '__main__':
while True:
dim = int(input("How many variables would you like to see in the Karnough table?"))
if dim > 1:
var_matrix = truth_table.KarnoughTable(dim)
var_matrix.input_resultmatrix()
rosenblatt_algorithm(var_matrix)
break
else:
print('You should not enter less than 2-variables. try again!')
|
#count the number of bits (1's) in a sequence
# For num = 5 you should return [0,1,1,2,1,2].
# example : [0, 1, 10, 110, 100, 101 ]
def countBits(num):
def count(i):
if(i <= 0):
return 0
else:
mod = i % 2
return mod + count(i // 2)
return [count(i) for i in range(num + 1)]
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object): #1->2->3 2
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head.next == None and n == 1:
return None
def remove(head):
if head.next == None:
if n == 1:
return (1, None)
return (1, head)
current, tail = remove(head.next)
if(current + 1 == n):
return (current + 1, tail)
else:
head.next = tail
return (current + 1, head)
_, linkedList = remove(head)
return linkedList
nodes = ListNode(1)
nodes.next = ListNode(2)
obj = Solution()
val = obj.removeNthFromEnd(nodes, 1)
|
import requests
user_key = "95175c79b787c7dd4265272c6271ae8b" # api_keys
print("1. Cari Restoran") # input untuk mencari resto
print("2. Daily Menu") # input untuk daily menu (hanya tersedia di Prague)
pilih = input("Masukkan pilihan: ")
headInfo = {'user-key':user_key} # headinfo untuk isi headers, bila tidak ada ini maka response akan error
if pilih == "1":
try:
user_input = input("Masukkan nama kota: ").lower() # nama kota menggunakan lowercase
if user_input.replace(" ","").isalpha() == True: # Error Handling
host = "https://developers.zomato.com/api/v2.1/" # host dari api url
city = "cities?q=" # pemanggilan API untuk cities
headInfo = {'user-key':user_key} # headinfo untuk isi headers, bila tidak ada ini maka response akan error
url = host + city + user_input # url secara lengkap untuk cities
data = requests.get(url, headers=headInfo) #pemanggilan dari zomato dan dimasukkan dalam variabel data
data = data.json() # data diubah menjadi bentuk json
id_cities = data["location_suggestions"][0]["id"] # pemanggilan id_cities dari API
search = f"search?entity_id={id_cities}&entity_type=city" #pemanggilan search dari API menggunakan id_cities sebagai komponen url
url_jumlah_resto = host + search # url untuk mencari jumlah resto
data_jml = requests.get(url_jumlah_resto, headers=headInfo) # pemanggilan dari zomato dan dimasukkan dalam variabel data2
data_jml = data_jml.json() # data diubah menjadi bentuk json
url2 = f"https://developers.zomato.com/api/v2.1/location_details?entity_id={id_cities}&entity_type=city"
data2 = requests.get(url2, headers=headInfo) # pemanggilan dari zomato dan dimasukkan dalam variabel data2
data2 = data2.json() # data diubah menjadi bentuk json
jumlah_resto = data_jml["results_found"] #jumlah resto
if jumlah_resto > 0: # pengecekan jumlah restoran
print(f"Jumlah restoran di kota tersebut adalah: {jumlah_resto}") #user output
display = int(input("Jumlah Restaurant yang akan ditampilkan: "))
temp = 1
for i in data2['best_rated_restaurant']:
if temp < jumlah_resto:
print(f"Nama Restoran: {i['restaurant']['name']}") #user output
print(f"Jenis Restoran: {i['restaurant']['establishment'][0]}")#user output
print(f"Cuisines: {i['restaurant']['cuisines']}")#user output
print(f"Alamat: {i['restaurant']['location']['address']}") #user output
print(f"Rating: {i['restaurant']['user_rating']['aggregate_rating']}") #user output
print(f"Nomor Telepon: {i['restaurant']['phone_numbers']}") #user output
print(" ")
temp += 1
else: # apabila jumlah resto 0
print("Tidak ada restoran Zomato di daerah ini") # Error Output
except:
print("Invalid Input!") # Error Output
elif pilih == "2":
nama_resto = input("Masukkan Nama Resto : ").lower() # input nama resto
nama_kota_resto = input("Masukkan Nama Kota : ").lower() # input kota resto
url_kota_resto = f"https://developers.zomato.com/api/v2.1/locations?query={nama_kota_resto}&count=1" # url kota resto
data_kota_resto = requests.get(url_kota_resto, headers=headInfo) # pemanggilan data menggunakan API
data_kota_resto = data_kota_resto.json() # mengubah data menjadi json
entity_type_resto = data_kota_resto['location_suggestions'][0]['entity_type'] # untuk entity type
id_cities_resto = data_kota_resto['location_suggestions'][0]['entity_id'] # untuk city id
url_resto_daily = f"https://developers.zomato.com/api/v2.1/location_details?entity_id={id_cities_resto}&entity_type={entity_type_resto}" # url lengkap
data_resto_daily = requests.get(url_resto_daily, headers=headInfo) # pemanggilan data untuk daily menu
data_resto_daily = data_resto_daily.json() # mengubah data menjadi json
restoran = False
for i in data_resto_daily['best_rated_restaurant']: # pengecekan Restoran sesuai input nama resto dan kota
if i['restaurant']['name'].lower() == nama_resto:
id_resto = i['restaurant']['R']['res_id']
restoran = True
break
if restoran == True:
url_daily = f"https://developers.zomato.com/api/v2.1/dailymenu?res_id={id_resto}" # url untuk daily menu
data_daily = requests.get(url_daily, headers=headInfo) # pemanggilan API
data_daily = data_daily.json() # mengubah data menjadi json
print("Menu yang tersedia:") # user output
try:
for i in data_daily['daily_menus'][0]['daily_menu']['dishes']:
print(f"- {i['dish']['name']}") # user output
except:
print(f"{data_daily['message']}") # user output
elif restoran == False:
print("Nama Resto Tidak Tersedia") # Error Output
else:
print('Invalid Input!') #Error Output
|
import sys
import utils.inputReaders as ir
print("Day 5 puzzle: Binary Boarding");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#read the file
board_passes = ir.read_oneline_records_as_list_entries(puzzle_file)
def get_seat_range_by_code(single_code, bound):
range_half = int(((bound[1] + 1)-bound[0])/2)
# code for lower half of range
if single_code in ["F","L"]:
return [bound[0],bound[1] - range_half]
# and the upper half
if single_code in ["B","R"]:
return [bound[0]+range_half, bound[1]]
def binary_split (code,bound):
new_bound = get_seat_range_by_code (code[0],bound)
if len(code)>1:
approx_pos = binary_split(code[1:],new_bound)
else:
# at the very end, the low and high bound will be exactly the same
# pointing to the location
return new_bound[0]
return approx_pos
seats = []
for board_pass in board_passes:
seat_row = binary_split(board_pass[0:7],[0,127])
seat_col = binary_split(board_pass[7:],[0,7])
seats.append(seat_row * 8 + seat_col)
print ("the highest seat id is %d" %(max(seats)))
seats.sort()
for i in range(len(seats)-1):
if seats[i+1] - seats[i] > 1:
print ("potential gap between seats %d and %d" %(seats[i] ,seats[i+1])) |
import sys
print("Day 6 puzzle: Chronal Coordinates");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
coordinates = []
with open(puzzle_file, 'r') as puzzle_in:
for cur_line in puzzle_in:
x = int(cur_line.split(",")[0].strip())
y = int(cur_line.split(",")[1].strip())
coordinates.append([x,y])
puzzle_in.close()
def get_cab_distance (start_x,start_y,end_x,end_y):
return abs(end_x - start_x) + abs(end_y - start_y)
def convert_coord_to_string (x,y):
return str(x)+"-"+str(y)
def get_x_from_key (key):
return int(key[0])
def get_y_from_key (key):
return int(key[-1])
# part 1
sorted_by_y = sorted(coordinates, key=lambda x:x[1])
sorted_by_x = sorted(coordinates, key=lambda x:x[0])
[min_y, max_y] = [sorted_by_y[0][1],sorted_by_y[-1][1]]
[min_x, max_x] = [sorted_by_x[0][0],sorted_by_x[-1][0]]
[top_c,left_c,right_c,down_c] = [sorted_by_y[0],sorted_by_x[0],sorted_by_x[-1],sorted_by_y[-1]]
# from minx,miny to maxx,maxy
# get all the points and try to calculate distance to
# any of given coordinates
max_dist = get_cab_distance(min_x,min_y,max_x,max_y)
areas = {}
for y in range(min_y,max_y + 1):
for x in range (min_x,max_x + 1):
dist_to_comp = max_dist
winning_loc = []
for target_loc in coordinates:
cur_dist = get_cab_distance(x,y,target_loc[0],target_loc[1])
# we hit the coordinate, no point to process
if cur_dist == 0:
winning_loc = target_loc
dist_to_comp = 0
break
# new closest
elif cur_dist < dist_to_comp:
dist_to_comp = cur_dist
winning_loc = target_loc.copy()
# a tie, reset the winner
elif cur_dist == dist_to_comp:
winning_loc = []
if len(winning_loc):
coord_key = convert_coord_to_string(winning_loc[0],winning_loc[1])
if coord_key not in areas:
areas[coord_key] = 1
else:
areas[coord_key] = areas[coord_key] + 1
# border areas are always infinite, remove them from list of entries
for c in areas.keys():
if get_x_from_key(c) == min_x or get_x_from_key(c) == max_x:
areas[c] = -1
elif get_y_from_key(c) ==min_y or get_y_from_key(c) == max_y:
areas[c] = -1
print (areas)
print ("The biggest area is ", max(areas.values()))
# part two
def is_safe (x, y, safe_dist, coordinates):
dist_to_comp = 0
for target_loc in coordinates:
dist_to_comp += get_cab_distance(x,y,target_loc[0],target_loc[1])
return dist_to_comp < safe_dist
# calculate safe region
regions = []
# safe_distance = 32
safe_distance = 10000
for [cx,cy] in coordinates:
# build safe areas around coordinates
print ("\nchecking around coordinate ", [cx,cy])
safe_flag = True
side_len = 1
region_size = 0
while safe_flag:
safe_flag = False
if side_len == 1:
if not is_safe(cx,cy,safe_distance,coordinates):
print ("can't build around coordinates, if they are unsafe")
break
else:
region_size += 1
for y in range(cy-side_len, cy+side_len+1):
if y == cy-side_len or y == cy+side_len:
for x in range(cx-side_len, cx+side_len+1):
if is_safe(x, y, safe_distance, coordinates):
safe_flag = True
region_size += 1
else:
for x in [cx-side_len, cx+side_len]:
if is_safe(x, y, safe_distance, coordinates):
safe_flag = True
region_size += 1
side_len += 1
print ("overall region size is: ", region_size)
regions.append(region_size)
print ("The biggest safe region is: ", max(regions)) |
import sys
import utils.locationHelpers as lh
print("Day 22 puzzle: Crab Combat");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
player1_deck =[]
player2_deck = []
with open(puzzle_file, 'r') as puzzle_in:
deck = 0
for cur_line in puzzle_in:
if cur_line.strip() == "":
deck = 0
if deck == 1:
player1_deck.append(int(cur_line.strip()))
elif deck == 2:
player2_deck.append(int(cur_line.strip()))
if cur_line.strip() == "Player 1:":
deck = 1
elif cur_line.strip() == "Player 2:":
deck = 2
puzzle_in.close()
deck1_len = len(player1_deck)
deck2_len = len(player2_deck)
double_deck = deck1_len * 2
deck1_index = 0
deck2_index = 0
# print (player1_deck,player2_deck)
def get_winner (card1,card2):
return 1 if card1>card2 else 2
def get_score (winner_deck):
winner_score = 0
for i in range(1,len(winner_deck)+1):
winner_score += i*winner_deck[-i]
return winner_score
def update_winner_deck(winner_deck, card1, card2):
winner_deck = winner_deck[1:]
c1 = card1 if card1>card2 else card2
c2 = card2 if card1>card2 else card1
winner_deck.append(c1)
winner_deck.append(c2)
return winner_deck
def update_looser_deck(looser_deck):
looser_deck = looser_deck[1:]
return looser_deck
rnd_cntr = 0
while deck1_len * deck2_len != 0:
#play
rnd_cntr += 1
print ("deck 1 %d deck 2 %d" %(deck1_len, deck2_len))
c1 = player1_deck[0]
c2 = player2_deck[0]
winner = get_winner(c1,c2)
if winner == 1:
player1_deck = update_winner_deck(player1_deck,c1,c2)
player2_deck = update_looser_deck(player2_deck)
deck1_len +=1
deck2_len -=1
elif winner == 2:
player2_deck = update_winner_deck(player2_deck,c1,c2)
player1_deck = update_looser_deck(player1_deck)
deck2_len +=1
deck1_len -=1
print ("round %d winner is player %d" %(rnd_cntr, winner))
print (player1_deck, deck1_len)
print (player2_deck, deck2_len)
ws = 0
if len(player1_deck)>0:
print ("player 1 wins")
ws = get_score (player1_deck)
else:
print ("player 2 wins")
ws = get_score (player2_deck)
print ("part 1: winner score is: %d" %(ws))
|
import sys;
print("Day 17 puzzle: Spinlock ");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
offset = 0;
#open file
with open(puzzle_file, 'r') as puzzle_in:
offset = int(puzzle_in.read().strip("\n"));
puzzle_in.close();
def calc_new_pos (index, cb_len, offset):
np = index
# from cur pos, move by offset
# if the offsset is bigger than remaining part of buffer
# wrap around
if offset % cb_len <= cb_len -(index + 1):
np = index + (offset % cb_len) + 1
else:
# calculate, num of tile to wrap
np = (offset % cb_len ) - (cb_len - (index + 1))
return np
max_num = int(50E6);
circ_buf_len = 1;
cur_index = 0;
num_to_store = 1;
val_at_p1 = None;
print ("spinlock starts....")
# we need to stop at 50th million operation and get the status before insert happens
while num_to_store < max_num :
# spinlock moves forward
cur_index = calc_new_pos (cur_index,circ_buf_len, offset);
if cur_index == 1:
val_at_p1 = num_to_store;
num_to_store += 1
circ_buf_len += 1
print ("the tile next to 0 is: ", val_at_p1 ); |
import sys
print("Day 14 puzzle: Chocolate Charts");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
num_recipes = 0
with open(puzzle_file, 'r') as puzzle_in:
num_recipes = int(puzzle_in.readline().strip("\n"))
puzzle_in.close()
class Elve:
def __init__(scoreboard_index):
self.index = scoreboard_index
scoreboard = [3, 7]
elve1_index = 0
elve2_index = 1
def create_receipes (rec1,rec2):
return list(str(rec1 + rec2))
def add_receipes (new_recipes,scoreboard):
[scoreboard.append(int(r)) for r in new_recipes]
return
def pick_new_receipe (cur_recipe_index, scoreboard):
num_steps = scoreboard[cur_recipe_index] + 1
next_index = -1
num_recipes = len(scoreboard)
if cur_recipe_index + num_steps < num_recipes - 1:
next_index = cur_recipe_index + num_steps
else:
next_index = (num_steps - (num_recipes - cur_recipe_index)) % num_recipes
return next_index
# num_recipes = 2018
receipes_ready = len(scoreboard)
while receipes_ready < num_recipes + 10:
new_rec = create_receipes (scoreboard[elve1_index], scoreboard[elve2_index])
add_receipes(new_rec,scoreboard)
receipes_ready = len(scoreboard)
if receipes_ready == num_recipes:
print ("------counting 10 receipes from here")
elve1_index = pick_new_receipe(elve1_index,scoreboard)
elve2_index = pick_new_receipe(elve2_index,scoreboard)
# print (scoreboard)
# print ("Elve 1 position %d" %(elve1_index))
# print ("Elve 2 position %d \n" %(elve2_index))
final_score = ''.join([str(x) for x in scoreboard[num_recipes:num_recipes+10]])
print ("The final scoreboard is: %s" %(final_score)) |
import sys
print("Day 2 puzzle: T1202 Program Alarm");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
instr_list = []
with open(puzzle_file, 'r') as puzzle_in:
instr_list = [int(instr) for instr in puzzle_in.readline().strip("\n").split(",")]
puzzle_in.close()
original_list = instr_list.copy()
# perform addition
def add (val1, val2, position):
insert_result (val1+val2,position)
return
def multiply (val1, val2, position):
insert_result (val1*val2, position)
return
def insert_result (val, position):
if position <= len(instr_list):
instr_list [position] = val
else:
print ("Invalid position %d to insert at" %(position))
return
def modify_input_data(noun=12,verb=2):
instr_list[1] = noun
instr_list[2] = verb
return
def get_val_at_pos (position):
return instr_list[position] if position <= len (instr_list) else -1
def reset_memory():
for i in range(len(original_list)):
instr_list[i] = original_list[i]
return
instructions = {
"1" : add,
"2" : multiply
}
offset = 4
for noun in range(len(instr_list)):
for verb in range (len(instr_list)):
pos = 0
reset_memory()
modify_input_data(noun,verb)
while instr_list[pos] != 99:
instructions[str(instr_list[pos])](get_val_at_pos(instr_list[pos+1]),get_val_at_pos(instr_list[pos+2]),instr_list[pos+3])
pos += offset
if instr_list[0] == 19690720:
print ("noun %d, verb %d, answer %d" %(noun,verb, 100*noun+verb))
sys.exit() |
import sys;
import math;
print("Day 3 puzzle: Spiral Memory");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
with open(puzzle_file, 'r') as puzzle_in:
for cur_line in puzzle_in:
mem_cell = int(cur_line.strip("\n"));
puzzle_in.close();
distance = 0;
spiral_len = 1;
spiral_layer = 0;
spiral_side = 1;
while spiral_len < mem_cell:
spiral_layer += 1;
spiral_len += 4 * (spiral_side + 1);
spiral_side += 2;
# now we need to calculate, the position on a given layer
# the layer starts in bottom-right corner and continues up, counterclockwise
rollback = spiral_len;
# the cell is somewhere in between...
# we know the maximal position on this kayer
# as well as side length
for i in range(4):
# process cell located on side
if rollback - mem_cell <= spiral_side - 2:
# when calculating distance, no matter which side we are at,
# we need to move to the level of layer "0" and then move
# straight through all layers
# level of layer "0" is always in the middle of side
distance = math.fabs(mem_cell - (rollback - spiral_layer)) + spiral_layer
break;
rollback -= (spiral_side - 2) ;
# process the corner
if rollback - 1 == mem_cell:
distance = 2 * spiral_layer;
break;
rollback -= 1;
print ("The distance between %d and 1 is %d" %(mem_cell,distance));
# part two - write to the cell sum of neighbours
# 147 142 133 122 59
# 304 5 4 2 57
# 330 10 1 1 54
# 351 11 23 25 26
# 362 747 806---> ...
prev_layer_vals = {};
cur_layer_vals = {};
new_val = 1;
prev_val = 1;
spiral_side = 1;
def calc_prev_corner(side):
if side:
return (side - 1)
else:
return 3;
def calc_next_corner(side):
return side;
def calc_spiral_key (side,index,corner):
return "s"+str(side)+"i"+str(index)+"c"+str(corner)
# [side, index in side, corner]
cell_pos = {
"side":-1,
"index":-1,
"corner":-1
};
while new_val < mem_cell:
# calculate memory position
# 17 16 15 14 13
# 18 5 4 3 12
# 19 6 1 2 11
# 20 7 8 9 10
# 21 22 23---> ...
if cell_pos["index"] + 1 == spiral_side:
# we need to move to corner
cell_pos["corner"] = cell_pos["side"]
cell_pos["side"] = -1
cell_pos["index"] = -1
elif cell_pos ["corner"] == 3:
# move to next layer
spiral_side += 2
prev_layer_vals = cur_layer_vals.copy()
cell_pos ["side"] = 0
cell_pos["index"] = 0
cell_pos ["corner"] = -1
elif cell_pos["side"] == -1:
# move from corner to next side
cell_pos ["side"] = cell_pos["corner"] + 1
cell_pos["index"] = 0
cell_pos ["corner"] = -1
else:
cell_pos["index"] += 1;
new_val = 0;
# determine your neighbours and calculate value stored in current memory cell:
# 147 142 133 122 59
# 304 5 4 2 57
# 330 10 1 1 54
# 351 11 23 25 26
# 362 747 806---> ...
# a starting cell on layer has 2 neighbours: corner from prev layer and zero index from prev layer
if cell_pos["index"] == 0 and cell_pos["side"] == 0:
# build a key for the layer - 1 table
if calc_spiral_key(-1,-1,3) in prev_layer_vals:
new_val = prev_layer_vals[calc_spiral_key(-1,-1,3)] + prev_layer_vals[calc_spiral_key(0,0,-1)]
else:
# this must be a first layer
new_val = 1;
# a corner cell has 2 neighbours: corner from prev layer and prev value from current layer
elif cell_pos["index"] == -1:
if calc_spiral_key(-1,-1,cell_pos["corner"]) in prev_layer_vals:
new_val = prev_layer_vals[calc_spiral_key(-1,-1,cell_pos["corner"])] + prev_val;
else:
# this must be a first layer
new_val = 1 + prev_val
# a cell on side has up to 4 neighbours: prev value from current layer; from previous layer, we consider
# cells indexed by: (index - 1), (index - 2), (index) amongst which some may turn out to be corners
else:
# we always have as neighbour the previous cell from current layer
new_val = prev_val;
# checking previous layer for cell accessed by (index -1) - this is a cell on the same level
# as the one for which we calculate the sum
if calc_spiral_key(cell_pos["side"],cell_pos["index"] - 1,-1) in prev_layer_vals:
new_val += prev_layer_vals[calc_spiral_key(cell_pos["side"],cell_pos["index"] - 1,-1)]
# but we might get the corner, instead
elif (cell_pos["index"] > 0) and calc_spiral_key(-1, - 1,cell_pos["side"]) in prev_layer_vals:
new_val += prev_layer_vals[calc_spiral_key(-1, - 1,cell_pos["side"])]
elif (cell_pos["index"] == 0) and calc_spiral_key(-1, - 1,calc_prev_corner(cell_pos["side"])) in prev_layer_vals:
new_val += prev_layer_vals[calc_spiral_key(-1, - 1,calc_prev_corner(cell_pos["side"]))]
# checking previous layer for cell accessed by (index)
if calc_spiral_key(cell_pos["side"],cell_pos["index"] , -1) in prev_layer_vals:
new_val += prev_layer_vals[calc_spiral_key(cell_pos["side"],cell_pos["index"], -1)]
# but we might consider the corner instead, if we are not the last cell on a side
# the last cell does not have (index) neighbour in the previous layer
elif (cell_pos["index"] != spiral_side -1) and calc_spiral_key(-1,-1,calc_next_corner(cell_pos["side"])) in prev_layer_vals:
new_val += prev_layer_vals[calc_spiral_key(-1,-1,calc_next_corner(cell_pos["side"]))]
# checking previous layer for cell accessed by (index - 2)
if calc_spiral_key(cell_pos["side"],cell_pos["index"] - 2, -1) in prev_layer_vals:
new_val += prev_layer_vals[calc_spiral_key(cell_pos["side"],cell_pos["index"] - 2, -1)]
# but we might hit a corner, if we are not a first cell. The first cell does not have
# (index - 2) neighbour, it has instead a neighbour from current layer
elif (cell_pos["index"] > 0) and calc_spiral_key(-1,-1,calc_prev_corner(cell_pos["side"])) in prev_layer_vals:
new_val += prev_layer_vals[calc_spiral_key(-1,-1,calc_prev_corner(cell_pos["side"]))]
# if no keys are stored, we are processing the first layer
if not(len(prev_layer_vals.keys())):
new_val += 1
# first cell on a side (except first cell in layer), has also as a neighbour the last cell on a previous side)
if cell_pos["index"] == 0:
new_val += cur_layer_vals[calc_spiral_key(cell_pos["side"] -1,spiral_side - 1,-1)]
# the last two cells on third side, has also a cell "0" as neighbour
if (cell_pos["side"] == 3 and cell_pos["index"] == spiral_side - 1) or (cell_pos["corner"] == 3):
new_val += cur_layer_vals[calc_spiral_key(0,0,-1)]
# store for next loop
cur_layer_vals[calc_spiral_key(cell_pos["side"],cell_pos["index"],cell_pos["corner"])] = new_val;
prev_val = new_val;
print ("The value for first cell with num higher than %d is %d" %(mem_cell, new_val)) |
import re;
print("Day 3 puzzle: Squares With Three Sides");
num_triangles = 0;
sequencer = 1;
sides = [[0,0,0],[0,0,0],[0,0,0]];
#open file
with open('./puzzle_input/day03.txt', 'r') as puzzle_in:
for cur_line in puzzle_in:
print(cur_line.strip("\n"));
# split string into array of directions
input_data = re.sub('\s+',' ', cur_line).strip().split(" ");
# print (input_data);
sides[0][sequencer%3] = int(input_data[0].strip());
sides[1][sequencer%3] = int(input_data[1].strip());
sides[2][sequencer%3] = int(input_data[2].strip());
# calculate triangle condition:
if (0 == sequencer%3):
if ( sides[0][0] + sides[0][1] > sides[0][2] ) and (sides[0][1] + sides[0][2] > sides[0][0]) and (sides[0][2] + sides[0][0] > sides[0][1]):
num_triangles += 1;
else:
print("this is not a triangle %d %d %d" %( sides[0][0], sides[0][1], sides[0][2] ));
if ( sides[1][0] + sides[1][1] > sides[1][2] ) and (sides[1][1] + sides[1][2] > sides[1][0]) and (sides[1][2] + sides[1][0] > sides[1][1]):
num_triangles += 1;
else:
print("this is not a triangle %d %d %d" %( sides[1][0], sides[1][1], sides[1][2] ));
if ( sides[2][0] + sides[2][1] > sides[2][2] ) and (sides[2][1] + sides[2][2] > sides[2][0]) and (sides[2][2] + sides[2][0] > sides[2][1]):
num_triangles += 1;
else:
print("this is not a triangle %d %d %d" %( sides[2][0], sides[2][1], sides[2][2] ));
sequencer += 1;
print ("number of possible trangles is: %d" %num_triangles);
puzzle_in.close(); |
import sys
import re
print("Day 12 puzzle: Subterranean Sustainability");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
init_state = [0,0]
game_of_life = {}
with open(puzzle_file, 'r') as puzzle_in:
init_state = list(puzzle_in.readline().strip("\n").split(": ")[1])
puzzle_in.readline()
for cur_line in puzzle_in:
[key,val] = cur_line.strip("\n").split(" => ")
game_of_life[key] = val
puzzle_in.close()
def get_LLCRR_key (pot_num, state):
return ''.join(state[pot_num:pot_num+5])
def get_plant_next_state (cur_state,algo):
return algo[cur_state] if cur_state in algo.keys() else "."
def set_plant_next_state (pot_num, state, next_gen):
next_gen[pot_num+2] = state
return
def set_rear_buffer(state,unconditional=False):
if state[-4:].count("#")>0 or unconditional:
[state.append(".") for x in range(4)]
return True
else:
return False
def set_front_buffer(state, unconditional=False):
if state[:4].count("#")>0 or unconditional:
[state.insert(0,".") for x in range(4)]
return True
else:
return False
# add a buffer in front and rear of the row
set_rear_buffer(init_state)
set_front_buffer(init_state)
print (''.join(init_state))
def compare_with_pattern (pattern,state,offset):
return ( pattern in ''.join(state) if pattern is not None else False)
num_gen = 20
next_state = ["."]*len(init_state)
pot_offs = 4
# after some time, the pattern repats and just moves one position right for each generation
pattern = None
ng = 0
while True:
num_pots = len(init_state)
ng += 1
for pn in range (num_pots-2):
if ng%2 != 0:
pk= get_LLCRR_key(pn,init_state)
set_plant_next_state(pn,get_plant_next_state(pk,game_of_life),next_state)
else:
pk= get_LLCRR_key(pn,next_state)
set_plant_next_state(pn,get_plant_next_state(pk,game_of_life),init_state)
if ng%2 != 0:
if compare_with_pattern(pattern,next_state,pot_offs):
print ("After %d generations, pattern appears next st contain pattern" %(ng))
break
else:
pattern = ''.join(next_state).strip('.')
if set_rear_buffer(next_state):
set_rear_buffer(init_state,True)
if set_front_buffer(next_state):
set_front_buffer(init_state,True)
pot_offs += 4
else:
if compare_with_pattern(pattern,init_state,pot_offs):
print ("After %d generations, pattern appears" %(ng))
break
else:
pattern = ''.join(init_state).strip('.')
if set_rear_buffer(init_state):
set_rear_buffer(next_state, True)
if set_front_buffer(init_state):
set_front_buffer(next_state, True)
pot_offs += 4
# calculate the sum
num_gen = 50000000000
total = 0
print ("pot offs: %d" %(pot_offs))
for i in range(len(init_state)):
if init_state[i] =="#":
#the first non-empty pot moves one position forward, each iteration
total += (i - pot_offs) + (num_gen - ng )
print ("The total after %d generations is: %d" %(num_gen,total))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(raw_input())
stack = [];
while n>0:
line = raw_input()
array = line.split()
if array[0] == 'push':
stack.append(int(array[1]))
print stack[len(stack)-1]
elif array[0] == 'pop':
stack.pop()
if len(stack) > 0:
print stack[len(stack)-1]
else: print 'EMPTY'
elif array[0] == 'inc':
if len(stack) > 0:
count = 0;
x = int (array[1])
d = int (array[2])
while x >0 and count < len(stack):
stack[count] = stack[count] + d;
x = x-1;
count = count + 1;
print stack[len(stack)-1]
else: print 'EMPTY'
n = n - 1 |
from sklearn.metrics import confusion_matrix, mean_squared_error
from sklearn.neural_network.multilayer_perceptron import MLPClassifier
from nn_classification_plot import plot_hidden_layer_weights, plot_histogram_of_acc, plot_images
import numpy as np
__author__ = 'bellec,subramoney'
"""
Computational Intelligence TU - Graz
Assignment 2: Neural networks
Part 1: Regression with neural networks
This file contains functions to train and test the neural networks corresponding the the questions in the assignment,
as mentioned in comments in the functions.
Fill in all the sections containing TODO!
"""
def ex_2_1(input2, target2):
"""
Solution for exercise 2.1
:param input2: The input from dataset2
:param target2: The target from dataset2
:return:
"""
# parse target2 2nd column
pose2 = []
for target in target2:
pose2.append(target[1])
mlp = MLPClassifier(activation='tanh', hidden_layer_sizes=6)
print("===========fit started===========")
mlp.fit(input2, pose2)
print("===========fit finished===========")
print("classes_: ", mlp.classes_)
print("n_layers_: ", mlp.n_layers_)
plot_hidden_layer_weights(mlp.coefs_[0])
print("===========predict started===========")
prediction = mlp.predict(input2)
print("===========predict finished===========")
cnf_matrix = confusion_matrix(pose2, prediction)
print(cnf_matrix)
return
def ex_2_2(input1, target1, input2, target2):
individualTarget1 = target1[:, 0]
individualTarget2 = target2[:, 0]
classifiers = []
training_scores = []
test_scores = []
for i in range(10):
classifiers.append(MLPClassifier(activation='tanh', hidden_layer_sizes=20, max_iter=1000, random_state=i))
for mlp in classifiers:
mlp.fit(input1, individualTarget1)
training_scores.append(mlp.score(input1, individualTarget1))
test_scores.append(mlp.score(input2, individualTarget2))
plot_histogram_of_acc(training_scores, test_scores)
best_index = test_scores.index(max(test_scores))
best_prediction = classifiers[best_index].predict(input2)
cnf_matrix = confusion_matrix(individualTarget2, best_prediction)
print(cnf_matrix)
misclassified_images = []
for i, pred in enumerate(best_prediction):
if pred != individualTarget2[i]:
misclassified_images.append(i)
plot_images(input2, misclassified_images) |
#!/usr/bin/env python
import sys
import util
numbers = set(util.numbers_from_file(sys.argv[1]))
def find_sum(val):
for n in numbers:
if (val - n) in numbers:
return n, val - n
return None
def product_of_three():
for n in numbers:
result = find_sum(2020 - n)
if result is None:
continue
print(n * result[0] * result[1])
return
product_of_three()
|
#!/usr/bin/python
print('Welcome to a fun game of dice!')
print('We call this game 10,000.')
print('Whats your name? You\'ll be player 1')
NAME = raw_input()
print "Nice to meet you", NAME, "you read to play?"
print("first i need to know if your familiar with the rules? (y or n)")
CHOICE = raw_input()
if CHOICE == 'y':
print NAME, "knows the game. nice."
else:
print NAME, "dont know shit."
|
import re
pattern = r"eggs"
if re.match(pattern,"moreeggs_extremeeggs"): # match looks for the exact start hence it will return No match found here.
print('Match Found!')
else:
print ('No match found!') |
class MyClass():
__hiddenVariable = 0 # double underscore used to hide the variable, and hence data hiding is done.
def add(self,increment):
self.__hiddenVariable+= increment
print (self.__hiddenVariable)
object = MyClass()
object.add(5)
print (object.__hiddenVariable) #this won't be printed.
|
import re
pattern = r"bread(eggs)*bread"
if re.match(pattern, "breadeggseggsbread"):
print ("Match found")
else:
print ("Sorry") |
#reindexing series and dataframes
from pandas import Series, DataFrame
obj = Series([100,200,300,400,500], index = ['d','a','b','e','c'])
print (obj)
#reindexing Series
obj = obj.reindex(['a','b','c','d','e'])
print (obj)
#----------------------------------------------------------
data = { 'Name' : ['John','Kevin','Sam'],
'Age' : [32,42,54],
'Salary':[300,400,500]
}
frame = DataFrame(data)
print(frame)
#reindexing row of DataFrame
frame = frame.reindex([0,2,1])
print (frame)
#reindexing column of DataFrame
fields = ['Age','Name','Salary']
frame =frame.reindex(columns=fields)
print (frame) |
import numpy as np
#this will divide 10 to 50 in 5 numbers
x = np.linspace(10,50,5)
print (x)
#this won't consider the endpoint i.e. 50 here.
x = np.linspace(10,50,5, endpoint=False)
print (x)
#this will print value of 10 to 100 in equal logarithmic space
a = np.logspace(1.0,2.0,num=10)
print (a)
#this will print the same as above but with base=2
a = np.logspace(1.0,2.0,num=10,base=2)
print (a) |
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print (a)
#integer indexing on multidimensional array
b = a [[0,1,2],[0,1,0]]
print(b) #this will print element 0 from 0th row, element 1 form 1st row and element 0th from 2nd row
x = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
print (x)
row = np.array([[0,0],[3,3]])
cols = np.array ([[0,2],[0,2]])
y = x[row,cols]
print (y)
#boolean indexing
print (x[x>5]) |
"""
Question: Consider a list in Python which includes prices of all the items in a store.
Build a function to discount the price of all the products by 10%.
Use map to apply the function to all the elements of the list so that all the product prices are discounted.
"""
items = [10, 20, 30, 40, 50]
def discount(x):
x -= x*0.10
return x
result = list(map(discount,items))
print (result) |
#----------------------WRITING------------------------------
file = open('demo1.txt', 'w+')
text = input("Enter what you want to write to the file:")
file.write(text)
file.close()
#----------------------READING--------------------------------
file = open('demo.txt', 'r')
print (file.read())
#print (file.readline())
file.close()
#-----------------------APPEND------------------------------------
file = open('demo1.txt','a')
text = "I will be added to demo.txt instead of deleting previous data."
file.write(text)
file.close()
#-----------------------------------------------------------------
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in write mode
r+ open an existing file in read+write mode
a+ create file if it doesn't exist and open it in append mode
''' |
from pandas import Series, DataFrame
#sorting a series
series_2 = Series([3,7,8,5,6,2],index=[2,3,5,6,7,1])
print(series_2.sort_index())
#sorting a dataframe
data_2 = {'Speed' : [200,300,400],
'Temp' : [35,37,39],
'Humidity': [42,43,45]}
frame_2 = DataFrame(data_2)
frame_2 =frame_2.reindex([2,1,0]) #shuffled the dataframe cz its always sorted.
print(frame_2.sort_index())
#sorting the column of dataframe.
frame_2 = frame_2.reindex(columns=['Speed','Humidity','Temp'])
print(frame_2.sort_index(axis=1,ascending = False)) |
for i in range(1,11):
print (i)
#-----------------------------------------------------------
fruits = ["apple", "banana", "orange", "mango"]
for fruit in fruits:
print (fruit)
#--------------even numbers from 1 to 20---------------------
for e in range (0,21,2):
print(e) |
### import modules ###
import pygame
import random
from random import randint
import Tkinter as tk
from Tkinter import *
from pygame import *
import math
#import datetime
import sys
import time
pygame.init()
######################
### start ###
def start():
print 'welcome to big bad boy braz tower defence game!'
print 'press: 1 = map1, s = see your high scores.'
optiona = raw_input('pick an option: ')
if optiona == '1':
execfile('map1.py')
return
elif optiona == 's':
scorefile = open('scores.txt','r')
for i in scorefile:
print i
else:
start()
def endgame():
print 'Game over!'
print 'Your score was:'
print score
pygame.quit()
options = raw_input('Enter your name or type cancel: ')
if options == 'cancel':
start()
return
else:
scorefile = open('scores.txt','a')
scorefile.write(options + "_")
scorefile.write(str(score) +"\n")
scorefile.close()
start()
return
start()
|
'''
This file is in supplement with ad_rs.py. Here we implement all the problems related to recommender system explained in the ex8.pdf
'''
import numpy as np
import matplotlib.pyplot as plt
from ad_rs import *
# -- READING INPUT DATA
data = read_data('ex8_movies.mat')
# -- Y is a 1682 x 943 matrix, containing ratings (1 - 5) of 1682 movies on 943 users
Y = data['Y']
# -- R is a 1682 x 943 matrix, where R(i,j) = 1 if and only if user j gave a rating to movie i
R = data['R']
print('Average rating for movie 1 (Toy Story): %f / 5' %np.mean(Y[0, R[0, :]]),'\n')
# -- We can "visualize" the ratings matrix by plotting it with imshow
# plt.figure(figsize=(8, 8))
# plt.imshow(Y)
# plt.ylabel('Movies')
# plt.xlabel('Users')
# plt.savefig('fig4.png',format = 'png', dpi = 600, bbox_inches = 'tight')
# Load pre-trained weights (X, Theta, num_users, num_movies, num_features)
data = read_data('ex8_movieParams.mat')
# -- assigning paramters
X, Theta, num_users, num_movies, num_features = data['X'], data['Theta'], data['num_users'], data['num_movies'], data['num_features']
# -- testing our implementation of cost function calculation
# Reduce the data set size so that this runs faster
num_users = 4
num_movies = 5
num_features = 3
X = X[:num_movies, :num_features]
Theta = Theta[:num_users, :num_features]
Y = Y[:num_movies, 0:num_users]
R = R[:num_movies, 0:num_users]
# Evaluate cost function unregularized
J, grad = cofiCostFunc(np.concatenate([X.ravel(), Theta.ravel()]), Y, R, num_users, num_movies, num_features)
print('Cost at loaded parameters: ', J, '\n')
# -- checking implementation of unregularized gradients
# checkCostFunction(0)
# Evaluate cost function regularized
J, grad = cofiCostFunc(np.concatenate([X.ravel(), Theta.ravel()]), Y, R, num_users, num_movies, num_features, 1.5)
print('Cost at loaded parameters (lambda = 1.5): %.2f' % J)
print(' (this value should be about 31.34)')
# -- checking implementation of regularized gradients
checkCostFunction(1.5) |
'''
Created on Jun 26, 2019
@author: sipika
'''
from Inheritance import MainDemo
class MyClass:
def __init__(self,a,b):
self.a = a
self.b = b
print("Hello Constructor")
def Func(self):
print("My Class Function")
print(self.a,self.b)
var = MyClass(34,'abc')
var.Func()
MainDemo.main()
|
'''
Created on Jul 5, 2019
@author: sipika
'''
from tkinter import *
from tkinter import messagebox
def Go():
from TkinterDemo import NewWin
root.dstroy()
root = Tk()
root.geometry("400x400")
ent = StringVar()
label = Label(root,text="My First Tkinter Demo", bg = "Green", fg="white")
#label.pack(side=BOTTOM,fill=X)
label.grid(row=1,column=1)
entry = Entry(root,text=ent )
entry.grid(row = 1,column=2)
btn= Button(root,text= "Submit", command=Go)
btn.grid(row=0,column=1)
mainloop() |
'''
Created on May 16, 2019
@author: sipika
'''
def is_called():
def is_returned():
print("Hello")
return is_returned
new = is_called()
#Outputs "Hello"
new()
#///////////////////////////////////////////////
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def make_pretty1(func):
def inner():
print("I got decorated1111")
func()
return inner
@make_pretty
@make_pretty1
def ordinary():
print("I am ordinary")
#data = make_pretty(ordinary)
ordinary()
"""
@make_pretty
def ordinary():
print("I am ordinary")
#is equivalent to
def ordinary():
print("I am ordinary")
ordinary = make_pretty(ordinary)""" |
'''
Created on May 2, 2019
@author: sipika
'''
str = "I am an Indian"
print(list(str))
list = str.split(" ")
print (list)
for i in range(len(list)-1,-1,-1):
print(list[i].capitalize(), end=" ")
|
# Mini Project 4, Yahtzee Strategy Planner
# Principles of Computing, Part 1
# Jordan Hall
# 09/20/2015
"""
Planner for Yahtzee
Simplifications: only allow discard and roll, only score against upper level
"""
# Used to increase the timeout, if necessary
#import codeskulptor
#codeskulptor.set_timeout(20)
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequences of
outcomes of given length.
"""
answer_set = set([()])
for dummy_idx in range(length):
temp_set = set()
for partial_sequence in answer_set:
for item in outcomes:
new_sequence = list(partial_sequence)
new_sequence.append(item)
temp_set.add(tuple(new_sequence))
answer_set = temp_set
return answer_set
def score(hand):
"""
Compute the maximal score for a Yahtzee hand according to the
upper section of the Yahtzee score card.
hand: full yahtzee hand
Returns an integer score
"""
scores = [0 for dummy_idx in range(max(hand))]
for elem in hand:
scores[elem-1] += elem
return max(scores)
def expected_value(held_dice, num_die_sides, num_free_dice):
"""
Compute the expected value based on held_dice given that there
are num_free_dice to be rolled, each with num_die_sides.
held_dice: dice that you will hold
num_die_sides: number of sides on each die
num_free_dice: number of dice to be rolled
Returns a floating point expected value
"""
# Create a list to use as the starting hand for each possible completed hand from the held_dice variable
starting_hand = [elem for elem in held_dice]
# Generate a list of all sequences possible with num_die_sides and num_free_dice
all_free_sequences = gen_all_sequences(set([idx for idx in range(1,num_die_sides+1)]),num_free_dice)
# Initialize variable to sum the total value of all sequences, to later calculate expected value
total_value = 0
# Construct each possible hand by combining the starting hand with each free sequence, add the hand's score to the total value
for seq in all_free_sequences:
temp_hand = tuple(sorted(starting_hand + [elem for elem in seq]))
total_value += score(temp_hand)
# Calculate expected value by dividing total value by the number of possible hands (since all have equal probability)
exp_value = float(total_value)/float(len(all_free_sequences))
return exp_value
def gen_all_holds(hand):
"""
Generate all possible choices of dice from hand to hold.
hand: full yahtzee hand
Returns a set of tuples, where each tuple is dice to hold
"""
# Create a set of unique hold hands by dice index so that duplicate values don't intefere
hold_idx_set = set([()])
for dummy_idx in range(len(hand)):
temp_set = set()
for partial_sequence in hold_idx_set:
for idx in range(len(hand)):
new_sequence = list(partial_sequence)
if idx not in new_sequence:
new_sequence.append(idx)
temp_set.add(tuple(new_sequence))
hold_idx_set.update(temp_set)
# Convert the unique set of hold hand indexes to an actual set of hold hand values
all_holds_set = set([()])
for idx_hand in hold_idx_set:
hold_hand = tuple(sorted([hand[idx_hand[idx]] for idx in range(len(idx_hand))]))
all_holds_set.add(hold_hand)
return all_holds_set
def strategy(hand, num_die_sides):
"""
Compute the hold that maximizes the expected value when the
discarded dice are rolled.
hand: full yahtzee hand
num_die_sides: number of sides on each die
Returns a tuple where the first element is the expected score and
the second element is a tuple of the dice to hold
"""
# Get the entire set of possible holds from the hand
all_holds_set = gen_all_holds(hand)
# Initialize variables to hold the maximum exp value and corresponding hold tuple
max_exp_value = 0
max_hold = ()
# Loop through all possible holds and find the one with the highest expected value score
for hold in all_holds_set:
temp_exp_value = expected_value(hold, num_die_sides, len(hand)-len(hold))
if temp_exp_value > max_exp_value:
max_exp_value = temp_exp_value
max_hold = hold
return (max_exp_value, max_hold)
def run_example():
"""
Compute the dice to hold and expected score for an example hand
"""
num_die_sides = 6
hand = (1, 1, 1, 5, 6)
hand_score, hold = strategy(hand, num_die_sides)
print "Best strategy for hand", hand, "is to hold", hold, "with expected score", hand_score
run_example()
#import poc_holds_testsuite
#poc_holds_testsuite.run_suite(gen_all_holds)
|
def minmax(a, b):
"return (min(a, b), max(a, b))"
if a <= b:
return (a, b)
else:
return (b, a)
def thisShouldNeverHappen(reason=None):
if reason is None:
reason = "This should never happen"
assert False, reason
def thisIsNotHandled(reason=None):
if reason is None:
reason = "This case is not handled"
assert False, reason
|
# 相加相乗平均 (x+y)/2 >= sqrt(xy) より
# x+y=Aなので A/2 >= sqrt(xy)
# 両辺二乗して (A/2)^2 >= xy
# よって最大値は (A/2)^2
a = int(input())
print((a//2)**2) |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, RobustScaler
from sklearn.linear_model import LinearRegression
from sklearn.feature_selection import SelectKBest, f_regression, RFE
def wrangle_data(df, target_name, modeling=False):
'''
Signature: prep_data(df, modeling=False)
Docstring:
This function accepts any dataframe and splits it into train, validate,
and test sets for EDA or modeling.
Parameters
----------
df : pandas.core.frame.DataFrame
target_name : str
target_name is the column name of the target variable
modeling : boolean, False by default
`modeling` parameter scales numeric data to use in machine learning models.
If modeling is False: The function returns unscaled X_set and y_set dataframes
If modeling is True: The function returns scaled X_set and y_set dataframes
Returns
-------
X_train, y_train, X_validate, y_validate, X_test, y_test
'''
# Create dummy variables for object dtypes
# Original object dtype columns are dropped
df = add_encoded_columns(df, drop_encoders=True)
# After columns are coded, this function accepts a cleaned and encoded
# dataframe and returns train, validate, and test sets
train, validate, test = train_validate_test(df)
# Split the train, validate, and test sets into 3 X_set and y_set
X_train, y_train = attributes_target_split(train, target_name)
X_validate, y_validate = attributes_target_split(validate, target_name)
X_test, y_test = attributes_target_split(test, target_name)
# If modeling is True
if modeling:
X_train, X_validate, X_test = add_scaled_columns(train, validate, test)
return X_train, y_train, X_validate, y_validate, X_test, y_test
def add_encoded_columns(df, drop_encoders=True):
'''
Signature: add_encoded_columns(df, drop_encoders=True)
Docstring:
This function accepts a DataFrame, creates encoded columns for object dtypes,
and returns a DataFrame with or without object dtype columns.
Parameters
----------
df : pandas.core.frame.DataFrame
Returns
-------
f, encoded_columns
'''
if df.select_dtypes('O').columns.to_list() == []:
return df
columns_to_encode = df.select_dtypes('O').columns.to_list()
encoded_columns = pd.get_dummies(df[columns_to_encode], drop_first=True, dummy_na=False)
df = pd.concat([df, encoded_columns], axis=1)
if drop_encoders:
df = df.drop(columns=columns_to_encode)
return df
else:
return df, encoded_columns
def train_validate_test(df):
'''
Signature: train_validate_test(df)
Docstring:
Parameters
----------
pandas.core.frame.DataFrame
Returns
-------
train, validate, test
'''
train_validate, test = train_test_split(df, test_size=.20, random_state=123)
train, validate = train_test_split(train_validate, test_size=.25, random_state=123)
return train, validate, test
def attributes_target_split(data_set, target_name):
'''
Signature: attributes_target_split(df, target)
Docstring:
Parameters
----------
pandas.core.frame.DataFrame
Returns
-------
'''
x = data_set.drop(columns=target_name)
y = data_set[target_name]
return x, y
def add_scaled_columns(train, validate, test, scaler=RobustScaler()):
'''
Signature: add_scaled_columns(train, validate, test, scaler)
Docstring:
Parameters
----------
pandas.core.frame.DataFrame
Returns
-------
train, validate, test
'''
columns_to_scale = train.select_dtypes(exclude='uint8').columns.to_list()
new_column_names = [c + '_scaled' for c in columns_to_scale]
scaler.fit(train[columns_to_scale])
# scale columns in train, validate and test sets
train_scaled = scaler.transform(train[columns_to_scale])
validate_scaled = scaler.transform(validate[columns_to_scale])
test_scaled = scaler.transform(test[columns_to_scale])
# drop columns that are now scaled
train.drop(columns=columns_to_scale, inplace=True)
validate.drop(columns=columns_to_scale, inplace=True)
test.drop(columns=columns_to_scale, inplace=True)
# concatenate scaled columns with the original train/validate/test sets
train = pd.concat([train,
pd.DataFrame(train_scaled,
columns=new_column_names,
index=train.index.values
)],
axis=1)
validate = pd.concat([validate,
pd.DataFrame(validate_scaled,
columns=new_column_names,
index=validate.index.values
)],
axis=1)
test = pd.concat([test,
pd.DataFrame(test_scaled,
columns=new_column_names,
index=test.index.values
)],
axis=1)
return train, validate, test
def features_for_modeling(predictors, target, k_features):
'''
Signature: features_for_modeling(predictors, target, k_features)
Docstring:
Parameters
----------
Returns
-------
'''
df_best = pd.DataFrame(select_kbest(predictors, target, k_features))
df_rfe = pd.DataFrame(select_rfe(predictors, target, k_features))
df_features = pd.concat([df_best, df_rfe], axis=1)
return df_features
def select_kbest(predictors, target, k_features=3):
'''
Signature: select_kbest(predictors, target, k_features=3)
Docstring:
Parameters
----------
pandas.core.frame.DataFrame
Returns
-------
'''
f_selector = SelectKBest(f_regression, k=k_features)
f_selector.fit(predictors, target)
f_mask = f_selector.get_support()
f_features = predictors.iloc[:,f_mask].columns.to_list()
print(f"Select K Best: {len(f_features)} features")
print(f_features)
return None
# return predictors[f_features]
def select_rfe(X, y, k_features=3):
'''
Signature: rfe(predictors, target, k_features=3)
Docstring:
Parameters
----------
pandas.core.frame.DataFrame
Returns
-------
'''
lm = LinearRegression()
rfe_init = RFE(lm, k_features)
X_rfe = rfe_init.fit(X, y)
rfe_mask = rfe_init.support_
rfe_features = X.iloc[:, rfe_mask].columns.to_list()
print(f"Recursive Feature Elimination: {len(rfe_features)} features")
print(rfe_features)
return None
#return X[rfe_features]
|
#!-*- coding:utf-8 -*-
# __author__ : Sora
# ___time___ : 2019/06/24/15:05
# SECTION 1 - IMPORTS
import networkx as nx
import numpy as np
import random as rd
import matplotlib.pyplot as plt
import warnings
import formula
init_nodes = int(input("Please type in the initial number of nodes (m_0): "))
final_nodes = int(input("\nPlease type in the final number of nodes: "))
m_parameter = int(input("\nPlease type in the value of m parameter (m<=m_0): "))
a = int(input("\nPlease type in the value of a : "))
print("\n")
print("Creating initial graph...")
G = nx.DiGraph()
for i in range (init_nodes):
G.add_node(i)
nx.draw(G, node_size=30)
plt.show()
print("Graph created. Number of nodes: {}".format(len(G.nodes())))
print("Adding nodes...")
def rand_prob_node():
nodes_probs = []
for node in G.nodes():
node_degr = G.in_degree(node)
node_proba = (node_degr + a) / (len(G.edges()) + a * len(G.nodes()))
nodes_probs.append(node_proba)
random_proba_node = np.random.choice(G.nodes(),p=nodes_probs)
return random_proba_node
def add_edge():
if len(G.edges()) == 0:
random_proba_node = 0
else:
random_proba_node = rand_prob_node()
new_edge = (random_proba_node, new_node)
print("Edge: {} {}".format(new_node + 1, random_proba_node + 1))
if new_edge in G.edges():
print("edge is exist!")
add_edge()
else:
print("add edge sucess!")
G.add_edge(new_node, random_proba_node)
# nx.draw(G, node_size=30)
# plt.show()
print("Edge added: {} {}".format(new_node + 1, random_proba_node + 1))
count = 0
new_node = init_nodes
for f in range(final_nodes - init_nodes):
print("----------> Step {} <----------".format(count))
G.add_node(init_nodes + count)
print("Node added: {}".format(init_nodes + count + 1))
count += 1
for e in range(0, m_parameter):
add_edge()
new_node += 1
print("\nFinal number of nodes ({}) reached".format(len(G.nodes())))
nx.draw(G, pos=nx.random_layout(G), node_size=3, width=0.05)
print("density:", formula.density(G))
print("clustering coefficient:", formula.clustering_coefficient(G))
a = formula.average_path_length(G)
print('nx.shortest_path_length(G):', a)
plt.savefig("price.png", dpi=1000)
plt.show()
for node in G.nodes():
node_degr = G.in_degree(node)
# print("node {} degree is {}".format(node + 1,node_degr))
|
"""
* Написать функцию которая считает кол-во символов в строке, встречающихся более 1 раза
* Вернуть кол-во этих символов
*
"""
import collections
def count_repeated_symbols(s):
count = 0
dict = collections.Counter(s)
for key in dict:
if dict[key] > 1:
count += 1
return count
print(count_repeated_symbols("aaaabbc"))
print(count_repeated_symbols("abbc"))
print(count_repeated_symbols("abbbc"))
print(count_repeated_symbols("abbccc"))
print(count_repeated_symbols("aabac"))
|
def main():
#escribe tu código abajo de esta línea
a = int(input())
lista = []
i = 0
if a>0 :
while i<a :
valor = input()
lista.append(valor)
i = i+1
print(lista)
listanodobles = []
for i in lista :
if i not in listanodobles:
listanodobles.append(i)
print(listanodobles)
else:
print('Error')
pass
if __name__=='__main__':
main()
|
""" My new app
gonna make a lot of $$$
"""
import math
# inherit from object to get additional features
class Circle(object):
""" an advanced toolkit """
version = '0.2'
def __init__(self, radius):
self.radius = radius
# this is cool! do this so you don't expose radius init variable
# is run after radius and updates your code!!!
@property
def radius(self):
return self.diameter / 2.0
@radius.setter
def radius(self, radius):
self.diameter = radius * 2.0
@staticmethod
def angle_to_grade(angle):
return math.tan(math.radians(angle)) * 100.0
def area(self):
""" perform a quad """
p = self.__perimeter()
r = p / math.pi / 2.0
return math.pi * r ** 2.0
def perimeter(self):
return 2.0 * math.pi * self.radius
__perimeter = perimeter
@classmethod
def from_bbd(cls, bbd):
radius = bbd / 2.0 / math.sqrt(2.0)
#return Circle(radius)
return cls(radius)
class Tire(Circle):
def perimeter(self):
return Circle.perimeter(self) * 1.25
print(Circle.version)
c = Circle(10)
print(c.radius)
print(c.area())
print(c.perimeter())
t = Tire(22)
print(t.radius)
print(t.area())
print(t.perimeter())
print("--------")
print(c.angle_to_grade(10))
|
"""
https://www.freecodecamp.org/news/python-property-decorator/
"""
class House(object):
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, new_price):
if new_price > 0 and isinstance(new_price, float):
self._price = new_price
else:
print("Please enter a valid price")
@price.deleter
def price(self):
print("boo")
del self._price
house = House(222.34)
print(house.price)
house.price = 150.01
print(house.price)
del house.price
|
# Write a program that prints the numbers from 1 to 100.
# For multiples of three, print "Fizz" instead of the number.
# For multiples of five, print "Buzz"
# For multiples of both, print "FizzBuzz"
data = []
n = 0
while n < 100:
n = n + 1
data.append(n)
print data
multiple_of_three = []
for b in data:
if b % 3 == 0:
multiple_of_three.append(b)
print multiple_of_three
multiple_of_five = []
for d in data:
if d % 5 == 0:
multiple_of_five.append(d)
print multiple_of_five
new = []
for c in data:
if c in multiple_of_three and c in multiple_of_five:
new.append("FizzBuzz")
elif c in multiple_of_three:
new.append('Fizz')
elif c in multiple_of_five:
new.append('Buzz')
else:
new.append(c)
print new
|
from Queue import *
import copy
from helper import *
def backTrackingSearch(board, theSquares, thePeers):
"""
Wrapper function to house backtracking algorithm.
Returns a solution or failure 'False'.
"""
#Deep copies to avoid altering arguments if BTS is called multiple times
squares = copy.deepcopy(theSquares)
peers = copy.deepcopy(thePeers)
#Grab list of keys of original squares and dict. to track currently set squares
origSquares, setSquares = setSquareInfo(board, theSquares)
#Remove original square values from their peer's domains (these values will never be allowed)
removeOrigValsFromAllPeerDomains(board, squares, peers, origSquares)
#Start recursive call
return backTrack(board, squares, peers, origSquares, setSquares)
def backTrack(board, squares, peers, origSquaresIn, setSquaresIn):
"""
Recursive method that essentially performs a DFS search to incrementally
build the board by assigning single values that don't currently cause
conflict. If we run into undeniable conflict later in the tree, we
return 'False' and "back-track" in the tree to assign a different value
than the one that was initially thought was acceptable.
This is to say that it visits each empty square and tries assigning values
to if from its domain. Whenever a conflict is apparent it trys the next.
If it succeeds but later we see another square has exhausted all of its
domain options, we know the previous value was a mistake.
We then backtrack.
"""
#Original Squares is list of keys, setSquares is a full map of set squares
originalSquares = copy.deepcopy(origSquaresIn)
setSquares = copy.deepcopy(setSquaresIn)
#Function I made that helped tremendously in debugging
#printCurrentState(board, squares, setSquares, originalSquares)
#Base Case: Return the completed board if the last assignment led completion
assignedBoard = assignmentComplete(board, squares, setSquares)
if assignedBoard:
return assignedBoard #a string representation of complete sudoku board
#Decide the next square to assign based on the MRV heuristic
aSquare = MRVNextEmptySquare(board, squares, originalSquares, setSquares)
domainOfSquare = board.dict[aSquare]
#Start iterating through all potential values to assign to the square
for value in domainOfSquare:
#Update the set-square dictionary
setSquares[aSquare] = value
#If conflict between this square value and already set ones, try a new value
if assignmentConflict(board, aSquare, peers, value, setSquares):
continue
else: #No conflicts with this assigned square value-- Move on.
#After this past assignment, update domains and see if the board is invalid.
#Important: 'newBoard' wont overwrite 'board' domains, if this turns out to be a bad value.
anyZeroDomains, newBoard = forwardCheck(board, aSquare, setSquares, peers)
if anyZeroDomains:
continue
#Recusive call to determine if the past assignment completed
# the board. If not, we ran into a problem later in the recursion
# even though this assigned value seemed to cause no immediate
# conflict. So we continue to the next possible assignement.
boardSolved = backTrack(newBoard, squares, peers, originalSquares, setSquares)
if boardSolved != False:
return boardSolved
else:
continue
#If we iterate through all possible domain values and no assignment works,
# we clearly assigned an incorrect value before. Return False and go back a
# layer of recursion to try a new a past value.
return False
def removeOrigValsFromAllPeerDomains(board, squares, peers, origSquares):
"""Remove originally set square values from all of their peer's domains."""
for origSquare in origSquares:
for peer in peers[origSquare]:
origSquareVal = board.dict[origSquare][0]
peerDomain = board.dict[peer]
if origSquareVal in peerDomain:
peerDomain.remove(origSquareVal)
def assignmentConflict(board, square, peers, squareVal, setSquares):
"""
Function to determine if a potential square value will cause a conflict
with it's already-assigned peers.
Return True if conflict. Otherwise, False.
"""
conflict = False
for peer in peers[square]:
#If the given peer IS in fact already set, check there's no conflict
if setSquares[peer] != False:
#Fail if a set peer is the same value as the current used squareVal
if squareVal == setSquares[peer]:
return True
#If no peer causes conflict, return False-- no conflicts
return False
def MRVNextEmptySquare(board, squares, originalSquares, setSquares):
"""
Function to choose the next square on the board to assign a value to.
Utalizes the "Minimum Remaining Values" (MRV) heuristic, in which it
chooses the square with a domain containing the fewest legal values.
Also only searches through those squares that are not yet assigned.
Returns a square (key).
"""
#We know that the largest a domain value can be is 9. 10 guarantees a choice.
smallestDomain = 10
minRemainValueSquare = None
for square in squares:
if square not in originalSquares and setSquares[square]==False:
squareDomainSize = len(board.dict[square])
if squareDomainSize < smallestDomain:
smallestDomain = squareDomainSize
minRemainValueSquare = square
return minRemainValueSquare
def forwardCheck(board, newlyAssignedSquare, setSquares, peers):
"""
Multi-purpose function, called after a new square is assigned a value. It:
1. Removes this newly-set square value from all of the squares peer domains.
2. Checks if any given square has no more values in its domain-- conflict.
Overall, forwardCheck both updates the dictionary and ends early if it
determines that a conflict will soon be present. If this function is called,
the new square value doesnt conflict with any already set values. Then,
the only option for failure is if any unassigned square has a 0-domain.
Returns tuple: boolean (if conflict due to zero-domain) and the updated board.
Important Note: This makes a deep copy of its argument board. This is so
that in the case of a backtrack, the old board is intact--unmodified.
"""
updatedBoard = copy.deepcopy(board)
anyZeroDomains = False
#Stage 1:
newAssignedVal = setSquares[newlyAssignedSquare]
for peer in peers[newlyAssignedSquare]:
if newAssignedVal in updatedBoard.dict[peer]:
updatedBoard.dict[peer].remove(newAssignedVal)
#Stage 2
if len(board.dict[peer]) == 0:
anyZeroDomains = True
#print("Hit a zero domain for: " + peer+". Backtrack?")
return anyZeroDomains, updatedBoard
return anyZeroDomains, updatedBoard
def setSquareInfo(board, squares):
"""
Called once in the wrapper function of BTS. This function does two things:
1. Creates a list of keys representing all the initially filled squares.
2. Creates a dictionary that stores which squares are "set" with a value.
Value is 'True'(some int) for 'assigned' and 'False' for 'not-assigned'.
To be used in functions such as getNextEmptySquare().
Returns a list and a dictionary
"""
#Key values (A1-I9) of original squares
origSquares = []
#Dictionary to hold all 'set' values
setSquares = dict()
for square in squares:
#If it isn't initially len=1, it wasn't initially set
if len(board.dict[square]) != 1:
setSquares[square] = False
else:
#This will always be a one element list, so safe to cast to string
setSquares[square] = board.dict[square][0]
origSquares.append(square)
return origSquares, setSquares
def assignmentComplete(board, squares, assigned):
"""
Function to determine if a board configuration is completely filled in.
Returns a string representing the board if every square is assigned a single value.
Otherwise, returns False.
"""
boardAssignment = ""
for square in squares:
if assigned[square] == False:
return False
else:
boardAssignment += assigned[square]
return boardAssignment
def buildSquaresAndPeers():
"""
Method to construct dictionaries for the squares and their respective
peers on the sudoku board. To be used essentially all helper functions.
"""
#A suduko board is numbered 1-9 and A-I
columns = "123456789"
rows = "ABCDEFGHI"
#List of all labeled "squares": 'A1', 'A2', ... ,'I9'
squares = cross(rows, columns)
#List of "units", where a unit is a (column, row, box) that requires all
# unique assignments to be avoid conflict.
unitlist = ([cross(rows, c) for c in columns] +
[cross(r, columns) for r in rows] +
[cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])
#Dictionary to hold all units that a particular square lives in
units = dict((s, [u for u in unitlist if s in u]) for s in squares)
#Dictionary maps squares to their respective peers
peers = dict((s, set(sum(units[s],[]))-set([s])) for s in squares)
return squares, peers
|
#料金を計算する関数
def calc(func,arg=1):
price = func(arg)
return price
#子供料金を計算する関数
def child(arg):
return 400 * arg
#大人料金を計算する関数
def adult(arg):
return 1200 * arg
#12歳,3人の料金を計算数する
age = 12
num = 3
if age < 16 :
price = calc(child,num)
else:
price = calc(adult,num)
print(f"{age}歳,{num}人で{price}円です。") |
sum = 50 + 37 + 10
limit = 100
if sum>=limit :
result = "Pass"
else:
result = "Failure"
result += "/" + str(sum-limit)
print(sum)
print("-" * 20)
print(result)
|
numlist = [3, 4.2, 10, "x", 1, 9]
sum = 0
for num in numlist:
if not isinstance(num, (int,float)):
print(num, "数値ではない値が含まれていました。")
break
sum += num
else:
print("合計", sum) |
from random import randint
miss = 0
correct = 0
print("問題!3回間違えたら終了。qで止める")
while miss<3:
a = randint(1,100)
b = randint(1,100)
ans = a + b
question = f"{a} + {b}は?"
value = input(question)
if value == "q":
break
if value == str(ans):
correct += 1
print("正解です!")
else:
miss += 1
print("不正解です!","×" * miss)
print("-" * 20)
print("正解:",correct)
print("不正解:",miss) |
import time
def run(bridge, duration=15, delta=1, delay=0):
'''Fade down the light at a specified delay.
Keyword arguments:
bridge -- the bridge that will be controlled (required)
duration -- length of time the effect will last (default 15)
delta -- amount of change between colors (default 1)
Requirement: delta > 1
delay -- delay between fade commands (default 0)
'''
# Keep track of time in effect
start_time = time.time()
# Ensure we do not get an infinite loop
delta = int(delta)
if delta == 0:
raise RuntimeError('rainbow_fade:delta value cannot be 0')
# Max selction of colors possible
max_colors = 256
# Main loop
i = 0
while True:
bridge.set_color_hex(chr(i))
# Check if effect duration has past
if time.time() - start_time > duration:
break
time.sleep(delay)
i = (delta + i) % max_colors
|
import crypt
import string
def brute():
file= open('passwd','r')
line = file.readline()
line = line[:-1]
line = line.split(":")
for i in string.ascii_lowercase:
for j in string.ascii_lowercase:
for k in string.ascii_lowercase:
if crypt.crypt(i+j+k,line[1]) == line[1]:
print('haslo: ',i+j+k)
brute()
|
def find_diff(current_word, next_word):
cost = 0
x = 1
d = dict()
e = dict()
alphabet = list('abcdefghijklmnopqrstuvwxyz')
for i in alphabet:
d[i] = x
x += 1
return min(abs(d[current_word] - d[next_word]), 26 - abs(d[current_word] - d[next_word]))
def driver(text):
text = list(text)
total_cost = find_diff('a', text[0])
for i in range(0, len(text) - 1):
current_cost = find_diff(text[i], text[i + 1])
total_cost += current_cost
print(total_cost)
def main():
n = input()
driver(n)
if __name__ == "__main__":
main()
|
n = input()
n = list(input())
if n.count('A') > n.count('D'):
print("Anton")
elif n.count('A') < n.count('D'):
print("Danik")
else:
print("Friendship") |
fruit = 'banana'
letter = fruit[1]
length = len(fruit)
last = fruit[length-1]
# print(letter)
# print(length)
# print(last)
# print(fruit[-1])
# 6.3 pg. 68
# index = 0
# while index < len(fruit):
# letter = fruit[index]
# print(letter)
# index = index+1
# print('-------')
# Exercise 6.1 pg.68
# index = len(fruit) - 1
# while index >= 0:
# letter = fruit[index]
# print(letter)
# index = index-1
# for char in fruit:
# print(char)
# 6.4 String slices
# s = 'Monty Python'
# print(s[0:5])
# print(s[6:12])
# print(fruit[:3])
# print(fruit[3:])
# print(fruit[3:3])
# fruit_2 = fruit[:]
# print(fruit_2)
# 6.5 Strings are immutable pg. 69
greeting = 'Hello, world!'
new_greeting = 'J' + greeting[1:]
# print(new_greeting)
# 6.6 Looping and counting pg. 70
# word = 'banana'
# count = 0
# for letter in word:
# if letter == 'a':
# count = count + 1
# print(count)
# Exercise 6.3
# def count_char(word: str, char: str):
# count = 0
# for letter in word:
# if letter == char:
# count = count + 1
# print(count)
# count_char('banana', 'a')
# 6.7 The in operator pg. 70
# if 'a' in 'banana':
# print('OMG!!!')
# 6.8 String comparision pg. 70
# word = 'banana'
# if word == 'banana':
# print('All right, bananas.')
# word = 'Banana'
# if word < 'banana':
# print('Your word, ' + word + ', comes before banana.')
# elif word > 'banana':
# print('Your word, ' + word + ', comes after banana.')
# else:
# print('All right, banannas.')
# 6.9 string methods pg. 71
stuff = 'Hello world'
# print(type(stuff))
# print(dir(stuff))
# print(help(str.capitalize))
# new_stuff = stuff.upper()
# print(new_stuff)
# index = stuff.find('wo')
# print(index)
# line = ' Her we go again!!! '
# print(line.strip())
line = 'Please have a nice day and focus on important for you things ;)'
# print(line.startswith('Please'))
# print(line.startswith('p'))
# print(line.lower())
# print(line.lower().startswith('p'))
# Exercise 6.4 pg. 73
# word = 'banana'
# print(word.count('a'))
# 6.10 Parsing strings pg. 73
# data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
# atpos = data.find('@')
# print(atpos)
# sppos = data.find(' ', atpos)
# print(sppos)
# host = data[atpos+1:sppos]
# print(host)
# 6.11 Format operator pg. 74
# camels = 42
# print('i have spotted %d camels.' % camels)
# print('In %d years I have spotted %g %s.' % (3, 0.1, 'camels'))
# print('%d %d %d' % (1, 22, 333))
|
# Ex 5.1 pg. 65
def user_input():
try:
user_input = input('Enter a number: ')
if user_input == 'done':
return user_input
return float(user_input)
except ValueError as err:
raise ValueError('Invalid input')
total = 0.0
average = 0.0
count = 0
while True:
try:
user_data = user_input()
except ValueError as err:
print(err)
continue
if user_data == 'done':
break
total = total + user_data
count = count + 1
average = total / count
print('Total:', total)
print('Count:', count)
print('Average:', average)
|
# 11 Regular Expressions pg. 129
import re
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# if re.search('^From:', line):
# print(line)
# 11.1 Character matching in regular expressions pg. 130
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# if re.search('^F..m:', line):
# print(line)
# . any character
# * zero or more characters
# + one or more characters
# .+ any character more than one
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# if re.search('^From:.+@', line):
# print(line)
# 11.2 Extracting data using regular expressions pg. 131
# s = 'Hello from csev@umich.edu to cwen@iupui.edu about the meeting @2PM'
# lst = re.findall('\S+@\S+', s)
# print(lst)
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# x = re.findall('[a-zA-Z0-9]\S*@\S*[a-zA-Z]', line)
# if len(x) > 0:
# print(x)
# 11.3 Combining searching and extracting pg. 133
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# if re.findall('^X\S*: [0-9.]+', line):
# print(line)
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# x = re.findall('^X\S*: ([0-9.]+)', line)
# if len(x) > 0:
# print(x)
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# x = re.findall('^Details:.*rev=([0-9.]+)', line)
# if len(x) > 0:
# print(x)
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# x = re.findall('^From .* ([0-9][0-9]):', line)
# if len(x) > 0:
# print(x)
# 11.4 Escape character pg. 137
# x = 'We just received $10.00 for cookies.'
# y = re.findall('\$[0-9.]+', x)
# print(y)
# 11.5 Summary pg.137
# ^ - beginning of the line
# $ - end of the line
# . - any character(a wildcard)
# \s - whitespace character
# \S - non-whitespace character(opposite of \s)
# * - zero or more characters
# *? - zero or more characters in "non-gready mode"
# + - one or more characters
# +? - one or more characters in "non-gready mode"
# [aeiou] - match a single character from specified set
# [a-z0-9] - range of characters, match a lowercase letter or digit
# [^A-Za-z] - a caret sign in the set notation inverts the logic. Any character
# except the uppercase or lowercase letter
# ( ) - are ignored for the purpose of matching, allow to extract a particular
# subset of the matched string but not the whole string
# \b - empty string, only at the start or end of a word
# \B - empty string, only NOT at the start or end of a word
# \d - any decimals digit, equivalent to the set [0-9]
# \D - any non-digit character, equivalent to the set [^0-9]
|
from itertools import permutations, combinations, combinations_with_replacement
lst = [1, 2, 3]
# perm = permutations(lst)
perm = permutations(lst, 2)
for i in list(perm):
print(i)
print('\n\n')
comb = combinations(lst, 2)
for i in list(comb):
print(i)
print('\n\n')
comb = combinations_with_replacement(lst, 2)
for i in list(comb):
print(i)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 1 21:55:46 2015
@author: Imanol
This code implements PSRL for the chain problem.
1-2-3-4-5-...-H
Where there is a positive reward only at the last state.
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 1 10:53:57 2015
@author: Imanol
"""
import numpy as np
import posterior_sampling
#---------------------------------------------------------------------------
def Reward(s,a,H):
"""
Computes the real reward which is one only if the state is the
last one in chain
IN
s: int
Current State.
a: int
Action taken
H: int
Time frame and number of States
OUT
r: real reward
"""
r = 0
if s==H:
r=1
return r
#---------------------------------------------------------------------------
def NewState(s,a,H):
"""
Computes the next state given the current state and the action taken.
The next state is computed by adding the action to the current state.
Except for the beginning and ending of the chain where if the action
results in a non existent state, the agent stays in the current state.
IN
s: int
Current State.
a: int
Action taken
H: int
Time frame and number of States
OUT
newstate: int
New State
"""
return max(min(s+a,H),1)
#--------------------------------------------------------------------------
def policy(R,P,Rl,Pl,S,A,H):
"""
Computes the policy for each state action pair (s,a). The policy is
computed as a greedy action taken over a upper confidence bound Value
Function.
IN
R: dict{int}
Dictionary containing the sum of observed rewards for each tupke
(t,s,a).
P: dict{np.array}
Dictionary of arrays of dimension |S|x1 containing the probability
of going to state s' given the tuple (t,s,a).
Rl: dict{int}
Sampled mean from posterior distribution
Pl: dict{int}
Sampled transition probabilities from posterior distribution
S: list
States
A: list
Actions
H: int
Number of states and time frame
"""
# We start by creating two dictionaries that will store the value function
# and the optimal policy
Q = {}
mu = {}
c1 = H
# We initialize Q and mu at time H-1
# For every state-action pair the value function is equal to the sampled
# reward plus the sampled expected to go cost.
# Qmax is an array which will store the maximum value of Q for each state.
Qmax = np.zeros((c1))
for t in xrange(H-1,-1,-1):
new_Qmax = np.zeros((c1))
for s in S:
Q = []
for a in A:
# We call the linearprogram function which solves the MDP for
# s,a
Q.append(Rl[(t,s,a)] + np.sum(Qmax*Pl[(t,s,a)]))
new_Qmax[s-1] = np.max(Q)
mu[(t,s)] = np.argmax(Q)*2-1
Qmax = new_Qmax
return mu
#---------------------------------------------------------------------------
def play(mu,H,R,P):
"""
Runs an episode given the optimal policy mu. The function updates
the dictionaries R, P, Lambda registering the new visited states and
the corresponding rewards.
IN
mu: dict
Dictionary of optimal actions acording to (t,s) pair.
H: int
Number of states or times.
R: dict{list}
Dictionary containing a list of observed rewards for each tuple
(t,s,a).
P: dict{np.array}
Dictionary of arrays of dimension |S|x1 containing the probability
of going to state s' given the tuple (t,s,a).
"""
s = 1
rew = 0
for t in xrange(H):
a = mu[(t,s)]
r = Reward(s,a,H)
rew+=r
n_s = NewState(s,a,H)
R[(t,s,a)].append(r)
P[(t,s,a)][n_s-1]= P[(t,s,a)][n_s-1]+1
s = n_s
return rew
#---------------------------------------------------------------------------
def PSRL(S,A,H,L):
"""
Computes the number of episodes it takes for PSRL to experience a positive
reward.
IN
S: list
States
A: list
Actions
H: int
Number of states and time frame
L: int
Number of episodes
OUT
success: int
Number of episodes before UCRL experiences a positive reward.
"""
# Make a very simple prior
mu = 0.
n_mu = 1.
tau = 1.
n_tau = 1.
prior_ng = posterior_sampling.convert_prior(mu, n_mu, tau, n_tau)
c1 = len(S)
prior_dir = np.ones(c1)
R = {}
P = {}
time = range(H);
av_rew = []
rew = 0
for l in xrange(L):
Rl = {}
Pl = {}
for t in time:
for s in S:
for a in A:
if (t,s,a) not in R:
R[(t,s,a)]=[]
P[(t,s,a)]=np.array([0 for i in xrange(c1)])
# If we have not visited (t,s,a) we don't update our prior
if len(R[(t,s,a)]) == 0:
Rpost = prior_ng
Ppost = prior_dir
else:
data = np.array(R[(t,s,a)])
counts = P[(t,s,a)]
# Posterior updating
Rpost = posterior_sampling.update_normal_ig(prior_ng, data)
Ppost = posterior_sampling.update_dirichlet(prior_dir, counts)
# Posterior sampling
Rl[(t,s,a)]= posterior_sampling.sample_normal_ig(Rpost)[0]
Pl[(t,s,a)]= posterior_sampling.sample_dirichlet(Ppost)
# Optimal policy
mu = policy(R,P,Rl,Pl,S,A,H)
#Episode
rew += play(mu,H,R,P)
if (l+1)%10==0:
print rew/float(10)
av_rew.append(rew/float(10))
rew = 0
return av_rew
if __name__ == '__main__':
H = 10
S = range(1,H+1)
A = [-1,1]
L = 10000
succp = []
succp = PSRL(S,A,H,L)
#for H in xrange(1,15):
# S = range(1,H+1)
#succp.append(PSRL(S,A,H,L))
#linesp = [[succp[i][j] for i in xrange(9,14)] for j in xrange(100)]
#plt.plot(linesp) |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 1 10:53:57 2015
@author: Imanol
This code implements UCRL for the chain problem.
1-2-3-4-5-...-H
Where there is a positive reward only at the last state.
"""
import numpy as np
import scipy.optimize as op
import random
import matplotlib.pyplot as plt
#---------------------------------------------------------------------------
def Reward(s,a,H):
"""
Computes the real reward which is one only if the state is the
last one in chain
IN
s: int
Current State.
a: int
Action taken
H: int
Time frame and number of States
OUT
r: real reward
"""
r = 0
if s==H:
r=1
return r
#---------------------------------------------------------------------------
def NewState(s,a,H):
"""
Computes the next state given the current state and the action taken.
The next state is computed by adding the action to the current state.
Except for the beginning and ending of the chain where if the action
results in a non existent state, the agent stays in the current state.
IN
s: int
Current State.
a: int
Action taken
H: int
Time frame and number of States
OUT
newstate: int
New State
"""
return max(min(s+a,H),1)
def linearprogram(Qmax,c1,P,R,Pl,Rl,Lambda):
"""
Computes the Linear Program:
max R(s,a) + sum(P(s'|s,a)*Qmax(s'))
Over R and P inside confidence sets.
IN
Qmax: np.array
Array containing the maximum value of the cost to go function
for every state from the previous iteration.
c1: int
Number of states
P: np.array
sum of times s' has been observed from (t,s,a)
R: int
sum of rewards observed at (t,s,a)
Pl: int
upper confidence bound for transition probabilities
Rl: int
upper confidence bound for rewards
Lambda: int
number of times (t,s,a) has been observed
OUT
max_value: int
max R(s,a) + sum(P(s'|s,a)*Qmax(s'))
"""
worse_states = list(np.argsort(Qmax+np.random.rand(c1)*0.00001))
new_prob = np.array(P/max(float(Lambda),1.0))
best_state = worse_states.pop()
new_prob[best_state] = min(1,new_prob[best_state]+Pl/2.0)
i=0
while sum(new_prob)>1 and i<len(worse_states):
state = worse_states[i]
prob_update = max(0,1-sum(new_prob)+new_prob[state])
new_prob[state] = prob_update
i+=1
max_value = np.sum(new_prob*Qmax) + Rl +R/max(float(Lambda),1.0)
return max_value
#---------------------------------------------------------------------------
def policy(R,P,Lambda,Rl,Pl,S,A,H):
"""
Computes the policy for each state action pair (s,a). The policy is
computed as a greedy action taken over a upper confidence bound Value
Function.
IN
R: dict{int}
Dictionary containing the sum of observed rewards for each tupke
(t,s,a).
P: dict{np.array}
Dictionary of arrays of dimension |S|x1 containing the probability
of going to state s' given the tuple (t,s,a).
Lambda: dict{int}
Dictionary containing the number of times the tuple (t,s,a) has been
visited
Rl: dict{int}
Upper bound for the reward for tuple (t,s,a)
Pl: dict{int}
Upper bound for the transition probabilities for tuple (t,s,a)
S: list
States
A: list
Actions
H: int
Number of states and time frame
"""
# We start by creating two dictionaries that will store the value function
# and the optimal policy
mu = {}
c1 = H
# We initialize Q and mu at time H-1
# For every state-action pair the value function is equal to the maximum
# over the bounded rewards set given
# Qmax is an array which will store the maximum value of Q for each state.
Qmax = np.zeros((c1))
for t in xrange(H-1,-1,-1):
new_Qmax = np.zeros((c1))
for s in S:
Q = []
for a in A:
# We call the linearprogram function which solves the MDP for
# s,a
Q.append(linearprogram(Qmax,c1,P[(t,s,a)],
R[(t,s,a)],Pl[(t,s,a)],
Rl[(t,s,a)],Lambda[(t,s,a)]))
new_Qmax[s-1] = np.max(Q)
mu[(t,s)] = np.argmax(Q)*2-1
Qmax = new_Qmax
return mu
#---------------------------------------------------------------------------
def play(mu,H,R,P,Lambda):
"""
Runs an episode given the optimal policy mu. The function updates
the dictionaries R, P, Lambda registering the new visited states and
the corresponding rewards.
IN
mu: dict
Dictionary of optimal actions acording to (t,s) pair.
H: int
Number of states or times.
R: dict{int}
Dictionary containing the sum of observed rewards for each tupke
(t,s,a).
P: dict{np.array}
Dictionary of arrays of dimension |S|x1 containing the probability
of going to state s' given the tuple (t,s,a).
Lambda: dict{int}
Dictionary containing the number of times the tuple (t,s,a) has been
visited
"""
s = 1
rew = 0
for t in xrange(H):
a = mu[(t,s)]
r = Reward(s,a,H)
rew +=r
n_s = NewState(s,a,H)
R[(t,s,a)] = R[(t,s,a)]+r
P[(t,s,a)][n_s-1]= P[(t,s,a)][n_s-1]+1
Lambda[(t,s,a)] = Lambda[(t,s,a)] +1
s = n_s
return rew
#---------------------------------------------------------------------------
def UCRL(S,A,H,d,L):
"""
Computes the number of episodes it takes for UCRL to experience a positive
reward.
IN
S: list
States
A: list
Actions
H: int
Number of states and time frame
d: double
precision delta
L: int
Number of episodes
OUT
success: int
Number of episodes before UCRL experiences a positive reward.
"""
c1 = len(S)
c2 = len(A)
# P and R will be dictionaries that will store the experienced transitions
# and rewards. Lambda will store the number of times a tuple (t,s,a ) is
# visited.
R = {}
P = {}
Lambda = {}
time = range(H)
av_rew = []
rew = 0
for l in xrange(L):
# Rl and Pl will store the upper confidence bounds for the rewards
# and the transition probabilities
Rl = {}
Pl = {}
for t in time:
for s in S:
for a in A:
# Initialization of the dictionaries
if (t,s,a) not in R:
R[(t,s,a)]=0.0
P[(t,s,a)]=np.zeros((c1))
Lambda[(t,s,a)]=0.0
# Confidence bounds
nl = Lambda[(t,s,a)]
Rl[(t,s,a)] = np.sqrt(7*np.log(2*c1*c2*H*(l+1)/float(d))/float(2*max(nl,1)))
Pl[(t,s,a)] = np.sqrt(14*c1*np.log(2*c1*c2*H*(l+1)/float(d))/float(max(nl,1)))
# Optimal policy
mu = policy(R,P,Lambda,Rl,Pl,S,A,H)
# Episode
rew += play(mu,H,R,P,Lambda)
if (l+1)%10==0:
av_rew.append(rew/float(10))
rew = 0
return av_rew
#---------------------------------------------------------------------------
if __name__ == '__main__':
"""
Main Function
"""
H = 2
S = range(1,H+1)
A = [-1,1]
d = .05
L = 1000
succ = []
for H in xrange(1,15):
S = range(1,H+1)
succ.append(UCRL(S,A,H,d,L))
lines = [[succ[i][j] for i in xrange(14)] for j in xrange(100)]
plt.plot(lines)
|
import csv
import sys
from util import Node, StackFrontier, QueueFrontier
# Maps names to a set of corresponding person_ids
names = {}
# Maps person_ids to a dictionary of: name, birth, movies (a set of movie_ids)
people = {}
# Maps movie_ids to a dictionary of: title, year, stars (a set of person_ids)
movies = {}
def load_data(directory):
"""
Load data from CSV files into memory.
"""
# Load people
with open(f"{directory}/people.csv", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
people[row["id"]] = {
"name": row["name"],
"birth": row["birth"],
"movies": set()
}
if row["name"].lower() not in names:
names[row["name"].lower()] = {row["id"]}
else:
names[row["name"].lower()].add(row["id"])
# Load movies
with open(f"{directory}/movies.csv", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
movies[row["id"]] = {
"title": row["title"],
"year": row["year"],
"stars": set()
}
# Load stars
with open(f"{directory}/stars.csv", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
try:
people[row["person_id"]]["movies"].add(row["movie_id"])
movies[row["movie_id"]]["stars"].add(row["person_id"])
except KeyError:
pass
def main():
if len(sys.argv) > 2:
sys.exit("Usage: python degrees.py [directory]")
directory = sys.argv[1] if len(sys.argv) == 2 else "large"
# Load data from files into memory
print("Loading data...")
load_data(directory)
print("Data loaded.")
source = person_id_for_name(input("Name: "))
if source is None:
sys.exit("Person not found.")
target = person_id_for_name(input("Name: "))
if target is None:
sys.exit("Person not found.")
path = shortest_path(source, target)
if path is None:
print("Not connected.")
else:
degrees = len(path)
print(f"{degrees} degrees of separation.")
path = [(None, source)] + path
for i in range(degrees):
person1 = people[path[i][1]]["name"]
person2 = people[path[i + 1][1]]["name"]
movie = movies[path[i + 1][0]]["title"]
print(f"{i + 1}: {person1} and {person2} starred in {movie}")
def shortest_path(source, target):
"""
Returns the shortest list of (movie_id, person_id) pairs
that connect the source to the target.
If no possible path, returns None.
"""
# Create a frontier and add the source as its initial node
frontier = QueueFrontier()
frontier.add(Node(source, None, None))
# Create empty explored set
explored_states = []
# Searching for a node with target state by removing nodes from the
# frontier and adding their neighbors to it
while True:
# If the forntier is empty, there is no path to between source and
# target and thus None is returned
if frontier.empty():
return None
# Remove a node from the frontier and jumpt out of the cycle, if it
# containts the target we are searching for
target_node = frontier.get_node_with_state(target)
if not target_node:
removed = frontier.remove()
else:
break
# Add the state of removed node to the explored states to avoid cycles
explored_states.add(removed.state)
# Add neighbors of removed node to the frontier
for neighbor in neighbors_for_person(removed.state):
state = neighbor[1]
action = neighbor[0]
if state not in explored_states:
frontier.add(Node(state, removed, action))
target_node = None
# Reconstruct the path to the target node
path = []
index = target_node
while True:
if index.state == source:
path.reverse()
return path
path.append((index.action, index.state))
index = index.parent
def person_id_for_name(name):
"""
Returns the IMDB id for a person's name,
resolving ambiguities as needed.
"""
person_ids = list(names.get(name.lower(), set()))
if len(person_ids) == 0:
return None
elif len(person_ids) > 1:
print(f"Which '{name}'?")
for person_id in person_ids:
person = people[person_id]
name = person["name"]
birth = person["birth"]
print(f"ID: {person_id}, Name: {name}, Birth: {birth}")
try:
person_id = input("Intended Person ID: ")
if person_id in person_ids:
return person_id
except ValueError:
pass
return None
else:
return person_ids[0]
def neighbors_for_person(person_id):
"""
Returns (movie_id, person_id) pairs for people
who starred with a given person.
"""
movie_ids = people[person_id]["movies"]
neighbors = set()
for movie_id in movie_ids:
for person_id in movies[movie_id]["stars"]:
neighbors.add((movie_id, person_id))
return neighbors
def print_frontier(frontier):
for node in frontier.frontier:
person = people[node.state]['name']
if not node.action:
movie = "N/A"
else:
movie = movies[node.action]['title']
if not node.parent:
parent = "N/A"
else:
parent = people[node.parent.state]['name']
print(f"[S: {person}, A: {movie}, P: {parent}] ")
def print_path(path, source):
state = people[source]['name']
path.reverse()
for link in path:
action = movies[link[0]]['title']
target = people[link[1]]['name']
print(f"{ state } played in { action } with { target }")
state = target
def debug():
load_data("small")
path = shortest_path('144', '102')
print(path)
if __name__ == "__main__":
main()
# debug()
|
def is_isomorphic(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
tmp_dict = dict()
tmp_set = set()
for i in range(len(s)):
if s[i] not in tmp_dict:
if t[i] in tmp_set:
return False
tmp_dict[s[i]] = t[i]
tmp_set.add(t[i])
else:
if tmp_dict[s[i]] != t[i]:
return False
return True
if __name__ == "__main__":
print(is_isomorphic("add", "tee"))
print(is_isomorphic("mom", "man"))
print(is_isomorphic("paper", "title"))
print(is_isomorphic("foo", "bar"))
print(is_isomorphic("gaga", "coco"))
print(is_isomorphic("abc", "bbc"))
|
"""Vertex and Graph Classes for a directed graph"""
class Vertex:
"""
class to keep track of vertices in a graph and their associated edges
"""
def __init__(self, key):
"""
initialize vertex with id number and empty dictionary of edges
"""
self._id = key
self._connected_to = {}
def add_neighbor(self, neighbor, weight=1):
"""
add information about a connected vertex to the vertex's _connected_to
dictionary
key is vertex, value is weight
"""
self._connected_to[neighbor] = weight
def remove_neighbor(self, neighbor, weight=1):
"""
remove neighbor information
"""
if neighbor in self._connected_to.keys():
self._connected_to.pop(neighbor)
def __str__(self):
"""
returns human-readable version of vertex's connections
"""
return str(self._id) + ' connected to ' + str([node._id for node in
self._connected_to])
def get_connections(self):
"""return list of connections"""
return self._connected_to.keys()
def get_id(self):
""" returns id of vertex"""
return self._id
def get_weight(self, neighbor):
"""
returns the weight of an edge betweeen self and a
given neighbor
"""
return self._connected_to[neighbor]
class Graph:
"""class to manage verices and edges in a directed graph"""
def __init__(self, graph_type='u'):
"""
contains a dictionary - _vertex_list - mapping vertex keys to vertex
objects and a count of the number of vertices in the graph
"""
self._graph_type = graph_type
self._vertex_list = {}
self._vertex_count = 0
def create_vertex(self, key):
"""
creates a new vertex and returns that vertex
"""
self._vertex_count += 1
new_vertex = Vertex(key)
self._vertex_list[key] = new_vertex
return new_vertex
def get_vertex(self, key):
""" returns the vertex object associated with a key """
if key in self._vertex_list:
return self._vertex_list[key]
else:
return None
def __contains__(self, key):
"""
returns a boolean indicating whether a given vertex is in the graph
"""
return key in self._vertex_list
def add_edge(self, tail_key, head_key, weight=1):
"""
adds a new edge to the graph. If either vertex is not present, it will
be added first.
in directed graph, edge is only added for the tail vertex
"""
if tail_key not in self._vertex_list:
self.create_vertex(tail_key)
if head_key not in self._vertex_list:
self.create_vertex(head_key)
self._vertex_list[tail_key].add_neighbor(self._vertex_list[head_key],
weight)
if self._graph_type == 'u':
self._vertex_list[head_key].add_neighbor(self._vertex_list
[tail_key], weight)
def get_vertices(self):
"""
return a list of keys of all vertices in the graph
"""
return self._vertex_list.keys()
def __iter__(self):
"""returns an iterator of all vertices"""
return iter(self._vertex_list.values())
def remove_vertex(self, key):
# TODO implement remove_vertex function
# 1. make sure vertex is in graph
# 2. get list of connected vertices
# 3. remove all relevant edges from connected vertices
# 4. remove actual vertex
# 5. update vertex count
pass
def remove_edge(self, tail_id, head_id, weight=1):
# TODO implment remove_edge function
# 1. check list in tail_id & remove if found
pass
def get_edges(self):
"""
returns a list of edges in the graph
edges represented as a tuple: (tail, head, weight)
"""
edge_list = []
for node in self._vertex_list:
edge_list.extend(node.get_connections())
return edge_list
def get_edge_count(self):
return len(self.get_edges())
def __str__(self):
# TODO create __str__ method for Graph Class
pass
def test():
g = Graph()
g.create_vertex(1)
g.create_vertex(2)
g.add_edge(1, 2)
g.add_edge(2, 3)
g.add_edge(3, 1)
g.add_edge(1, 2, 1)
print(str(g.get_vertex(1)))
print(str(g.get_vertex(2)))
print(str(g.get_vertex(3)))
if __name__ == '__main__':
test()
|
"""
Simple breadth first search function
"""
import graph_class
class BfsVertex(graph_class.Vertex):
"""
Minor class adjustments to make BFS work better
"""
def __init__(self, vertex_id, edges=None):
"""
Adapt base class setup to make _node_id a list of lists:
[[node_id, explored],...]
"""
# graph_class.Vertex.__init__(self, vertex_id, edges)
super().__init__(vertex_id, edges)
for node_number in range(len(self._node_id)):
self._node_id[node_number] = [self._node_id[node_number], False]
def mark_explored(self):
"""
Marks node as explored
"""
for node in self.get_nodes():
node[1] = True
def mark_unexplored(self):
"""
Marks node as unexplored
"""
for node in self.get_nodes():
node[1] = False
def explored_value(self):
"""
returns boolean as to whether node is explored
"""
return self.get_nodes()[1]
def __repr__(self):
"""printable list of nodes and edges for the object"""
return "Node: " + str(self._node_id) + " Edge: " \
+ str(self._edge_list)
class BfsGraph(graph_class.Graph):
"""
minor class adjustments to make this work better
"""
def create_vertex(self, key):
"""
creates a new vertex and returns that vertex
"""
new_vertex = BfsVertex(key)
self._vertex_list[key] = new_vertex
return new_vertex
def bfs(graph, start_node=1):
"""Basic BFS function"""
search_queue = []
start_vertex = graph.get_vertex(start_node)
search_queue.append(start_vertex)
start_vertex.mark_explored()
while len(search_queue) > 0:
active_node = search_queue.pop(0)
for edge in active_node.get_edges():
linked_vertex = graph.get_vertex(edge)
if not linked_vertex.get_nodes()[0][1]:
linked_vertex.mark_explored()
search_queue.append(linked_vertex)
def create_graph(graph_data):
"""
create graph class object from file
"""
new_graph = BfsGraph()
for item in range(len(graph_data)):
new_graph.create_vertex(graph_data[item][0][0])
for edge in range(len(graph_data[item][1])):
new_graph.get_vertex(
graph_data[item][0][0]).add_edge(graph_data[item][1][edge])
return new_graph
test_graph_data = [[[1], [2, 3, 5]],
[[2], [1, 2]],
[[3], [1, 4, 5]],
[[4], [3, 5]],
[[5], [1, 3, 4]]]
if __name__ == '__main__':
test_graph = create_graph(test_graph_data)
print(str(test_graph))
print('run bfs')
bfs(test_graph, 1)
print(str(test_graph))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.