text
stringlengths 37
1.41M
|
---|
class TreeNode(object):
def __init__(self, data = None, no = None, yes = None):
"""Creates a tree with specified dataand reference to the left and right children"""
self.item = data
self.left = no
self.right = yes
def addLeft(self, data = None, no = None, yes = None):
self.left = TreeNode(data, no, yes)
def addRight(self, data = None, no = None, yes = None):
self.right = TreeNode(data, no, yes)
def getLeft(self):
return self.left
def getRight(self):
return self.right
def setValue(self, val):
self.item = val
def getValue(self):
return self.item
|
"""
Play tic tac toe.
Players are represented by values True (o) and False (x). Spaces are
represented by None.
"""
from copy import deepcopy
O = True
X = False
SPACE = None
CHAR_TO_PLAYER = {'o': O, 'x': X, ' ': SPACE}
PLAYER_TO_CHAR = {O: 'o', X: 'x', SPACE: " "}
def did_player_win(board, player):
"""Has 'player' won on this board?"""
return (did_player_win_horizontal(board, player) or
did_player_win_vertical(board, player) or
did_player_win_diagonal(board, player))
def did_player_win_horizontal(board, player):
"""Did 'player' win horizontally on this board?"""
for row in board:
if all(spot == player for spot in row):
return True
return False
def did_player_win_vertical(board, player):
"""Did 'player' win vertically on this board?"""
for col_index in range(3):
if all(board[row_index][col_index] == player
for row_index in range(3)):
return True
return False
def did_player_win_diagonal(board, player):
"""Did 'player' win diagonally on this board?"""
return (all(board[i][i] == player for i in range(3)) or
all(board[i][2 - i] == player for i in range(3)))
def is_full(board):
"""Is the game over?"""
return all(all(s is not None for s in row) for row in board)
def naive_take_turn(board):
"""Take the first open spot"""
new_board = deepcopy(board)
for row in range(3):
for col in range(3):
if board[row][col] == SPACE:
new_board[row][col] = X
return new_board
def take_turn(board, player=X):
"""Return the board after o's next turn."""
(row, col), _ = tic_tac_toe_minimax(board, player)
board = deepcopy(board)
board[row][col] = player
return board
def string_to_board(board_string):
"""Convert a string into 3x3 nested lists."""
# Do some sanity checks
if len(board_string) != 9:
raise ValueError("Board doesn't have 9 spaces!")
for char in board_string:
if char not in "ox +":
raise ValueError(
"'{}' is not a valid character- board must be made up of x's,"
"o's, and spaces.".format(char))
# Is it possible x's turn?
# If x's == o's + 1, x started, o's turn
# If x's == o's, o started, o's turn
# Otherwise, this is not a reasonable board
num_xs = board_string.count('x')
num_os = board_string.count('o')
return [[CHAR_TO_PLAYER[board_string[row * 3 + col]] for col in range(3)]
for row in range(3)]
def board_to_string(board):
"""Convert board to string"""
return "".join(
"".join(PLAYER_TO_CHAR[spot] for spot in row) for row in board)
def get_next_moves(board, player):
"""
Return a dictionary of all possible moves, and their resulting boards.
"""
moves = dict()
for row in range(3):
for col in range(3):
if board[row][col] == SPACE:
moves[(row, col)] = deepcopy(board)
moves[(row, col)][row][col] = player
return moves
def get_final_score(board, player):
"""
Return the final score for player, or None if the game isn't over.
"""
if did_player_win(board, player):
return 1
if did_player_win(board, not(player)):
return -1
if is_full(board):
return 0
# Otherwise, the game isn't over yet!
return None
def tic_tac_toe_minimax(board, player, depth=0):
"""Get best next move for player and its score
Specifically, return row and col of a players best move, and and integer
representing score: -1 if the best possible outcome for the player is a
loss, 0 for a tie, 1 for a win.
Use the minmax algorithm- For all open spaces, recurse to find the other
players next move, and choose this players move to minimize the next
players score.
"""
best_row = None
best_col = None
least_next_score = float("inf")
for row_index in range(3):
for col_index in range(3):
if board[row_index][col_index] == SPACE:
# Set this space. After evaluating it we will need to unset it
board[row_index][col_index] = player
# If we just won, go here!
if did_player_win(board, player):
board[row_index][col_index] = SPACE
return (row_index, col_index), 9 - depth
# Did we draw?
if is_full(board):
# This was the only option so we can just return it
board[row_index][col_index] = SPACE
return (row_index, col_index), 0
# Otherwise recurse to get the next player's move
_, next_score = tic_tac_toe_minimax(
board, not(player), depth + 1)
if next_score < least_next_score:
least_next_score = next_score
best_row = row_index
best_col = col_index
board[row_index][col_index] = SPACE
score = -least_next_score # because the game is zero-sum
return (best_row, best_col), score
|
# https://github.com/albertauyeung/matrix-factorization-in-python
import numpy as np
class MF():
def __init__(self, R, K, alpha, beta, iterations):
"""
Perform matrix factorization to predict empty
entries in a matrix.
Arguments
- R (ndarray) : user-item rating matrix
- K (int) : number of latent dimensions
- alpha (float) : learning rate
- beta (float) : regularization parameter
"""
self.R = R
self.num_users, self.num_items = R.shape
self.K = K
self.alpha = alpha
self.beta = beta
self.iterations = iterations
def train(self):
# Initialize user and item latent feature matrice
self.P = np.random.normal(scale=1./self.K, size=(self.num_users, self.K))
self.Q = np.random.normal(scale=1./self.K, size=(self.num_items, self.K))
# Initialize the biases
self.b_u = np.zeros(self.num_users)
self.b_i = np.zeros(self.num_items)
self.b = np.mean(self.R[np.where(self.R != 0)])
# Create a list of training samples
self.samples = [
(i, j, self.R[i, j])
for i in range(self.num_users)
for j in range(self.num_items)
if self.R[i, j] > 0
]
# Perform stochastic gradient descent for number of iterations
training_process = []
for i in range(self.iterations):
np.random.shuffle(self.samples)
self.sgd()
mse = self.mse()
training_process.append((i, mse))
if (i+1) % 10 == 0:
print("Iteration: %d ; error = %.4f" % (i+1, mse))
return training_process
def mse(self):
"""
A function to compute the total mean square error
"""
xs, ys = self.R.nonzero()
predicted = self.full_matrix()
error = 0
for x, y in zip(xs, ys):
error += pow(self.R[x, y] - predicted[x, y], 2)
return np.sqrt(error)
def sgd(self):
"""
Perform stochastic graident descent
"""
for i, j, r in self.samples:
# Computer prediction and error
prediction = self.get_rating(i, j)
e = (r - prediction)
# Update biases
self.b_u[i] += self.alpha * (e - self.beta * self.b_u[i])
self.b_i[j] += self.alpha * (e - self.beta * self.b_i[j])
# Create copy of row of P since we need to update it but use older values for update on Q
P_i = self.P[i, :][:]
# Update user and item latent feature matrices
self.P[i, :] += self.alpha * (e * self.Q[j, :] - self.beta * self.P[i,:])
self.Q[j, :] += self.alpha * (e * P_i - self.beta * self.Q[j,:])
def get_rating(self, i, j):
"""
Get the predicted rating of user i and item j
"""
prediction = self.b + self.b_u[i] + self.b_i[j] + self.P[i, :].dot(self.Q[j, :].T)
return prediction
def full_matrix(self):
"""
Computer the full matrix using the resultant biases, P and Q
"""
return self.b + self.b_u[:,np.newaxis] + self.b_i[np.newaxis:,] + self.P.dot(self.Q.T) |
"""19. Write a Python program to create Fibonacci series upto n using Lambda."""
num=int(input("enter a number: "))
lis=[]
for i in range(num+1):
lis.append(i)
get_Fibonacci=lambda num:num if num<=1 else get_Fibonacci(num-1)+get_Fibonacci(num-2)
print(list(map(get_Fibonacci,lis)))
|
"""8. Write a Python program to remove the nth index character from a nonempty string."""
inp=input("enter a non empty string: ")
index = int(input("enter the index of the character you want to remove: "))
print(inp[0:index] + inp[index+1:]) |
"""16. Write a Python program to sum all the items in a list. """
no_of_items=int(input("enter the no of items you want in a list: "))
inp_list=[]
for i in range(no_of_items):
inp=int(input("enter the list items of integers : "))
inp_list.append(inp)
sum=0
for i in inp_list:
sum=sum+i
print(sum) |
"""4. Write a Python program to get a single string from two given strings, separated
by a space and swap the first two characters of each string.
Sample String : 'abc', 'xyz'
Expected Result : 'xyc abz'
"""
inp= input("enter your string: ")
new_inp=inp.split(" ")
str1=new_inp[0]
str2=new_inp[1]
new_str1=str1.replace(str1[0],str2[0])
new_str2=str2.replace(str2[0],str1[0])
print(new_str1,new_str2) |
"""11. Write a Python program to count the occurrences of each word in a given
sentence."""
inp=input("enter your sentence: ")
inp_list=inp.split()
inp_dict={}
for i in inp_list:
if i in inp_dict:
inp_dict[i]+=1
else:
inp_dict[i]=1
print(inp_dict) |
"""17. Write a Python program to multiplies all the items in a list."""
no_of_items=int(input("enter the no of items you want in a list: "))
inp_list=[]
for i in range(no_of_items):
inp=int(input("enter the list items of integers : "))
inp_list.append(inp)
mul=1
for i in inp_list:
mul=mul*i
print(mul) |
"""36. Write a Python program to sum all the items in a dictionary. """
sample_dict={1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144,
13: 169, 14: 196, 15: 225}
sum=0
for i in sample_dict:
sum=sum+sample_dict[i]
print(sum)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 16:09:37 2018
@author: xuyijun
"""
from datetime import timedelta
from datetime import datetime
# adate = datetime.strptime('12/12/2018','%m/%d/%Y')
# print(adate.strftime('%B %d, %Y))
def interval_plan_period():
return 7
def str_date_to_date_time(str_date: 'MM/DD/YYYY/'):
return datetime.strptime(str_date, '%m/%d/%Y')
def date_time_to_str_date(datetime_obj):
return datetime_obj.strftime('%m/%d/%Y')
def get_all_fridays(from_date: 'MM/DD/YYYY/', to_date: 'MM/DD/YYYY/', day_list=[5]):
tmp_list = list()
date_list = list()
# Creates a list of all the dates falling between the from_date and to_date range
for x in range((str_date_to_date_time(to_date) - str_date_to_date_time(from_date)).days + 1):
tmp_list.append(str_date_to_date_time(from_date) + timedelta(days=x))
for date_record in tmp_list:
if date_record.weekday() in day_list:
date_list.append(date_record)
return date_list
def parse_a_matric(matric, moves_date):
if ';' in str(matric):
# use the whatever thats has been written
the_matric_wanted_at_moves_date = matric
# imagine the string is '09/03/2018,20;9/3/2019,10'
# list_of_dates
# list_of_values
else:
return matric
return the_matric_wanted_at_moves_date
def write_a_matric():
the_parse_able_string = 0
return the_parse_able_string
def check_a_matric():
return 0 |
# Problem 2
# 10/10 points (graded)
# Assume s is a string of lower case characters.
# Write a program that prints the number of times the string 'bob' occurs in s.
# For example, if s = 'azcbobobegghakl', then your program should print
# Number of times bob occurs is: 2
count=0
for i in range(len(s)):
if s[i]=='b':
if (i+1)<len(s) and (i+2)<len(s):
if s[i+1]=='o' and s[i+2]=='b':
count+=1
print("Number of times bob occurs is: "+str(count))
#Solved it after 10 attempts because of "index error : string out of range"
#so added if statement "if (i+1)<len(s) and (i+2)<len(s):" |
# Murovanyi Andrey, KNIT16-A
# По дате d, m, y определить дату следующего дня
import sys
days = range(1, 32)
mounths = range(1, 13)
years = range(1901, 2016)
flag = True
while flag:
try:
d, m, y = int(input('Day: ')), int(input('Mounth: ')), int(input('Year: '))
except ValueError:
print('Day must be integer number')
continue
if d in days and m in mounths and y in years:
if d + 1 not in days:
d = 1
if m + 1 not in mounths:
m = 1
y += 1
else:
m += 1
print('Date of the next day: {}.{}.{}'.format(d, m, y))
else:
print('Data out of range!')
while True:
x = input('Try again? [y/n]').lower()
if x == 'y':
break
elif x == 'n':
sys.exit()
|
# To run this, you can install BeautifulSoup
# https://pypi.python.org/pypi/beautifulsoup4
# Or download the file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
values = []
span = soup.find_all('span')
for num in span:
values.append(int(num.string))
print ("Count: " + str(len(values)))
print("Sum: " + str(sum(values)))
|
import re
def replaceLetters(ptext, ctext):
j = 0
ctext = list(ctext)
for i in range(len(ctext)):
char = ctext[i]
if re.match('[A-Z]', char):
ctext[i] = ptext[j]
j += 1
return ''.join(ctext)
|
from insert_in_DB import *
class Person:
def take_input(self):
print("Enter your contact's information")
self.id=input("enter id :")
self.first_name = input("First name = ")
self.last_name = input("Lastst name = ")
self.age = input("Age = ")
self.phone_number = input("Phone number = ")
self.city=input("City name= ")
self.dist=input("Distric name= ")
def Entry_in_DB(self):
db1=Db()
db1.put_input(self.id,self.first_name,self.last_name,self.age,self.phone_number,self.city,self.dist)
def getEntries(self):
db1=Db()
db1.get_input()
def name_input(self):
self.first_name=input("Enter first name you want to find : ")
self.last_name=input("Enter last name of person : ")
def find_entry(self):
db1=Db()
db1.select_name_input(self.first_name,self.last_name)
def delete_by_name(self):
self.first_name=input("enter a first name for delete : ")
self.last_name=input(("enter last name : "))
def delete_entry(self):
db1=Db()
db1.delete_name(self.first_name,self.last_name)
#def update_by_name(self):
# self.id=input("enter id u want to update : ")
def update_entry(self):
db1=Db()
print("enter updated info:")
self.id=input("enter id u want to update : ")
self.first_name=input("enter new First Name : ")
self.last_name=input("Enter new Last Name : ")
db1.update_name_record(self.id,self.first_name,self.last_name)
|
import argparse
import socket
import sys
import csv
"""
Simple example pokerbot, written in python.
This is an example of a bare bones pokerbot. It only sets up the socket
necessary to connect with the engine and then always returns the same action.
It is meant as an example of how a pokerbot should communicate with the engine.
"""
THRESHOLD=10.0
class opposer():
def __init__(self,name):
self.name=name
#attributes
class Game():
def __init__(self, opponent):
self.opponent=opposer(opponent)
self.current_equity=0
self.cardmap={"2":1,"3":2,"4":3,"5":4,"6":5,"7":8,"8":9,"9":10,"10":11,"J":12,"Q":13,"K":14,"A":0}
self.equity_dic={}
self.potsize=0
self.numBoardCards=0
self.BoardCards=None
self.lastActions=None
self.legalActions=None
self.timebank=0
self.button=False
self.handId=0
self.holeCards=None
self.myBank=0
self.otherBank=0
# with open('equity.csv', 'rb') as f:
# reader=csv.reader(f)
# for row in reader:
# self.equity_dic[row[1]]=row[3]
def play_handler(self,packet):
if packet[0]=="GETACTION":
self.play(packet)
elif packet[0]=="KEYVALUE":
pass
elif packet[0]=="REQUESTKEYVALUES":
s.send("FINISH\n")
elif packet[0]=="NEWHAND":
self.handId=packet[1]
self.button=packet[2]
self.holeCards=packet[3:7]
self.myBank=packet[7]
self.otherBank=packet[8]
self.timebank=packet[9]
#self.current_equity=self.equity_dic[" ".join(packet[3:6])]
else:# handover
pass
#GETACTION potSize numBoardCards [boardCards] numLastActions [lastActions] numLegalActions [legalActions] timebank
def play(self,packet):
place=1
self.potsize=packet[place]
place+=1
self.numBoardCards=int(packet[place])
place+=1
self.BoardCards=packet[place:self.numBoardCards+place]
place+=self.numBoardCards
numLastActions=int(packet[place])
place+=1
self.lastActions=packet[place:place+numLastActions]
place+=numLastActions
numLegalActions=int(packet[place])
place+=1
self.legalActions=packet[place:place+numLegalActions]
place+=numLegalActions
self.timebank=packet[place]
class Player:
def run(self, input_socket):
# Get a file-object for reading packets from the socket.
# Using this ensures that you get exactly one packet per read.
f_in = input_socket.makefile()
data = f_in.readline().strip()
game=Game(data.split()[2])#initilize game against a certian player
while True:
# Block until the engine sends us a packet.
data = f_in.readline().strip()
# If data is None, connection has closed.
if not data:
print "Gameover, engine disconnected."
break
words = data.split()
game.play_handler(words)
# When appropriate, reply to the engine with a legal action.
# The engine will ignore all spurious responses.
# The engine will also check/fold for you if you return an
# illegal action.
# When sending responses, terminate each response with a newline
# character (\n) or your bot will hang!
#word = data.split()[0]
# if word == "GETACTION":
# Currently CHECK on every move. You'll want to change this.
# s.send("CHECK\n")
#elif word == "REQUESTKEYVALUES":
# At the end, the engine will allow your bot save key/value pairs.
# Send FINISH to indicate you're done.
# s.send("FINISH\n")
# Clean up the socket.
s.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A Pokerbot.', add_help=False, prog='pokerbot')
parser.add_argument('-h', dest='host', type=str, default='localhost', help='Host to connect to, defaults to localhost')
parser.add_argument('port', metavar='PORT', type=int, help='Port on host to connect to')
args = parser.parse_args()
# Create a socket connection to the engine.
print 'Connecting to %s:%d' % (args.host, args.port)
try:
s = socket.create_connection((args.host, args.port))
except socket.error as e:
print 'Error connecting! Aborting'
exit()
bot = Player()
bot.run(s)
|
#!/usr/bin/env python3
# usage: python3 ./baseN.py --help
import math
import argparse
def encode(text, encodeMap, encodingBit):
binary = ''.join([format(x, '08b') for x in text.encode('utf8')])
binary += (encodingBit - len(binary) % encodingBit) * '0'
splittedArray = [binary[x:x + encodingBit] for x in range(0, len(binary), encodingBit)]
encodedString = ''.join([encodeMap[int(x, 2)] for x in splittedArray])
encodedString += (2 - len(encodedString) % 2) * '='
return encodedString
def decode(text, encodeMap, encodingBit):
text = text.replace('=', '')
indexMap = [encodeMap.index(x) for x in text]
binString = ''.join([format(x, f'0{encodingBit}b') for x in indexMap])
binString += (8 - len(binString) % 8) * '0'
binArray = [binString[x:x + 8] for x in range(0, len(binString), 8)]
decodedString = bytes([int(x, 2) for x in binArray]).decode('utf8')
return decodedString
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('text', help='source text')
parser.add_argument('--map', type=argparse.FileType(), help='map file')
parser.add_argument(
'--decode', action='store_const', const=decode, default=encode, dest='function', help='decode mode')
args = parser.parse_args()
encodeMap = list(args.map.read())
encodingBit = math.floor(math.log2(len(encodeMap)))
print('Base' + str(2**encodingBit) + ' (mapsize: ' + str(len(encodeMap)) + ')')
source = args.text
print('source: ' + source)
processed = args.function(source, encodeMap, encodingBit)
print('target: ' + processed)
|
#Program to deposit and withdrawal
class Operator:
def add(self,a,b):
return a+b
def sub(self,a,b):
return a-b
def mul(self,a,b):
return a*b
def div(self,a,b):
if b==0:
return 0
else:
return a/b
class Account(Operator):
def __init__(self,bal):
self.bal=bal
def setBalance(self,bal):
self.bal=bal
def getBalance(self):
return self.bal
def deposit(self,dep):
print("deposit",dep)
self.bal=super().add(self.bal,dep)
def withdraw(self,wd):
print("withdraw",wd)
self.bal=super().sub(self.bal,wd)
a=Account(0)
print("balance",a.getBalance())
a.deposit(30000)
print("balance",a.getBalance())
a.withdraw(20000)
print("balance",a.getBalance())
|
num=int(input("Enter number : "))
count=0 #number of digits
while num>0:
count+=1
num//=10
print("The number of digits in the number is :",count)
|
first_number=int(input("Enter the first number: "))
second_number=int(input("Enter the second number: "))
total=first_number+second_number
print("Sum of two number is :",total)
|
n=int(input("Enter a number : "))
total=0
while n>0:
digit=n%10
total+=digit
n//=10
print("The sum of the digits is :",total)
|
score=[73,95,80,57,99]
#compute the sum of scores
def func_sum(s):
sum=0
for i in s:
sum+=i
return sum
total=func_sum(score)
print("Total score :",total)
print("Average score :",total/len(score))
|
low=int(input("Enter the lower limit for the range : "))
up=int(input("Enter the upper limit for the range : "))
#if the number is odd, print it.
for i in range(low,up+1):
if i%2==1:
print(i)
|
#input grades
s1=int(input("Enter the score of subject 1: "))
s2=int(input("Enter the score of subject 2: "))
s3=int(input("Enter the score of subject 3: "))
s4=int(input("Enter the score of subject 4: "))
s5=int(input("Enter the score of subject 5: "))
#Calculate average
avg=(s1+s2+s3+s4+s5)/5
print("Average =",avg)
if avg>=90:
print("Grade: A")
elif 80<=avg<90:
print("Grade: B")
elif 70<=avg<80:
print("Grade: C")
elif 60<=avg<70:
print("Grade: D")
else:
print("Grade: F")
|
a={i for i in range(1,101) if i%3==0}
b={i for i in range(1,101) if i%5==0}
print(a)
print(b)
c=a&b
print(c)
print(sorted(c))
|
myAge=input("Enter your age:")
myName=input("Enter your name:")
print("** Printing type of input value **")
print("type of myAge:",type(myAge))
print("type of myName:",type(myName))
|
a=int(input("Please Enter the First Angle of a Triangle: ")) #First angle
b=int(input("Please Enter the Second Angle of a Triangle: ")) #Second angle
c=int(input("Please Enter the Third Angle of a Triangle: ")) #Third angle
sum=a+b+c
if sum==180:
print("This is a Valid Triangle")
else:
print("This is a Invalid Triangle")
|
'''
lets say we have a list
of folder and file names that
we want to join to represent a path
'''
print('\\'.join(['folder1', 'folder2', 'file.jpg']))
'''
that would print out:
folder1\folder2\file.jpg
NOTICE that Windows uses backslashes and
that the backslashes are doubled because
each backslash needs to be escaped by another
backslash character.
If you want your programs to work on all operating
systems, you will have to write your Python scripts
to handle both cases.
that's where the 'os' module comes in
'''
import os
print( os.path.join('folder1', 'folder2', 'file.jpg')) # folder1\folder2\file.jpg
'''
If I had called this function on OS X or Linux,
the string would have been
folder1/folder2/file.jpg
notice the forward slashes
'''
####### os module examples
# creating strings for file names
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
print(os.path.join('D:\\new\\', filename))
'''
D:\new\accounts.txt
D:\new\details.csv
D:\new\invite.docx
'''
####### current working directory(cwd) or '.'
print( os.getcwd() ) # e:\AutoEstudio\Python\Automate the boring stuff with Python\MY CODE
'''
os.chdir('C:\\Windows\\System32') # also -> os.chdir(r'C:\Windows\System32')
print( os.getcwd() ) # 'C:\Windows\System32'
'''
###### absolute and relative paths
'''
There are two ways to specify a file path.
• An absolute path, which always begins with the root folder
• A relative path, which is relative to the program’s current working
directory
There are also the dot (.) and dot-dot (..) folders. These are not real
folders but special names that can be used in a path. A single period (“dot”)
for a folder name is shorthand for “this directory.” Two periods (“dot-dot”)
means “the parent folder.”
'''
####### get the absolute path of a file or folder in the current directory. os.path.abspath()
print( os.path.abspath('00-filenames-and-paths.py') )
# E:\AutoEstudio\Python\Automate the boring stuff with Python\MY CODE\reading-and-writing-files\00-filenames-and-paths.py
print( os.path.abspath('new') )
# E:\AutoEstudio\Python\Automate the boring stuff with Python\MY CODE\reading-and-writing-files\new
###### is the string an absolute path. os.path.isabs()
# here i pass a raw string (r'') not to use double \\. We could've passed a string and use \\ instead
print( os.path.isabs(r'E:\AutoEstudio\Python\Automate the boring stuff with Python\MY CODE\reading-and-writing-files\new') )
# True
####### getting a relative path given the current directory as starting point
cwd = r'E:\AutoEstudio\Python\Automate the boring stuff with Python\MY CODE\reading-and-writing-files'
f = r'E:\AutoEstudio\Python\Automate the boring stuff with Python\MY CODE\reading-and-writing-files\new\test.txt' # the file we want the relpath for
print ( os.path.relpath(f, cwd) ) # new\test.txt
# getting the directory part of the path
print( os.path.dirname( f ) ) #excludes the file: test.txt
# E:\AutoEstudio\Python\Automate the boring stuff with Python\MY CODE\reading-and-writing-files\new
# getting the basename, for a file
print( os.path.basename( f ) ) # test.txt
# or folder
print( os.path.basename( cwd ) ) # reading-and-writing-files
######### does the path exist?
print( os.path.exists( f ) ) # True
print( os.path.exists( r'Z:\folderThatDoesntExist\file.txt' ) ) # false
print( os.path.isfile( f ) ) # True
print( os.path.isdir( cwd ) ) # True
print( os.path.getsize( f ) ) # 0 size in bytes as an integer
print( os.path.getsize( r'E:\AutoEstudio\Python\Automate the boring stuff with Python' ) ) # 4096
####### return a list of all files and folders within a folder, notice is os.listdir() not os.path.listdir()
print( os.listdir(r'E:\AutoEstudio\Python\Automate the boring stuff with Python'))
'''
['01 Python Basics', '02 Flow Control', '03 Functions', '04 Handling Errors with tryexcept',
'05 Writing a Complete Program Guess the Number', '06 Lists', '07 Dictionaries', '08 More About Strings',
'09 Running Programs from the Command Line', '10 Regular Expressions', '11 Files', '12 Debugging',
'13 Web Scraping', '14 Excel Word and PDF Documents', '15 Email', '16 GUI Automation',
'automate-the-boring-stuff-with-python-2015-.pdf', 'MY CODE']
'''
totalSize = 0
for filename in os.listdir(r'E:\AutoEstudio\Python\Automate the boring stuff with Python'):
file = os.path.join('E:\\AutoEstudio\\Python\\Automate the boring stuff with Python', filename)
if os.path.isfile(file):
totalSize += os.path.getsize(file)
print( totalSize)
###### creating new folders
'''
cwd = os.getcwd()
newfolders = cwd + '\\new\\new2'
os.makedirs(newfolders) # creates new and new2 under the cwd
'''
os.makedirs(os.getcwd() + '\\new3\\new4') # this will create both new3 and new4
'''
or
os.makedirs('D:\\new3\\new4')
or
os.makedirs(r'D:\new3\new4')
'''
|
'''
You can save variables in your Python programs to binary shelf files using
the shelve module. This way, your program can restore data to variables
from the hard drive. The shelve module will let you add Save and Open
features to your program. For example, if you ran a program and entered
some configuration settings, you could save those settings to a shelf file and
then have the program load them the next time it is run
'''
import shelve
# save the data
shelfFile = shelve.open('mydata') # create a handler and create or open a file called mydata,
cats = ['Zophie', 'Pooka', 'Simon']
shelfFile['cats'] = cats # use the handler to stoore the data in the mydata file, much like in a dictionary using a key
shelfFile.close()
# get the data
shelfFile = shelve.open('mydata')
print(type(shelfFile)) # <class 'shelve.DbfilenameShelf'>
print( shelfFile['cats'] ) #use the key to get the data from the file ['Zophie', 'Pooka', 'Simon']
shelfFile.close()
'''
on Windows, you will see three new files
in the current working directory: mydata.bak, mydata.dat, and mydata.dir. On
OS X, only a single mydata.db file will be created.
'''
'''
Just like dictionaries, shelf values have keys() and values() methods that
will return list-like values of the keys and values in the shelf. Since these
methods return list-like values instead of true lists, you should pass them
to the list() function to get them in list form.
'''
shelfFile = shelve.open('mydata')
print( list(shelfFile.keys()) ) # ['cats']
print( list(shelfFile.values()) ) # [['Zophie', 'Pooka', 'Simon']]
shelfFile.close() |
'''
saving error messages to a file
using the traceback module
'''
import traceback
try:
raise Exception("A custom error message")
except:
errorFile = open('debugging\\error_log.txt', 'a') # open in append mode so we can keep all error records
errorFile.write( traceback.format_exc()) # write the traceback exception to the file
errorFile.write('\n')
errorFile.close()
'''
assert False, "Error message here"
if the condition following the keyword assert
evaluates to False, raise the error message
assert is for programmer errors not user errors
is for detecting potential bugs in our code
and they should crash our programs
letting us find our errors sooner rather than later
'''
Blvd_and_80th = {'ns':'green', 'we':'red'}
def switchLights(intesection):
for key in intesection.keys():
if intesection[key] == 'green':
intesection[key] = 'yellow'
elif intesection[key] == 'yellow':
intesection[key] = 'red'
elif intesection[key] == 'red':
intesection[key] = 'green'
print( Blvd_and_80th )
switchLights(Blvd_and_80th)
print( Blvd_and_80th )
'''
output:
{'ns': 'green', 'we': 'red'}
{'ns': 'yellow', 'we': 'green'}
the previous example logic is faulty as we can see
there are no red lights in either direction.
But there are no errors thrown, because there are no syntax errors
It's our mistake.
But we might have not noticed until we run the script
a couple times. Especially if we only called our function and
didnt use print() to check the before and after values
we can make sure we get a heads up early by writing
an assert statement
'''
# the same faulty logic is present here, we just crash and print a message letting us know
Blvd_and_80th = {'ns':'green', 'we':'red'}
def switchLights(intesection):
for key in intesection.keys():
if intesection[key] == 'green':
intesection[key] = 'yellow'
elif intesection[key] == 'yellow':
intesection[key] = 'red'
elif intesection[key] == 'red':
intesection[key] = 'green'
assert 'red' in intesection.values(), "NEITHER LIGHT IS RED IN THE INTERSECTION!"+str(intesection) # if 'red' is not in either value of the intesection
switchLights(Blvd_and_80th)
|
'''
Author: Josh Vocal
Description: Convert a decimal number to binary and sum the bianry number.
'''
#Main
#Converts the input number into a binary number and slices it
#Joins "+" into the binary number. Ex "1+0+1+1"
#Uses the evaluation function to add the numbers in the string.
print(eval("+".join(bin(input("Please enter a number: "))[2:])))
|
'''
Author: Josh Vocal
Descripton: Program will talke 3 arguments. The first will be a day, followed by month, then year.
The program will compute the day of the week that dat will fall on.
Version: 1.0
Changes:
'''
#Imports
import calendar
#Functions
def day():
print("Pick a day from 1-31 depending on the month: ")
return input("What is the day? ")
def month():
print("Janurary = 1\nFeburary = 2\nMarch = 3\nApril = 4\nMay = 5\nJune = 6\nJuly = 7\nAugust = 8\nSeptember = 9\nOctober = 10\nNovember = 11\nDecember = 12")
return input("What is the month? ")
def year():
print("Please select a year after 1970")
return input("What is the year? ")
#Main
#calendary.weekday returns a int depending on what day of the week from 1 -7
weekday = calendar.weekday(year(), month(), day())
if (weekday == 0 ):
print ("Monday")
if (weekday == 1 ):
print ("Tuesday")
if (weekday == 2 ):
print ("Wednesday")
if (weekday == 3 ):
print ("Thursday")
if (weekday == 4 ):
print ("Friday")
if (weekday == 5 ):
print ("Saturday")
if (weekday == 6 ):
print ("Sunday")
|
num1= int(input("enter first num"))
num2= int(input("enter second num"))
rem = num1 % 2
if(rem==0):
print(num1,"even integer")
else:
print(num1,"odd integer")
|
from automata import *
from scanner import *
#keywords
keywords =['while', 'do']
#character
digit="0123456789"
digit= character(digit)
tab=chr(9)
tab= character(tab)
eol=chr(10)
eol= character(eol)
blanco=eol+chr(13)+tab
blanco= character(blanco)
#tokens
number=digit+" (("+digit+")*)"
decnumber=digit+" (("+digit+")*) " +". "+digit+" (("+digit+")*)"
white=blanco+" (("+blanco+")*)"
automata_keyword=[]
automata =[number,decnumber,white]
charss =[chr(9),chr(10),eol+chr(13)+tab]
scanner(keywords, automata , automata_keyword, charss)
def Expr():
while(True):
Stat ("")
get(".")
return result
def Stat ():
value = 0
value = input()
value = Factor(value)
return result
def Expression( result):
result1 = 0
result2 = 0
result1 = Term(result1)
while(follow() == '+' or follow() == '-'):
if(follow()=='+'):
result2=Term(result2)
result1+=result2
elif(follow()=='-'):
result2=Term(result2)
result1-=result2
result=result1
return result
def Term( result):
result1 = 0
result2 = 0
result1 = Factor(result1)
while(follow() == '*' or follow() == '/'):
if(follow()=='*'):
result2=Factor(result2)
result1*=result2
elif(follow()=='/'):
result2=Factor(result2)
result1/=result2
result=result1
return result
def Factor( result):
signo=1
if follow() =="-":
signo = -1
## "("Expression( result)")")
result*=signo
return result
def Number( result):
result = int(value)
return result
|
from utils import timeIt
'''
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=((n*(3*n-1))/2) 1, 5, 12, 22, 35, ...
Hexagonal Hn=(n*(2*n-1)) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
'''
@timeIt
def problem45():
triangles = set()
pentagonals = set()
hexagonals = set()
for n in xrange(1,100001):
triangles.add((n*(n+1))/2)
pentagonals.add(((n*(3*n-1))/2))
hexagonals.add((n*(2*n-1)))
print max(triangles.intersection(pentagonals).intersection(hexagonals))
problem45()
|
from utils import timeIt
'''
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
@timeIt
def problem9():
for a in range(1,1001):
for b in range(1,1001):
c=(a**2+b**2)**.5
if a + b + c == 1000:
print a*b*c
return
problem9()
|
import networkx as nx
from itertools import combinations
class ACL(object):
"""Represent a single ACL"""
def __init__ (self, grant, portmin, portmax = None):
if not portmax:
portmax = portmin
self.grant = grant
self.portmin = portmin
self.portmax = portmax
def allowsPort (self, port):
""" Does this ACL allow a particular port through"""
return ((self.portmin <= port) and (port <= self.portmax))
def allowsConnection (self, group, port):
return (((self.grant == SecurityGroup.world) or (self.grant == group)) and self.allowsPort(port))
def __repr__ (self):
return "%s %d -- %d"%(self.grant, self.portmin, self.portmax)
class SecurityGroup(object):
"""Represents a security group"""
world = "any" # A security globe for the world
def __init__ (self, name, inbound, outbound):
self.name = name
self.inbound = map(lambda i: ACL(*i), inbound)
self.outbound = map(lambda i: ACL(*i), outbound)
def allowsInboundConnection (self, group, port):
"""Does this security group allow inbound connection from group and port"""
return any(map(lambda acl: acl.allowsConnection(group, port), self.inbound))
def allowsOutboundConnection (self, group, port):
"""Does this security group allow outbound connection to group and port"""
return any(map(lambda acl: acl.allowsConnection(group, port), self.outbound))
def allowsInboundPort (self, port):
"""Does this security group allow inbound connection on port"""
return any(map(lambda acl: acl.allowsPort(port), self.inbound))
def allowsOutboundConnection (self, group, port):
"""Does this security group allow outbound connection to group and port"""
return any(map(lambda acl: acl.allowsConnection(group, port), self.outbound))
def allowsOutboundPort (self, port):
"""Does this security group allow outbound connection on port"""
return any(map(lambda acl: acl.allowsPort(port), self.outbound))
def __repr__ (self):
return "%s <<Inbound>> [%s] <<Outbound>> [%s]"%(self.name, ' '.join(map(str, self.inbound)), \
' '.join(map(str, self.outbound)))
class Instance(object):
"""An instance"""
def __init__ (self, name, group):
self.name = name
self.group = group
def __repr__ (self):
return "%s -> %s"%(self.name, self.group)
class Configuration(object):
"""An entire configuration"""
def __init__ (self, securitygroups, instances):
self.secgroups = map(lambda i: SecurityGroup(*i), securitygroups)
#self.secgroups.append(\
#SecurityGroup(SecurityGroup.world, \
#[(SecurityGroup.world, 1, 65535)],\
#[(SecurityGroup.world, 1, 65535)]))
self.instances = map(lambda i: Instance(*i), instances)
self.secgroup_map = {sg.name: sg for sg in self.secgroups}
self.instance_map = {vm.name: vm.group for vm in self.instances}
self.instance_per_sg = {}
for instance in self.instances:
self.instance_per_sg[instance.group] = self.instance_per_sg.get(instance.group, 0) + 1
self.instance_per_sg[SecurityGroup.world] = float("inf") # Overkill
def __repr__ (self):
return "Security groups: \n\t%s\n Instances: \n\t%s\n Security Group weights: \n\t%s"%\
('\n\t'.join(map(str, self.secgroups)), \
'\n\t'.join(map(str, self.instances)),\
'\n\t'.join(map(lambda (a, b): '%s %s'%(a, str(b)), self.instance_per_sg.items())))
def acls_allow_connection (self, sg, port, acls):
return any(map(lambda a: a.allowsConnection(sg, port), acls))
def connection_allowed_secgroups (self, srcSG, destSG, port):
"""Can two security groups talk to each other over a specific port"""
outbound_allowed = self.secgroup_map[srcSG].allowsOutboundConnection(destSG, port)
inbound_allowed = self.secgroup_map[destSG].allowsInboundConnection(srcSG, port)
return (outbound_allowed and inbound_allowed)
def groups_with_inbound_access (self, target, port):
"""Find all groups that can connect to target at port"""
# Get a list of all security groups from which target would accept connection at port.
if target is SecurityGroup.world:
inboundPossible = map(lambda a: ACL(a, 1, 65535), self.secgroup_map.keys())
else:
inboundPossible = filter(lambda a: a.allowsPort(port), self.secgroup_map[target].inbound)
# Get the subset of the above that allow outbound connections to the target group at port.
groups = filter(lambda a: self.secgroup_map[a.grant].allowsOutboundConnection(target, port), inboundPossible)
return map(lambda acl: acl.grant, groups)
def groups_with_outbound_access (self, src, port):
"""Find all groups that src can connect to at port"""
# Get a list of all ports to which source can connect
if src is SecurityGroup.world:
outboundPossible = map(lambda a: ACL(a, 1, 65535), self.secgroup_map.keys())
else:
outboundPossible = filter(lambda a: a.allowsPort(port), self.secgroup_map[src].outbound)
# Find those that allow connection
groups = filter(lambda a: self.secgroup_map[a.grant].allowsInboundConnection(src, port), outboundPossible)
return map(lambda acl: acl.grant, groups)
def direct_connection_allowed (self, src, dest, port):
"""Check if this configuration allows direct connection on a particular port between a source and destination. A
machine name that is not a valid instance is treated as being outside the datacenter"""
srcSG = self.instance_map.get(src, SecurityGroup.world)
destSG = self.instance_map.get(dest, SecurityGroup.world)
return self.connection_allowed_secgroups(srcSG, destSG, port)
def indirect_connection_allowed (self, src, dest, port):
"""Check if this configuration allows indirect connection (i.e. can we chain together machines, using the same
protocol) on a particular port between a source and destination. A machine name that is not a valid instance is
treated as being outside the datacenter"""
srcSG = self.instance_map.get(src, SecurityGroup.world)
destSG = self.instance_map.get(dest, SecurityGroup.world)
to_explore = [destSG]
explored = set()
while to_explore:
destSG = to_explore.pop()
if destSG in explored:
continue
elif self.connection_allowed_secgroups(srcSG, destSG, port):
return True
else:
explored.add(destSG)
others = self.groups_with_inbound_access(destSG, port)
others = filter(lambda a: a not in explored and (self.instance_per_sg.get(a, 0) > 0), others)
to_explore.extend(others)
return False
def direct_connection_fix_sg (self, srcSG, destSG, port):
outbound_allowed = self.acls_allow_connection(destSG, port, self.secgroup_map[srcSG].outbound)
inbound_allowed = self.acls_allow_connection(srcSG, port, self.secgroup_map[destSG].inbound)
fix = []
if not outbound_allowed:
fix.append((srcSG, "outbound", ACL(destSG, port)))
if not inbound_allowed:
fix.append((destSG, "inbound", ACL(srcSG, port)))
# Only one fix in this case, no choosing of what is better
return fix
def direct_connection_fix (self, src, dest, port):
"""Fix cases where VMs are not directly connected"""
if self.direct_connection_allowed(src, dest, port):
return [] # Don't need to fix anything.
else:
# Find each of them
srcSG = self.instance_map.get(src, SecurityGroup.world)
destSG = self.instance_map.get(dest, SecurityGroup.world)
return [self.direct_connection_fix_sg(srcSG, destSG, port)]
def fix_metric (self, fix):
"""Metric for goodness of fix. We are basically asking how many new machines can now directly connect to some SG
because of this fix"""
# No new connectivity
if not fix:
return 0
# A fix only connects two groups, so is fine
fix = fix[0]
sg1 = fix[0]
sg2 = fix[2].grant
return max(self.instance_per_sg[sg1], self.instance_per_sg[sg2])
def indirect_connection_fix_graph (self, src, dest, port):
"""Yaron's algorithm for incremental indirect connection fixing"""
graph = nx.DiGraph()
graph.add_nodes_from(self.secgroup_map.keys())
for (sa, sb) in combinations(self.secgroup_map.keys(), 2):
if self.instance_per_sg.get(sa, 0) == 0:
continue
if self.instance_per_sg.get(sb, 0) == 0:
continue
weight = max(self.instance_per_sg[sa], self.instance_per_sg[sb])
if self.connection_allowed_secgroups(sa, sb, port):
graph.add_edge(sa, sb, weight=0)
else:
graph.add_edge(sa, sb, weight = weight)
if self.connection_allowed_secgroups(sb, sa, port):
graph.add_edge(sb, sa, weight=0)
else:
graph.add_edge(sb, sa, weight = weight)
srcSG = self.instance_map.get(src, SecurityGroup.world)
destSG = self.instance_map.get(dest, SecurityGroup.world)
paths = nx.all_shortest_paths(graph, srcSG, destSG, weight = "weight")
edges = map(lambda l: zip(l, l[1:]), paths)
weights = map(lambda l: map(lambda e: (e, graph.get_edge_data(*e)['weight']), l), edges)
non_zero_edges = map(lambda l: filter(lambda (e, w): w > 0, l), weights)
just_edges = map(lambda l: map(lambda (e, w): e, l), non_zero_edges)
fixes = map(lambda l: map(lambda (e1, e2): self.direct_connection_fix_sg(e1, e2, port), l), just_edges)
return non_zero_edges
def indirect_connection_fix (self, src, dest, port):
"""Check if this configuration allows indirect connection (i.e. can we chain together machines, using the same
protocol) on a particular port between a source and destination. A machine name that is not a valid instance is
treated as being outside the datacenter"""
srcSG = self.instance_map.get(src, SecurityGroup.world)
destSG = self.instance_map.get(dest, SecurityGroup.world)
origDestSG = destSG
to_explore = [destSG]
explored = set()
fixes = []
# Explore by changing the destination further away, the ideas is to take the transitive closure of all groups
# reachable from the destination and connect source to this.
while to_explore:
destSG = to_explore.pop()
if destSG in explored:
continue
elif self.connection_allowed_secgroups(srcSG, destSG, port):
return []
else:
explored.add(destSG)
others = self.groups_with_inbound_access(destSG, port)
others = filter(lambda a: a not in explored and (self.instance_per_sg.get(a, 0) > 0), others)
outbound_allowed = self.acls_allow_connection(destSG, port, self.secgroup_map[srcSG].outbound)
inbound_allowed = self.acls_allow_connection(srcSG, port, self.secgroup_map[destSG].inbound)
fix = []
if not outbound_allowed:
fix.append((srcSG, "outbound", ACL(destSG, port)))
if not inbound_allowed:
fix.append((destSG, "inbound", ACL(srcSG, port)))
fixes.append(fix)
to_explore.extend(others)
destSG = origDestSG
explored.clear()
to_explore = self.groups_with_outbound_access(srcSG, port)
explored.add(srcSG)
## Transitive closure from the source. Essentially find everything reachable from the source
while to_explore:
srcSG = to_explore.pop()
if srcSG in explored:
continue
elif self.connection_allowed_secgroups(srcSG, destSG, port):
return []
else:
explored.add(destSG)
others = self.groups_with_outbound_access(srcSG, port)
others = filter(lambda a: a not in explored and (self.instance_per_sg.get(a, 0) > 0), others)
outbound_allowed = self.acls_allow_connection(destSG, port, self.secgroup_map[srcSG].outbound)
inbound_allowed = self.acls_allow_connection(srcSG, port, self.secgroup_map[destSG].inbound)
fix = []
if not outbound_allowed:
fix.append((srcSG, "outbound", ACL(destSG, port)))
if not inbound_allowed:
fix.append((destSG, "inbound", ACL(srcSG, port)))
fixes.append(fix)
to_explore.extend(others)
min_fix_length = min(map(self.fix_metric, fixes))
filtered_fixes = filter(lambda c: len(c) == min_fix_length, fixes)
return (fixes, filtered_fixes)
test_config1 = \
Configuration(\
[("frontend",
[("frontend", 1, 65535),
("any", 22)],
[("frontend", 1, 65535),
("backend", 1, 65535)]),
("backend",
[("backend", 1, 65535)],
[("backend", 1, 65535),
("any", 22)])],
[("a", "frontend"), ("b", "backend"), ("c", "backend")])
test_config2 = \
Configuration(\
[("frontend",
[("frontend", 1, 65535),
("any", 22)],
[("frontend", 1, 65535),
("backend", 1, 65535)]),
("backend",
[("backend", 1, 65535),
("frontend", 1, 65535)],
[("backend", 1, 65535),
("any", 22)])],
[("a", "frontend"), ("b", "backend"), ("c", "backend")])
test_config3 = \
Configuration(\
[("sg1",
[("sg1", 1, 65535),
("sg2", 1, 65535)],
[("sg1", 1, 65535)]),
("sg2",
[("sg2", 1, 65535),
("sg3", 1, 65535)],
[("sg1", 1, 65535),
("sg2", 1, 65535)]),
("sg3",
[("any", 22),
("any", 80),
("sg3", 1, 65535)],
[("sg2", 1, 65535),
("sg3", 1, 65535)])],
[("a", "sg1"), ("b", "sg2"), ("c", "sg3")])
test_config4 = \
Configuration(\
[("sg1",
[("sg1", 1, 65535),
("sg2", 1, 65535)],
[("sg1", 1, 65535)]),
("sg2",
[("sg2", 1, 65535),
("sg3", 1, 65535)],
[("sg1", 1, 65535),
("sg2", 1, 65535)]),
("sg3",
[("any", 22),
("any", 80),
("sg3", 1, 65535)],
[("sg2", 1, 65535),
("sg3", 1, 65535)])],
[("a", "sg1"), ("c", "sg3")])
test_config5 = \
Configuration(\
[("sg1",
[("sg1", 1, 65535),
("sg2", 1, 65535)],
[("sg1", 1, 65535)]),
("sg2",
[("sg2", 1, 65535),
("sg3", 1, 65535)],
[("sg1", 1, 65535),
("sg2", 1, 65535)]),
("sg3",
[],
[("sg2", 22)]),
("sg4",
[("any", 22),
("any", 80),
("sg3", 1, 65535)],
[("sg2", 1, 65535),
("sg3", 1, 65535)])],
[("a", "sg1"), ("b", "sg2"), ("c", "sg3"), ("d", "sg4")])
test_config6 = \
Configuration(\
[("sg1",
[("sg1", 1, 65535),
("sg2", 1, 65535)],
[("sg1", 1, 65535),
("sg2", 1, 65535)]),
("sg2",
[("sg1", 1, 65535),
("sg2", 1, 65535),
("sg3", 1, 65535)],
[("sg1", 1, 65535),
("sg2", 1, 65535)]),
("sg3",
[("sg4", 22)],
[("sg4", 22)]),
("sg4",
[("sg5", 22),
("sg5", 80),
("sg3", 1, 65535)],
[("sg3", 1, 65535)]),
("sg5",
[],
[("sg4", 1, 65535)])],
[("a", "sg1"), ("b", "sg2"), ("c", "sg3"), ("d", "sg4")])
test_config7 = \
Configuration(
[("a",
[],
[("b", 1, 65535)]),
("b",
[("a", 1, 65535)],
[]),
("c",
[],
[("d", 1, 65535)]),
("d",
[("c", 1, 65535)],
[]),
("e",
[],
[("f", 1, 65535)]),
("f",
[("e", 1, 65535)],
[])],
[("m1", "a"), ("m2", "b"), ("m3", "c"), ("m4", "d"), ("m5", "e")])
if __name__ == "__main__":
configs = [test_config1, test_config2, test_config3, test_config4, test_config5, test_config6]
for config in configs:
print config
instances = map(lambda i: i.name, config.instances)
instances.append("z")
for (ia, ib) in combinations(instances, 2):
print "Testing %s %s"%(ia, ib)
if not config.indirect_connection_allowed(ia, ib, 22):
print "Fix for %s %s is %s"%(ia, ib, "\n\t".join(map(str, config.indirect_connection_fix_graph(ia, ib, 22))))
else:
print "%s %s allowed"%(ia, ib)
|
## El método de ordenamiento que se utiliza es el Bubblesort,
## debido a que se comparan los dos primeros elementos y si no estan
## en el orden que les corresponde los intercambia. Se repite el proceso
## con los dos siguientes numeros hasta llegar al final.
def bubbleSortMenor(arr):
for i in range(0, len(arr)-1):
for j in range(0,len(arr)-(i+1)):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print(arr)
return arr
lista = [47,3,21,32,56,92]
print(bubbleSortMenor(lista)) |
import time
start = time.time()
def negativos(lista):
negativo = []
for i in lista:
if i < 0:
negativo.append(i)
return negativo
lista = [0,3,6,-1,6,-3,9,-15,-10]
print(negativos(lista))
end = time.time()
print( end - start )
## El tiempo de ejecución de algortimo es de 0.00046706199645996094 s
## En todos los casos el algortimo va a tener que recorrer todas las posiciones del arreglo, por lo que no
## existiría peor caso; todos serían iguales. |
import random
from code.hand import Hand
from code.tile import Tile
class MahjongTable(object):
"""Coordinates games of mahjong."""
def __init__(self, mahjong_player, unique_tiles):
self.hand_len = 14
self.mahjong_player = mahjong_player
self.tileset = self.generate_tileset(unique_tiles)
def generate_pond(self, max_len):
"""
Iterate through a game, asking mahjong_player to make new
discards until max_len is reached or the hand is finished.
Return the pond and winning tile.
"""
discard_pile = []
wall = self.generate_wall()
hand = Hand(wall[0:self.hand_len])
wall = wall[(self.hand_len+1):len(wall)]
while len(discard_pile) < max_len:
if hand.is_complete():
return discard_pile, hand[len(hand) - 1]
else:
discard = self.mahjong_player.make_discard(hand)
hand = Hand(hand.remove_tiles([discard]))
discard_pile.append(discard)
hand.append(wall.pop(0))
return discard_pile, None
def generate_wall(self):
"""Generate a fresh wall from self.tileset."""
return random.sample(self.tileset, len(self.tileset))
@staticmethod
def generate_tileset(unique_tile_str):
"""
Turn a list of tile strings to a list of four Tile objects.
"""
unique_tiles = [Tile(x) for x in unique_tile_str]
return unique_tiles + unique_tiles + unique_tiles + unique_tiles
|
data = ""
with open("sample1.txt", "rb") as file:
data = file.read()
with open("sample2.txt") as file1:
with open("sample1.txt") as file2:
file2.write(file1.read())
with open("sample2.txt") as file:
file.write(data)
print("File Replaced")
del data |
#Leer tres números enteros diferentes entre sí y determinar el número mayor de los tres.
"""Ejercicio 8"""
class Mayor_3:
def __init__(self):
pass
def NumMayor(self):
print("")
n1 = int(input("Ingrese primer número entero: "))
n2 = int(input("Ingrese segudo número entero: "))
n3 = int(input("Ingrese tercer número entero: "))
print()
if n1 > n2 and n1 > n3:
nM = n1
else:
if n2 > n3:
nM = n2
else:
nM = n3
print("El número mayor es:", nM)
print()
mayor = Mayor_3()
mayor.NumMayor()
|
from db import db
class StoreModel(db.Model):
__tablename__ = 'store'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
# ? When we use lazy = 'dynamic' it optimises the code otherwise pyhton create an object with the list of items for every store created. By doing so : self.items becomes a query builder that can look into ItemModel
items = db.relationship('ItemModel', lazy='dynamic')
def __init__(self, name):
self.name = name
def json(self):
# ? Since self.items became a query builder we have to use the method .all to acces all the items
return {"name": self.name, "items": [item.json() for item in self.items.all()]}
@classmethod
def find_by_name(cls, name):
return cls.query.filter_by(name=name).first()
# * This method work for update and insert
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
|
target = int(input('Enter an integer: '))
answer = 0
while answer**2 < target:
answer += 1
if answer**2 == target:
print(f'Root square of {target} is {answer}')
else:
print(f'{target} does not have root square')
|
'''
Created on Aug 23, 2020
Calculate Largest Palindrome of the product of two three digit numbers
@author: Pranaw Bajracharya
'''
"""
Since the question is find the largest palindrome of the product of two three digit numbers,
I suppose the simplest/most brute force method would be to find the minimum and maximum value of
the product of two three digit numbers. The smallest three digit number is 100 and the greatest
is 999. Thus, the palindrome will be between 100*100 and 999*999.
I'm guessing it would be a lot closer to the 999*999 so we will start from there and move down,
checking to see if the numbers in between are palindromes.
"""
import sys
maximum = 999
minimum = 100
for x in range(maximum,minimum,-1):
for y in range(maximum,minimum,-1):
multiplied = x * y
number = str(multiplied)
length = len(number)
first, second = number[:length//2], number[length//2:]
if(first[::-1] == second):
print(number)
|
import re
print(re.search(r"[pP]ython","Python"))
print(re.search(r"[a-z]way","the end of the highway"))
print(re.search(r"[a-z]way","What a way to go"))
print(re.search(r".way","What a way to go"))
# match any character that aren;t in a group we use "^" this
# Any character that is not a letter
print(re.search(r"[^a-zA-Z0-9]","What a way to go"))
# If we want to match either one expression or another, we can use the pipe symbol to do that.
print("\nPipe\n")
print(re.search(r"cat|dog","I like cat"))
# If we want to get all possible matches, we can do that using the findall function, which is also provided by the re module
print("\nFindall\n")
print(re.findall(r"cat|dog","I like cats and dogs"))
print(re.findall(r"cat|dog","I like cats and dogs and dogs")) |
a=[]
a.append(5)
print(a)
a.append("Hello")
print(a)
print(len(a))
for x in a:
print(x)
a.remove(5)
print(a)
x=a.pop(0)
print(x)
print(a)
print(int(3.79)+int(2.1)) |
with open("demo.txt") as file:
for line in file:
print(line.upper())
with open("demo.txt") as file:
for line in file:
print(line.strip().upper()) |
file = open("demo.txt")
print(file.readline())
print(file.readline())
print(file.read())
file.close()
#--------------------------------------
file = open("demo.txt")
print(file.readline())
print(file.readline())
file.close()
file = open("demo.txt")
print(file.read())
file.close()
with open("demo.txt") as file:
print(file.read()) |
import csv
f = open("demo.txt") #open file
csv_f = csv.reader(f)
for row in csv_f:
name,product,country=row
print("Name: {}, Product: {}, Country: {}".format(name,product,country))
f.close() |
class Soldier:
def __init__(self):
self._weapons = list()
def add_weapon(self, weapon):
self._weapons.append(weapon)
def fight(self):
print(f"Fighting with {', '.join([str(weapon) for weapon in self._weapons])}")
class Sword:
def __init__(self, color):
self._color = color
def __str__(self):
return f"cool {self._color} sword"
class Shield:
def __init__(self, color):
self._color = color
def __str__(self):
return f"important {self._color} shield"
class Arch:
def __init__(self, color):
self._color = color
def __str__(self):
return f"long range {self._color} arch"
class SoldierBuilder:
def __init__(self, color):
self._color = color
def create(self, weapons):
soldier = Soldier()
for weapon in weapons:
if weapon == "sword":
sword = Sword(self._color)
soldier.add_weapon(sword)
elif weapon == "shield":
shield = Shield(self._color)
soldier.add_weapon(shield)
elif weapon == "arch":
arch = Arch(self._color)
soldier.add_weapon(arch)
return soldier
if __name__ == '__main__':
color1 = input("Enter first soldier's color: ")
color2 = input("Enter second soldier's color: ")
first_color_builder = SoldierBuilder(color1)
second_color_builder = SoldierBuilder(color2)
soldier1 = first_color_builder.create(["sword", "shield"])
soldier2 = second_color_builder.create(["sword", "shield"])
soldier3 = second_color_builder.create(["arch", "shield"])
soldier1.fight()
soldier2.fight()
soldier3.fight() |
from oop.basic_dog_class import Dog
class Pomeranian(Dog):
def __init__(self, name):
super().__init__(name)
print("Pomeranian was created.", end="\n\n")
def bark(self):
#super().bark()
print("I'm costly.")
if __name__ == '__main__':
my_dog = Pomeranian("Bolt")
my_dog.bark()
print(my_dog.legs)
print(my_dog.favorite_color(), end="\n\n")
print(isinstance(my_dog, Pomeranian))
print(isinstance(my_dog, Dog)) |
# Author: Chirag Maniar
# copyright @2019 by Chirag Maniar
# Execl sheet discount calculation and chart building
# Importing excel required packages
import openpyxl as excel
def process_excel_sheet(filename):
# Selecting workbook i.e. Excel sheet
workbook = excel.load_workbook(filename)
# Selecting the sheet, operations are required to perform upon
sheet = workbook["Sheet1"]
# Calculating and adding discounted price in new created column for selected
# row
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
discounted_price = cell.value * 0.9 # Discount of total 10%
discounted_price_cell = sheet.cell(row, 4) # Selecting the column and row
discounted_price_cell.value = f"${discounted_price}" # Put value after discount
# Crate a new sheet with added discount
workbook.save("Discount_Added_File.xlsx")
print("File processed successfully!")
# Give excel file needs to be processed
process_excel_sheet("transactions.xlsx")
|
numbers = range(1, 101)
numbers = list(numbers)
even = [x for x in numbers if x % 2 == 0]
print sum(even) |
def get_guess():
acceptable_input = False
while not acceptable_input:
try:
raw_guess_numbers = [int(x) for x in input("Enter your guess: ")]
if len(raw_guess_numbers) != 4:
print "Your guess must be 4 numbers long!"
continue
if out_of_range(raw_guess_numbers):
print "All numbers must be between 1 and 7!"
continue
if len(raw_guess_numbers) != len(set(raw_guess_numbers)):
print "No duplicate numbers allowed!"
continue
acceptable_input = True
except ValueError:
print "You must only use numbers!"
def out_of_range(numbers_list):
for number in numbers_list:
if not (1 <= number and number <= 7):
return True
return False
print get_guess()
|
import random
# These lists will be used as tests in your check_values function
computer_list = [1,2,3,5];
user_list = [2,7,3,4];
def check_values(user, computer):
colors = []
shuffled = user[:]
random.shuffle(shuffled)
for number in shuffled:
if number in computer:
input_number_pos = user.index(number)
computer_number_pos = computer.index(number)
if input_number_pos == computer_number_pos:
colors.append("RED")
else:
colors.append("WHITE")
else:
colors.append("BLACK")
return colors
print check_values(user_list, computer_list)
|
from types import StringType
from collections import Iterable
class MaxHeap(object):
def __init__(self):
self.array = []
self.cur_size = 0
def heapify(self, item_list):
self.array = item_list
self.cur_size = len(item_list)
for i in range(self.cur_size-1, -1, -1):
self._heapify(i)
def push(self, item):
"""
push an item into the heap, re-arange the heap according to the key
"""
self.array.append(item)
self.cur_size += 1
cur = self.cur_size - 1
while (cur != 0):
p = cur >> 1
if self.get_key(self.array[cur]) > self.get_key(self.array[p]):
self.swap(cur, p)
else:
return
cur = p
def pop(self):
"""
pop the item with largest key value
"""
if self.cur_size == 0:
raise ValueError("No elements in the heap")
ret = self.array[0]
self.array[0] = self.array[self.cur_size-1]
self.array.pop()
self.cur_size -= 1
self._heapify(0)
return ret
def top(self):
"""
peek the top of the heap
"""
if self.cur_size == 0:
raise ValueError("No elements in the heap")
return self.array[0]
def size(self):
"""
return the size of the heap
"""
return self.cur_size
def get_key(self, item):
if isinstance(item, Iterable) and not isinstance(item, StringType):
return item[0]
else:
return item
def swap(self, i, j):
tmp = self.array[i]
self.array[i] = self.array[j]
self.array[j] = tmp
def _heapify(self, node):
if node >= self.cur_size:
return
l = (node << 1) + 1
r = (node << 1) + 2
if l >= self.cur_size and r >= self.cur_size:
return
elif r >= self.cur_size:
# only left child
if self.get_key(self.array[l]) > self.get_key(self.array[node]):
self.swap(l, node)
else:
# both child alive
if self.get_key(self.array[node]) >= self.get_key(self.array[l]) and self.get_key(self.array[node]) >= self.get_key(self.array[r]):
return
if self.get_key(self.array[l]) >= self.get_key(self.array[r]):
self.swap(l, node)
self._heapify(l)
else:
self.swap(r, node)
self._heapify(r)
if __name__=="__main__":
hp = MaxHeap()
items = [4,3,6,5,1,8,10,4,5,2,1,7]
hp.heapify(items)
hp.push(20)
for i in range(hp.size()):
print(hp.pop())
|
def InsertionSort(arr,n):
for i in range(1,n):
temp = arr[i]
j = i - 1
while j>=0 and arr[j] > temp:
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = temp
arr = [1,5,3,7,2,6,0]
n = 7
InsertionSort(arr,n)
print(arr) |
a = {"apple","abc",23}
a.remove('apple')
a.discard(23)
print(a)
## a.pop() - remove on , we dont know
# functions of sets
a = {1,2,3,4}
b = {3,4,5,6}
print(a.intersection(b))
print(a.union(b))
print(a.difference(b))
print(a.symmetric_difference(b)) # union minus intersection
print(a.intersection_update(b))
a.difference_update(b)
a.symmetric_difference_update(b)
print(a)
a.issubset(b)
a.isdisjoint(b)
a.issuperset(b)
|
def powerNumber(x,n):
if n == 0:
return 1
smallAns = powerNumber(x,n-1)
return x * smallAns
x,n = input().split(' ')
output = powerNumber(int(x),int(n))
print(output) |
n=5
if n%2==0:
for i in range((n//2)):
for j in range(n):
print(2*n*i+j+1,end=" ")
print()
for i in range((n//2),0,-1):
for j in range(n):
print(2*n*i+j+1-n,end=" ")
print()
else:
for i in range((n//2)+1):
for j in range(n):
print(2*n*i+j+1,end=" ")
print()
for i in range((n//2),0,-1):
for j in range(n):
print(2*n*i+j+1-n,end=" ")
print() |
def merge(arr1, arr2 , arr) :
#Your code goes here
index1 = 0
index2 = 0
index3 = 0
n = len(arr1)
m = len(arr2)
while index1 < n and index2 < m:
if(arr1[index1] >= arr2[index2]):
arr[index3] = arr2[index2]
index2 += 1
index3 += 1
else:
arr[index3] = arr1[index1]
index1 += 1
index3 += 1
if(index1 < n):
while index1 < n:
arr[index3] = arr1[index1]
index1 += 1
index3 += 1
if(index2 < m):
while index2 < m:
arr[index3] = arr2[index2]
index2 += 1
index3 += 1
def mergeSort(arr, start, end):
# Please add your code here
if len(arr) == 0 or len(arr) == 1:
return
mid = len(arr)//2
s1 = arr[0:mid]
s2 = arr[mid:]
mergeSort(s1,start,end)
mergeSort(s2,start,end)
merge(s1,s2,arr)
# Main
n=int(input())
arr=list(int(i) for i in input().strip().split(' '))
mergeSort(arr, 0, n)
print(*arr)
|
import random
#------Checking if number is even
number = int(input("Enter a number: "))
if (number % 2) == 0:
print("Even")
else:
print("Odd")
#------Sum of digits
num = random.randint(100, 1000)
num_sum = 0
n = 0
print("Number is {}".format(num))
while num > 0:
n = num%10
num_sum += n
num //= 10
print("Sum is {}".format(num_sum))
#------Finding min and max values in random numbers without lists or arrays
rand_num = 0
minimum = 100
maximum = 0
for i in range(10):
rand_num = random.randint(1, 100)
if rand_num > maximum:
maximum = rand_num
if rand_num < minimum:
minimum = rand_num
print(rand_num)
print("Max is {}".format(maximum))
print("Min is {}".format(minimum))
#------All words in one string
strng = ""
for i in range(5):
word = input("Enter your word: ")
strng += word + ' '
print(strng)
|
from modules.检测录音频率 import 检测录音频率
from modules.播放随机波 import 播放随机波
from utils.波处理 import 读取wav文件 , 时域转频域 , 求主导频率
import matplotlib.pyplot as plt
from 练习 import 练习
from 听音识名 import 听音识名
from 看名唱音 import 看名唱音
from 跟唱 import 跟唱
from 自由练习_唱 import 自由练习_唱
from 自由练习_唱_连续 import 自由练习_唱_连续
import os , sys
while True:
os.system("cls")
x = input("""选择练习?
0)退出
1)查看日志
2)听音识名
3)看名唱音
4)跟唱
5)自由练习(唱)
6)自由练习(唱+连续)
>> """)
x = x.strip()
if x == "":
x = 1
else:
x = int(x)
if x == 0:
input("按回车退出")
break
elif x == 1:
练习记录 = 练习.获得练习记录()
print (练习记录)
input("按回车返回")
elif x == 2:
练 = 听音识名()
练.run()
elif x == 3:
练 = 看名唱音()
练.run()
elif x == 4:
练 = 跟唱()
练.run()
elif x == 5:
自由练习_唱()
elif x == 6:
自由练习_唱_连续() |
def sumOfEvenFibs(sumLimit):
"""
Assumes sumLimit is non-negative.
Returns the sum of even terms of in the Fibonacci series.
>>> sumOfEvenFibs(1000)
798
"""
fib = dict()
fib[0] = 0
fib[1] = 1
i = 2
while (fib[i-1] + fib[i-2]) <= sumLimit:
fib[i] = fib[i-1] + fib[i-2]
i = i + 1
evenFibSum = 0
for j in fib:
if fib[j] % 2 == 0:
evenFibSum += fib[j]
return evenFibSum
print(sumOfEvenFibs(4000000))
|
# Leetcode Problem #1130 - Minimum Cost Tree From Leaf Values
# https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/submissions/
class Solution:
def __init__(self):
self.mem = {}
def mctFromLeafValues(self, arr: List[int]) -> int:
if not arr:
return 0
return self.dp(arr, 0, len(arr) - 1)[1]
def dp(self, arr: List[int], s: int, e: int) -> tuple:
"""Find optimized result of arr[s:e+1], i.e. [s, e].
Returns:
max_of_subtree: The maxinum value in [s,e] range.
minimum_cost: Minimum cost tree sum.
"""
if s == e: # 1 node
return (arr[s], 0)
key = (s, e)
if key in self.mem:
return self.mem[key]
if e - s == 1: # 2 nodes
res = (max(arr[s], arr[e]), arr[s] * arr[e])
else:
costs = []
for k in range(s, e):
left_max, left_cost = self.dp(arr, s, k)
right_max, right_cost = self.dp(arr, k + 1, e)
costs.append(left_cost + right_cost + left_max * right_max)
res = (max(arr[s:e + 1]), min(costs))
self.mem[key] = res
# print(f'key: {key}, value: {res}')
return res
|
# Leetcode Problem #112 - Path Sum
# https://leetcode.com/problems/path-sum/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
return self.dfs([root], sum)
def dfs(self, path: List[TreeNode], target: int) -> bool:
cur = path[-1]
if not cur.left and not cur.right:
# is leaf
if target == cur.val:
return True
if cur.left:
if self.dfs(path + [cur.left], target - cur.val):
return True
if cur.right:
if self.dfs(path + [cur.right], target - cur.val):
return True
return False
|
#! /usr/bin/env python
import sys,math
def hypothenuse(side1, side2):
"""
The algorithm the man behind the door
uses is the same used to compute the
hypothenuse for a triangle with catheti
x and y :)
"""
hyp = math.sqrt(side1 * side1 + side2 * side2)
return round(hyp, 2)
line = sys.stdin.readline()
num_cases = int(line)
for i in range(num_cases):
line = sys.stdin.readline()
nums = [int(x) for x in line.split()]
result = hypothenuse(nums[0], nums[1])
if int(result) == result:
print(int(result))
else:
print("{0:.2f}".format(result))
|
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Function scrollbox")
# Initialize our country "databases":
# - the list of country codes (a subset anyway)
# - a parallel list of country names, in the same order as the country codes
# - a hash table mapping country code to population<
functionCodes = ('wf', 'wb', 'tr', 'tl', 'ki', 'li', 'sy')
functionNames = ('WalkForwards', 'WalkBackwards', 'TurnRight', 'TurnLeft', 'Kick', 'Lift', 'Say')
fnames = StringVar(value=functionNames)
descriptions = {'wf':'move the robot forwards', 'wb':'move the robot backwards', 'tr':'turn the robot right', 'tl':'turn the robot left','ki':'make the robot kick', 'li':'make the robot lift its arms', 'sy':'make the robot speak'}
# State variables
statusmsg = StringVar()
# Called when the selection in the listbox changes
def showDescriptions(*args):
idxs = lbox.curselection()
if len(idxs)==1:
idx = int(idxs[0])
code = functionCodes[idx]
name = functionNames[idx]
popn = descriptions[code]
statusmsg.set("The funciton %s will %s" % (name, popn))
# Create and grid the outer content frame
c = ttk.Frame(root, padding=(3, 3, 12, 12))
c.grid(column=0, row=0, sticky=(N,W,E,S))
c.grid_columnconfigure(0, weight=1)
c.grid_rowconfigure(0,weight=1)
# Create the different widgets
lbox = Listbox(c, listvariable=fnames, height=5)
scrollbar = ttk.Scrollbar(c, orient=VERTICAL, command=lbox.yview)
lbox.configure(yscrollcommand=scrollbar.set)
status = ttk.Label(c, textvariable=statusmsg, anchor=W)
# Grid all the widgets
lbox.grid(column=0, row=0, sticky=(N,S,E,W))
status.grid(column=0, row=2, columnspan=2, sticky=(W,E))
scrollbar.grid(column=2, row=0, sticky=(N,S))
# Set event bindings for when the selection in the listbox changes,
lbox.bind('<<ListboxSelect>>', showDescriptions)
# Colorize alternating lines of the listbox
for i in range(0,len(functionNames),2):
lbox.itemconfigure(i, background='#f0f0ff')
# Set the starting state of the interface
statusmsg.set('')
lbox.selection_set(0)
showDescriptions()
root.mainloop() |
# Activity 8.2.5: Task 5
#File: ACT_8_2_Task5_Team256.py
#Date: 18 Oct 2018
#By: Alex Tillman
# Justin Kohler
# Ryan Steffan
# David McCoy
#
#Section: 021
#Team 256
#
#Electronic Signature
# Alex Tillman
# Justin Kohler
# Ryan Steffan
# David McCoy
#This electronic signature above indiccates the script
#submitted for evaluation is my individual work, and i
#ahve a general understanding of all aspects of its
#development and execution
#
#A BRIEF DESCRIPTION OF WHAT THE SCRIPT OR FUNCTION DOES
#This program outputs the area of a circle given two inputs
def areaOfCircle(r):
import math
area = math.pi*r**2
print("Area of circle:",area)
def main():
x = int(input("enter radius:"))
areaOfCircle(x)
|
# HW 8.1 Python Individual
#File: HW8_1_Task1_functions_Tillmaaa.py
#Date: 28 Oct 2018
#By: Alex Tillman
# Justin Kohler
# Ryan Steffen
# David McCoy
#Section: 021
#Team 256
#
#Electronic Signature
# Alex Tillman
#
#
#
#This electronic signature above indiccates the script
#submitted for evaluation is my individual work, and i
#ahve a general understanding of all aspects of its
#development and execution
#
#A BRIEF DESCRIPTION OF WHAT THE SCRIPT OR FUNCTION DOES
#Calculates a persons age in years and age in minutes
gpa = float(input("Enter your gpa up to one decimal point: "))
if gpa < 0:
print("Error: Invalid GPA")
elif gpa < 1 and gpa >0 :
print("Faile semester- registration")
elif gpa < 2 and gpa >=1 :
print("On probation for next semester")
elif gpa < 3 and gpa >=2 :
print("Pass")
elif gpa < 3.5 and gpa >=3 :
print("Dean's list for semester")
elif gpa <= 4 and gpa >=3.5 :
print("Highest honors for semester")
elif gpa >4 :
print("Error: Invalid GPA")
else :
print("Error: Invalid GPA")
|
from dinosaur import Dinosaur
class Herd:
def __init__(self):
self.dinosaurs = []
def create_herd(self):
dinosaur_one = Dinosaur("Ken", 100)
dinosaur_two = Dinosaur("Dennis", 150)
dinosaur_three = Dinosaur("Oscar", 200)
self.dinosaurs.append(dinosaur_one)
self.dinosaurs.append(dinosaur_two)
self.dinosaurs.append(dinosaur_three)
def display_dinosaurs(self):
for dinosaur in self.dinosaurs:
print(dinosaur.dinosaur_name + ' ' + str(dinosaur.health) +
' ' + str(dinosaur.attack_power))
|
import random
def tirar_dados():
dado1 = random.randint(1,6)
dado2 = random.randint(1,6)
suma1 = dado1 + dado2
return dado1, dado2, suma1
def juego():
numberl = [4,5,6,8,9,10]
dados =tirar_dados()
d1 = dados[0]
d2 = dados[1]
s = dados[2]
gano = 0
if s == 7 or s == 11:
print('ganaste')
gano = 1
elif s in numberl:
not_seven = True
while not_seven:
segundo_tiro = tirar_dados()
d1n = segundo_tiro[0]
d2n = segundo_tiro[1]
sn = segundo_tiro[2]
if sn == 7:
print('perdiste, salio un 7 antes')
not_seven = False
elif sn == s:
print('ganaste')
gano = 1
not_seven = False
else:
s = sn
else:
print('perdiste, 2, 3 o 12')
return gano
def resultados(cantidad = 100):
money = 20
won = 0
lost = 0
meta = 0
quiebra = 0
for i in range(cantidad):
if money == 50:
print("Se acabo, dinero:", money)
print('iteracion :', i)
meta += 1
money = 20
elif money == 0:
print('Quiebra :', money)
quiebra += 1
money = 20
r =juego()
if r == 1:
won += 1
money += 1
else:
lost += 1
money -= 1
print('Dinero: ', money)
print('Meta :', meta)
print('Quiebra: ', quiebra)
return money, meta, quiebra
resultados()
|
from tkinter import *
from tkinter import messagebox as MessageBox
from tkinter import filedialog as FileDialog
from tkinter import colorchooser as ColorChooser
from io import open
fileroute=""
def aboutus():
MessageBox.showinfo('About Us', 'This is a GUI for test purposes, just have fun')
def help():
MessageBox.showinfo('Help', 'This is a GUI for test purposes, just have fun')
def exit():
answer=MessageBox.askyesno('Exit', 'Are you sure you want to exit')
if answer:
root.destroy()
def newf():
global fileroute
mssg.set('New File')
fileroute=""
textbox.delete(1.0, 'end')
def bg_color():
color=ColorChooser.askcolor(title='Choose new background color')
textbox.config(bg=color[1])
def font_color():
color=ColorChooser.askcolor(title='Choose new font color')
textbox.config(fg=color[1])
def openf():
global fileroute
mssg.set('Open File')
fileroute=FileDialog.askopenfilename(title='Open a file', initialdir='.',
filetypes=(("Text files","*.txt"),
) )
if fileroute != "":
file_r=open(fileroute, 'r')
text=file_r.read()
textbox.delete(1.0, 'end')
textbox.insert('insert', text)
file_r.close()
root.title(fileroute + " - My Text Editor")
def savef():
mssg.set('Save File')
if fileroute != "":
text=textbox.get(1.0, 'end-1c')
file_w=open(fileroute, 'w+')
file_w.write(text)
file_w.close()
mssg.set('Saved')
else:
savef_as()
def savef_as():
global fileroute
mssg.set('Save File As...')
f=FileDialog.asksaveasfile(title='Save as ...', mode='w', defaultextension=".txt") #en formato write
if f is not None:
fileroute=f.name
text=textbox.get(1.0, 'end-1c')
f=open(fileroute, 'w+')
f.write(text)
f.close()
mssg.set('Saved As'+ f.name)
else:
mssg.set('Saved Canceled')
fileroute=""
root=Tk()
root.title('My Text Editor')
root.iconbitmap('pencil.ico')
########Menu
menubar=Menu(root)
root.config(menu=menubar)
filemenu=Menu(menubar, tearoff=0)
filemenu.add_command(label='New File', command=newf)
filemenu.add_command(label='Open File', command=openf)
filemenu.add_command(label='Save', command=savef)
filemenu.add_command(label='Save As', command=savef_as)
filemenu.add_separator()
filemenu.add_command(label='Exit', command=exit)
editmenu=Menu(menubar, tearoff=0)
editmenu.add_command(label='Change bckgd color', command=bg_color)
editmenu.add_command(label='Change font color', command=font_color)
helpmenu=Menu(menubar, tearoff=0)
helpmenu.add_command(label='Welcome')
helpmenu.add_command(label='Help me', command=help)
helpmenu.add_separator()
helpmenu.add_command(label='About Us', command=aboutus)
menubar.add_cascade(label='File', menu=filemenu)
menubar.add_cascade(label='Edit', menu=editmenu)
menubar.add_cascade(label='Help', menu=helpmenu)
###########################################################
#Textbox
textbox=Text(root)
textbox.pack (fill= 'both', expand=1)
textbox.config(bd=0, padx=5, pady=3, font=('Courier New', 12), fg='white', bg='black')
mssg=StringVar()
mssg.set('Welcome!')
btmmessage=Label(root, textvar=mssg, justify='left')
btmmessage.pack(side='left')
root.mainloop()
|
# Ask how many items user wants to sell.
sold = int(input("How many items are you selling? "))
print("You are selling {} items".format(sold))
|
class Node():
def __init__(self,data):
self.data=data
self.next=None
class circularLinkedList():
def __init__(self):
self.last = None
def addToEmpty(self,data):
if (self.last!=None):
return
temp = Node(data)
self.last = temp
self.last.next = self.last
return self.last
def addBegin(self,data):
if (self.last==None):
return self.addToEmpty(data)
temp = Node(data)
temp.next = self.last.next
self.last.next = temp
return self.last
def addAfter(self,data,item):
if self.last==None:
return
temp = Node(data)
p = self.last.next
while p!=None:
if p.data == item:
temp.next = p.next
p.next = temp
if p==self.last:
self.last = temp
return self.last
else:
return self.last
p = p.next
if p==None:
print('Item not found in Linked List')
return
temp.next = Node(data)
def addLast(self,data):
if (self.last==None):
return self.addToEmpty(data)
temp = Node(data)
temp.next = self.last.next
self.last.next = temp
self.last = temp
def sortInsert(self,dt):
temp = self.last.next
prev = self.last
while (temp.next!=self.last.next and temp.data<=dt):
prev = temp
temp=temp.next
if temp==self.last:
if temp.data > dt:
self.addAfter(dt, prev.data)
else:
self.addLast(dt)
elif temp==self.last.next:
if temp.data > dt:
self.addBegin(dt)
else:
self.addAfter(dt, prev.data)
else:
self.addAfter(dt, prev.data)
def traverse(self):
if (self.last==None):
print ('List is empty')
return
temp = self.last.next
while(temp):
print(temp.data,end = " ")
temp=temp.next
if (temp==self.last.next):
break
if __name__=='__main__':
clist = circularLinkedList()
last = clist.addLast(3)
last = clist.addLast(7)
last = clist.addLast(9)
last = clist.addLast(11)
last = clist.sortInsert(5)
clist.traverse() |
# each item in the manifest is an item and its weight
manifest = [["bananas", 15], ["mattresses", 34], ["dog kennels",42], ["machine that goes ping!", 120], ["tea chests", 10], ["cheeses", 0]]
#Sorted cargo hold from heaviest to lightest
#manifest.sort(key=lambda weight: weight[1], reverse=True)
cargo_weight = 0
cargo_hold = []
# Loop through sorted manifest, stop early when cargo_hold is full.
for cargo in manifest:
# break out of loop early if we've already filled cargo hold to capacity.
#if cargo_weight > 100:
# break
if cargo_weight + cargo[1] <= 100:
cargo_hold.append(cargo[0])
cargo_weight += cargo[1]
print(cargo_weight)
print(cargo_hold)
|
def tag_count(xml_count):
"""
Function that takes as its argument a list of strings. It return a count of how many of those strings are XML tags.
"""
count = 0
for x in xml_count:
if x[0] == '<' and x[-1] == '>':
count = count + 1
return count
# Test for the tag_count function:
list1 = ['<greeting>', 'Hello World!', '</greeting>']
count = tag_count(list1)
print("Expected result: 2, Actual result: {}".format(count))
|
def html_list(input):
"""
This Function takes one argument, a list of strings, and returns a single string which is an HTML list.
"""
output = ["<ul>"]
for values in input:
#This works too but the one I used is cleaner.
#output.append("<li>" + values + "</li>")
output.append("<li>{}</li>".format(values))
output.append("</ul>")
return "\n".join(output)
test = ['first string', 'second string']
print(html_list(test))
|
"""
_*_ coding:utf-8 _*_
@Auther:JeffWb
@data:2018.11.22
@Version:3.6
"""
""">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Chain to stack<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"""
class StackUnderFlow(ValueError):
pass
class Node:
def __init__(self,elem,next):
self.elem = elem
self._next = next
class CStack:
def __init__(self,top = None):
self.top = top
def is_empty(self):
return self.top == None
#elem push
def push(self,elem):
self.top = Node(elem,self.top)
#stack out and return elem
def stack_out(self):
if self.top == None:
raise StackUnderFlow("stack is empty,stack out fail")
else:
e = self.top.elem
self.top = self.top._next
return e
#return top elem
def top(self):
if self.top == None:
raise StackUndeFlow("stack is empty,top fail")
return self.top.elem
#return deepth of stack
def deepth(self):
if self.top == None:
return 0
else:
i = 0
temp = self.top
while temp != None:
temp = temp.next
i += 1
return i
if __name__ == '__main__':
cs = CStack(Node(1))
cs.is_empty()
cs.push(2)
cs.push(3)
print(cs.top())
print(cs.stack_out())
print(cs.deepth())
|
"""
_*_ coding:utf-8 _*_
@Auther:JeffWb
@data:2018.11.22
@Version:3.6
"""
""">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Sequence to queue<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"""
class queueError(ValueError):
pass
class SQueue:
def __init__(self):
self.elem = []
#empty?
def is_empty(self):
return self.elem == []
#length of queue
def length(self):
return len(self.elem)
#enqueue
def enqueue(self,elem):
self.elem.append(elem)
#dequeue
def dequeue(self):
if self.elem == []:
raise queueError("queue is empty,dequeue fail")
else:
return self.elem.pop(0)
#queue first
def queue_first(self):
if self.elem == []:
raise queueError("queue is empty,queue first is None")
else:
return self.elem[0]
#clear queue
def clear(self):
self.elem = []
if __name__ == '__main__':
sq = SQueue()
sq.enqueue(1)
sq.enqueue(2)
sq.is_empty()
sq.length()
print(sq.top())
print(sq.dequeue())
print(sq.length())
|
def print_rangoli(size):
entry=1
letters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',\
'u','v','w','x','y','z']
constant=size+(size-1)+2*(size-1)
for i in range (0,((2*size))):
str1=''
str2=''
if i < size:
for j in range(0,entry):
str1+='-'+letters[size-j-1]
str1+=str1[::-1][1:]
spaces2add=(constant-(len(str1)))/2
if i==size-1:
str1=str1[1:-1]
for o in range(spaces2add):
str1='-'+str1+'-'
entry+=1
print str1
elif i==size:
entry-=1
else:
entry-=1
for k in range(0,entry):
str2+='-'+letters[size-k-1]
str2+=str2[::-1][1:]
spaces2add=(constant-(len(str2)))/2
if i==0:
str2=str2[1:-1]
for o in range(spaces2add):
str2='-'+str2+'-'
print str2
if __name__ == '__main__':
n = int(raw_input())
print_rangoli(n)
# takes a input from user
# number of points to draw the rangoli
|
from _generate_site.elements import *
page = Page("jit-project/progress-timeline/journal-4.html",
nav_loc=["JIT Project", "Progress Timeline", "[8] Journal 4"])
page += Title("Journal 4: Weeks 14-15")
page += Paragraph("February 27, 2021 - March 20, 2021")
page += Heading('Goals for this Journal:')
page += OrderedList([
Paragraph("Make Parameters and Branches work"),
Paragraph("Generate said Parameters and Branches"),
Paragraph("Implement If-statements"),
Paragraph("Implement Comparisons"),
Paragraph("Implement Blocks"),
Paragraph("Implement While-statements"),
Paragraph(f"Create Instruction Emission Optimizations for everything implemented over these two weeks, like {inline_code('xor rax, rax')} over {inline_code('mov rax, 0')}"),
])
page += Heading("Research")
page += Paragraphs(f"""
{bold("Note: all references labelled at the bottom.")}
{bold("Note: I used code snippets instead of screenshots because this is a programming project.")}
{bold("Note: I used pseudocode instead of actual C for the sake of clarity.")}
These were the weeks focused on {bold('control-flow')}. The subject of this journal, therefore, will be branches, comparison,
and loops.
The essence of control-flow is dynamically choosing what code runs based on the state of the program. It sounds fancy,
but it's essentially just if-statements and loops. The if-statement is one fundamental example of control flow:
""")
page += Code("""
if (a > b) {
foo();
} else {
bar();
}
""")
page += Paragraphs(f"""
The program in this example can take two paths once it reaches the if-statement. It can either execute 'foo', or it can
execute 'bar'. When the program reaches {inline_code('if (a > b)')}, it dynamically chooses between the first or second path,
depending on whether 'a' is greater than 'b' or not. In other words, the if-statement controls the flow of the program between
two different paths.
The other fundamental control-flow pattern is the while-statement, or while-loop:
""")
page += Code("""
while (a < b) {
a = a + 1;
}
""")
page += Paragraphs(f"""
For as long as {inline_code('a < b')}, 1 will be added to a. The while-statement directs the flow of the program into the body
of the loop, the {inline_code('{ a = a + 1; }')}, for as long as the condition is true.
From these two patterns, most other common forms of control-flow can be built. The normal switch statement, with {inline_code('break')}s
after every case:
""")
page += Code("""
switch (a) {
case 1: {
print("a is 1");
break;
}
case 2: {
print("a is 2");
break;
}
default: {
print("a is something other than 1 or two");
break;
}
}
""")
page += Paragraphs(f"""
Such a form could be rewritten as a series of nested if-statements:
""")
page += Code("""
if (a == 1) {
print("a is 1");
} else {
if (a == 2) {
print("a is 1");
} else {
print("a is something other than 1 or two");
}
}
""")
page += Paragraphs(f"""
The regular for-statement:
""")
page += Code("""
for (i = 25; i >= 0; i = i - 1) {
print(i + " seconds left");
}
""")
page += Paragraphs(f"""
This could be replace with the following:
""")
page += Code("""
i = 25
while (i >= 0) {
print(i + " seconds left");
i = i - 1;
}
""")
page += Paragraphs(f"""
in fact, the while statement can be replaced if you use the more primitive goto-statement. The above could be replaced with:
""")
page += Code("""
i = 25
label cond:
if (i >= 0) {
print(i + " seconds left");
i = i - 1;
goto cond;
} else {
goto after;
}
label after:
""")
page += Paragraphs(f"""
The goto does exactly what it looks like it does, immediately move the program to corresponding label. Thus, by carefully placing
those goto's, we can create loops, especially by jumping with a goto to a point where the code will naturally return to that same
goto.
But we can do even better. A conditional goto (which only jumps if it's condition it true) could replace all if-statements:
""")
page += Code("""
i = 25
cond = i >= 0
goto after if cond;
label cond:
print(i + " seconds left");
i = i - 1;
goto cond;
label after:
""")
page += Paragraphs(f"""
I've shown that you can reduce for-loops and switch-statements to if-statements and while-loops. I've also shown
that if-statements and while-loops can be reduced to regular and conditional goto's. Therefore, we can reduce for-loops and
switch-statements, and indeed all higher control-flow forms, into the dead simple goto.
CPU's are designed to be simple in both operation and function. Therefore, there is no direct support for advanced control
flow in assembly. If you want to make an if-statement, you'll have to make it out of goto's. The bulk of my work for
this period is figuring out how to do reduce advanced control-flow forms into goto's efficiently.
The basis of the system I devised is the concept of "basic blocks", or blocks for short. I did not come up with this term,
rather, I learned of it while researching about SSA form, because blocks are an essential component of SSA form. See the
reference on LLVMLite for the actual source.
The essence of a block is that it breaks down program flow into its most basic pieces. Code will always start at the top
of a basic block, will always go all the way through in one specific path, and at the end will choose a new basic block to
go to. Additionally, within a basic block, SSA rules must be followed: all values must have a single, defined point of origin.
Let's review what doesn't qualify as valid SSA first:
""")
page += Code("""
%a = 0 > 1 // assign the true/false value of whether 0 is greater than 1 to the value "a"
%b = 5
%c = 7
%d = %a ? %b : %c // This is a ternary operator. It'll set %d to %b if %a is true, otherwise it'll set %d to %c (see sources).
// It is illegal because there are two paths to take, either %d = %b or %d = %c
%c = %a // illegal because in SSA, you can't reassign a value. Rather, just make a new one with a different name
""")
page += Paragraphs(f"""
Now that we've reviewed that, I can show how we can reduce higher control-flow forms into a basic-block based system.
The following examples will be using almost exactly the same system that I have implemented into my actual code.
We start with the following code that uses a for-loop to determine whether k is prime:
""")
page += Code("""
k = 27;
is_prime = true;
for (i = 2; i < k; i++) {
if (k % i == 0) {
// btw, the % operator is the modulus operator
// it'll calculate the remainder when k is divided by i
// so if k is 7 and i is 2, k % i will be 1.
// if the modulus is 0, that means that k divides evenly with i
is_prime = false;
}
}
""")
page += Paragraphs(f"""
As I've demonstrated before, we can replace the for-loop with a while-loop.
""")
page += Code("""
k = 27;
is_prime = true;
i = 2
while (i < k) {
if (k % i == 0) {
is_prime = false;
}
i++;
}
""")
page += Paragraphs(f"""
Then we replace the while-loops and if-statements with the equivalent goto's and conditional goto's.
""")
page += Code("""
k = 27;
is_prime = true;
i = 2
label start;
while_cond = i < k;
goto after_while if while_cond;
mod = k % i;
if_cond = mod != 0;
goto after_if if if_cond;
is_prime = false;
label after_if:
i++;
goto start;
label after_while;
""")
page += Paragraphs(f"""
We've reached a problem in our quest to convert this for-loop into SSA form. Variables are being assigned multiple times,
and all the goto's make it hard to figure out how to replace variable reassignments with new variables. (Additionally, it
would be impossible to do so because variables are being reassigned an indeterminate number of times. We would have to actually
execute the program to figure out how many times we would have to reassign 'is_prime', for example.)
Let's try a new approach. We start off in a block called "entry". Whenever we reach a point where the program flow could take
multiple paths, we create multiple new blocks, and tell our current block to choose between the new blocks. I'll explain what I
mean with a simpler example:
""")
page += Code("""
a = 7;
if (a < 0) {
print("a is negative");
} else {
print("a is positive");
}
b = a + 3;
""")
page += Paragraphs(f"""
We start off working in the entry block, and generate the {inline_code('a = 7;')} in that block.
""")
page += Code("""
block @"entry" {
%a = int64 7; // int32 means signed 64 bit integer (uint64 would be unsigned).
}
""")
page += Paragraphs(f"""
We then reach the if-statement and its split. First, we generate the condition:
""")
page += Code("""
block @"entry" {
%a = int64 7;
%temporary_cond = lt a, 0; // lt means less than ('<').
}
""")
page += Paragraphs(f"""
Then we create 3 new blocks. One is what we execute if the condition is true, one if what we execute when the condition is
false, and the final one is what we come back to after the if-statement. Remember, we cannot jump out of the middle of a
basic block, so the stuff which comes after an if-statement must be in a new block.
""")
page += Code("""
block @"entry" {
%a = int64 7;
%temporary_cond = lt a, 0; // lt means less than ('<').
}
block @"if_true" {
}
block @"if_false" {
}
block @"after_if" {
}
""")
page += Paragraphs(f"""
We tell the entry block that it must conditionally branch to if_true if %temporary_cond is true, and if_false otherwise.
We call this final instruction a "terminator" because it terminates a block. A terminator must be some form of branch
to a new block, or a return instruction.
""")
page += Code("""
block @"entry" {
%a = int64 7;
%temporary_cond = lt a, 0; // lt means less than ('<').
} then cbranch(%temporary_cond) {true: @"if_true", false: @"if_false"); // cbranch stands for conditional branch
block @"if_true" {
}
block @"if_false" {
}
block @"after_if" {
}
""")
page += Paragraphs(f"""
We then visit each branch of the if-statement in turn, and generate the appropriate code.
""")
page += Code("""
block @"entry" {
%a = int64 7;
%temporary_cond = lt a, 0; // lt means less than ('<').
} then cbranch(%temporary_cond) {true: @"if_true", false: @"if_false");
block @"if_true" {
print("a is negative");
}
block @"if_false" {
print("a is positive");
}
block @"after_if" {
}
""")
page += Paragraphs(f"""
We must then terminate those two blocks. We know that each will go to after_if, so we can just emit a regular,
unconditional branch.
""")
page += Code("""
block @"entry" {
%a = int64 7;
%temporary_cond = lt a, 0; // lt means less than ('<').
} then cbranch(%temporary_cond) {true: @"if_true", false: @"if_false");
block @"if_true" {
print("a is negative");
} then branch @"after_if";
block @"if_false" {
print("a is positive");
} then branch @"after_if";
block @"after_if" {
}
""")
page += Paragraphs(f"""
Finally, we can generate the code in the after_if.
""")
page += Code("""
block @"entry" {
%a = int64 7;
%temporary_cond = lt a, 0; // lt means less than ('<').
} then cbranch(%temporary_cond) {true: @"if_true", false: @"if_false");
block @"if_true" {
print("a is negative");
} then branch @"after_if";
block @"if_false" {
print("a is positive");
} then branch @"after_if";
block @"after_if" {
%b = $a + 3;
}
""")
page += Paragraphs(f"""
This example demonstrates the principles of breaking control-flow into basic blocks. To make this a loop, all some code has
to do is make one of the branches point to an earlier block which will lead back to the branch. But what if we want variables
which could have different values? Like in this example:
""")
page += Code("""
a = 7;
if (a < 0) {
b = 3;
} else {
b = 4;
}
c = a + b;
""")
page += Paragraphs(f"""
In normal SSA code, we'd use something called a phi instruction (from LLVMLite). A phi instruction is what gets around the
limitation of SSA that each value can have only one definition, which is very annoying when we have an example like above
where the b in {inline_code('c = a + b;')} has two different definitions which we cannot choose from until the code runs.
The phi node for this b would take the form {inline_code('%b = phi {@if_true: %b.1, @if_false: %b.2}')} where %b.1 is the
b from {inline_code('b = 3')} while %b.2 is the b from {inline_code('b = 4')}. The phi node lets us choose which value to use
depending on which block we have come from.
However, phi nodes are pretty hard to generate on the fly. We need to use a somewhat complicated algorithm involving
a construction known as "dominance frontiers". However, this requires a separate pass over the generated IR, which takes
extra time. Therefore, I came up with a simpler, if less mathematically rigorous system which saves time and memory at the
expense of less precisely defined IR. I think this a good trade off.
The two most important parts of my system are BlockParameter instructions and that I keep track of what values
each variable is currently in. Let's reduce the above code example to my system's block system.
Like before, we generate the stuff before the if-statement and the condition into the first block, and generate the 3 other blocks.
Additionally, whenever we generate a value, we keep track of what variable it would be assigned to in the actual program,
if it is in one.
""")
page += Code("""
block @"entry" {
%a ("a") = int64 7; // the ("a") tells us that %a stores the variable "a"
%temporary_cond (none) = lt a, 0; // the (none) tells us that %temporary_cond doesn't have a variable associated
}
block @"if_true" {
}
block @"if_false" {
}
block @"after_if" {
}
""")
page += Paragraphs(f"""
Like before, we generate a cbranch. However, this time, we do a lot of extra work for it with the following code
({hyperlink('link to code in repo', 'https://github.com/Totillity/ojit/blob/78a9481e51de6525829808f924285e06bb3d74ab/asm_ir_builders.c#L184')}):
""")
page += Code("""
void merge_blocks(IRBuilder* builder, struct BlockIR* to, struct BlockIR* from) {
if (to->has_vars) {
FOREACH_INSTR(curr_instr, to->first_instrs) {
if (curr_instr->base.id == ID_BLOCK_PARAMETER_IR) {
struct ParameterIR* param = &curr_instr->ir_parameter;
if (param->var_name == NULL) continue;
IRValue arg;
if (!hash_table_get(&from->variables, STRING_KEY(param->var_name), (uint64_t*) &arg)){
param->var_name = NULL;
} else {
INC_INSTR(arg);
}
} else {
break;
}
}
} else {
struct BlockIR* original_block = builder->current_block;
builder_temp_swap_block(builder, to);
TableEntry* curr_entry = from->variables.last_entry;
while (curr_entry) {
builder_add_parameter(builder, curr_entry->key.cmp_obj);
IRValue arg = (void*) curr_entry->value;
INC_INSTR(arg);
curr_entry = curr_entry->prev;
}
builder_temp_swap_block(builder, original_block);
to->has_vars = true;
}
}
""")
page += Paragraphs(f"""
Essentially, if the block has never been branched to before, we generate a BlockParameter instruction in it for every variable
in the originating block. Therefore, for blocks if_true and if_false, we'd generate:
""")
page += Code("""
block @"entry" {
%a ("a") = int64 7;
%temporary_cond (none) = lt a, 0;
} then cbranch(%temporary_cond) {true: @"if_true", false: @"if_false");
block @"if_true" {
%a.1 ("a") = parameter "a"
}
block @"if_false" {
%a.2 ("a") = parameter "a"
}
block @"after_if" {
}
""")
page += Paragraphs(f"""
Now it's time to create the two blocks' terminators. Each is still an unconditional branch to after_if like before,
but when if_false generates its branch, the merge_block function I showed above notices that it isn't the first block
which branches to after_if (if_true is the first). Therefore, it deactivates any parameters which have already been generated
in after_if which aren't variables in if_false. This behavior isn't used here, but is needed whenever two alternate paths
generate differently named variables. In that case, we don't want the code which comes after the two paths to be able to
refer to variables which are only defined in one branch, because we didn't necessarily take that branch when the code is actually
executed.
Anyways, here's the new code. We still just keep a and b in after_if.
""")
page += Code("""
block @"entry" {
%a.0 ("a") = int64 7;
%temporary_cond (none) = lt a.0, 0;
} then cbranch(%temporary_cond) {true: @"if_true", false: @"if_false");
block @"if_true" {
%a.1 ("a") = parameter "a"
%b.1 ("b") = 3
} then branch @"after_if"
block @"if_false" {
%a.2 ("a") = parameter "a"
%b.2 ("b") = 4
} then branch @"after_if"
block @"after_if" {
%a.3 ("a") = parameter "a"
%b.3 ("b") = parameter "b"
%c.0 ("c") = %a.3 + %b.3
}
""")
page += Paragraphs(f"""
When we generate code, all we have to do is ensure that a parameter always arrives in that block in a specific register
(for example, specific that %a.3 must always be in RAX). Then it's the branches' job to make sure that is actually the case.
The branches must look at the most recent definition of a particular variable (which is why we store the value's variables)
and tell that value it must be in the same register as the parameter.
Thus, we can use multiple definitions of variables in SSA form.
Don't worry, I haven't forgotten why I went on this whole tangent. Here's the sample we are trying to convert into block-based
IR, for your convenience:
""")
page += Code("""
k = 27;
is_prime = true;
for (i = 2; i < k; i++) {
if (k % i == 0) {
is_prime = false;
}
}
""")
page += Paragraphs(f"""
As I've shown before, we can convert it into a form with while-loops, which are much easier to use.
""")
page += Code("""
k = 27;
is_prime = true;
i = 2;
while (i < k) {
if (k % i == 0) {
is_prime = false;
}
i++;
}
""")
page += Paragraphs(f"""
Using our newfound knowledge of blocks, we can translate the sample into the following:
""")
page += Code("""
block @"entry" {
%k.0 ("k") = int32 27;
%is_prime.0 ("is_prime") = bool true;
%i.0 ("i") = 2;
} then branch @"cond";
block @"cond" {
%k.1 ("k") = parameter "k";
%is_prime.1 ("is_prime") = parameter "is_prime";
%i.1 ("i") = parameter "i";
%.cond.0 = lt %i.1, %k.1;
} then cbranch(%.cond.0) {true: @"loop_body", false: @"after_loop"};
block @"loop_body" {
%k.2 ("k") = parameter "k";
%is_prime.2 ("is_prime") = parameter "is_prime";
%i.2 ("i") = parameter "i";
%.0 = mod %k.2, %i.2;
%.cond.1 = eq %.0, int32 0;
} then cbranch(%.cond.1) {true: @"if_true", false: @"after_if"};
block @"if_true" {
%k.3 ("k") = parameter "k";
%is_prime.3 ("is_prime") = parameter "is_prime";
%i.3 ("i") = parameter "i";
%is_prime.4 = bool false;
} then branch @"after_if";
block @"after_if" {
%k.4 ("k") = parameter "k";
%is_prime.5 ("is_prime") = parameter "is_prime";
%i.4 ("i") = parameter "i";
%i.5 ("i") = add %i.4, int32 1;
} then branch @"cond";
block @"cond" {
%k.5 ("k") = parameter "k";
%is_prime.6 ("is_prime") = parameter "is_prime";
%i.6 ("i") = parameter "i";
...
""")
page += Paragraphs(f"""
As I said before, now that we have this dead simple representation of the program, it is very easy to convert it into assembly.
We can simply generate the code for each block, string them into a line, and use the JMP instruction or the Jcc instruction
family to jump around.
Let's also go over conditionals real quick. In the x86 and x64 instruction sets, you cannot directly predicate a jump
based on the contents of a register. As an example, you can't do something like this:
""")
page += Code("""
mov rax, 3 // set rax to 3
mov rcx, 4 // set rcx to 4
lt rax, rcx // set rax to 1 if rax < rcx, or 0 otherwise
jmp_if rax, 0x47 // if rax is 1, then jump forward 0x47 bytes
""")
page += Paragraphs(f"""
Those last two instructions, lt and jmp_if, don't exist. Instead, x86 uses a concept called flags. Flags can be imagined as a set of
special registers with the sole purpose of storing whether a particular condition is true or false. There are many flags
in a processor which operates on x86, each of which stores information about something different, but only 5 are important to
us: The Carry Flag, the Parity Flag, the Zero Flag, the Sign Flag, and the Overflow flag.
Some instructions will set flags, some will ignore them, and others will read from them. An instruction in the first category
is the add instruction. Say we execute {inline_code('mov rax, 3; add rax, 2')}. After this snippet executes, the value in
rax will clearly be 5. When the add instruction finishes, it will set different flags based on that final value. Since
the result does not change signs compared to the operands, the Overflow Flag is unset (set to 0, no matter its previous value).
Since the result fits in the normal 64 bits, the Carry Flag is Unset. Since the number of bits which are 1 in 5 {inline_code('0000 0101')}
is even, the Parity flag is set. Since the most significant bit of 5 in its 64 bit representation is unset, the Sign Flag is unset.
Finally, since 5 is not 0, the Zero Flag is unset.
You can then do some conditional operations based on these flags. The most common instructions are those of the Jcc family.
JE (Jump Equal), for example, will only jump if the Zero Flag is set. JAE (Jump Above or Equal) will only jump if the Carry
Flag is unset.
You might ask why JE jumps when the Zero Flag is set. After all, what does an equality check have to do with a zero check?
The answer is the almighty CMP instruction. CMP subtracts two values and sets the flags based on the result, but does not
store said result. By using this instruction and carefully choosing what Jcc instruction to use, you can make any comparison
between two numbers. For example, take {inline_code('cmp rax, rcx')}. The CMP instruction will subtract the two registers.
If they are equal, then the result will be zero and the Zero flag set. Therefore, if you follow this instruction with a JE
instruction, the JE instruction will in fact be dependent on whether rax and rcx are equal. The other Jcc instructions follow the
same idea.
By using this concept of flags, explained in the Intel Instruction Reference, we can do comparisons and conditional jumps.
There are also a few more optimization opportunities jumps open up. One would be the different varieties of the JMP and
Jcc instructions: some come with a 4-byte offset and others with a 1-byte offset. If we know the jump is to somewhere within
127 bytes on either side (1-byte signed goes from -128 to 127), then we can use the 3x shorter 1-byte form. Additionally,
if we the know that a Jcc is predicated on a SUB instruction, then we know we can skip the CMP since the SUB will have set the
flags already in the exact same way.
Another optimization I've done shows just how obscure x86 optimization can be. The {inline_code('mov rax, 0')} instruction
sets the value of rax to 0. This takes 10 bytes ({inline_code('48 b8 00 00 00 00 00 00 00 00')} if you do it the obvious way,
loading a 64 byte immediate into rax. It can be done in only 7 bytes ({inline_code('48 c7 c0 00 00 00 00')}) if you load
a 32 byte immediate instead and take advantage of the fact that x86 automatically sign-extends 32 byte immediate to 64 bytes.
The shortest way, however, is to just XOR the register you want to zero out with itself. Since it is a mathematical identity
that a number xor'ed with itself will be zero, this trick will always work. By doing so, you shave this operation down to
only 3 bytes {inline_code('48 31 c0')}.
""")
page += Heading("Main Accomplishments")
page += OrderedList([
Paragraph("Implemented Blocks"),
Paragraph("Implemented and Debugged Block Parameters"),
Paragraph("Implemented Jumps and Jcc in Assembly"),
Paragraph("Implemented Conditionals and their Optimizations"),
Paragraph("Implemented If statements, While Loops, and Comparisons"),
Paragraph("Implemented simple optimizations for the above"),
])
page += Heading("Reflection")
page += Paragraphs(f"""
The above stuff took far longer than expected, because I did not prepare enough for it. Then again, how can you prepare
for this without actually doing it at least once? However, now that I did get everything to work, it feels very rewarding.
I spent 3 full days trying to make If-statements and block parameters work. Once those were finished, I went on to try and
implement while loops. To my surprise, those 3 days of work on If-statement paid off, and while loops actually worked on the first
try. They were a 5 minute addition.
I'm now at a point where I feel comfortable working on types, objects, and co. Once I finish that area, I can move on to
the actual JIT part of the JIT, where it chooses optimizations based on what the program is actually doing at a given time.
The 5th journal is looking to be packed.
""")
page += Heading("Sources:")
page += OrderedList([
Paragraph(f"{hyperlink('x64 Instruction Reference', 'https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf')}"),
Paragraph(f"{hyperlink('Reference on x64 encoding #1', 'https://pyokagan.name/blog/2019-09-20-x86encoding/')}"),
Paragraph(f"{hyperlink('Reference on x64 encoding #2', 'http://ref.x86asm.net/geek64.html')}"),
Paragraph(f"{hyperlink('Reference on x64 encoding #3', 'https://wiki.osdev.org/X86-64_Instruction_Encoding')}"),
Paragraph(f"{hyperlink('Reference on LLVMLite'), 'https://llvmlite.readthedocs.io/en/latest/user-guide/ir/index.html'}"),
Paragraph(f"{hyperlink('Ternary Operator in JavaScript, and similar in C, Java C#, etc.'), 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator'}"),
Paragraph(f"{hyperlink('Ternary Operator in Python'), 'https://docs.python.org/3/reference/expressions.html?highlight=ternary#conditional-expressions'}"),
Paragraph(f"{hyperlink('Dominance Frontiers', 'https://en.wikipedia.org/wiki/Static_single_assignment_form#Computing_minimal_SSA_using_dominance_frontiers')}"),
Paragraph(f"{hyperlink('Explanation of Overflow vs Carry Flag', 'http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt')}"),
])
__pages__ = [page]
|
import sqlite3
# 将游标获取的元组根据数据库列表转为字典表
def make_dicts(cursor, row):
return dict((cursor.description[i][0], value) for i, value in enumerate(row))
class SqlHelper(object):
def __init__(self):
self.path = r"e:\test\test.db"
# 打开数据库连接
def get_db(self):
db = sqlite3.connect(self.path)
db.row_factory = make_dicts
return db
# 执行SQL语句,但不返回结果
def execute_sql(self, sql, prms=()):
c = self.get_db().cursor()
c.execute(sql, prms)
c.connection.commit()
# 执行用于选择数据的SQL语句。
def query_sql(self, sql, prms=(), one=False):
c = self.get_db().cursor()
result = c.execute(sql, prms).fetchall()
c.close()
return (result[0] if result else None) if one else result
db = SqlHelper()
|
import turtle,time
yy=turtle.Turtle()
yy.color('white')
yy.shape('turtle')
xx=turtle.Screen()
xx.bgcolor('black')
num_sides=int(input('要畫幾邊形(3-10):'))
side_length=70
angle=360.0/num_sides
for i in range(num_sides):
yy.forward(side_length)
yy.right(angle)
time.sleep(1)
turtle.done() |
import pygame
from pygame.sprite import Sprite
class Ammo(Sprite):
"""Ammunition used by spaceship"""
def __init__(self, board_settings, screen, ship):
"""constructor for ammo super class"""
super(Ammo,self).__init__()
self.screen = screen
self.rect = pygame.Rect(0,0,board_settings.bullet_size,
board_settings.bullet_length)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
# positional info of ammo
self.y = float(self.rect.y)
self.color = board_settings.bullet_color
self.speed_factor = board_settings.bullet_speed_factor
def update(self):
"""updates the position of the shots fired by ship up screen"""
self.y -= self.speed_factor
self.rect.y = self.y
def draw_ammo(self):
"""Draw the bullet to the screen"""
pygame.draw.rect(self.screen,self.color,self.rect)
|
__author__ = "Adam Najman"
"""
Adam Najman
CSCI HW 5
Dijkstra's Algorithm using an array!
Running time is O(V^2 + E)
Please see input.txt for graphs
The second to last graph has 12 nodes and 144 edges.
This takes twice as long in the array implementation
compared to the binary heap version.
"""
import re
from collections import defaultdict
from time import time
def dijkarray(v, ec):
emat, cmat = [None for x in xrange(v)], \
[float('inf') for y in xrange(v)]
emat[0], cmat[0] = 0, 0
source = min(ec.keys())
rnd = ec[source]
while rnd is not None and source < e:
for elem in rnd:
#print elem, source
if elem[1] < cmat[elem[0]]:
emat[elem[0]] = source
cmat[elem[0]] = elem[1] + cmat[source]
del ec[source]
if len(ec.keys()) == 0:
break
source = min(ec.keys())
rnd = ec[source]
#print "emat is: ", emat #UNCOMMENT TO SEE TOTAL
#print "cmat is: ", cmat #COSTS AND PATHS
if cmat[-1] == float('inf'):
return "UNREACHABLE"
return cmat[-1]
f = open('input.txt', 'r')
v, e = 0, 0
while v is not -1:
temp = f.readline()
delim = " "
v, e = temp.split(delim)
v, e = int(v), int(e)
if v is -1:
break
#print "v, e: ", v, e
line = f.readline()
#print "line: " , line
delim = " ", "-", ":", "\n"
pattern = '|'.join(map(re.escape, delim))
foo = re.split(pattern, line)
for x in xrange(len(foo)-1):
foo[x] = int(foo[x])
ec = defaultdict(list)
qq = 0
while qq < (len(foo)-1):
if foo[qq] in ec.keys():
temp = ec[foo[qq]]
temp.append((foo[qq+1], foo[qq+2]))
ec[foo[qq]] = temp
else:
ec[foo[qq]] = [(foo[qq+1], foo[qq+2])]
qq += 3
#t = time()
ac = dijkarray(v, ec)
print ac
#print t - time()
|
__author__ = "Adam Najman"
__filename__ = "lcs.py"
__homework_number__ = 3
from time import time
from collections import defaultdict
diagonal = -1
left = 0
up = 1
def topdown(s1, s2):
return None
def bottomup(s1, s2):
print "comparing " , s1 , " and " , s2
for i in xrange(1, len(s1)):
for j in xrange(1, len(s2)):
if s1[i-1] == s2[j-1]:
print "opt[",i,"][",j,"]= ", opt[i-1][j-1] + 1
opt[i][j] = opt[i-1][j-1] + 1
#print "back[",i,"][",j,"]= ", diagonal
back[i][j] = diagonal
elif opt[i-1][j] >= opt[i][j-1]:
print "opt[",i,"][",j,"]= ", opt[i-1][j]
opt[i][j] = opt[i-1][j]
#print "back[",i,"][",j,"]= ", up
back[i][j] = up
else:
print "opt[",i,"][",j,"]= ", opt[i][j-1]
opt[i][j] = opt[i][j-1]
#print "back[",i,"][",j,"]= ", left
back[i][j] = left
"""
if i == 0 or j == 0:
opt[i][j] = 0
if s1[i] == s2[i]:
opt[i][j] = opt[i-1][j-1] + 1
else:
opt[i][j] = max( opt[i][j-1], opt[i-1][j] )
"""
#print opt.values()
print opt.keys()
for foo in opt.keys():
print foo, opt[foo]
print back.keys()
for bar in back.keys():
print back[bar]
print len(s1)
print len(s2)
def backtrace(s, i, j):
#print back
print i, back[i], j
print back[i][j]
if i == 0 or j == 0:
print "return"
return
if back[i][j] == diagonal:
print "diagonal"
backtrace(s, i-1, j-1)
print s[i]
elif back[i][j] == up:
print "going up"
backtrace(s, i-1, j)
else:
print "going left"
backtrace(s, i, j-1)
f = open("lcsin.txt", 'r')
o = open("lcsout.txt", 'w')
def go(func, oper):
for group in oper:
opt = defaultdict(lambda: defaultdict(int))
back = defaultdict(lambda: defaultdict(int))
t = time()
print func(group[0], group[1])
if opt.keys() == []:
print "NO LCS"
print t - time()
lines = []
for line in f:
lines.append(line.split())
#go(topdown, lines)
#go(bottomup, lines)
for group in lines:
opt = defaultdict(lambda: defaultdict(int))
back = defaultdict(lambda: defaultdict(int))
t = time()
print topdown(group[0], group[1])
if opt.keys() == []:
print "NO LCS"
else:
backtrace(group[0], len(group[0]), len(group[1]))
print t - time()
for group in lines:
opt = defaultdict(lambda: defaultdict(int))
back = defaultdict(lambda: defaultdict(int))
t = time()
print opt, back
print bottomup(group[0], group[1])
if opt.keys() == []:
print "NO LCS"
else:
print "backkeys is: ", back.keys(), len(back.keys())
print "backvals is: ", back.values(), len(back.values())
backtrace(group[0], len(back.keys()) - 1, \
len(back.values()) - 2)
print t - time()
|
while True:
print("**************************")
print("1. Retrieve")
print("2. Add")
print("3. Update")
print("4. Delete")
print("5. Quit")
print("**************************")
input_num = int(input(">"))
if input_num == 1:
print("Retrieve")
elif input_num == 2:
print("Add")
elif input_num == 3:
print("Update")
elif input_num == 4:
print("Delete")
elif input_num == 5:
print("Bye Bye!!")
break
|
class Animal(object):
def drink(self):
print("这是一个喝水的方法")
pass
def run(self):
print("这是一个跑步的方法")
pass
def eat(self):
print("这是一个吃饭的方法")
pass
def bark(self):
print("这是一个喊叫的方法")
pass
class Tiger(Animal):
def __init__(self, name):
self.name = name
def run(self):
print("%s 跑步,这是一只狗儿" % (self.name))
def drink(self):
print("%s 喝水,这是一只狗儿" % (self.name))
def eat(self):
print("%s 吃饭,这是一只狗儿" % (self.name))
def bark(self):
print("%s 喊叫,这是一只狗儿" % (self.name))
class Lion(Animal):
def __init__(self, name):
self.name = name
def run(self):
print("%s 跑步,这是一只猫儿" % (self.name))
def bark(self):
super().bark() # super()方法可以返回一个父类的对象,可以用来在子类中调用父类方法
print("%s 喊叫,这是一只猫儿" % (self.name))
class TigerLion(Lion, Tiger):
def __init__(self, name):
self.name = name
if __name__ == '__main__':
tiger1 = TigerLion("虎狮兽")
tiger1.run()
|
def checkpass(p):
check = 0;
lower = [a.islower() for a in p]
upper = [a.isupper() for a in p]
digit = [a.isdigit() for a in p]
for i in lower:
if (i == True):
check = check + 1;
break
for i in upper:
if (i == True):
check = check + 1;
break
for i in digit:
if (i == True):
check = check + 1;
break
if (check == 3):
return True
else:
return False
print (checkpass("8fhwhFNSeri"))
print (checkpass("8fhwheri"))
def strength(p):
strength = 1;
lower = [a.islower() for a in p]
upper = [a.isupper() for a in p]
digit = [a.isdigit() for a in p]
for i in lower:
if (i == True):
strength = strength * 1.1;
for i in upper:
if (i == True):
strength = strength * 1.2;
for i in digit:
if (i == True):
strength = strength * 1.3;
if (strength > 10):
return 10
else:
return strength
print strength("hudhfUNSEU4273488")
print strength("trnirnitrngirtin")
print strength("trtin")
print strength("rPP5n")
|
import numpy as np
# Write a function that takes as input a list of numbers, and returns
# the list of values given by the softmax function.
def softmax(L):
prob = []
summ = 0
for i in range(len(L)):
summ += np.exp(L[i])
for i in range(len(L)):
prob.append(np.exp(L[i])/summ)
return prob |
import random, re
class MineSweeper:
"""
Beginner: 9 x 9, 10 mines
Intermediate: 16 x 16, 40 mines
Advanced: 30 x 16, 99 mines
Customized: 9 x 9 to 30 x 24, 10 to 668 mines with max of (X-1) x (Y-1) for X x Y
"""
def __init__(self, nx, ny):
self.__board = Board(nx, ny)
def put_mines(self, *coords):
for x, y in coords:
self.__board.put_mine(x, y)
def put_random_mines(self, num):
for i in range(num):
self.__board.put_random_mine()
def open(self, x, y):
b = self.__board
if b.is_open(x, y):
return True
elif b.is_mine(x, y):
return False
else:
b.open(x, y)
return True
def start(self):
while True:
print(self.__board)
while True:
command = self.__interpret(input('> '))
if command:
break
if command == 'q':
break
if not self.open(*command):
self.__finish("BOOM!")
break
if self.__board.is_all_open():
self.__finish("CLEAR!!")
break
def __finish(self, message):
print()
print(message)
print(self.__board.to_s(with_lid=False))
def __interpret(self, command):
if not command:
return False
if command.lower() == 'q':
return 'q'
if re.search("\A\d+\D+\d+\Z", command):
x, y = map(int, re.split("\D+", command))
if self.__board.is_open(x, y):
print("Already OPEN.")
return False
return (x, y)
return False
def __str__(self):
return str(self.__board)
class Board:
OB = ' '
MINE = '*'
def __init__(self, nx, ny):
self.__nx = nx
self.__ny = ny
self.__num_mines = 0
self.__initialize()
def __initialize(self):
self.__cells = []
for x in range(self.__nx + 2):
if x in [0, self.__nx + 1]:
row = [self.OB] * (self.__ny + 2)
else:
row = [self.OB] + ['0'] * self.__ny + [self.OB]
self.__cells.append(row)
self.__lids = []
for x in range(self.__nx + 1):
self.__lids.append([True] * (self.__ny + 1))
def nx(self):
return self.__nx
def ny(self):
return self.__ny
def put_mine(self, x, y):
self.__cells[x][y] = self.MINE
self.__num_mines += 1
for _x, _y in self.__adjacent_coordinates(x, y):
if self.__cells[_x][_y] == self.MINE:
continue
self.__increment(_x, _y)
def put_random_mine(self):
while True:
x = random.randrange(1, self.nx() + 1)
y = random.randrange(1, self.ny() + 1)
if not self.is_mine(x, y):
break
self.put_mine(x, y)
def __adjacent_coordinates(self, x, y):
return ((_x, _y) for _y in (y - 1, y, y + 1) for _x in (x - 1, x, x + 1) if _x != x or _y != y)
def is_mine(self, x, y):
return self.__cells[x][y] == self.MINE
def is_open(self, x, y):
return not self.__lids[x][y]
def is_all_open(self):
n_lids = sum(1 if self.__lids[x][y] else 0
for y in range(1, self.ny() + 1)
for x in range(1, self.nx() + 1))
return n_lids == self.__num_mines
def is_ob(self, x, y):
return self.__cells[x][y] == self.OB
def open(self, x, y):
if self.is_ob(x, y) or self.is_open(x, y):
return
self.__lids[x][y] = False
if self.__is_on_mine_edge(x, y):
return
for _x, _y in self.__adjacent_coordinates(x, y):
self.open(_x, _y)
def __is_on_mine_edge(self, x, y):
return 1 <= int(self.__cells[x][y]) < 9
def __increment(self, x, y):
value = self.__cells[x][y]
if value.isdigit():
self.__cells[x][y] = str(int(value) + 1)
def to_s(self, with_lid=True):
buffer = []
for y in range(1, self.__ny + 1):
rows = [self.__cell_display(x, y, with_lid) for x in range(1, self.__nx + 1)]
buffer.append(' '.join(rows))
return "\n".join(buffer)
def __cell_display(self, x, y, with_lid):
return '-' if with_lid and self.__lids[x][y] else self.__cells[x][y]
def __str__(self):
return self.to_s()
if __name__ == '__main__':
"""
ms = MineSweeper(5, 7)
ms.put_mines((2, 4), (3, 6))
ms.open(5, 1)
ms = MineSweeper(10, 10)
ms.put_mines((3, 3), (3, 8), (8, 3), (8, 8))
ms.open(5, 5)
"""
nx = 9
ny = 9
ms = MineSweeper(nx, ny)
ms.put_random_mines(10)
x = random.randrange(nx) + 1
y = random.randrange(ny) + 1
ms.start()
|
import re
from functools import reduce
import operator
def swap_digits_all(s, d1, d2):
d1, d2 = map(str, (d1, d2))
c_tmp = 'x'
return s.replace(d1, c_tmp).replace(d2, d1).replace(c_tmp ,d2)
def is_upsidedown(n):
s = str(n)
if re.search(r'[23457]', s):
return False
s_rev = ''.join(reversed(s))
return s == swap_digits_all(s_rev, 6, 9)
debug = 0
def count_for_same_num_digits_as(s_num, is_greater, allows_zero_at_top=False):
if debug: print('"{} {}" ==> '.format('>' if is_greater else '<', s_num), end='')
f_cmp_eq = operator.ge if is_greater else operator.le
f_cmp_ne = operator.gt if is_greater else operator.lt
f_count = lambda s_num, s_nums: len([n for n in map(int, s_nums) if f_cmp_eq(n, int(s_num))])
f_choose = max if is_greater else min
length = len(s_num)
if length == 1:
retval = f_count(s_num, ('0', '1', '8'))
elif length == 2:
nums = ('11', '69', '88', '96')
if allows_zero_at_top:
nums += ('00',)
retval = f_count(s_num, nums)
else:
d1, d2 = s_num[0], s_num[-1]
digits = ('1', '6', '8', '9')
if allows_zero_at_top:
digits += ('0',)
count_d1 = f_count(d1, digits)
if debug: print("(count_d1 = {})".format(count_d1))
count = 0
str_num_max_or_min = ('0' if is_greater else '9') * (length - 2)
count_all_for_two_digit_less = count_for_same_num_digits_as(str_num_max_or_min, is_greater, allows_zero_at_top=True)
if d1 not in digits:
count += count_all_for_two_digit_less * count_d1
else:
if count_d1 > 1:
count += count_all_for_two_digit_less * (count_d1 - 1)
s_num_two_less = s_num[1:-1]
count_sub_for_two_digit_less = count_for_same_num_digits_as(s_num_two_less, is_greater, allows_zero_at_top=True)
count += count_sub_for_two_digit_less
if d1 == '6':
d2 = int(d2) - (9 - 6)
elif d1 == '9':
d2 = int(d2) + (9 - 6)
if f_cmp_ne(int(d2), int(d1)) and is_upsidedown(s_num_two_less):
count -= 1
retval = count
if debug: print(retval)
return retval
def first_half_and_mid_and_second_half_of(n):
s = str(n)
length = len(s)
m1 = length // 2
m2 = m1 + (1 if length % 2 == 1 else 0)
half1 = s[:m1]
mid = s[m1:m2]
half2 = s[m2:]
return half1, mid, half2
def upsidedown(x, y):
count = count_for_same_num_digits_as(x, is_greater=True)
count += count_for_same_num_digits_as(y, is_greater=False)
for num_digits in range(len(x) + 1, len(y)):
count += 4 * 5 ** (num_digits // 2 - 1) * (3 if num_digits % 2 == 1 else 1)
return count
def upsidedown_brutally(x, y):
count = 1 if is_upsidedown(x) else 0
while True:
x = int(x) + 1
if int(x) > int(y):
break
if is_upsidedown(x):
count += 1
return count
if __name__ == '__main__':
import sys
sys.path.insert(0, './codewars')
import test
test.assert_equals(upsidedown('0','10'),3)
test.assert_equals(upsidedown('6','25'),2)
test.assert_equals(upsidedown('10','100'),4)
test.assert_equals(upsidedown('100','1000'),12)
test.assert_equals(upsidedown('100000','12345678900000000'),718650)
test.assert_equals(upsidedown('10000000000','10000000000000000000000'),78120000)
test.assert_equals(upsidedown('861813545615','9813815838784151548487'),74745418)
test.assert_equals(upsidedown('5748392065435706','643572652056324089572278742'),2978125000)
test.assert_equals(upsidedown('9090908074312','617239057843276275839275848'),2919867187)
|
class SubseqenceFinder:
def __init__(self, str):
self.__str = str
def is_subsequence(self, s):
pos_start = 0
for c in s:
pos = self.__str.find(c, pos_start)
if pos == -1:
return False
pos_start = pos + 1
return True
def longest_subsequence(self, array_of_s):
array_of_subseqs = filter(lambda s:self.is_subsequence(s), array_of_s)
array_shortest_first = sorted(array_of_subseqs, key=lambda s:len(s))
if len(array_shortest_first) == 0:
return ''
else:
return array_shortest_first[-1]
|
"""
2 3
..#
...
""
import sys, random
n_blocks = int(sys.argv[1]) if len(sys.argv) >= 2 else 9
nx, ny = (9, 9)
coords_blocks = []
while len(coords_blocks) < n_blocks:
x = random.randrange(nx)
y = random.randrange(ny)
if (x, y) in ((0, 0), (nx - 1, ny - 1)):
continue
elif (x, y) not in coords_blocks:
coords_blocks.append((x, y))
for y in range(ny):
print(''.join(['#' if (x, y) in coords_blocks else '.' for x in range(nx)]))
quit()
"""
def print_turns(turns):
print(" ", end='')
for y in range(len(turns[0])):
print("{0:>2} ".format(y), end='')
print()
print('-' * (3 + 4 * len(turns[0])))
for x, row in enumerate(turns):
print("{0:>2}: ".format(x), end='')
for cell in row:
if cell is None:
print(" N ", end='')
else:
s = ','.join(map(lambda e: 'N' if e == BLOCK else str(e), cell)) + ' '
print(s, end='')
print()
nx, ny = 9, 9
paths = tuple(map(list, [
".#.#.....",
".....#...",
"....#..#.",
"..#......",
"......#..",
"...#....#",
"..#..#...",
"......#.#",
".........",
]))
nx, ny = map(int, input().split())
paths = tuple([tuple(input()) for x in range(nx)])
BLOCK = 99999999
turns = [[None] * ny for x in range(nx)]
x = 0
blocked = False
for y in range(ny):
if paths[x][y] == '#' or blocked:
turns[x][y] = (BLOCK, BLOCK)
blocked = True
else:
turns[x][y] = (BLOCK, 0)
y = 0
blocked = False
for x in range(nx):
if paths[x][y] == '#' or blocked:
turns[x][y] = (BLOCK, BLOCK)
blocked = True
else:
turns[x][y] = (0, BLOCK)
turns[0][0] = [0, 0]
for x in range(1, nx):
for y in range(1, ny):
cell_above = turns[x - 1][y]
if paths[x][y] == '#':
turns[x][y] = (BLOCK, BLOCK)
else:
if cell_above == (BLOCK, BLOCK):
downward = BLOCK
else:
downward = min(cell_above[0], cell_above[1] + 1)
cell_left = turns[x][y - 1]
if cell_left == (BLOCK, BLOCK):
rightward = BLOCK
else:
rightward = min(cell_left[0] + 1, cell_left[1])
turns[x][y] = [downward, rightward]
print(min(turns[-1][-1]))
|
import numpy as np
from scipy import stats
import matplotlib.pyplot
MONTE_CARLO_SIMULATION_NUMBER = 1000
NUMBER_OF_EMPLOYEES = 1000
RETIREMENT_AGE = 65
MAX_TYPICAL_LIFESPAN = 100 # The beta distribution is defined for 0 to 1, so we need to scale to 0 to 1
NUMBER_OF_YEARS = 10000
EMPLOYEE_AGE = 45
P_VALUE_FOR_SKEW_MIN = 0.025
P_VALUE_FOR_SKEW_MAX = 0.975
#LIFESPAN_FOLLOWS_BETA_DISTRIBUTION = True # Unused for anything currently
# Note: the beta distribution has 2 parameters, alpha and beta
ALPHA_PARAMETER = 5
BETA_PARAMETER = 10
# Further note: the mean of a beta distribution is alpha / (alpha + beta) so for employee age 45 (5, 10) implies an average lifespan of 33+45 = 78
TURNOVER_PER_YEAR = 0.1 # If turnover = 1, entirely new workforce each year; if turnover is 0, workforce never changes
# With no error/variance in expected lifespan per person, number of employees who reach retirement age
print("")
turnover_count = int(NUMBER_OF_EMPLOYEES * TURNOVER_PER_YEAR)
employee_lifespans = []
number_reaching_retirement_age = []
employee_lifespans.append(np.random.beta(ALPHA_PARAMETER, BETA_PARAMETER, NUMBER_OF_EMPLOYEES) * MAX_TYPICAL_LIFESPAN + EMPLOYEE_AGE)
years_required_to_reach_symmetry = 0
for simulation_run in range(MONTE_CARLO_SIMULATION_NUMBER):
for year_number in range(NUMBER_OF_YEARS):
number_reaching_retirement_age.append((employee_lifespans[-1] >= RETIREMENT_AGE).sum())
#print("With sample mean of number expected to reach retirement: " + str(np.mean(number_reaching_retirement_age)))
#print("And sample standard deviation of number expected to reach retirement : " + str(np.std(number_reaching_retirement_age, ddof=1))) # The 1 takes the unbiased (sample) standard deviation
#print("And skew of number expected to reach retirement: " + str(stats.skew(number_reaching_retirement_age)))
if year_number > 7: # Skewtest requires at least 8 samples
skewtest = stats.skewtest(number_reaching_retirement_age)[1]
if skewtest < P_VALUE_FOR_SKEW_MIN or skewtest >= P_VALUE_FOR_SKEW_MAX:
years_required_to_reach_symmetry += year_number
break
employee_lifespans.append(employee_lifespans[-1])
np.random.shuffle(employee_lifespans[-1])
employee_lifespans[-1][0:turnover_count] = np.random.beta(ALPHA_PARAMETER, BETA_PARAMETER, turnover_count) * MAX_TYPICAL_LIFESPAN + EMPLOYEE_AGE
# Uncomment below to show graphs
# Use bin width of 1
"""if year_number == 1 or year_number > 100 and year_number % 9 == 0:
matplotlib.pyplot.hist(number_reaching_retirement_age, range(int(np.floor(min(number_reaching_retirement_age))), int(np.ceil(max(number_reaching_retirement_age)))))
matplotlib.pyplot.title('Expected lifespans for population of ' + str(NUMBER_OF_EMPLOYEES) + ' employees all initially age ' + str(EMPLOYEE_AGE) + ' if everyone has the same lifespan probability distribution (those individual distributions are skewed)')
matplotlib.pyplot.show()"""
print(years_required_to_reach_symmetry / MONTE_CARLO_SIMULATION_NUMBER) # average years to reach symmetry
# TODO: Try another function for life expectancy (e.g. from wikipedia)
# TODO: Think more analytically about the longitudinal analysis/"mixture problem" aspect
# TODO: Solve numerically for years to approach normality (or no skew i.e. symmetry)
# TODO: Incorporate aging
|
#From the Computing for Biologits: Chapter 1 Chapter Problem - gcContent.pys
from twoSalDNAs import *
# inIsland and outsideIsland
#>>> gcContent(inIsland)
#0.4275
#>>> gcContent(outsideIsland)
#0.5427
# This is a program used to calculate the
# GC Content, now for all DNA strings of any lengh.
def gcContent(DNA):
''' Computes the GC content of a DNA string,
now of any lenghth.'''
count = 0;
for i in range(len(DNA)):
if(DNA[i] == "G" or DNA[i] == "C"):
count += 1;
print(count / len(DNA));
#from Computing For Biologists: Chapter 1 Exercises 1 - count.py
def count(letter, string):
''' This function count takes in a letter,
or string with just 1 symbol in it, and
return the number of instances of that
letter in the input string. '''
#Itierate through the input string
count = 0;
for i in range(len(string)):
if( string[i] == letter):
count += 1;
print(count);
#from Computing For Biologists: Chapter 1 Exercises 1 - elif.py
def ORFadvisor(DNA) :
''' This function ORFadvisor(DNA) takes in a
string of DNA as input and will prompt
the user if they have complied with the
3 requirements of a strand of DNA to be ORF.'''
if(len(DNA) % 3 == 0 and
DNA[0: 3: 1] == 'ATG' and
(
(DNA[len(DNA) - 3: len(DNA): 1] == 'TGA' ) or
(DNA[len(DNA) - 3: len(DNA): 1] == 'TAG' ) or
(DNA[len(DNA) - 3: len(DNA): 1] == 'TAA' )
)
):
return ("This is an ORF")
elif(DNA[0: 3: 1] != 'ATG'):
return ("The first three bases are not ATG")
elif( DNA[len(DNA) - 3: len(DNA): 1] != 'TGA' and #DONT forget that AND is vital, NOT or
DNA[len(DNA) - 3: len(DNA): 1] != 'TAG' and #DONT forget that AND is vital, NOT or
DNA[len(DNA) - 3: len(DNA): 1] != 'TAA'
):
return ("The last 3 bases are not a STOP codon")
else:
return ("The string is not of the correct length")
def friendly(greeting):
''' This function friendly(greeting) take in a
greeting from user as input and then returns
a greeting to screen based on the user input.
Must say Hello or Hi, ask a question, else
it is not understandable.'''
if(greeting[0: 2: 1] == "Hi" or
greeting[0: 5: 1] == "Hello"):
return("Hey there, did you have a happy Mother's Day?")
elif(greeting[len(greeting) - 1] == "?"):
return("Good question!")
else:
return("I am sorry, but I did not understand you.")
|
#This is ifelse.py which is the 2nd exerise of chapter 1
#from Computing For Biologists.
def absolute(n) :
''' This function absolute(x) is to take input
and return the absolute value as output. '''
#>>> absolute(-3)
#3
#>>> absolute(5000000)
#5000000
if n < 0:
return (-n)
else:
return (n)
def palindrome4(input):
''' This function palindrome4(input) is to take an
input of a 4 character string and return
whether true or false. If not exactly 4 return
return false as well. '''
#>>> palindrome4("poop")
#True
#>>> palindrome4("dad")
#False
#>>> palindrome4("bool")
#False
#>>> palindrome4("abba")
#True
if (input == input[len(input) - 1: 0:-1] + input[0] and len(input) == 4) :
return (True)
else:
return (False)
def ORF(inputDNA):
''' This function ORF, Open Reading Frame, is to
take in a string of DNA as input, and then returns
the Boolean value True if input fulfills the following
3 conditions:
1) begins with 'ATG',
2) ends with 'TGA' or 'TAG' or 'TAA',
3) string length is a multiple of 3
'''
if(len(inputDNA) % 3 == 0 and
inputDNA[0: 3: 1] == 'ATG' and
(
(inputDNA[len(inputDNA) - 3: len(inputDNA): 1] == 'TGA' ) or
(inputDNA[len(inputDNA) - 3: len(inputDNA): 1] == 'TAG' ) or
(inputDNA[len(inputDNA) - 3: len(inputDNA): 1] == 'TAA' )
)
):
return (True)
else:
return(False)
################ first.py ###############
def power(x) :
'''This function power(x) is to take the
input and set it to the power of the
input'''
return ( x ** x)
def stringMultiply(myString, number) :
''' This function takes in an input string
and concatenates the string a specific
number of times. '''
#>>> stringMultiply('fernando', 3)
# 'fernandofernandofernando'
return (myString * number)
def listMaker(myString, number) :
''' This function takes in an input string
and number and returns new list with a
concatenated number of copies. '''
#>>> listMaker('hello fernando', 2)
#['hello fernando', 'hello fernando']
return ([myString] * number);
def countCodons (myDNAString) :
''' This function takes a DNA string as input
in multiples of 3, and then returns the
number of codons in that string. '''
#>>> countCodons("GCTGCTGCT")
#3.0
return (len(myDNAString) / 3)
def palindromeMaker(inputString) :
''' This function takes a string as input
and returns the string followed by its
reverse. It will work for any length
string. '''
#>>> palindromeMaker("fernando")
#'fernandoodnanref'
return (inputString + inputString[len(inputString) - 1: 0: -1] + inputString[0])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.