content stringlengths 7 1.05M |
|---|
# -*- encoding:utf-8 -*-
# index rule:
# 3 ------6------- 2
#
# 7 ------ ------- 5
#
# 0 ------4------- 1
# Stores the triangle values
raw_trigs = [
[],
[(0,7,4)],
[(4,5,1)],
[(0,5,1),(0,7,5)],
[(5,6,2)],
[(0,7,4), (4,7,5), (7,6,5), (5,6,2)],
[(1,4,6), (1,6,2)],
[(1,0,7), (1,7,6), (1,6,2)],
[(7,3,6)],
[(0,3,4), (4,3,6)],
[(1,4,5), (4,7,5), (5,7,6), (7,3,6)],
[(0,5,1), (0,6,5), (0,3,6)],
[(7,3,5), (5,3,2)],
[(0,3,4), (4,3,5), (5,3,2)],
[(7,3,2), (4,7,2), (1,4,2)],
[(0,2,1), (0,3,2)],
]
index_to_pos = [
[0,0],
[2,0],
[2,2],
[0,2],
[1,0],
[2,1],
[1,2],
[0,1],
]
class Worker(object):
def __init__(self):
self.rt_verts = []
self.rt_trigs = []
self.rt_flex_verts = []
def execute(self):
for case, trig_list in enumerate(raw_trigs):
self.process_case(case, trig_list)
worker.format_csharp("MarchingSquareData.txt")
def process_case(self, case, trig_list_raw):
vi_list = []
vpos_list = []
trig_list = []
flex_list = []
for trig_raw in trig_list_raw:
# print trig_raw
for vi in trig_raw:
# record vert index
if not vi in vi_list:
vi_list.append(vi)
vpos_list.append(self.get_vert_pos(vi))
# record lerp parents
if vi >= 4:
parents = self.get_lerp_parents(case, vi)
flex_list.append(parents)
else:
flex_list.append(None)
# record triangle
trig_list.append(vi_list.index(vi))
self.rt_verts.append(vpos_list)
self.rt_trigs.append(trig_list)
self.rt_flex_verts.append(flex_list)
def get_vert_pos(self, index):
return index_to_pos[index]
def get_lerp_parents(self, case, index):
if index < 4:
return
a, b = (index-4)%4, (index-3)%4
cell_values = self.get_case_cell_values(case)
if cell_values[a] > cell_values[b]:
return b, a
return a, b
def get_case_cell_values(self, case):
return case & 1, case >> 1 & 1, case >> 2 & 1, case >> 3 & 1
def format_csharp(self, filename):
msg = ""
template = "\tnew int[%d] {%s},\n"
anchor_template = "\tnew int[%d][] {%s},\n"
with open(filename, 'w') as f:
# Write cell vertices
f.write("\n\npublic static int[][] cellVertPos = new int[][]\n{\n")
msg = ""
for index in xrange(4):
msg += template % (2, "%d,%d" % tuple(index_to_pos[index]))
f.write(msg)
f.write("};")
# Write vertices
f.write("\n\npublic static int[][] vertices = new int[][]\n{\n")
msg = ""
for vert_list in self.rt_verts:
vert_str = ""
for vert in vert_list:
vert_str += "%d,%d," % tuple(vert)
msg += template % (len(vert_list) * 2, vert_str)
f.write(msg)
f.write("};")
# Write triangles
f.write("\n\npublic static int[][] triangles = new int[][]\n{\n")
msg = ""
for trig_list in self.rt_trigs:
trig_str = ""
for trig_index in trig_list:
trig_str += "%d," % trig_index
msg += template % (len(trig_list), trig_str)
f.write(msg)
f.write("};")
# Write flexible vertices
f.write("\n\npublic static int[][][] anchors = new int[][][]\n{\n")
msg = ""
for flex_list in self.rt_flex_verts:
flex_str = ""
for parents in flex_list:
if parents is not None:
flex_str += "new int[2]{%d,%d}," % parents
else:
flex_str += "null,"
msg += anchor_template % (len(flex_list), flex_str)
f.write(msg)
f.write("};")
worker = Worker()
worker.execute()
# print worker.rt_verts
# print worker.rt_trigs
# print worker.rt_flex_verts
|
def mininum_temperature(arr_temp):
min_val = arr_temp[0]
i = 1
while i < len(arr_temp):
if (i < min_val):
min_val = arr_temp[i]
i += 1
return min_val
def maximum_temperature(arr_temp):
max_val = arr_temp[0]
i = 1
while i < len(arr_temp):
if (i > max_val):
max_val = arr_temp[i]
i += 1
return max_val
def min_max(temperature):
print(temperature)
print(f'A menor temperatura do mês foi de: {mininum_temperature(temperature)}')
print(f'A maior temperatura do mês foi de: {maximum_temperature(temperature)}\n')
def main():
min_max([1,2,3,4,5,6,7])
min_max([-1,-2,-3,-4,-5,-6,-7])
min_max([-1,-2,-3,-4,-5,-6,-7,-50,100,30,31,312,3,11,54,1,42,3,12,312,31,541,3,12,31])
main() |
class TypeNode:
def __init__(self,className,parent="Object"):
self.name = className
self.attrlist = [Attribute("self",className)]
self.methodlist = {}
self.default = "void"
self.parent = parent
self.children = []
# def GetAttribute(self,attrName):
# attr = [attr.Name == attrName for attr in self.attrlist]
# return attr[0]
# def GetMethod(self,methodName):
# meth = [meth.Name == methodName for meth in self.attrlist]
# return meth[0]
def DefineAttribute(self, attrName, attrType):
if not (self._IsDefineAttribute(attrName) == None):
return False
self.attrlist.append(Attribute(attrName,attrType))
# print("------selflist ", self.attrlist)
return True
def DefineMethod(self, methodName,argName,argType,returnType,rename):
if not (self._IsLocalDefineMethod(methodName) == None) or self._IsDefineADiferentMethodWhitSameName(methodName,argName,argType,returnType):
return False
# self.methodlist.append(Method(methodName,argName,argType,returnType,rename))
self.methodlist[methodName] = Method(methodName,argName,argType,returnType,rename)
return True
def GetMethodReturnType(self,methodName):
self.methodlist.values()
for element in self.methodlist.values():
# print("//////element.paramsType paramsType",element.paramsType , paramsType)
if element.name == methodName:
# for i,param in enumerate(paramsType):
# element.paramsType[i] derived paramstype
# print("element.returnType",element.returnType)
return element
if self.parent == None:
return None
return self.parent.GetMethodReturnType(methodName)
def _IsDefineMethod(self, methodName,argName,argType,returnType):
for element in self.methodlist.values():
if element.name == methodName and ((element.returnType == returnType) and (element.paramsType == argType) ):
return True
if self.parent == None:
return False
return self.parent._IsDefineMethod(methodName,argName,argType,returnType)
def _IsDefineAttribute(self, attrName):
attr = [ attr.Type for attr in self.attrlist if attr.Name == attrName]
if len(attr):
return attr[0]
if self.parent == None:
return None
return self.parent._IsDefineAttribute(attrName)
def _IsDefineAttributeInParent(self, attrName):
parent = self.parent
if parent == None:
return None
return parent._IsDefineAttribute(attrName)
def _IsLocalDefineMethod(self, methodName):
meth = self.methodlist.get(methodName)
# [ meth for meth in self.methodlist if meth.name == methodName]
return meth
# if len(meth):
# return meth[0]
# return None
def _IsDefineADiferentMethodWhitSameName(self, methodName,argName,argType,returnType):
for element in self.methodlist.values():
if element.name == methodName and (not (element.returnType == returnType) or not(element.paramsType == argType) ):
return True
if self.parent == None:
return False
return self.parent._IsDefineADiferentMethodWhitSameName(methodName,argName,argType,returnType)
def IsDerived(self, ancestor):
derivedparent = self.parent
if derivedparent == None:
return False
if derivedparent.Name == ancestor:
return True
return derivedparent.IsDerived(ancestor)
# def GetTypeNode(self,typeName):
# if self.name == typeName:
# return self
# for child in self.children:
# cd = child.GetTypeNode(typeName)
# if not (cd == None):
# return cd
# return child
class Attribute:
def __init__(self, attrName,attrType):
self.Name = attrName
self.Type = attrType
class Method:
def __init__(self, name,paramsName, paramsType,returnType,rename):
self.name = name
self.returnType = returnType
self.paramsType = paramsType
self.paramsName = paramsName
self.rename = rename
# self.mmholder = mmholder
class Context:
def __init__(self, parent = None):
if parent == None:
self.buildin = self.__GetBuildIn()
# self.hierarchy = {"Object":TypeNode("Object",None)}
# self.hierarchyNode = TypeNode("Object",None)
self.variables = {} #nombre de la variable, su tipo
self.parent = parent
self.children = []
self.currentClass = None
self.order_classes = []
# self.index_at_parent = 0 if parent is None else len(parent.locals)
def __GetBuildIn(self):
self.hierarchy = {}
typeObject = TypeNode("Object",parent = None)
self.hierarchy["Object"] = typeObject
typeString = TypeNode("String","Object")
# typeObject = TypeNode("Object",self.hierarchy["Object"])
typeBool = TypeNode("Bool","Object")
typeInt = TypeNode("Int","Object")
typeIO = TypeNode("IO","Object")
typeObject.methodlist["abort"] = (Method("abort",[],[],"Object",None))
typeObject.methodlist["type_name"] =(Method("type_name",[],[],"String",None))
typeIO.methodlist["in_string"] =(Method("in_string",[],[],"String",None))
typeIO.methodlist["in_int"] =(Method("in_int",[],[],"Int",None))
typeIO.methodlist["out_string"] = (Method("out_string", ["x"], ["String"], "IO", None))
typeIO.methodlist["out_int"] = (Method("out_int", ["x"], ["Int"], "IO", None))
typeString.methodlist["length"] =(Method("length",[],[],"Int",None))
typeString.methodlist["concat"] =(Method("concat",["s"],["String"],"String",None))
typeString.methodlist["substr"] =(Method("substr",["i","l"],["Int","Int"],"String",None))
typeInt.default = 0
typeBool.default = "false"
typeString.default = ""
self.hierarchy["String"] = typeString
self.hierarchy["Bool"] = typeBool
self.hierarchy["Int"] = typeInt
self.hierarchy["IO"] = typeIO
return [typeString,typeBool,typeInt]
########
def GetMethodReturnType(self,ctype,methodName,paramsType):
myctype = self.hierarchy[ctype]
meth = myctype.GetMethodReturnType(methodName)
if meth == None:
return None
if not (len(paramsType)== len(meth.paramsType)):
return None
for i,param in enumerate(paramsType):
if not (meth.paramsType[i] == param) and (not self.IsDerived(param,meth.paramsType[i])):
return None
return meth.returnType
def GetType(self,typeName): # devuelve el objeto
# print ("self1",self.hierarchyNode.GetTypeNode(typeName))
return self.hierarchy.get(typeName)
def IsDefineType(self,typeName):
return self.hierarchy.__contains__(typeName)
def CreateType(self,typeName,typeParent):
if not self.GetType(typeName) == None:
return False
newType = TypeNode(typeName,typeParent)
# parent.children.append(newType)
self.hierarchy[typeName] = newType
return True
def LinkTypes(self,errors):
values = list(self.hierarchy.values())
# for item in values:
# print(item.name)
# print("values1",values1)
# a = self.hierarchy["String"]
# print("a",a.name)
# values = values1.remove(a)
# print("values",values)
for item in values:
# print("item.name",item.name)
# print("item.parent",item.parent)
if not (item.parent == None):
# print("item.parent1",item.parent)
parent = self.GetType(item.parent)
# print("here",parent)
if parent == None:
errors.append("(0,0) - TypeError: El tipo "+ item.parent + " no esta definido")
return False
item.parent = parent
parent.children.append(item)
return self.IsValid(errors)
# return True
def IsDerived(self, derived, ancestor):
# print("derived,ancestor",derived,ancestor)
derivedType = self.GetType(derived)
return self._IsDerived(derivedType,ancestor)
def _IsDerived(self, derived, ancestor):
# print("derived,ancestor1",derived.name,ancestor)
derivedparent = derived.parent
if derivedparent == None:
return False
if derivedparent.name == ancestor:
return True
return self._IsDerived(derivedparent,ancestor)
def IsValid(self,errors): #revisar q no haya ciclos
for item in self.buildin:
if len(item.children):
errors.append("(0,0) - SemanticError: No se puede heredar del metodo "+ item.name)
# print("buildin con hijos " + item.name)
return False
return self.NotExistCicle(errors)
def NotExistCicle(self,errors):
# self.order_classes = []
self._NotExistCicle( self.hierarchy["Object"],self.order_classes)
# print("No Hay ciclo", len(self.order_classes) == len(self.hierarchy))
# print(self.order_classes)
if len(self.order_classes) == len(self.hierarchy):
self.sorted = self.order_classes
return True
errors.append("(0,0) - SemanticError: No pueden existir ciclos en la herencia")
return False
# return len(self.order_classes) == len(self.hierarchy)
def _NotExistCicle(self, a: TypeNode, types: list):
# print("aciclicos",a.name)
if a is None:
return True
if types.__contains__(a.name):
return False
types.append(a.name)
for child in a.children:
if not self._NotExistCicle(child, types):
return False
return True
def NotIOReimplemetation(self):
# print("------------")
# print("HOLA")
io = self.hierarchy["IO"]
succ = io.children
# print("----cosita",io.children)
# print("----cosita2",io.children[0].methodlist)
# print("succ ", succ)
while len(succ):
item = succ.pop()
# print("metodos", item.methodlist.values())
for m in item.methodlist.values():
if m.name == "in_string" or m.name == "in_int" or m.name == "out_string" or m.name == "out_int":
return False
succ = succ + item.children
# print("------------")
return True
def LCA(self,a: TypeNode, b: TypeNode):
# Si son iguales
if a.name == b.name:
return a.name
# Lista de los posibles ancestros
ancestors = []
# Voy subiendo hasta llegar a la raíz y guardando los nodos.name que son los ancestros de a
while a is not None:
ancestors.append(a.name)
a = a.parent
# Trato de encontrar un ancestro de b que sea ancestro de a, el cual será el LCA
# b = b.parent
while b is not None:
if ancestors.__contains__(b.name):
return b.name
b = b.parent
return None
#######
def DefineVariable(self, vname, vtype):
var = VariableInfo(vname,vtype)
self.variables[vname] = var
return var
# def IsDefineVariable(self,vname):
# print("is def var")
# if self.variables.__contains__(vname):
# print("contain")
# return True, self.variables[vname]
# if not (self.parent == None):
# print("parent")
# return self.parent.IsDefineVariable(vname)
# return False,None
def _GetType(self, vname):
var = self.variables.get(vname)
if var == None:
return None
return var.ctype
def GetVinfo(self,vname):
# print("is def var")
var = self.variables.get(vname)
if not (var == None):
# print("contain",vname)
return var
if self.parent == None:
return None
# print("parent")
return self.parent.GetVinfo(vname)
def IsDefineVariable(self,vname):
vinfo = self.GetVinfo(vname)
if vinfo == None:
vtype = self.hierarchy[self.currentClass]._IsDefineAttributeInParent(vname)
if vtype == None:
return None
return vtype
return vinfo.ctype
# def GetVariableType(self,variable):
# return self.variables[variable]
# def IsLocalVariable(self,vname):
# if self.variables.__contains__(vname):
# return True, self.variables[vname]
# return False,None
def CreateChildContext(self):
childContext = Context(self)
childContext.hierarchy = self.hierarchy
childContext.currentClass = self.currentClass
return childContext
class VariableInfo:
def __init__(self, name, ctype = None, vmholder = 0):
self.name = name
self.ctype = ctype
self.vmholder = vmholder
def __str__(self):
return " name: " + str(self.name) + ", tipo: "+ str(self.ctype) + ", vmholder: " + str(self.vmholder)
class MethodInfo:
def __init__(self, name, vmholder = 0, paramsType = [], returnType = None):
self.name = name
self.vmholder = vmholder
self.paramsType = paramsType
self.returnType = returnType
def __str__(self):
return " name: " + str(self.name) + ", vmholder: " + str(self.vmholder)
class ClassInfo:
def __init__(self, name, attr_length = 0, meth_length = 0, parent = None):
self.name = name
self.attr_length = attr_length
self.meth_length = meth_length
self.parent = parent
def __str__(self):
return " name: " + str(self.name) + " parent: " + str(self.parent.cinfo.name) + ", attr_length: " + str(self.attr_length) + ", meth_length: " + str(self.meth_length)
|
"""
Python package to help with daily work on heusler materials.
"""
name = "heuslertools"
|
make = "Ford"
model = "Everest"
def start_engine():
print (f'{make} {model} engine started')
|
# KATA MODULO 08
# EJERCICIO 01 Crear y modificar un diccionario de Python
# Agrega el código para crear un nuevo diccionario denominado 'planet'. Rellena con la siguiente información:
# name: Mars
# moons: 2
# Crea un diccionario llamado planet con los datos propuestos
# Para recuperar valores, puede utilizar el método get o corchetes ([ ]) con el nombre de la clave que desea recuperar.
# Muestra el nombre del planeta y el número de lunas que tiene.
planet = {'name':'Mars', 'moons':'2'}
print("The planet " + planet.get('name') + " has " + planet['moons'] + " moons")
planet['circunferencia (km)'] = {'polar': '6752','equatorial':'6792'}
# Imprime el nombre del planeta con su circunferencia polar.
print(planet.get('name') + ' ' + planet['circunferencia (km)']['polar'])
print(planet) |
class Resource():
def __init__(self, path):
self.path = path
def __str__(self):
return '-i {}'.format(self.path)
class Resources(list):
def add(self, path):
self.append(Resource(path))
def append(self, resource):
resource.number = len(self)
super().append(resource)
def __delitem__(self, index):
for resource in self[index:]:
resource.number -= 1
super().__delitem__(index)
def __str__(self):
return ' '.join(str(r) for r in self)
|
# Python - 3.6.0
Test.describe('Basic tests')
names = ['john', 'matt', 'alex', 'cam']
ages = [16, 25, 57, 39]
for name, age in zip(names, ages):
person = Person(name, age)
Test.it(f'Testing for {name} and {age}')
Test.assert_equals(person.info, f'{name}s age is {age}')
|
aluno = {
}
aluno['nome'] = str(input('Nome: ').title())
aluno['média'] = float(input(f'Média de {aluno["nome"]} é: '))
print('-='*20)
if aluno['média'] >= 7:
aluno['situação'] = 'Aprovado!'
elif aluno ['média'] < 5:
aluno['situação'] = 'Reprovado!'
else:
aluno['situação']='Recuperação!'
print(f'O nome é igual a {aluno["nome"]}')
print(f'Média é igual a {aluno["média"]}')
if aluno['situação'] == 'Aprovado!':
print(f'Situação do {aluno["nome"]}:', f'\033[1;34m{aluno["situação"]}\033[m')
elif aluno['situação'] == 'Recuperação':
print(f'Situação do {aluno["nome"]}:', f'\033[1;33m{aluno["situação"]}\033[m')
else:
print(f'Situação do {aluno["nome"]}:', f'\033[1;31m{aluno["situação"]}\033[m') |
#Floating loop
first_list = list(range(10))
for i in first_list:
first_list[i] = float(first_list[i])
print(first_list)
|
def read_file(filename):
"""
Read input file and save the lines into a list.
:param filename: input file
:return: grid of octopuses
"""
grid = []
with open(filename, 'r', encoding='UTF-8') as file:
for line in file:
grid.append([int(s) for s in list(line.strip())])
return grid
def model_light(grid, steps):
"""
Simulate steps
:param grid: grid of octopuses
:param steps: number of steps to simulate
:return: number of flashes
"""
flashes = 0
for step in range(0, steps):
previous_flashes = -1
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
if grid[i][j]:
grid[i][j] += 1
else:
grid[i][j] = 1
while previous_flashes != flashes:
previous_flashes = flashes
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
if grid[i][j] and grid[i][j] > 9:
flashes += 1
grid[i][j] = None
# Up
if i > 0 and grid[i - 1][j]:
grid[i - 1][j] += 1
# Down
if i < len(grid) - 1 and grid[i + 1][j]:
grid[i + 1][j] += 1
#
if j > 0 and grid[i][j - 1]:
grid[i][j - 1] += 1
if j < len(grid[i]) - 1 and grid[i][j + 1]:
grid[i][j + 1] += 1
if i > 0 and j > 0 and grid[i - 1][j - 1]:
grid[i - 1][j - 1] += 1
if i > 0 and j < len(grid[i]) - 1 and grid[i - 1][j + 1]:
grid[i - 1][j + 1] += 1
if i < len(grid) - 1 and j < len(grid[i]) - 1 and grid[i + 1][j + 1]:
grid[i + 1][j + 1] += 1
if i < len(grid) - 1 and j > 0 and grid[i + 1][j - 1]:
grid[i + 1][j - 1] += 1
return flashes
def all_flashing_steps(grid):
"""
Find the exact moments when the octopuses will all flash simultaneously
:param grid: grid of octopuses
:return: number of steps required for the exact moments when the octopuses will all flash simultaneously
"""
steps = 0
flashes = 0
n_of_octopuses = len(grid) * len(grid[0])
current_flashes = 0
flashed = 0
while(flashed != n_of_octopuses):
steps += 1
previous_flashes = -1
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
if grid[i][j]:
grid[i][j] += 1
else:
grid[i][j] = 1
flashed = 0
while previous_flashes != flashes:
previous_flashes = flashes
current_flashes = 0
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
if grid[i][j] and grid[i][j] > 9:
current_flashes += 1
flashed += 1
grid[i][j] = None
# Up
if i > 0 and grid[i - 1][j]:
grid[i - 1][j] += 1
# Down
if i < len(grid) - 1 and grid[i + 1][j]:
grid[i + 1][j] += 1
#
if j > 0 and grid[i][j - 1]:
grid[i][j - 1] += 1
if j < len(grid[i]) - 1 and grid[i][j + 1]:
grid[i][j + 1] += 1
if i > 0 and j > 0 and grid[i - 1][j - 1]:
grid[i - 1][j - 1] += 1
if i > 0 and j < len(grid[i]) - 1 and grid[i - 1][j + 1]:
grid[i - 1][j + 1] += 1
if i < len(grid) - 1 and j < len(grid[i]) - 1 and grid[i + 1][j + 1]:
grid[i + 1][j + 1] += 1
if i < len(grid) - 1 and j > 0 and grid[i + 1][j - 1]:
grid[i + 1][j - 1] += 1
flashes += current_flashes
return steps
if __name__ == '__main__':
grid = read_file('input.txt')
# flashes = model_light(grid, 100)
steps = all_flashing_steps(grid)
print(steps)
|
# compat3.py
# Copyright (c) 2013-2019 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0111,W0122,W0613
###
# Functions
###
def _readlines(fname, fpointer1=open, fpointer2=open):
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
try: # pragma: no cover
with fpointer1(fname, "r") as fobj:
return fobj.readlines()
except UnicodeDecodeError: # pragma: no cover
with fpointer2(fname, "r", encoding="utf-8") as fobj:
return fobj.readlines()
def _unicode_to_ascii(obj): # pragma: no cover
# pylint: disable=E0602
return obj
def _write(fobj, data):
"""Write data to file."""
fobj.write(data)
|
## Adicionando Cores
##\033[formatação:corTexto:corFundom
print('\033[0;30;41mOlá mundo!')
print('\033[4;33;44mOlá mundo!')
print('\033[1;35;43mOlá mundo!')
print('\033[30;42mOlá mundo!\033[0;0;0m')
print('\033[mOlá mundo!')
print('\033[7;33;44mOlá mundo!')
## Verifica quantidade de caracteres em uma string
s='Prova de Python'
print(len(s)) |
class Fibonacci:
"""Implementations of the Fibonacci number."""
@staticmethod
def fib_iterative(index):
"""
Iterative algorithm for calculating the Fibonacci number.
:param index: Index of a number in the Fibonacci sequence.
:return: Fibonacci number.
"""
lower = 0
higher = 1
for i in range(1, index):
tmp = lower + higher
lower = higher
higher = tmp
return higher
@staticmethod
def fib_recursive(index):
"""
Recursive algorithm for calculating the Fibonacci number.
:param index: Index of a number in the Fibonacci sequence.
:return: Fibonacci number.
"""
if index <= 1:
return index
else:
return Fibonacci.fib_recursive(index - 1) + Fibonacci.fib_recursive(index - 2)
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"win": "game.ipynb",
"lose": "game.ipynb"}
modules = ["game.py"]
doc_url = "https://thecharlieblake.github.io/solitairenet/"
git_url = "https://github.com/thecharlieblake/solitairenet/tree/master/"
def custom_doc_links(name): return None
|
# Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.
num = int(input('Digite um valor qualquer:'))
resultado = num % 2 #resultado da divisão
#Todo valor impar dá 1
#Todo valor par dá 0
if resultado == 0:
print('{} é PAR'.format(num))
else:
print('{} é Impar'.format(num)) |
""" Helper routines for generating gpu kernels for nvcc.
"""
def nvcc_kernel(name, params, body):
"""Return the c code of a kernel function.
:param params: the parameters to the function as one or more strings
:param body: the [nested] list of statements for the body of the function. These will be
separated by ';' characters.
"""
paramstr = ', '.join(params)
def flatbody():
for b in body:
if isinstance(b, (list, tuple)):
for bb in b:
yield bb
else:
yield b
bodystr = ';\n'.join(flatbody())
return """__global__ void %(name)s (%(paramstr)s)
{
%(bodystr)s;
}
""" %locals()
def code_version(version):
"""decorator to support version-based cache mechanism"""
if not isinstance(version, tuple):
raise TypeError('version must be tuple', version)
def deco(f):
f.code_version = version
return f
return deco
UNVERSIONED = ()
@code_version((1,))
def inline_reduce(N, buf, pos, count, manner_fn):
"""
Return C++ code for a function that reduces a contiguous buffer.
:param N: length of the buffer
:param buf: buffer pointer
:param pos: index of executing thread
:param count: number of executing threads
:param manner_fn: a function that accepts strings of arguments a and b, and returns c code
for their reduction. (Example: return "%(a)s + %(b)s" for a sum reduction).
:postcondition:
This function leaves the answer in position 0 of the buffer. The rest of the buffer is
trashed by this function.
:note: buf should be in gpu shared memory, we access it many times.
"""
loop_line = manner_fn("%s[%s]"%(buf,pos), "%s[i]" %(buf))
r_16 = manner_fn("%s[%s]" %(buf, pos), "%s[%s+16]" %(buf, pos))
r_8 = manner_fn("%s[%s]" %(buf, pos), "%s[%s+8]" %(buf, pos))
r_4 = manner_fn("%s[%s]" %(buf, pos), "%s[%s+4]" %(buf, pos))
r_2 = manner_fn("%s[%s]" %(buf, pos), "%s[%s+2]" %(buf, pos))
r_1 = manner_fn("%s[%s]" %(buf, pos), "%s[%s+1]" %(buf, pos))
return """
{
// This function trashes buf[1..N], leaving the reduction result in buf[0].
if (%(pos)s < warpSize)
{
for (int i = %(pos)s + warpSize; i < %(N)s; i += warpSize)
{
%(buf)s[%(pos)s] = %(loop_line)s;
}
if (%(pos)s < 16)
{
//reduce so that %(pos)s 0 has the sum of everything
if(%(pos)s + 16 < %(N)s)
%(buf)s[%(pos)s] = %(r_16)s;
if(%(pos)s + 8 < %(N)s)
%(buf)s[%(pos)s] = %(r_8)s;
if(%(pos)s + 4 < %(N)s)
%(buf)s[%(pos)s] = %(r_4)s;
if(%(pos)s + 2 < %(N)s)
%(buf)s[%(pos)s] = %(r_2)s;
if(%(pos)s + 1 < %(N)s)
%(buf)s[%(pos)s] = %(r_1)s;
}
}
}
""" % locals()
@code_version(inline_reduce.code_version)
def inline_reduce_max(N, buf, pos, count):
return inline_reduce(N, buf, pos, count, lambda a, b: "max(%s, %s)"%(a,b))
@code_version(inline_reduce.code_version)
def inline_reduce_sum(N, buf, pos, count):
return inline_reduce(N, buf, pos, count, lambda a, b: "%s + %s"%(a,b))
@code_version(inline_reduce.code_version)
def inline_reduce_min(N, buf, pos, count):
return inline_reduce(N, buf, pos, count, lambda a, b: "min(%s, %s)"%(a,b))
@code_version(inline_reduce.code_version)
def inline_reduce_prod(N, buf, pos, count):
return inline_reduce(N, buf, pos, count, lambda a, b: "%s * %s"%(a,b))
@code_version((2,) + inline_reduce_max.code_version + inline_reduce_sum.code_version)
def inline_softmax(N, buf, buf2, threadPos, threadCount):
"""
:param N: length of the buffer
:param threadPos: index of executing thread
:param threadCount: number of executing threads
:Precondition: buf and buf2 contain two identical copies of the input to softmax
:Postcondition: buf contains the softmax, buf2 contains un-normalized softmax
:note: buf and buf2 should be in gpu shared memory, we access it many times.
:note2: We use __i as an int variable in a loop
"""
return [
#get max of buf (trashing all but buf[0])
inline_reduce_max(N, buf, threadPos, threadCount),
'__syncthreads()',
'float row_max = '+buf+'[0]',
'__syncthreads()',
'for(int __i='+threadPos+'; __i<'+N+'; __i+='+threadCount+'){',
buf+'[__i] = exp('+buf2+'[__i] - row_max)',
buf2+'[__i] = '+buf+'[__i]',
'}',
'__syncthreads()',
inline_reduce_sum(N, buf, threadPos, threadCount),
'__syncthreads()',
'float row_sum = '+buf+'[0]',
'__syncthreads()',
# divide each exp() result by the sum to complete the job.
'for(int __i='+threadPos+'; __i<'+N+'; __i+='+threadCount+'){',
buf+'[__i] = '+buf2+'[__i] / row_sum',
'}',
'__syncthreads()',
]
|
def smooth(dataset):
dataset_length = len(dataset)
dataset_extra_weights = [ItemWeight(*x) for x in dataset]
def get_next():
if dataset_length == 0:
return None
if dataset_length == 1:
return dataset[0][0]
total_weight = 0
result = None
for extra in dataset_extra_weights:
extra.current_weight += extra.effective_weight
total_weight += extra.effective_weight
if extra.effective_weight < extra.weight:
extra.effective_weight += 1
if not result or result.current_weight < extra.current_weight:
result = extra
if not result: # this should be unreachable, but check anyway
raise RuntimeError
result.current_weight -= total_weight
return result.key
return get_next
class ItemWeight:
__slots__ = ('key', 'weight', 'current_weight', 'effective_weight')
def __init__(self, key, weight):
self.key = key
self.weight = weight
self.current_weight = 0
self.effective_weight = weight
|
# O(nlogn) time | O(n) space
def mergeSort(array):
if len(array) <= 1:
return array
subarray = array[:]
mergeSortHelper(array, 0, len(array)-1)
return array
def mergeSortHelper(array, l, r):
if l == r:
return
m = (l + r) // 2
mergeSortHelper(array, l, m)
mergeSortHelper(array, m + 1, r)
merge(array, l, m, r)
def merge(arr, l, m, r):
subarray = arr[:]
i = l
j = m + 1
k = l
while i <= m and j <= r:
if subarray[i] <= subarray[j]:
arr[k] = subarray[i]
i += 1
else:
arr[k] = subarray[j]
j += 1
k += 1
while i <= m:
arr[k] = subarray[i]
i += 1
k += 1
while j <= r:
arr[k] = subarray[j]
j += 1
k += 1
|
# This is the custom function interface.
# You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
def f(self, x, y):
return x + y
class Solution:
def findSolution(self, customfunction, z: int):
ret = []
i = 1
while customfunction.f(i, 1) <= z:
j = 1
while True:
if customfunction.f(i, j) == z:
ret.append([i, j])
break
elif customfunction.f(i, j) > z:
break
else:
j += 1
i += 1
return ret
cf = CustomFunction()
slu = Solution()
print(slu.findSolution(CustomFunction(), 5))
|
#!/usr/bin/env python
class SulException(Exception):
"""
"""
class ConfigurationException(SulException):
pass
class ServerException(SulException):
pass
class DirectoryNotFoundException(SulException):
pass
class IntegrityException(SulException):
pass
|
class UndergroundSystem:
def __init__(self):
self.count = defaultdict(int)
self.time = defaultdict(int)
self.traveling = dict()
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.traveling[id] = (stationName, t)
def checkOut(self, id: int, stationName: str, t: int) -> None:
(prev_station, prev_t) = self.traveling[id]
del self.traveling[id]
key = (prev_station, stationName)
self.count[key] += 1
self.time[key] += (t-prev_t)
def getAverageTime(self, startStation: str, endStation: str) -> float:
key = (startStation, endStation)
return self.time[key] / self.count[key]
# Your UndergroundSystem object will be instantiated and called as such:
# obj = UndergroundSystem()
# obj.checkIn(id,stationName,t)
# obj.checkOut(id,stationName,t)
# param_3 = obj.getAverageTime(startStation,endStation) |
class Patcher(object):
""" A dumb class to allow a mock.patch object to be used as a decorator and
a context manager
Typical usage::
import mock
import sys
my_mock = Patcher(mock.patch("sys.platform", "win32"))
@my_mock
def func1():
print(sys.platform)
def func2():
with my_mock:
print(sys.platform)
"""
def __init__(self, patcher):
self._patcher = patcher
def __call__(self, func):
return self._patcher(func)
def __enter__(self):
return self._patcher.__enter__()
def __exit__(self, *a, **kw):
return self._patcher.__exit__(*a, **kw)
class MultiPatcher(object):
""" Like Patcher, but applies a list of patchers.
"""
def __init__(self, patchers):
self._patchers = patchers
def __call__(self, func):
ret = func
for patcher in self._patchers:
ret = patcher(ret)
return ret
def __enter__(self):
return [patcher.__enter__() for patcher in self._patchers]
def __exit__(self, *a, **kw):
for patcher in self._patchers:
patcher.__exit__(*a, **kw)
|
def test_clear_images(client, seeder, app, utils):
user_id, admin_unit_id = seeder.setup_base()
image_id = seeder.upsert_default_image()
url = utils.get_image_url_for_id(image_id)
utils.get_ok(url)
runner = app.test_cli_runner()
result = runner.invoke(args=["cache", "clear-images"])
assert "Done." in result.output
|
def binary_slow(n):
assert n>=0
bits = []
while n:
bits.append('01'[n&1])
n >>= 1
bits.reverse()
return ''.join(bits) or '0'
|
# Containers for txid sequences start with this string.
CONTAINER_PREFIX = 'txids'
# Transaction ID sequence nodes start with this string.
COUNTER_NODE_PREFIX = 'tx'
# ZooKeeper stores the sequence counter as a signed 32-bit integer.
MAX_SEQUENCE_COUNTER = 2 ** 31 - 1
# The name of the node used for manually setting a txid offset.
OFFSET_NODE = 'txid_offset'
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class ValidNodeConfig(object):
def __init__(self, nodeVersion=None, imageId=None):
"""
:param nodeVersion: (Optional) kubernetes node 的版本
:param imageId: (Optional) 镜像id
"""
self.nodeVersion = nodeVersion
self.imageId = imageId
|
# Solution 1 - recursion
# O(log(n)) time / O(log(n)) space
def binarySearch1(array, target):
return binarySearchHelper1(array, target, 0, len(array) - 1)
def binarySearchHelper1(array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
potentialMatch = array[middle]
if target == potentialMatch:
return middle
elif target < potentialMatch:
return binarySearchHelper1(array, target, left, middle - 1)
else:
return binarySearchHelper1(array, target, middle + 1, right)
# Solution 2 - iteration
# O(log(n)) time / O(1) space
def binarySearch2(array, target):
return binarySearchHelper1(array, target, 0, len(array) - 1)
def binarySearchHelper2(array, target, left, right):
while left <= right:
middle = (left + right) // 2
potentialMatch = array[middle]
if target == potentialMatch:
return middle
elif target < potentialMatch:
right = middle - 1
else:
left = middle + 1
return -1
|
def levenshtein(source: str, target: str) -> int:
"""Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using the
Wagner-Fischer algorithm
(https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm).
These distances are defined recursively, since the distance between two
strings is just the cost of adjusting the last one or two characters plus
the distance between the prefixes that exclude these characters (e.g. the
distance between "tester" and "tested" is 1 + the distance between "teste"
and "teste"). The Wagner-Fischer algorithm retains this idea but eliminates
redundant computations by storing the distances between various prefixes in
a matrix that is filled in iteratively.
"""
# Create matrix of correct size (this is s_len + 1 * t_len + 1 so that the
# empty prefixes "" can also be included). The leftmost column represents
# transforming various source prefixes into an empty string, which can
# always be done by deleting all characters in the respective prefix, and
# the top row represents transforming the empty string into various target
# prefixes, which can always be done by inserting every character in the
# respective prefix. The ternary used to build the list should ensure that
# this row and column are now filled correctly
s_range = range(len(source) + 1)
t_range = range(len(target) + 1)
matrix = [[(i if j == 0 else j) for j in t_range] for i in s_range]
# Iterate through rest of matrix, filling it in with Levenshtein
# distances for the remaining prefix combinations
for i in s_range[1:]:
for j in t_range[1:]:
# Applies the recursive logic outlined above using the values
# stored in the matrix so far. The options for the last pair of
# characters are deletion, insertion, and substitution, which
# amount to dropping the source character, the target character,
# or both and then calculating the distance for the resulting
# prefix combo. If the characters at this point are the same, the
# situation can be thought of as a free substitution
del_dist = matrix[i - 1][j] + 1
ins_dist = matrix[i][j - 1] + 1
sub_trans_cost = 0 if source[i - 1] == target[j - 1] else 1
sub_dist = matrix[i - 1][j - 1] + sub_trans_cost
# Choose option that produces smallest distance
matrix[i][j] = min(del_dist, ins_dist, sub_dist)
# At this point, the matrix is full, and the biggest prefixes are just the
# strings themselves, so this is the desired distance
return matrix[len(source)][len(target)]
def levenshtein_norm(source: str, target: str) -> float:
"""Calculates the normalized Levenshtein distance between two string
arguments. The result will be a float in the range [0.0, 1.0], with 1.0
signifying the biggest possible distance between strings with these lengths
"""
# Compute Levenshtein distance using helper function. The max is always
# just the length of the longer string, so this is used to normalize result
# before returning it
distance = levenshtein(source, target)
return float(distance) / max(len(source), len(target))
# imagin, imogen, imagen, image, imagines, imahine, imoge
# list_que, status_list; dark, synthwav, synthese, "fantasy,"; bing
# could you embedify these instead of recalculating string distance? or cache
def match(source: str, targets: list[str]) -> tuple[float, str]:
return sorted(((levenshtein_norm(source, target), target) for target in targets))[0]
|
"""
pymatrices Package :-
- A Python 3.x Package to implement Matrices and its properties...
"""
class matrix:
"""Creates a Matrix using a 2-D list"""
def __init__(self, matrix):
self.__rows = len(matrix)
self.__cols = len(matrix[0])
for rows in matrix:
if len(rows) != self.__cols:
raise TypeError("Invalid Matrix")
if not isinstance(matrix, list):
tempMat = list(matrix)
else:
tempMat = matrix
for i in range(len(matrix)):
if not isinstance(matrix[i], list):
tempMat[i] = list(matrix[i])
self.__mat = tempMat
@property
def matrix(self):
return self.__mat
@property
def order(self):
return (self.__rows, self.__cols)
@property
def transpose(self):
order, res = self.order, []
for i in range(order[1]):
temp = []
for j in range(order[0]):
temp.append(self.matrix[j][i])
res.append(temp)
return matrix(res)
@property
def primaryDiagonalValues(self):
res = []
for i in range(len(self.matrix)):
for j in range(len(self.matrix[i])):
if i == j:
res.append(self.matrix[i][j])
return res
@property
def secondaryDiagonalValues(self):
order, res = self.order, []
for i in range(len(self.matrix)):
for j in range(len(self.matrix[i])):
if i+j == (order[0]-1):
res.append(self.matrix[i][j])
return res
def __repr__(self):
neg, minLen, res = False, len(f"{self.matrix[0][0]}"), ""
for row in self.matrix:
for val in row:
if len(f"{val}") > minLen:
minLen = len(f"{val}")
for row in self.matrix:
for val in row:
strVal = f"{val}"
res += " "*(minLen-len(strVal)) + strVal + " "
res += "\n"
return res
def __add__(self, other):
if isinstance(other, matrix):
if self.order == other.order:
res, temp = [], []
row, col = self.order
for i in range(row):
for j in range(col):
sum_elem = self.matrix[i][j] + other.matrix[i][j]
temp.append(sum_elem)
res.append(temp)
temp = []
return matrix(res)
else:
raise ValueError("Order of the Matrices must be same")
else:
raise TypeError(f"can only add matrix (not '{type(other).__name__}') to matrix")
def __sub__(self, other):
if isinstance(other, matrix):
if self.order == other.order:
res, temp = [], []
row, col = self.order
for i in range(row):
for j in range(col):
sum_elem = self.matrix[i][j] - other.matrix[i][j]
temp.append(sum_elem)
res.append(temp)
temp = []
return matrix(res)
else:
raise ValueError("Order of the Matrices must be same")
else:
raise TypeError(f"can only subtract matrix (not '{type(other).__name__}') from matrix")
def __mul__(self, other):
assert isinstance(other, (matrix, int, float)), f"Can only multiply either matrix or int or float (not {type(other).__name__}) with matrix"
if isinstance(other, matrix):
sOrder, oOrder = self.order, other.order
if sOrder[1] == oOrder[0]:
res = []
T_other = other.transpose
tOrder = T_other.order
for i in range(sOrder[0]):
temp = []
for j in range(tOrder[0]):
sum_val = 0
for k in range(tOrder[1]):
sum_val += (self.matrix[i][k] * T_other.matrix[j][k])
temp.append(sum_val)
res.append(temp)
else:
raise ValueError("Matrices can't be multiplied.")
elif isinstance(other, (int, float)):
order, res = self.order, []
for row in range(order[0]):
temp = []
for col in range(order[1]):
temp.append(self.matrix[row][col]*other)
res.append(temp)
return matrix(res)
def __truediv__(self, other):
if isinstance(other, (int, float)):
order, res = self.order, []
for row in range(order[0]):
temp = []
for col in range(order[1]):
temp.append(self.matrix[row][col]/other)
res.append(temp)
return matrix(res)
else:
raise ValueError("Matrix can only be divided by a number")
def __eq__(self, other):
if isinstance(other, matrix):
sOrder = self.order
if sOrder == other.order:
for row in range(sOrder[0]):
for col in range(sOrder[1]):
if self.matrix[row][col] != other.matrix[row][col]:
return False
else:
return True
else:
return False
else:
return False
def __neg__(self):
order, res = self.order, []
for row in range(order[0]):
temp = []
for col in range(order[1]):
temp.append(-self.matrix[row][col])
res.append(temp)
return matrix(res)
def positionOf(self, value):
row, col = self.order
for i in range(row):
for j in range(col):
if self.matrix[i][j] == value:
return (i+1, j+1)
else:
raise ValueError(f"There is no Element as {value} in the Matrix.")
def minorOfValueAt(self, row, column):
row -= 1; column -= 1
mat = [self.matrix[i] for i in range(len(self.matrix)) if i != row]
res = [[i[j] for j in range(len(i)) if j!=column] for i in mat]
return matrix(res)
def valueAt(self, row, column):
return self.matrix[row-1][column-1]
def adjoint(matrix1):
"""Returns the adjoint of matrix"""
order, mat = matrix1.order, matrix1.matrix
if order[0] == 2:
return matrix([[mat[1][1], -mat[0][1]], [-mat[1][0], mat[0][0]]])
else:
res = [[((-1)**(i+j+2))*(mat[i][j])*(determinant(matrix1.minorOfValueAt(i+1, j+1))) for j in range(order[1])] for i in range(order[0])]
return matrix(res)
def createByFilling(value, order):
"""Creates a Matrix of order by Filling it with value"""
rows, cols = order[0], order[1]
res = [[value for __ in range(cols)] for _ in range(rows)]
return matrix(res)
def createColumnMatrix(values):
"""Creates a Column Matrix with values"""
return matrix([[i] for i in values])
def createRowMatrix(values):
"""Creates a Row Matrix with values"""
return matrix([[i for i in values]])
def determinant(matrix):
"""Returns the determinant of matrix"""
order = matrix.order
if order[0] == order[1]:
mat = matrix.matrix
if order[0] == 1:
return mat[0][0]
elif order[0] == 2:
return (mat[1][1]*mat[0][0]) - (mat[1][0]*mat[0][1])
else:
M11 = mat[0][0]*(determinant(matrix.minorOfValueAt(1, 1)))
M12 = mat[0][1]*(determinant(matrix.minorOfValueAt(1, 2)))
M13 = mat[0][2]*(determinant(matrix.minorOfValueAt(1, 3)))
return M11 + M12 + M13
else:
raise ValueError(f"can only find the determinant of square matrix, not '{order[0]}x{order[1]}' matrix.")
def eigenvalues(matrix):
order = matrix.order
S1 = sum(matrix.primaryDiagonalValues)
assert order[0] in (1, 2, 3), "Maximum Order is 3x3"
if order[0] == 2:
S2 = determinant(matrix)
a, b, c = (1, -S1, S2)
disc = (b**2-4*a*c)**0.5
return ((-b+disc)/2*a, (-b-disc)/2*a)
elif order[0] == 3:
S2 = determinant(matrix.minorOfValueAt(1, 1))+determinant(matrix.minorOfValueAt(2, 2))+determinant(matrix.minorOfValueAt(3, 3))
S3 = determinant(matrix)
a, b, c, d = 1, -S1, S2, -S3
d0 = b**2 - 3*a*c
d1 = 2*b**3 - 9*a*b*c + 27*(a**2)*d
sqrt = (d1**2 - 4*(d0**3))**0.5
c1 = ((d1+sqrt)/2)**0.33
croot = (-1+3j)/2
try:
r1 = (-1/(3*a))*(b+c1+(d0/c1))
r2 = (-1/(3*a))*(b+croot*c1+(d0/croot*c1))
r3 = (-1/(3*a))*(b+(croot**2)*c1+(d0/(croot**2)*c1))
return (r1, r2, r3)
except ZeroDivisionError:
return ((-b/(3*a)),)*3
def inverse(matrix):
"""Returns the inverse of matrix"""
det = determinant(matrix)
if det != 0:
return adjoint(matrix)/det
else:
raise TypeError("Matrix is Singular.")
def isDiagonal(matrix):
"""Returns True if matrix is a 'Diagonal Matrix' else Returns False"""
order, mat = matrix.order, matrix.matrix
for row in range(order[0]):
for col in range(order[1]):
if row != col:
if mat[row][col] != 0:
return False
else:
return True
def I(order):
"""Returns the Identity Matrix of the given order"""
assert isinstance(order, int), f"order must be 'int' but got '{type(order).__name__}'"
res = [[0 for _ in range(order)] for __ in range(order)]
for i in range(order):
for j in range(order):
if i==j:
res[i][j] = 1
return matrix(res)
def O(order):
"""Returns the Square Null Matrix of the given order"""
assert isinstance(order, int), f"order must be 'int' but got '{type(order).__name__}'"
res = [[0 for _ in range(order)] for __ in range(order)]
return matrix(res)
def isIdempotent(matrix):
"""Returns True if matrix is an 'Idempotent Matrix' else Returns False"""
return True if matrix*matrix == matrix else False
def isIdentity(matrix):
"""Returns True if matrix is an 'Identity Matrix' else Returns False"""
return True if matrix == I(matrix.order[0]) else False
def isNilpotent(matrix):
"""Returns True if matrix is a 'Nilpotent Matrix' else Returns False"""
res = matrix
for i in range(1, matrix.order[0]+1):
res *= matrix
if isNull(res):
return True
else:
return False
def isNull(matrix):
"""Returns True if matrix is a 'Null Matrix' else Returns False"""
for i in matrix.matrix:
for j in i:
if j != 0:
return False
else:
return True
def isOrthogonal(matrix):
"""Returns True if matrix is an 'Orthogonal Matrix' else Returns False"""
return True if matrix*matrix.transpose == 0 else False
def isScalar(matrix):
"""Returns True if matrix is a 'Scalar Matrix' else Returns False"""
if isDiagonal(matrix):
order, val, mat = matrix.order, matrix.matrix[0][0], matrix.matrix
for row in range(order[0]):
for col in range(order[1]):
if row == col:
if mat[row][col] != val:
return False
else:
return True
else:
return False
def isSingular(matrix):
"""Returns True if matrix is a 'Singular Matrix' else Returns False"""
return True if determinant(matrix) == 0 else False
def isSquare(matrix):
"""Returns True if matrix is a 'Square Matrix' else Returns False"""
order = matrix.order
return True if order[0] == order[1] else False
def isSymmetric(matrix):
"""Returns True if matrix is a 'Symmetric Matrix' else Returns False"""
return True if matrix == matrix.transpose else False
def isSkewSymmetric(matrix):
"""Returns True if matrix is a 'Skew Symmetric Matrix' else Returns False"""
return True if matrix == -matrix.transpose else False |
# Uebungsblatt 2
# Uebung 1
i = 28
f = 28.0
print(i, id(i), type(i))
print(f, id(f), type(f))
# Uebung 2
i = 28.0
f = 28.0
print(i, id(i), type(i))
print(f, id(f), type(f))
# Uebung 3
s = "Hello"
s2 = s
print(s, id(s), s2, id(s2))
s += " World"
print(s, id(s), s2, id(s2))
# Uebung 4
m = ['a', 'b', 'd', 'e', 'f']
print(m, id(m))
m[0]='A'
print(m, id(m))
# Uebung 5
m2 = m
print(m, id(m), m2, id(m2))
m += 'g'
print(m, id(m), m2, id(m2))
# Uebung 6
t = (1, 2, [31, 32], 4)
t2 = t
print(t, id(t), t2, id(t2))
# t[0] = 'X'
# t[2,0] = 'X'
# TypeError: 'tuple' object does not support item assignment
# Uebung 7
t += 5,
print(t, id(t), t2, id(t2))
# Uebung 8
del t
# print(t, id(t), t2, id(t2))
# NameError: name 't' is not defined
print(t2, id(t2))
del t2
# print(t2, id(t2))
# NameError: name 't2' is not defined
# Uebung 9
x = 5
y = '5'
# z = x + y
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
|
n, m = map(int, input().split())
f = list(int(i) for i in input().split())
f.sort()
# formula -> f[i+n-1] - f[i]
ans = 10**9
for i in range(m-n+1):
ans = min(ans, f[i+n-1] - f[i])
print(ans) |
ENDPOINT_PATH = 'foobar'
BOOTSTRAP_SERVERS = 'localhost:9092'
TOPIC_RAW_REQUESTS = 'test.raw_requests'
TOPIC_PARSED_DATA = 'test.parsed_data'
USERNAME = None
PASSWORD = None
SASL_MECHANISM = None
SECURITY_PROTOCOL = 'PLAINTEXT'
# Use these when trying with FVH servers
# SASL_MECHANISM = "PLAIN"
# SECURITY_PROTOCOL = "SASL_SSL"
|
"""
Analyser of the relation.
@author: Minchiuan Gao <minchiuan.gao@gmail.com>
Build Date: 2015-Nov-25 Wed
"""
class RelationValue(object):
def __init__(self, title, weight, abbr, level):
self.title = title
self.weight = weight
self.abbr = abbr
self.level = level
class Analyse(object):
def __init__(self):
self.weigth = {}
def caculate_value(self, r1, r2, r3):
pass
def caculate_weigth(self, person1, peron2):
'''
Caculates the weight between person1 and person2
'''
pass
def read_data(self):
data = open('./data.data', 'r')
for line in data.readlines():
row = line.split('\t')
relationValue = RelationValue(row[0], row[1], row[2], row[3])
self.weight
if __name__ == '__main__':
analyse = Analyse()
analyse.read_data()
|
iSay = input('Введите фразу: ')
print('Введите 2 слова из этой фразы')
iFind1 = input('Первое: ')
iFind2 = input('Второе: ')
word1 = iSay.find(iFind1)
word2 = iSay.find(iFind2)
if (word1 < word2):
print('ДА')
else:
print('НЕТ')
|
# input
print('What is my favourite food?')
input_guess = input("Guess? ")
# response
while input_guess != 'electricity':
print("Not even close.")
input_guess = input("Guess? ")
print("You guessed it! Buzzzz")
|
"""Crie um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas:
B) Uma listagem com as pessoas mais pesadas:
C) Uma listagem com as pessoas mais leves:"""
temp = []
princ = []
mai = men = 0
while True:
temp.append(str(input('Nome: ')))
temp.append(float(input('Peso: ')))
if len(princ) == 0:
mai = men = temp[1]
else:
if temp[1] > mai:
mai = temp[1]
if temp[1] < men:
men = temp[1]
princ.append(temp[:])
temp.clear()
resp = str(input('Quer continuar? S/N '))
if resp in 'Nn':
break
print('\033[32m=|\033[m' * 40)
print(f'Os dados foram {princ}')
print(f'Ao todo foram cadastradas {len(princ)} pessoas. ')
print(f"O maior peso foi de \033[32m{mai}\033[m Kg. Peso de ", end='')
for p in princ:
if p[1] == mai:
print(f'[{p[0]}] ', end='')
print()
print(f"O menor peso foi de \033[32m{men}\033[m Kg. Peso de ", end='')
for p in princ:
if p[1] == men:
print(f'[{p[0]}] ', end='')
print()
print('\033[32m=|\033[m' * 40)
|
# Use enumerate() and other skills to return the count of the number of items in
# the list whose value equals its index.
def count_match_index(numbers):
return len([number for index, number in enumerate(numbers) if index == number])
result = count_match_index([0, 2, 2, 1, 5, 5, 6, 10])
print(result)
|
__title__ = 'elasticsearch-cli'
__version__ = '0.0.1'
__author__ = 'nevercaution'
__license__ = 'Apache v2'
|
## Largest 5 digit number in a series
## 7 kyu
## https://www.codewars.com/kata/51675d17e0c1bed195000001
def solution(digits):
biggest = 0
for index in range(len(digits) - 4):
if int(digits[index:index+5]) > biggest:
biggest = int(digits[index:index+5])
return biggest |
def candidates():
candidatesDictionary = {
#Initials : [First_name, Last_name, Club, Last_seen, 'TV_station', Total_time, Last_screenshot]
'AD': ['Andrzej', 'Duda', 'Bezpartyjny', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Prezydent_Rzeczypospolitej_Polskiej_Andrzej_Duda.jpg/240px-Prezydent_Rzeczypospolitej_Polskiej_Andrzej_Duda.jpg'],
'MKB' : ['Małgorzata', 'Kidawa-Błońska', 'Platforma Obywatelska', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Kidawa-B%C5%82o%C5%84ska_%28cropped%29.jpg/240px-Kidawa-B%C5%82o%C5%84ska_%28cropped%29.jpg'],
'SH' : ['Szymon', 'Hołownia', 'Bezpartyjny', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/02019_%283%29_Szymon_Ho%C5%82ownia.jpg/166px-02019_%283%29_Szymon_Ho%C5%82ownia.jpg'],
'RB' : ['Robert', 'Biedroń', 'Wiosna / Nowa Lewica','b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Robert_wiki.png/240px-Robert_wiki.png'],
'WKK' : ['Władysław', 'Kosiniak-Kamysz', 'Polskie Stronnictwo Ludowe', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/W%C5%82adys%C5%82aw_Kosiniak-Kamysz_Sejm_2016.JPG/163px-W%C5%82adys%C5%82aw_Kosiniak-Kamysz_Sejm_2016.JPG'],
'KB' : ['Krzysztof', 'Bosak', 'Konfederacja / Ruch Narodowy', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/JKRUK_20190927_KRZYSZTOF_BOSAK_KIELCE_IMGP2283.jpg/209px-JKRUK_20190927_KRZYSZTOF_BOSAK_KIELCE_IMGP2283.jpg'],
'PLM' : ['Piotr', ' Liroy-Marzec', 'Skuteczni', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Piotr_Liroy-Marzec_Sejm_2016a.jpg/168px-Piotr_Liroy-Marzec_Sejm_2016a.jpg'],
'LS' : ['Leszek', 'Samborski', 'Odpowiedzialność', 'b/d', 'b/d', 'b/d', 'https://portalniezalezny.pl/wp-content/uploads/2016/05/leszek_samobrski.jpg'],
'PB' : ['Piotr', 'Bakun', 'Bezpartyjny', 'b/d', 'b/d', 'b/d', 'https://scontent.fwaw5-1.fna.fbcdn.net/v/t1.0-9/43248180_340778723157575_4132832989245603840_n.png?_nc_cat=100&_nc_oc=AQmnsAjKoKb3pMRLc0q626fo64-Nr_dxI9DQl4QVONXckCPINnh77CJHUY_T5fJElL8&_nc_ht=scontent.fwaw5-1.fna&oh=5c22ef03e08609abaee81b7739d6c552&oe=5F02CDF5'],
'SZ' : ['Stanisław', 'Żółtek', 'Kongres Nowej Prawicy / PolEXIT', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Stanis%C5%82aw_%C5%BB%C3%B3%C5%82tek.JPG/180px-Stanis%C5%82aw_%C5%BB%C3%B3%C5%82tek.JPG'],
'WP' : ['Wojciech', 'Podjacki', 'Liga Obrony Suwerenności', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Wojciech_Podjacki.JPG/800px-Wojciech_Podjacki.JPG'],
#'MP' : ['Mirosław', ' Piotrowski', 'Ruch Prawdziwa Europa - Europa Christi', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Miros%C5%82aw_Piotrowski_%28Martin_Rulsch%29_1.jpg/152px-Miros%C5%82aw_Piotrowski_%28Martin_Rulsch%29_1.jpg'],
#'AV' : ['Andrzej', ' Voigt', 'Bezpartyjny', 'b/d', 'b/d', 'b/d', '']
}
return candidatesDictionary
def candidates_color_mapping(candidates):
colors = px.colors.qualitative.Light24
candidatesNames = ['{} {}'.format(candidates[candidate][0], candidates[candidate][1]) for candidate in candidates]
candidates_color_map = dict(zip(candidatesNames, colors))
return candidates_color_map |
"""
Quantum Probability
===================
"""
class QuantumProbability(
int,
):
def __init__(
self,
probability: int,
):
super().__new__(
int,
probability,
)
|
# Databricks notebook source
## Enter your group specific information here...
GROUP='group05' # CHANGE TO YOUR GROUP NAME
# COMMAND ----------
"""
Enter any project wide configuration here...
- paths
- table names
- constants
- etc
"""
# Some configuration of the cluster
spark.conf.set("spark.sql.shuffle.partitions", "32") # Configure the size of shuffles the same as core count on your cluster
spark.conf.set("spark.sql.adaptive.enabled", "true") # Spark 3.0 AQE - coalescing post-shuffle partitions, converting sort-merge join to broadcast join, and skew join optimization
# Mount the S3 class and group specific buckets
CLASS_DATA_PATH, GROUP_DATA_PATH = Utils.mount_datasets(GROUP)
# create the delta tables base dir in the s3 bucket for your group
BASE_DELTA_PATH = Utils.create_delta_dir(GROUP)
# Create the metastore for your group and set as the default db
GROUP_DBNAME = Utils.create_metastore(GROUP)
# class DB Name (bronze data resides here)
CLASS_DBNAME = "dscc202_db"
# COMMAND ----------
displayHTML(f"""
<table border=1>
<tr><td><b>Variable Name</b></td><td><b>Value</b></td></tr>
<tr><td>CLASS_DATA_PATH</td><td>{CLASS_DATA_PATH}</td></tr>
<tr><td>GROUP_DATA_PATH</td><td>{GROUP_DATA_PATH}</td></tr>
<tr><td>BASE_DELTA_PATH</td><td>{BASE_DELTA_PATH}</td></tr>
<tr><td>GROUP_DBNAME</td><td>{GROUP_DBNAME}</td></tr>
<tr><td>CLASS_DBNAME</td><td>{CLASS_DBNAME}</td></tr>
</table>
""") |
"""
A simple script.
This file shows why we use print.
Author: Walker M. White (wmw2)
Date: July 31, 2018
"""
x = 1+2 # I am a comment
x = 3*x
print(x) |
"""
В генеалогическом древе у каждого человека, кроме родоначальника, есть ровно один родитель. Каждом элементу дерева
сопоставляется целое неотрицательное число, называемое высотой. У родоначальника высота равна 0, у любого другого
элемента высота на 1 больше, чем у его родителя.Вам дано генеалогическое древо, определите высоту всех его элементов.
Формат ввода
Программа получает на вход число элементов в генеалогическом древе N. Далее следует N-1 строка, задающие родителя для
каждого элемента древа, кроме родоначальника.Каждая строка имеет вид имя_потомка имя_родителя.
Формат вывода
Программа должна вывести список всех элементов древа в лексикографическом порядке.После вывода имени каждого элемента
необходимо вывести его высоту.
Примечания
Эта задача имеет решение сложности O(n), но вам достаточнонаписать решение сложности O(n²) (не считая сложности
обращенияк элементам словаря).Пример ниже соответствует приведенному древу рода Романовых.
"""
tree = dict()
for i in range(int(input()) - 1):
child, parent = input().split()
tree[child] = parent
all_man = set(tree.keys()) | set(tree.values())
heights = dict()
def f(name):
if name not in tree:
heights[name] = 0
return 0
parent = tree[name]
if parent in heights:
value = heights[parent] + 1
else:
value = f(parent) + 1
heights[name] = value
return value
for name in all_man:
if name not in heights:
f(name)
for name in sorted(heights):
print(name, heights[name])
|
sal = float(input('Qual é o salario do funcionario? R$ '))
if sal > 1250:
alm = sal + (sal * 10 / 100)
if sal <= 1250:
alm = sal + (sal * 15 /100)
print('Quem ganhava R$ {:.2f} passa a ganhar R$ {:.2f} agora.'.format(sal, alm))
|
{
"targets": [
{
"target_name": "game",
"sources": [ "game.cpp" ]
}
]
} |
class Stack:
def __init__(self,max_size=4):
self.max_size = max_size
self.stk = [None]*max_size
self.last_pos = -1
def pop(self):
if self.last_pos < 0:
raise IndexError()
temp = self.stk[self.last_pos]
self.stk[self.last_pos]=None
if self.last_pos >=0:
self.last_pos-=1
return temp
def push(self,value):
if self.last_pos > self.max_size:
raise IndexError()
if self.last_pos<0:
self.last_pos+=1
self.stk[self.last_pos]=value
return
self.last_pos+=1
self.stk[self.last_pos]=value
def top(self):
return self.stk[self.last_pos]
def test_stack():
stk = Stack()
stk.push(1)
stk.push(2)
stk.push(3)
stk.push(4)
# print("********************")
# stk.push(5)
print("********************")
print(stk.pop())
print(stk.top())
print(stk.pop())
print(stk.top())
print(stk.pop())
print(stk.top())
print(stk.pop())
print(stk.pop())
if __name__ == "__main__":
test_stack() |
#!/usr/bin/env python3
"""Peter Rasmussen, Programming Assignment 1, utils.py
This module provides miscellaneous utility functions for this package.
"""
def compute_factorial(n: int) -> int:
"""
Compute n-factorial.
:param n: Number to compute factorial for
:return: n-factorial
"""
if (not isinstance(n, int)) or (n < 0):
raise ValueError("compute_factorial() only accepts non-negative integer values.")
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
def n_choose_k(n, m=2) -> int:
"""
Return number of ways to draw a subset of size m from set of size n.
:param n: Set size
:param m: Size of each subset
:return: Number of ways to draw a subset of size m from set of size n
"""
integers = (not isinstance(n, int)) or (not isinstance(m, int))
nonnegative = (n >= 0) and (m >= 0)
if integers and nonnegative:
raise TypeError("The parameters n and m must be non-negative integers.")
if m > n:
raise ValueError("The parameter m must be less than or equal to n.")
return int(compute_factorial(n) / (compute_factorial(m) * compute_factorial(n - m)))
|
# Cambiar valor de la semilla aca
seed = 1
# Cambiar cantidad de iteraciones aca
cantidadIteraciones = 10
# Devuelve un número aleatorio entre 0 y 1
def random():
global seed
a = 16807
m = 2147483647
q = 127773
r = 2836
hi = seed // q
lo = seed % q
test = a*lo - r*hi
if (test > 0):
seed = test
else:
seed = test + m
return seed / m
# Imprime valor de la semilla y los numeros aleatorios generados
print("Semilla:", seed)
for i in range(0, cantidadIteraciones):
print("Iteracion:", i+1, ", Valor:", random()) |
DEFAULT_SERVER_HOST = "localhost"
DEFAULT_SERVER_PORT = 11211
DEFAULT_POOL_MINSIZE = 2
DEFAULT_POOL_MAXSIZE = 5
DEFAULT_TIMEOUT = 1
DEFAULT_MAX_KEY_LENGTH = 250
DEFAULT_MAX_VALUE_LENGTH = 1024 * 1024 # 1 megabyte
STORED = b"STORED\r\n"
NOT_STORED = b"NOT_STORED\r\n"
EXISTS = b"EXISTS\r\n"
NOT_FOUND = b"NOT_FOUND\r\n"
DELETED = b"DELETED\r\n"
TOUCHED = b"TOUCHED\r\n"
END = b"END\r\n"
VERSION = b"VERSION"
OK = b"OK\r\n"
|
def median(pool):
copy = sorted(pool)
size = len(copy)
if size % 2 == 1:
return int(copy[int((size-1) / 2)])
else:
return (int(copy[int((size) / 2)-1]) + int(copy[int(size / 2)])) / 2
|
# Python program to calculate C(n, k)
# Returns value of Binomial Coefficient
# C(n, k)
def binomialCoefficient(n, k):
# since C(n, k) = C(n, n - k)
if(k > n - k):
k = n - k
# initialize result
res = 1
# Calculate value of
# [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1]
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
# Driver program to test above function
n,k= map(int, input().split())
res = binomialCoefficient(n, k)
print("Value of C(% d, % d) is % d" %(n, k, res))
'''
TEST CASES
Input =
5 3
Output =
Value of C( 5, 3) is 10
Input =
8 1
Output =
Value of C( 8, 1) is 8
'''
|
#does array have duplicate entries
a=[1,2,3,4,5,1,7]
i=1
j=1
for num in a:
for ab in range(len(a)):
if num==a[i]:
print("duplicate found! ",num,"is = a[",i,"]")
else:
print(num,"is not = a[",i,"]" )
if i>4:
break
else:
i=i+1
i=0
|
{
'name': 'To-Do Kanban board',
'description': 'Kanban board to manage to-do tasks.',
'author': 'Daniel Reis',
'depends': ['todo_ui'],
'data': ['views/todo_view.xml'],
}
|
# play sound
file = "HappyBirthday.mp3"
print('playing sound using native player')
os.system("afplay " + file) |
class SkiffKernel(object):
"""SkiffKernel"""
def __init__(self, options=None, **kwargs):
super(SkiffKernel, self).__init__()
if not options:
options = kwargs
self._json = options
self.__dict__.update(options)
def __repr__(self):
return '<%s (#%s) %s>' % (self.name, self.id, self.version)
|
class Solution(object):
def splitIntoFibonacci(self, S):
"""
:type S: str
:rtype: List[int]
"""
Solution.res= []
self.backtrack(0, 0, 0, [],S)
return Solution.res
def backtrack(self, start, last1, last2, intList, string):
for i in range(start,len(string)):
cur = int(string[start:i + 1])
if len(string[start:i + 1]) != len(str(cur)):
break
# if cur > 2147483647:
# break
if len(intList) == 0:
self.backtrack(i + 1, cur, last2, intList + [cur], string)
elif len(intList) == 1:
self.backtrack(i + 1, last1, cur, intList + [cur], string)
else:
if cur > last1 + last2:
break
elif cur == last1 + last2:
if i == len(string) - 1:
Solution.res = intList + [cur]
return
else:
self.backtrack(i + 1, last2, cur, intList + [cur], string)
else:
continue
s = Solution()
print(s.splitIntoFibonacci("123456579")) |
v = 18
_v = 56
def f():
pass
def _f():
pass
class MyClass(object):
pass
class _MyClass(object):
pass
|
# Değişkenlerin tanımlanması.
adet = 20
x = 0
buyuk = 0
kucuk = 0
i = 0
p = 0
j = 0
ort = 0
p_ort = 0
# İlk “x” değerinin döngüye girmeden girilmesi
x = int(input())
buyuk = x
kucuk = x
# Değişkenlere koşullar kontrol edilerek değer atanması
if (x > 0):
p_ort = p_ort + x
p += 1
if (x > 100 and x < 200) :
j += 1
ort = ort + x
# “adet-1” kere dönen döngünün oluşturulması
for i in range(0,adet-1):
# “x” değerinin döngüde girilmesi
x = int(input())
# Pozitif sayıların tespit edilmesi
if(x > 0):
p_ort = p_ort + x
p += 1
# 100<x<200 koşulunun kontrol edilmesi
if(x > 100 and x >200):
j += 1
# “x>buyuk” ve “x<kucuk” koşulunun kontrol edilmesi.
if(x > buyuk):
buyuk = x
if(x < kucuk):
kucuk = x
# “x” değerinin “ort”a eklenmesi.
ort = ort + x
# Ortalamaların hesaplanması
ort = ort / adet
p_ort = p_ort / p
# Sonuçların yazdırılması
print("Ortalama= ",ort)
print("En buyuk sayi= ",buyuk)
print("En kucuk sayi= ",kucuk)
print("Pozitif olanlarin ortalamasi= ",p_ort)
print("100-200 arasindaki sayilarin sayisi= ",j)
|
# -*- coding: utf-8 -*-
# Service key from www.data.go.kr
ServiceKey = "Ej9BN7hUDaYUbYCEde4crW5llAbmNvkMXsLimF3up9FBCO4nkGilDfzfHQe33kIhgXBt%2Bl%2BPbnivoQn%2BTMmLWg%3D%3D"
MobileOS = "ETC"
MobileApp = "Test"
Languages = [
{"code": "Kor", "name": "한국"},
{"code": "Eng", "name": "English"},
{"code": "Jpn", "name": "일본"},
{"code": "Chs", "name": "중문간체"},
{"code": "Cht", "name": "중문번체"},
{"code": "Ger", "name": "Germany"},
{"code": "Fre", "name": "French"},
{"code": "Spn", "name": "Spain"},
{"code": "Rus", "name": "Russian"},
]
AreaCodes = [
{"code1": 1, "name": "서울"},
{"code1": 2, "name": "인천"},
{"code1": 3, "name": "대전"},
{"code1": 4, "name": "대구"},
{"code1": 5, "name": "광주"},
{"code1": 6, "name": "부산"},
{"code1": 7, "name": "울산"},
{"code1": 8, "name": "세종"},
{"code1": 31, "name": "경기"},
{"code1": 32, "name": "강원"},
{"code1": 33, "name": "충북"},
{"code1": 34, "name": "충남"},
{"code1": 35, "name": "경북"},
{"code1": 36, "name": "경남"},
{"code1": 37, "name": "전북"},
{"code1": 38, "name": "전남"},
{"code1": 39, "name": "제주"},
]
Cat1 = [
{"code": "A01", "name": "자연"},
{"code": "A02", "name": "인문"},
{"code": "A03", "name": "레포츠"},
{"code": "A04", "name": "쇼핑"},
{"code": "A05", "name": "음식"},
{"code": "B01", "name": "교통"},
{"code": "B02", "name": "숙박"},
{"code": "C01", "name": "추천코스"},
]
Cat2 = [
{"code": "A0101", "name": "자연관광지"},
{"code": "A0102", "name": "관광자원"},
{"code": "A0201", "name": "역사관광지"},
{"code": "A0202", "name": "휴양관광지"},
{"code": "A0203", "name": "체험관광지"},
{"code": "A0204", "name": "산업관광지"},
{"code": "A0205", "name": "건축조형물"},
{"code": "A0206", "name": "문화시설"},
{"code": "A0207", "name": "축제"},
{"code": "A0208", "name": "공연행사"},
{"code": "A0301", "name": "레포츠소개"},
{"code": "A0302", "name": "육상레포츠"},
{"code": "A0303", "name": "수상레포츠"},
{"code": "A0304", "name": "항공레포츠"},
{"code": "A0305", "name": "복합레포츠"},
{"code": "A0401", "name": "쇼핑"},
{"code": "A0502", "name": "음식점"},
{"code": "B0101", "name": "교통수단"},
{"code": "B0102", "name": "교통시설"},
{"code": "B0201", "name": "숙박시설"},
{"code": "C0112", "name": "가족코스"},
{"code": "C0113", "name": "나홀로코스"},
{"code": "C0114", "name": "힐링코스"},
{"code": "C0115", "name": "도보코스"},
{"code": "C0116", "name": "캠핑코스"},
{"code": "C0117", "name": "맛코스"},
]
WellnessCategories = [
{"code": "A01010600", "name": "자연휴양림"},
{"code": "A01010700", "name": "수목원"},
{"code": "A02020300", "name": "온천/욕장/스파"},
{"code": "A02020400", "name": "이색찜질방"},
{"code": "A02020500", "name": "헬스투어"},
{"code": "A02030100", "name": "농,산,어촌 체험"},
{"code": "A02030200", "name": "전통체험"},
{"code": "A02030300", "name": "산사체험"},
{"code": "A02030500", "name": "관광농원"},
{"code": "A05020800", "name": "채식전문점"},
# {"code": "B02011400", "name": "의료관광호텔"},
{"code": "B02011600", "name": "한옥스테이"},
{"code": "C01140001", "name": "힐링코스"},
{"code": "C01150001", "name": "도보코스"},
{"code": "C01160001", "name": "캠핑코스"}
]
IntroContentTypes = {
12:"관광지",
14:"문화시설",
15:"행사/공연/축제",
25:"여행코스",
28:"레포츠",
32:"숙박",
38:"쇼핑",
39:"음식점"
}
Cat3 = [
{"code": "A01010100", "name": "국립공원"},
{"code": "A01010200", "name": "도립공원"},
{"code": "A01010300", "name": "군립공원"},
{"code": "A01010400", "name": "산"},
{"code": "A01010500", "name": "자연생태관광지"},
{"code": "A01010600", "name": "자연휴양림"},
{"code": "A01010700", "name": "수목원"},
{"code": "A01010800", "name": "폭포"},
{"code": "A01010900", "name": "계곡"},
{"code": "A01011000", "name": "약수터"},
{"code": "A01011100", "name": "해안절경"},
{"code": "A01011200", "name": "해수욕장"},
{"code": "A01011300", "name": "섬"},
{"code": "A01011400", "name": "항구/포구"},
{"code": "A01011500", "name": "어촌"},
{"code": "A01011600", "name": "등대"},
{"code": "A01011700", "name": "호수"},
{"code": "A01011800", "name": "강"},
{"code": "A01011900", "name": "동굴"},
{"code": "A01020100", "name": "희귀동.식물"},
{"code": "A01020200", "name": "기암괴석"},
{"code": "A02010100", "name": "고궁"},
{"code": "A02010200", "name": "성"},
{"code": "A02010300", "name": "문"},
{"code": "A02010400", "name": "고택"},
{"code": "A02010500", "name": "생가"},
{"code": "A02010600", "name": "민속마을"},
{"code": "A02010700", "name": "유적지/사적지"},
{"code": "A02010800", "name": "사찰"},
{"code": "A02010900", "name": "종교성지"},
{"code": "A02011000", "name": "안보관광"},
{"code": "A02020100", "name": "유원지"},
{"code": "A02020200", "name": "관광단지"},
{"code": "A02020300", "name": "온천/욕장/스파"},
{"code": "A02020400", "name": "이색찜질방"},
{"code": "A02020500", "name": "헬스투어"},
{"code": "A02020600", "name": "테마공원"},
{"code": "A02020700", "name": "공원"},
{"code": "A02020800", "name": "유람선/잠수함관광"},
{"code": "A02030100", "name": "농.산.어촌 체험"},
{"code": "A02030200", "name": "전통체험"},
{"code": "A02030300", "name": "산사체험"},
{"code": "A02030400", "name": "이색체험"},
{"code": "A02030500", "name": "관광농원"},
{"code": "A02030600", "name": "이색거리"},
{"code": "A02040100", "name": "제철소"},
{"code": "A02040200", "name": "조선소"},
{"code": "A02040300", "name": "공단"},
{"code": "A02040400", "name": "발전소"},
{"code": "A02040500", "name": "광산"},
{"code": "A02040600", "name": "식음료"},
{"code": "A02040700", "name": "화학/금속"},
{"code": "A02040800", "name": "기타"},
{"code": "A02040900", "name": "전자/반도체"},
{"code": "A02041000", "name": "자동차"},
{"code": "A02050100", "name": "다리/대교"},
{"code": "A02050200", "name": "기념탑/기념비/전망대"},
{"code": "A02050300", "name": "분수"},
{"code": "A02050400", "name": "동상"},
{"code": "A02050500", "name": "터널"},
{"code": "A02050600", "name": "유명건물"},
{"code": "A02060100", "name": "박물관"},
{"code": "A02060200", "name": "기념관"},
{"code": "A02060300", "name": "전시관"},
{"code": "A02060400", "name": "컨벤션센터"},
{"code": "A02060500", "name": "미술관/화랑"},
{"code": "A02060600", "name": "공연장"},
{"code": "A02060700", "name": "문화원"},
{"code": "A02060800", "name": "외국문화원"},
{"code": "A02060900", "name": "도서관"},
{"code": "A02061000", "name": "대형서점"},
{"code": "A02061100", "name": "문화전수시설"},
{"code": "A02061200", "name": "영화관"},
{"code": "A02061300", "name": "어학당"},
{"code": "A02061400", "name": "학교"},
{"code": "A02070100", "name": "문화관광축제"},
{"code": "A02070200", "name": "일반축제"},
{"code": "A02080100", "name": "전통공연"},
{"code": "A02080200", "name": "연극"},
{"code": "A02080300", "name": "뮤지컬"},
{"code": "A02080400", "name": "오페라"},
{"code": "A02080500", "name": "전시회"},
{"code": "A02080600", "name": "박람회"},
{"code": "A02080700", "name": "컨벤션"},
{"code": "A02080800", "name": "무용"},
{"code": "A02080900", "name": "클래식음악회"},
{"code": "A02081000", "name": "대중콘서트"},
{"code": "A02081100", "name": "영화"},
{"code": "A02081200", "name": "스포츠경기"},
{"code": "A02081300", "name": "기타행사"},
{"code": "C01050100", "name": "추천여행코스"},
{"code": "C01050200", "name": "여행코스견문록"},
{"code": "C01120001", "name": "가족코스"},
{"code": "C01130001", "name": "나홀로코스"},
{"code": "C01140001", "name": "힐링코스"},
{"code": "C01150001", "name": "도보코스"},
{"code": "C01160001", "name": "캠핑코스"},
{"code": "C01170001", "name": "맛코스"},
{"code": "A03010100", "name": "육상레포츠"},
{"code": "A03010200", "name": "수상레포츠"},
{"code": "A03010300", "name": "항공레포츠"},
{"code": "A03020100", "name": "스포츠센터"},
{"code": "A03020200", "name": "수련시설"},
{"code": "A03020300", "name": "경기장"},
{"code": "A03020400", "name": "인라인(실내 인라인 포함)"},
{"code": "A03020500", "name": "자전거하이킹"},
{"code": "A03020600", "name": "카트"},
{"code": "A03020700", "name": "골프"},
{"code": "A03020800", "name": "경마"},
{"code": "A03020900", "name": "경륜"},
{"code": "A03021000", "name": "카지노"},
{"code": "A03021100", "name": "승마"},
{"code": "A03021200", "name": "스키/스노보드"},
{"code": "A03021300", "name": "스케이트"},
{"code": "A03021400", "name": "썰매장"},
{"code": "A03021500", "name": "수렵장"},
{"code": "A03021600", "name": "사격장"},
{"code": "A03021700", "name": "야영장,오토캠핑장"},
{"code": "A03021800", "name": "암벽등반"},
{"code": "A03021900", "name": "빙벽등반"},
{"code": "A03022000", "name": "서바이벌게임"},
{"code": "A03022100", "name": "ATV"},
{"code": "A03022200", "name": "MTB"},
{"code": "A03022300", "name": "오프로드"},
{"code": "A03022400", "name": "번지점프"},
{"code": "A03022500", "name": "자동차경주"},
{"code": "A03022600", "name": "스키(보드) 렌탈샵"},
{"code": "A03022700", "name": "트래킹"},
{"code": "A03030100", "name": "윈드서핑/제트스키"},
{"code": "A03030200", "name": "카약/카누"},
{"code": "A03030300", "name": "요트"},
{"code": "A03030400", "name": "스노쿨링/스킨스쿠버다이빙"},
{"code": "A03030500", "name": "민물낚시"},
{"code": "A03030600", "name": "바다낚시"},
{"code": "A03030700", "name": "수영"},
{"code": "A03030800", "name": "래프팅"},
{"code": "A03040100", "name": "스카이다이빙"},
{"code": "A03040200", "name": "초경량비행"},
{"code": "A03040300", "name": "헹글라이딩/패러글라이딩"},
{"code": "A03040400", "name": "열기구"},
{"code": "A03050100", "name": "복합 레포츠"},
{"code": "B02010100", "name": "관광호텔"},
{"code": "B02010200", "name": "수상관광호텔"},
{"code": "B02010300", "name": "전통호텔"},
{"code": "B02010400", "name": "가족호텔"},
{"code": "B02010500", "name": "콘도미니엄"},
{"code": "B02010600", "name": "유스호스텔"},
{"code": "B02010700", "name": "펜션"},
{"code": "B02010800", "name": "여관"},
{"code": "B02010900", "name": "모텔"},
{"code": "B02011000", "name": "민박"},
{"code": "B02011100", "name": "게스트하우스"},
{"code": "B02011200", "name": "홈스테이"},
{"code": "B02011300", "name": "서비스드레지던스"},
{"code": "B02011400", "name": "의료관광호텔"},
{"code": "B02011500", "name": "소형호텔"},
{"code": "B02011600", "name": "한옥스테이"},
{"code": "A04010100", "name": "5일장"},
{"code": "A04010200", "name": "상설시장"},
{"code": "A04010300", "name": "백화점"},
{"code": "A04010400", "name": "면세점"},
{"code": "A04010500", "name": "할인매장"},
{"code": "A04010600", "name": "전문상가"},
{"code": "A04010700", "name": "공예,공방"},
{"code": "A04010800", "name": "관광기념품점"},
{"code": "A04010900", "name": "특산물판매점"},
{"code": "A05010100", "name": "한국요리소개"},
{"code": "A05010200", "name": "궁중음식"},
{"code": "A05010300", "name": "전통차"},
{"code": "A05010400", "name": "한과"},
{"code": "A05010500", "name": "전통주/민속주"},
{"code": "A05010600", "name": "지역음식"},
{"code": "A05010700", "name": "조리법"},
{"code": "A05010800", "name": "식사법"},
{"code": "A05020100", "name": "한식"},
{"code": "A05020200", "name": "서양식"},
{"code": "A05020300", "name": "일식"},
{"code": "A05020400", "name": "중식"},
{"code": "A05020500", "name": "아시아식"},
{"code": "A05020600", "name": "패밀리레스토랑"},
{"code": "A05020700", "name": "이색음식점"},
{"code": "A05020800", "name": "채식전문점"},
{"code": "A05020900", "name": "바/까페"},
{"code": "A05021000", "name": "클럽"},
{"code": "B01010100", "name": "항공"},
{"code": "B01010200", "name": "철도"},
{"code": "B01010300", "name": "지하철"},
{"code": "B01010400", "name": "버스"},
{"code": "B01010500", "name": "선박"},
{"code": "B01010600", "name": "렌터카"},
{"code": "B01010700", "name": "택시"},
{"code": "B01020100", "name": "공항"},
{"code": "B01020200", "name": "기차역"},
{"code": "B01020300", "name": "버스터미널"},
{"code": "B01020400", "name": "여객선터미널"},
] |
def solve_single_lin(opt_x_s):
'''
solve one opt_x[s]
'''
opt_x_s.solve(solver='MOSEK', verbose = True)
return opt_x_s |
pkgname = "xsetroot"
pkgver = "1.1.2"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
makedepends = [
"xbitmaps", "libxmu-devel", "libxrender-devel",
"libxfixes-devel", "libxcursor-devel"
]
pkgdesc = "X root window parameter setting utility"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "https://xorg.freedesktop.org"
source = f"$(XORG_SITE)/app/{pkgname}-{pkgver}.tar.bz2"
sha256 = "10c442ba23591fb5470cea477a0aa5f679371f4f879c8387a1d9d05637ae417c"
def post_install(self):
self.install_license("COPYING")
|
def is_num(in_value):
"""Checks if a value is a valid number.
Parameters
----------
in_value
A variable of any type that we want to check is a number.
Returns
-------
bool
True/False depending on whether it was a number.
Examples
--------
>>> is_num(1)
True
>>> is_num("Hello")
False
You can also pass more complex objects, these will all be ''False''.
>>> is_num({"hi": "apple"})
False
"""
try:
float(in_value)
return True
except (ValueError, TypeError):
return False
|
class Item:
def __init__(self, block_id, count, damage, data):
self.block_id = block_id
self.count = count
self.damage = damage
self.data = data
def __str__(self):
return 'block: {:3d}, count: {:2d}, damage: {}'.format(self.block_id, self.count, self.damage)
|
"""
103. Binary Tree Zigzag Level Order Traversal
Given a binary tree,
return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
a modification from 102
author: gengwg
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.preorder(root, 0, res)
return res
def preorder(self, root, level, res):
if root:
# create an empty list for new level
if len(res) <= level:
res.append([])
if level % 2 == 0:
# even level, append at the end
res[level].append(root.val)
else:
# at odd level, append to the beginning
res[level].insert(0, root.val)
self.preorder(root.left, level + 1, res)
self.preorder(root.right, level + 1, res)
|
BAZEL_VERSION_SHA256S = {
"0.14.1": "7b14e4fc76bf85c4abf805833e99f560f124a3b96d56e0712c693e94e19d1376",
"0.15.0": "7f6748b48a7ea6bdf00b0e1967909ce2181ebe6f377638aa454a7d09a0e3ea7b",
"0.15.2": "13eae0f09565cf17fc1c9ce1053b9eac14c11e726a2215a79ebaf5bdbf435241",
"0.16.1": "17ab70344645359fd4178002f367885e9019ae7507c9c1ade8220f3628383444",
}
# This is the map from supported Bazel versions to the Bazel version used to
# generate the published toolchain configs that the former should be used with.
# This is needed because, in most cases, patch updates in Bazel do not result in
# changes in toolchain configs, so we do not publish duplicated toolchain
# configs. So, for example, Bazel 0.15.2 should still use published toolchain
# configs generated with Bazel 0.15.0.
BAZEL_VERSION_TO_CONFIG_VERSION = {
"0.14.1": "0.14.1",
"0.15.0": "0.15.0",
"0.15.2": "0.15.0",
"0.16.1": "0.16.1",
}
|
def censor(text, word):
bigstring = text.split()
print (bigstring)
words = ""
" ".join(bigstring)
return bigstring
print (censor("hello hi hey", "hi")) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 18:30:18 2020
@author: MarcoSilva
"""
def general_poly (L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
def f(x):
total = 0
fact = len(L) - 1
for num in L:
print(num)
total += num * x**fact
fact -= 1
return total
return f
|
config = {
'api_root': 'https://library.cca.edu/api/v1',
'client_id': 'abcedfg-123445678',
'client_secret': 'abcedfg-123445678',
}
|
"""
Power digit sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
"""
exponent = 1000
def initial_func(exponent):
return sum(int(digit) for digit in f'{2 ** exponent}')
def improved_func(exponent):
pass
# 1366
print(initial_func(exponent))
# print(improved_func(exponent))
|
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.logo = A(B('Placement portal'),_class="brand",
_id="web2py-logo")
response.title = request.application.replace('_',' ').title()
response.subtitle = ''
## read more at http://dev.w3.org/html5/markup/meta.name.html
response.meta.author = 'Your Name <you@example.com>'
response.meta.description = 'a cool new app'
response.meta.keywords = 'web2py, python, framework'
response.meta.generator = 'Web2py Web Framework'
## your http://google.com/analytics id
response.google_analytics_id = None
#########################################################################
## this is the main application menu add/remove items as required
#########################################################################
if auth.has_membership('student_group') and not auth.has_membership('spc_group'):
response.menu= [
(T('Home'), False, URL('default', 'index'), []),
(T('Apply'), False, URL('s_controller','apply_for'),[]
),(T('Spc'), False,URL('s_controller','spc'),[])
]
elif auth.has_membership('student_group') and auth.has_membership('spc_group'):
response.menu= [
(T('Home'), False, URL('default', 'index'), []),
(T('Apply'), False, URL('s_controller','apply_for'),[]
),(T('View Student Deatils'), False, URL('s_controller','spc_view'),[]
)]
elif auth.has_membership('company_group'):
response.menu= [
(T('Home'), False, URL('default', 'index'), []),
(T('New Posting'), False,URL('c_controller','posting'),[]),
(T('View Posting'), False,URL('c_controller','view_posting'),[])
]
elif auth.has_membership('TPO'):
response.menu = [
(T('Home'), False, URL('default', 'index'), []),
]
else:
response.menu = [
(T('Home'), False, URL('default', 'index'), []),
(T('Student Register'), False, URL('s_controller', 'reg_s'), []),
(T('Company Register'), False, URL('c_controller', 'reg_c'), [])
]
DEVELOPMENT_MENU = True
if "auth" in locals(): auth.wikimenu()
|
def bubble_sort(elements: list):
"""Sort the list inplace using bubble sort.
Args:
--
elements (list): list of elements
"""
size = len(elements)
for i in range(size - 1):
# if list is already sorted track it using swapped variable
swapped = False
for j in range(size - 1 - i):
if elements[j] > elements[j + 1]:
# swapping
tmp = elements[j]
elements[j] = elements[j + 1]
elements[j + 1] = tmp
swapped = True
if not swapped:
break
if __name__ == "__main__":
elements = [5, 9, 2, 1, 67, 34, 88, 34]
print(f"Before Sorting: {elements}")
bubble_sort(elements)
print(f"After sorting: {elements} ")
|
# filter().py
def func(a):
if a <100:
return True
else:
return False
print(list(filter(func,[10,56,101,500])))
# 返回True所对应的值
def f(x):
x = 100
print(x)
a = 1
f(a)
print(a)
|
# game model list base class for all object collections in game
class GameModelList():
def __init__(
self,
game,
game_models=[],
collidable=False,
block_color=None
):
self.game = game
self.game_models = game_models
self.collidable = collidable
self.block_color = block_color
for model in self.game_models:
model.set_collidable(self.collidable)
def add_game_model(self, game_model):
self.game_models.append(game_model)
game_model.set_collidable(self.collidable)
def get_game_models(self):
return self.game_models
def remove_game_model(self, game_model):
self.game_models.remove(game_model)
def get_block_color(self):
return self.block_color
def draw(self):
for block in self.game_models:
block.draw()
def update(self):
for model in self.game_models:
model.update()
|
# Author: Ian Burke
# Module: Emerging Technologies
# Date: September, 2017
# Problem Sheet: https://emerging-technologies.github.io/problems/python-fundamentals.html
# create a function to reverse a string
def reverse():
word = input("Enter a string: ") #user enters a string and store it in word
word = word[::-1] # slices and reverses the string
# Reference: https://stackoverflow.com/questions/931092/reverse-a-string-in-python
print(word)
reverse() # call function to run
|
# GENERATED VERSION FILE
# TIME: Tue Oct 26 14:07:11 2021
__version__ = '0.3.0+dc45206'
short_version = '0.3.0'
|
class Cuenta:
def __init__(self, nombre, numero, saldo):
self.nombre = nombre
self.numero= numero
self.saldo = saldo
def depositar(self, a):
self.saldo=self.saldo+a
return self.saldo
def retirar(self, a):
self.saldo=self.saldo-a
return self.saldo
|
# coding: utf-8
def convert(word):
word = word.replace('vv','1')
word = word.replace('ll','2')
word = word.replace('ss','3')
word = word.replace('gg','4')
word = word.replace('rr','5')
word = word.replace('ng','6')
word = word.replace('μ','7')
word = word.replace('+','8')
word = word.replace('TMg','9')
word = word.replace('¥r','j')
word = word.replace('¥rr','z')
word = word.replace('¥g','x')
word = word.replace('¥k','h')
word = word.replace('¥q','d')
return word
def deconvert(word):
word = word.replace('1','vv')
word = word.replace('2','ll')
word = word.replace('3','ss')
word = word.replace('4','gg')
word = word.replace('5','rr')
word = word.replace('6','ng')
word = word.replace('7','m2')
word = word.replace('8','n2')
word = word.replace('9','ng2')
word = word.replace('j','¥r')
word = word.replace('z','¥rr')
word = word.replace('x','¥g')
word = word.replace('h','¥k')
word = word.replace('d','¥q')
return word |
temp=n=int(input("Enter a number: "))
sum1 = 0
while(n > 0):
sum1=sum1+n
n=n-1
print(f"natural numbers in series {sum1}+{n}")
print(f"The sum of first {temp} natural numbers is: {sum1}") |
n = str(input('Digite seu nome : ')).strip()
print('Muito prazer em te conhecer ! ')
nome = n.split()
print('O seu primeiro nome é: {}'.format(nome[0]))
print('O seu último nome é: {}'.format(nome[len(nome)-1]))
#n = str(input('Digite seu nome completo : ')).strip()
#print('Olá! Prazer em te conhecer ! ')
#nome = n.split()
#print('O seu primeiro nome é: {} '.format(nome[0]))
#print('O seu último nome é: {}'.format(nome[len(nome)-1]))
#n = str(input('Digite seu nome completo : '))
#print('Ola seja Bem-vindo! Muito prazer em te conhecer ! ')
#nome = n.split()
#print('O seu primeiro nome é: {}'.format(nome[0]))
#print('O seu último nome é: {}'.format(nome[len(nome)-1]))
|
# red_black_node.py
class Node:
"""
A class used to represent a Node in a red-black search tree.
Attributes:
key: The key is the value the node shall be sorted on. The key can be an integer,
float, string, anything capable of being sorted.
instances (int): The number of times the key for a node was inserted into the tree.
parent (node): The pointer to the parent of the node.
left (node): The pointer to the left child node.
right (node): The pointer to the right child node.
is_red (bool): The color attribute keeps track of whether a node is red or black.
"""
def __init__(self, key):
"""
Parameters:
key: The key is the value the node shall be sorted on. The key can be an integer,
float, string, anything capable of being sorted.
"""
self.key = key
self.instances = 1
self.parent = None
self.left = None
self.right = None
self.is_red = True
def recolor(self):
"""
Switches the color of a Node from red to black or black to red.
"""
if self.is_red:
self.is_red = False
else:
self.is_red = True
def add_instance(self):
"""
Allows for duplicates in a node by making it "fat" instead of
creating more nodes which would defeat the purpose of a self-
balancing tree.
"""
self.instances += 1
def remove_instance(self):
"""
Allows for removal of a single instance of a key from the
search tree rather than pruning an entire node from the tree.
"""
self.instances -= 1
def delete(self):
"""
Zeroes out a node for deletion.
"""
self.key = None
self.instances = 0
self.parent = None
self.left = None
self.right = None
self.is_red = False # Null nodes are, by default, black. |
def get_max_profit(stock_prices):
# initialize the lowest_price to the first stock price
lowest_price = stock_prices[0]
# initialize the max_profit to the
# difference between the first and the second stock price
max_profit = stock_prices[1] - stock_prices[0]
# loop through every price in stock_prices
# starting from the second price
for index in range(1, len(stock_prices)):
# if price minus lowest_price is greater than max_profit
if stock_prices[index] - lowest_price > max_profit:
# set max_profit to the difference between price and lowest_price
max_profit = stock_prices[index] - lowest_price
# if price is lower than lowest_price
if stock_prices[index] < lowest_price:
# set lowest_price to price
lowest_price = stock_prices[index]
# return max_profit
return max_profit
|
# Given an integer n, return the number of trailing zeroes in n!.
# Example 1:
# Input: 3
# Output: 0
# Explanation: 3! = 6, no trailing zero.
# Example 2:
# Input: 5
# Output: 1
# Explanation: 5! = 120, one trailing zero.
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
x = 5
ans = 0
while n >= x:
ans += n // x
x *= 5
return ans
print(Solution().trailingZeroes(1808548329))
|
class EventMongoRepository:
database_address = "localhost"
def __init__(self):
self.client = "Opens a connection with mongo"
def add_event(self, event):
pass
def remove_event(self, event):
pass
def update_event(self, event):
pass
|
class SuperList(list):
def __len__(self):
return 1000
super_list1 = SuperList()
print(len(super_list1))
super_list1.append(5)
print(super_list1[0])
print(issubclass(list, object)) |
# Python Developer
# 3.1. Практика
#
# 1. У вас есть массив чисел. Напишите три функции, которые вычисляют сумму этих чисел:
# с for-циклом,
# a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# i = 0
# b = 0
# for i in a:
# b = b + i
# print(b)
# с while -циклом, с * рекурсией.
# a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# # b = 0
# # while a:
# # b = b + (a.pop())
# print(b)
# 2. Напишите функцию, которая создаёт комбинацию двух списков таким образом:
# [1, 2, 3] (+) [11, 22, 33] -> [1, 11, 2, 22, 3, 33]
# 3. Существует ли треугольник с заданными сторонами.
# str_1 = list(input('Введите стороны треугольника через пробел:'))
# if (str_1[1] + str_1[2]) > str_1[3] and (str_1[2] + str_1[3]) > str_1[1] and (str_1[1] + str_1[3]) > str_1[3]:
# print('Треугольник существует')
# else:
# print('Треугольник не существует')
# 4. Расстояние между точками. На вход поступает два значение (кортежа) с координатами - широта и долгота.
# Найти расстояние между этими точками. cos(d) = sin(φА)·sin(φB) + cos(φА)·cos(φB)·cos(λА − λB),
# где φА и φB — широты, λА, λB — долготы данных пунктов,
# d — расстояние между пунктами, измеряется в радианах длиной дуги большого круга земного шара.
# Расстояние между пунктами, измеряемое в километрах,
# определяется по формуле: L = d·R, где R = 6371 км — средний радиус земного шара.
#
# 5. Поиск квадратных уравнений, имеющих решение. Программа принимает от пользователя диапазоны
# для коэффициентов a, b, c квадратного уравнения: ax2 + bx + c = 0.
# Перебирает все варианты целочисленных коэффициентов в указанных диапазонах,
# определяет квадратные уравнения, которые имеют решение.
# 6. Заданы M строк символов, которые вводятся с клавиатуры.
# Каждая строка представляет собой последовательность символов,
# включающих в себя вопросительные знаки.
# Заменить в каждой строке все имеющиеся вопросительные знаки звёздочками.
# 7. Системная дата имеет вид 2009-06-15.
# Нужно преобразовать это значение в строку,
# строку разделить на компоненты (символ→разделитель→дефис),
# потом из этих компонентов сконструировать нужную строку. (2009-06-15 -> 15/06/2009)
#
# # 8. Задан вес в граммах. Определить вес в тоннах и килограммах.
# weigth_g = int(input('Введите вес в граммах'))
# a = weigth_g / 1000
# b = a / 1000
# print('Вес в килограммах:', a)
# print('Вес в тоннах', b)
# 9. Имеется коробка со сторонами: A × B × C. Определить, пройдёт ли она в дверь с размерами M × K.
# a = int(input('Введите стороны коробки, a:'))
# b = int(input('Введите стороны коробки, b:'))
# c = int(input('Введите стороны коробки, c:'))
# m = int(input('Введите ширину двери, m:'))
# k = int(input('Введите высоту двери, k:'))
# i = 'Не проходит'
# if a < m:
# if b < k:
# i = 'Проходит'
# elif c < k:
# i = 'Проходит'
# elif b < m:
# if a < k:
# i = 'Проходит'
# elif c < k:
# i = 'Проходит'
# elif c < m:
# if a < k:
# i = 'Проходит'
# elif b < k:
# i = 'Проходит'
# print(i)
# 10. Можно ли из бревна, имеющего диаметр поперечного сечения D, выпилить квадратный брус шириной A?
# diam_1 = int(input('Введите диаметр бревна:'))
# weld_1 = int(input('Введите сторону квадрата:'))
# if diam_1 >= (weld_1 * (2 ** 0.5)):
# print('Возможно')
# else:
# print('Невозможно')
# 11. Дан номер места в плацкартном вагоне. Определить, какое это место: верхнее или нижнее, в купе или боковое.
# place_1 = int(input('Введите номер места в плацкартном вагоне:'))
# if 55 > place_1 > 36:
# print('Боковое место')
# elif 37 > place_1 > 0 and place_1 % 2 == 0:
# print('Верхнее место в купе')
# elif 37 > place_1 > 0 and place_1 % 2 > 0:
# print('Нижнее место в купе')
# else:
# print('Указанное место не входит в вагон')
# 12. Известна денежная сумма. Разменять её купюрами 500, 100, 10 и монетой 2 грн., если это возможно.
a = int(input('Введите сумму для размена:'))
b = a // 500
b1 = a % 500
c = b1 // 100
c1 = b1 % 100
d = c1 // 10
d1 = c1 % 10
e = d1 // 2
e1 = d1 % 2
if e1 > 0:
print('Сумму не возможно разменять полностью, остаток будет равен:', e1)
print('Количество купюр 500 грн:', b)
print('Количество купюр 100 грн:', c)
print('Количество купюр 10 грн:', d)
print('Количество монет 2 грн:', e)
# 13. Пользователь вводит число n, программа должна проверить является ли оно простым и сообщить об этом.
#
# 14. Вывести таблицу умножения числа M в диапазоне от числа a до числа b. Числа M, a и b вводит пользователь.
# 15. Дан одномерный массив числовых значений, насчитывающий N элементов.
# Поменять местами элементы, стоящие на чётных и нечётных местах: A[1] ↔ A[2]; A[3] ↔ A[4] ...
# 16. Вывести список простых чисел в диапазоне d. Диапазон d вводит пользователь. |
"""
link: https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix
problem: 求给定矩阵的最大严格递增路径长度
solution: DP。从小到大排序所有元素,因为路径只能从低向高长,g[i][j] 记录当检查到 matrix[i][j] 时,以 matrix[i][j] 为终点的最大路径长度。
因为做了排序,时间复杂度O(nm(log_nm))
solution-fix: 拓扑排序。思路同上,不做排序,遍历一次记录每个点附近比其小的点数量作为入度,用拓扑序遍历,时间复杂度可以压到 O(nm)
"""
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix or not matrix[0]:
return 0
n, m, q = len(matrix), len(matrix[0]), []
g = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m):
q.append((matrix[i][j], i, j))
q.sort()
res = 1
for k in q:
x, y, t = k[1], k[2], 1
for ii, jj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
i, j = x + ii, y + jj
if 0 <= i < n and 0 <= j < m and matrix[i][j] < matrix[x][y] and g[i][j] + 1 > t:
t = g[i][j] + 1
g[x][y] = t
res = max(res, t)
return res
# ---
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix or not matrix[0]:
return 0
n, m, q = len(matrix), len(matrix[0]), []
g = [[[1, 0] for _ in range(m)] for _ in range(n)]
for x in range(n):
for y in range(m):
for ii, jj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
i, j = x + ii, y + jj
if 0 <= i < n and 0 <= j < m and matrix[i][j] < matrix[x][y]:
g[x][y][1] += 1
if g[x][y][1] == 0:
q.append((x, y))
res = 1
while q:
k = q.pop()
x, y = k[0], k[1]
res = max(res, g[x][y][0])
for ii, jj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
i, j = x + ii, y + jj
if 0 <= i < n and 0 <= j < m and matrix[i][j] > matrix[x][y]:
g[i][j][0] = max(g[i][j][0], g[x][y][0] + 1)
g[i][j][1] -= 1
if g[i][j][1] == 0:
q.append((i, j))
return res
|
class Finding:
def __init__(self, filename, secret_type, secret_value, line_number=None, link=None):
self._filename = filename
self._secret_type = secret_type
self._secret_value = secret_value
self._line_number = line_number
self._link = link
@property
def filename(self):
return self._filename
@property
def secret_type(self):
return self._secret_type
@property
def link(self):
return self._link
@property
def line_number(self):
return self._line_number
def __eq__(self, other):
if isinstance(other, Finding):
return self.filename == other.filename and \
self.secret_type == other.secret_type and \
self._secret_value == other._secret_value
def __hash__(self):
return hash((self._filename, self._secret_type, self._secret_value))
def __str__(self):
s = "Secret type {} found in {}".format(self._secret_type, self._filename)
if self._line_number is not None:
s = s + ":{}".format(self._line_number)
if self._link is not None:
s = s + " ({})".format(self._link)
return s
def __repr__(self):
return "<{}> ({})".format(self._secret_type, self._filename)
|
"""
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def threeSumClosest(self, nums, target):
nums.sort()
# 初始化
a = abs(nums[0] + nums[1] + nums[2] - target) # 存储最开始三个元素和target的距离
res = nums[0] + nums[1] + nums[2]
for i in range(len(nums)):
left, right = i+1, len(nums)-1
while left < right:
total = nums[i] + nums[left] + nums[right]
# 只需要多一步更新阈值并存储结果的环节
if abs(total - target) < a:
# 此时距离小于当前阈值,更新阈值
a = abs(total - target)
res = total
# 双指针
if total == target:
return total
elif total > target:
right -= 1
elif total < target:
left += 1
return res
if __name__ == "__main__":
nums = [0,0,0]
target = 1
answer = Solution().threeSumClosest(nums, target)
print(answer) |
PATH_ROOT = "/sra/sra-instant/reads/ByExp/sra/SRX/SRX{}/{}/"
def read_srx_list(file):
srxs = set()
with open(file, "r") as fh:
next(fh)
for line in fh:
if line.startswith("SRX"):
srxs.add(line.rstrip())
return list(srxs)
def read_srr_file(srr_file):
srr_data = {}
with open(srr_file, "r") as fh:
for line in fh:
line = line.rstrip()
srx, srrs = line.split("\t")
srrs = srrs.split(", ")
assert srx.startswith("SRX")
assert srx not in srr_data
for srr in srrs:
assert srr.startswith("SRR")
assert "," not in srr
assert " " not in srr
srr_data[srx] = srrs
return srr_data
def fetch_srr_ids(srx, conn):
assert srx.startswith("SRX")
first_chunk = srx[3:6]
path = PATH_ROOT.format(first_chunk, srx)
res = conn.nlst(path)
return map(lambda x: x.split("/")[-1], res)
def build_srr_list(srxs, conn):
srr_data = {}
for srx in srx_ids:
srrs = fetch_srr_ids(srx, conn)
srr_data[srx] = srrs
return srr_data
|
# Exercício Python 051
# Leia o primeiro termo e a razão de uma progressão aritmética
# Mostre os 10 primeiros termos dessa progressão
n = int(input('Digite o primeiro termo: '))
p = int(input('Digite a constante de progressão: '))
for c in range(n,10,p):
print('{}·'.format(c),end='')
print('FIM')
# Professor
n = int(input('Digite o primeiro termo: '))
p = int(input('Digite a constante de progressão: '))
t = 10 * p + n
for c in range(n, t, p):
print('{}·'.format(c),end='')
print('FIM')
|
styles = {
"alignment": {
"color": "black",
"linestyle": "-",
"linewidth": 1.0,
"alpha": 0.2,
"label": "raw alignment"
},
"despiked": {
"color": "blue",
"linestyle": "-",
"linewidth": 1.4,
"alpha": 1.0,
"label": "de-spiked alignment"
},
"line1": {
"color": "black",
"linestyle": "-",
"linewidth": 1.2,
"alpha": 0.3,
"label": "line1"
},
"line2": {
"color": "blue",
"linestyle": "-",
"linewidth": 1.4,
"alpha": 1.0,
"label": "line2"
},
"line3": {
"color": "green",
"linestyle": "-",
"linewidth": 1.4,
"alpha": 1.0,
"label": "line3"
},
"point1": {
"color": "red",
"marker": "o",
"markersize": 6,
"markeredgecolor": "black",
"alpha": 1.0,
"linestyle": "None",
"label": "point1"
},
"point2": {
"color": "orange",
"marker": "o",
"markersize": 4,
"markeredgecolor": "None",
"alpha": 0.5,
"linestyle": "None",
"label": "point2"
},
"point3": {
"color": "None",
"marker": "o",
"markersize": 4,
"markeredgecolor": "brown",
"alpha": 1.0,
"linestyle": "None",
"label": "point3"
}
} |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 18:24:11 2021
@author: User
"""
# Objetos, pilas y colas
class Rectangulo():
def __init__(self, x, y):
self.x = x
self.y = y
def base(self):
return
def altura(self):
return
def area(self):
return
def desplazar(self, desplazamiento):
return
def rotar(self, x):
return
def __str__(self):
return f'({self.x}, {self.y})'
# Used with `repr()`
def __repr__(self):
return
class Punto():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x}, {self.y})'
# Used with `repr()`
def __repr__(self):
return f'Punto({self.x}, {self.y})'
def __add__(self, b):
return Punto(self.x + b.x, self.y + b.y)
|
# Faça um programa que leia o peso de cinco pessoas.
# No final, mostre qual foi o maior e o menor peso lidos.
menor_peso = 999
maior_peso = -1
for i in range(1, 6):
peso = float(input(f'Peso {i}: '))
if peso > maior_peso:
maior_peso = peso
elif peso < menor_peso:
menor_peso = peso
print(f'Menor peso: {menor_peso}')
print(f'Maior peso: {maior_peso}')
|
# encoding: utf-8
# module errno
# from (built-in)
# by generator 1.147
"""
This module makes available standard errno system symbols.
The value of each symbol is the corresponding integer value,
e.g., on most systems, errno.ENOENT equals the integer 2.
The dictionary errno.errorcode maps numeric codes to symbol names,
e.g., errno.errorcode[2] could be the string 'ENOENT'.
Symbols that are not relevant to the underlying system are not defined.
To map error codes to error messages, use the function os.strerror(),
e.g. os.strerror(2) could return 'No such file or directory'.
"""
# no imports
# Variables with simple values
E2BIG = 7
EACCES = 13
EADDRINUSE = 10048
EADDRNOTAVAIL = 10049
EAFNOSUPPORT = 10047
EAGAIN = 11
EALREADY = 10037
EBADF = 9
EBUSY = 16
ECHILD = 10
ECONNABORTED = 10053
ECONNREFUSED = 10061
ECONNRESET = 10054
EDEADLK = 36
EDEADLOCK = 36
EDESTADDRREQ = 10039
EDOM = 33
EDQUOT = 10069
EEXIST = 17
EFAULT = 14
EFBIG = 27
EHOSTDOWN = 10064
EHOSTUNREACH = 10065
EILSEQ = 42
EINPROGRESS = 10036
EINTR = 4
EINVAL = 22
EIO = 5
EISCONN = 10056
EISDIR = 21
ELOOP = 10062
EMFILE = 24
EMLINK = 31
EMSGSIZE = 10040
ENAMETOOLONG = 38
ENETDOWN = 10050
ENETRESET = 10052
ENETUNREACH = 10051
ENFILE = 23
ENOBUFS = 10055
ENODEV = 19
ENOENT = 2
ENOEXEC = 8
ENOLCK = 39
ENOMEM = 12
ENOPROTOOPT = 10042
ENOSPC = 28
ENOSYS = 40
ENOTCONN = 10057
ENOTDIR = 20
ENOTEMPTY = 41
ENOTSOCK = 10038
ENOTTY = 25
ENXIO = 6
EOPNOTSUPP = 10045
EPERM = 1
EPFNOSUPPORT = 10046
EPIPE = 32
EPROTONOSUPPORT = 10043
EPROTOTYPE = 10041
ERANGE = 34
EREMOTE = 10071
EROFS = 30
ESHUTDOWN = 10058
ESOCKTNOSUPPORT = 10044
ESPIPE = 29
ESRCH = 3
ESTALE = 10070
ETIMEDOUT = 10060
ETOOMANYREFS = 10059
EUSERS = 10068
EWOULDBLOCK = 10035
EXDEV = 18
WSABASEERR = 10000
WSAEACCES = 10013
WSAEADDRINUSE = 10048
WSAEADDRNOTAVAIL = 10049
WSAEAFNOSUPPORT = 10047
WSAEALREADY = 10037
WSAEBADF = 10009
WSAECONNABORTED = 10053
WSAECONNREFUSED = 10061
WSAECONNRESET = 10054
WSAEDESTADDRREQ = 10039
WSAEDISCON = 10101
WSAEDQUOT = 10069
WSAEFAULT = 10014
WSAEHOSTDOWN = 10064
WSAEHOSTUNREACH = 10065
WSAEINPROGRESS = 10036
WSAEINTR = 10004
WSAEINVAL = 10022
WSAEISCONN = 10056
WSAELOOP = 10062
WSAEMFILE = 10024
WSAEMSGSIZE = 10040
WSAENAMETOOLONG = 10063
WSAENETDOWN = 10050
WSAENETRESET = 10052
WSAENETUNREACH = 10051
WSAENOBUFS = 10055
WSAENOPROTOOPT = 10042
WSAENOTCONN = 10057
WSAENOTEMPTY = 10066
WSAENOTSOCK = 10038
WSAEOPNOTSUPP = 10045
WSAEPFNOSUPPORT = 10046
WSAEPROCLIM = 10067
WSAEPROTONOSUPPORT = 10043
WSAEPROTOTYPE = 10041
WSAEREMOTE = 10071
WSAESHUTDOWN = 10058
WSAESOCKTNOSUPPORT = 10044
WSAESTALE = 10070
WSAETIMEDOUT = 10060
WSAETOOMANYREFS = 10059
WSAEUSERS = 10068
WSAEWOULDBLOCK = 10035
WSANOTINITIALISED = 10093
WSASYSNOTREADY = 10091
WSAVERNOTSUPPORTED = 10092
# no functions
# no classes
# variables with complex values
errorcode = {
1: 'EPERM',
2: 'ENOENT',
3: 'ESRCH',
4: 'EINTR',
5: 'EIO',
6: 'ENXIO',
7: 'E2BIG',
8: 'ENOEXEC',
9: 'EBADF',
10: 'ECHILD',
11: 'EAGAIN',
12: 'ENOMEM',
13: 'EACCES',
14: 'EFAULT',
16: 'EBUSY',
17: 'EEXIST',
18: 'EXDEV',
19: 'ENODEV',
20: 'ENOTDIR',
21: 'EISDIR',
22: 'EINVAL',
23: 'ENFILE',
24: 'EMFILE',
25: 'ENOTTY',
27: 'EFBIG',
28: 'ENOSPC',
29: 'ESPIPE',
30: 'EROFS',
31: 'EMLINK',
32: 'EPIPE',
33: 'EDOM',
34: 'ERANGE',
36: 'EDEADLOCK',
38: 'ENAMETOOLONG',
39: 'ENOLCK',
40: 'ENOSYS',
41: 'ENOTEMPTY',
42: 'EILSEQ',
10000: 'WSABASEERR',
10004: 'WSAEINTR',
10009: 'WSAEBADF',
10013: 'WSAEACCES',
10014: 'WSAEFAULT',
10022: 'WSAEINVAL',
10024: 'WSAEMFILE',
10035: 'WSAEWOULDBLOCK',
10036: 'WSAEINPROGRESS',
10037: 'WSAEALREADY',
10038: 'WSAENOTSOCK',
10039: 'WSAEDESTADDRREQ',
10040: 'WSAEMSGSIZE',
10041: 'WSAEPROTOTYPE',
10042: 'WSAENOPROTOOPT',
10043: 'WSAEPROTONOSUPPORT',
10044: 'WSAESOCKTNOSUPPORT',
10045: 'WSAEOPNOTSUPP',
10046: 'WSAEPFNOSUPPORT',
10047: 'WSAEAFNOSUPPORT',
10048: 'WSAEADDRINUSE',
10049: 'WSAEADDRNOTAVAIL',
10050: 'WSAENETDOWN',
10051: 'WSAENETUNREACH',
10052: 'WSAENETRESET',
10053: 'WSAECONNABORTED',
10054: 'WSAECONNRESET',
10055: 'WSAENOBUFS',
10056: 'WSAEISCONN',
10057: 'WSAENOTCONN',
10058: 'WSAESHUTDOWN',
10059: 'WSAETOOMANYREFS',
10060: 'WSAETIMEDOUT',
10061: 'WSAECONNREFUSED',
10062: 'WSAELOOP',
10063: 'WSAENAMETOOLONG',
10064: 'WSAEHOSTDOWN',
10065: 'WSAEHOSTUNREACH',
10066: 'WSAENOTEMPTY',
10067: 'WSAEPROCLIM',
10068: 'WSAEUSERS',
10069: 'WSAEDQUOT',
10070: 'WSAESTALE',
10071: 'WSAEREMOTE',
10091: 'WSASYSNOTREADY',
10092: 'WSAVERNOTSUPPORTED',
10093: 'WSANOTINITIALISED',
10101: 'WSAEDISCON',
}
|
'''
'''
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
if length <= 2:
return length
left = 0
cur = 0
while cur < length - 1:
sums = 1
while cur < length - 1 and nums[cur] == nums[cur + 1]:
sums += 1
cur += 1
for i in range(min(sums, 2)):
nums[left] = nums[cur]
left += 1
cur += 1
if cur == length - 1:
nums[left] = nums[cur]
left += 1
#nums = nums[:left + 1]
return left
|
# Problem description: http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
def make_change(money, coins):
if money < 0:
return 0
elif money == 0:
return 1
elif not coins:
return 0
else:
return make_change(money - coins[-1], coins) + make_change(money, coins[:-1])
coins = [1, 2, 3]
money = 4
make_change(money, coins) |
_notes_dict_array_hz = {
'C': [8.176, 16.352, 32.703, 65.406, 130.81, 261.63, 523.25, 1046.5, 2093.0, 4186.0, 8372.0],
'C#': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8],
'Df': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8],
'D': [9.177, 18.354, 36.708, 73.416, 146.83, 293.66, 587.33, 1174.7, 2349.3, 4698.6, 9397.3],
'Ef': [9.723, 19.445, 38.891, 77.782, 155.56, 311.13, 622.25, 1244.5, 2489.0, 4978.0, 9956.1],
'D#': [9.723, 19.445, 38.891, 77.782, 155.56, 311.13, 622.25, 1244.5, 2489.0, 4978.0, 9956.1],
'E': [10.301, 20.602, 41.203, 82.407, 164.81, 329.63, 659.26, 1318.5, 2637.0, 5274.0, 10548.1],
'F': [10.914, 21.827, 43.654, 87.307, 174.61, 349.23, 698.46, 1396.9, 2793.8, 5587.7, 11175.3],
'F#': [11.563, 23.125, 46.249, 92.499, 185.0, 369.99, 739.99, 1480.0, 2960.0, 5919.9, 11839.8],
'Gf': [11.563, 23.125, 46.249, 92.499, 185.0, 369.99, 739.99, 1480.0, 2960.0, 5919.9, 11839.8],
'G': [12.25, 24.5, 48.999, 97.999, 196.0, 392.0, 783.99, 1568.0, 3136.0, 6271.9, 12543.9],
'Af': [12.979, 25.957, 51.913, 103.83, 207.65, 415.3, 830.61, 1661.2, 3322.4, 6644.9],
'G#': [12.979, 25.957, 51.913, 103.83, 207.65, 415.3, 830.61, 1661.2, 3322.4, 6644.9],
'A': [13.75, 27.5, 55.0, 110.0, 220.0, 440.0, 880.0, 1760.0, 3520.0, 7040.0],
'Bf': [14.568, 29.135, 58.27, 116.54, 233.08, 466.16, 932.33, 1864.7, 3729.3, 7458.6],
'A#': [14.568, 29.135, 58.27, 116.54, 233.08, 466.16, 932.33, 1864.7, 3729.3, 7458.6],
'B': [15.434, 30.868, 61.735, 123.47, 246.94, 493.88, 987.77, 1975.5, 3951.1, 7902.1]
}
midi_note_hz = [8.176, 8.662, 9.177, 9.723, 10.301, 10.914, 11.563, 12.25, 12.979, 13.75, 14.568, 15.434, 16.352, 17.324, 18.354, 19.445, 20.602, 21.827, 23.125, 24.5, 25.957, 27.5, 29.135, 30.868, 32.703, 34.648, 36.708, 38.891, 41.203, 43.654, 46.249, 48.999, 51.913, 55.0, 58.27, 61.735, 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, 92.499, 97.999, 103.83, 110.0, 116.54, 123.47, 130.81, 138.59, 146.83, 155.56, 164.81, 174.61, 185.0, 196.0, 207.65, 220.0, 233.08, 246.94, 261.63, 277.18, 293.66, 311.13, 329.63, 349.23, 369.99, 392.0, 415.3, 440.0, 466.16, 493.88, 523.25, 554.37, 587.33, 622.25, 659.26, 698.46, 739.99, 783.99, 830.61, 880.0, 932.33, 987.77, 1046.5, 1108.7, 1174.7, 1244.5, 1318.5, 1396.9, 1480.0, 1568.0, 1661.2, 1760.0, 1864.7, 1975.5, 2093.0, 2217.5, 2349.3, 2489.0, 2637.0, 2793.8, 2960.0, 3136.0, 3322.4, 3520.0, 3729.3, 3951.1, 4186.0, 4434.9, 4698.6, 4978.0, 5274.0, 5587.7, 5919.9, 6271.9, 6644.9, 7040.0, 7458.6, 7902.1, 8372.0, 8869.8, 9397.3, 9956.1, 10548.1, 11175.3, 11839.8, 12543.9]
def note_freq(note, octave):
octave_idx = octave + 1
return _notes_dict_array_hz[note][octave_idx] |
def funct(l1, l2):
s = len(set(l1+l2))
return s
for t in range(int(input())):
n = int(input())
l = input().split()
a = {}
for i in l:
p = i[1:]
if p in a:
a[p].append(i[0])
else:
a[p] = [i[0]]
b = list(a.keys())
s = 0
for i in range(len(a)):
for j in range(i+1, len(a)):
ans = funct(a[b[i]], a[b[j]])
s += (ans-len(a[b[i]]))*(ans-len(a[b[j]]))
print(2*s)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.