content
stringlengths
7
1.05M
""" 107. Word Break https://www.lintcode.com/problem/word-break/description?_from=ladder&&fromId=160 DFS on dictionary """ class Solution: """ @param s: A string @param wordSet: A dictionary of words dict @return: A boolean """ def wordBreak(self, s, wordSet): # write your code here return self.dfs(0, s, wordSet) def dfs(self, index, s, wordSet): if (index == len(s)): return True for word in wordSet: if not s[index:].startswith(word): continue if self.dfs(index + len(word), s, wordSet): return True return False
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. # Input: [-2,1,-3,4,-1,2,1,-5,4], # Output: 6 # Explanation: [4,-1,2,1] has the largest sum = 6. #https://www.geeksforgeeks.org/print-the-maximum-subarray-sum/ def naive(a): b = [] index = [] for i in range(len(a)): for j in range(i,len(a)): b.append(sum(a[i:j+1])) index.append([i,j]) return b, index def main(a): curr_sum = max_sum = a[0] end_index = 0 for i in range(1,len(a)): curr_sum=max(a[i], curr_sum+a[i]) if max_sum < curr_sum: end_index = i max_sum = max(max_sum, curr_sum) _max_sum = max_sum start_index = end_index while start_index >= 0: _max_sum -=a[start_index] if _max_sum ==0: break start_index -= 1 # print(start_index, end_index) for i in range(start_index, end_index+1): print(a[i], end=" ") return max_sum if __name__ == "__main__": a=[-2,1,-3,4,-1,5,1,-5,4] # b, index=naive(a) # print(max(b),index[b.index(max(b))]) # print(b) # print(index[27], b[27]) print(main(a))
# cook your dish here #input n=int(input("")) resp=[] for i in range(0,n): resp.append(input("")) #print(n,resp) def validlang(req): newreq=[] for i in req: if i!=" ": newreq.append(i) needed=[newreq[0],newreq[1]] lang1=[newreq[2],newreq[3]] lang2=[newreq[4],newreq[5]] final=[] for i in needed: if i in lang1: final.append("A") else: final.append("B") if final[0]!=final[1]: return 0 elif final[0]==final[1] and final[0]=="A": return 1 elif final[0]==final[1] and final[0]=="B": return 2 for i in resp: print(validlang(i))
# Time: O(nlogn) # Space: O(1) # sort class Solution(object): def maxConsecutive(self, bottom, top, special): """ :type bottom: int :type top: int :type special: List[int] :rtype: int """ special.sort() result = max(special[0]-bottom, top-special[-1]) for i in xrange(1, len(special)): result = max(result, special[i]-special[i-1]-1) return result
""" from __future__ import annotations import threading import time from typing import TYPE_CHECKING from bot import app_vars if TYPE_CHECKING: from bot import Bot class TaskScheduler(threading.Thread): def __init__(self, bot: Bot): super().__init__(daemon=True) self.name = "SchedulerThread" self.tasks = {} # self.user = User(0, "", "", 0, 0, "", is_admin=True, is_banned=False) def run(self): while True: for t in self.tasks: if self.get_time() >= t: task = self.tasks[t] task[0](task[1], self.user) time.sleep(app_vars.loop_timeout) def get_time(self): return int(round(time.time())) """
nombre = "Fulanito Fulanovsky" usa_lentes = True tiene_mascota = False edad = 25 pasatiempos = ["Correr", "Cocinar", "Leer", "Bailar"] celulares = { "xiaomi redmi": { "RAM": 3, "ROM": 32, "Procesador": 2.1 }, "iphone xs": { "RAM": 4, "ROM": 64, "Procesador": 2.6 }, } print("Nombre: {}".format(nombre)) print("Usa lentes?: {}".format(usa_lentes)) print("Tiene mascotas?: {}".format(usa_lentes)) print("Edad: {}".format(edad)) print("Pasatiempos: {}".format(pasatiempos)) print("Celulares: {}".format(celulares)) #and = "Palabrita" #print(and)
alerts = [ { "uuid": "d916cb34-6ee3-48c0-bca5-3f3cc08db5d3", "type": "v1/insights/droplet/cpu", "description": "CPU is running high", "compare": "GreaterThan", "value": 70, "window": "5m", "entities": [], "tags": [], "alerts": {"slack": [], "email": ["alerts@example.com"]}, "enabled": True, } ]
# Uses Python3 n = int(input('Enter the number for which you want fibonnaci: ')) def fibonnaci_last_digit(num): second_last = 0 last = 1 if num < 0: return 'Incorrect input' elif num == 0: return second_last elif num == 1: return last for i in range(1, num): next = ((last % 10) + (second_last % 10)) % 10 second_last = last last = next return last print(fibonnaci_last_digit(n))
class User: def __init__(self, name): self.name = name class SubscribedUser(User): def __init__(self, name): super(SubscribedUser, self).__init__(name) self.subscribed = True class Account: def __init__(self, user, email_broadcaster): self.user = user self.email_broadcaster = email_broadcaster def on_account_created(self, event): return self.email_broadcaster.broadcast(event, self.user) class Rectangle: def __init__(self, width, height): self._height = height self._width = width @property def area(self): return self._width * self._height def __str__(self): return f"Width: {self.width}, height: {self.height}" @property def width(self): return self._width @width.setter def width(self, value): self._width = value @property def height(self): return self._height @height.setter def height(self, value): self._height = value
def count_elem(array, query): def first_occurance(array, query): lo, hi = 0, len(array) -1 while lo <= hi: mid = lo + (hi - lo) // 2 if (array[mid] == query and mid == 0) or \ (array[mid] == query and array[mid-1] < query): return mid elif (array[mid] <= query): lo = mid + 1 else: hi = mid - 1 def last_occurance(array, query): lo, hi = 0, len(array) -1 while lo <= hi: mid = lo + (hi - lo) // 2 if (array[mid] == query and mid == len(array) - 1) or \ (array[mid] == query and array[mid+1] > query): return mid elif (array[mid] <= query): lo = mid + 1 else: hi = mid - 1 first = first_occurance(array, query) last = last_occurance(array, query) if first is None or last is None: return None return last - first + 1 array = [1,2,3,3,3,3,4,4,4,4,5,6,6,6] print(array) print("-----COUNT-----") query = 3 print("count: ", query, " :" , count_elem(array, query)) print("-----COUNT-----") query = 5 print("count: ", query, " :" , count_elem(array, query)) print("-----COUNT-----") query = 7 print("count: ", query, " :" , count_elem(array, query)) print("-----COUNT-----") query = 1 print("count: ", query, " :" , count_elem(array, query)) print("-----COUNT-----") query = -1 print("count: ", query, " :" , count_elem(array, query)) print("-----COUNT-----") query = 9 print("count: ", query, " :" , count_elem(array, query))
#!/usr/bin/env python main = units.configure.cli.prompt if __name__ == '__main__': main()
dist = int(input('Qual a distancia em km da sua viagem? ')) if dist <= 200: preco = dist * 0.5 print('O preço da viagem sera de: {}'.format(preco)) else: preco = dist * 0.45 print('O preço da viagem sera de: {}'.format(preco))
class DatabaseFormat (object): def __init__(self, logger): self.logger = logger # Table name self.type = None # Primary key self.id = None # 1:N Relationship with records in other tables self.parent = None self.parent_type = None self.children = {} # N:N Relationship with records in other tables self.associated_objects = {} def create_child(self, child): """ Create 1:N relation between object :param child: :return: """ self.children[child.type][child.id] = child child.parent = self child.parent_type = self.type self.logger.info("Added record: parent_id=%s; parent_type=%s; child_id=%s; child_type=%s;" % (self.id, self.type, child.id, child.type)) def clear_children(self): # delete all children for children_type in self.children.values(): for child in list(children_type.values()): child.delete() self.logger.info("cleared children of object id=%s; type=%s; parent_id=%s" % (self.id, self.type, self.parent.id)) def clear_friends(self): # delete N:N relationship for nn_object_type in self.associated_objects.values(): for nn_object in nn_object_type.values(): del nn_object.associated_objects[self.type][self.id] self.logger.info("cleared nn_association with object id=%s; type=%s; parent_id=%s" % (self.id, self.type, self.parent.id)) def clear(self): self.clear_children() self.clear_friends() def delete(self): self.clear() # delete 1:N relationship with the parent del self.parent.children[self.type][self.id] self.logger.info("Deleted record: id=%s; type=%s" % (self.id, self.type)) def assign(self, friend): """ Create N:N relation between object :param friend: :return: """ if friend.id not in self.associated_objects[friend.type] and self.id not in friend.associated_objects[self.type]: self.associated_objects[friend.type][friend.id] = friend friend.associated_objects[self.type][self.id] = self self.logger.info("New assignment: id=%s; type=%s with id=%s; type=%s" % (self.id, self.type, friend.id, friend.type)) else: self.logger.error("Duplicate assignment requested: id=%s; type=%s with id=%s; type=%s" % (self.id, self.type, friend.id, friend.type)) def detach(self, friend): if friend.id in self.associated_objects[friend.type]: del self.associated_objects[friend.type][friend.id] del friend.associated_objects[self.type][self.id] self.logger.info("Delete assignment: id=%s; type=%s with id=%s; type=%s" % (self.id, self.type, friend.id, friend.type)) else: self.logger.error("Unknown unassignment requested: id=%s; type=%s with id=%s; type=%s" % (self.id, self.type, friend.id, friend.type)) def get_db(self): return self.parent.get_db() def _get_record_generic_part(self): data = {} # Primary key data['id'] = self.id # Parent if self.parent is None: data['parent'] = "orphan" else: data['parent'] = self.parent.id # Children data['children'] = {} for child_type, children in self.children.items(): data['children'][child_type] = [] for id, child in children.items(): data['children'][child_type].append(id) # n:n relation self._get_record_nn_relationship(data) return data def _get_recursive_record_generic_part(self): data = {} # Primary key data['id'] = self.id # Children data['children'] = {} for child_type, children in self.children.items(): data['children'][child_type] = {} for id, child in children.items(): data['children'][child_type][id] = child.dump_json_format() # n:n relation self._get_record_nn_relationship(data) return data def _get_record_nn_relationship(self, data): # n:n relation data['associated_objects'] = {} for object_type, nn_objects in self.associated_objects.items(): data['associated_objects'][object_type] = [] for id, nn_object in nn_objects.items(): data['associated_objects'][object_type].append(id) return data def _get_record_specific_part(self, data): # to be override pass return data def get_json_format(self): data = self._get_record_generic_part() data = self._get_record_specific_part(data) return data def dump_json_format(self): data = self._get_recursive_record_generic_part() data = self._get_record_specific_part(data) return data
class Command: ADVANCE = 1 REVERSE = 2 ADVANCE_LEFT = 3 ADVANCE_RIGHT = 4 REVERSE_LEFT = 5 REVERSE_RIGHT = 6 OBSTACLE_FRONT = 7 OBSTACLE_BOTTOM = 8 NONE_OBSTACLE_FRONT = 9 NONE_OBSTACLE_BOTTOM = 10 BRAKE = 11 DISABLE_MOTER = 12
print('this is test3') print('add=====') print('add=====2')
# 以下の解説を参考に作成 # https://drken1215.hatenablog.com/entry/2020/11/16/204900 h, w = map(int, input().split()) field = [list(input()) for _ in range(h)] MOD = 10 ** 9 + 7 dp = [[0] * (w + 1) for _ in range(h + 1)] X = [[0] * (w + 1) for _ in range(h + 1)] Y = [[0] * (w + 1) for _ in range(h + 1)] Z = [[0] * (w + 1) for _ in range(h + 1)] dp[1][1] = 1 for i in range(1, h + 1): for j in range(1, w + 1): if field[i - 1][j - 1] == "#": continue left = X[i][j - 1] top = Y[i - 1][j] lefttop = Z[i - 1][j - 1] current = (dp[i][j] + left + top + lefttop) % MOD dp[i][j] = current X[i][j] += (left + current) % MOD Y[i][j] += (top + current) % MOD Z[i][j] += (lefttop + current) % MOD print(dp[-1][-1])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: b.lin@mfm.tu-darmstadt.de """ def CreateInputFileUpper(InputFileName,MeshFile): data = open(InputFileName,'w+') data.write("\n[Mesh]\ \n type = FileMesh\ \n file = %s \ \n construct_side_list_from_node_list = true\ \n[]\ \n[MeshModifiers]\ \n [./interface]\ \n type = BreakMeshByBlock\ \n [../]\ \n[]\ \n\ \n[MeshModifiers]\ \n [./surface1]\ \n type = BoundingBoxNodeSet\ \n new_boundary = 's'\ \n bottom_left = '0 0 0' # xmin ymin zmin\ \n top_right = '0.4 0 0.052' #xmax ymin+a zmax\ \n # depends_on = 'block1'\ \n [../]\ \n [./surface2]\ \n type = BoundingBoxNodeSet\ \n new_boundary = 'w'\ \n bottom_left = '0 0 0' # xmin ymin zmin\ \n top_right = '0 0.4 0.052' # xmin+a ymax zmax\ \n # depends_on = 'block1'\ \n [../]\ \n [./surface3]\ \n type = BoundingBoxNodeSet\ \n new_boundary = 'n'\ \n bottom_left = '0.0 0.397 0.0' #xmin ymax-a zmin\ \n top_right = '0.4 0.4 0.052' #xmax ymax zmax\ \n # depends_on = 'block1'\ \n [../]\ \n [./surface4]\ \n type = BoundingBoxNodeSet\ \n new_boundary = 'o'\ \n bottom_left = '0.396 0.0 0.0' #xmax-a ymin+a zmin\ \n top_right = '0.4 0.4 0.052' #xmax ymax zmax\ \n # depends_on = 'block1'\ \n [../]\ \n []\ \n\ \n[GlobalParams]\ \n PhiN = 3.61667e-07 #A.Kulachenko T.uesaka MoM (2012)\ \n PhiT = 5.044e-06 #A.Kulachenko T.uesaka MoM (2012) 3.6275\ \n MaxAllowableTraction ='0.00206667 0.00646667 0.00646667' # #A.Kulachenko T.uesaka MoM (2012)\ \n DeltaN = 0.00035 # #A.Kulachenko T.uesaka MoM (2012)\ \n DeltaT = 0.00156 # #A.Kulachenko T.uesaka MoM (2012)\ \n C_ijkl = '100 0.33 0.33 10.72 4.2 10.72 4.35 4.35 35.97'\ \n[]\ \n\ \n[Variables]\ \n [./disp_x]\ \n initial_condition = 1e-15\ \n [../]\ \n [./disp_y]\ \n initial_condition = 1e-15\ \n [../]\ \n [./disp_z]\ \n initial_condition = 1e-15\ \n [../]\ \n[]\ \n\ \n[AuxVariables]\ \n [./vonMises]\ \n family = MONOMIAL\ \n order = FIRST\ \n [../]\ \n [./Rx]\ \n family = LAGRANGE\ \n order = FIRST\ \n [../]\ \n [./Ry]\ \n family = LAGRANGE\ \n order = FIRST\ \n [../]\ \n [./Rz]\ \n family = LAGRANGE\ \n order = FIRST\ \n [../]\ \n [./E]\ \n family = MONOMIAL\ \n order = CONSTANT\ \n [../]\ \n []\ \n\ \n[Kernels]\ \n [./TensorMechanics]\ \n displacements = 'disp_x disp_y disp_z'\ \n save_in = 'Rx Ry Rz'\ \n [../]\ \n[]\ \n\ \n[InterfaceKernels]\ \n [./interface_X]\ \n type = CZMInterfaceKernel\ \n disp_index = 0\ \n variable = disp_x\ \n neighbor_var = disp_x\ \n disp_1 = disp_y\ \n disp_1_neighbor = disp_y\ \n disp_2 = disp_z\ \n disp_2_neighbor = disp_z\ \n boundary = interface\ \n [../]\ \n [./interface_Y]\ \n type = CZMInterfaceKernel\ \n disp_index = 1\ \n variable = disp_y\ \n neighbor_var = disp_y\ \n disp_1 = disp_x\ \n disp_1_neighbor = disp_x\ \n disp_2 = disp_z\ \n disp_2_neighbor = disp_z\ \n boundary = interface\ \n [../]\ \n [./interface_Z]\ \n type = CZMInterfaceKernel\ \n disp_index = 2\ \n variable = disp_z\ \n neighbor_var = disp_z\ \n disp_1 = disp_x\ \n disp_1_neighbor = disp_x\ \n disp_2 = disp_y\ \n disp_2_neighbor = disp_y\ \n boundary = interface\ \n [../]\ \n[]\ \n[AuxKernels]\ \n [./vonMises]\ \n type = RankTwoScalarAux\ \n rank_two_tensor = stress\ \n variable = vonMises\ \n scalar_type = VonMisesStress\ \n [../]\ \n [./elastic_energy]\ \n type = ElasticEnergyAux\ \n variable = E\ \n [../]\ \n[]\ \n\ \n[UserObjects]\ \n [./CZMObject]\ \n type = Exp3DUserObject\ \n disp_x = disp_x\ \n disp_x_neighbor = disp_x\ \n disp_y = disp_y\ \n disp_y_neighbor = disp_y\ \n disp_z = disp_z\ \n disp_z_neighbor = disp_z\ \n execute_on = 'LINEAR'\ \n [../]\ \n[]\ \n\ \n[Materials] " %(MeshFile)) data.close() def CreateInputFileLower(InputFileName): data = open(InputFileName,'w+') data.write("\n [../]\ \n [./strain]\ \n #type = ComputeFiniteStrain\ \n type = ComputeSmallStrain\ \n displacements = 'disp_x disp_y disp_z'\ \n [../]\ \n [./stress]\ \n #type = ComputeFiniteStrainElasticStress\ \n type = ComputeLinearElasticStress\ \n [../]\ \n [./CZMMaterial]\ \n type = Exp3DMaterial\ \n uo_CohesiveInterface = CZMObject\ \n IsDebug = 0\ \n #outputs = exodus\ \n # output_properties = 'Damage DamageN DamageT TractionLocal DispJumpLocal'\ \n #output_properties = 'Damage Damage Area AreaElemID AreaNodeID AreaNormal'\ \n boundary = interface\ \n [../]\ \n[]\ \n\ \n[BCs]\ \n [./suy]\ \n type = PresetBC\ \n variable = disp_y\ \n value = 0.0\ \n boundary = 's'\ \n [../]\ \n [./nuy]\ \n type = PresetBC\ \n variable = disp_y\ \n value = 0.0\ \n boundary = 'n'\ \n [../]\ \n [./wux]\ \n type = PresetBC\ \n variable = disp_x\ \n value = 0.0\ \n boundary = 'w'\ \n [../]\ \n [./oux]\ \n type = FunctionPresetBC\ \n variable = disp_x\ \n function = t\ \n boundary = 'o'\ \n [../]\ \n[]\ \n\ \n[Preconditioning]\ \n [./smp]\ \n type = SMP\ \n full = true\ \n [../]\ \n[]\ \n[Executioner]\ \n type = Transient\ \n #solve_type = PJFNK\ \n solve_type = NEWTON\ \n automatic_scaling = true\ \n petsc_options_iname = '-pc_type -ksp_gmres_restart -pc_factor_mat_solver_type'\ \n petsc_options_value = ' lu 2000 superlu_dist'\ \n compute_scaling_once= true\ \n nl_rel_tol = 1e-10\ \n nl_abs_tol = 1e-09\ \n nl_max_its = 30\ \n # [./TimeStepper]\ \n # type = IterationAdaptiveDT\ \n dt= 1.0e-5\ \n # optimal_iterations = 10\ \n # growth_factor = 1.3\ \n # cutback_factor = 0.5\ \n # [../]\ \n num_steps = 10000000\ \n[]\ \n[Outputs]\ \n print_linear_residuals = true\ \n console = true\ \n csv = true\ \n interval = 3\ \n perf_graph = true\ \n [./oute]\ \n type = Exodus\ \n elemental_as_nodal = true\ \n output_material_properties = true\ \n # show_material_properties = 'Damage TractionLocal DispJumpLocal'\ \n show_material_properties = 'Damage'\ \n [../]\ \n[]\ \n# [Debug]\ \n# show_var_residual = 'disp_x disp_y disp_z'\ \n# []\ \n[Postprocessors]\ \n # [./vonMises]\ \n # type = ElementAverageValue\ \n # variable = vonMises\ \n # []\ \n [ReactionForce_front]\ \n type = NodalSum\ \n variable = 'Rx'\ \n boundary = 'o'\ \n [../]\ \n [./D0]\ \n type = SideValueIntegralPostProcessor\ \n input_value = 1.0\ \n boundary = interface\ \n [../]\ \n [./D]\ \n type = SideDamgeFractionPostProcess\ \n MateName = 'Damage'\ \n pps_name = D0\ \n boundary = interface\ \n [../]\ \n # [Elastic_Energy_sum]\ \n # type = ElementAverageValue\ \n # variable = 'E'\ \n # [../]\ \n[] ") data.close()
def setup(): size(500,500) smooth() background(255) noStroke() colorMode(HSB) flug = True def draw(): global flug if(flug): for i in range(0,10): for j in range(0,5): fill (10, random (0, 255) , random (10, 250)) rect(j*40+50 , i*40+50 , 35, 35) rect ((10 -j)*40+10 , i*40+50 , 35, 35) def mouseClicked(): global flug flug=not flug
class Vertex: def __init__(self): self.stime = None self.etime = None self.colour = "U" self.pred = None self.next = None class Node: def __init__(self, k): self.val = k self.next = None class edge: def __init__(self, v1, v2): self.e1 = v1 self.e2 = v2 L = [] TE = [] BE = [] FE = [] CE = [] E = [] def main(): n = int(input("Enter number of vertices:")) for i in range(n): L.append(Vertex()) # M=[[0 for i in range(0,n)]for j in range(0,n)] e = int(input("Enter number of edges:")) print("Enter the edges:") for i in range(0, e): v1, v2 = input().split() v1, v2 = int(v1), int(v2) N1 = Node(v1) E.append(edge(v1, v2)) tmp = L[v1].next tmp2 = L[v1] while tmp != None: if (not tmp.next) or tmp.next.val > N1.val: N1.next = tmp2.next tmp2.next = N1 break tmp2 = tmp2.next tmp = tmp.next for i in range(len(L)): tmp = L[i].next while tmp != None: print(tmp.val) tmp = tmp.next # N2=Node(v2) """if L[v1].next==None: L[v1].next=N2 else: tmp=L[v1].next N2.next=tmp L[v1].next=N2""" """if L[v2].next==None: L[v2].next=N1 else: tmp=L[v2].next N1.next=tmp L[v2].next=N1""" s = int(input("Enter the source vertex:")) DFS(s) for i in range(n): print("Vertex:", i, "Time:[", L[i].stime, ",", L[i].etime, "]") print("Tree edges:") for i in range(len(TE)): print(TE[i].e1, " ", TE[i].e2) time = 0 def DFS(u): global time time = time + 1 # print(time) L[u].stime = time L[u].colour = "V" tmp = L[u].next while tmp != None: if L[tmp.val].colour == "U": TE.append(edge(u, tmp.val)) DFS(tmp.val) L[tmp.val].pred = u elif L[tmp.val].colour == "E": CE.append(edge(u, tmp.value)) tmp = tmp.next L[u].colour = "E" time = time + 1 # print(time) L[u].etime = time if __name__ == '__main__': main()
# # Copyright 2019-2020 VMware, Inc. # # SPDX-License-Identifier: BSD-2-Clause # # Flask configurations DEBUG = True # Application configurations OBJECT_STORE_HTTPS_ENABLED = False
class FlockAIController: def __init__(self): pass def run(self): pass
class BaseError(Exception): """Base Error Management All custom error exception should inherit from this class. This base exception only handle error message. """ def __init__(self): self._message = None @property def message(self): return self._message class ContainerError(BaseError): """Error Container Custom exception to trigger an error when some application not implement Core.Container abstract class. """ def __init__(self, app_name): BaseError.__init__(self) self._message = "ContainerError: Cannot use {} as container application".format(app_name) self._app_name = app_name Exception.__init__(self, self._message) @property def app_name(self): return self._app_name class ComponentError(BaseError): """Error Component Should be triggered when cannot initialize component object, or given component object is not instance from Component abstract class. """ def __init__(self, com_name): BaseError.__init__(self) self._message = "ComponentError: Cannot use {} as component object".format(com_name) class DotenvNotAvailableError(BaseError): """Error Dotenv Custom exception should be triggered when dotenv file not found. """ def __init__(self): BaseError.__init__(self) self._message = 'Unable to load environment file.' class UnknownEnvError(BaseError): """Error Unknown Environment Name Custom exception that should be triggered when system try to load all environment variables from unspecified environment name. """ def __init__(self, name=None): BaseError.__init__(self) self._message = 'Unknown environment name: {}.'.format(name)
#!/usr/bin/python3 # --- 001 > U5W2P1_Task11_w1 def solution( a, b ): input = [a, b] larger = -float('inf') for x in input: if(larger < x): larger = x return larger if __name__ == "__main__": print('----------start------------') a = 1510 b = 7043 print(solution( a, b)) print('------------end------------')
def get_converter_type_any(*args, **kwargs): """ Handle converter type "any" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'array', 'items': { 'type': 'string', 'enum': args, } } return schema def get_converter_type_int(*args, **kwargs): """ Handle converter type "int" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'integer', 'format': 'int32', } if 'max' in kwargs: schema['maximum'] = kwargs['max'] if 'min' in kwargs: schema['minimum'] = kwargs['min'] return schema def get_converter_type_float(*args, **kwargs): """ Handle converter type "float" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'number', 'format': 'float', } return schema def get_converter_type_uuid(*args, **kwargs): """ Handle converter type "uuid" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'string', 'format': 'uuid', } return schema def get_converter_type_path(*args, **kwargs): """ Handle converter type "path" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'string', 'format': 'path', } return schema def get_converter_type_string(*args, **kwargs): """ Handle converter type "string" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'string', } for prop in ['length', 'maxLength', 'minLength']: if prop in kwargs: schema[prop] = kwargs[prop] return schema def get_converter_type_default(*args, **kwargs): """ Handle converter type "default" :param args: :param kwargs: :return: return schema dict """ schema = {'type': 'string'} return schema
# on test start def enbale(instance): return False def action(instance): pass
TUNSETIFF = 0x400454ca IFF_TUN = 0x0001 IFACE_IP = "10.1.2.1/24" MTU = 65000 ServerIP = "199.230.109.242" debug = True updateSeqno = 105 Runloc = "/home/icmp/"
#Desafio: Calculadora do amor print("Calculadora do amor") print("<3 "*7) #solicita ao usuario o nome de duas pessoas #converte os nomes para minúsculos e tira os espaços nomes = input("Digite o nome de 2 pessoas: ").strip().lower() #atribui o valor zero para a variável placar placar = 0 #o laço de repetição realiza a busca de cada letra nos nomes. for letra in nomes: #a condição define que se as letras no loop do laço estiver nas vogais #o placar que é zero recebe ele mesmo mais 5 pontos. if letra in "aeiou": placar += 5 #a condição define que se as letras no loop do laço estiver na palavra amor #o placar que é zero recebe ele mesmo mais 10 pontos. if letra in "amor": placar += 10 #imprime uma mensagem com o valor do placar de acordo com o resultado #das condições informadas print(f"Seu placar de compatibilidade : {placar}") #estrutura de condição para exibir uma mensagem personalizada #caso o placar seja menor que dez, então imprime a mensagem if placar < 10: print("Esqueça esta pessoas! Nunca vai dar certo!") #caso não seja, ele imprime a mensagem abaixo else: print("Vocês terão um relacionamento muito intenso! <3")
class Slides_Menu(): def Slides_Menu_Active(self,paths,subdir): cgipaths=self.Slides_CGI_Paths() rpaths=list(paths) rpaths.append(subdir) res=False if ( len(cgipaths)>len(paths) ): res=True for i in range( len(rpaths) ): if ( rpaths[i]!=cgipaths[i]): res=False return res def Slides_Menu_Path(self,paths): return "/".join([self.DocRoot]+paths) def Slides_Menu_Pre(self,paths): paths=self.Slides_CGI_Paths() paths.pop() html=[] rpaths=[] for path in paths: html=html+[ self.Slide_Menu_Entry_Title_A(rpaths), ] rpaths.append(path) return self.HTML_List(html)+[self.BR()] def Slides_Menu(self,paths): url="/".join(paths) cssclass="leftmenu" htmllist=[] path="/".join([self.DocRoot]+paths) subdirs=self.Path_Dirs( self.Slides_Menu_Path(paths), "Name.html" ) for subdir in subdirs: htmlitem=[] if (self.Slides_Menu_Active(paths,subdir)): rpaths=list(paths) rpaths.append(subdir) htmlitem=self.Slides_Menu(rpaths) else: htmlitem=self.Slide_SubMenu_Entry(subdir,paths,cssclass) htmllist.append(htmlitem) html=[] html=html+[ self.Slide_Menu_Entry(paths,cssclass) ] html=html+[ self.HTML_List( htmllist, "UL", { "style": 'list-style-type:square', } ) ] return html def Slide_Menu_Entry(self,paths,cssclass): cpath=self.CGI_POST("Path") path="/".join(paths) name=self.Slide_Name_Get(paths) if (path==cpath): return self.B( name+"*", { "title": self.Slide_Title_Get(paths), } ) return [ #Moved to Slide_Menu_Pre self.Slide_Menu_Entry_Title_A(paths,name,cssclass) ] def Slide_Menu_Entry_Title_A(self,paths,name=None,cssclass=None): if (name==None): name=self.Slide_Name_Get(paths) if (cssclass==None): cssclass="leftmenu" return self.A( "?Path="+"/".join(paths), name, { "class": cssclass, "title": self.Slide_Title_Get(paths), } )
class Solution: def reorderSpaces(self, text: str) -> str: spaces = text.count(" ") words = [w for w in text.split(" ") if w] l = len(words) if l == 1: return words[0] + " " * spaces each, remaining = divmod(spaces, l - 1) return (" " * each).join(words) + (" " * remaining)
{ 'targets': [ { 'target_name': 'freetype2', 'dependencies': [ 'gyp/libfreetype.gyp:libfreetype' ], 'sources': [ 'src/freetype2.cc', 'src/fontface.cc' ], "include_dirs" : [ "<!(node -e \"require('nan')\")" ], } ] }
class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: d = {} matches = {} for i, name in enumerate(list1): d[name] = i for i, name in enumerate(list2): if name in d: matches[name] = i + d[name] l = sorted(matches.items(), key = lambda x:x[1]) ans = [] for (res, sm) in l: if sm == l[0][1]: ans.append(res) return ans
bakeQty = int(input()) bakeCapacity = int(input()) CurniEatOnHour = int(input()) GanioEatOnHour = int(input()) hours = int(input()) productivityOnHour = bakeCapacity-CurniEatOnHour-GanioEatOnHour if productivityOnHour*hours>=bakeQty: print('YES') else: print('NO-',"{:.0f}".format(bakeQty-productivityOnHour*hours))
# -*- coding: utf-8 -*- """ Created on Fri Jul 12 19:36:35 2019 @author: Rob """ # Find how many times throughout the show each Friend is saying name # of some other Friend # Include nicknames: Pheebs, Rach, Mon, Joseph, # Create nested dictionary with a Friend and for each friend # place how many times they are saying name of other Friends # Each key -- Friend name, should have subdictionary with # other Friend names keys and for each of them value will # be a list of the counts how many times per episode # they were called by key Friend. def friend_mentions(): """ Returns: Nested dictionary. """ name_mentiones = { 'Monica' : (), 'Rachel' : (), 'Ross' : (), 'Joey' : (), 'Phoebe' : (), 'Chandler': () } return name_mentiones # Who was the most featured in the beginning in each episode # Find counts of Friends names before the Openning Credits # (Openning title); in a file def episode_intro(): intro_count = [] opening_credits = '**Opening Credits**' for i, each_ep in enumerate(all_episodes_in_a_season_txt): # There are plenty formatings for "Opening Credits", fine all of them and replace them with the most used ones replace_each_ep = each_ep.replace('### Opening Credits', opening_credits).replace('Opening Credits**', opening_credits).replace('**OPENING TITLES**', opening_credits).replace('OPENING TITLES', opening_credits).replace('## Credits', opening_credits).replace('OPENING CREDITS', opening_credits).replace('Opening Credits', opening_credits).replace('**Opening credits.**', opening_credits).replace('Opening credits', opening_credits).replace('OPENING SEQUENCE',opening_credits) # Check if the phrase "**Opening Credits**" is in the text if '**Opening Credits**' not in replace_each_ep: print(i) get_intro = replace_each_ep.split('**Opening Credits**')[0] # Remove text within [] and () brackets. These lines are scene description. one_intro_tmp = re.sub( "\[[^\]]*\]", "", get_intro) # Removes [] intro_clear = re.sub('\([^)]*\)', "",one_intro_tmp) # Removes () intro_count.append(intro_clear) print(intro_count[225][0:2600]) print(len(intro_count)) return intro_count # Find how many times the scenes are in the Central Perk # How many times the scene before openning credits in in Central Perk # Scenes are not always placed in text - locate ep. without that def scene_central_perk(): counts_central_perk = [] counts_central_perk_openning = [] return counts_central_perk, counts_central_perk_openning # Divide every episode into scenes and find which of Friends are # the most frequent featured in scenes together def frequently_together(): return # Find lines, apearance of Janice throughout the series # Make her cloudword # Count how many times she says "Oh My God" def janice(): return ################################################## ########### Handle the functions ################# ################################################## if __name__ == "__main__": intro = episode_intro()
weight_list=[] price_list=[] def knapsack(capacity,weight_list,price_list): x=list(range(len(price_list))) ratio=[v/w for v,w in zip(price_list,weight_list)] x.sort(key=lambda i:ratio[i],reverse=True) Maximum_profit=0 for i in x: if(weight_list[i]<=capacity): Maximum_profit+=price_list[i] capacity-=weight_list[i] else: Maximum_profit+=(price_list[i]*capacity)/weight_list[i] break return Maximum_profit n=int(input("Enter how many number of object available in market:")) print("Enter weight of object:") for i in range(0,n): item1=int(input()) weight_list.append(item1) print("Enter price:") for i in range(0,n): item2=int(input()) price_list.append(item2) print("Entered profit:",weight_list) print("Entered price list of objects:",price_list) capacity=int(input("Enter capacity of the bag:")) Maximum_profit=knapsack(capacity,weight_list,price_list) print("Maximum profit obtaind:",Maximum_profit)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Aug 27 22:37:42 2018 @author: owen """
# _*_ coding: utf-8 _*_ """ python_metaclass.py by xianhu """ class Foo(object): def hello(self): print("hello world!") return foo = Foo() print(type(foo)) # <class '__main__.Foo'> print(type(foo.hello)) # <class 'method'> print(type(Foo)) # <class 'type'> temp = Foo # 赋值给其他变量 Foo.var = 11 # 增加参数 print(Foo) # 作为函数参数 # ======================================================================== def init(self, name): self.name = name return def hello(self): print("hello %s" % self.name) return Foo = type("Foo", (object,), {"__init__": init, "hello": hello, "cls_var": 10}) foo = Foo("xianhu") print(foo.hello()) print(Foo.cls_var) print(foo.__class__) print(Foo.__class__) print(type.__class__) # ======================================================================== class Author(type): def __new__(mcs, name, bases, dict): # 添加作者属性 dict["author"] = "xianhu" return super(Author, mcs).__new__(mcs, name, bases, dict) class Foo(object, metaclass=Author): pass foo = Foo() print(foo.author)
# Exercício Python #001 - Somando dois números n1 = int(input('Digite um numero: ')) n2 = int(input('Digite outro valor: ')) s = n1 + n2 print('A soma ente {} e {} é igual a {}!' .format(n1, n2, s))
############################################################################### # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. ############################################################################### def get_permutation_config(n_dims): input_perm_axes = [0, n_dims + 1] + list(range(1, n_dims + 1)) output_perm_axes = [0] + list(range(2, n_dims + 2)) + [1] return input_perm_axes, output_perm_axes
testcases = int(input()) for t in range(testcases): rounds = int(input()) chef_points = 0 morty_points = 0 for round in range(rounds): chef, morty = list(map(int, input().split())) chef_sum = 0 morty_sum = 0 while(chef != 0): r = int(chef % 10) chef = int(chef / 10) chef_sum += r while(morty != 0): r = int(morty % 10) morty = int(morty / 10) morty_sum += r if(chef_sum > morty_sum): chef_points += 1 #print(str(0) + " " + str(chef_sum)) elif(chef_sum < morty_sum): morty_points += 1 #print(str(1) + " " + str(morty_sum)) else: chef_points += 1 morty_points += 1 #print(str(2) + " " + str(morty_sum)) print('0 ' + str(chef_points) if chef_points > morty_points else '1 ' + str(morty_points) if chef_points < morty_points else '2 ' + str(morty_points))
nomes = ("Alexandre", "Eduardo", "Henrique", "Murilo", "Theo", "André", "Enrico", "Henry", "Nathan", "Thiago", "Antônio", "Enzo", "Ian", "Otávio", "Thomas", "Augusto", "Erick", "Isaac", "Pietro", "Vicente", "Breno", "Felipe", "João", "Rafael", "Vinícius", "Bruno", "Fernando", "Kaique", "Raul", "Vitor", "Caio", "Francisco", "Leonardo", "Rian", "Yago", "Cauã", "Frederico", "Luan", "Ricardo", "Ygor", "Daniel", "Guilherme", "Lucas", "Rodrigo", "Yuri", "Danilo", "Gustavo", "Mathias", "Samuel", "Agatha", "Camila", "Esther", "Isis", "Maitê", "Natália", "Alícia", "Carolina", "Fernanda", "Joana", "Malu", "Nicole", "Amanda", "Catarina", "Gabriela", "Laís", "Maria", "Olívia", "Ana", "Cecília", "Gabrielle", "Lara", "Mariah", "Pietra", "Antonela", "Clara", "Giovanna", "Larissa", "Mariana", "Rafaela", "Aurora", "Clarice", "Giulia", "Lavínia", "Marina", "Rebeca", "Bárbara", "Eduarda", "Heloísa", "Letícia", "Maya", "Sara", "Beatriz", "Elisa", "Isabel", "Liz", "Melissa", "Sophie", "Bianca", "Emanuelly", "Isabelly", "Lorena", "Milena", "Stella", "Bruna", "Emilly", "Isadora", "Luana", "Mirella", "Vitória", "Yasmin") generos = ("ação", "animação", "aventura", "comédia", "comédia romântica", "documentário", "drama", "ficção científica", "guerra", "musical", "policial", "romance", "super-herói", "suspense", "terror") class Filme: def __init__(self, nome, genero, indie, novo): self.nome = nome #str self.genero = genero #str self.indie = indie #bool self.novo = novo #bool filmes = [] # filmes novos e não-indie filmes.append(Filme('Alita: Anjo de Combate (2019)', 'ação', 0, 1)) filmes.append(Filme('Dumbo (2019)', 'animação', 0, 1)) filmes.append(Filme('Aladdin (2019)', 'aventura', 0, 1)) filmes.append(Filme('De Pernas pro Ar 3 (2019)', 'comédia', 0, 1)) filmes.append(Filme('Casal Improvável (2019)', 'comédia romântica', 0, 1)) filmes.append(Filme('Amazônia - O despertar da florestania (2019)', 'documentário', 0, 1)) filmes.append(Filme('Superação - O Milagre da Fé (2019)', 'drama', 0, 1)) filmes.append(Filme('Capitã Marvel (2019)', 'ficção científica', 0, 1)) filmes.append(Filme('Tolkien (2019)', 'guerra', 0, 1)) filmes.append(Filme('UglyDolls (2019)', 'musical', 0, 1)) filmes.append(Filme('Pokémon - Detetive Pikachu (2019)', 'policial', 0, 1)) filmes.append(Filme('After (2019)', 'romance', 0, 1)) filmes.append(Filme('Vingadores: Ultimato (2019)', 'super-herói', 0, 1)) filmes.append(Filme('A Maldição da Chorona (2019)', 'suspense', 0, 1)) filmes.append(Filme('Cemitério maldito (2019)', 'terror', 0, 1)) # filmes novos e indie filmes.append(Filme('The Offender (2019)', 'ação', 1, 1)) filmes.append(Filme('A Lenda dos Guardiões (2010)', 'animação', 1, 1)) filmes.append(Filme('O Grande Hotel Budapeste (2014)', 'aventura', 1, 1)) filmes.append(Filme('Night of Adventure (2019)', 'comédia', 1, 1)) filmes.append(Filme('Scott Pilgrim Contra o Mundo (2010)', 'comédia romântica', 1, 1)) filmes.append(Filme('O Sushi dos Sonhos de Jiro (2011)', 'documentário', 1, 1)) filmes.append(Filme('Eu, Você e a Garota Que Vai Morrer (2015)', 'drama', 1, 1)) filmes.append(Filme('Ela (2013)', 'ficção científica', 1, 1)) filmes.append(Filme('Little Boy - Além do Impossível (2015)', 'guerra', 1, 1)) filmes.append(Filme('Inside Llewyn Davis: Balada de um Homem Comum (2013)', 'musical', 1, 1)) filmes.append(Filme('Um Deslize Perigoso (2015)', 'policial', 1, 1)) filmes.append(Filme('A Garota Dinamarquesa (2015)', 'romance', 1, 1)) filmes.append(Filme('Kick-Ass (2010)', 'super-herói', 1, 1)) filmes.append(Filme('Frank (2014)', 'suspense', 1, 1)) filmes.append(Filme('O Uivo (2015)', 'terror', 1, 1)) # filmes antigos e indie filmes.append(Filme('O Profissional (1994)', 'ação', 1, 0)) filmes.append(Filme('Planeta Fantástico (1973)', 'animação', 1, 0)) filmes.append(Filme('Pequena Miss Sunshine (2006)', 'aventura', 1, 0)) filmes.append(Filme('Barbarella (1968)', 'comédia', 1, 0)) filmes.append(Filme('Essa Estranha Atração (1988)', 'comédia romântica', 1, 0)) filmes.append(Filme('A Enseada (2009)', 'documentário', 1, 0)) filmes.append(Filme('O Barco: Inferno no Mar (1981)', 'drama', 1, 0)) filmes.append(Filme('Laranja Mecânica (1971)', 'ficção científica', 1, 0)) filmes.append(Filme('Vá e Veja (1985)', 'guerra', 1, 0)) filmes.append(Filme('The Rocky Horror Picture Show (1975)', 'musical', 1, 0)) filmes.append(Filme('Taxi Driver: Motorista de Táxi (1976)', 'policial', 1, 0)) filmes.append(Filme('Maurice (1987)', 'romance', 1, 0)) filmes.append(Filme('The Crow (1994)', 'super-herói', 1, 0)) filmes.append(Filme('Parceiros da Noite (1980)', 'suspense', 1, 0)) filmes.append(Filme('Trilogia de Terror (1975)', 'terror', 1, 0)) # filmes antigos e não-idie filmes.append(Filme('Star Wars, Episódio V: O Império Contra-Ataca (1980)', 'ação', 0, 0)) filmes.append(Filme('A Viagem de Chihiro (2001)', 'animação', 0, 0)) filmes.append(Filme('O Senhor dos Anéis: O Retorno do Rei (2003)', 'aventura', 0, 0)) filmes.append(Filme('Luzes da Cidade (1931)', 'comédia', 0, 0)) filmes.append(Filme('A Vida é Bela (1997)', 'comédia romântica', 0, 0)) filmes.append(Filme('Shoah (1985)', 'documentário', 0, 0)) filmes.append(Filme('Um Sonho de Liberdade (1994)', 'drama', 0, 0)) filmes.append(Filme('Matrix (1999)', 'ficção científica', 0, 0)) filmes.append(Filme('O Resgate do Soldado Ryan (1998)', 'guerra', 0, 0)) filmes.append(Filme('O Pianista (2002)', 'musical', 0, 0)) filmes.append(Filme('Seven: Os Sete Crimes Capitais (1995)', 'policial', 0, 0)) filmes.append(Filme('Forrest Gump: O Contador de Histórias (1994)', 'romance', 0, 0)) filmes.append(Filme('Batman: O Cavaleiro das Trevas (2008)', 'super-herói', 0, 0)) filmes.append(Filme('Os Suspeitos (1995)', 'suspense', 0, 0)) filmes.append(Filme('Psicose (1960)', 'terror', 0, 0)) # expressões regulares pegaNome = r'\w[a-zÀ-ÿ]*$' pegaApelido = r'^\w{2}' regExGeneros = r'(animação|animacao|animaçao|animações|animaçoes|ação|açao|aventura|comédia romântica|comedia romântica|comedia romantica|comédia|comedia|documentario|documentário|drama|ficção científica|ficção|sci fi|sci-fi|ficçao cientifica|ficção cientifica|guerra|musical|policial|romance|super-herói|herói|heroi|super heroi|super-heroi|suspense|terror|horror)' curte = r'(sim|gosto|curto|pode ser|aham|ok|true|tru|ye|yes|certo|adoro|amo|as vezes|sou)' naoCurte = r'(não|nao|na verdade|nah|gosto mesmo é de|não gosto|nao gosto)' encontraLancamento = r'(lançamentos|lançamento|lancamento|lancamentos|blockbuster|AAA|novos|novo)' encontraAntigo = r'(antigos|clássicos|clássico|classico|classicos|antigo|datados)' encontraIndie = r'(nao famoso|não famoso|não famosos|nao famosos|indie|indies|desconnhecido|desconhecidos|não popular|não populares|nao populares|obscuro|obscuro|cult|cults|não muito popular|não muito populares|nao muito populares|nao popular|nao muito popular|independente|independentes)' encontraConhecido = r'(\bconhecidos\b|\bconhecido\b|popular|populares|famoso|famosos|pop)' # (tanto faz|nao importa|qualquer|qualquer um|tu que sabe|voce decide|decidir|decide aí) # fillers fillers = ("", "", "", "", "", "", "", "", "", "", "") # base de dados de falas da fase 1 falasNomeNada = ("Olha... se você não quer falar eu não vou te forçar, mas de agora em diante você será ", "Hmmmm temos alguém que se importa com a privacidade aqui... vou te chamar de ", "Tá bom então, vou te chamar de ") falasNomeComprido = ("Nossa que nome grande, vamos fazer assim vou te chamar de ", "Bah eu não vou escrever tudo isso, vou te chamar de ", "kkkkk como pronuncia tudo isso? Vou te chamar de ") falasNomeElogio = ("Haha que nome engraçado ", "Gostei desse nome, vou chamar minha tartaruga de ", "Que nome simpático ") falasSugereGenero = ("Bah eu chutaria que tu é uma pessoa que gosta do gênero ", "Olha... eu te recomendo bastante o gênero ", "Tu tem cara de alguém passa tardes assistindo filmes do gênero ") falasEscolheGeneroAleatorio = ("Aff assim você não tá me ajudando, vamos fazer assim eu escolho o gênero ", "Hmmmm... ok então vamos com o gênero ", "Não to te entendendo, então vou escolher o gênero ") falasNaoReconheceGenero = ("Perdão mas eu não entendi", "Não conheço esse aí não", "É pra você me dizer seu gênero favorito salkjdaskj") falasComentaSobreGenero = ("Hehe já passei mais tardes do que gostaria de admitir assistindo filmes de ", "Ahhhh! Eu adoro filmes de ", "É clichê, mas são muito bons os filmes de ") # base de dados de falas da fase 2 falasComentaSobreLancamento = ("Ah nada como ir no cinema aproveitar um filme recém lançado", "Bah eu também, todo mundo conversando sobre o filme recém lançado, muito bom", "Opa, temos alguém que gosta dos novos filmes então") falasComentaSobreAntigo = ("Ah sim, nada como assistir os grandes clássicos", "Então você é do tipo que comenta sobre os filmes que assite pros seus pais e é da epoca deles", "Nossa eu também adoro filmes mais antigos, é uma nova vibe comparando com os lançamentos atuais") # base de dados de falas da fase 3 falasComentaSobreConhecido = ("Ah eu também prefiro filmes conhecidos, é mais fácil pra conversar sobre com os amigos", "O bom de filmes conhecidos é que tem bastante review na internet!", "Opa eu também gosto de filmes mais conhecidos e tal") falasComentaSobreIndie = ("Uhhhh temos alguém cult aqui, só nos filmes independentes obscuros", "Então você é do tipo que comenta sobre os filmes que assite e seus amigos ficam ????", "Bah eu também adoro! Mas é dificil encontrar pessoas pra conversar sobre") # base de dados de falas da fase 2 e 3 falasNaoReconhece = ("Perdão mas eu não entendi, pode repetir?", "Não entendi, repete por favor", "AH sim, não pera, não entendi, pode repetir?") falasEscolheAleatorio = ("Rsrs não quer falar é, então vamos de filmes ", "Ah já que você não quer participar eu escolho filmes ", "Ok... vou escolher filmes ") falasResumeSituacao = ("Certo então estamos procurando por filmes de ", "Ok estabelecemos que queremos filmes de ", "Tá então vamos procurar por filmes de ") # base de dados de falas da fase 4 falasMostraRecomendacao = ("Certo, então eu minha recomendação pra você é ", "Feito! Então eu te recomendo o filme ", "Ufa terminamos, minha recomendação pra você é ") falasMensagemDeTchau = ("É isso! Terminamos, foi um prazer recomendar um filme pra você! Tchau!", "Ok, meu trabalho aqui está feito, foi um prazer te recomendar um filme, adeus!",)
class Solution: def fizzBuzz(self, n: int) -> List[str]: d = {3: 'Fizz', 5: 'Buzz'} return [''.join([d[k] for k in d if i % k == 0]) or str(i) for i in range(1, n + 1)]
print(0) # 0 print(-0) # 0 print(0 == -0) # True print(0 is -0) # True print(0.0) # 0.0 print(-0.0) # -0.0 print(0.0 == -0.0) # True print(0.0 is -0.0) # False
""" Write a function that takes a string as input and reverse only the vowels of a string. Example: Input: "hello" Output: "holle" Example: Input: "leetcode" Output: "leotcede" Note: - The vowels does not include the letter "y". """ #Difficulty: Easy #481 / 481 test cases passed. #Runtime: 48 ms #Memory Usage: 14.8 MB #Runtime: 48 ms, faster than 92.51% of Python3 online submissions for Reverse Vowels of a String. #Memory Usage: 14.8 MB, less than 61.15% of Python3 online submissions for Reverse Vowels of a String class Solution: def reverseVowels(self, s: str) -> str: s = list(s) i = 0 l = len(s) - 1 #vowels = 'aAeEiIoOuU' vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} while i < l: if s[i] in vowels: while s[l] not in vowels: l -= 1 if i < l: s[i], s[l] = s[l], s[i] i += 1 l -= 1 continue i += 1 return ''.join(s)
frase = 'Curso em vídeo Python' frase2 = frase.replace('Python','Teste') print(frase[9::2]) print(len(frase)) print(frase.count('o',0,21)) print(frase.find('deo')) print(frase.find('android')) print('Curso' in frase) print('Hoje' in frase) print(frase) print(frase2) print(frase.upper()) print(frase.lower()) print(frase.capitalize()) print(frase.title()) print(frase.split()) print('-'.join(frase))
def update_param(name, param): if name == 'distribution': param['values'].remove('custom') return param return None # param untouched def class_extensions(): @property def Lambda(self): """DEPRECATED. Use ``self.lambda_`` instead""" return self._parms["lambda"] if "lambda" in self._parms else None @Lambda.setter def Lambda(self, value): self._parms["lambda"] = value extensions = dict( __imports__="""import h2o""", __class__=class_extensions, __init__validation=""" if "Lambda" in kwargs: kwargs["lambda_"] = kwargs.pop("Lambda") """ ) overrides = dict( alpha=dict( setter=""" # For `alpha` and `lambda` the server reports type float[], while in practice simple floats are also ok assert_is_type({pname}, None, numeric, [numeric]) self._parms["{sname}"] = {pname} """ ), lambda_=dict( setter=""" assert_is_type({pname}, None, numeric, [numeric]) self._parms["{sname}"] = {pname} """ ), ) doc = dict( __class__=""" Fits a generalized additive model, specified by a response variable, a set of predictors, and a description of the error distribution. A subclass of :class:`ModelBase` is returned. The specific subclass depends on the machine learning task at hand (if it's binomial classification, then an H2OBinomialModel is returned, if it's regression then a H2ORegressionModel is returned). The default print-out of the models is shown, but further GAM-specific information can be queried out of the object. Upon completion of the GAM, the resulting object has coefficients, normalized coefficients, residual/null deviance, aic, and a host of model metrics including MSE, AUC (for logistic regression), degrees of freedom, and confusion matrices. """ )
# Calling the following function like so def print_date(year, month, day): joined = str(year) + '/' + str(month) + '/' + str(day) print(joined) result = print_date(1871, 3, 19) print('result of call is:', result) # prints the following output, in that order: # 1871/3/19 # result of call is: None # Explain why the two lines of output appeared in the order they did. # What’s wrong in this example? result = print_date(1871,3,19) def print_date(year, month, day): joined = str(year) + '/' + str(month) + '/' + str(day) print(joined)
""" Day 01 - Solution 01 Puzzle input as file to read. """ def main() -> None: """ Call the functions and display. """ expense_list = import_list() print(f"Part 1: {find_sum_two(expense_list)}") print(f"Part 2: {find_sum_three(expense_list)}") def import_list() -> list: """ Read file and return list. :return: List of integers :rtype: list """ file = open("../puzzle-input", "r") string_list = list(file.readlines()) int_list = [int(i) for i in map(str.strip, string_list)] file.close() return int_list def find_sum_two(expenses: list, total=2020) -> int: """ Iterate over the list and subtract from total value. :param expenses: List of integers :param total: Total value :return: Product of two values :rtype: int """ for first in expenses: second = total - first if second in expenses: return first * second raise ValueError("Not solvable") def find_sum_three(expenses: list) -> int: """ Attempt every calculation while iterating over list to find third entry. :param expenses: List of integers :return: Product of three values :rtype: int """ while expenses: selected = expenses.pop() remainder = 2020 - selected try: return selected * find_sum_two(expenses, total=remainder) except ValueError: continue if __name__ == "__main__": main()
#!/usr/bin/env python # encoding: utf-8 # @author: Zhipeng Ye # @contact: Zhipeng.ye19@xjtlu.edu.cn # @file: permutation.py # @time: 2020-03-18 22:46 # @desc: def permute(nums): paths = [] def record_path(path,nums_copy): if len(nums_copy) ==1: path.append(nums_copy[0]) paths.append(path) return for i in range(len(nums_copy)): path = path[:] path.append(nums_copy[i]) nums_copy_copy = nums_copy[:] del(nums_copy_copy[i]) record_path(path,nums_copy_copy) record_path([],nums) print(paths) permute([1,2,3])
"""The code template to supply to the front end. This is what the user will be asked to complete and submit for grading. Do not include any imports. This is not a REPL environment so include explicit 'print' statements for any outputs you want to be displayed back to the user. Use triple single quotes to enclose the formatted code block. """ challenge_code = '''k_bits = 2 n_bits = 2 all_bits = k_bits + n_bits aux = range(k_bits) main = range(k_bits, all_bits) dev = qml.device("default.qubit", wires=all_bits) def PREPARE(alpha_list): """Create the PREPARE oracle as a matrix. Args: alpha_list (array[float]): A list of coefficients. Returns: array[complex]: The matrix representation of the PREPARE routine. """ zero_vec = np.array([1] + [0]*(2**k_bits - 1)) ################## # YOUR CODE HERE # ################## '''
def spread_bunnies(lair, rows, columns): b_ees = [] for i in range(rows): for j in range(columns): if lair[i][j] == 'B': b_ees.append([i, j]) for b in b_ees: i = b[0] j = b[1] if i - 1 >= 0: lair[i - 1][j] = 'B' if i + 1 < rows: lair[i + 1][j] = 'B' if j - 1 >= 0: lair[i][j - 1] = 'B' if j + 1 < columns: lair[i][j + 1] = 'B' return lair rows, columns = map(int, input().split(' ')) lair = [] for _ in range(rows): lair.append([]) [lair[-1].append(x) for x in input()] directions = [x for x in input()] position = [] for i in range(rows): for j in range(columns): if lair[i][j] == 'P': position.append(i) position.append(j) break initial_row = position[0] initial_column = position[1] row = initial_row column = initial_column for move in directions: spread_bunnies(lair, rows, columns) if move == 'L': if column - 1 >= 0: if lair[row][column] != 'B': lair[row][column] = '.' row = row column = column - 1 if lair[row][column] == 'B': [print(''.join(row)) for row in lair] print(f"dead: {row} {column}") break else: lair[row][column] = 'P' else: if lair[row][column] != 'B': lair[row][column] = '.' [print(''.join(row)) for row in lair] print(f'won: {row} {column}') break if move == 'R': if column + 1 < columns: if lair[row][column] != 'B': lair[row][column] = '.' row = row column = column + 1 if lair[row][column] == 'B': [print(''.join(row)) for row in lair] print(f"dead: {row} {column}") break else: lair[row][column] = 'P' else: if lair[row][column] != 'B': lair[row][column] = '.' [print(''.join(row)) for row in lair] print(f'won: {row} {column}') break if move == 'U': if row - 1 >= 0: if lair[row][column] != 'B': lair[row][column] = '.' row = row - 1 column = column if lair[row][column] == 'B': [print(''.join(row)) for row in lair] print(f"dead: {row} {column}") break else: lair[row][column] = 'P' else: if lair[row][column] != 'B': lair[row][column] = '.' [print(''.join(row)) for row in lair] print(f'won: {row} {column}') break if move == 'D': if row + 1 < rows: if lair[row][column] != 'B': lair[row][column] = '.' row = row + 1 column = column if lair[row][column] == 'B': [print(''.join(row)) for row in lair] print(f"dead: {row} {column}") break else: lair[row][column] = 'P' else: if lair[row][column] != 'B': lair[row][column] = '.' [print(''.join(row)) for row in lair] print(f'won: {row} {column}') break
# ... client initialization left out data_client = client.data file_path = "experiments/data.xrdml" dataset_id = 1 ingester_list = data_client.list_ingesters() xrdml_ingester = ingester_list.find_by_id("citrine/ingest xrdml_xrd_converter") # Printing the ingester's arguments, we can see it requires an argument with the # name `sample_id`, and another with the name `chemical_formula`, both of which # should be strings. print(ingester.arguments) # [{ 'name': 'sample_id', # 'desc': 'An ID to uniquely identify the material referenced in the file.', # 'type': 'String', # 'required': True }, # { 'name': 'chemical_formula', # 'desc': 'The chemical formula of the material referenced in the file.', # 'type': 'String', # 'required': True }] ingester_arguments = [ { "name": "sample_id", "value": "1212" }, { "name": "chemical_formula", "value": "NaCl" }, ] # To ingest the file using the file_path as the destination path data_client.upload_with_ingester( dataset_id, file_path, xrdml_ingester, ingester_arguments ) # To ingest the file using a different destination path data_client.upload_with_ingester( dataset_id, file_path, xrdml_ingester, ingester_arguments, 'data.xrdml' )
class Action: def __init__(self, target, full, title, short): self.target = target self.full = full self.title = title self.short = short def __repr__(self): return '{"destructive":0, "full":"%s", "title":"%s", "short":"%s","identifier":"%s"}'%(self.title, self.full, self.short, self.target)
### SELF-ORGANIZING MAPS (SOM) CLUSTERING ON TIME-HORIZON ### # INITIALIZE TRANSFORMED DATA & SELECTED SERIES/CHANNELS df = data.copy() list_channel = ['CBS', 'NBC', 'ABC', 'FOX', 'MSNBC', 'ESPN' ,'CNN', 'UNI', 'DISNEY CHANNEL', 'MTV'] list_target = ['18+', 'F18-34'] list_day_part = ['Morning', 'Daytime', 'Early Fringe', 'Prime Time', 'Late Fringe'] end_date = '2019-09-28' def split_dataframe(df, chunk_size=7): chunks = list() num_chunks = len(df) // chunk_size + 1 for i in range(num_chunks): chunks.append(df[i*chunk_size:(i+1)*chunk_size]) return chunks df_output_final = pd.DataFrame() for channel in tqdm(list_channel): for target in list_target: for day_part in list_day_part: random_seed = 1234 df_all = data.copy() df_all = df_all[(df_all['daypart'] == day_part) & (df_all['target'] == target)] df_all['Week'] = df_all['date'].apply(lambda x: x.strftime('%V')) df = data[(data['date'] < end_date) & (data['daypart'] == day_part) & (data['target'] == target)][['date', 'target', 'daypart', channel]].reset_index(drop=True) if channel == 'MTV': impute = df[df['MTV'] == 0] impute = df.loc[df['date'].isin(impute['date'] - dt.timedelta(days=364*2)), 'MTV'] df.loc[df['MTV'] == 0, 'MTV'] = impute.values df['Week'] = df['date'].apply(lambda x: x.strftime('%V')) df['Trend'] = sm.tsa.seasonal_decompose(df[channel], model='additive', freq=7, extrapolate_trend='freq').trend df['Seasonal_weekly'] = sm.tsa.seasonal_decompose(df[channel], model='additive', freq=7, extrapolate_trend='freq').seasonal df['Fourier'] = data[(data['date'] < end_date) & (data['daypart'] == day_part) & (data['target'] == target)]['fourier_' + channel].reset_index(drop=True) df = df[df['date'] != '2016-02-29'].reset_index(drop=True) for week in df['Week'].unique(): for df_split in split_dataframe(df.loc[df['Week'] == week, :], 7): if df_split.empty: continue # TREND & SEASONALITY Yt = df.loc[df_split.index, channel] - df.loc[df_split.index, 'Trend'] - df.loc[df_split.index, 'Seasonal_weekly'] Zt = df.loc[df_split.index, channel] - df.loc[df_split.index, 'Seasonal_weekly'] Xt = df.loc[df_split.index, channel] - df.loc[df_split.index, 'Trend'] df.loc[df_split.index, 'Trend_aggr'] = 1 - np.var(Yt) / np.var(Zt) df.loc[df_split.index, 'Seasonal_aggr'] = 1 - np.var(Yt) / np.var(Xt) # FOURIER TERMS AS PERIODICITY df.loc[df_split.index, 'Fourier_aggr'] = df.loc[df_split.index, 'Fourier'].mean() # KURTOSIS & SKEWNESS df.loc[df_split.index, 'Kurtosis'] = kurtosis(df_split[channel]) df.loc[df_split.index, 'Skewness'] = skew(df_split[channel]) # SERIAL CORRELATION --- USING LJONBOX TEST res = sm.tsa.SARIMAX(df.loc[df_split.index, channel], order=(1,0,1), random_seed=random_seed).fit(disp=-1) df.loc[df_split.index, 'Serial_correlation'] = sm.stats.acorr_ljungbox(res.resid, boxpierce=True, lags=1)[3][0] # NON-LINEARITY --- USING BDS TEST df.loc[df_split.index, 'NON_LINEARITY'] = sm.tsa.stattools.bds(df.loc[df_split.index, channel])[0] # SELF-SIMILARITY --- USING HURST EXPONENT df.loc[df_split.index, 'Self_similarity'] = nolds.hurst_rs(df.loc[df_split.index, channel]) # CHAOS --- USING LYAPUNOV EXPONENT df.loc[df_split.index, 'Chaos'] = nolds.lyap_r(df.loc[df_split.index, channel], emb_dim=1, min_neighbors=1, trajectory_len=2) df_cluster = df[-365:].reset_index(drop=True).merge(df.iloc[-365*2:-365, 8:].reset_index(drop=True), left_index=True, right_index=True, how='left', suffixes=('', '_YEAR2')) df_cluster = df_cluster.merge(df.iloc[-365*3:-365*2, 8:].reset_index(drop=True), left_index=True, right_index=True, how='left', suffixes=('', '_YEAR3')) df_cluster = df_cluster.drop(columns=['date', channel, 'Trend', 'Seasonal_weekly', 'Fourier']).groupby('Week').mean().reset_index() df_cluster.iloc[:, 1:] = MinMaxScaler().fit_transform(df_cluster.iloc[:, 1:]) def SOM_evaluate(som1, som2, sigma, learning_rate): som_shape = (int(som1), int(som2)) som = MiniSom(som_shape[0], som_shape[1], df_cluster.iloc[:, 1:].values.shape[1], sigma=sigma, learning_rate=learning_rate, neighborhood_function='gaussian', random_seed=random_seed) som.train_batch(df_cluster.iloc[:, 1:].values, 10000, verbose=False) return -som.quantization_error(df_cluster.iloc[:, 1:].values) SOM_BO = BayesianOptimization(SOM_evaluate, {'sigma': (1, 0.01), 'som1': (1, 10), 'som2': (5, 15), 'learning_rate': (0.1, 0.001)}, random_state=random_seed, verbose=0) SOM_BO.maximize(init_points=20, n_iter=20) som_shape = (int(SOM_BO.max['params']['som1']), int(SOM_BO.max['params']['som2'])) som = MiniSom(som_shape[0], som_shape[1], df_cluster.iloc[:, 1:].values.shape[1], sigma=SOM_BO.max['params']['sigma'], learning_rate=SOM_BO.max['params']['learning_rate'], neighborhood_function='gaussian', random_seed=random_seed) winner_coordinates = np.array([som.winner(x) for x in df_cluster.iloc[:, 1:].values]).T cluster_index = np.ravel_multi_index(winner_coordinates, som_shape) df_cluster['cluster'] = cluster_index df = df_all.merge(df_cluster[['Week', 'cluster']], on='Week', how='left') df_final = pd.concat([df[['date', 'daypart', 'target', channel]], pd.get_dummies(df['cluster'], prefix='Cluster', drop_first=True)], axis=1) df_final = df_final.rename(columns={channel: 'value'}) df_final.insert(0, column='channel', value=[channel]*len(df_final)) df_output_final = df_output_final.append(df_final, ignore_index=True) df_output_final
# FUNCTION decimal range step value def drange(start, stop, step): r = start while r < stop: yield r r += step
""" Problem 20: Factorial digit sum n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ def factorial(n): if n == 1: return 1 return factorial(n - 1) * n fact_100 = factorial(100) total = 0 for i in str(fact_100): total += int(i) print('Result =', total)
# -*- coding: utf-8 -*- """ Ian O'Rourke Created on Sun Feb 7 17:57:23 2021 Python 2 - DAT 129 - SP21 Homework Week 1 Icon Creator """ def wheeler(ten_set,this_list): '''Ensure the user inputs 10 characters.''' # Setting up while loop so the user can be prompted again if more # or less than 10 characters are provided for the input prompts in # main(). wheel = True while wheel != False: if len(ten_set) != 10: print('Try again.') ten_set = input('Enter ten.: ') else: this_list.append(ten_set) wheel = False return('Onto the next one!') def menu_displayer(ready_menu): '''Displays a list as a menu for the user for potential options.''' counter = 0 for entry in ready_menu: counter = counter + 1 print(counter,') ',entry,sep='') def icon_maker(dictionary): '''Makes an icon switches 0s to spaces and 1s to Xs.''' for key in dictionary: for item in dictionary[key]: for digit in item: if '0' in digit: item = item.replace(digit,' ') else: item = item.replace(digit,'X') print(item) def icon_negative(dictionary): '''Swaps 0s for Xs and 1s for spaces.''' for key in dictionary: for item in dictionary[key]: for digit in item: if '0' in digit: item = item.replace(digit,'X') else: item = item.replace(digit,' ') print(item) def inverter(dictionary): '''Makes the icon from the end of the given inputs.''' for key in dictionary: for item in dictionary[key]: for digit in item: if '0' in digit: item = item.replace(digit,' ') else: item = item.replace(digit,'X') print(item[::-1]) def scale_twice(dictionary): '''Scales the icon by 2x.''' for key in dictionary: for vert in range(0,2): for item in dictionary[key]: for digit in item: if '0' in digit: item = item.replace(digit,' ' * 2) else: item = item.replace(digit,'X' * 2) print(item) def scale_thrice(dictionary): '''Scales the icon by 3x.''' for key in dictionary: for vert in range(0,3): for item in dictionary[key]: for digit in item: if '0' in digit: item = item.replace(digit,' ' * 3) else: item = item.replace(digit,'X' * 3) print(item) def main(): # Greeting and instructing the user. print('''Welcome! Using just a simply entry of 0s and 1s, this program will generate a 10 x 10 image that can serve as an icon for you. Simply type a sequence using 0 and 1 (if anything else is typed, it will count as a 1) for each row until all 10 are complete! Let's begin!''') # Establishing keys and values for primary dictionary. first_row = 'Row 1' second_row = 'Row 2' third_row = 'Row 3' fourth_row = 'Row 4' fifth_row = 'Row 5' sixth_row = 'Row 6' seventh_row = 'Row 7' eighth_row = 'Row 8' ninth_row = 'Row 9' tenth_row = 'Row 10' first_ten = [] second_ten = [] third_ten = [] fourth_ten = [] fifth_ten = [] sixth_ten = [] seventh_ten = [] eighth_ten = [] ninth_ten = [] tenth_ten = [] icon_dict = { first_row : first_ten, second_row : second_ten, third_row : third_ten, fourth_row: fourth_ten, fifth_row : fifth_ten, sixth_row : sixth_ten, seventh_row : seventh_ten, eighth_row : eighth_ten, ninth_row : ninth_ten, tenth_row : tenth_ten } # Collecting 100 0s and 1s from the user. Divided into 10 input # commands to help make it convenient for the user to enter all 100. first_input = input('Let\'s start with the first row of 10.: ') wheeler(first_input,first_ten) second_input = input('Now let\'s do the second.: ') wheeler(second_input,second_ten) third_input = input('And the now the third: ') wheeler(third_input,third_ten) fourth_input = input('And the fourth.: ') wheeler(fourth_input,fourth_ten) fifth_input = input('Now the fifth.: ') wheeler(fifth_input,fifth_ten) sixth_input = input('And the sixth.: ') wheeler(sixth_input,sixth_ten) seventh_input = input('The seventh: ') wheeler(seventh_input,seventh_ten) eighth_input = input('The eighth.: ') wheeler(eighth_input,eighth_ten) ninth_input = input('Now the ninth.: ') wheeler(ninth_input,ninth_ten) tenth_input = input('And now the final ten.: ') wheeler(tenth_input,tenth_ten) # Letting the user know that the input is complete. print('\nLet\'s see what we\'ve got!') print('') # Showing the results. icon_maker(icon_dict) # Setting up the menu for the user to make transformations. menu_list = ['See Original','Reverse','Invert','Scale x 2','Scale x 3','End Program'] print('\nAre they any transformations you would like to use?') print('') # Getting the menu to run. option_wheel = True while option_wheel != False: # Displaying the menu. menu_displayer(menu_list) option_input = input('\nPlease select an option. ') # Option for viewing the original creation. if option_input == '1': print('\nHere\'s the original icon.') icon_maker(icon_dict) print('\nAny other transformations you would like to see?') print('') # Option for viewing the icon reversed like a negative. elif option_input == '2': print('\nLet\'s how this looks reversed!') icon_negative(icon_dict) print('\nAny other transformations you would like to see?') print('') # Option for viewing the icon inverted. elif option_input == '3': print('\nLet\'s see how this looks inverted!') inverter(icon_dict) print('\nAny other transformations you would like to see?') print('') # Option for viewing the icon scaled x 2. elif option_input == '4': print('\nNow let\'s see how this looks scaled at 2x!') scale_twice(icon_dict) print('\nAny other transformations you would like to see?') print('') # Option for viewing the icon scaled x 3. elif option_input == '5': print('\nNow let\'s see how this looks scaled at 3x!') scale_thrice(icon_dict) print('\nAny other transformations you would like to see?') print('') # Ends the program. elif option_input == '6': print('\nAll right! Thanks for using this program!') option_wheel = False # For all other options that are not 1-6. else: print('\nNot a valid option. Try again.') print('') if __name__ == "__main__": main()
del_items(0x8012EA14) SetType(0x8012EA14, "void PreGameOnlyTestRoutine__Fv()") del_items(0x80130AEC) SetType(0x80130AEC, "void DRLG_PlaceDoor__Fii(int x, int y)") del_items(0x80130FC0) SetType(0x80130FC0, "void DRLG_L1Shadows__Fv()") del_items(0x801313D8) SetType(0x801313D8, "int DRLG_PlaceMiniSet__FPCUciiiiiii(unsigned char *miniset, int tmin, int tmax, int cx, int cy, int setview, int noquad, int ldir)") del_items(0x80131844) SetType(0x80131844, "void DRLG_L1Floor__Fv()") del_items(0x80131930) SetType(0x80131930, "void StoreBlock__FPiii(int *Bl, int xx, int yy)") del_items(0x801319DC) SetType(0x801319DC, "void DRLG_L1Pass3__Fv()") del_items(0x80131C08) SetType(0x80131C08, "void DRLG_LoadL1SP__Fv()") del_items(0x80131CE4) SetType(0x80131CE4, "void DRLG_FreeL1SP__Fv()") del_items(0x80131D14) SetType(0x80131D14, "void DRLG_Init_Globals__Fv()") del_items(0x80131DB8) SetType(0x80131DB8, "void set_restore_lighting__Fv()") del_items(0x80131E48) SetType(0x80131E48, "void DRLG_InitL1Vals__Fv()") del_items(0x80131E50) SetType(0x80131E50, "void LoadL1Dungeon__FPcii(char *sFileName, int vx, int vy)") del_items(0x8013201C) SetType(0x8013201C, "void LoadPreL1Dungeon__FPcii(char *sFileName, int vx, int vy)") del_items(0x801321D4) SetType(0x801321D4, "void InitL5Dungeon__Fv()") del_items(0x80132234) SetType(0x80132234, "void L5ClearFlags__Fv()") del_items(0x80132280) SetType(0x80132280, "void L5drawRoom__Fiiii(int x, int y, int w, int h)") del_items(0x801322EC) SetType(0x801322EC, "unsigned char L5checkRoom__Fiiii(int x, int y, int width, int height)") del_items(0x80132380) SetType(0x80132380, "void L5roomGen__Fiiiii(int x, int y, int w, int h, int dir)") del_items(0x8013267C) SetType(0x8013267C, "void L5firstRoom__Fv()") del_items(0x80132A38) SetType(0x80132A38, "long L5GetArea__Fv()") del_items(0x80132A98) SetType(0x80132A98, "void L5makeDungeon__Fv()") del_items(0x80132B24) SetType(0x80132B24, "void L5makeDmt__Fv()") del_items(0x80132C0C) SetType(0x80132C0C, "int L5HWallOk__Fii(int i, int j)") del_items(0x80132D48) SetType(0x80132D48, "int L5VWallOk__Fii(int i, int j)") del_items(0x80132E94) SetType(0x80132E94, "void L5HorizWall__Fiici(int i, int j, char p, int dx)") del_items(0x801330D4) SetType(0x801330D4, "void L5VertWall__Fiici(int i, int j, char p, int dy)") del_items(0x80133308) SetType(0x80133308, "void L5AddWall__Fv()") del_items(0x80133578) SetType(0x80133578, "void DRLG_L5GChamber__Fiiiiii(int sx, int sy, int topflag, int bottomflag, int leftflag, int rightflag)") del_items(0x80133838) SetType(0x80133838, "void DRLG_L5GHall__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x801338EC) SetType(0x801338EC, "void L5tileFix__Fv()") del_items(0x801341B0) SetType(0x801341B0, "void DRLG_L5Subs__Fv()") del_items(0x801343A8) SetType(0x801343A8, "void DRLG_L5SetRoom__Fii(int rx1, int ry1)") del_items(0x801344A8) SetType(0x801344A8, "void L5FillChambers__Fv()") del_items(0x80134B94) SetType(0x80134B94, "void DRLG_L5FTVR__Fiiiii(int i, int j, int x, int y, int d)") del_items(0x801350E4) SetType(0x801350E4, "void DRLG_L5FloodTVal__Fv()") del_items(0x801351E8) SetType(0x801351E8, "void DRLG_L5TransFix__Fv()") del_items(0x801353F8) SetType(0x801353F8, "void DRLG_L5DirtFix__Fv()") del_items(0x80135554) SetType(0x80135554, "void DRLG_L5CornerFix__Fv()") del_items(0x80135664) SetType(0x80135664, "void DRLG_L5__Fi(int entry)") del_items(0x80135B84) SetType(0x80135B84, "void CreateL5Dungeon__FUii(unsigned int rseed, int entry)") del_items(0x80138128) SetType(0x80138128, "unsigned char DRLG_L2PlaceMiniSet__FPUciiiiii(unsigned char *miniset, int tmin, int tmax, int cx, int cy, int setview, int ldir)") del_items(0x8013851C) SetType(0x8013851C, "void DRLG_L2PlaceRndSet__FPUci(unsigned char *miniset, int rndper)") del_items(0x8013881C) SetType(0x8013881C, "void DRLG_L2Subs__Fv()") del_items(0x80138A10) SetType(0x80138A10, "void DRLG_L2Shadows__Fv()") del_items(0x80138BD4) SetType(0x80138BD4, "void InitDungeon__Fv()") del_items(0x80138C34) SetType(0x80138C34, "void DRLG_LoadL2SP__Fv()") del_items(0x80138CD4) SetType(0x80138CD4, "void DRLG_FreeL2SP__Fv()") del_items(0x80138D04) SetType(0x80138D04, "void DRLG_L2SetRoom__Fii(int rx1, int ry1)") del_items(0x80138E04) SetType(0x80138E04, "void DefineRoom__Fiiiii(int nX1, int nY1, int nX2, int nY2, int ForceHW)") del_items(0x80139010) SetType(0x80139010, "void CreateDoorType__Fii(int nX, int nY)") del_items(0x801390F4) SetType(0x801390F4, "void PlaceHallExt__Fii(int nX, int nY)") del_items(0x8013912C) SetType(0x8013912C, "void AddHall__Fiiiii(int nX1, int nY1, int nX2, int nY2, int nHd)") del_items(0x80139204) SetType(0x80139204, "void CreateRoom__Fiiiiiiiii(int nX1, int nY1, int nX2, int nY2, int nRDest, int nHDir, int ForceHW, int nH, int nW)") del_items(0x8013988C) SetType(0x8013988C, "void GetHall__FPiN40(int *nX1, int *nY1, int *nX2, int *nY2, int *nHd)") del_items(0x80139924) SetType(0x80139924, "void ConnectHall__Fiiiii(int nX1, int nY1, int nX2, int nY2, int nHd)") del_items(0x80139F8C) SetType(0x80139F8C, "void DoPatternCheck__Fii(int i, int j)") del_items(0x8013A240) SetType(0x8013A240, "void L2TileFix__Fv()") del_items(0x8013A364) SetType(0x8013A364, "unsigned char DL2_Cont__FUcUcUcUc(unsigned char x1f, unsigned char y1f, unsigned char x2f, unsigned char y2f)") del_items(0x8013A3E4) SetType(0x8013A3E4, "int DL2_NumNoChar__Fv()") del_items(0x8013A440) SetType(0x8013A440, "void DL2_DrawRoom__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8013A544) SetType(0x8013A544, "void DL2_KnockWalls__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8013A714) SetType(0x8013A714, "unsigned char DL2_FillVoids__Fv()") del_items(0x8013B098) SetType(0x8013B098, "unsigned char CreateDungeon__Fv()") del_items(0x8013B3A4) SetType(0x8013B3A4, "void DRLG_L2Pass3__Fv()") del_items(0x8013B53C) SetType(0x8013B53C, "void DRLG_L2FTVR__Fiiiii(int i, int j, int x, int y, int d)") del_items(0x8013BA84) SetType(0x8013BA84, "void DRLG_L2FloodTVal__Fv()") del_items(0x8013BB88) SetType(0x8013BB88, "void DRLG_L2TransFix__Fv()") del_items(0x8013BD98) SetType(0x8013BD98, "void L2DirtFix__Fv()") del_items(0x8013BEF8) SetType(0x8013BEF8, "void L2LockoutFix__Fv()") del_items(0x8013C284) SetType(0x8013C284, "void L2DoorFix__Fv()") del_items(0x8013C334) SetType(0x8013C334, "void DRLG_L2__Fi(int entry)") del_items(0x8013CD80) SetType(0x8013CD80, "void DRLG_InitL2Vals__Fv()") del_items(0x8013CD88) SetType(0x8013CD88, "void LoadL2Dungeon__FPcii(char *sFileName, int vx, int vy)") del_items(0x8013CF78) SetType(0x8013CF78, "void LoadPreL2Dungeon__FPcii(char *sFileName, int vx, int vy)") del_items(0x8013D164) SetType(0x8013D164, "void CreateL2Dungeon__FUii(unsigned int rseed, int entry)") del_items(0x8013DB1C) SetType(0x8013DB1C, "void InitL3Dungeon__Fv()") del_items(0x8013DBA4) SetType(0x8013DBA4, "int DRLG_L3FillRoom__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8013DE00) SetType(0x8013DE00, "void DRLG_L3CreateBlock__Fiiii(int x, int y, int obs, int dir)") del_items(0x8013E09C) SetType(0x8013E09C, "void DRLG_L3FloorArea__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8013E104) SetType(0x8013E104, "void DRLG_L3FillDiags__Fv()") del_items(0x8013E234) SetType(0x8013E234, "void DRLG_L3FillSingles__Fv()") del_items(0x8013E300) SetType(0x8013E300, "void DRLG_L3FillStraights__Fv()") del_items(0x8013E6C4) SetType(0x8013E6C4, "void DRLG_L3Edges__Fv()") del_items(0x8013E704) SetType(0x8013E704, "int DRLG_L3GetFloorArea__Fv()") del_items(0x8013E754) SetType(0x8013E754, "void DRLG_L3MakeMegas__Fv()") del_items(0x8013E898) SetType(0x8013E898, "void DRLG_L3River__Fv()") del_items(0x8013F2D8) SetType(0x8013F2D8, "int DRLG_L3SpawnEdge__FiiPi(int x, int y, int *totarea)") del_items(0x8013F564) SetType(0x8013F564, "int DRLG_L3Spawn__FiiPi(int x, int y, int *totarea)") del_items(0x8013F778) SetType(0x8013F778, "void DRLG_L3Pool__Fv()") del_items(0x8013F9CC) SetType(0x8013F9CC, "void DRLG_L3PoolFix__Fv()") del_items(0x8013FB00) SetType(0x8013FB00, "int DRLG_L3PlaceMiniSet__FPCUciiiiii(unsigned char *miniset, int tmin, int tmax, int cx, int cy, int setview, int ldir)") del_items(0x8013FE80) SetType(0x8013FE80, "void DRLG_L3PlaceRndSet__FPCUci(unsigned char *miniset, int rndper)") del_items(0x801401C8) SetType(0x801401C8, "unsigned char WoodVertU__Fii(int i, int y)") del_items(0x80140274) SetType(0x80140274, "unsigned char WoodVertD__Fii(int i, int y)") del_items(0x80140310) SetType(0x80140310, "unsigned char WoodHorizL__Fii(int x, int j)") del_items(0x801403A4) SetType(0x801403A4, "unsigned char WoodHorizR__Fii(int x, int j)") del_items(0x80140428) SetType(0x80140428, "void AddFenceDoors__Fv()") del_items(0x8014050C) SetType(0x8014050C, "void FenceDoorFix__Fv()") del_items(0x80140700) SetType(0x80140700, "void DRLG_L3Wood__Fv()") del_items(0x80140EF0) SetType(0x80140EF0, "int DRLG_L3Anvil__Fv()") del_items(0x8014114C) SetType(0x8014114C, "void FixL3Warp__Fv()") del_items(0x80141234) SetType(0x80141234, "void FixL3HallofHeroes__Fv()") del_items(0x80141388) SetType(0x80141388, "void DRLG_L3LockRec__Fii(int x, int y)") del_items(0x80141424) SetType(0x80141424, "unsigned char DRLG_L3Lockout__Fv()") del_items(0x801414E4) SetType(0x801414E4, "void DRLG_L3__Fi(int entry)") del_items(0x80141C04) SetType(0x80141C04, "void DRLG_L3Pass3__Fv()") del_items(0x80141DA8) SetType(0x80141DA8, "void CreateL3Dungeon__FUii(unsigned int rseed, int entry)") del_items(0x80141EBC) SetType(0x80141EBC, "void LoadL3Dungeon__FPcii(char *sFileName, int vx, int vy)") del_items(0x801420E0) SetType(0x801420E0, "void LoadPreL3Dungeon__FPcii(char *sFileName, int vx, int vy)") del_items(0x80143F40) SetType(0x80143F40, "void DRLG_L4Shadows__Fv()") del_items(0x80144004) SetType(0x80144004, "void InitL4Dungeon__Fv()") del_items(0x801440A0) SetType(0x801440A0, "void DRLG_LoadL4SP__Fv()") del_items(0x80144168) SetType(0x80144168, "void DRLG_FreeL4SP__Fv()") del_items(0x80144190) SetType(0x80144190, "void DRLG_L4SetSPRoom__Fii(int rx1, int ry1)") del_items(0x80144290) SetType(0x80144290, "void L4makeDmt__Fv()") del_items(0x80144334) SetType(0x80144334, "int L4HWallOk__Fii(int i, int j)") del_items(0x80144484) SetType(0x80144484, "int L4VWallOk__Fii(int i, int j)") del_items(0x80144600) SetType(0x80144600, "void L4HorizWall__Fiii(int i, int j, int dx)") del_items(0x801447D0) SetType(0x801447D0, "void L4VertWall__Fiii(int i, int j, int dy)") del_items(0x80144998) SetType(0x80144998, "void L4AddWall__Fv()") del_items(0x80144E78) SetType(0x80144E78, "void L4tileFix__Fv()") del_items(0x80147060) SetType(0x80147060, "void DRLG_L4Subs__Fv()") del_items(0x80147238) SetType(0x80147238, "void L4makeDungeon__Fv()") del_items(0x80147470) SetType(0x80147470, "void uShape__Fv()") del_items(0x80147714) SetType(0x80147714, "long GetArea__Fv()") del_items(0x80147770) SetType(0x80147770, "void L4drawRoom__Fiiii(int x, int y, int width, int height)") del_items(0x801477D8) SetType(0x801477D8, "unsigned char L4checkRoom__Fiiii(int x, int y, int width, int height)") del_items(0x80147874) SetType(0x80147874, "void L4roomGen__Fiiiii(int x, int y, int w, int h, int dir)") del_items(0x80147B70) SetType(0x80147B70, "void L4firstRoom__Fv()") del_items(0x80147DBC) SetType(0x80147DBC, "void L4SaveQuads__Fv()") del_items(0x80147E5C) SetType(0x80147E5C, "void DRLG_L4SetRoom__FPUcii(unsigned char *pSetPiece, int rx1, int ry1)") del_items(0x80147F30) SetType(0x80147F30, "void DRLG_LoadDiabQuads__FUc(unsigned char preflag)") del_items(0x80148094) SetType(0x80148094, "unsigned char DRLG_L4PlaceMiniSet__FPCUciiiiii(unsigned char *miniset, int tmin, int tmax, int cx, int cy, int setview, int ldir)") del_items(0x801484AC) SetType(0x801484AC, "void DRLG_L4FTVR__Fiiiii(int i, int j, int x, int y, int d)") del_items(0x801489F4) SetType(0x801489F4, "void DRLG_L4FloodTVal__Fv()") del_items(0x80148AF8) SetType(0x80148AF8, "unsigned char IsDURWall__Fc(char d)") del_items(0x80148B28) SetType(0x80148B28, "unsigned char IsDLLWall__Fc(char dd)") del_items(0x80148B58) SetType(0x80148B58, "void DRLG_L4TransFix__Fv()") del_items(0x80148EB0) SetType(0x80148EB0, "void DRLG_L4Corners__Fv()") del_items(0x80148F44) SetType(0x80148F44, "void L4FixRim__Fv()") del_items(0x80148F80) SetType(0x80148F80, "void DRLG_L4GeneralFix__Fv()") del_items(0x80149024) SetType(0x80149024, "void DRLG_L4__Fi(int entry)") del_items(0x80149920) SetType(0x80149920, "void DRLG_L4Pass3__Fv()") del_items(0x80149AC4) SetType(0x80149AC4, "void CreateL4Dungeon__FUii(unsigned int rseed, int entry)") del_items(0x80149B54) SetType(0x80149B54, "int ObjIndex__Fii(int x, int y)") del_items(0x80149C08) SetType(0x80149C08, "void AddSKingObjs__Fv()") del_items(0x80149D38) SetType(0x80149D38, "void AddSChamObjs__Fv()") del_items(0x80149DB4) SetType(0x80149DB4, "void AddVileObjs__Fv()") del_items(0x80149E60) SetType(0x80149E60, "void DRLG_SetMapTrans__FPc(char *sFileName)") del_items(0x80149F24) SetType(0x80149F24, "void LoadSetMap__Fv()") del_items(0x8014A22C) SetType(0x8014A22C, "unsigned long CM_QuestToBitPattern__Fi(int QuestNum)") del_items(0x8014A2FC) SetType(0x8014A2FC, "void CM_ShowMonsterList__Fii(int Level, int List)") del_items(0x8014A374) SetType(0x8014A374, "int CM_ChooseMonsterList__FiUl(int Level, unsigned long QuestsNeededMask)") del_items(0x8014A414) SetType(0x8014A414, "int NoUiListChoose__FiUl(int Level, unsigned long QuestsNeededMask)") del_items(0x8014A41C) SetType(0x8014A41C, "void ChooseTask__FP4TASK(struct TASK *T)") del_items(0x8014A930) SetType(0x8014A930, "void ShowTask__FP4TASK(struct TASK *T)") del_items(0x8014AB4C) SetType(0x8014AB4C, "int GetListsAvailable__FiUlPUc(int Level, unsigned long QuestsNeededMask, unsigned char *ListofLists)") del_items(0x8014AC70) SetType(0x8014AC70, "unsigned short GetDown__C4CPad(struct CPad *this)") del_items(0x8014AC98) SetType(0x8014AC98, "void AddL1Door__Fiiii(int i, int x, int y, int ot)") del_items(0x8014AE28) SetType(0x8014AE28, "void AddSCambBook__Fi(int i)") del_items(0x8014AF00) SetType(0x8014AF00, "void AddChest__Fii(int i, int t)") del_items(0x8014B100) SetType(0x8014B100, "void AddL2Door__Fiiii(int i, int x, int y, int ot)") del_items(0x8014B270) SetType(0x8014B270, "void AddL3Door__Fiiii(int i, int x, int y, int ot)") del_items(0x8014B34C) SetType(0x8014B34C, "void AddSarc__Fi(int i)") del_items(0x8014B450) SetType(0x8014B450, "void AddFlameTrap__Fi(int i)") del_items(0x8014B4E4) SetType(0x8014B4E4, "void AddTrap__Fii(int i, int ot)") del_items(0x8014B600) SetType(0x8014B600, "void AddObjLight__Fii(int i, int r)") del_items(0x8014B6DC) SetType(0x8014B6DC, "void AddBarrel__Fii(int i, int ot)") del_items(0x8014B7AC) SetType(0x8014B7AC, "void AddShrine__Fi(int i)") del_items(0x8014B918) SetType(0x8014B918, "void AddBookcase__Fi(int i)") del_items(0x8014B990) SetType(0x8014B990, "void AddBookstand__Fi(int i)") del_items(0x8014B9F8) SetType(0x8014B9F8, "void AddBloodFtn__Fi(int i)") del_items(0x8014BA60) SetType(0x8014BA60, "void AddPurifyingFountain__Fi(int i)") del_items(0x8014BB64) SetType(0x8014BB64, "void AddArmorStand__Fi(int i)") del_items(0x8014BC0C) SetType(0x8014BC0C, "void AddGoatShrine__Fi(int i)") del_items(0x8014BC74) SetType(0x8014BC74, "void AddCauldron__Fi(int i)") del_items(0x8014BCDC) SetType(0x8014BCDC, "void AddMurkyFountain__Fi(int i)") del_items(0x8014BDE0) SetType(0x8014BDE0, "void AddTearFountain__Fi(int i)") del_items(0x8014BE48) SetType(0x8014BE48, "void AddDecap__Fi(int i)") del_items(0x8014BEE0) SetType(0x8014BEE0, "void AddVilebook__Fi(int i)") del_items(0x8014BF64) SetType(0x8014BF64, "void AddMagicCircle__Fi(int i)") del_items(0x8014BFF8) SetType(0x8014BFF8, "void AddBrnCross__Fi(int i)") del_items(0x8014C060) SetType(0x8014C060, "void AddPedistal__Fi(int i)") del_items(0x8014C10C) SetType(0x8014C10C, "void AddStoryBook__Fi(int i)") del_items(0x8014C2C8) SetType(0x8014C2C8, "void AddWeaponRack__Fi(int i)") del_items(0x8014C370) SetType(0x8014C370, "void AddTorturedBody__Fi(int i)") del_items(0x8014C408) SetType(0x8014C408, "void AddFlameLvr__Fi(int i)") del_items(0x8014C480) SetType(0x8014C480, "void GetRndObjLoc__FiRiT1(int randarea, int *xx, int *yy)") del_items(0x8014C58C) SetType(0x8014C58C, "void AddMushPatch__Fv()") del_items(0x8014C6B0) SetType(0x8014C6B0, "void AddSlainHero__Fv()") del_items(0x8014C6F0) SetType(0x8014C6F0, "unsigned char RndLocOk__Fii(int xp, int yp)") del_items(0x8014C7D4) SetType(0x8014C7D4, "unsigned char TrapLocOk__Fii(int xp, int yp)") del_items(0x8014C83C) SetType(0x8014C83C, "unsigned char RoomLocOk__Fii(int xp, int yp)") del_items(0x8014C8D4) SetType(0x8014C8D4, "void InitRndLocObj__Fiii(int min, int max, int objtype)") del_items(0x8014CA80) SetType(0x8014CA80, "void InitRndLocBigObj__Fiii(int min, int max, int objtype)") del_items(0x8014CC78) SetType(0x8014CC78, "void InitRndLocObj5x5__Fiii(int min, int max, int objtype)") del_items(0x8014CDA0) SetType(0x8014CDA0, "void SetMapObjects__FPUcii(unsigned char *pMap, int startx, int starty)") del_items(0x8014D064) SetType(0x8014D064, "void ClrAllObjects__Fv()") del_items(0x8014D154) SetType(0x8014D154, "void AddTortures__Fv()") del_items(0x8014D2E0) SetType(0x8014D2E0, "void AddCandles__Fv()") del_items(0x8014D368) SetType(0x8014D368, "void AddTrapLine__Fiiii(int min, int max, int tobjtype, int lobjtype)") del_items(0x8014D704) SetType(0x8014D704, "void AddLeverObj__Fiiiiiiii(int lx1, int ly1, int lx2, int ly2, int x1, int y1, int x2, int y2)") del_items(0x8014D70C) SetType(0x8014D70C, "void AddBookLever__Fiiiiiiiii(int lx1, int ly1, int lx2, int ly2, int x1, int y1, int x2, int y2, int msg)") del_items(0x8014D980) SetType(0x8014D980, "void InitRndBarrels__Fv()") del_items(0x8014DB1C) SetType(0x8014DB1C, "void AddL1Objs__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8014DC54) SetType(0x8014DC54, "void AddL2Objs__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8014DD68) SetType(0x8014DD68, "void AddL3Objs__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8014DE68) SetType(0x8014DE68, "unsigned char TorchLocOK__Fii(int xp, int yp)") del_items(0x8014DEA8) SetType(0x8014DEA8, "void AddL2Torches__Fv()") del_items(0x8014E05C) SetType(0x8014E05C, "unsigned char WallTrapLocOk__Fii(int xp, int yp)") del_items(0x8014E0C4) SetType(0x8014E0C4, "void AddObjTraps__Fv()") del_items(0x8014E43C) SetType(0x8014E43C, "void AddChestTraps__Fv()") del_items(0x8014E58C) SetType(0x8014E58C, "void LoadMapObjects__FPUciiiiiii(unsigned char *pMap, int startx, int starty, int x1, int y1, int w, int h, int leveridx)") del_items(0x8014E6F8) SetType(0x8014E6F8, "void AddDiabObjs__Fv()") del_items(0x8014E84C) SetType(0x8014E84C, "void AddStoryBooks__Fv()") del_items(0x8014E99C) SetType(0x8014E99C, "void AddHookedBodies__Fi(int freq)") del_items(0x8014EB94) SetType(0x8014EB94, "void AddL4Goodies__Fv()") del_items(0x8014EC44) SetType(0x8014EC44, "void AddLazStand__Fv()") del_items(0x8014EDD8) SetType(0x8014EDD8, "void InitObjects__Fv()") del_items(0x8014F43C) SetType(0x8014F43C, "void PreObjObjAddSwitch__Fiiii(int ot, int ox, int oy, int oi)") del_items(0x8014F784) SetType(0x8014F784, "void FillSolidBlockTbls__Fv()") del_items(0x8014F954) SetType(0x8014F954, "void SetDungeonMicros__Fv()") del_items(0x8014F95C) SetType(0x8014F95C, "void DRLG_InitTrans__Fv()") del_items(0x8014F9D0) SetType(0x8014F9D0, "void DRLG_MRectTrans__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8014FA70) SetType(0x8014FA70, "void DRLG_RectTrans__Fiiii(int x1, int y1, int x2, int y2)") del_items(0x8014FAF0) SetType(0x8014FAF0, "void DRLG_CopyTrans__Fiiii(int sx, int sy, int dx, int dy)") del_items(0x8014FB58) SetType(0x8014FB58, "void DRLG_ListTrans__FiPUc(int num, unsigned char *List)") del_items(0x8014FBCC) SetType(0x8014FBCC, "void DRLG_AreaTrans__FiPUc(int num, unsigned char *List)") del_items(0x8014FC5C) SetType(0x8014FC5C, "void DRLG_InitSetPC__Fv()") del_items(0x8014FC74) SetType(0x8014FC74, "void DRLG_SetPC__Fv()") del_items(0x8014FD24) SetType(0x8014FD24, "void Make_SetPC__Fiiii(int x, int y, int w, int h)") del_items(0x8014FDC4) SetType(0x8014FDC4, "unsigned char DRLG_WillThemeRoomFit__FiiiiiPiT5(int floor, int x, int y, int minSize, int maxSize, int *width, int *height)") del_items(0x8015008C) SetType(0x8015008C, "void DRLG_CreateThemeRoom__Fi(int themeIndex)") del_items(0x80151094) SetType(0x80151094, "void DRLG_PlaceThemeRooms__FiiiiUc(int minSize, int maxSize, int floor, int freq, int rndSize)") del_items(0x8015133C) SetType(0x8015133C, "void DRLG_HoldThemeRooms__Fv()") del_items(0x801514F0) SetType(0x801514F0, "unsigned char SkipThemeRoom__Fii(int x, int y)") del_items(0x801515BC) SetType(0x801515BC, "void InitLevels__Fv()") del_items(0x801516C0) SetType(0x801516C0, "unsigned char TFit_Shrine__Fi(int i)") del_items(0x80151968) SetType(0x80151968, "unsigned char TFit_Obj5__Fi(int t)") del_items(0x80151B58) SetType(0x80151B58, "unsigned char TFit_SkelRoom__Fi(int t)") del_items(0x80151C08) SetType(0x80151C08, "unsigned char TFit_GoatShrine__Fi(int t)") del_items(0x80151CA0) SetType(0x80151CA0, "unsigned char CheckThemeObj3__Fiiii(int xp, int yp, int t, int f)") del_items(0x80151E0C) SetType(0x80151E0C, "unsigned char TFit_Obj3__Fi(int t)") del_items(0x80151ECC) SetType(0x80151ECC, "unsigned char CheckThemeReqs__Fi(int t)") del_items(0x80151F98) SetType(0x80151F98, "unsigned char SpecialThemeFit__Fii(int i, int t)") del_items(0x80152174) SetType(0x80152174, "unsigned char CheckThemeRoom__Fi(int tv)") del_items(0x80152420) SetType(0x80152420, "void InitThemes__Fv()") del_items(0x80152794) SetType(0x80152794, "void HoldThemeRooms__Fv()") del_items(0x801528A0) SetType(0x801528A0, "void PlaceThemeMonsts__Fii(int t, int f)") del_items(0x80152A6C) SetType(0x80152A6C, "void Theme_Barrel__Fi(int t)") del_items(0x80152C04) SetType(0x80152C04, "void Theme_Shrine__Fi(int t)") del_items(0x80152CEC) SetType(0x80152CEC, "void Theme_MonstPit__Fi(int t)") del_items(0x80152E38) SetType(0x80152E38, "void Theme_SkelRoom__Fi(int t)") del_items(0x8015313C) SetType(0x8015313C, "void Theme_Treasure__Fi(int t)") del_items(0x801533BC) SetType(0x801533BC, "void Theme_Library__Fi(int t)") del_items(0x8015362C) SetType(0x8015362C, "void Theme_Torture__Fi(int t)") del_items(0x801537BC) SetType(0x801537BC, "void Theme_BloodFountain__Fi(int t)") del_items(0x80153830) SetType(0x80153830, "void Theme_Decap__Fi(int t)") del_items(0x801539C0) SetType(0x801539C0, "void Theme_PurifyingFountain__Fi(int t)") del_items(0x80153A34) SetType(0x80153A34, "void Theme_ArmorStand__Fi(int t)") del_items(0x80153BEC) SetType(0x80153BEC, "void Theme_GoatShrine__Fi(int t)") del_items(0x80153D5C) SetType(0x80153D5C, "void Theme_Cauldron__Fi(int t)") del_items(0x80153DD0) SetType(0x80153DD0, "void Theme_MurkyFountain__Fi(int t)") del_items(0x80153E44) SetType(0x80153E44, "void Theme_TearFountain__Fi(int t)") del_items(0x80153EB8) SetType(0x80153EB8, "void Theme_BrnCross__Fi(int t)") del_items(0x80154050) SetType(0x80154050, "void Theme_WeaponRack__Fi(int t)") del_items(0x80154208) SetType(0x80154208, "void UpdateL4Trans__Fv()") del_items(0x80154268) SetType(0x80154268, "void CreateThemeRooms__Fv()") del_items(0x80154470) SetType(0x80154470, "void InitPortals__Fv()") del_items(0x801544D0) SetType(0x801544D0, "void InitQuests__Fv()") del_items(0x801548D4) SetType(0x801548D4, "void DrawButcher__Fv()") del_items(0x80154918) SetType(0x80154918, "void DrawSkelKing__Fiii(int q, int x, int y)") del_items(0x801549A4) SetType(0x801549A4, "void DrawWarLord__Fii(int x, int y)") del_items(0x80154B10) SetType(0x80154B10, "void DrawSChamber__Fiii(int q, int x, int y)") del_items(0x80154CE0) SetType(0x80154CE0, "void DrawLTBanner__Fii(int x, int y)") del_items(0x80154E24) SetType(0x80154E24, "void DrawBlind__Fii(int x, int y)") del_items(0x80154F68) SetType(0x80154F68, "void DrawBlood__Fii(int x, int y)") del_items(0x801550B0) SetType(0x801550B0, "void DRLG_CheckQuests__Fii(int x, int y)") del_items(0x801551EC) SetType(0x801551EC, "void InitInv__Fv()") del_items(0x8015524C) SetType(0x8015524C, "void InitAutomap__Fv()") del_items(0x80155410) SetType(0x80155410, "void InitAutomapOnce__Fv()") del_items(0x80155420) SetType(0x80155420, "unsigned char MonstPlace__Fii(int xp, int yp)") del_items(0x801554DC) SetType(0x801554DC, "void InitMonsterGFX__Fi(int monst)") del_items(0x801555E4) SetType(0x801555E4, "void PlaceMonster__Fiiii(int i, int mtype, int x, int y)") del_items(0x80155684) SetType(0x80155684, "int AddMonsterType__Fii(int type, int placeflag)") del_items(0x801557B8) SetType(0x801557B8, "void GetMonsterTypes__FUl(unsigned long QuestMask)") del_items(0x80155868) SetType(0x80155868, "void ClrAllMonsters__Fv()") del_items(0x801559A8) SetType(0x801559A8, "void InitLevelMonsters__Fv()") del_items(0x80155A2C) SetType(0x80155A2C, "void GetLevelMTypes__Fv()") del_items(0x80155E74) SetType(0x80155E74, "void PlaceQuestMonsters__Fv()") del_items(0x8015628C) SetType(0x8015628C, "void LoadDiabMonsts__Fv()") del_items(0x8015639C) SetType(0x8015639C, "void PlaceGroup__FiiUci(int mtype, int num, unsigned char leaderf, int leader)") del_items(0x801569AC) SetType(0x801569AC, "void SetMapMonsters__FPUcii(unsigned char *pMap, int startx, int starty)") del_items(0x80156BD0) SetType(0x80156BD0, "void InitMonsters__Fv()") del_items(0x80156FAC) SetType(0x80156FAC, "void PlaceUniqueMonst__Fiii(int uniqindex, int miniontype, int unpackfilesize)") del_items(0x801577CC) SetType(0x801577CC, "void PlaceUniques__Fv()") del_items(0x80157990) SetType(0x80157990, "int PreSpawnSkeleton__Fv()") del_items(0x80157AF8) SetType(0x80157AF8, "int encode_enemy__Fi(int m)") del_items(0x80157B50) SetType(0x80157B50, "void decode_enemy__Fii(int m, int enemy)") del_items(0x80157C68) SetType(0x80157C68, "unsigned char IsGoat__Fi(int mt)") del_items(0x80157C94) SetType(0x80157C94, "void InitMissiles__Fv()") del_items(0x80157EB0) SetType(0x80157EB0, "void InitNoTriggers__Fv()") del_items(0x80157ED4) SetType(0x80157ED4, "void InitTownTriggers__Fv()") del_items(0x80158234) SetType(0x80158234, "void InitL1Triggers__Fv()") del_items(0x80158348) SetType(0x80158348, "void InitL2Triggers__Fv()") del_items(0x801584D8) SetType(0x801584D8, "void InitL3Triggers__Fv()") del_items(0x80158634) SetType(0x80158634, "void InitL4Triggers__Fv()") del_items(0x80158848) SetType(0x80158848, "void InitSKingTriggers__Fv()") del_items(0x80158894) SetType(0x80158894, "void InitSChambTriggers__Fv()") del_items(0x801588E0) SetType(0x801588E0, "void InitPWaterTriggers__Fv()") del_items(0x8015892C) SetType(0x8015892C, "void InitVPTriggers__Fv()") del_items(0x80158978) SetType(0x80158978, "void InitStores__Fv()") del_items(0x801589F8) SetType(0x801589F8, "void SetupTownStores__Fv()") del_items(0x80158BA8) SetType(0x80158BA8, "void DeltaLoadLevel__Fv()") del_items(0x80159828) SetType(0x80159828, "unsigned char SmithItemOk__Fi(int i)") del_items(0x8015988C) SetType(0x8015988C, "int RndSmithItem__Fi(int lvl)") del_items(0x80159998) SetType(0x80159998, "unsigned char WitchItemOk__Fi(int i)") del_items(0x80159AD8) SetType(0x80159AD8, "int RndWitchItem__Fi(int lvl)") del_items(0x80159BD8) SetType(0x80159BD8, "void BubbleSwapItem__FP10ItemStructT0(struct ItemStruct *a, struct ItemStruct *b)") del_items(0x80159CBC) SetType(0x80159CBC, "void SortWitch__Fv()") del_items(0x80159DDC) SetType(0x80159DDC, "int RndBoyItem__Fi(int lvl)") del_items(0x80159F00) SetType(0x80159F00, "unsigned char HealerItemOk__Fi(int i)") del_items(0x8015A0B4) SetType(0x8015A0B4, "int RndHealerItem__Fi(int lvl)") del_items(0x8015A1B4) SetType(0x8015A1B4, "void RecreatePremiumItem__Fiiii(int ii, int idx, int plvl, int iseed)") del_items(0x8015A27C) SetType(0x8015A27C, "void RecreateWitchItem__Fiiii(int ii, int idx, int lvl, int iseed)") del_items(0x8015A3D4) SetType(0x8015A3D4, "void RecreateSmithItem__Fiiii(int ii, int idx, int lvl, int iseed)") del_items(0x8015A470) SetType(0x8015A470, "void RecreateHealerItem__Fiiii(int ii, int idx, int lvl, int iseed)") del_items(0x8015A530) SetType(0x8015A530, "void RecreateBoyItem__Fiiii(int ii, int idx, int lvl, int iseed)") del_items(0x8015A5F4) SetType(0x8015A5F4, "void RecreateTownItem__FiiUsii(int ii, int idx, unsigned short icreateinfo, int iseed, int ivalue)") del_items(0x8015A680) SetType(0x8015A680, "void SpawnSmith__Fi(int lvl)") del_items(0x8015A81C) SetType(0x8015A81C, "void SpawnWitch__Fi(int lvl)") del_items(0x8015AB88) SetType(0x8015AB88, "void SpawnHealer__Fi(int lvl)") del_items(0x8015AEA4) SetType(0x8015AEA4, "void SpawnBoy__Fi(int lvl)") del_items(0x8015AFF8) SetType(0x8015AFF8, "void SortSmith__Fv()") del_items(0x8015B10C) SetType(0x8015B10C, "void SortHealer__Fv()") del_items(0x8015B22C) SetType(0x8015B22C, "void RecreateItem__FiiUsii(int ii, int idx, unsigned short icreateinfo, int iseed, int ivalue)")
# -*- coding: utf-8 -*- description = "Gauss meter setup" group = "optional" tango_base = "tango://phys.maria.frm2:10000/maria" devices = dict( field = device("nicos.devices.entangle.AnalogInput", description = "Lakeshore LS455, DSP Gauss Meter", tangodevice = tango_base + "/ls455/field", ), )
"""Main module.""" class TemplateCollection: def __init__(self, list_of_templates): self.list_of_templates = list_of_templates def write(self, filename, header=None): with open(filename, 'w') as fi: if header: fi.write(header+"\n\n\n") for ntemp, t in enumerate(self.list_of_templates): if len(t.filled_template) == 0: print(f"warning: template {ntemp} is not filled") for ln in t.filled_template: fi.write(ln) def fill_line(ln, replace_dict): for key, val in replace_dict.items(): ln = ln.replace(key, val) return ln class Template: def __init__(self, replace_dict=None): self.line_list, self.replaceable_strings = self.empty_template() self.filled_template = [] if replace_dict: self.fill_template(replace_dict) def _validate_replace_dict(self, replace_dict: dict): for k, v in replace_dict.items(): if k not in self.replaceable_strings: raise ValueError(f"{k} is not a valid template string, please check replaceable_strings") if type(v) is not str: raise ValueError(f"{k} value must be a string") def fill_template(self, replace_dict: dict): self._validate_replace_dict(replace_dict) for ln in self.line_list: f_ln = fill_line(ln, replace_dict) self.filled_template.append(f_ln) def empty_template(self): # needs to returna the template as a list of strings and a list of strings # that are allowed to be replaced raise NotImplementedError
""" Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime? Hint: A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful. Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. """ class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ while num>9: c=0 while num: c+=num%10 num//=10 num=c return num
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ n = ListNode(l1.val + l2.val) head = n n1 = l1.next n2 = l2.next while n1 is not None or n2 is not None: if n1 is None: new_n = ListNode(n2.val) elif n2 is None: new_n = ListNode(n1.val) else: new_n = ListNode(n1.val + n2.val) n.next = new_n n = new_n if n1 is not None: n1 = n1.next if n2 is not None: n2 = n2.next # Processing carry bits n = head while n is not None: if n.val >= 10: n.val -= 10 if n.next is not None: n.next.val += 1 else: n.next = ListNode(1) break n = n.next return head
#x+x^2/2!+x^3/3!+x^4/4!...... x=int(input("Enter a number ")) n=int(input("Enter number of terms in the series ")) sum=0 fact=1 for y in range(1,n+1): fact=fact*y sum=sum+pow(x,y)/fact print(sum)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDiffInBST(self, root: TreeNode) -> int: def inorder(node): if node: inorder(node.left) vals.append(node.val) inorder(node.right) vals = [] inorder(root) return min(b - a for a, b in zip(vals, vals[1:]))
# -*- coding: utf-8 -*- ''' torstack.config.builder config builder definition. :copyright: (c) 2018 by longniao <longniao@gmail.com> :license: MIT, see LICENSE for more details. '''
class StaticPoliceBaseError(Exception): pass class StaticPoliceBaseNotice(Exception): pass # # Generic errors # class FunctionNotFoundError(StaticPoliceBaseError): pass class StaticPoliceTypeError(StaticPoliceBaseError): pass class StaticPoliceKeyNotFoundError(StaticPoliceBaseError): pass # # Policy notices # class PolicySkipFunctionNotice(StaticPoliceBaseNotice): pass
class Config(object): '''parent configuration file''' DEBUG = True SECRET_KEY = 'hardtoguess' ENV = 'development' TESTING = False class DevelopmentConfig(Config): DEBUG = True url = "dbname = 'stackoverflow_db' user = 'postgres' host = 'localhost' port = '5432' password = 'admin'" class TestingConfig(Config): DEBUG = True TESTING = True url = "dbname = 'test_db' user = 'postgres' host = 'localhost' port = '5432' password = 'admin'" class StaginConfig(Config): DEBUG = True class ProductionConfig(Config): DEBUG = False TESTING = False app_config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'staging': StaginConfig, 'production': ProductionConfig } db_url = DevelopmentConfig.url test_url = TestingConfig.url secret_key = Config.SECRET_KEY
km = float(input("Digite a quantidade de km rodados: ")); dias = int(input("Digite a quantidade de dias em que carro foi alugado:")); valor = ((0.15 * km) + (60 * dias)); print(f"O valor a ser pago pelos {dias} dias e {km}km é R${valor:.2f}");
class NumberException(Exception): pass class Number: # all hex numbers _number_map = "0123456789ABCDEF" def __init__(self, str_number="0", base=10): self._number_list = ["0"] self._number_base = 10 self._number_str = "0" self.set_number(str_number, base) def get_number(self) -> str: """:returns The number in string format""" return self._number_str def get_base(self) -> int: """:returns The base of the number""" return self._number_base def get_number_list(self) -> list: """:returns The internal number list""" return self._number_list[:] def set_number(self, str_number, base): """ Set the number and base :param str_number :param base """ # set the number base self._number_base = base # the original string passed self._number_str = str_number # validate and trow exception on error self._validate_number_base() self._validate_number_str() # the list of numbers reversed self._number_list = self._number_str_to_number_list(self._number_str, self._number_base) @staticmethod def _number_str_to_number_list(number_str, number_base) -> list: """ Convert a str to proper list of numbers that are reversed e.g: "F9" (base 16) will output [9, 15] :returns list """ # reverse the number temp_reversed = Number._reverse(number_str) # convert to appropriate digits return [int(i, number_base) for i in temp_reversed] @staticmethod def _number_list_to_number_str(number_list): """ Convert a list of number in any base to a string """ Number._normalize_result(number_list) if not number_list: # handle when list is empty return "0" # reverse to the original state temp_reversed = Number._reverse(number_list) return "".join([Number._number_map[i] for i in temp_reversed]) def _validate_number_str(self): """ Check if _number_str is valid Raises: NumberException - on invalid number """ if not isinstance(self._number_str, str): raise NumberException("Must be a string") # use python builtin to convert char to number try: int(self._number_str, self._number_base) except ValueError: raise NumberException("Number %s is not of base %d" % (self._number_str, self._number_base)) def _validate_number_base(self): """" Check if _number_base is valid """ if not isinstance(self._number_base, int): raise NumberException("Base is not an int") if self._number_base < 2 or self._number_base > 16: raise NumberException("Please choose a base between 2 and 16") @staticmethod def _validate_operation(base1, base2): """ Check if we can do on an operation on these numbers :raises NumberException - on invalid number """ if base1 != base2: raise NumberException("Can not do operation on 2 different bases. Please convert to a common base") @staticmethod def _reverse(object_abstract: list): """ Reverse an object that is iterable :returns the list reversed """ return object_abstract[::-1] @staticmethod def _normalize_lists(list1, list2): """ Make the two lists the same length my appending zeroes to the end """ len_list1 = len(list1) len_list2 = len(list2) len_diff = abs(len_list2 - len_list1) if len_diff: if len_list1 < len_list2: # extend the first list list1.extend([0] * len_diff) else: # extend second list list2.extend([0] * len_diff) @staticmethod def _normalize_result(result): """ Remove all non significant zeroes from result eg: if result = [4, 3, 2, 1, 0, 0, 0] which represents the number 0001234 after normalization result = [4, 3, 2, 1] which represents the number 1234 """ i = len(result) - 1 while i >= 0 and result[i] == 0: i -= 1 result.pop() def __str__(self): """ Str context """ return self.get_number() def __add__(self, other): """ Add to another number """ # print "add number list = ", self._number_list, other._number_list base = self.get_base() self._validate_operation(base, other.get_base()) number_a = self.get_number_list() number_b = other.get_number_list() # will hold the result number_c = [] # print number_a, number_b # normalize lists self._normalize_lists(number_a, number_b) len_number_a = len(number_a) transport = 0 # transport number, must be integer i = 0 while i < len_number_a: temp = number_a[i] + number_b[i] + transport # add to the result list number_c.append(temp % base) # the transport is quotient transport = temp // base i += 1 # overflow append transport if transport: number_c.append(transport) return Number(self._number_list_to_number_str(number_c), base) def __sub__(self, other): """ Subtract from another number of variable length """ # assume this one if bigger than other base = self.get_base() self._validate_operation(base, other.get_base()) number_a = self.get_number_list() number_b = other.get_number_list() # will hold the result number_c = [] # normalize lists self._normalize_lists(number_a, number_b) len_number_a = len(number_a) transport = 0 # transport number i = 0 while i < len_number_a: # check if we need to borrow if number_a[i] + transport < number_b[i]: temp = (number_a[i] + transport + base) - number_b[i] # set transport for next iteration transport = -1 else: # number_a[i] is bigger than number_b[i] NO need for borrow temp = (number_a[i] + transport) - number_b[i] transport = 0 # add to the result list number_c.append(temp) i += 1 return Number(self._number_list_to_number_str(number_c), base) def __mul__(self, other): """ Multiply with another number of 1 digit aka a scalar """ base = self.get_base() number_a = self.get_number_list() if isinstance(other, Number): # works only with one digit self._validate_operation(base, other.get_base()) number_b = other._number_list[:] number_b = number_b[0] elif isinstance(other, int): number_b = other else: raise NumberException("Wrong input") # will hold the result number_c = [] len_number_a = len(number_a) transport = 0 # transport number, must be an integer i = 0 while i < len_number_a: temp = number_a[i] * number_b + transport # add to the result list number_c.append(temp % base) # the transport is the quotient transport = temp // base i += 1 # if overflow append transport while transport: number_c.append(transport % base) transport //= base return Number(self._number_list_to_number_str(number_c), base) def __divmod__(self, other) -> tuple: """ Divide and return quotient and remainder """ base = self.get_base() number_a = self.get_number_list() if isinstance(other, Number): # works only with one digit self._validate_operation(base, other.get_base()) number_b = other._number_list[:] number_b = number_b[0] elif isinstance(other, int): number_b = other else: raise NumberException("Wrong input") # will hold the result number_c = [] len_number_a = len(number_a) remainder = 0 # transport number i = len_number_a - 1 while i >= 0: temp = remainder * base + number_a[i] number_c.append(temp // number_b) remainder = temp % number_b i -= 1 # reverse it because we inserted in reverse order number_c = self._reverse(number_c) return Number(self._number_list_to_number_str(number_c), base), remainder def __floordiv__(self, other): return divmod(self, other)[0] def __mod__(self, other): return divmod(self, other)[1] def is_zero(self): """ Check if number is zero :returns True or False """ if len(self._number_list) == 1 and self._number_list[0] == 0: return True for i in self._number_list: if i != 0: return False return True def convert_substitution(self, destination_base: int): """ Convert number to another base using substitution method :param destination_base :returns A new Number object """ if destination_base < 2 or destination_base > 16: raise NumberException("Base inputted is invalid") number = self.get_number_list() source_base = self.get_base() # because of our implementation we perform the calculation in the destination base result = Number("0", destination_base) power = Number("1", destination_base) for digit in number: # take every digit and multiply it by the corresponding power result += power * digit # increase the power for the next iteration # e.g for base 2, the power will be: 1, 2, 4, 8, etc power *= source_base self.set_number(result.get_number(), destination_base) return self def convert_division(self, destination_base: int): """ Convert number to another base using division method NOTE: only works with decimal numbers, and our internal number representation has decimal numbers, so we can use the overwritten // and % operators. :param destination_base :returns A new Number object """ if destination_base < 2 or destination_base > 16: raise NumberException("Base inputted is invalid") number = Number(self.get_number(), self.get_base()) result = [] while not number.is_zero(): quotient, remainder = divmod(number, destination_base) # The remainder is part of the result result.append(remainder) # Use next quotient for the division number = quotient self.set_number(self._number_list_to_number_str(result), destination_base) return self @staticmethod def _validate_rapid_conversion(source_base, destination_base): """ Checks if source_base if a power of destination_base or destination_base is a power of source_base :raises NumberException on invalid bases """ # checks if b is a power of a def _check(base_a, base_b): i = 1 while i < base_b: i *= base_a return i == base_b if _check(source_base, destination_base) or _check(destination_base, source_base): return # do nothing raise NumberException("Can not use rapid conversion") def convert_rapid(self, destination_base): """ Convert number to another base using rapid conversions NOTE: For this method to work, one of the bases must be a power of another one e.g: 2 and 16 (2^4 = 16), 3 and 9 (3^2 = 9) :param destination_base string :returns self """ if destination_base < 2 or destination_base > 16: raise NumberException("Base inputted is invalid") source_base = self.get_base() self._validate_rapid_conversion(source_base, destination_base) number = self.get_number_list() result = [] def get_len_group(base_a, base_b): # calculate the length of the group of replaced digits in base_b # swap bases, base_a must be smaller than base_b if base_a > base_b: base_a, base_b = base_b, base_a k = base_a length = 1 while k < base_b: k *= base_a length += 1 return length # the length of the group of digits len_group = get_len_group(source_base, destination_base) len_number = len(number) # convert to smaller base if source_base > destination_base: for i in range(len_number): # the number of digits to convert to for j in range(len_group): result.append(number[i] % destination_base) number[i] //= destination_base else: # convert to larger base i = 0 # compute the number while i < len_number: power = 1 temp = 0 j = 0 while j < len_group and i < len_number: temp += power * number[i] power *= source_base i += 1 j += 1 result.append(temp) self.set_number(self._number_list_to_number_str(result), destination_base) return self
{ 'targets': [ { 'target_name': 'sophia', 'product_prefix': 'lib', 'type': 'static_library', 'include_dirs': ['db'], 'link_settings': { 'libraries': ['-lpthread'], }, 'direct_dependent_settings': { 'include_dirs': ['db'], }, 'sources': [ 'db/cat.c', 'db/crc.c', 'db/cursor.c', 'db/e.c', 'db/file.c', 'db/gc.c', 'db/i.c', 'db/merge.c', 'db/recover.c', 'db/rep.c', 'db/sp.c', 'db/util.c', ], }, ], }
''' Leetcode problem No 416 Parition Equal Subset Sum Solution written by Xuqiang Fang on 4 April ''' class Solution(object): def canPartition(self, nums): s = 0; for i in nums: s += i if((s & 1) == 1): return False s >>= 1 dp = [0]*(s+1) dp[0] = 1 for i in range(len(nums)): for j in range(s,nums[i]-1,-1): dp[j] += dp[j-nums[i]] if(dp[s] == 0): return False else: return True def main(): nums = [1,5,11,5] s = Solution() print(s.canPartition(nums)) print(s.canPartition([1,2,3,5])) main()
# -*- python -*- # Copied from the drake project # https://github.com/RobotLocomotion/drake/blob/17423f8fb6f292b4af0b4cf3c6c0f157273af501/tools/workspace/generate_include_header.bzl load(":pathutils.bzl", "output_path") # Generate a header that includes a set of other headers def _generate_include_header_impl(ctx): # Collect list of headers hdrs = [] for h in ctx.attr.hdrs: for f in h.files.to_list(): hdrs.append(output_path(ctx, f, ctx.attr.strip_prefix)) # Generate include header content = "#pragma once\n" content = content + "\n".join(["#include \"%s\"" % h for h in hdrs]) ctx.actions.write(output = ctx.outputs.out, content = content) generate_include_header = rule( attrs = { "hdrs": attr.label_list(allow_files = True), "strip_prefix": attr.string_list(default = ["**/include/"]), "out": attr.output(mandatory = True), }, output_to_genfiles = True, implementation = _generate_include_header_impl, ) """Generate a header that includes a set of other headers. This creates a rule to generate a header that includes a list of other headers. The generated file will be of the form:: #include "hdr" #include "hdr" Args: hdrs (:obj:`str`): List of files or file labels of headers that the generated header will include. strip_prefix (:obj:`list` of :obj:`str`): List of prefixes to strip from the header names when forming the ``#include`` directives. """
name = input("请输入用户名:") pwd = input("请输入用户密码:") if name == "admin" : if pwd == "admin2020" : print("用户名和密码都正确,可以成功登录!") else : print("用户名正确,密码不正确!") else : if pwd == "admin2020" : print("用户名不正确,密码正确!") else : print("用户名和密码都不正确!")
print('b') for i in range(2): print(i)
####################################### # 文字列の操作 ####################################### def f(a, b): # 数値aとbの和を計算しxに代入せよ # (次の行を書き換える) x = 0 return x def g(a, b): # 数値aとbの積を計算し、xに代入せよ # (次の行を書き換える) x = 0 return x assert f(3, 5) == 8 assert g(2, 3) == 6 print("OK")
cat_colors=[(212,212,212),(100,100,100),(90,70,100),(70,3,89),(60,30,100),(58,83,139),(50,181,122),(175,220,46),(253,181,36),(255,62,76)] for i, col in enumerate(cat_colors): print("""#extinction_category label:nth-child(%i){ background-color: #%s }"""%(i+1,"".join(("{:02x}".format(c) for c in col))))
string = 'hehhhEhehehehehHHHHeeeeHHHehHHHeh' # string = string.replace('h', 'H', string.count('h') - 1).replace('H', 'h',1) # print(string) string1 = string[:string.find('h') + 1] string2 = string[string.rfind('h'):] string3 = string[string.find('h') + 1:string.rfind('h')] string3 = string3.replace('h', 'H') print(string1) print(string2) print(string3) print(string1 + string3 + string2)
# Time: O(n) # Space: O(n) class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ lookup = set(candies) return min(len(lookup), len(candies)/2)
while True: cont=int(input(" ")) if(cont==2002): print("Acceso Permitido") break else: print("Acceso Denegado")
class HondaInputOutputController: def __init__(self, send_func): self.send = send_func def left_turn_signal(self, on): if on: msg = b"\x30\x0a\x0f\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def right_turn_signal(self, on): if on: msg = b"\x30\x0b\x0f\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def hazard_lights(self, on): if on: msg = b"\x30\x08\x0f\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def parking_lights(self, on): if on: msg = b"\x30\x25\x0f\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def headlight_low_beams(self, on): if on: msg = b"\x30\x1c\x0f\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def headlight_high_beams(self, on): if on: msg = b"\x30\x1d\x0f\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def front_fog_lights(self, on): if on: msg = b"\x30\x20\x0f\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def daytime_running_lights(self, on): if on: msg = b"\x30\x36\x0f\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def lock_all_doors(self): self.send(0x16f118f0, b"\x30\x04\x01\x00\x00\x00\x00\x00") def unlock_all_doors(self): self.send(0x16f118f0, b"\x30\x05\x01\x00\x00\x00\x00\x00") def unlock_all_doors_alt(self): self.send(0x16f118f0, b"\x30\x06\x01\x00\x00\x00\x00\x00") def trunk_release(self): self.send(0x16f118f0, b"\x30\x09\x01\x00\x00\x00\x00\x00") def front_wipers_slow(self, on): if on: msg = b"\x30\x19\x05\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def front_wipers_fast(self, on): if on: msg = b"\x30\x1a\x05\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def front_washer_pump(self, on): if on: msg = b"\x30\x1b\x05\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def rear_wiper(self, on): if on: msg = b"\x30\x0d\x05\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def rear_washer_pump(self, on): if on: msg = b"\x30\x0e\x05\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f118f0, msg) def left_blindspot_flash(self, on): if on: msg = b"\x30\x01\x08\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f19ff0, msg) def right_blindspot_flash(self, on): if on: msg = b"\x30\x01\x08\x00\x00\x00\x00\x00" else: msg = b"\x20" self.send(0x16f1a7f0, msg)
#!/usr/bin/env python # ############################################################################### # Author: Greg Zynda # Last Modified: 12/09/2019 ############################################################################### # BSD 3-Clause License # # Copyright (c) 2019, Greg Zynda # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### FORMAT = "[%(levelname)s - %(filename)s:%(lineno)s - %(funcName)15s] %(message)s" BaseIndex = {'A':0, 'T':1, 'G':2, 'C':3, \ 0:'A', 1:'T', 2:'G', 3:'C'} def main(): pass if __name__ == "__main__": main()
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.11 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') print('流程控制实验:if-elif-else') a = input('请输入:') if a == 'Q': print('输入的字符为Q') elif a == 'X': print('输入的字符为X') elif a == 'Z': print('输入的字符为Z') else: print('输入的字符不为Q,也不为X,也不为Z')
class queue(object): """ A queue is a container of objects (a linear collection) that are inserted and removed according to the first-in first-out (FIFO) principle. >>> from pydsa import queue >>> q = queue() >>> q.enqueue(5) >>> q.enqueue(8) >>> q.enqueue(19) >>> q.dequeue() 5 """ def __init__(self): self.List = [] def isEmpty(self): return self.List == [] def enqueue(self, item): """ Insert element in queue. """ self.List.append(item) def dequeue(self): """ Remove element from front of the Queue. """ return self.List.pop(0) def size(self): """ Return size of Queue. """ return len(self.List)
# format example : [일반] 편한식사 (보랏빛소) - 7800원 https://ridibooks.com/v2/Detail?id=2129000044 FORMAT_PRINT_BOOK_MSG = '[%s] %s (%s) - %s원 https://ridibooks.com/v2/Detail?id=%s' # format example : [만화] 새로운 이벤트 : 온다 리쿠 최고의 걸작! 《꿀벌과 천둥》 출간 이벤트 https://ridibooks.com/event/6880 FORMAT_PRINT_EVENT_MSG = '[%s] 새로운 이벤트 : %s %s' HASHTAG_BOOK_RENEWAL = '#리디책수정' LENGTH_TWEET_LIMIT = 140 LENGTH_TITLE_LIMIT = 35 TIME_TWEET_UPDATE_SECOND = 10 TIME_REFRESH_MINUTE = 2 RETRY_READ_URL_COUNT = 5
def average(array): array = set(array) sumN = 0 for x in array: sumN = sumN + x return(sumN/len(array))
# Using Sorting # Overall complexity: O(n log n ) as sorted() has that complexity def unique2(S): temp = sorted(S) for j in range(1, len(S)): # O(n) if temp[j-1] == temp[j]: # O(1) return False return True if __name__ == "__main__": a1 = [1, 2, 3, 5, 7, 9, 4] print("The elements of {} are {}".format(a1, 'unique' if unique2(a1) else 'not unique')) a2 = [1, 2, 3, 5, 7, 9, 1] print("The elements of {} are {}".format(a2, 'unique' if unique2(a2) else 'not unique'))
def get_city_year(p0,perc,delta,target): years = 0 if p0 * (perc/100) + delta <= 0: return -1 while p0 < target: p0 = p0 + p0 * (perc/100) + delta years += 1 return years # a = int(input("Input current population:")) # b = float(input("Input percentage increase:")) # c = int(input("Input delta:")) # d = int(input("Input future population:")) # print(get_city_year(a,b,c,d)) print(get_city_year(1000, 2, -50, 5000)) print(get_city_year(1500, 5, 100, 5000)) print(get_city_year(1500000, 2.5, 10000, 2000000))
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: map = { } for i in range(len(nums)): if target - nums[i] in map: return [map[target - nums[i]] , i] else: map[nums[i]] = i
def rectangle(width, height): answer = width * height answer = int(answer) return answer print(rectangle(int(input()), int(input())))
""" 1021. Remove Outermost Parentheses Easy A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. Example 1: Input: "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()". Example 2: Input: "(()())(())(()(()))" Output: "()()()()(())" Explanation: The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". Example 3: Input: "()()" Output: "" Explanation: The input string is "()()", with primitive decomposition "()" + "()". After removing outer parentheses of each part, this is "" + "" = "". Note: S.length <= 10000 S[i] is "(" or ")" S is a valid parentheses string """ class Solution: def removeOuterParentheses(self, S: str) -> str: res, stack = "", [] for c in S: if c == '(': if stack: res += c stack.append("(") if c == ')': stack.pop() if stack: res += c return res class Solution: def removeOuterParentheses(self, S: str) -> str: res, count = [], 0 for c in S: if c == '(' and count > 0: res.append(c) if c == ')' and count > 1: res.append(c) count += 1 if c == '(' else -1 return "".join(res)
a=int(input("Enter the number:")) if a %2 == 0: print('Number is Even') else: print("Number is Odd")
def same_frequency(num1, num2): """Do these nums have same frequencies of digits? >>> same_frequency(551122, 221515) True >>> same_frequency(321142, 3212215) False >>> same_frequency(1212, 2211) True """ for num in str(num1): if str(num1).count(num) != str(num2).count(num): return False return True print(same_frequency(551122, 221515)) print(same_frequency(321142, 3212215)) print(same_frequency(1212, 2211))
expected_output = { "src":{ "31.1.1.2":{ "dest":{ "31.1.1.1":{ "interface":"GigabitEthernet0/0/0/0", "location":"0/0/CPU0", "session":{ "state":"UP", "duration":"0d:0h:5m:50s", "num_of_times_up":1, "type":"PR/V4/SH", "owner_info":{ "ipv4_static":{ "desired_interval_ms":500, "desired_multiplier":6, "adjusted_interval_ms":500, "adjusted_multiplier":6 } } }, "received_parameters":{ "version":1, "desired_tx_interval_ms":500, "required_rx_interval_ms":500, "required_echo_rx_interval_ms":0, "multiplier":6, "diag":"None", "demand_bit":0, "final_bit":0, "poll_bit":0, "control_bit":1, "authentication_bit":0, "my_discr":18, "your_discr":2148532226, "state":"UP" }, "transmitted_parameters":{ "version":1, "desired_tx_interval_ms":500, "required_rx_interval_ms":500, "required_echo_rx_interval_ms":1, "multiplier":6, "diag":"None", "demand_bit":0, "final_bit":0, "poll_bit":0, "control_bit":1, "authentication_bit":0, "my_discr":2148532226, "your_discr":18, "state":"UP" }, "timer_vals":{ "local_async_tx_interval_ms":500, "remote_async_tx_interval_ms":500, "desired_echo_tx_interval_ms":500, "local_echo_tax_interval_ms":0, "echo_detection_time_ms":0, "async_detection_time_ms":3000 }, "local_stats":{ "interval_async_packets":{ "Tx":{ "num_intervals":100, "min_ms":1, "max_ms":500, "avg_ms":229, "last_packet_transmitted_ms_ago":48 }, "Rx":{ "num_intervals":100, "min_ms":490, "max_ms":513, "avg_ms":500, "last_packet_received_ms_ago":304 } }, "interval_echo_packets":{ "Tx":{ "num_intervals":0, "min_ms":0, "max_ms":0, "avg_ms":0, "last_packet_transmitted_ms_ago":0 }, "Rx":{ "num_intervals":0, "min_ms":0, "max_ms":0, "avg_ms":0, "last_packet_received_ms_ago":0 } }, "latency_of_echo_packets":{ "num_of_packets":0, "min_ms":0, "max_ms":0, "avg_ms":0 } } } } } } }
""":mod:`krcurrency` --- 한국은행 원화대비 외화환율 조회 라이브러리 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 SuHun Han (ssut). :license: MIT License, see LICENSE for more details. """ __author__ = 'ssut' __author_email__ = 'ssut@ssut.me' __version__ = '1.0.0' __license__ = 'MIT' __url__ = 'https://github.com/ssut/py-krcurrency' __all__ = None
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def list(students): for idx, student in enumerate(students, 1): print( '{:>7}: ФИО: {}, Номер группы: {}, Русский язык: {}, Математика: {}, Информатика: {}, История: {}, Физика: {};'.format( idx, student.get('name', ''), student.get('post', ''), student.get('a', 0), student.get('b', 0), student.get('c', 0), student.get('d', 0), student.get('e', 0)))
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # 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. __all__ = [ 'TIMER_ENABLED_LOG_LINE', 'TIMER_DISABLED_LOG_LINE' ] # Integration tests look for these loglines to validate timer enable/disable TIMER_ENABLED_LOG_LINE = 'Timer is enabled.' TIMER_DISABLED_LOG_LINE = 'Timer is disabled.'
REDIS_OPTIONS = {'db': 0} TEST_REDIS_OPTIONS = {'db': 0} DEBUG = False LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'default': { 'level': 'INFO', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'aiohttp.access': { 'handlers': ['default'], 'level': 'INFO', }, 'aiohttp.server': { 'handlers': ['default'], 'level': 'INFO', }, } }
# p41.py def find_n(n): if n == 1: return 1 elif n/2 == int(n/2): return find_n(n/2) else: return find_n(n-1) + 1 num1 = int(input()) print(find_n(num1))
nome = str(input('Digite o seu nome: ')) dividido = nome.split() print('='*25) print(nome.upper()) print(nome.lower()) print('O seu nome tem {} letras.'.format(len(''.join(dividido)))) print('O seu primeiro nome tem {} letras.'.format(len(dividido[0]))) print('='*25)
""" Crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com a formatação correta. """ matriz = [] print('='*50) for coluna in range(0, 3): matriz.append(list()) for linha in range(0, 3): matriz[coluna].append(int(input(f'Digite o valor para [{coluna}, {linha}]: '))) print('='*50) for coluna in range(0, 3): for linha in range(0, 3): if linha == 2: print(f'[{matriz[coluna][linha]:^5}]') else: print(f'[{matriz[coluna][linha]:^5}] ', end='') print('='*50)
class Solution: """ https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 """ @staticmethod def twoSum(numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ seen = {} for i, num in enumerate(numbers, 1): try: return [seen[num], i] except KeyError: seen[target - num] = i