text
stringlengths 37
1.41M
|
---|
import re
import math
import time
import numpy as np
import matplotlib.pyplot as plt
#to hierarchical clustering with Eucledean distance.
#cluster distance is average distance
#agglomerative algorithm
#to implement a hierarchical cluster algorithm
#check if a point is in an list of points
def pointIn(p, ps):
result=False
for i in range(len(ps)):
if ps[i].index==p.index:
result=True
return result
#find the index of a poinnt in a list of list of points
#garranteed to be there
def getIndex(p,clusters):
index=0
for i in range(len(clusters)):
if pointIn(p,clusters[i]):
index=i
return index
#distance of 2 points
def distance(pa, pb):
#a and b are data points
d=0
data1=pa.data
data2=pb.data
for i in range(len(pa.data)):
d=d+ (data1[i]-data2[i])*(data1[i]-data2[i])
d=math.sqrt(d)
return d
#distance of 2 cluster of points
def nodeDistance(na, nb):
#use mean distance as meansure of distance between clusters
lena=len(na.points)
lenb=len(nb.points)
if lena==0 or lenb==0:
return 0
dist=0
for i in range(lena):
for j in range(lenb):
dist=dist+distance(na.points[i],nb.points[j])
dist=dist/(lena*lenb)
return dist
#represents a data point
class Point():
def __init__(self, index, data, label):
self.index=index #as a indexing id for data point
self.data=data
self.label=label
#represents a clustering node
class Node():
def __init__(self,points,step):
self.points=points #a list of datapoints
self.step=step
self.edges=[]
#class to do hierarchial clustering
class HierarchyCluster():
def __init__(self):
#self.nodes=[]
clusters=[] #current nodes during calculation
self.allpoints=[] #holds all data points
self.givenClusters=[] #calculate based on label
for i in range(4):
self.givenClusters.append([])
data=readData()
dimension=len(data[0])-1
print("the dimension of data is")
print(dimension)
for i in range(len(data)):
if np.random.rand()<=0.01: #randomly get about 400 samples
p=Point(i,data[i][1:],data[i][0])
self.allpoints.append(p)
self.givenClusters[int(data[i][0])-1].append(p)
n=Node([p],len(data))
clusters.append(n)
#inittiating clusters with single nodes.
#building the hierarchical tree
length=len(clusters)
print("initial length "+str(length))
self.alldistance=np.zeros((length,length))
for i in range(length):
for j in range(length):
self.alldistance[i][j]=distance(clusters[i].points[0],clusters[j].points[0])
while length>1:
minavd=nodeDistance(clusters[0],clusters[1])
indexa=0
indexb=1
for i in range(length-1):
for j in range(i+1,length):
#print(j)
d=nodeDistance(clusters[i],clusters[j])
#print(d)
if d < minavd:
minavd=d
indexa=i
indexb=j
#print("loop")
n1=clusters.pop(indexa)
n2=clusters.pop(indexb-1)
#clusters[i].points=n1.points+n2.points
nodet=Node(n1.points+n2.points,length)
self.connect(nodet,n1)
self.connect(nodet,n2)
#print("node has edges "+ str(len(nodet.edges)))
clusters.append(nodet)
length=length-1
print("current length "+str(length))
self.root=clusters[0]
def connect(self, nodea,nodeb):
nodea.edges.append(nodeb)
#from the hierarchical clustering generate clusters given the number of groups
def generateClusters(self,groupnumber):
resultnodes=[self.root]
while len(resultnodes) < groupnumber:
minstep=10000
minindex=0
for i in range(len(resultnodes)):
if resultnodes[i].step<minstep:
minstep=resultnodes[i].step
minindex=i
n=resultnodes.pop(minindex)
for i in range(len(n.edges)):
resultnodes.append(n.edges[i])
result=[]
for i in range(len(resultnodes)):
result.append(resultnodes[i].points)
print(len(resultnodes[i].points))
return result
#n is the number of clusters
#calculate Rand Index
def randIndex(self,clusters):
print("cluster has "+str(len(clusters)))
print("given clusters has "+str(len(self.givenClusters)))
c2=self.givenClusters
l=len(self.allpoints)
count=0
for i in range(l-1):
for j in range(i+1,l):
i1=getIndex(self.allpoints[i], c2)
i2=getIndex(self.allpoints[i],clusters)
j1=getIndex(self.allpoints[j],c2)
j2=getIndex(self.allpoints[j],clusters)
if i1==j1 and i2==j2:
count=count+1
if i1!=j1 and i2!=j2:
count=count+1
#print( str(i1)+" "+str(j1)+ " "+str(i2)+" "+str(j2))
return 2*count/(l * l-1)
def readData():
data=[]
with open('data.txt', newline='') as csvfile:
for line in csvfile:
sp=re.split(" +",line)
p=[]
for i in range(len(sp)-1):
p.append(float(sp[i+1]))
data.append(p)
return data
def main():
#the executing body
g=HierarchyCluster()
ris=[]
for i in range(2,10):
c1=g.generateClusters(i)
ri=g.randIndex(c1)
ris.append(ri)
plt.plot(range(2,10), ris)
plt.title('cluster number vs Rand Index')
plt.xlabel('cluster number')
plt.ylabel('Rand Index')
plt.grid(True)
plt.show()
if __name__=='__main__':
main()
|
#primeiro exemplo de funรงรตes
def meuverso(palavras):
print(palavras)
print(palavras)
print(gato)
def gato_duplo (parte1, parte2):
gato = parte1 + parte2
meuverso (gato)
linha1= "miau"
linha2= "grrr miau"
gato_duplo(linha1,linha2)
|
def gradient_descent(formula, init, epoch, lr, delta=1e-8):
"""formula: f(1), f(2), f(3)
w: the weight of init
epoch: the epoch for iterations
lr: the step"""
for i in range(epoch):
f1 = formula(init - delta)
f2 = formula(init + delta)
g = (f2 - f1) / (2 * delta)
init -= g * lr
return init
def f(x):
return (x+3)**2+5
w = gradient_descent(f, 3, 1000, 0.1)
print(w)
|
#-*-coding=utf-8-*-
import os
my_name = 'zeb'
my_height = 78
my_age = 19
my_eyes = 'Blue'
print(f"Let's talk about {my_name}.")
tatal = my_age * 3
print(f"if i {my_name} and age is {my_age}")
types_of_people = 10
x = f"there are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"those who know {binary} adnd those who {do_not}."
print(x)
print(f"I said: {y}")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious))
print(x + y)
print("." * 20)
print("its fleece was white as {}".format("snow"))
print("this end changed", end=' ')
print("see")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-19 17:26:31
# @Author : ZubinGou ([email protected])
# @Link : https://github.com/ZubinGou
# @Version : $Id$
import os
# 1
def make_inc(n):
return lambda x: x + n
f = make_inc(98)
print(f(99))
print(f(0))
# 2
sum = lambda a, b, c: a + b + c
print(sum(23,23,1))
# 3
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda x: x[1])
print(pairs)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-20 17:42:06
# @Author : ZubinGou ([email protected])
# @Link : https://github.com/ZubinGou
# @Version : $Id$
import os
the_count = list(range(1, 6))
print(the_count)
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
for num in the_count:
print(f"this is count {num}")
for fruit in fruits:
print(f"A fruits of type: {fruit}")
elements = []
for i in range(0, 6):
print(f"Adding {i} to the list.")
elements.append(i)
for i in elements:
print(f"Element was: {i}")
|
#!/usr/bin/env python
import os, sys
fb = open('input.txt', 'r')
text = fb.read().split('\n')[:-1]
# print(text)
def run_file(text):
i = 0
acc = 0
lines = []
while(i < len(text)):
if i in lines:
# print("infinite loop detected!")
return
else:
lines.append(i)
#print("i: ", i, "\nacc: ", acc)
action = text[i][:3]
value = int(text[i][4:])
if action == "nop":
pass
elif action == "acc":
acc = acc + value
elif action == "jmp":
i = i + value
continue
i = i + 1
print("i: ", i, ", acc: ", acc)
run_file(text)
for j in range(len(text[:])):
text2 = text[:]
# print(text2[j])
if text2[j][:3] == "jmp":
text2[j] = text2[j].replace("jmp", "nop")
elif text2[j][:3] == "nop":
text2[j] = text2[j].replace("nop", "jmp")
# print(text2[j])
run_file(text2)
|
# Process:
# Import necessary libraries
# Get spreadsheet location and name
# Store values in variables
# Make the input text of the name of the stock uppercase
# Present a small menu which will allow to either edit, add, or view
# Create functions for each with proper logic
import openpyxl
import os
from openpyxl import workbook
from openpyxl import load_workbook
def setup():
directory = "C:\\Users\\shrey\\Desktop"
directory = directory.lower()
os.chdir(directory)
spreadname = "Stocks.xlsx"
workbook = openpyxl.load_workbook(spreadname)
""" sheet_Arr = workbook.sheetnames
answer = ''
sheetname = ''
while answer != 'Y':
for x in sheet_Arr:
answer = input(x + ": Is this the sheetname which you are trying to access? (Y/N) ")
answer = answer.upper()
if (answer == 'Y'):
sheetname = sheet_Arr[0]
break
print(sheetname)
choose(sheet, workbook) """
sheet = workbook["Sheet1"]
return sheet
def showStock(stockName):
sheet = setup()
stockName = stockName.upper()
stockRow = 0
toReturn = ''
for i in range(1, sheet.max_row + 1):
if sheet.cell(row=i, column = 2).value == stockName:
stockRow = i
toReturn += '\n'
toReturn += "Here is the info for " + str(stockName) + ":" + '\n'
for i in range(1, sheet.max_column + 1):
if i == 8 or i == 3 or i == 2 or i == 1:
toReturn += str(i) + ": " + sheet.cell(row = 1, column = i).value + ": " + str(sheet.cell(row = stockRow, column = i).value)
else:
toReturn += str(i) + ": " + sheet.cell(row = 1, column = i).value + ": " + str(float((sheet.cell(row = stockRow, column = i).value)))
toReturn += '\n'
return toReturn
def showCurrentStocks() -> str:
sheet = setup()
toReturn = ''
toReturn += "Here is a current list of your stocks: " + '\n'
for i in range(2, sheet.max_row + 1):
toReturn += "Investment Name: " + str(sheet.cell(row = i, column = 1).value) + '\n' + "Stock Symbol: " + str(sheet.cell(row = i, column = 2).value)
toReturn += '\n'
return toReturn
def getStockRow(stock):
sheet = setup()
stockRow = 1
for i in range(1, sheet.max_row + 1):
if sheet.cell(row=i, column = 2).value == stock:
stockRow = i
return stockRow
def editStock(choice, stockSymbol, edit):
directory = "C:\\Users\\shrey\\Desktop"
directory = directory.lower()
os.chdir(directory)
spreadname = "Stocks.xlsx"
workbook = openpyxl.load_workbook(spreadname)
sheet = workbook["Sheet1"]
stockRow = getStockRow(stockSymbol)
if choice == 7 or choice == 2 or choice == 3 or choice == 1:
sheet.cell(row = stockRow, column = choice).value = edit
else:
sheet.cell(row = stockRow, column = choice).value = float(edit)
workbook.save("Stocks.xlsx")
def addStock(sheet, workbook):
line = sheet.max_row + 1
for i in range(1, sheet.max_column + 1):
if i == 7 or i == 2 or i == 1:
add = input(sheet.cell(row = 1, column = i).value + ": ")
sheet.cell(row = line, column = i).value = add
else:
add = input(sheet.cell(row = 1, column = i).value + ": ")
sheet.cell(row = line, column = i).value = float(add)
directory = "C:\\Users\\shrey\\Desktop"
directory = directory.lower()
os.chdir(directory)
workbook.save("Stocks.xlsx")
def main():
answer = 'Y'
while answer == 'Y':
setup()
answer = input("Continue? (Y/N) ")
if __name__ == "__main__":
main()
|
from __future__ import print_function
import sys
#class for the parsed instructions, add type, target for extra fuinctionality
class instruction3ac :
def __init__(self, no, type, in1, in2, out) :
if type == 'cmp': debug(in1=in1,in2=in2,out=out)
self.no, self.type, self.in1, self.in2, self.out = no, type, in1, in2, out
def __str__(self) :
return "Instruction No :{},Instruction Type :{}".format(self.no,self.type)
def __repr__(self) :
return "\n{}. {} {} {} {} ".format(self.no,self.out, self.type, self.in1, self.in2)
#raw is a list of the parsed instructions
#block is a list of instructions corresdonding to a basic block
#TODO : a block generator, which builds the global data structures block, symtable and clears address and register descriptors
raw = []
block = []
#vset[] is a set of all the variables of the program. To be used in the .data section
vset = set()
stringMap = {}
arrayset = {}
#rset is a list of all the general purpose registers
rset = ['eax', 'ebx', 'ecx', 'edx']
#symtable[] is a list st symtable[instruction_no.]<var : nextuse>. nextuse = INF means that the variable is dead
symtable = []
#address descriptor adesc{} is a dictionary st adesc[var] = Register containing var.
# note that each variable will be contained in atmost 1 register. adesc[var] == None implies that no register contains var
# and thus var should be present in memory
adesc = {}
curr_scope = ""
#For keeping count of Number of function temps and arguments.
num_var = dict()
num_arg = dict()
#For mapping local variables and function arguments to the correct stack pointer
memmap = dict()
globmap = set()
#register descriptor rdesc{} is a dictionary st rdesc[reg] = var st reg currently holds the correct value of the "live" variable
#var. Note that a register can contain atmost 1 variable. rdesc[reg] = None implies that the register is free.
rdesc = {}
#list of string to store the output of the block
out = []
#Total number of instructions, the registers zprime, yprime and L used in register allocation
numins = 0
zprime = None
yprime = None
L = None
debug_flag = 0
def print_symbol_table() :
if debug_flag :
s = [[str(e) for e in row.values()] for row in symtable]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = ' '.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print('-'*(sum(lens)+len(lens)*2)+'|',file = sys.stderr)
print(fmt.format(*adesc),'|',file = sys.stderr)
print('-'*(sum(lens)+len(lens)*2)+'|',file = sys.stderr)
print(' |\n'.join(table),' |',file = sys.stderr)
def debug(*arg,**kwarg) :
if debug_flag :
print('\033[91m',file = sys.stderr)
for a in arg :
print(a,end=', ', file = sys.stderr)
for k,v in kwarg.items() :
print(k,'=',v,end=', ', file = sys.stderr)
print('\033[0m', file = sys.stderr)
|
myList = ['Sofia','carlos','mauricio','Rafa','Fabian','Beatriz','Pablo','Edgar','Santiago']
myList2 = ['Pepe','lepu']
#size = len(myList)
#print(myList)
#myList.sort(reverse=True,key=len)
#print(sorted(myList))s
#print(myList.pop(0))
#print(myList[3:9])
#myList.append('Renato')
#print(myList)
#myList.remove('Beatriz')
#print(myList)
#myList.extend(myList2)
#print(myList)
print([*myList,*myList2])
#cmd + alt nos ayuda a agrrar varias cosas t con |
#message = input("introduce un mensaje")
#print("This is the message:" , message)
'''eset es un comentario
de mas de una linea
waoooooo
'''
'''
number1 =int (input('give me the first number'))
number2 = int (input('give me the second number'))
_sum = number1 + number2
if _sum == 10:
print('okay u got ten')
elif _sum > 10:
print ('u got more than ten')
else:
print('is not ten')
'''
while True:
try:
numero1 = int(input('give me some value'))
numero2 = int(input('give me the second value'))
_sum = numero1 + numero2
if _sum == 10:
print('si es igual a 10')
break
elif _sum > 10:
print('es mayor a 10')
else:
print('What =(')
except ValueError:
print('Esto esta mal no sumo strings')
break
|
from board import Board
from game_tile import GameTile
class GameBoard(Board):
def __init__(self, width, height, num_mines):
super().__init__(width, height, num_mines)
self.total_selections = 0
self.mine_selected = False
def add_tiles_to_board(self):
for i in range(self.height):
row = []
for j in range(self.width):
row.append(GameTile((i,j)))
self.board.append(row)
def select(self, game_tile):
'''
Selects given tile if it is selectable, if the tile
is blank recursively select all of its neighbours
'''
if self.total_selections == 0:
self.add_mines(game_tile)
if game_tile.is_selected() or game_tile.is_flagged():
return
self.total_selections += 1
game_tile._is_selected = True
if game_tile.is_mine():
self.mine_selected = True
# if selected tile is blank, recurse over its blank neighbours.
if game_tile.is_blank():
for neighbour_tile in self.get_neighbours(game_tile):
if neighbour_tile.is_blank():
self.select(neighbour_tile)
def flag(self, game_tile):
"""
Flags/deflags at the given coordinate
"""
# deflag
if game_tile.is_flagged():
game_tile._is_flagged = False
# flag
else:
game_tile._is_flagged = True
def game_over(self):
return self.game_won() is True or self.game_lost() is True
def game_won(self):
return self.width * self.height - self.num_mines == self.total_selections
def game_lost(self):
return self.mine_selected |
# Program to display the Fibonacci sequence up to n-th term
nSequence = int(input("How many sequences do you wish to complete? "))
# first two numbers in the sequence
num1, num2 = 0, 1
# initializing a counter
count = 0
# check if the number of squences is valid
if nSequence <= 0:
print("Please enter a positive integer.")
elif nSequence == 1:
print("Fibonacci sequence up to",nSequence,":")
print(num1)
else:
print("Fibonacci sequence:")
while count < nSequence:
print(num1)
nth = num1 + num2
# update values
num1 = num2
num2 = nth
count += 1 |
"""่พๅ
ฅไธไธชๆดๆฐ k (k < 50), ่พๅบไธไธช k*k ็ไนๅฎซๅพใ
็คบไพ๏ผ
5*5
17 24 01 08 15
23 05 07 14 16
04 06 13 20 22
10 12 19 21 03
11 18 25 02 09
"""
import random
def exch(arr, a, b):
tamp = arr[a]
arr[a] = arr[b]
arr[b] = tamp
def shuffle(arr):
"""Rearrange array so that result is a uniformly random permutation.
Args:
arr: A list instance.
"""
for i in range(len(arr)):
r = random.randrange(i + 1)
exch(arr, i, r)
# creat the asked array and shuffle it
x = int(input())
arr = list(range(1, x * x + 1))
shuffle(arr)
# print the number graph
width = len(str(x * x))
for i in range(x * x):
if i % x == 0:
print('\n')
print('%0*d' % (width, arr[i]), end=" ")
|
#*****Funciones 7*****
print('\nFunciones Ejercicio # 07\n')
def calcularpresupuesto(presupuesto):
presu_ginecologia = presupuesto * 0.40
presu_traumatologia = presupuesto * 0.30
presu_padiatria = presupuesto * 0.30
return presu_ginecologia, presu_traumatologia, presu_padiatria
presupuesto = float(input(('Ingrese el presupuesto anual de todas las รกreas-->ยข ')))
x, y, z = calcularpresupuesto(presupuesto)
print(f'El presupuesto anual asignado es de ยข{presupuesto}. Para Ginecologรญa el presupuesto es de ยข{x}. Para Traumatologรญa el presupuesto es de ยข{y}. Para Padiatrรญa el presupuesto es de ยข{z}')
|
#*****Funciones 4*****
print('\nFunciones Ejercicio # 04\n')
def preciofinal (precio):
precio = precio * (1+0.30)
return precio
costo = float(input(('Ingrese el costo del artรญculo-->ยข')))
resultado = preciofinal(costo)
print(f'\nLa tienda compra el artรญculo a ยข{costo} y lo vende a ยข{resultado}')
|
class Node:
def __init__(self, label, *children):
self.label = label
self.children = children
def __str__(self):
chstr = [str(i) for i in self.children]
chstr = ', '.join(chstr)
return "Node {}: [{}]".format(self.label, chstr)
class Leaf:
def __init__(self, label, val):
self.label = label
self.val = val
def __str__(self):
return "Leaf {}: {}".format(self.label, self.val)
def main():
# syntax tree for 5 + 7
l1 = Leaf('NUM', 5)
l2 = Leaf('+', '+')
l3 = Leaf('NUM', 7)
expr = Node('expr', l1, l2, l3)
print 'done.'
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
# This program is an example for running a motor at a set power value.
# The motor will turn with a constant torque, at whatever RPM allows it.
#
# Created by the Purdue ENGR 16X teaching team
# Contact a TA if you have any questions regarding this program.
#
# Hardware: Connect EV3 or NXT motors to the BrickPi3 motor port A.
# Make sure that the BrickPi3 is running on a 12v power supply.
#
# Results: When you run this program, motor A will run at the
# specified power.
#
# Syntax: BP.set_motor_dps(<PORT>, <VALUE>)
# Sets motor in port <PORT> to the degrees-per-second value <VALUE>
# The motor will apply whatever torque is required to keep this
# rotational valocity. There is an upper limit, but it could be
# different based on input voltage and motor type.
import time #library for sleep function
import brickpi3 #library for BrickPi dependencies
BP = brickpi3.BrickPi3() #creating a BP object
MOTOR = BP.PORT_A #defining the motor port to be used, motor should be plugged into the
#corresponding port on the BrickPi
try:
print('Enter desired speed for motor A in degrees/sec.\nCtrl+C to terminate program.\n')
while True:
dps = float(input('Enter desired speed: ')) #get dps from user input
BP.set_motor_dps(MOTOR, dps) #sets motor to dps input
print('Current speed is {:.4f} degrees/sec'.format(dps))
time.sleep(0.02)
except KeyboardInterrupt: #ctrl+c will trigger the program to terminate
# Stop all motors, reset all sensors, and return LED control to the firmware.
BP.reset_all()
|
from pprint import pprint
class Player():
def __init__(self, name, card1, card2, bank, dealer=False):
self.cards = [card1, card2]
self.name = name
self.bank = bank
self.dealer = dealer
self.score = self.__calculate_cards_value__()
if (dealer):
self.cards[0].secret = True
def reset_cards(self, card1, card2):
self.cards = [card1, card2]
self.score = self.__calculate_cards_value__()
def lose_bet(self, amount):
self.bank -= amount
def win_bet(self, amount):
self.bank +=amount
def can_place_bet(self,amount):
if amount > self.bank:
print("lol, you can't bet more than you have")
return False
return True
def add_card(self, card):
self.cards.append(card)
self.score = self.__calculate_cards_value__()
if self.score == 0:
print(f"{self.name} busted!")
def __calculate_cards_value__(self):
"""
Calculates values for players cards
Set value to 0, if hand is bust
"""
score = 0
aces = False
# first treat all aces as 1 and track if any of the cards is ace
# then if aces found -> try to return sum + 10 (as only one ace in hand could be 11)
# if that is > thatn 21, try to return sum where all aces are 1
# if that is > 21, then player is bust
for card in self.cards:
# first try to convert value to int
try:
score += int(card.rank)
except ValueError:
# card is some high rank card
if card.rank in ['jack','queen','king']:
score += 10
else:
# ace found
aces = True
score += 1
if aces:
if score+10 <= 21:
return score+10
elif score <= 21:
return score
else:
return 0
elif score <= 21:
return score
else:
return 0
def get_cards_value(self):
return self.score
def print_cards(self):
print(f"{self.name} cards:")
pprint(self.cards)
|
# Filename: wall_area_of_room2
# Created by: jasongreen
# Date: Saturday, January 12, 2019
# Time of Creation: 12:07
# ---
# calculate wall area of room NOT
# including two windows and a door
# I'm sure I could do this in an array, but don't know how.
room_perimeter = int(input("Please enter the room's perimeter: "))
room_Height = int(input("Please enter the room height: "))
window_one_height = int(input("Please enter the height of Window #1: "))
window_one_width = int(input("Please enter the width of Window #1: "))
window_two_height = int(input("Please enter the height of Window #2: "))
window_two_width = int(input("Please enter the width of Window #2: "))
door_height = int(input("Please enter the door height: "))
door_width = int(input("Please enter the door width: "))
window_one_area = window_one_width * window_one_height
window_two_area = window_two_width * window_two_height
door_area = door_width * door_height
room_Wall_Area_noWindow_noDoor = ((room_perimeter * room_Height) -
((window_one_area +
window_two_area +
door_area)))
print("The wall area of the room without doors and windows is: {0} square feet.".format(room_Wall_Area_noWindow_noDoor)) |
import sys
def get_fuel(mass):
"""
Fuel required to launch a given module is based on its mass.
Specifically, to find the fuel required for a module, take its mass,
divide by three, round down, and subtract 2.
For example:
For a mass of 12, divide by 3 and round down to get 4,
then subtract 2 to get 2.
>>> get_fuel(12)
2
For a mass of 14, dividing by 3 and rounding down still yields 4,
so the fuel required is also 2.
>>> get_fuel(14)
2
For a mass of 1969, the fuel required is 654.
>>> get_fuel(1969)
654
For a mass of 100756, the fuel required is 33583.
>>> get_fuel(100756)
33583
"""
return int(mass / 3) - 2
def main(input_file):
total = 0
for line in input_file:
total += get_fuel(int(line))
print(total)
if __name__ == '__main__':
main(sys.stdin)
|
#this script adds course entries to the classes_for_prototype.csv file
#so that we can have some discussion sections in our test data
import random
import csv
courses_input = []
with open("intermediate_data_file.csv", "rU") as data:
reader = csv.reader(data)
for row in reader:
#print(row)
courses_input.append(row)
#print(courses_input)
courses_output = []
# 0: IDENT_DIV 1: IDENT_SUFX_CD 2: xlisting 3: DEPARTMENT 4: CRS_TITLE 5: credit
# 6: CRS_DESCRIPTION 7: FORMAT 8: FINALEXAMSTATUS 9: PREREQS 10: CR_RESTRICT
# 11: AC 12: AL 13: BS 14: HS 15: IS 16: PV 17: PS 18: SS 19: RCA 20: RCB 21: pubHealthMaj 22: type
for item in courses_input:
#choose which courses will have current instances
if random.randint(0,1) == 1:
item[23] = "Y"
if random.randint(0, 3) == 3:
item[24] = "Y"
courses_output.append(item)
with open("courses_for_prototype.csv", "wb") as data:
writer = csv.writer(data)
writer.writerows(courses_output) |
# -*- coding: utf-8 -*-
import random
import string
import sys
notPrintable = {'๐พ', '๐ฟ', '๐', '๐', '๐', '๐', '๐', '๐
', '๐', '๐', '๐', '๐จ', '๐ฉ', '๐ช', '๐ซ', '๐ฌ', '๐ญ', '๐ฎ','๐พ'}
viableCharacters = [chr(i) for i in range(0x1F300, 0x1F578) if chr(i)
not in notPrintable]
viableCharacters += [chr(i) for i in range(0x1F5ff, 0x1F649) if chr(i) not
in notPrintable]
print(viableCharacters)
englishSymbols = string.ascii_letters + string.digits
sentence = input("Enter Sentence to encode ")
filename = input("Enter filename to write to ")
f = input("Should capitals also be encoded? (y or n) ")
while f not in "yn":
print("Please type y or n")
f = input(">> ")
if "n" == f[0]:
englishSymbols =englishSymbols.replace(string.ascii_uppercase, "")
f = input("Should digits also be encoded? (y or n) ")
while f not in "yn":
print("Please type y or n")
f = input(">> ")
if "n" == f[0]:
englishSymbols =englishSymbols.replace(string.digits, "")
while True:
mapping = {}
for symbol in englishSymbols:
mapping[symbol] = random.choice(viableCharacters)
finalString = ""
for key in mapping:
finalString += key + "\t" + mapping[key]
finalString += "\n"
finalString += "\n"
finalString += sentence
finalString += "\n"
for letter in sentence:
if letter in englishSymbols:
letter = mapping[letter]
finalString += letter
print(finalString)
fileToWrite = open(filename, "w")
fileToWrite.write(finalString)
fileToWrite.close()
y = input("is this a good encoding? press y to exit")
if (y == "y"):
break
|
# As an exercise , add a method __sub__(self, other) that overloads the subtraction operator, and try it out.
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __sub__(self, other):
return self.x - other.x, self.y - other.y
p = Point()
p1 = Point(2, 4)
p2 = Point(4, 6)
print(p1-p2)
|
import numpy as np
from helper import *
def sigmoid(x):
# Sigmoid activation function: f(x) = 1 / (1 + e^(-x))
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
# Derivative of sigmoid: f'(x) = f(x) * (1 - f(x))
fx = sigmoid(x)
return fx * (1 - fx)
def relu(x):
# Relu function: f(x) = x (x>0), f(x)=0 (x<=0)
return x * (x > 0)
def relu_derivative(x):
# Derivative of Relu: f(x) = 1 (x>0), f(x)=0 (x<=0)
return 1 * (x > 0)
class NeuralNetwork:
def __init__(self, x, y, layer_size, lr=0.1, final_lr=0.001, n_epochs=10, batch_size=1, learning_rate_decay=0.95):
self.input = x
self.output = y
self.lr = lr
self.n_epochs = n_epochs
self.batch_size = batch_size
self.layer_size = layer_size
self.n_layers = len(self.layer_size)-1
self.learning_rate_decay = learning_rate_decay
self.step_num = find_step_num(lr, final_lr, learning_rate_decay, n_epochs)
self.weight = []
self.bias = []
### initial weight and bias for each layer
for i in range(0, self.n_layers):
self.weight.append(np.random.normal(size=(self.layer_size[i], self.layer_size[i+1])))
self.bias.append(np.random.normal(size=(1, self.layer_size[i+1])))
### propagate the input from the first layer to last layer
##### ReLu as activation function for hidden layer
##### Sigmoid as activation function for the last layer
def forward(self, x):
self.layers = []
self.layers.append(x)
for i in range(self.n_layers):
z_output = np.dot(self.layers[i], self.weight[i]) + self.bias[i]
if i < self.n_layers - 1:
output = relu(z_output)
else:
output = sigmoid(z_output)
self.layers.append(output)
return self.layers
### loss function: MSE
def mse(self, y_true, y_pred):
return np.mean(np.power(y_true - y_pred, 2))
### backpropagation: calculate the gradient and update the weights
def back_propagation(self, y):
self.grad_list = []
d_output = (self.layers[-1] - y) * sigmoid_derivative(self.layers[-1])
self.grad_list.append(d_output)
for i in range(self.n_layers-1, 0, -1):
delta = np.dot(self.grad_list[-1], self.weight[i].T) * relu_derivative(self.layers[i])
self.grad_list.append(delta)
self.grad_list.reverse()
for i in range(len(self.grad_list)):
d_weight = np.dot(self.layers[i].T, self.grad_list[i])
d_bias = self.grad_list[i]
self.weight[i] -= d_weight * self.lr
self.bias[i] -= d_bias * self.lr
error = self.mse(self.layers[-1], y)
return error
### training function
def train(self, x_train, y_train):
losses = []
for epoch in range(self.n_epochs):
error = 0
for x, y in zip(x_train, y_train):
self.forward(x.reshape(1, len(x)))
error += self.back_propagation(y.reshape(1, len(y)))
if epoch % self.step_num == 0:
# Decay learning rate
self.lr *= self.learning_rate_decay
error /= len(x_train)
print(f'epoch{epoch} - error:{error}')
losses.append(error)
return losses
### predict the output with the input
def predict(self, input):
output_list = self.forward(input)
return output_list[-1]
# Calculate accuracy percentage
def accuracy_metric(self, y_true, y_pred):
correct = 0
for i in range(len(y_true)):
if y_true[i] == y_pred[i]:
correct += 1
return correct / float(len(y_true)) * 100.0 |
import sys
def reverse_word(word):
reversed_word = []
''' turn the string into list '''
array = list(word)
''' reverse by getting the index of the last character to the first'''
index = len(word)-1
while index >= 0:
reversed_word.append(array[index])
index -= 1
return reversed_word
''' join the list into string'''
def print_reversed(reverse_words):
word = "".join(reverse_words)
print(word)
if __name__=="__main__":
word = sys.argv[1]
print_reversed(reverse_word(word))
|
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 16:19:56 2020
@author: vidhy"""
#---------------------------------------The knapsack problem---------------------------------------------------
import numpy as np
import pandas as pd
import random as rd
from random import randint
import matplotlib.pyplot as plt
item_number = np.arange(1,9)
#weight of rice bag
weight = [2,4,5,6,8,15,17,20]
#respective price
value = [5,11,15,30,26,35,40,50]
knapsack_threshold = 50 #Maximum weight that the bag of rice can hold
print('The list is as follows:')
print('Item No. Weight Value')
for i in range(item_number.shape[0]):
print('{0} {1} {2}\n'.format(item_number[i], weight[i], value[i]))
#declare the initial population
solutions_per_pop = 8
pop_size = (solutions_per_pop, item_number.shape[0])
print('Population size = {}'.format(pop_size))
initial_population = np.random.randint(2, size = pop_size)
initial_population = initial_population.astype(int)
num_generations = 50
print('Initial population: \n{}'.format(initial_population))
#fitness function
def cal_fitness(weight, value, population, threshold):
fitness = np.empty(population.shape[0])
for i in range(population.shape[0]):
S1 = np.sum(population[i] * value)
S2 = np.sum(population[i] * weight)
if S2 <= threshold:
fitness[i] = S1
else :
fitness[i] = 0
return fitness.astype(int)
#crossover function
def selection(fitness, num_parents, population):
fitness = list(fitness)
parents = np.empty((num_parents, population.shape[1]))
for i in range(num_parents):
max_fitness_idx = np.where(fitness == np.max(fitness))
parents[i,:] = population[max_fitness_idx[0][0], :]
fitness[max_fitness_idx[0][0]] = -999999
return parents
#For crossover we will be using one-point crossover
def crossover(parents, num_offsprings):
offsprings = np.empty((num_offsprings, parents.shape[1]))
crossover_point = int(parents.shape[1]/2)
crossover_rate = 0.8
i=0
while (parents.shape[0] < num_offsprings):
parent1_index = i%parents.shape[0]
parent2_index = (i+1)%parents.shape[0]
x = rd.random()
if x > crossover_rate:
continue
parent1_index = i%parents.shape[0]
parent2_index = (i+1)%parents.shape[0]
offsprings[i,0:crossover_point] = parents[parent1_index,0:crossover_point]
offsprings[i,crossover_point:] = parents[parent2_index,crossover_point:]
i=+1
return offsprings
#In Mutation, which chromosome will undergo mutation is being done randomly.
# For creating mutants we will be using bit-flip technique i.e. if the selected gene which is going to undergo mutation is 1 then change it to 0 and vice-versa.
def mutation(offsprings):
mutants = np.empty((offsprings.shape))
mutation_rate = 0.4
for i in range(mutants.shape[0]):
random_value = rd.random()
mutants[i,:] = offsprings[i,:]
if random_value > mutation_rate:
continue
int_random_value = randint(0,offsprings.shape[1]-1)
if mutants[i,int_random_value] == 0 :
mutants[i,int_random_value] = 1
else :
mutants[i,int_random_value] = 0
return mutants
def optimize(weight, value, population, pop_size, num_generations, threshold):
parameters, fitness_history = [], []
num_parents = int(pop_size[0]/2)
num_offsprings = pop_size[0] - num_parents
for i in range(num_generations):
fitness = cal_fitness(weight, value, population, threshold)
fitness_history.append(fitness)
parents = selection(fitness, num_parents, population)
offsprings = crossover(parents, num_offsprings)
mutants = mutation(offsprings)
population[0:parents.shape[0], :] = parents
population[parents.shape[0]:, :] = mutants
print('Last generation: \n{}\n'.format(population))
fitness_last_gen = cal_fitness(weight, value, population, threshold)
print('Fitness of the last generation: \n{}\n'.format(fitness_last_gen))
max_fitness = np.where(fitness_last_gen == np.max(fitness_last_gen))
parameters.append(population[max_fitness[0][0],:])
return parameters, fitness_history
#The corresponding items of the parameters in the item_number array will be the ones that the rice will take to fit in 50kg bag.
parameters, fitness_history = optimize(weight, value, initial_population, pop_size, num_generations, knapsack_threshold)
print('The optimized parameters for the given inputs are: \n{}'.format(parameters))
selected_items = item_number * parameters
print('\nSelected items that will maximize the knapsack without breaking it:')
for i in range(selected_items.shape[1]):
if selected_items[0][i] != 0:
print('{}\n'.format(selected_items[0][i]))
|
from random import shuffle, randrange
from time import sleep
from structures import Tree, RBTreeNode
BLACK = RBTreeNode.BLACK
RED = RBTreeNode.RED
NIL = RBTreeNode.NIL
def tree_insert(tree, data):
node = RBTreeNode(data)
node.left = node.right = NIL
tree_insert_node(tree, node)
def tree_insert_node(tree, z):
x = tree.root
y = None
while x:
y = x
if z.data < x.data:
x = x.left
else:
x = x.right
z.parent = y
if not y:
tree.root = z
elif z.data < y.data:
y.left = z
else:
y.right = z
insert_case(tree, z)
def insert_case(tree, z):
# Initally, z.color is RED
#
# Case 1: z is root
if not z.parent:
# change z.color to BLACK
z.color = BLACK
return
# Case 2: z.parent.color is BLACK, OK
if z.parent.color == BLACK:
return
#
# Now, z.parent.color is RED, so z must have a grandparent.
# The colors of z and z.parent are both RED which is not allowed, we should deal with it.
#
# Case 3: z.uncle.color is RED
if z.uncle and z.uncle.color == RED:
# invert the colors of z.parent, z.uncle and z.grandparent
z.parent.color = BLACK
z.uncle.color = BLACK
z.grandparent.color = RED
# process z.grandparent
insert_case(tree, z.grandparent)
return
#
# Now, z has no uncle or z.uncle.color is BLACK
#
# Case 4:
if z == z.parent.right and z.parent == z.grandparent.left:
# exchange the role of z and z.parent
tree.rotate_left(z.parent)
z = z.left
# now, z == z.parent.left and z.parent == z.grandparent.left
# turn to Case 5.1
elif z == z.parent.left and z.parent == z.grandparent.right:
# exchange the role of z and z.parent
tree.rotate_right(z.parent)
z = z.right
# now, z == z.parent.right and z.parent == z.grandparent.right
# turn to Case 5.2
# Case 5:
# First, invert the colors of z.parent and z.grandparent
z.parent.color = BLACK
z.grandparent.color = RED
# Case 5.1:
if z == z.parent.left and z.parent == z.grandparent.left:
tree.rotate_right(z.grandparent)
# Case 5.2
else:
tree.rotate_left(z.grandparent)
def get_smallest_child(node):
x = node
while x.left:
x = x.left
return x
def tree_delete(tree, data):
z = tree_search(tree, data)
if z:
if z.right:
s = get_smallest_child(z.right)
z.data, s.data = s.data, z.data
z = s
tree_delete_one_child_node(tree, z)
return True
else:
return False
def tree_delete_one_child_node(tree, z):
child = z.left if z.left else z.right
if not z.parent and not child:
tree.root = None
return
if not z.parent:
child.parent = None
child.color = BLACK
tree.root = child
return
if z.parent.left == z:
z.parent.left = child
else:
z.parent.right = child
child.parent = z.parent
if z.color == BLACK:
if child.color == RED:
child.color = BLACK
else:
delete_case(tree, child)
def delete_case(tree, x):
#
# Initally, x.color is BLACK
#
# Case 1: x is root
if not x.parent:
return
# Case 2: x.sibling.color is RED
if x.sibling.color == RED:
# invert colors of x.parent and x.sibing
x.parent.color = RED
x.sibling.color = BLACK
# rotate
if x == x.parent.left:
tree.rotate_left(x.parent)
else:
tree.rotate_right(x.parent)
# turn to Case 4, 5, 6
s = x.sibling
# Case 3: x.parent, x.sibling and its childs are both BLACK
if x.parent.color == s.color == s.left.color == s.right.color == BLACK:
s.color = RED
delete_case(tree, x.parent)
return
# Case 4:
if x.parent.color == RED and s.color == s.left.color == s.right.color == BLACK:
s.color = RED
x.parent.color = BLACK
return
# Case 5:
if s.color == BLACK:
if x == x.parent.left and s.right.color == BLACK and s.left.color == RED:
s.color = RED
s.left.color = BLACK
tree.rotate_right(s)
elif x == x.parent.right and s.left.color == BLACK and s.right.color == RED:
s.color = RED
s.right.color = BLACK
tree.rotate_left(s)
# Case 6:
s = x.sibling
s.color = x.parent.color
x.parent.color = BLACK
if x == x.parent.left:
s.right.color = BLACK
tree.rotate_left(s.parent)
else:
s.left.color = BLACK
tree.rotate_right(s.parent)
def tree_build(tree, lst):
shuffle(lst)
for i in lst:
tree_insert(tree, i)
def tree_search(tree, data):
x = tree.root
while x and x.data != data:
if x.data > data:
x = x.left
else:
x = x.right
return x
tree = Tree()
tree.bind('x', 0x00ff00)
tree.bind('z', 0x0000ff)
N = 50
lst = [randrange(N) for _ in range(N)]
tree_build(tree, lst)
sleep(1)
for i in lst:
tree_delete(tree, i)
|
# MNIST handwritten digit recognition problem
# Simple NN with one hidden layer
# For plotting ad hoc MNIST instances
from keras.datasets import mnist
import matplotlib.pyplot as plt
# For NN
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
def show_data(X_train):
# Call within run() function
# Plot first 4 images of dataset as gray scale
plt.subplot(221)
plt.imshow(X_train[0], cmap=plt.get_cmap('gray'))
plt.subplot(222)
plt.imshow(X_train[1], cmap=plt.get_cmap('gray'))
plt.subplot(223)
plt.imshow(X_train[2], cmap=plt.get_cmap('gray'))
plt.subplot(224)
plt.imshow(X_train[3], cmap=plt.get_cmap('gray'))
# Show the plot
plt.show()
def baseline_model(num_pixels, num_classes):
# Create model
model = Sequential()
model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu'))
model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def run():
# Set seed for reproducibility
seed = 7
numpy.random.seed(seed)
# Load the MNIST dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Shape and flatten dataset array
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
# Normalise inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
# One hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
# Build the model
model = baseline_model(num_pixels, num_classes)
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Baseline error: %.2f%%" % (100-scores[1]*100))
# Run the script
run()
|
class BinarySearch(list):
def __init__(self, a, b, *args):
list.__init__(self, *args)
self.list_length = a
self.step = b
end = self.list_length * self.step
for i in range(self.step, end+1, self.step):
self.append(i)
@property
def length(self):
return len(self)
def search(self, value, start=0, end=None, count=0):
if not end:
end = self.length - 1
if value == self[start]:
return {'index': start, 'count': count}
elif value == self[end]:
return {'index': end, 'count': count}
mid = (start + end) // 2
if value == self[mid]:
return {'index': mid, 'count': count}
elif value > self[mid]:
start = mid + 1
elif value < self[mid]:
end = mid - 1
if start >= end:
return {'index': -1, 'count': count}
count += 1
return self.search(value, start, end, count) |
"""Scoring, analysing
This file includes functions to analyse the tweets and
give them scores.
"""
import re
import os
def get_words():
"""Get words
Returns a list with first a list of positive words
and second a list of negative words.
"""
# path to the directory including the word-files
dir_path = os.path.dirname(os.path.realpath(__file__)) + "\\src\\"
# reading in the positive and negative words as lists
pos_words = []
neg_words = []
with open(dir_path + "positive-words.txt") as positive, open(dir_path + "negative-words.txt") as negative:
for line in positive:
li = line.strip()
if not li.startswith(";"):
pos_words.append(line.rstrip())
for line in negative:
li = line.strip()
if not li.startswith(";"):
neg_words.append(line.rstrip())
return [pos_words, neg_words]
def scoring(tweets):
"""Scoring
Returns a dictionary containing the tweets as keys and the
scoring as their values.
"""
scored_tweets = {}
for tweet in tweets:
# removing unwanted parts
tweet = re.sub('https://', '', tweet)
tweet = re.sub('http://', '', tweet)
tweet = re.sub('[^[:graph:]]', ' ', tweet)
tweet = re.sub('[[:punct:]]', '', tweet)
tweet = re.sub('[[:cntrl:]]', '', tweet)
tweet = re.sub('\\d+', '', tweet)
tweet = re.sub('#', '', tweet)
tweet = re.sub('\u2026', '', tweet)
tweet = tweet.lower()
# split to a list of words
tweet_list = tweet.split()
# getting words for scoring
words = get_words()
pos_words = words[0]
neg_words = words[1]
# defining the score
pos_matches = 0
neg_matches = 0
for pos, neg in zip(pos_words, neg_words):
pos_matches += tweet_list.count(pos)
neg_matches += tweet_list.count(neg)
scored_tweets.update({tweet : pos_matches - neg_matches})
return scored_tweets
|
import zipfile
import shutil
f = open('fileone.txt', 'w+')
f.write('ONE FILE')
f.close
f = open('filetwo.txt', 'w+')
f.write('TWO FILE')
f.close
comp_file = zipfile.ZipFile('comp_file.zip', 'w')
comp_file.write('fileone.txt', compress_type = zipfile.ZIP_DEFLATED)
comp_file.write('filetwo.txt', compress_type = zipfile.ZIP_DEFLATED)
comp_file.close()
zip_obj = zipfile.ZipFile('comp_file.zip', 'r')
zip_obj.extractall('extracted_content')
dir_to_zip = '/home/tmorris24/Python/exercises/extracted_content'
output_filename = 'example'
shutil.make_archive(output_filename, 'zip', dir_to_zip)
shutil.unpack_archive('example.zip', 'final_unzip', 'zip')
|
import deck
import card
import hand
def black_jack():
deck1 = deck.Deck()
balance = 1000
print("Welcome to Black Jack!\n")
while True:
win = 0
playerturn = 0
dealerturn = 0
print(f"Current Balance: ${balance}")
if balance <= 0:
print("You are out of money! Goodbye!")
break
play = input("Would you like to place a bet? Please enter Yes to play.\
\nEnter any other input to quit\n\n")
if play == "Yes" or play == "yes" or play == "y":
pass
else:
print(f"Goodbye! Your final balance is: ${balance}")
break
print(f"\nPlease enter a bet!\nCurrent Balance: ${balance}")
bet = 0
while bet <= 0 or bet > balance:
try:
bet = int(input("Enter a bet: $"))
except:
bet = -1
if bet <= balance and bet > 0:
pass
else:
print(f"\nPlease enter a valid bet!\n\nCurrent Balance: ${balance}")
print(f"Bet Placed!: ${bet}\n")
print("Let's Play!\n")
playerhand = hand.Hand(deck1)
dealerhand = hand.Hand(deck1)
while win == 0:
print(f"Dealer is showing a {dealerhand.hand[-1].rank} of {dealerhand.hand[-1].suit}\n")
while playerturn == 0:
print("Player Hand:")
for i, val in enumerate(playerhand.hand):
print(f"{playerhand.hand[i].rank} of {playerhand.hand[i].suit}")
print(f"Player has {playerhand.total()}\n")
move = input("Would you like to hit or stay?: ")
if move == "Hit" or move == "hit":
playerhand.hit(deck1)
if playerhand.total() > 21:
print("Player Busts!\n")
win = -1
playerturn = 1
elif move == "Stay" or "stay":
print(f"Player stays with {playerhand.total()}\n")
playerturn = 1
else:
print("I didn't understand you!\n")
if win == -1:
print(f"Dealer wins with a {dealerhand.hand[-1].rank} of {dealerhand.hand[-1].suit}\
and a {dealerhand.hand[-2].rank} of {dealerhand.hand[-2].suit}\n")
break
print(f"Dealer reveals a {dealerhand.hand[-2].rank} of {dealerhand.hand[-2].suit}\n")
while dealerturn == 0:
print("Dealer Hand:")
for i, val in enumerate(dealerhand.hand, -1):
print(f"{dealerhand.hand[i].rank} of {dealerhand.hand[i].suit}")
print(f"Dealer has {dealerhand.total()}\n")
if dealerhand.total() <= 16:
print("The dealer hits\n")
dealerhand.hit(deck1)
else:
print(f"The dealer stays with {dealerhand.total()}\n")
dealerturn = 1
if dealerhand.total() > 21:
print("The dealer busts\n")
win = 1
dealerturn = 1
break
if win == 1 or ((playerhand.total() > dealerhand.total()) and win != -1):
print(f"The player wins with {playerhand.total()}!\n")
balance += bet
elif win == -1 or playerhand.total() < dealerhand.total():
print(f"The dealer wins with {dealerhand.total()}!\n")
balance -= bet
else:
print("The player and dealer drew!\n")
black_jack()
|
import requests
import bs4
result = requests.get("https://en.wikipedia.org/wiki/Jonas_Salk")
print(type(result))
# print(result.text)
soup = bs4.BeautifulSoup(result.text, "lxml")
# print(soup)
print(soup.select('title'))
site_paragraphs = soup.select("p")
print(site_paragraphs)
print(site_paragraphs[0])
|
# imports all openGL functions
from OpenGL.GL import *
from OpenGL.GL import shaders
from matutils import *
# we will use numpy to store data in arrays
import numpy as np
class Uniform:
"""
We create a simple class to handle uniforms, this is not necessary,
but allow to put all relevant code in one place
"""
def __init__(self, uniform_name, value=None):
"""
Initialise the uniform parameter
:param uniform_name: the name of the uniform, as stated in the GLSL code
"""
self.name = uniform_name
self.value = value
self.location = -1
def link(self, program):
"""
This function needs to be called after compiling the GLSL program to fetch the location of the uniform
in the program from its name
:param program: the GLSL program where the uniform is used
"""
self.location = glGetUniformLocation(program=program, name=self.name)
if self.location == -1:
print('(E) Warning, no uniform {}'.format(self.name))
def bind_matrix(self, M=None, number=1, transpose=True):
"""
Call this before rendering to bind the Python matrix to the GLSL uniform mat4.
You will need different methods for different types of uniform, but for now this will
do for the PVM matrix
:param number: the number of matrices sent, leave that to 1 for now
:param transpose: Whether the matrix should be transposed
"""
if M is not None:
self.value = M
if self.value.shape[0] == 4 and self.value.shape[1] == 4:
glUniformMatrix4fv(self.location, number, transpose, self.value)
elif self.value.shape[0] == 3 and self.value.shape[1] == 3:
glUniformMatrix3fv(self.location, number, transpose, self.value)
else:
print('(E) Error: Trying to bind as uniform a matrix of shape {}'.format(self.value.shape))
def bind(self, value):
if value is not None:
self.value = value
if isinstance(self.value, int):
self.bind_int()
elif isinstance(self.value, float):
self.bind_float()
elif isinstance(self.value, np.ndarray):
if self.value.ndim == 1:
self.bind_vector()
elif self.value.ndim == 2:
self.bind_matrix()
else:
print('Wrong value bound: {}'.format(type(self.value)))
def bind_int(self, value=None):
if value is not None:
self.value = value
glUniform1i(self.location, self.value)
def bind_float(self, value=None):
if value is not None:
self.value = value
glUniform1f(self.location, self.value)
def bind_vector(self, value=None):
if value is not None:
self.value = value
if value.shape[0] == 2:
glUniform2fv(self.location, 1, value)
elif value.shape[0] == 3:
glUniform3fv(self.location, 1, value)
elif value.shape[0] == 4:
glUniform4fv(self.location, 1, value)
else:
print('(E) Error in Uniform.bind_vector(): Vector should be of dimension 2,3 or 4, found {}'.format(
value.shape[0]))
def set(self, value):
"""
function to set the uniform value (could also access it directly, of course)
"""
self.value = value
class FurShader:
"""
This is the base class for loading and compiling the GLSL shaders.
"""
def __init__(self):
"""
Initialises the shaders
:param vertex_shader: the name of the file containing the vertex shader GLSL code
:param fragment_shader: the name of the file containing the fragment shader GLSL code
"""
print('Creating shader program.')
# tells the program where to find the shaders.
vertex_shader = 'shaders/vertex_shader.glsl'
fragment_shader = 'shaders/fragment_shader.glsl'
# load the vertex shader GLSL code
print('Load vertex shader from file: {}'.format(vertex_shader))
with open(vertex_shader, 'r') as file:
self.vertex_shader_source = file.read()
# load the fragment shader GLSL code
print('Load fragment shader from file: {}'.format(fragment_shader))
with open(fragment_shader, 'r') as file:
self.fragment_shader_source = file.read()
# All of the uniforms which are required for the shaders.
self.uniforms = {
'UVScale': Uniform('UVScale'),
'num_of_layers': Uniform('num_of_layers'),
'current_layer': Uniform('current_layer'),
'projection': Uniform('projection'),
'view': Uniform('view'),
'model': Uniform('model'),
'fur_length': Uniform('fur_length'),
'furFlowOffset': Uniform('furFlowOffset'),
'textureUnit0': Uniform('textureUnit0'),
'textureUnit1': Uniform('textureUnit1')
}
self.model_program = None
def compile(self, attributes):
"""
Call this function to compile the GLSL codes for both shaders.
:return:
"""
print('Compiling GLSL shaders....')
try:
self.program = glCreateProgram()
glAttachShader(self.program, shaders.compileShader(self.vertex_shader_source, shaders.GL_VERTEX_SHADER))
glAttachShader(self.program, shaders.compileShader(self.fragment_shader_source, shaders.GL_FRAGMENT_SHADER))
except RuntimeError as error_message:
print('(E) An error occurred while compiling {} shader:\n {}\n... forwarding exception...'.format(self.name,
error_message)),
raise error_message
self.bindAttributes(attributes)
# Links the program
glLinkProgram(self.program)
# tell OpenGL to use this shader program for rendering
glUseProgram(self.program)
# link all uniforms
for uniform in self.uniforms:
self.uniforms[uniform].link(self.program)
def bindAttributes(self, attributes):
# bind all shader attributes to the correct locations in the VAO
for attrib_name, location in attributes.items():
glBindAttribLocation(self.program, location, attrib_name)
print('Binding attribute {} to location {}'.format(attrib_name, location))
def bind(self, model, M, UVScale, num_of_layers, fur_length, current_layer, furFlowOffset):
"""
Call this function to enable this GLSL Program (you can have multiple GLSL programs used during rendering!)
"""
# tell OpenGL to use this shader program for rendering
glUseProgram(self.program)
P = model.scene.P
V = model.scene.camera.V
# set the uniforms
self.uniforms['projection'].bind(P)
self.uniforms['view'].bind(V)
self.uniforms['model'].bind(M)
self.uniforms['UVScale'].bind_float(UVScale)
self.uniforms['num_of_layers'].bind_float(num_of_layers)
self.uniforms['fur_length'].bind_float(fur_length)
self.uniforms['current_layer'].bind_float(current_layer)
self.uniforms['furFlowOffset'].bind_float(furFlowOffset)
self.uniforms['textureUnit0'].bind(0)
self.uniforms['textureUnit1'].bind(1)
def unbind(self):
glUseProgram(0)
|
import unittest
class Node:
def __init__(self, keyIn, valueIn):
self.key = keyIn
self.value = valueIn
self.left = None
self.right = None
def __repr__(self):
return "Node{ key : " + str(self.key) + ", value : " + str(self.value) + "}"
def getKey(self):
return self.key
def setKey(self, keyIn):
self.key = keyIn
def getValue(self):
return self.value
def setValue(self, valueIn):
self.value = valueIn
def getLeft(self):
return self.left
def setLeft(self, nodeIn):
self.left = nodeIn
def getRight(self):
return self.right
def setRight(self, nodeIn):
self.right = nodeIn
class BST:
def __init__(self):
self.root = Node(None, None)
def size(self):
return self.__size(self.root)
def __size(self, nodeIn):
if nodeIn == None or nodeIn.getKey() == None:
return 0
left = nodeIn.getLeft() == None
right = nodeIn.getRight() == None
if left & right:
return 1
elif right:
return 1 + self.__size(nodeIn.getLeft())
elif left:
return 1 + self.__size(nodeIn.getRight())
else:
return 1 + self.__size(nodeIn.getRight()) + self.__size(nodeIn.getLeft())
def isEmpty(self):
return self.size() == 0
def put(self, keyIn, valueIn):
if self.root.getKey() == None:
self.root = Node(keyIn, valueIn)
else:
self.root = self.__put(self.root, keyIn, valueIn)
def __put(self, nodeIn, keyIn, valueIn):
if nodeIn == None or nodeIn.getKey() == None:
return Node(keyIn, valueIn)
else:
if keyIn > nodeIn.getKey():
nodeIn.setRight(self.__put(nodeIn.getRight(), keyIn, valueIn))
else:
nodeIn.setLeft(self.__put(nodeIn.getLeft(), keyIn, valueIn))
return nodeIn
def get(self, keyIn):
return self.__get(self.root, keyIn)
def __get(self, curNode, keyIn):
if curNode == None:
return None
if curNode.getKey() == keyIn:
return curNode.getValue()
elif curNode.getKey() < keyIn:
if curNode.getRight() == None:
return None
return self.__get(curNode.getRight(), keyIn)
elif curNode.getKey() > keyIn:
if curNode.getLeft() == None:
return None
return self.__get(curNode.getLeft(), keyIn)
def contains(self, keyIn):
return self.get(keyIn) != None
def remove(self, keyIn):
value = self.get(keyIn)
self.root = self.__remove(self.root, keyIn)
return value
def __remove(self, nodeIn, keyIn):
if nodeIn == None:
return None
if keyIn < nodeIn.getKey():
nodeIn.setLeft(self.__remove(nodeIn.getLeft(), keyIn))
elif keyIn > nodeIn.getKey():
nodeIn.setRight(self.__remove(nodeIn.getRight(), keyIn))
else:
if nodeIn.getRight() == None:
return nodeIn.getLeft();
if nodeIn.getLeft() == None:
return nodeIn.getRight()
min = self.__min(nodeIn.getRight())
min.setLeft(nodeIn.getLeft())
nodeIn = nodeIn.getRight()
return nodeIn
def min(self):
return self.__min(self.root).getKey();
def __min(self, nodeIn):
if nodeIn.getLeft() == None:
return nodeIn
else:
return self.__min(nodeIn.getLeft())
def max(self):
return self.__max(self.root).getKey();
def __max(self, nodeIn):
if nodeIn.getRight() == None:
return nodeIn
else:
return self.__max(nodeIn.getRight())
def __repr__(self):
temp = self.toString(self.root)
temp = temp[0:len(temp)-2]
return "{" + temp + "}"
def toString(self, nodeIn):
if(nodeIn==None):
return ""
return self.toString(nodeIn.getLeft()) + str(nodeIn.getKey()) + "=" + str(nodeIn.getValue()) + ", " + self.toString(nodeIn.getRight())
def isBST(bst):
return(isBSTNode(bst.root))
def isBSTNode(nodeIn):
if nodeIn.getLeft() == None and nodeIn.getRight() == None:
return True
elif nodeIn.getLeft() != None and nodeIn.getRight() == None:
return(nodeIn.getLeft().getKey() < nodeIn.getKey() and isBSTNode(nodeIn.getLeft()))
elif nodeIn.getLeft() == None and nodeIn.getRight() != None:
return(nodeIn.getRight().getKey() > nodeIn.getKey() and isBSTNode(nodeIn.getRight()))
else:
return(nodeIn.getLeft().getKey() < nodeIn.getKey() and nodeIn.getRight().getKey() > nodeIn.getKey() and isBSTNode(nodeIn.getLeft()) and isBSTNode(nodeIn.getRight()))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# function: https://practice.geeksforgeeks.org/problems/coin-change/0
# author: jmhuang
# email: [email protected]
# date: 2018/7/1
import sys
global matrix
def calculate_coin_change(number, number_list):
global matrix
if number == 0:
return 0
if not number_list:
return 0
number_list.sort()
if number < number_list[0]:
return 0
if matrix[number][number_list[0]] != -1:
return matrix[number][number_list[0]]
result = 0
for i, num in enumerate(number_list):
if number < num:
break
elif number == num:
result += 1
else:
result += calculate_coin_change(number - num, number_list[i:])
matrix[number][number_list[0]] = result
return result
if __name__ == "__main__":
lines = sys.stdin.readlines()
total_groups = int(lines[0])
for group in range(total_groups):
number_len = int(lines[group * 3 + 1])
global matrix
number_list = list(map(int, lines[group * 3 + 2].split()))
total = int(lines[group * 3 + 3])
matrix = [[-1 for i in range(total + 1)] for i in range(total + 1)]
result = calculate_coin_change(total, number_list)
# for each in matrix:
# print each
print(result) |
import requests
from datetime import datetime
def get_proxies(request="getproxies", proxytype="http", timeout="10000", country="all", ssl="all", anonymity="all"):
"""
returns a list of proxies as strings ['host1:port1', 'host2:port2'] or None if proxies aren't found.
proxytype - http, socks4, and socks5
timeout - time in ms
country - all, US, CA, AU, DE, FR, GB, GE, IN, IT, JP, MX, PH, PK, US, RU, SG, and more
ssl - all, yes, and no
anonymity - all, elite, anonymous, and transparent
"""
request = request
proxytype = proxytype
timeout = timeout
country = country
ssl = ssl
anonymity = anonymity
url = "https://api.proxyscrape.com/"+ \
"?request="+request+ \
"&proxytype="+proxytype+ \
"&timeout="+timeout+ \
"&country="+country+ \
"&ssl="+ssl+ \
"&anonymity="+anonymity
r = requests.get(url)
proxy_list = r.text
proxies = proxy_list.split("\r\n")
if(len(proxy_list) > 0):
return proxy_list
else:
return None
def import_proxies(request="getproxies", proxytype="http", timeout="10000", country="all", ssl="all", anonymity="all"):
"""
Imports all proxies into a text file - 'proxies/proxies.txt'
Returns True on completion and None if proxies aren't found.
"""
proxies = get_proxies(request=request, proxytype=proxytype, timeout=timeout, country=country, ssl=ssl, anonymity=anonymity)
proxy_file = open("./proxies/proxies.txt", "w+")
if(len(proxies) < 1):
return None
for proxy in proxies:
if(len(proxy)> 4):
proxy_file.write(proxy+"\n")
return True |
from math import sqrt
import numpy as np
from sympy import Matrix
def get_pos_array(key,alphabet):
"""
Gets an array of positions of a string in the alphabet
Params:
key - word to be transformed
alphabet - alphabet that contains the key
Return:
An array of positions
"""
pos_pass = []
for letter in key:
pos_pass.append(alphabet.find(letter))
return pos_pass
def generate_matrix(key,alphabet):
"""
Generate a matrix given a key and an alphabet
Params:
key - key to be transformed to a matrix
alphabet - Alphabet
Return:
Matrix of positions of the given key
"""
pos_pass = np.asarray(get_pos_array(key,alphabet))
a = pos_pass.reshape(int(sqrt(len(key))),int(sqrt(len(key))))
return a
def dot_matrix(A,alphabet,s):
"""
Generates the string of the product of a matrix and a string in the alphabet
Params:
A - matrix to be multiplied
alphabet - alphabet
s - string to be multiplied
Return:
String of the result of the product between the matrix and the string
"""
pos_pass = np.asarray(get_pos_array(s,alphabet))
enciphered_vector = A.dot(pos_pass)%26
res = ''
for i in enciphered_vector:
res += alphabet[int(i)]
return res
def mod_mat_inv(A,m):
"""
Calculates the module matrix inverse
Params:
A - Matrix
m - module
Return:
The module matrix inverse of the given matrix
"""
A = Matrix(A)
A = A.inv_mod(m)
return np.array(A).astype(np.int32)
|
import unittest
from calculator import Calculator
class TestStringMethods(unittest.TestCase):
def test_expression(self):
calc = Calculator("1,2")
self.assertEqual(calc.expr, "1,2")
def test_invalid_expression(self):
with self.assertRaises(RuntimeError):
Calculator("a,b")
if __name__ == '__main__':
unittest.main()
|
earnings = float(input("ะะฒะตะดะธัะต ะทะฝะฐัะตะฝะธะต ะฒััััะบะธ:"))
expenses = float(input("ะะฒะตะดะธัะต ะทะฝะฐัะตะฝะธะต ะธะทะดะตัะถะตะบ:"))
if earnings > expenses:
print("ะัะธะฑัะปั โ ะฒััััะบะฐ ะฑะพะปััะต ะธะทะดะตัะถะตะบ")
profit = earnings - expenses
efficiency = profit / earnings
print("ะ ะตะฝัะฐะฑะตะปัะฝะพััั ัะพััะฐะฒะปัะตั %.2f" % efficiency)
employers = int(input("ะะฒะตะดะธัะต ะบะพะปะธัะตััะฒะพ ัะพัััะดะฝะธะบะพะฒ:"))
print("ะัะธะฑัะปั ะฝะฐ ะพะดะฝะพะณะพ ัะพัััะดะฝะธะบะฐ ัะพััะฐะฒะปัะตั: %.2f" % (profit / employers))
else:
print("ะฃะฑััะพะบ โ ะธะทะดะตัะถะบะธ ะฑะพะปััะต ะฒััััะบะธ") |
# ะ ะตะฐะปะธะทะพะฒะฐัั ััะฝะบัะธั int_func(),
# ะฟัะธะฝะธะผะฐัััั ัะปะพะฒะพ ะธะท ะผะฐะปะตะฝัะบะธั
ะปะฐัะธะฝัะบะธั
ะฑัะบะฒ ะธ ะฒะพะทะฒัะฐัะฐัััั ะตะณะพ ะถะต,
# ะฝะพ ั ะฟัะพะฟะธัะฝะพะน ะฟะตัะฒะพะน ะฑัะบะฒะพะน.
# ะะฐะฟัะธะผะตั, print(int_func(โtextโ)) -> Text.
#
# ะัะพะดะพะปะถะธัั ัะฐะฑะพัั ะฝะฐะด ะทะฐะดะฐะฝะธะตะผ.
# ะ ะฟัะพะณัะฐะผะผั ะดะพะปะถะฝะฐ ะฟะพะฟะฐะดะฐัั ัััะพะบะฐ ะธะท ัะปะพะฒ, ัะฐะทะดะตะปะตะฝะฝัั
ะฟัะพะฑะตะปะพะผ.
# ะะฐะถะดะพะต ัะปะพะฒะพ ัะพััะพะธั ะธะท ะปะฐัะธะฝัะบะธั
ะฑัะบะฒ ะฒ ะฝะธะถะฝะตะผ ัะตะณะธัััะต.
# ะกะดะตะปะฐัั ะฒัะฒะพะด ะธัั
ะพะดะฝะพะน ัััะพะบะธ, ะฝะพ ะบะฐะถะดะพะต ัะปะพะฒะพ ะดะพะปะถะฝะพ ะฝะฐัะธะฝะฐัััั ั ะทะฐะณะปะฐะฒะฝะพะน ะฑัะบะฒั.
# ะะตะพะฑั
ะพะดะธะผะพ ะธัะฟะพะปัะทะพะฒะฐัั ะฝะฐะฟะธัะฐะฝะฝัั ัะฐะฝะตะต ััะฝะบัะธั int_func().
def int_func(word):
return word.capitalize()
def int_func_multi(sentence):
return_value = ""
for word in sentence.split():
return_value += int_func(word) + " "
return return_value
print(int_func("ัะะทะฃะปะฌัะั:"), int_func_multi(input("ะะฒะตะดะธัะต ัััะพะบั: "))) |
# ะ ะตะฐะปะธะทะพะฒะฐัั ััะฝะบัะธั, ะฟัะธะฝะธะผะฐัััั ะฝะตัะบะพะปัะบะพ ะฟะฐัะฐะผะตััะพะฒ,
# ะพะฟะธััะฒะฐััะธั
ะดะฐะฝะฝัะต ะฟะพะปัะทะพะฒะฐัะตะปั: ะธะผั, ัะฐะผะธะปะธั, ะณะพะด ัะพะถะดะตะฝะธั, ะณะพัะพะด ะฟัะพะถะธะฒะฐะฝะธั, email, ัะตะปะตัะพะฝ.
# ะคัะฝะบัะธั ะดะพะปะถะฝะฐ ะฟัะธะฝะธะผะฐัั ะฟะฐัะฐะผะตััั ะบะฐะบ ะธะผะตะฝะพะฒะฐะฝะฝัะต ะฐัะณัะผะตะฝัั.
# ะ ะตะฐะปะธะทะพะฒะฐัั ะฒัะฒะพะด ะดะฐะฝะฝัั
ะพ ะฟะพะปัะทะพะฒะฐัะตะปะต ะพะดะฝะพะน ัััะพะบะพะน.
def pretty_user_print(first_name, last_name, birth_year, city, email, phone):
print(f"{last_name} {first_name}, {birth_year} ะณะพะดะฐ ัะพะถะดะตะฝะธั.\nะัะพะถะธะฒะฐะตั ะฒ ะณะพัะพะดะต {city}.\nemail: {email}\nัะตะปะตัะพะฝ: {phone}")
name = input("ะะฒะตะดะธัะต ะธะผั: ")
last_name = input("ะะฒะตะดะธัะต ัะฐะผะธะปะธั: ")
year = int(input("ะะฒะตะดะธัะต ะณะพะด ัะพะถะดะตะฝะธั: "))
city = input("ะะฒะตะดะธัะต ะณะพัะพะด ะฟัะพะถะธะฒะฐะฝะธั: ")
email = input("ะะฒะตะดะธัะต email: ")
phone_number = input("ะะฒะตะดะธัะต ัะตะปะตัะพะฝ: ")
print("\nะะพะปััะตะฝั ัะปะตะดัััะธะต ะดะฐะฝะฝัะต: \n")
pretty_user_print(first_name=name, last_name=last_name, birth_year=year, city=city, email=email, phone=phone_number) |
class StackMin:
def __init__(self):
self.stack = []
def add(self, item):
minval = self.getmin()
minval = min(minval, item)
self.stack.append((item, minval))
def getmin():
if len(self.stack) == 0:
return inf("float")
return self.stack[-1][1]
def remove(self):
data = self.stack.pop()
return data
add(5) - mini = 5
add(1) - mini = 1
add(1000) - mini= 1
Stack min :
How would you design a stack which, in addition to push and pop, has function min which returns the minimun element?
Push, pop and minimun element? Push, pop and min should all operate in 0(1) time |
"""
One Away: There
are
threetypes
of
edits that
can
be performed onstrings:insert a character,removea character, orreplacea character.Given
two
strings, write a function to check if they are one edit(orzero edits) away.
EXAMPLE
pale, pIe -> true
pales,pale -> true
pale,bale -> true
pale, bake -> false
"""
class Solution:
def isOneEditDistance(self, s: str, t: str) -> bool:
# if abs(len(s) - len(t)) == 1 and ( not s or not t):
# return True
if abs(len(s) - len(t)) > 1 or (not s and not t):
return False
# Defining largest and smaller strings
shortS = s if len(s) <= len(t) else t
longS = s if len(s) > len(t) else t
# Defining two pointers starting at zero
index1 = 0 # index1 is associated with shortS
index2 = 0 # index2 is associated with longS
# defining a boolean flag, represents whether we found a single difference
foundifference = False
while index1 < len(shortS) and index2 < len(longS):
# if the letters are different, if foundifference, we return false, otherwise, we set
# foundifference to True
if shortS[index1] != longS[index2]:
if foundifference:
return False
foundifference = True
# if the strings are same lengths, we increment both pointers
if len(shortS) == len(longS):
index1 += 1
index2 += 1
else:
# if the strings have different lengths, we incrememt the pointer of the
# the largest string
index2 += 1
else:
# if the letters at specifics indexes are the same, we increment both pointers
index1 += 1
index2 += 1
# if after while loop, we still have a letter that is left, if previously found a difference(foundifference #is True), we return False, otherwise we set foundifference to True
if index1 < len(shortS) or index2 < len(longS):
if foundifference:
return False
foundifference = True
return foundifference
def make_letter_counts_dict(str):
"""Return dict of letters and # of occurrences in phrase."""
letter_counts = {}
for letter in str:
letter_counts[letter] = letter_counts.get(letter, 0) + 1
return letter_counts
def oneAway(str1,str2):
A = {}
B = {}
A= make_letter_counts_dict(str1)
print (A)
B= make_letter_counts_dict(str2)
print (B)
count = 0
for (key,value) in A.items():
if not (key,value) in B.items():
count += 1
return count==1
print(oneAway("task", "take")) |
# Call Center: Imagine you have a call center with three levels of employees: Respondent,
# manager, and director. An incoming telephone call must be first allocated to a respondent who is free.
# if the responder can't handle the call, he or she must escalate the call to a manager.
# if the manager is not free or not able to handle it, the the call should be escalated to a director. Design the classes and datastructures
# for this problem. Implement a method dispatchCall() which assigns a call to the first
# available employee.
class CallCenter(): # are the parantheses necessary?
def __init__(self, respondents, managers, director):
self.respondents = respondents
self.managers = managers
self.director = director
self.respondent_queue = []
self.call_queue = []
for respondent in respondents:
respondent.callcenter = self # not sure why
if not respondent.call:
self.respondent_queue.append(respondent)
def route_respondent(self, respondent):
if len(self.call_queue):
respondent.take_call(self, call_queue.pop())
else:
self.respondent_queue(respondent)
def route_call(self, call):
if len(self.respondent_queue):
self.respondent_queue.pop(0).take_call
else:
self.call_queue.append(call)
class Call():
def __init__(self, issue):
self.issue = issue
self.employee = None
def resolve(self, handled):
if handled:
self.issue = None
self.employee = None
def apologize_and_hangup(self):
# Try calling our competitor
self.employee = None
class Employee(object):
def __init__(self, name, manager):
self.name = name
self.manager = manager
def take_call(self,call):
if self.call:
self.escalate(call)
else:
self.call = call
self.call.employee = self # why ?
def escalate(self, call):
if self.manager:
self.manager.take_call(call)
else:
call.apologize_and_hangup
def finish_call(self, handled = True):
if not handed:
if self.manager:
self.manager.take_call(self.call)
else:
call.apologize_and_hangup()
self.call = None
class manager(Employee):
pass
class Director(Employee):
def __init__(self, name):
super(Director,self).__init__(name, None) # why ?
|
# [15,16,19,20,25,1,3,4,5,7,10,14], key = 5
# mid
# left = 0
# right = len(arr) - 1
# mid = left + right//2
# mid = left + (right-left)/2
# compute the mid value
# if arr[mid] < arr[left], we know that the left side is not sorted and we need to explore the right side first and then the left side
# if arr[right] < arr[mid], we know that the rightt side is not sorted and we need to explore the left side first and then the right side
# if arr[left] == arr[mid], the left is sorted and I need to evaluate the key value in regard to arr[left], if arr[left]< key, then I need to search the right first and then the left
# if arr[right] == arr[mid], right or left could be all repeats.
# if arr[mid] != arr[right], we search the left side else we save the result of the search of teh right side in a variable called result. if result == -1
# we search the left side else we return the result. at the very end, aligning the if statements we return -1
#if arr[right] > arr[mid]
# def search_in_rotated_array(arr, key):
# if not arr: return
# return binarySearch(arr, 0, len(arr) - 1, key)
# def splitInHalf()
# time complexity is 0(log n ) without duplicates or 0(n) with duplicates
def binarySearch(arr, left, right, key):
mid = left + (right - left) // 2
if key == arr[mid]:
return mid
if right < left:
return -1
if arr[left] > arr[mid]: # providing a hint that the right side is sorted
if arr[mid] < key and key <= arr[right]: # sort the right side
return binarySearch(arr, mid + 1, right, key )
else:
return binarySearch(arr, left, mid - 1, key) # searching the left side
elif arr[left] < arr[mid]: # left side is ordered
if arr[mid] > key and arr[left] <= key:
return binarySearch(arr, left, mid - 1, key)
else:
return binarySearch(arr, mid + 1, right, key )
elif arr[left] == arr[mid]: # left and right are all repeats
if arr[mid] != arr[right]: # if right side is different, search it
return binarySearch(arr,mid + 1, right, key) # searching the right side
else:
result = binarySearch(arr, left, mid - 1, key ) # searching the left side
if result == -1:
return binarySearch(arr, left, mid - 1, key) # searching the left side
else:
return result
return -1
arr = [15,16,19,20,25,1,3,4,5,7,10,14]
print(binarySearch(arr, 0, len(arr)-1, 25))
# [15,16,19,20,25,1,3,4,5,7,10,14], key = 5
# hint 298:
# can you modify binary search for this purpose?
# hint 310:
# what is the runtime of your algorithm? What will happen if the array has duplicates
# Implement a binary search:
# def binary_search(arr,l, r, key):
# if not arr: return
# mid = l + (r - l )// 2
# if arr[mid] == key:
# return mid
# elif arr[mid] < key:
# return binary_search(arr, mid + 1, r, key)
# elif arr[mid] > key:
# return binary_search(arr, l, mid - 1, key )
# arr = [15,16,19,20,25,1,3,4,5,7,10,14]
# print(binary_search(arr, 0, len(arr)-1,20 ))
|
# Testing assigned variables and output.
x = 5
y = 7
z = x + y
print ("z is equal to", z, "by addition. \nThanks!")
z = y - x
print ("z is equal to", z, "by subtraction. \nThanks!")
# Testing conditional flow control
max = x if(x > y) else y
print( '\nGreater value is', max)
|
import networkx as nx
for i in range(10):
print(i)
# Iterate through list - a bit more Pythonic
z = [42, 15, 9, 'italy', 14]
for z_item in z:
print(z_item)
# iterate through a dict
z2 = {42: "tyger", 15: "burning", 9: "bright", 3: "yeats"}
for z_key in z2:
print(z_key, z2[z_key])
|
Name = input("What is your Name ")
Branch = input("What is your Branch ")
College = input("What is your college Name ")
Gender = input("What is your Gender ")
Age = input("What is your Age ")
print(Name + "\n" + Branch + "\n" + College + "\n" + Gender + "\n" + Age) |
# tasks guessing game
# 0
# Hangman-0.png
# Word: hangman
# Guess: E
# Misses:
# 1
# Hangman-1.png
# Word: _ _ _ _ _ _ _
# Guess: T
# Misses: e
# 2
# Hangman-2.png
# Word: _ _ _ _ _ _ _
# Guess: A
# Misses: e, t
# 3
# Hangman-2.png
# Word: _ A _ _ _ A _
# Guess: O
# Misses: e, t
# option+ cmd + L
import re
def check_whole_answer(arrayOfGuessAnswer, answer):
strArray = ''.join(arrayOfGuessAnswer) # convert list to string
if strArray == answer:
return True # it is in the array, stop
else:
return False # not in the array, just going
def insert_answer(arrayOfGuessAnswer, guess, answer):
for n, i in enumerate(answer): # n returns number, i return the character
if guess in i:
arrayOfGuessAnswer[n] = guess
def check_input(guess):
checkCharacter = False
while not checkCharacter:
guess = input("please guess a letter \n")
if not re.match("[a-z]", guess):
print("Invalid character!")
checkCharacter = False
elif len(guess) > 1:
print("only a single character is allowed!")
checkCharacter = False
else:
checkCharacter = True
return guess
# initial
answer = "hangman" # declare the answer, convert the answer to no space and small letter
answer = answer.lower() # lowercase
answer = answer.replace(" ", "") # no space
miss_time = 0
MAX_ESTIMATED_TIME = 6
arrayOfGuessAnswer = []
for a in range(len(answer)):
arrayOfGuessAnswer.append("_")
print(arrayOfGuessAnswer)
setOfMissAnswer = set()
guess = ""
print("hangman begin! \n")
print("Chances : ", MAX_ESTIMATED_TIME)
while not check_whole_answer(arrayOfGuessAnswer, answer) and miss_time < MAX_ESTIMATED_TIME: # not only refer to the first condition
guess = check_input(guess)
if guess in answer:
insert_answer(arrayOfGuessAnswer, guess, answer)
print(arrayOfGuessAnswer)
else:
setOfMissAnswer.add(guess)
print("you guessed it wrong!")
print(setOfMissAnswer)
miss_time += 1
print("remaining chance : ", MAX_ESTIMATED_TIME - miss_time)
if miss_time >= 6:
print("you lose!")
else:
print("you win!, end game")
|
def recurse_dict (value, bag_dict, already_counted) :
if value not in already_counted :
count = 1
already_counted.append(value)
else :
count = 0
if value not in bag_dict :
return already_counted, count
arr = bag_dict.get(value)
for i in arr :
already_counted, num = recurse_dict(i, bag_dict, already_counted)
count += num
return already_counted, count
def solution1(input_text) :
dict_bags = {}
for line in input_text :
outer_bag, inner_bags = line.split("contain")
outer_bag = ''.join([i for i in outer_bag if i.isalpha() or i == ' '])
inner_bags = ''.join([i for i in inner_bags if i.isalpha() or i == ',' or i == ' '])
inner_bags = inner_bags.replace("bags", "")
inner_bags = inner_bags.replace("bag", "")
outer_bag = outer_bag.replace("bags", "")
outer_bag = outer_bag.replace("bag", "")
outer_bag = outer_bag.strip()
inner_bags = inner_bags.split(",")
#print (outer_bag, inner_bags)
for bag in inner_bags :
bag = bag.strip()
if bag != "no other" :
if bag in dict_bags :
arr = dict_bags.get(bag)
arr.append(outer_bag)
dict_bags[bag] = arr
else :
dict_bags[bag] = [outer_bag]
null, count = recurse_dict("shiny gold", dict_bags, ["shiny gold"])
return count
def recurse_dict_2 (value, bag_dict) :
count = 1
if value not in bag_dict :
return count
arr = bag_dict.get(value)
for i in arr :
#print (value,i, recurse_dict_2(i[1], bag_dict), recurse_dict_2(i[1], bag_dict) * int(i[0]))
count += recurse_dict_2(i[1], bag_dict) * int(i[0])
return count
def solution2(input_text) :
dict_bags = {}
for line in input_text :
outer_bag, inner_bags = line.split("contain")
outer_bag = ''.join([i for i in outer_bag if i.isalpha() or i == ' '])
inner_bags = ''.join([i for i in inner_bags if i.isalnum() or i == ',' or i == ' '])
inner_bags = inner_bags.replace("bags", "")
inner_bags = inner_bags.replace("bag", "")
outer_bag = outer_bag.replace("bags", "")
outer_bag = outer_bag.replace("bag", "")
outer_bag = outer_bag.strip()
inner_bags = inner_bags.strip()
inner_bags = inner_bags.split(",")
#print (outer_bag, inner_bags)
arr = [n.split() for n in inner_bags]
for n in arr :
if n[0] != "no" :
if outer_bag in dict_bags:
arr = dict_bags[outer_bag]
arr.append((n[0], n[1] + ' ' + n[2]))
dict_bags.update({outer_bag : arr})
else :
dict_bags[outer_bag] = [(n[0], n[1] + ' ' + n[2])]
return recurse_dict_2("shiny gold", dict_bags) - 1
with open("input.txt") as f:
input_text = f.readlines()
print (solution1(input_text))
with open("test.txt") as f:
input_text = f.readlines()
print (solution1(input_text))
with open("input.txt") as f:
input_text = f.readlines()
print (solution2(input_text))
with open("test.txt") as f:
input_text = f.readlines()
print (solution2(input_text)) |
import json
import urllib.request
CONVERSION_FACTIOR = 250
# Main function which will run loop until there are no new pages to read in API
def main():
weights = []
url_base = "http://wp8m3he1wt.s3-website-ap-southeast-2.amazonaws.com"
url_api = "/api/products/1"
while True:
url = url_base + url_api
data = get_data(url)
append_cubic_weight(weights, data)
if(data["next"] == None):
break
else:
url_api = data["next"]
average_weight(weights)
# Funtion to access data from API and convert it into JSON
def get_data(url):
res = urllib.request.urlopen(url)
return json.loads(res.read())
# Function to populate list with cubic weight for every Air Conditoner
def append_cubic_weight(weights, data):
for objects in data["objects"]:
if(objects["category"] == "Air Conditioners"):
dimensions = get_dimensions(objects)
weights.append(get_cubic_weight(dimensions))
# Function to retrieve dimension of Air Conditioner and converting every dimension into cm
def get_dimensions(i):
w = i["size"]["width"] / 100
l = i["size"]["length"] / 100
h = i["size"]["height"] / 100
return (w, l, h)
# Function to calculate cubic weight of 1 Air Conditioner
def get_cubic_weight(dimensions):
return round(dimensions[0] * dimensions[1] * dimensions[2] * CONVERSION_FACTIOR, 3)
# Function to calculate average weight of all Air Conditoners
def average_weight(weight):
total_weight = sum(weight)
average = round(total_weight/len(weight), 3)
print("\nAverage weight for {} Air Conditioners is {}kg\n".format(
len(weight), average))
if __name__ == "__main__":
main()
|
# Google image web scraper for Nostalgia Machine project
# Adapted from:
# https://github.com/hardikvasa/google-images-download/issues/301#issuecomment-587097949
# and
# https://towardsdatascience.com/image-scraping-with-python-a96feda8af2d
#
###############################################################################################################
# todo - fix bug that saves empty image files
# todo - fix scrolling issue at beginning of program
import time
import shutil
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
import os
import urllib3
from urllib3.exceptions import InsecureRequestWarning
if __name__ == '__main__':
urllib3.disable_warnings(InsecureRequestWarning)
t0 = time.time() # Start program timer!
folder_name = 'testpictures' # Destination folder in which to save images
search_keywords = "Spongebob screencaps"
max_images = 100
# Create an empty folder in which to store pictures once they download
if not os.path.exists(folder_name): # If folder doesn't exist, just make a new one
os.mkdir(folder_name)
else: # If folder already exists, empty its contents, delete the folder, then make a new one
shutil.rmtree(folder_name)
os.rmdir(folder_name)
os.mkdir(folder_name)
# Use webdriver, open an empty Firefox browser
driver = webdriver.Firefox(executable_path="/home/megan/Python/Project/geckodriver")
# Navigate browser to page specified by search_url - in this case, the home page for Google Images
search_url = 'https://www.google.com/imghp?hl=en'
driver.get(search_url)
# Locate the search bar and types in the search keywords
driver.find_element_by_name("q").send_keys(search_keywords + Keys.ENTER)
# Give the page some time to load the search results - if you don't, the next part won't work!
time.sleep(3)
url_set = set() # Initialize empty set for storing urls - allows you to ignore any duplicates
url_count = 0 # Size of url_set
results_start = 0 # This marks the location of the page where the current range of search results begins
# Keep going until you've reached the desired number of images
while url_count < max_images:
# This line of code uses a JavascriptExecutor (an interface of the selenium webdriver) which scrolls all the way
# to the bottom of the current results. Doing this **may** automatically load more search results as well.
print("Scrolling down ...")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Get all image thumbnails (i.e. the long list of results which your search initially displays, before any clicking)
thumb_results = driver.find_elements_by_css_selector("img.Q4LuWd")
number_results = len(thumb_results) # TOTAL number of thumbnail results loaded so far
# This condition will be met if you reach the end of the search results
if number_results == results_start:
print("Reached end of results. Collected {} image links!".format(url_count))
break
print(f"Found {number_results} total search results. Extracting links from range {results_start}-{number_results}")
# Loops through a fixed range of urls - this is usually fewer than the total number of search results currently loaded
for thumb_img in thumb_results[results_start:number_results]:
# Attempt to click every thumbnail such that we can get the real image behind it
try:
thumb_img.click()
time.sleep(0.1)
except Exception: # if any exception occurs, just skip the current image and move on to the next one
continue
# Now that you've clicked on the image, extract the image url
actual_images = driver.find_elements_by_css_selector('img.n3VNCb')
for actual_image in actual_images:
# Make sure that 'src' is a url containing the substring 'http'
if actual_image.get_attribute('src') and 'http' in actual_image.get_attribute('src'):
# Add new url to the set
url_set.add(actual_image.get_attribute('src'))
url_count = len(url_set) # Update the size of the image_url set
# Break out of loop if you've collected the desired number of urls, or when you run out of search results
if url_count >= max_images or results_start == number_results:
print("Done! Collected {} image links!".format(url_count))
break # End the while loop
elif results_start == number_results:
print("Reached end of results. Collected {} image links!".format(url_count))
break
else:
print("Found", url_count, "total image links, looking for more ...")
time.sleep(3)
# Although scrolling to the bottom of the page will automatically load more results for your first few attempts,
# eventually this will stop and you'll have to click a "show more results" button before continuing
show_more_button = driver.find_element_by_css_selector(".mye4qd")
if show_more_button: # If this button exists...
print("Pressing the 'show more results' button ...")
driver.execute_script("document.querySelector('.mye4qd').click();") # ... click it.
# Move the result starting point further down
results_start = len(thumb_results)
driver.close()
# At this point, we've gathered all the urls we need and the web browser window is closed. Now we need to save those
# images into a local folder.
print("Attempting to save images to {} ...".format(folder_name))
# Use count to track the number of successfully DOWNLOADED images thus far
download_count = 0
# Iterate through the set of urls
for url in url_set:
try:
# Use an HTTP get request to read the actual image data from the url
response = requests.get(url, verify=False, stream=True) # doesn't need to verify host's SSL certificate; don't download body of response immediately
raw_data = response.raw.read()
# The os.path.join() method concatenates the paths of folder_name and the new image file
# e.g. f = ....PycharmProjects/webscraping/testpictures/img_1.jpg
with open(os.path.join(folder_name, 'img_' + str(download_count) + '.jpg'), 'wb') as f:
f.write(raw_data)
download_count += 1
except Exception as e:
print('Failed to write rawdata.')
t1 = time.time()
print("Program took {} seconds to save {} images".format(t1-t0, download_count))
|
#
# Example file for working with date information
#
from datetime import date
from datetime import time
from datetime import datetime
def main():
## DATE OBJECTS
# Get today's date from the simple today() method from the date class
oToday = date.today()
daynames = ["mon","tue","wed","thu","fri", "sat", "sun"]
print(oToday, daynames[oToday.weekday()], oToday.day, oToday.year, oToday.month)
# print out the date's individual components
# retrieve today's weekday (0=Monday, 6=Sunday)
## DATETIME OBJECTS
# Get today's date from the datetime class
oToday = None
oToday = datetime.now()
print(oToday, oToday.weekday(),oToday.year)
# Get the current time
if __name__ == "__main__":
main();
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset= pd.read_csv('50_Startups.csv')
X=dataset.iloc[:,:-1].values
Y=dataset.iloc[:,4].values
#encoding strings into numbers
from sklearn.preprocessing import LabelEncoder ,OneHotEncoder
labelencoder_X= LabelEncoder()
X[:,3]=labelencoder_X.fit_transform(X[:,3])
onehotencoder=OneHotEncoder(categorical_features=[3])
X=onehotencoder.fit_transform(X).toarray()
#removing 1st column to tackle dummy variable trap
X=X[:,1:]
#cross validation
from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0)
#fitting Simple linear regression to training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,Y_train)
#predicting test results
Y_pred=regressor.predict(X_test)
#building optimal model using backward elimination
import statsmodels.regression.linear_model as sm
X= np.append(arr=np.ones((50,1)).astype(int),values= X ,axis=1)
X_opt = X[:,[0,1,2,3,4,5]]
regressor_OLS=sm.OLS(endog = Y,exog = X_opt).fit()
regressor_OLS.summary()
X_opt = X[:,[0,1,3,4,5]]
regressor_OLS=sm.OLS(endog = Y,exog = X_opt).fit()
regressor_OLS.summary()
X_opt = X[:,[0,3,4,5]]
regressor_OLS=sm.OLS(endog = Y,exog = X_opt).fit()
regressor_OLS.summary()
X_opt = X[:,[0,3,5]]
regressor_OLS=sm.OLS(endog = Y,exog = X_opt).fit()
regressor_OLS.summary()
X_opt = X[:,[0,3]]
regressor_OLS=sm.OLS(endog = Y,exog = X_opt).fit()
regressor_OLS.summary()
|
def str_interval(x):
"""Return a string representation of interval x.
>>> str_interval(interval(-1, 2))
'-1 to 2'
"""
return '{0} to {1}'.format(lower_bound(x), upper_bound(x))
def add_interval(x, y):
"""Return an interval that contains the sum of any value in interval x and
any value in interval y.
>>> str_interval(add_interval(interval(-1, 2), interval(4, 8)))
'3 to 10'
"""
lower = lower_bound(x) + lower_bound(y)
upper = upper_bound(x) + upper_bound(y)
return interval(lower, upper)
def mul_interval(x, y):
"""Return the interval that contains the product of any value in x and any
value in y.
>>> str_interval(mul_interval(interval(-1, 2), interval(4, 8)))
'-8 to 16'
"""
p1 = lower_bound(x) * lower_bound(y)
p2 = upper_bound(x) * lower_bound(y)
p3 = lower_bound(x) * upper_bound(y)
p4 = upper_bound(x) * upper_bound(y)
return interval(min(p1,p2,p3,p4), max(p1,p2,p3,p4))
def interval(a, b):
"""Construct an interval from a to b."""
x = [a, b]
return x
def lower_bound(x):
"""Return the lower bound of interval x."""
return x[0]
def upper_bound(x):
"""Return the upper bound of interval x."""
return x[1]
def div_interval(x, y):
"""Return the interval that contains the quotient of any value in x divided
by any value in y.
Division is implemented as the multiplication of x by the reciprocal of y.
>>> str_interval(div_interval(interval(-1, 2), interval(4, 8)))
'-0.25 to 0.5'
"""
assert upper_bound(y) or upper_bound(y) == 0 , "division by zero"
reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))
return mul_interval(x, reciprocal_y)
def sub_interval(x, y):
"""Return the interval that contains the difference between any value in x
and any value in y.
>>> str_interval(sub_interval(interval(-1, 2), interval(4, 8)))
'-9 to -2'
"""
lower = upper_bound(y) - lower_bound(x)
upper = upper_bound(x) - lower_bound(y)
return interval(lower, upper)
def par1(r1, r2):
return div_interval(mul_interval(r1, r2), add_interval(r1, r2))
#par1 for (-3,0),(4,5) shows the interval to be (-15, 0), which is not right; probably due to simplification occuring at the the end of each function
def par2(r1, r2):
one = interval(1, 1)
rep_r1 = div_interval(one, r1)
rep_r2 = div_interval(one, r2)
return div_interval(one, add_interval(rep_r1, rep_r2))
#par2 for (-3,0),(4,5) shows the interval to be not computed = division by zero; checks to divide by zero or not
def quadratic(x, a, b, c):
y0 = a*(pow(x[0],2)) + b*(x[0]) + c
y1 = a*(pow(x[1],2)) + b*(x[1]) + c
h = ((-b)/(2*a))
k = a*(pow(h,2)) + b*(h) + c
if a < 0:
if x[0] > h or x[1] < h:
return interval(y0, y1)
elif x[0] < h and x[1] > h:
return interval(min(y0,y1), k)
elif a > 0:
if x[0] > h or x[1] < h:
return interval(y0, y1)
elif x[0] < h and x[1] > h:
return interval(k, min(y0, y1))
def polynomial(x, c):
"""Return the interval that is the range of the polynomial defined by
coefficients c, for domain interval x.
>>> str_interval(polynomial(interval(0, 2), [-1, 3, -2]))
'-3 to 0.125'
>>> str_interval(polynomial(interval(1, 3), [1, -3, 2]))
'0 to 10'
>>> str_interval(polynomial(interval(0.5, 2.25), [10, 24, -6, -8, 3]))
'18.0 to 23.0'
"""
|
print('Please enter some sentences. Type "quit" on a line by itself to quit.')
total = int(0)
average = int(0)
list1 = []
word_list=[]
num_word=0
x=input('')
while x != "quit":
list1.append(x)
x=input('')
for sentance in list1:
word_list=sentance.split()
num_word+=len(word_list)
total+=1
average = num_word/total
print("These sentences have an average of",format(average,'.2f'),"words.")
|
# -*- coding=utf-8 -*-
# Implementation of Charikar simhashes in Python
# See: http://dsrg.mff.cuni.cz/~holub/sw/shash/#a1
# ๆๆๅญ่ฝฌๅไธบhash
class SimhashBuilder:
def __init__(self, word_list=[], hashbits=128):
self.hashbits = hashbits
self.hashval_list = [self._string_hash(word) for word in word_list]
print('Totally: %s words' % (len(self.hashval_list),))
# with open('word_hash.txt', 'w') as outs:
# for word in word_list:
# outs.write(word+'\t'+str(self._string_hash(word))+os.linesep)
def _string_hash(self, word):
# A variable-length version of Python's builtin hash
if word == "":
return 0
else:
x = ord(word[0]) << 7
m = 1000003
mask = 2 ** self.hashbits - 1
for c in word:
x = ((x * m) ^ ord(c)) & mask
x ^= len(word)
if x == -1:
x = -2
return x
def sim_hash_nonzero(self, feature_vec):
finger_vec = [0] * self.hashbits
# Feature_vec is like [(idx,nonzero-value),(idx,nonzero-value)...]
for idx, feature in feature_vec:
hashval = self.hashval_list[int(idx)]
for i in range(self.hashbits):
bitmask = 1 << i
if bitmask & hashval != 0:
finger_vec[i] += float(feature)
else:
finger_vec[i] -= float(feature)
# print finger_vec
fingerprint = 0
for i in range(self.hashbits):
if finger_vec[i] >= 0:
fingerprint += 1 << i
# ๆดไธชๆๆกฃ็fingerprintไธบๆ็ปๅไธชไฝๅคงไบ็ญไบ0็ไฝ็ๅ
return fingerprint
def sim_hash(self, feature_vec):
finger_vec = [0] * self.hashbits
for idx, feature in enumerate(feature_vec):
if float(feature) < 1e-6:
continue
hashval = self.hashval_list[idx]
for i in range(self.hashbits):
bitmask = 1 << i
if bitmask & hashval != 0:
finger_vec[i] += float(feature)
else:
finger_vec[i] -= float(feature)
# print finger_vec
fingerprint = 0
for i in range(self.hashbits):
if finger_vec[i] >= 0:
fingerprint += 1 << i
# ๆดไธชๆๆกฃ็fingerprintไธบๆ็ปๅไธชไฝๅคงไบ็ญไบ0็ไฝ็ๅ
return fingerprint
def _add_word(self, word):
self.hashval_list.append(self._string_hash(word))
def update_words(self, word_list=[]):
for word in word_list:
self._add_word(word)
|
# -*- coding:utf-8 -*-
import numpy as np
import random
# Object oriented approach
class RandomWalker:
def __init__(self):
self.position = 0
def walk(self, n):
self.position = 0
for i in range(n):
yield self.position
self.position += 2*random.randint(0, 1) - 1
def random_walk(n):
position = 0
walk = [position]
for i in range(n):
position += 2*random.randint(0, 1)-1
walk.append(position)
return walk
def random_walk_faster(n=1000):
from itertools import accumulate
# Only available from Python 3.6
steps = random.choices([-1,+1], k=n)
return [0]+list(accumulate(steps))
def random_walk_fastest(n=1000):
# No 's' in numpy choice (Python offers choice & choices)
steps = np.random.choice([-1,+1], n)
return np.cumsum(steps)
if __name__ == '__main__':
walker = RandomWalker()
walk = [position for position in walker.walk(1000)]
print(walk)
|
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
def data_filter_sort(data_path):
# ๅผๅ
ฅๆฐๆฎ
chipo = pd.read_csv(url_local, sep='\t')
# ๆpriceๅ่ฝฌๆขไธบfloatๆ ผๅผ
dollarizer = lambda x: float(x[1:-1])
chipo['item_price'] = chipo['item_price'].apply(dollarizer)
# ๅ ้คๆ้ๅค็ๆฐๆฎ
chipo.filtered = chipo.drop_duplicates(['item_name', 'quantity'])
# ๆ้ๅบquantityไธบ1๏ผไธไปทๆ ผๅคงไบ10็ไบงๅ
chipo_one_prod = chipo.filtered[chipo['quantity'] == 1]
print(chipo_one_prod[chipo_one_prod['item_price'] > 10].item_name.unique())
# ๆฏไธช็ฉๅ็ไปทๆ ผๆฏๅคๅฐ
price_per_item = chipo_one_prod[['item_name', 'item_price']]
price_per_item = price_per_item.sort_values(by='item_price', ascending=False)
print(price_per_item)
# ๆ นๆฎๅๅๅๅญๆๅบ
print(chipo['item_name'].sort_values())
# ๆ่ดต็ๅๅ่ขซ็นไบๅคๅฐๆฌก
most_expensive_item = price_per_item.at[0, 'item_name']
print(most_expensive_item)
print(chipo[chipo['item_name'] == most_expensive_item]['quantity'].sum)
# Veggie Salad Bowl่ขซ็นไบๅคๅฐๆฌก
print(chipo[chipo['item_name'] == 'Veggie Salad Bowl']['quantity'].sum())
# ๆๅคๅฐๆฌก้กพๅฎข็นไบๅคงไบไธ็ฝ็Canned Soda
chipo_drink_steak_cans = chipo[(chipo['item_name'] == 'Canned Soda') & (chipo['quantity'] > 1)]
print(len(chipo_drink_steak_cans))
if __name__ == '__main__':
url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv'
url_local = '/apps/data/ai_nlp_testing/raw/pandas_exercises/chipotle.tsv'
data_filter_sort(url_local)
|
# -*- coding:utf-8 -*-
from pyhanlp import *
# ็จๆท่ชๅฎไน่ฏๅ
ธ
class CustomisedDict:
def __init__(self):
self.CustomDictionary = JClass("com.hankcs.hanlp.dictionary.CustomDictionary")
# def add(self, word):
# self.CustomDictionary.add(word)
def add(self, word, nature_with_freq=None):
self.CustomDictionary.add(word, nature_with_freq)
def insert(self, word, nature_with_freq):
self.CustomDictionary.insert(word, nature_with_freq)
def remove(self, word):
self.CustomDictionary.remove(word)
def get(self, word):
return self.CustomDictionary.get(word)
# test
if __name__ == '__main__':
text = "ๆปๅ็ฎ้่ขญๅ่บซ็๏ผ่ฟๅจถ็ฝๅฏ็พ๏ผ่ตฐไธไบบ็ๅท
ๅณฐ"
print(HanLP.segment(text))
customized_dict = CustomisedDict()
# ็จๆท่ชๅฎไน่ฏๅ
ธ
customized_dict.add('ๆปๅ็ฎ')
customized_dict.insert('็ฝๅฏ็พ', 'nz 1024')
# ๅ ้ค่ฏ่ฏญ
# customized_dict.remove('ๆปๅ็ฎ')
customized_dict.add('ๅ่บซ็', 'nz 1024 n 1')
print(customized_dict.get('ๅ่บซ็'))
print(HanLP.segment(text))
|
import numpy as np
import matplotlib.pyplot as plt
from scipy.odr import *
import random
def odr_demo():
# Initiate some data, giving some randomness using random.random().
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([i ** 2 + random.random() for i in x])
# Define a function (quadratic in our case) to fit the data with.
def linear_func(p, x):
m, c = p
return m * x + c
# Create a model for fitting.
linear_model = Model(linear_func)
# Create a RealData object using our initiated data from above.
data = RealData(x, y)
# Set up ODR with the model and data.
odr = ODR(data, linear_model, beta0=[0., 1.])
# Run the regression.
out = odr.run()
# Use the in-built pprint method to give us results.
out.pprint()
if __name__ == '__main__':
odr_demo()
|
# -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
from scipy.spatial import Delaunay
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
def spatial():
# Delaunayไธ่ง
points = np.array([[0, 4], [2, 1.1], [1, 3], [1, 2]])
tri = Delaunay(points)
plt.triplot(points[:, 0], points[:, 1], tri.simplices.copy())
plt.plot(points[:, 0], points[:, 1], 'o')
plt.show()
# ๅ
ฑ้ข็น
points = np.array([[0, 0], [0, 1], [1, 0], [1, 1], [1, 1]])
tri = Delaunay(points)
print(tri.coplanar)
# ๅธๅฃณ
points = np.random.rand(10, 2) # 30 random points in 2-D
hull = ConvexHull(points)
plt.plot(points[:, 0], points[:, 1], 'o')
for simplex in hull.simplices:
plt.plot(points[simplex, 0], points[simplex, 1], 'k-')
plt.show()
if __name__ == '__main__':
spatial()
|
#Simple Caesar cypher.
from string import *
from collections import deque
def key(n): #Slightly round-about way of generating the lookup-table, in order to preserve case
lower = deque(ascii_lowercase)
upper = deque(ascii_uppercase)
lower.rotate(n)
upper.rotate(n)
return list(lower)+list(upper)
def encrypt(s, n):
return ''.join(ascii_letters[key(n).index(c)] for c in s)
def decrypt(s, n):
return ''.join(key(n)[ascii_letters.index(c)] for c in s)
op, text, n = input().split()
if op == 'e':
print(encrypt(text, int(n)))
elif op == 'd':
print(decrypt(text, int(n)))
else:
print('Unknown option, use "d/e text n"') |
from math import factorial
def pascal(n,k):
n, k = n-1, k-1
if k>n:
return "No such number"
return factorial(n)//(factorial(k)*factorial(n-k))
print(pascal(*map(int, input().split()))) |
#Functional programming killed the Python
from itertools import chain, zip_longest
dataz = []
for _ in range(int(input())):#Read input lines from stdin
dataz.append(input())
words = list(chain.from_iterable(map(str.split, dataz))) + list(chain.from_iterable(map(str.split, map(''.join, zip_longest(*dataz, fillvalue=' '))))) #Split words, both horizontally ad vertically
with open('dictionary.txt', 'r') as f: #Load a dictionary
dictionary = set(map(str.strip, f.readlines()))
def greed(word): #Greedy match. Note lack of spaghetti code
if len(word) < 3:
return ''
if word.lower() in dictionary:
return word
if word.lower()[::-1] in dictionary:
return word[::-1]
return max(greed(word[1:]), greed(word[:-1]), key=len)
for w in sorted(w for w in map(greed, words) if w ): #Filtering and worting
print(w.lower()) |
"""
## Problem1 Kth Smallest Element in a BST (https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/)
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 โค k โค BST's total elements.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
TIME- O(maxdepth)
SPACE - O(maxdepth)
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
stack = []
count = 0
while root != None or stack != []:
while root != None: #go left left left and keep append the roots to stack
stack.append(root)
root = root.left
top = stack.pop() # at en dof left start poping
count += 1 # keep count of pops, popped element will be in ascending order - inorder of BST
if k == count: # when count is equal to k RETURN TOP.VAL
return top.val
root = top.right # AFTER POP go to right of popped/top node
|
"""
// Time Complexity :O(n) where n=number of words
// Space Complexity :O(1) two hashmaps will store 26*2 keys
// Did this code successfully run on Leetcode :Not LC problem
// Any problem you faced while coding this :
"""
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if (len(s)!=len(t)):
return False
sHashMap={}
tHashMap={}
for char in range(len(s)):
schar=s[char]
tchar=t[char]
if schar not in sHashMap: # if key does not exist add
sHashMap[schar]=t[char]
elif sHashMap.get(schar)!=t[char]:#If existing key does not match with char
return False
if tchar not in tHashMap:
tHashMap[tchar]=s[char]
elif tHashMap.get(tchar)!=s[char]:
return False
return True
if __name__=="__main__":
so=Solution()
s="egg"
t="add"
print(so.isIsomorphic(s,t))
|
def bracket (a,f,s=0.01,m=2): #f รฉ para avaliar, #s รฉ o passo, m รฉ o multiplicador para acelerar o processo.
bracket = [a] #criando vetor com o intervalo desejado. # a=-2
#print("\nprimeiro bracket:",bracket)
b = a + s # รฉ um ponto b tal que รฉ a soma de a + o passo, para avaliar se o prรณximo ponto รฉ maior ou menor, tem de ser menor pois quer minimizar.
bracket = [a,b] #criando vetor com o intervalo desejado. # a=-2 ; b = -2+0.01=-1.99
#print("\n\nsegundo bracket:",bracket)
fa = f(a) #valor da funรงรฃo no ponto a, indo para fa, ou seja, รฉ a^2
#print("\nimpriminfo fa",fa,"\n")
fb = f(b) #valor da funรงรฃo no ponto b, indo para fb,ou seja, รฉ b^2
#print("\nimpriminfo fb",fb,"\n")
if fa>=fb :
c = b + s #criando ponto para encontrar o mรญnimo preservando o ponto a.
fc = f(c)
while fc < fb: #encontrando o mรญnimo comparando pontos.
b = c
fb = fc
s = s*m
c = c + s
fc = f(c)
print("\naqui estรก procurando-se o menor valor de b\nvalors de b:",b,"valors de b:",c)
print("fb",fb,"valor de fc",fc)
bracket = [a,c] #criando vetor com o intervalo desejado.
print("\n\nvalor encontrado minimizando: ",bracket,)
elif fa < fb :
c = a - s
fc = f(c)
while fc < fa :
a = c
fa = fc
s = s*m
c = c - s
bracket = [c,b] #criando lista com C e B
print("\n\nquarto bracket:",bracket)
return bracket
f = lambda x: x**2 # f รฉ minha funรงรฃo
b = bracket(-2,f)
print("\n\n\nbreacket final",b)
|
print("printing all alphabets from a-z")
initialASCIIValue=int(input())
finalASCIIValue=int(input())
while(initialASCIIValue>0):
print(chr(initialASCIIValue))
initialASCIIValue=initialASCIIValue+1
if(initialASCIIValue==finalASCIIValue):
break
|
initialValue=int(input("Enter the Number : "))
inputNumber=int(input("Enter the Number : "))
sumValue=0
for number in range(initialValue,inputNumber+1):
if(number>1):
for i in range(2,number):
if((number%i) == 0):
break
else:
sumValue=sumValue+number
print(sumValue)
|
def firstDigit(number):
while(number>=10):
number=number/10
return int(number)
def lastDigit(number):
while(number>0):
return number%10
number=int(input("Enter the Number : "))
firstDigit(number)
lastDigit(number)
print("Sum of First and last digit is :",(firstDigit(number)+lastDigit(number)))
|
digit=int(input("Enter the number : "))
temp=digit
count=0
while(temp>0):
temp=temp//10
count=count+1
print("Number of digits in number is :", count)
|
from arrays import Array2D
# Open the text file for reading.
grade_file = open( "grade.txt", "r" )
# Extract the first two values which indicate the size of the array.
num_students = int( grade_file.readline() )
num_exams = int( grade_file.readline() )
# Create the 2 -D array to store the grades.
exam_grades = Array2D( num_students, num_exams )
# Extract the grades from the remaining lines.
i = 0
for student in grade_file :
grades = student.split()
for j in range( num_exams ):
exam_grades[i,j] = int( grades[j] )
i += 1
# Close the text file.
grade_file.close()
# Compute each student's average exam grade.
for i in range( num_students ) :
# Tally the exam grades for the ith student.
total = 0
for j in range( num_exams ) :
total += exam_grades[i,j]
# Compute average for the ith student.
exam_avg = total / num_exams
print( "{:2d}: {:6.2f}".format(i+1, exam_avg) )
# Add 2 points to every grade.
for row in range(exam_grades.num_rows()):
for col in range(exam_grades.num_cols()):
grade = exam_grades[row,col]
grade = grade + 2
exam_grades[row,col] = grade |
import sqlite3
def LoadDataBase(name):
conn=sqlite3.connect(name)
cur=conn.cursor()
cur.execute("CREATE TABLE Usuarios(email text primary key, name text, password text);")
conn.commit()
conn.close()
def save(email, name, password):
conn=sqlite3.connect("DataBase")
cur=conn.cursor()
cur.execute("SELECT * FROM Usuarios;")
print("Se registra correctamente")
cur.execute("INSERT INTO Usuarios(email, name, password) VALUES ('"+email+"','"+name+"','"+password+"');")
conn.commit()
conn.close()
def init(email, password):
conn=sqlite3.connect("DataBase")
cur=conn.cursor()
cur.execute("SELECT * FROM Usuarios WHERE email='"+email+"';")
datos=cur.fetchall()
print(datos)
usuario = datos[0][1]
if datos[0][2] == password:
conn.commit()
conn.close()
return "Hola "+usuario+" :)"
else:
conn.commit()
conn.close()
return "Contraseรฑa incorrecta"
|
"""
Calculates the minimum edit distance between two strings.
In other words, minimum number of operations to convert a to b.
Also known as the Levenshtein algorithm.
Arguments:
1. a: string
2. b: string
3. cost: (cost of making an edit) int {default 1}
"""
from memoize import memoize
@memoize
def minimum_edit_distance(a, b, cost_insert_delete=1, cost_substitution=2):
if(not all(isinstance(arg, str) for arg in [a, b])):
raise Exception("Please pass strings!")
if(len(a) == 0):
return(len(b))
elif(len(b) == 0):
return(len(a))
else:
return(
min(
minimum_edit_distance(a[1:], b, cost_insert_delete) + cost_insert_delete,
minimum_edit_distance(a, b[1:], cost_insert_delete) + cost_insert_delete,
minimum_edit_distance(a[1:], b[1:], cost_insert_delete) + (
lambda x, y, cost: 0 if x[0] == y[0] else cost)(a, b, cost_substitution
)
)
)
|
import time
import re
# main() calculates number of possible passwords
def main():
meet = 0
doubles = False
ascending_sequence = True
initial_time = time.time()
try:
with open("data.txt", "r") as input:
given_range_str = input.read()
given_range_list = re.split("-", given_range_str)
for password in range(int(given_range_list[0]), int(given_range_list[1])+1):
password_string = str(password)
if len(password_string) != 6:
continue
for digit in range(len(password_string)-1):
if password_string[digit] == password_string[digit+1]:
doubles = True
elif password_string[digit] > password_string[digit+1]:
ascending_sequence = False
continue
if doubles and ascending_sequence:
meet += 1
doubles = False
ascending_sequence = True
except FileNotFoundError:
print("File not found")
except:
print("Error found")
print("met-criteria passwords: ", meet)
elapsed_time = time.time() - initial_time
print('time: {} secs'.format(elapsed_time))
return elapsed_time
# avg_time calculates average proccesing time for the indicated number of tests
def avg_time(number_of_tests):
return print("average time:",
sum([main() for _ in range(number_of_tests)]) / number_of_tests)
if __name__ == '__main__':
main()
|
import MapReduce
import sys
"""
@ jim pizagno 06.06.2014
This code will take data from a sparse matrix "a" and multiply it times
sparse matrix "b".
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: column of final matrix
# value: row/column of final matrix
if record[0] == "a":
i = record[1]
j = record[2]
value = record[3]
for k in range(0,5):
emit = str(i) + "," + str(k)
mr.emit_intermediate( emit , ["a", j, value])
else:
j = record[1]
k = record[2]
value = record[3]
for i in range(0,5):
emit = str(i) + "," + str(k)
mr.emit_intermediate( emit , ["b", j , value])
def reducer(key, list_of_values):
# key: column of final matrix
# value: sum of values
list_A = [0,0,0,0,0]
list_B = [0,0,0,0,0]
for value in list_of_values:
if value[0] == "a":
list_A[value[1]] = value[2]
if value[0] == "b":
list_B[value[1]] = value[2]
sum = 0
for j in range(0,5):
sum += list_A[j] * list_B[j]
i = key.split(",")[0]
j = key.split(",")[1]
mr.emit(( int(i) , int(j) , sum))
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
# Bonus:
# cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.
# For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
#
#
def cons(a, b) -> int:
return lambda f: f(a,b)
def cdr(f):
return f(lambda a, b: a)
def car(f):
return f(lambda a, b: b)
if __name__ == '__main__':
print(cdr(cons(3,4))) |
from itertools import groupby
# Question 1.6
# Implement a method to perform basic string compression usng the counts of repeated characters.
#
# (1) Grouping by chars with groupby(string)
# (2) Counting length of group with sum(1 for _ in group) (because no len on group is possible)
# (3) Joining into proper format
# (4) Removing 1 chars for single items
#
def string_compress(string: str) -> str:
return ''.join('%s%s' % (char, sum(1 for char in group)) for char, group in groupby(string)).replace('1', '')
|
import numpy as np
import time
#Fibonacci para python
def Fibonacci(N):
if(N<2):
return 1
else:
return (Fibonacci(N-1)+Fibonacci(N-2))
#sacar tiempo para comparar, se hace un for para guardar N y el tiempo para cada iteracion
enes=[]
tiemposenes=[]
for i in range(36):
enes.append(i)
t0=time.time()
Fibonacci(i)
t1=time.time()-t0
tiemposenes.append(t1)
print enes
print tiemposenes
|
# =========== define objective function for unsupervised competitive learning ==========
def bingo(y_true, y_pred):
# y_true can be ignored
# find the biggest 3 outputs
threshold = np.partition(y_pred, -3)[-3] # last 3 elements would be biggest
loss = map( lambda y:
if y >= threshold:
(1 - y) # if it is the winner, ideal value = 1.0
else:
(y) # if it is loser, ideal value = 0.0
, y_pred)
return np.array(loss)
|
"""
@author JungBok Cho
@version 1.0
"""
import time
# Word list file
WORDSLIST = "words.txt"
# Pairs file
PAIRLIST = "pairs.txt"
# Dictionary to store every word
dictionary = dict()
# Minimum and Maximum of word length
wordMin, wordMax = 4, 6
def readWordsFile():
""" Function to read word list file
and store every word in the dictionary. """
file = open(WORDSLIST, "r")
for line in file:
line = line.strip()
if wordMin <= len(line) <= wordMax:
# Store words separately depending on the word length
if len(line) in dictionary:
dictionary.get(len(line)).add(line)
else:
dictionary[len(line)] = set()
dictionary.get(len(line)).add(line)
file.close()
def readPairsFile():
""" Function to read pairs file and
call findPath function to initiate the BFS. """
file = open(PAIRLIST, "r")
count = 1
for line in file:
line = line.strip()
tempList = line.split(" ")
# Get beginning and ending words
begWord = tempList.pop(0)
endWord = tempList.pop(0)
print(count, end="")
print(". Beginning word: " + begWord + ", Ending word: " + endWord)
# Call findPath function and measure the speed using timeit class
start = time.time()
result = findPath(dictionary.get(len(begWord)), begWord, endWord)
end = time.time()
# Print the result
if isinstance(result, str):
print(" - " + result)
else:
print("Path: ", end="")
print(result)
print("Time in seconds: {}".format(end - start))
print()
count += 1
file.close()
def findPath(tempDictionary, begWord, endWord):
""" Find the shortest path between words with Breath First Search """
if len(begWord) != len(endWord):
return "Length of pairs must be equivalent"
elif not (wordMin <= len(begWord) <= wordMax and
wordMin <= len(endWord) <= wordMax):
return "Path does not exist"
elif begWord == endWord:
return [begWord]
else:
if begWord in tempDictionary and endWord in tempDictionary:
visited = set() # Set to check if word was visited
visited.add(begWord)
queue = [[begWord]] # Create a queue of lists
# Process until the queue is empty
while len(queue) > 0:
currList = queue.pop(0)
# List to store a cut-down version of tempDictionary
tempList = []
smallerTempDictionary(currList, tempDictionary, tempList, visited)
# Using unvisited words, create new currLists and append to the queue
for currWord in tempList:
if currWord not in currList:
temp = currList[:]
temp.append(currWord)
if temp[-1] == endWord:
return temp
queue.append(temp)
return "Path does not exist"
def smallerTempDictionary(currList, tempDictionary, tempList, visited):
""" Create a cut-down version of tempDictionary """
# Find all the words that are one letter apart
# from the last word in the currList
for i in range(len(currList[-1])):
for char in range(ord('a'), ord('z') + 1):
word = currList[-1][:i] + chr(char) + currList[-1][i + 1:]
if word in tempDictionary and word != currList[-1] and word not in visited:
tempList.append(word)
visited.add(word)
def _main():
""" Main function to print Hello and Goodbye messages
and call readWordsFile and readPairsFile functions"""
print("\nWelcome to Word Ladder program.\n")
print("These are the files you are using:")
print("Word List file:", WORDSLIST)
print("Pair List file:", PAIRLIST, "\n")
readWordsFile()
readPairsFile()
print("Thank you for playing this program!\n")
""" Call main method if this file is main module """
if __name__ == '__main__':
_main()
|
# 0 = not cute / 1 = cute
N = int(input())
cute = 0
notcute = 0
for i in range(1, N+1) :
opinion = int(input())
if opinion == 1 :
cute += 1
elif opinion == 0 :
notcute += 1
if cute > notcute :
print('Junhee is cute!')
else :
print('Junhee is not cute!') |
print('QUESTรO 05')
def acoes_bolsa(lista):
d1 = 0
d4 = 4
s= sum(lista[d1:d4])
for c in range(len(lista)-3):
soma = sum(lista[d1:d4])
d1 += 1
d4 += 1
if soma > s:
s = soma
return s
print(acoes_bolsa([-1,-2,-3,-4,-5,-6,-7,-8]))
|
import turtle
turtle.shape('turtle')
finn = turtle.clone()
finn.shape('square')
finn.color('yellow')
finn.goto(100,0)
finn.goto(100,100)
finn.goto(0,100)
finn.goto(0,0)
charlie = turtle.Turtle()
charlie.shape = ('triangle')
charlie.color('blue')
charlie.goto(100,100)
charlie.goto(200,0)
charlie.goto(0,0)
finn.goto(-400,100)
finn.stamp()
finn.goto(-100,100)
charlie.goto(-400,-100)
charlie.stamp()
charlie.goto(-100,-100)
turtle.mainloop()
|
"""
N,M์ด ์ฃผ์ด์ง๋ค. M์ ์
๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ ์ฐ์ฐ์ ๊ฐ์
M๊ฐ์ ์ค์๋ ๊ฐ๊ฐ์ ์ฐ์ฐ์ด ์ฃผ์ด์ง๋ค
'ํ ํฉ์น๊ธฐ' ์ฐ์ฐ์ 0, a, b ํํ๋ก ์ฃผ์ด์ง๋ค. ์ด๋ a๋ฒ ํ์์ด ์ํ ํ๊ณผ b๋ฒ ํ์์ด ์ํ ํ์ ํฉ์น๋ค๋ ์๋ฏธ
'๊ฐ์ ํ ์ฌ๋ถ ํ์ธ' ์ฐ์ฐ์ 1, a, b ํํ๋ก ์ฃผ์ด์ง๋ค. ์ด๋ a๋ฒ ํ์๊ณผ b๋ฒ ํ์์ด ๊ฐ์ ํ์ ์ํด ์๋ ์ง๋ฅผ ํ์ธํ๋ ์ฐ์ฐ์ด๋ค
a,b๋ N ์ดํ์ ์์ ์ ์์ด๋ค
'๊ฐ์ ํ ์ฌ๋ถ ํ์ธ' ์ฐ์ฐ์ ๋ํ์ฌ ํ์ค์ ํ๋์ฉ yes ํน์ no๋ก ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ค
"""
# ํน์ ์์๊ฐ ์ํ ์งํฉ์ ์ฐพ๊ธฐ
def find_parent(parent, x):
# ๋ฃจํธ ๋
ธ๋๊ฐ ์๋๋ผ๋ฉด ๋ฃจํธ ๋
ธ๋๋ฅผ ์ฐพ์ ๋ ๊น์ง ์ฌ๊ท์ ์ผ๋ก ํธ์ถ
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
# ๋ ์์๊ฐ ์ํ ์งํฉ์ ํฉ์น๊ธฐ
def union_parent(parent, a, b):
a = find_parent(parent, b)
b = find_parent(parent, a)
if a < b:
parent[b] = a
else:
parent[a] = b
# n,m ์
๋ ฅ๋ฐ๊ธฐ
n, m = map(int, input().split())
# ๋ถ๋ชจ ํ
์ด๋ธ ์ด๊ธฐํ
parent = [0] * (n + 1)
# ๋ถ๋ชจ ํ
์ด๋ธ ์์์ ๋ถ๋ชจ๋ฅผ ์๊ธฐ ์์ ์ผ๋ก ์ด๊ธฐํ
for i in range(0, n + 1):
parent[i] = i
# ๊ฐ ์ฐ์ฐ์ ํ๋์ฉ ํ์ธ
for i in range(m):
oper, a, b = map(int, input().split())
# ํฉ์งํฉ ์ฐ์ฐ์ธ ๊ฒฝ์ฐ
if oper == 0:
union_parent(parent, a, b)
# ์ฐพ๊ธฐ ์ฐ์ฐ์ธ ๊ฒฝ์ฐ
elif oper == 1:
if find_parent(parent, a) == find_parent(parent, b):
print('YES')
else:
print('NO')
|
#!/usr/bin/env python3
# Return the number of unique pairs from a list that sum up to a given integer
def numberOfPairs(a, k):
uniques = set()
for i,x in enumerate(a):
idx = 0
for y in a[i:]:
if x == y and idx == 0:
idx += 1
elif x + y == k
uniques.add("".join(str(n) for n in sorted([x,y])))
return len(uniques)
if __name__ == "__main__":
assert numberOfPairs([1,3,46,1,3,9], 47) == 1
assert numberOfPairs([6,6,3,9,3,5,1], 12) == 2
assert numberOfPairs([1,1,1,1], 2) == 1
print("All tests passed!")
|
import pprint
import pandas as pd
import math
import numpy as np
"""
The program implements the ID3 algorithm to generate the decision tree for classification
and the decision tree would be saved in a dictionary in hierarchy structure.
This is not a generalize program to receive any data format.
It is actually only designed for finishing our assignment.
"""
attributes_values = {
'Department': ['Research & Development', 'Sales', 'Human Resources'],
'BusinessTravel': ['Travel_Rarely', 'Travel_Frequently', 'Non-Travel'],
'EducationField': ['Life Sciences', 'Medical', 'Marketing'],
'MonthlyIncome': ['<5881', '>=5881'],
'Age': ['<38', '>=38']
}
def split(data, attribute, value):
"""
Splitting examples and dropping the attribute of splitting
:param data: The examples
:param attribute: The attribute for splitting determining how to split the example
:param value: The value of the attribute for splitting
:return: Return the subset of the example after splitting
"""
subset = data.loc[data[attribute] == value]
# drop column from current list
subset = subset.drop([attribute], axis=1)
return subset
def is_end_with_same_label(data):
"""
To tell if the examples only contain ony a class of label
:param data: the example
:return: If the example only contains one label, then return false
"""
# every elements are in the same class
if 'Yes' in data['Attrition'].values and 'No' not in data['Attrition'].values:
return 'Yes'
else:
if 'Yes' not in data['Attrition'].values and 'No' in data['Attrition'].values:
return 'No'
def entropy(positive, negative, total):
"""
To calculate the entropy. Looks stupid but works for the binary label.
:param positive: the number positive
:param negative: the number of negative
:param total: the total total number positive and negative
:return: the entropy
"""
if positive == 0 and negative == 0:
return 0
if positive != 0 and negative == 0:
return -(positive / total) * math.log((positive / total), 2)
if positive == 0 and negative != 0:
return -(negative / total) * math.log((negative / total), 2)
if positive != 0 and negative != 0:
return -(positive / total) * math.log((positive / total), 2) - (negative / total) * math.log((negative / total), 2)
def compute_info_gain(root_entropy, counts, total):
"""
Compute the information gain for the target attribute. The function is specialized only for the attribute that
has three
:param root_entropy: The entropy of the splitting attribute
:param counts: The counts consists of
[total number of first values, positive number of first value,
second number of second value, positive number of second value
...]
:param total: The total number of attributes
:return: the information gain for the the attributes
"""
entropy_sum = 0
print(range(0, int(len(counts)/2)))
i = 0
while i < len(counts):
entropy_sum += counts[i] / total * entropy(counts[i+1], counts[i] - counts[i+1], counts[i])
i += 2
info_gain = root_entropy - entropy_sum
return info_gain
def get_category_info_gain(data, attribute, values, root_entropy, total):
"""
Counts the label and compute the information gain
"""
counts = []
for value in values:
counts.append(data.loc[data[attribute] == value].count()[attribute])
counts.append(data.loc[data[attribute] == value].loc[data['Attrition'] == 'Yes'].count()[attribute])
return compute_info_gain(root_entropy, counts, total)
def compute_all(data):
"""
Compute the information gain of each attribute. The function is specialized only for our data format.
:param data:
:return: A dictionary of the information gain
"""
# Terminate when there is no more attribute to be selected
if len(data.columns) is 1:
# return yes or no when there are only one class
if is_end_with_same_label(data) == 'Yes' or is_end_with_same_label(data) == 'No':
return is_end_with_same_label(data)
# return the most common class
yes_count = data['Attrition'].tolist().count('Yes')
no_count = data['Attrition'].tolist().count('No')
if yes_count > no_count:
return 'Yes'
else:
return 'No'
# terminate when all element is in the same class
if is_end_with_same_label(data) == 'Yes' or is_end_with_same_label(data) == 'No':
return is_end_with_same_label(data)
root_entropy = entropy(data['Attrition'].value_counts()['Yes'],
data['Attrition'].value_counts()['No'],
len(data.index)
)
result = {}
attribute_list = data.columns.tolist()
attribute_list.remove('Attrition')
for key in attribute_list:
result[key] = get_category_info_gain(data, key, attributes_values[key],
root_entropy,
len(data.index))
return result
def run(data, k, tree_dict):
"""
This is recursive function that recursively split examples and save the decision tree in the dictionary
:param data:
:param k: The tree depth
:param tree_dict: The dictionary holds the decision tree
:return: Return the current level of decision tree
"""
k = k
result = compute_all(data)
# terminate when all element is in the same class
if result == 'Yes' or result == 'No' or result is None:
tree_dict['Result'] = result
print(result)
print('---------------------------------------')
else:
# else continue to find the maximum info and split
max_info_gain_attr = max(result, key=result.get)
possible_attributes = attributes_values[max_info_gain_attr]
# Split
for value in possible_attributes:
print('The ' + max_info_gain_attr + ' is the max at level ' + str(k))
print('Inspecting Condition ' + str(value))
sub_data = split(data, max_info_gain_attr, value)
if sub_data.size == 0:
yes_count = data['Attrition'].tolist().count('Yes')
no_count = data['Attrition'].tolist().count('No')
if yes_count > no_count:
print('Yes')
if max_info_gain_attr not in tree_dict.keys():
tree_dict = {max_info_gain_attr: {}}
tree_dict[max_info_gain_attr][value] = {'Result': 'Yes'}
else:
tree_dict[max_info_gain_attr][value] = {'Result': 'Yes'}
print('---------------------------------------')
else:
print('No')
if max_info_gain_attr not in tree_dict.keys():
# tree_dict = {max_info_gain_attr: {}}
tree_dict.update({max_info_gain_attr: {}})
tree_dict[max_info_gain_attr][value] = {'Result': 'No'}
else:
tree_dict[max_info_gain_attr][value] = {'Result': 'No'}
print('---------------------------------------')
else:
if max_info_gain_attr not in tree_dict.keys():
branch = {}
tree_dict.update({max_info_gain_attr: {value: branch}})
run(sub_data, k + 1, branch)
else:
branch = {}
tree_dict[max_info_gain_attr][value] = branch
run(sub_data, k + 1, branch)
return tree_dict
if __name__ == '__main__':
data = pd.read_csv('training_data.csv')
data = data[['Age', 'Attrition', 'BusinessTravel', 'Department', 'EducationField', 'MonthlyIncome']]
print('Start:')
tree_dict = {}
run(data, 0, tree_dict)
pprint.pprint(tree_dict)
np.save('tree', tree_dict)
|
import collections
class SymbolTable(collections.MutableMapping):
def __init__(self):
"""Initialize the symbol table to a stack with global scope"""
self.stack = []
self.push()
return
def push(self):
"""Pushes and returns an empty dictionary onto the symbol table"""
d = {}
self.stack.append(d)
return d
def pop(self):
"""Removes and returns the top-level symbol dictionary"""
v = self.stack[-1]
del self.stack[-1]
return v
def __len__(self):
"""Return total number of elements in the symbol table"""
return sum(map(len, self.stack))
def __iter__(self):
"""Iterator to the stack"""
for d in reversed(self.stack):
for k in d:
yield k
return
def top(self, symbol):
"""Look in the top level of the symbol table for the symbol"""
return self.stack[-1].get(symbol)
def __getitem__(self, symbol):
"""Get the value that is stored under symbol"""
for d in reversed(self.stack):
v = d.get(symbol)
if v is not None:
return v
return None
def __setitem__(self, symbol, value):
"""Set the value of symbol to be value"""
self.stack[-1][symbol] = value
return
def __delitem__(self, symbol):
"""Deletes and returns the item associated with symbol"""
for d in reversed(self.stack):
v = d.get(symbol)
if v is not None:
item = v
del d[symbol]
return item
return None
def find(self, symbol):
"""Returns a integer that gives the position of the symbol in the table"""
for i in reversed(range(self.num_levels)):
if symbol in self.stack[i]:
return i
return -1
@property
def functions(self):
"""Returns a dict of the functions that are in the global scope"""
return self.stack[0]
@property
def num_levels(self):
"""Returns the number of levels of the symbol table"""
return len(self.stack)
|
"""
CMSC 12300 / CAPP 30123
Task: Descriptive analysis (Exploring Questions)
Main author: Sanittawan (Nikki)
"""
import csv
import re
from mrjob.job import MRJob
class GetMaxAnsQuest(MRJob):
"""
A class for finding questions with the most
number of answers per year from 2008 to 2019 using
a MapReduce framework
"""
def mapper(self, _, line):
"""
Maps year to answer counts and title of the question
Inputs:
line: a single line in a CSV file
Returns: a year as key and a tuple of answer counts and
title
"""
row = csv.reader([line]).__next__()
try:
post_type = int(row[1])
if post_type == 1:
create_date = row[4]
search = re.search(r"20[01][0-9]", create_date)
if search:
year = search.group()
title = row[13]
answer_counts = row[15]
yield year, (int(answer_counts), title)
except (IndexError, ValueError):
pass
def combiner(self, year, val):
"""
Combine counts of all unique bi-grams
Inputs:
year: (string) the year the question was posted
val: (tuple) of number of answers and title
Returns: a year and a tuple containing the maximum number of
answer counts
"""
try:
max_ans = max(val)
yield year, max_ans
except (TypeError, ValueError):
pass
def reducer(self, year, val):
"""
Reduce all counts of a unique bi-gram tag
Inputs:
year: (string) the year the question was posted
val: (tuple) of number of answers and title
Returns: a year and a tuple containing the maximum number of
answer counts
"""
try:
max_ans = max(val)
yield year, max_ans
except (TypeError, ValueError):
pass
if __name__ == '__main__':
GetMaxAnsQuest.run()
|
def listtGenerator():
lst1 = []
for i in range(10,100):
lst1.append(i)
i += 1
return lst1
def Generate_table(number):
n = 1
lst = []
for i in range(10):
i = n*number
n = n+1
lst.append(i)
return lst
def WrongTable(table):
import random
rand = random.choice(lst)
for item in table:
if item > 10:
item = rand
else:
pass
return table
if __name__ == '__main__':
import random
table_of_no = int(input("Please enter the number you want to get the table\n"))
table = Generate_table(table_of_no)
lst = listtGenerator()
tableW = WrongTable(table)
print(tableW)
|
"""
A simple PyQt5 UI example
Created by: Jacob Lewis
Date: June 8th, 2016
"""
import sys
import numpy as np
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
V_NUM = "0.1"
class CircleCanvas(QGraphicsView):
"""
Renders the circle
"""
def __init__(self, circleCheckbox, parent=None):
super(CircleCanvas, self).__init__(parent)
self.circleCheckbox = circleCheckbox
def paintEvent(self, QPaintEvent):
qp = QPainter(self.viewport())
qp.fillRect(QRect(0, 0, self.width(), self.height()), QColor(200, 200, 200, 255))
qp.setPen(Qt.red)
# only draw the circle if the circleCheckBox is checked
if self.circleCheckbox.isChecked():
qp.drawEllipse(10, 10, 200, 200)
ctr = (self.width() // 2, self.height() // 2)
# draw axises
qp.drawLine(0, ctr[1], self.width(), ctr[1])
qp.drawLine(ctr[0], 0, ctr[0], self.height())
# Draw notches
NOTCH_SEP = 30
NOTCH_SIZE = 5
for x in range(ctr[0] // NOTCH_SEP):
dist = NOTCH_SEP * x
qp.drawLine(ctr[0] + dist, ctr[1] - NOTCH_SIZE, ctr[0] + dist, ctr[1] + NOTCH_SIZE)
qp.drawLine(ctr[0] - dist, ctr[1] - NOTCH_SIZE, ctr[0] - dist, ctr[1] + NOTCH_SIZE)
for y in range(ctr[1] // NOTCH_SEP):
dist = NOTCH_SEP * y
qp.drawLine(ctr[0] - NOTCH_SIZE, ctr[1] + dist, ctr[0] + NOTCH_SIZE, ctr[1] + dist)
qp.drawLine(ctr[0] - NOTCH_SIZE, ctr[1] - dist, ctr[0] + NOTCH_SIZE, ctr[1] - dist)
#points = np.array([complex(x, y) for x in range(-50, 51) for y in range(50, -51, -1)])
points = np.array([2, 0+2j, 0-2j, -2, 1.61803399, -0.618033989])
qp.setPen(Qt.blue)
self.display_points(qp, points, ctr, NOTCH_SEP)
try:
mTrans = (eval(self.a.toPlainText()), eval(self.b.toPlainText()),
eval(self.c.toPlainText()), eval(self.d.toPlainText()))
for i in range(len(points)):
# if points[i].real == points[i].imag == 0:
# continue
points[i] = self.mob_trans(points[i], mTrans)
points *= eval(self.a2.toPlainText())
points += eval(self.b2.toPlainText())
except Exception:
pass
# points[1] = self.mob_trans(points[1], mTrans)
# points[2] = self.mob_trans(points[2], mTrans)
# points[3] = self.mob_trans(points[3], mTrans)
#points *= cmath.e**(1j*cmath.pi/4)
print(points)
# points[1] *= 1+1j
# points[2] *= 1+1j
# points[3] *= 1+1j
qp.setPen(Qt.black)
self.display_points(qp, points, ctr, NOTCH_SEP, 4)
qp.end()
def display_points(self, qp, points, ctr, sep_size, rad=2):
for point in points:
qp.drawEllipse(QRectF((ctr[0] + point.real * sep_size - rad),
(ctr[1] - point.imag * sep_size - rad),
rad*2,
rad*2))
def mob_trans(self, z, trans):
a, b, c, d = trans
return (a * z + b) / (c * z + d)
class Form(QWidget):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
# The Dimensions of the side bar and bottom bar
self.DIM_PANEL_RIGHT_WIDTH = 200
self.DIM_PANEL_BOTTOM_HEIGHT = 50
# Setup the basic window properties
self.setMinimumWidth(700)
self.setMinimumHeight(550)
# Setup the Panels
self.setupSidePanel()
self.setupBottomPanel()
# Setup the Graphical View
self.sceneLayout = QVBoxLayout()
self.gview = CircleCanvas(self.showCircle)
self.gview.a = self.a
self.gview.b = self.b
self.gview.c = self.c
self.gview.d = self.d
self.gview.a2 = self.a2
self.gview.b2 = self.b2
self.gview.setUpdatesEnabled(True)
self.sceneLayout.addWidget(self.gview)
# Setup and attach all views to the main grid
self.grid = QGridLayout()
self.grid.setColumnMinimumWidth(1, self.DIM_PANEL_RIGHT_WIDTH)
self.grid.setRowMinimumHeight(1, self.DIM_PANEL_BOTTOM_HEIGHT)
self.grid.addItem(self.sceneLayout, 0, 0)
self.grid.addItem(self.bottomButtons, 1, 0)
self.grid.addItem(self.groupHolder, 0, 1)
# Set the layout the the grid
self.setLayout(self.grid)
self.setWindowTitle('CPPS Explorer v%s' % V_NUM)
def setupSidePanel(self):
# Side Panel
self.groupHolder = QGridLayout()
# Side Panel Group 1
group1 = QVBoxLayout()
titleLabel = QLabel("Mobius Transformation Params\n T(z) = (az+b)/(cz+d)")
titleLabel.setMaximumHeight(30)
self.a = QTextEdit("1")
self.a.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH//2)
self.a.setMaximumHeight(30)
self.a.textChanged.connect(lambda: self.gview.viewport().repaint())
self.b = QTextEdit("0")
self.b.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH//2)
self.b.setMaximumHeight(30)
self.b.textChanged.connect(lambda: self.gview.viewport().repaint())
self.c = QTextEdit("0")
self.c.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH//2)
self.c.setMaximumHeight(30)
self.c.textChanged.connect(lambda: self.gview.viewport().repaint())
self.d = QTextEdit("1")
self.d.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH//2)
self.d.setMaximumHeight(30)
self.d.textChanged.connect(lambda: self.gview.viewport().repaint())
sg1 = QVBoxLayout()
sg1.setDirection(QBoxLayout.LeftToRight)
sg1.addWidget(self.a)
sg1.addWidget(self.b)
sg2 = QVBoxLayout()
sg2.setDirection(QBoxLayout.LeftToRight)
sg2.addWidget(self.c)
sg2.addWidget(self.d)
slider1 = QSlider(Qt.Horizontal)
slider1.setMinimum(-500)
slider1.setMaximum(500)
slider1.setValue(100)
slider1.valueChanged.connect(lambda:self.a.setText(str(int(slider1.value())/100.0)))
slider1.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH)
slider2 = QSlider(Qt.Horizontal)
slider2.setMinimum(-500)
slider2.setMaximum(500)
slider2.setValue(0)
slider2.valueChanged.connect(lambda: self.b.setText(str(int(slider2.value()) / 100.0)))
slider2.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH)
slider3 = QSlider(Qt.Horizontal)
slider3.setMinimum(-500)
slider3.setMaximum(500)
slider3.setValue(0)
slider3.valueChanged.connect(lambda: self.c.setText(str(int(slider3.value()) / 100.0)))
slider3.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH)
slider4 = QSlider(Qt.Horizontal)
slider4.setMinimum(-500)
slider4.setMaximum(500)
slider4.setValue(100)
slider4.valueChanged.connect(lambda: self.d.setText(str(int(slider4.value()) / 100.0)))
slider4.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH)
group1.addWidget(titleLabel, alignment=Qt.AlignTop)
group1.addWidget(slider1, alignment=Qt.AlignTop)
group1.addWidget(slider2, alignment=Qt.AlignTop)
group1.addWidget(slider3, alignment=Qt.AlignTop)
group1.addWidget(slider4, alignment=Qt.AlignTop)
group1.addItem(sg1)
group1.addItem(sg2)
#Side Panel Group 2
group2 = QVBoxLayout()
titleLabel2 = QLabel("Transform T(z) = (az+b)")
# radio groups in group 2
# radioGroup = QButtonGroup(group2)
# radio1 = QRadioButton("Option 1")
# radio1.toggled.connect(lambda: self.radioButtonChange(radio1))
# radio1.setChecked(True)
# radio2 = QRadioButton("Option 2")
# radio2.toggled.connect(lambda: self.radioButtonChange(radio2))
#
# radioGroup.addButton(radio1)
# radioGroup.addButton(radio2)
#
# radioGroup2 = QButtonGroup(group2)
# radio3 = QRadioButton("Option 3a")
# radio3.toggled.connect(lambda: self.radioButtonChange(radio3))
# radio3.setChecked(True)
# radio4 = QRadioButton("Option 2b")
# radio4.toggled.connect(lambda: self.radioButtonChange(radio4))
#
# radioGroup2.addButton(radio3)
# radioGroup2.addButton(radio4)
self.a2 = QTextEdit("1")
self.a2.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH // 2)
self.a2.setMaximumHeight(30)
self.a2.textChanged.connect(lambda: self.gview.viewport().repaint())
self.b2 = QTextEdit("0")
self.b2.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH // 2)
self.b2.setMaximumHeight(30)
self.b2.textChanged.connect(lambda: self.gview.viewport().repaint())
sg3 = QVBoxLayout()
sg3.setDirection(QBoxLayout.LeftToRight)
sg3.addWidget(self.a2)
sg3.addWidget(self.b2)
slider5 = QSlider(Qt.Horizontal)
slider5.setMinimum(-500)
slider5.setMaximum(500)
slider5.setValue(100)
slider5.setMaximumHeight(30)
slider5.valueChanged.connect(lambda: self.a2.setText(str(int(slider5.value()) / 100.0)))
slider5.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH)
slider6 = QSlider(Qt.Horizontal)
slider6.setMinimum(-500)
slider6.setMaximum(500)
slider6.setValue(0)
slider6.setMaximumHeight(30)
slider6.valueChanged.connect(lambda: self.b2.setText(str(int(slider6.value()) / 100.0)))
slider6.setMaximumWidth(self.DIM_PANEL_RIGHT_WIDTH)
group2.addWidget(titleLabel2, alignment=Qt.AlignTop)
group2.addWidget(slider5, alignment=Qt.AlignTop)
group2.addWidget(slider6, alignment=Qt.AlignTop)
group2.addItem(sg3)
# group2.addWidget(radio1, alignment=Qt.AlignTop)
# group2.addWidget(radio2, alignment=Qt.AlignTop)
# group2.addWidget(radio3, alignment=Qt.AlignTop)
# group2.addWidget(radio4, alignment=Qt.AlignTop)
# attach all groups to group holder grid
self.groupHolder.addItem(group1, 0, 0) # group, row, col
self.groupHolder.setRowMinimumHeight(1, 50)
self.groupHolder.addItem(group2, 2, 0) # group, row, col
def setupBottomPanel(self):
# Bottom Panel
self.exitButton = QPushButton("Quit")
self.exitButton.setMaximumWidth(100)
self.exitButton.clicked.connect(self.exitNow)
self.showCircle = QCheckBox("Draw Circle")
self.showCircle.stateChanged.connect(self.checkboxChange)
self.bottomButtons = QVBoxLayout()
self.bottomButtons.setDirection(QBoxLayout.LeftToRight)
#self.bottomButtons.addWidget(self.showCircle)
self.bottomButtons.addWidget(self.exitButton)
def radioButtonChange(self, radioBtn):
if radioBtn.isChecked():
print(radioBtn.text(), "is checked")
def checkboxChange(self):
# used to force a repaint to either display or hide the circle
self.gview.viewport().repaint()
print("checkbox is:", self.showCircle.isChecked())
def exitNow(self):
print("exit")
exit()
def resizeEvent(self, QResizeEvent):
print("width %d, height %d" % (self.width(), self.height()))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Form()
w.show()
sys.exit(app.exec_())
|
s=str(input('introduceti un nume si un prenume:'))
a,b=s.split()
print(a)
print(b)
if((a.title()==a)and(b.title()==b)):
print('numele introdus este corect')
else:
print('numele introdus este incorect') |
sexo = input('Informe o seu sexo: ')
if(sexo== 'f'):
print('O sexo Informado foi o sexo feminino.')
elif(sexo== 'm'):
print('O sexo informado foi o sexo masculino.')
else:
print('Sexo nรฃo detectado.')
|
import urllib.request, urllib.parse, urllib.error
import json
url=input("Enter location: ")
#url = ' http://py4e-data.dr-chuck.net/comments_10141.json'
#open url
url_open = urllib.request.urlopen(url)
#extract data
data = url_open.read()
#put the data into a dictionary
data_parsed = json.loads(data)
'''print the sum of all 'count' occurrences. The file has the following structure:
{
"note":"This file contains the actual data for your assignment",
"comments":[
{
"name":"abc",
"count":100
},
{
"name":"cde",
"count":77
}, ...
}
'''
total = 0
for item in data_parsed['comments']:
total += int(item['count'])
print ('Total: ', total) |
def flat_list(nested_lst, low, high):
lst = []
if isinstance(nested_lst, list):
for i in range(low, high+1):
if isinstance(nested_lst[i], list):
lst.extend(flat_list(nested_lst[i], 0, len(nested_lst[i])-1))
else:
lst.append(nested_lst[i])
else:
return nested_lst
return lst
|
def rightView(root):
if not root:
return
queue=[]
queue.append(root)
while queue:
l=len(queue)
while l:
temp=queue[0]
if l==1:
print(temp.data,end=" ")
l-=1
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
queue.pop(0)
|
import sqlite3
import random
class SimpleSQL3:
"""Table/db created upon init
If working with an existing DB, leave the column_dict kwarg blank -
column names will be populated automatically.
database_name: looks for suffix '.db' - will add
'.db' if not found. This can be overridden with the
override boolean argument
**column_dict takes the column name and the type:
col_name='TEXT'
Wildcard search: query = "%" + query + "%"
fetch_all=True, change to false to use fetchone() func
No fetchmany() support at this time, probably a simple if statement
"""
def __init__(self, database_name, table_name, override=False, **column_dict):
assert database_name and table_name is not None, "One/more missing: database_name, table_name"
self.database_name = database_name
self.table_name = table_name
self.override = override
if not override:
if not self.database_name.endswith(".db"):
self.database_name = f"{database_name}.db"
else:
self.database_name = database_name
self.column_dict = column_dict
if len(self.column_dict) is 0:
# Gets the column names for working with an existing DB
conn = sqlite3.connect(self.database_name)
c = conn.cursor()
c.execute(f"""SELECT * FROM {self.table_name}""")
self.column_names = list(map(lambda x: x[0], c.description))
self.column_types = ["TEXT"] * len(self.column_names)
c.close()
conn.close()
else:
self.column_names = list(self.column_dict.keys())
self.column_types = list(column_dict.values())
col_vals = "?," * len(str(self.column_names).split(","))
self.col_vals = col_vals[:-1]
self.columns = "".join([f"{a} {b.upper()}, " for a, b in zip(self.column_names, self.column_types)])[:-2]
# Last 2 chars are always a space and comma
conn = sqlite3.connect(self.database_name)
c = conn.cursor()
c.execute(f"CREATE TABLE IF NOT EXISTS {self.table_name} ({self.columns})")
c.close()
conn.close()
def insert(self, *args):
args = (args)
assert len(args) == len(self.col_vals.split(',')), f"{len(args)} argument and {len(self.col_vals.split(','))} column - length do not match"
conn = sqlite3.connect(self.database_name)
c = conn.cursor()
c.execute(f"""INSERT INTO {self.table_name} VALUES ({self.col_vals})""", args)
conn.commit()
c.close()
conn.close()
def select_cols_like(self, sel_col, like_col, query, fetch_all=True):
assert fetch_all is not None, "fetch_all must be boolean"
query = (query,)
conn = sqlite3.connect(self.database_name) # path to DB as well
c = conn.cursor()
c.execute(f"""SELECT {sel_col} FROM {self.table_name} WHERE {like_col} LIKE ?""", query)
if not fetch_all:
return c.fetchone()
else:
return c.fetchall()
c.close()
conn.close()
def select_cols_equal(self, sel_col, equal_col, query, fetch_all=True):
assert fetch_all is not None, "fetch_all must be boolean"
query = (query,)
conn = sqlite3.connect(self.database_name) # path to DB as well
c = conn.cursor()
c.execute(f"""SELECT {sel_col} FROM {self.table_name} WHERE {equal_col}=?""", query)
if not fetch_all:
return c.fetchone()
else:
return c.fetchall()
c.close()
conn.close()
def select_all_table(self, fetch_all=True):
assert fetch_all is not None, "fetch_all must be boolean"
conn = sqlite3.connect(self.database_name) # path to DB as well
c = conn.cursor()
c.execute(f"""SELECT * FROM {self.table_name}""")
if not fetch_all:
return c.fetchone()
else:
return c.fetchall()
c.close()
conn.close()
def update(self, set_col, where_col, set_var, where_var):
conn = sqlite3.connect(self.database_name) # path to DB as well
c = conn.cursor()
c.execute(f"""UPDATE {self.table_name} SET {set_col} = ? WHERE {where_col} = ?""", (set_var, where_var))
conn.commit()
c.close()
conn.close()
def delete(self):
# TODO
pass
def custom_sql(self, sql_statement, fetch_all=True):
conn = sqlite3.connect(self.database_name) # path to DB as well
c = conn.cursor()
c.execute(f"""{sql_statement}""")
if not fetch_all:
return c.fetchone()
else:
return c.fetchall()
conn.commit()
c.close()
conn.close()
def __repr__(self):
return f"\nDB Name: {self.database_name}, \nTable Name: {self.table_name}, \nOverride: {self.override},\nColumns: {self.column_dict}"
def __str__(self):
return f"\nDB Name: {self.database_name}, \nTable Name: {self.table_name}, \nOverride: {self.override},\nColumns: {self.column_dict}"
# Add checks and balances: if column is TEXT then data=str(data), etc..
if __name__ == '__main__':
# (self, database_name, table_name, override=False, **column_dict)
day = "2018-08-19"
my_table = SimpleSQL3("testDB", "testCols", False, col1="TEXT", col2="TEXT", col3="TEXT", col4="TEXT")
my_table.insert(random.randint(1, 50), random.randint(1, 50), random.randint(1, 50), random.randint(1, 50))
all_table = my_table.select_all_table()
cols_eqal = my_table.select_cols_equal("col1", "col2", "9") # sel_col, equal_col, query
cols_like = my_table.select_cols_like("col3", "col4", "UPDATED") # sel_col, like_col, query
# cols_eqal.select_cols_equal("col1, col2, col3", "col4='SOMETHING' AND col5", day) # Example of using 'AND' statement
my_table.update("col1", "col1", "UPDATED", "12") # set_col, where_col, set_var, where_var
custom_thing = my_table.custom_sql("SELECT * FROM testCols")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.