content
stringlengths
7
1.05M
# Base node class class Node(): def __init__(self): self.children = [None]*26 self.isend = False #Trie class class Trie(): def __init__(self): self.__root = Node() def __len__(self): """ returns length of the trie Returns: [int]: [length of the trie] """ return len(self.search_by_prefix('')) def __str__(self): """ returns all values in the trie Returns: [string]: [all values in the trie] """ ll = self.search_by_prefix('') string = "" for i in ll: string += i string += "\n" return string def chartoint(self, character): """ returns the unicode value of a character Returns: [int]: [integer value of the character] """ return ord(character) - ord('a') def remove(self, string): """ removes an item from the trie Args: string ([string]): [string to be removed] Raises: ValueError: [handles if the keyword does not exist in the trie] ValueError: [handles if the keyword does not exist in the trie] """ ptr = self.__root length = len(string) exists = True for idx in range(length): i = self.chartoint(string[idx]) if ptr.children[i] is not None: ptr = ptr.children[i] else: exists = False if ptr.isend is not True: exists = False if exists == False: print("Keyword does not exist in trie") ptr.isend = False return def insert(self, string): """ inserts a string into the trie Args: string ([string]): [string to be inserted into the trie] """ ptr = self.__root length = len(string) for idx in range(length): i = self.chartoint(string[idx]) if ptr.children[i] is not None: ptr = ptr.children[i] else: ptr.children[i] = Node() ptr = ptr.children[i] ptr.isend = True def search(self, string): """ searches for a string inside the trie Args: string ([string]): [string to search for] Returns: [bool]: [if the string is found in the trie or not] """ ptr = self.__root length = len(string) for idx in range(length): i = self.chartoint(string[idx]) if ptr.children[i] is not None: ptr = ptr.children[i] else: return False if ptr.isend is not True: return False return True def __getall(self, ptr, key, key_list): """ gets all values given arguments Args: ptr ([type]) key ([type]) key_list ([list]) """ if ptr is None: key_list.append(key) return if ptr.isend is True: key_list.append(key) for i in range(26): if ptr.children[i] is not None: self.__getall(ptr.children[i], key + chr(ord('a') + i), key_list) def search_by_prefix(self, key): """ gets all strings starting with a prefix Args: key ([string]): [key to search by] Returns: [list]: [list with all strings starting with key] """ ptr = self.__root key_list = [] length = len(key) for idx in range(length): i = self.chartoint(key[idx]) if ptr.children[i] is not None: ptr = ptr.children[i] else: return None self.__getall(ptr, key, key_list) return key_list
sequence = input().split(", ") my_dict = {} for el in sequence: ascii_number = ord(el) if el not in my_dict: my_dict[el] = ascii_number print(my_dict)
points = [(1,1), (2,2), (2.5,1)] print(points[2][0]) y=0 x=0 #point -> neue Variable für jeden Listeneintrag for point in points: print(point[1]) y = y+point[1] x = x+point[0] print(x,y) avg_x = x / len(points) avg_y = y / len(points) print(avg_x,avg_y) w_enumerator = 0 w_denominator = 0 for point in points: w_enumerator += (point[0]-avg_x)*(point[1]-avg_y) # Du tuesch das setze. aso bi jedem loop durchlauf wird de alt wert ersetzt. Du wotsch glaub "w_enumerator +=" anstatt "w_enumerator =", (das addiert nach jedem durchlauf de neui wert zum alte wert vo w_enumerator dezue) print(w_enumerator) for point in points: w_denominator += (point[0]-avg_x)**2 print(w_denominator) w1 = w_enumerator/w_denominator print(w1) w0 = 0 w0 = avg_y - w1 * avg_x print(w0)
''' Faça um programa que receba duas notas digitadas pelo usuário. Se a nota for maior ou igual a seis, escreva aprovado, senão escreva reprovado. ''' nota1 = float(input('Digite a primeira nota: ')) nota2 = float(input('Digite a segunda nota: ')) media = (nota1 + nota2) / 2 resultado = 'aprovado' if media < 6: resultado = 'reprovado' print('O aluno foi ' + resultado)
# @desc Can a triangle be made by these sides? # @desc By Jake '24 def form_triangle(side1, side2, side3): if side1 + side2 > side3 and side1 + side3 > side2 and side2 + side3 > side1: return True else: return False def main(): print(form_triangle(10, 5, 25)) print(form_triangle(3, 4, 5)) print(form_triangle(6, 2, 7)) print(form_triangle(12, 6, 5)) print(form_triangle(8, 19, 20)) if __name__ == '__main__': main()
def main(): # 1 add # 2 multiply # 99 halt # What value is at position 0 part_one() part_two() def part_one(): print("Part One") with open("input.txt", "r") as input_file: for line in input_file: numbers = list(map(int, line.split(","))) # Restore numbers[1] = 12 numbers[2] = 2 i = 0 while i < len(numbers): n = numbers[i] if n == 99: break n1 = numbers[numbers[i + 1]] n2 = numbers[numbers[i + 2]] if n == 1: result = n1 + n2 elif n == 2: result = n1 * n2 else: print("Error!") break numbers[numbers[i + 3]] = result i += 4 print(numbers[0], numbers) def part_two(): print("Part Two") with open("input.txt", "r") as input_file: for line in input_file: for i_noun in range(0, 100): for i_verb in range(0, 100): numbers = list(map(int, line.split(","))) numbers[1] = i_noun numbers[2] = i_verb i = 0 while i < len(numbers): n = numbers[i] if n == 99: break noun = numbers[numbers[i + 1]] verb = numbers[numbers[i + 2]] if n == 1: result = noun + verb elif n == 2: result = noun * verb else: print("Error!") break numbers[numbers[i + 3]] = result i += 4 if numbers[0] == 19690720: print(numbers[0], " = 100 * ", i_noun, " * ", i_verb, numbers) if __name__ == "__main__": main()
# Written by Mayank # This program is used to first parse the dataset files for training # and testing and then compile them into dataparsed.cpp file # from where we can load the data into sgx enclave. accdataAC = "" accdataBD = "" acclabelAC = "" acclabelBD = "" accdatasample = "" acclabelsample = "" #First accdataAC file = open("mnist_data_8_AC", "r") while True: curline = file.readline() #print(curline) if len(curline) is 0: break curline = curline[:-1] if len(curline) > 0: accdataAC += curline + ' ' file.close() #First accdataBD file = open("mnist_data_8_BD", "r") while True: curline = file.readline() #print(curline) if len(curline) is 0: break curline = curline[:-1] if len(curline) > 0: accdataBD += curline + ' ' file.close() #First acclabelAC file = open("mnist_labels_8_AC", "r") while True: curline = file.readline() #print(curline) if len(curline) is 0: break curline = curline[:-1] if len(curline) > 0: acclabelAC += curline + ' ' file.close() #First acclabelBD file = open("mnist_labels_8_BD", "r") while True: curline = file.readline() #print(curline) if len(curline) is 0: break curline = curline[:-1] if len(curline) > 0: acclabelBD += curline + ' ' file.close() #First accdatasample file = open("mnist_data_8_samples", "r") while True: curline = file.readline() #print(curline) if len(curline) is 0: break curline = curline[:-1] if len(curline) > 0: accdatasample += curline + ' ' file.close() #First acclabelsample file = open("mnist_labels_8_samples", "r") while True: curline = file.readline() #print(curline) if len(curline) is 0: break curline = curline[:-1] if len(curline) > 0: acclabelsample += curline + ' ' file.close() # Slice on whitespaces split_dataAC = accdataAC.split() split_dataBD = accdataBD.split() split_labelAC = acclabelAC.split() split_labelBD = acclabelBD.split() split_datasample = accdatasample.split() split_labelsample = acclabelsample.split() cppfile = open("dataparsed.cpp", "w") cppfile.seek(0) cppfile.truncate() boilerplate = "#include \"dataparsed.h\"\n" cppfile.write(boilerplate) lenlist = []; #DataAC declaration_full = "" curlen = len(split_dataAC) lenlist.append(curlen) declaration_full = declaration_full + "int dataAC["+str(curlen)+"] = {" for i in range(curlen): if i == curlen-1: declaration_full = declaration_full + split_dataAC[i] else: declaration_full = declaration_full + split_dataAC[i] + ", " declaration_full = declaration_full + "};\n" cppfile.write(declaration_full) #DataBD declaration_full = "" curlen = len(split_dataBD) lenlist.append(curlen) declaration_full = declaration_full + "int dataBD["+str(curlen)+"] = {" for i in range(curlen): if i == curlen-1: declaration_full = declaration_full + split_dataBD[i] else: declaration_full = declaration_full + split_dataBD[i] + ", " declaration_full = declaration_full + "};\n" cppfile.write(declaration_full) #LabelAC declaration_full = "" curlen = len(split_labelAC) lenlist.append(curlen) declaration_full = declaration_full + "int labelAC["+str(curlen)+"] = {" for i in range(curlen): if i == curlen-1: declaration_full = declaration_full + split_labelAC[i] else: declaration_full = declaration_full + split_labelAC[i] + ", " declaration_full = declaration_full + "};\n" cppfile.write(declaration_full) #LabelBD declaration_full = "" curlen = len(split_labelBD) lenlist.append(curlen) declaration_full = declaration_full + "int labelBD["+str(curlen)+"] = {" for i in range(curlen): if i == curlen-1: declaration_full = declaration_full + split_labelBD[i] else: declaration_full = declaration_full + split_labelBD[i] + ", " declaration_full = declaration_full + "};\n" cppfile.write(declaration_full) #Datasample declaration_full = "" curlen = len(split_datasample) lenlist.append(curlen) declaration_full = declaration_full + "int datasample["+str(curlen)+"] = {" for i in range(curlen): if i == curlen-1: declaration_full = declaration_full + split_datasample[i] else: declaration_full = declaration_full + split_datasample[i] + ", " declaration_full = declaration_full + "};\n" cppfile.write(declaration_full) #Labelsample declaration_full = "" curlen = len(split_labelsample) lenlist.append(curlen) declaration_full = declaration_full + "int labelsample["+str(curlen)+"] = {" for i in range(curlen): if i == curlen-1: declaration_full = declaration_full + split_labelsample[i] else: declaration_full = declaration_full + split_labelsample[i] + ", " declaration_full = declaration_full + "};\n" cppfile.write(declaration_full) print("Contents of data files compiled and written to dataparsed.cpp") cppfile.close() cppheader = open("dataparsed.h", "w") cppheader.seek(0) cppheader.truncate() headerinfo = "#include <string>\n#include <stdio.h>\n#include <stdlib.h>\nextern int dataAC["+str(lenlist[0])+"];\nextern int dataBD["+str(lenlist[1])+"];\nextern int labelAC["+str(lenlist[2])+"];\nextern int labelBD["+str(lenlist[3])+"];\nextern int datasample["+str(lenlist[4])+"];\nextern int labelsample["+str(lenlist[5])+"];" cppheader.write(headerinfo) cppheader.close() print("Header file written")
# We're going to use a custom timer, so we don't actually have to do anything # in these functions. def top(): mid1() mid2() mid3(5) C1.samename() C2.samename() def mid1(): bot() for i in range(5): mid2() bot() def mid2(): bot() def bot(): pass def mid3(x): if x > 0: mid4(x) def mid4(x): mid3(x - 1) class C1(object): @staticmethod def samename(): pass class C2(object): @staticmethod def samename(): pass expected_output_py2 = """event: ns : Nanoseconds events: ns summary: 59000 fl=<filename> fn=top 5 6000 cfl=<filename> cfn=mid1 calls=1 13 5 27000 cfl=<filename> cfn=mid2 calls=1 20 5 3000 cfl=<filename> cfn=mid3 calls=1 28 5 21000 cfl=<filename> cfn=samename:38 calls=1 38 5 1000 cfl=<filename> cfn=samename:44 calls=1 44 5 1000 fl=<filename> fn=mid1 13 9000 cfl=<filename> cfn=mid2 calls=5 20 13 15000 cfl=<filename> cfn=bot calls=2 24 13 2000 cfl=~ cfn=<range> calls=1 0 13 1000 fl=<filename> fn=mid2 20 12000 cfl=<filename> cfn=bot calls=6 24 20 6000 fl=<filename> fn=bot 24 8000 fl=<filename> fn=mid3 28 11000 cfl=<filename> cfn=mid4 calls=5 33 28 19000 fl=<filename> fn=mid4 33 10000 cfl=<filename> cfn=mid3 calls=5 28 33 17000 fl=<filename> fn=samename:38 38 1000 fl=<filename> fn=samename:44 44 1000 fl=~ fn=<method 'disable' of '_lsprof.Profiler' objects> 0 1000 fl=~ fn=<range> 0 1000 """.replace('<filename>', top.__code__.co_filename) expected_output_py3 = """event: ns : Nanoseconds events: ns summary: 57000 fl=<filename> fn=top 5 6000 cfl=<filename> cfn=mid1 calls=1 13 5 25000 cfl=<filename> cfn=mid2 calls=1 20 5 3000 cfl=<filename> cfn=mid3 calls=1 28 5 21000 cfl=<filename> cfn=samename:38 calls=1 38 5 1000 cfl=<filename> cfn=samename:44 calls=1 44 5 1000 fl=<filename> fn=mid1 13 8000 cfl=<filename> cfn=mid2 calls=5 20 13 15000 cfl=<filename> cfn=bot calls=2 24 13 2000 fl=<filename> fn=mid2 20 12000 cfl=<filename> cfn=bot calls=6 24 20 6000 fl=<filename> fn=bot 24 8000 fl=<filename> fn=mid3 28 11000 cfl=<filename> cfn=mid4 calls=5 33 28 19000 fl=<filename> fn=mid4 33 10000 cfl=<filename> cfn=mid3 calls=5 28 33 17000 fl=<filename> fn=samename:38 38 1000 fl=<filename> fn=samename:44 44 1000 fl=~ fn=<method 'disable' of '_lsprof.Profiler' objects> 0 1000 """.replace('<filename>', __file__)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu May 18 11:06:15 2017 @author: tomislav """ def sliding_window(image, stepSize=20, windowSize=(200, 200)): for y in xrange(0, image.shape[0]-windowSize[1]+stepSize, stepSize): for x in xrange(0, image.shape[1]-windowSize[0]+stepSize, stepSize): yield (x, y, image[y:y+windowSize[1], x:x+windowSize[0]])
# Copyright 2021 Fabian Meumertzheim # # 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. load("@bazel_tools//tools/jdk:toolchain_utils.bzl", "find_java_toolchain") load(":codegen.bzl", "generate_nested_structure") load(":common.bzl", "camel_case_identifier", "escape", "make_default_info", "runfile_structs") DEFINITION_TEMPLATE = """/* * Original label: {raw_label} * Remapped label: {remapped_label} */ public static final String {escaped_name} = "{rlocation_path}";""" CLASS_TEMPLATE = """// Automatically generated by rules_runfiles. package {package}; public final class {class_name} {{ {content} }} """ def _begin_inner_class(segment): return """public static final class %s { private %s() {};""" % (segment, segment) def _end_inner_class(segment): return "}" def _emit(runfile): return DEFINITION_TEMPLATE.format( escaped_name = escape(runfile.name), raw_label = runfile.raw_label, remapped_label = runfile.remapped_label, rlocation_path = runfile.rlocation_path, ) def _java_runfiles_impl(ctx): runfiles = runfile_structs(ctx, ctx.attr.data, ctx.attr.raw_labels) content = generate_nested_structure( runfile_structs = runfiles, begin_group = _begin_inner_class, end_group = _end_inner_class, emit = _emit, indent_per_level = 2, ) class_name = camel_case_identifier(ctx.attr.name) java_file_name = "%s.java" % class_name java_file = ctx.actions.declare_file(java_file_name) java_package = ctx.attr.package or _get_java_full_classname(ctx.label.package) ctx.actions.write(java_file, CLASS_TEMPLATE.format( class_name = class_name, content = content, package = java_package, )) jar_file_name = "%s.jar" % class_name jar_file = ctx.actions.declare_file(jar_file_name) java_toolchain = find_java_toolchain(ctx, ctx.attr._java_toolchain) full_java_info = java_common.compile( ctx, java_toolchain = java_toolchain, # The JLS (§13.1) guarantees that constants are inlined. Since the generated code only # contains constants, we can remove it from the runtime classpath. neverlink = True, output = jar_file, source_files = [java_file], ) # Do not expose the full compile jar so that regular javac is never invoked. The compilation is # fully handled by turbine. This is # * sufficient since the generated code exports no methods in its public interface; # * necessary since javac would complain about nested classes having the same name as an # enclosing class, but turbine and the JVM don't. hjar_file = full_java_info.compile_jars.to_list()[0] java_info = JavaInfo( output_jar = hjar_file, compile_jar = hjar_file, neverlink = True, ) return [ make_default_info(ctx, ctx.attr.data), java_common.merge([ java_info, ctx.attr._runfiles_lib[JavaInfo], ]), ] _java_runfiles = rule( implementation = _java_runfiles_impl, attrs = { "data": attr.label_list( allow_files = True, mandatory = True, ), "package": attr.string(), "raw_labels": attr.string_list(), "_java_toolchain": attr.label(default = "@bazel_tools//tools/jdk:current_java_toolchain"), "_runfiles_lib": attr.label(default = "//third_party/bazel_tools/tools/java/runfiles"), }, fragments = ["java"], provides = [JavaInfo], ) def java_runfiles(name, data, package = None, **kwargs): _java_runfiles( name = name, data = data, package = package, raw_labels = data, visibility = ["//visibility:private"], **kwargs ) # A slightly modified Starlark reimplementation of Bazel's JavaUtil#getJavaFullClassname. def _get_java_full_classname(source_pkg): java_path = _get_java_path(source_pkg) if java_path != None: return java_path.replace("/", ".") return source_pkg # A Starlark reimplementation of Bazel's JavaUtil#getJavaPath. def _get_java_path(main_source_path): path_segments = main_source_path.split("/") index = _java_segment_index(path_segments) if index >= 0: return "/".join(path_segments[index + 1:]) return None _KNOWN_SOURCE_ROOTS = ["java", "javatests", "src", "testsrc"] # A Starlark reimplementation of Bazel's JavaUtil#javaSegmentIndex. def _java_segment_index(path_segments): root_index = -1 for pos, segment in enumerate(path_segments): if segment in _KNOWN_SOURCE_ROOTS: root_index = pos break if root_index == -1: return root_index is_src = "src" == path_segments[root_index] check_maven_index = root_index if is_src else -1 max = len(path_segments) - 1 if root_index == 0 or is_src: for i in range(root_index + 1, max): segment = path_segments[i] if "src" == segment or (is_src and ("javatests" == segment or "java" == segment)): next = path_segments[i + 1] if ("com" == next or "org" == next or "net" == next): root_index = i elif "src" == segment: check_maven_index = i break if check_maven_index >= 0 and check_maven_index + 2 < len(path_segments): next = path_segments[check_maven_index + 1] if "main" == next or "test" == next: next = path_segments[check_maven_index + 2] if "java" == next or "resources" == next: root_index = check_maven_index + 2 return root_index
""" 0784. Letter Case Permutation Medium Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. You can return the output in any order. Example 1: Input: S = "a1b2" Output: ["a1b2","a1B2","A1b2","A1B2"] Example 2: Input: S = "3z4" Output: ["3z4","3Z4"] Example 3: Input: S = "12345" Output: ["12345"] Example 4: Input: S = "0" Output: ["0"] Constraints: S will be a string with length between 1 and 12. S will consist only of letters or digits. """ class Solution: def letterCasePermutation(self, S: str) -> List[str]: res = [""] for s in S: if s.isalpha(): res = [i+j for i in res for j in [s.lower(), s.upper()]] else: res = [i+s for i in res] return res
# Questão 1114 - Senha fixa # Link da questão - https://www.urionlinejudge.com.br/judge/pt/problems/view/1114 correta = False # Flag que indica se a senha indicada foi a correta while not correta: senha = str(input()) # Pega a senha da entrada if senha != '2002': print('Senha Invalida') # Se a senha difere da real else: print('Acesso Permitido') # Se a senha é correta correta = True # Mudamos o valor da flag para parar o loop
# -*- coding: utf-8 -*- """ Created on Sat Jul 14 19:08:07 2018 @author: Yilin Liu """ class Parameter(object): def __init__(self, re, it, co, no): self.regularization = re self.most_iter_num = it self.convergence = co self.nonconvexity = no def print_value(self): print(self.regularization, self.most_iter_num, self.convergence, self.nonconvexity)
# **Please read this problem entirely!!** The majority of this problem consists of learning how to read code, which is an incredibly useful and important skill. At the end, you will implement a short function. Be sure to take your time on this problem - it may seem easy, but reading someone else's code can be challenging and this is an important exercise. # # # Representing hands # A hand is the set of letters held by a player during the game. The player is initially dealt a set of random letters. For example, the player could start out with the following hand: a, q, l, m, u, i, l. In our program, a hand will be represented as a dictionary: the keys are (lowercase) letters and the values are the number of times the particular letter is repeated in that hand. For example, the above hand would be represented as: # # hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1} # Notice how the repeated letter 'l' is represented. Remember that with a dictionary, the usual way to access a value is hand['a'], where 'a' is the key we want to find. However, this only works if the key is in the dictionary; otherwise, we get a KeyError. To avoid this, we can use the call hand.get('a',0). This is the "safe" way to access a value if we are not sure the key is in the dictionary. d.get(key,default) returns the value for key if key is in the dictionary d, else default. If default is not given, it returns None, so that this method never raises a KeyError. For example: # # >>> hand['e'] # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # KeyError: 'e' # >>> hand.get('e', 0) # 0 # Converting words into dictionary representation # One useful function we've defined for you is getFrequencyDict, defined near the top of ps4a.py. When given a string of letters as an input, it returns a dictionary where the keys are letters and the values are the number of times that letter is represented in the input string. For example: # # >>> getFrequencyDict("hello") # {'h': 1, 'e': 1, 'l': 2, 'o': 1} # As you can see, this is the same kind of dictionary we use to represent hands. # # Displaying a hand # Given a hand represented as a dictionary, we want to display it in a user-friendly way. We have provided the implementation for this in the displayHand function. Take a few minutes right now to read through this function carefully and understand what it does and how it works. # # Generating a random hand # The hand a player is dealt is a set of letters chosen at random. We provide you with the implementation of a function that generates this random hand, dealHand. The function takes as input a positive integer n, and returns a new object, a hand containing n lowercase letters. Again, take a few minutes (right now!) to read through this function carefully and understand what it does and how it works. # # Removing letters from a hand (you implement this) # The player starts with a hand, a set of letters. As the player spells out words, letters from this set are used up. For example, the player could start out with the following hand: a, q, l, m, u, i, l. The player could choose to spell the word quail . This would leave the following letters in the player's hand: l, m. Your task is to implement the function updateHand, which takes in two inputs - a hand and a word (string). updateHand uses letters from the hand to spell the word, and then returns a copy of the hand, containing only the letters remaining. For example: # # >>> hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1} # >>> displayHand(hand) # Implemented for you # a q l l m u i # >>> hand = updateHand(hand, 'quail') # You implement this function! # >>> hand # {'a':0, 'q':0, 'l':1, 'm':1, 'u':0, 'i':0} # >>> displayHand(hand) # l m # Implement the updateHand function. Make sure this function has no side effects: i.e., it must not mutate the hand passed in. Before pasting your function definition here, be sure you've passed the appropriate tests in test_ps4a.py. hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1} def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ hand_clone = hand.copy() for c in word: hand_clone[c] = hand_clone.get(c, 0) - 1 return hand_clone print(updateHand(hand, 'quail'))
# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): return {'pypit.tests': ['files/*']}
""" sm.sendNext("want some item?") sm.giveAndEquip(1382000) sm.dispose() """
class Item: def __init__(self, id, assignment_id = None, inherent = None, max_inherent = None): self.id = id self.assignment_id = assignment_id self.inherent = inherent self.max_inherent = max_inherent self.reviews = {} class User: def __init__(self, name): self.name = name self.users = set() self.reviews = {} class Review: def __init__(self, review_id = None, grade = None, extra_informative_feature = None): self.review_id = id self.grade = grade self.extra_informative_feature = extra_informative_feature class Graph: def __init__(self): self.items = set() self.users = set() self.reviews = {} self.items_with_ground_truth = [] self.user_dict = {} self.item_dict = {} def add_item(self, item_id, inherent = None, max_inherent = None, assignment_id = None): item = Item(id = item_id, inherent= inherent, max_inherent= max_inherent, assignment_id= assignment_id) self.item_dict[item_id] = item self.items = self.items | {item} def add_user(self, user_name): user = User(user_name) self.user_dict[user_name] = user self.users = self.users | {user} def get_user(self, user_name): return self.user_dict.get(user_name) def get_item(self, item_id): return self.item_dict.get(item_id) def has_voted(self, user_name,item_id): if not user_name in self.user_dict or not item_id in self.item_dict: return False if (self.get_user(user_name), self.get_item(item_id)) in self.reviews: return True else: return False def get_no_of_votes(self, item_id): if not item_id in self.item_dict: return 0 return len(self.get_item(item_id).reviews) def add_review(self, user_name, item_id, review, assignment_id = None): """ Adds a review to the graph. It inserts the review to the generic dictionary of reviews but also to the item.reviews and user.reviews dictionaries. There is redundancy of information but enhances accessibility. """ # If user name or item id are not in the graph create respective objects if not user_name in self.user_dict: self.add_user(user_name) if not item_id in self.item_dict: self.add_item(item_id, assignment_id= assignment_id) # Get user and item objects that correspond to user name and user id user = self.get_user(user_name) item = self.get_item(item_id) # add review to the dictionaries item.reviews[user] = review user.reviews[item] = review self.reviews[(user, item)] = review
# 用途:用4种方法计算出结果为8 print(4 + 4) print(16 // 2) print(2 * 4) print(10 - 2) #姓名:YB #日期:2020年8月2日 #用途:说明喜爱数字 x = 414 msg = "My favourite number is " + str(x) print(msg)
#Maior de dois números #Função def maximo(x, y): if x > y: return x else: return y print(maximo(5, 6)) print(maximo(2, 1)) print(maximo(3, 3))
# シンプルな条件分岐 s = str(input()) if s == 'a' or s == 'e' or s == 'i' or s == 'o' or s == 'u': print('vowel') else: print('consonant')
description = 'LakeShore 340 cryo controller' group = 'optional' includes = ['alias_T'] tango_base = 'tango://miractrl.mira.frm2:10000/mira/' devices = dict( T_ls2 = device('nicos.devices.entangle.TemperatureController', description = 'temperature regulation', tangodevice = tango_base + 'ls2/ls_control1', pollinterval = 0.7, maxage = 2, ), T_ls2_A = device('nicos.devices.entangle.Sensor', description = 'sensor A', tangodevice = tango_base + 'ls2/ls_sensor1', pollinterval = 0.7, maxage = 2, ), T_ls2_B = device('nicos.devices.entangle.Sensor', description = 'sensor B', tangodevice = tango_base + 'ls2/ls_sensor2', pollinterval = 0.7, maxage = 2, ), T_ls2_C = device('nicos.devices.entangle.Sensor', description = 'sensor C', tangodevice = tango_base + 'ls2/ls_sensor3', pollinterval = 0.7, maxage = 2, ), T_ls2_D = device('nicos.devices.entangle.Sensor', description = 'sensor D', tangodevice = tango_base + 'ls2/ls_sensor4', pollinterval = 0.7, maxage = 2, ), ) alias_config = { 'T': {'T_ls2': 180}, # lower than default T_ccr5 'Ts': {'T_ls2_A': 60, 'T_ls2_B': 50}, }
class ActivePetUpdateRequestPacket: def __init__(self): self.type = "ACTIVEPETUPDATEREQUEST" self.commandType = 0 self.instanceId = 0 def write(self, writer): writer.writeByte(self.commandType) writer.writeInt32(self.instanceId) def read(self, reader): self.commandType = reader.readByte() self.instanceId = reader.readInt32()
### create tuple of 3 elements: point3d = (4, 0, 3) print(point3d[0], point3d[1], point3d[2]) # 4 0 3 print(point3d[-1], point3d[-2], point3d[-3]) # 3 0 4 ### retrieve tuple items address = ('Bulgaria', 'Sofia', 'Nezabravka str', 14) country = address[0] town = address[1] street = address[2] street_num = address[3] print(country, town, street, street_num) # Bulgaria Sofia Nezabravka str 14 ### change a tuple item: # address[0] = "France" # TypeError: 'tuple' object does not support item assignment ### create tuple with 3 elements: ada_birth_date = (10, "December", 1815) # retrieve tuple elements: ada_birth_day = ada_birth_date[0] ada_birth_month = ada_birth_date[1] ada_birth_year = ada_birth_date[2] print("Ada is born on {} {} in {}".format(ada_birth_month, ada_birth_day, ada_birth_year)) # Ada is born on December 10 in 181
__author__ = "Jason Lin" __email__ = "jason40418@yahoo.com.tw" __license__ = "MIT" __version__ = "1.0.0"
# -*- coding: utf-8 -*- # Scrapy settings for scraper project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'scraper' SPIDER_MODULES = ['scraper.spiders'] NEWSPIDER_MODULE = 'scraper.spiders' JOBDIR = 'jobs/crunchbase' # Crawl responsibly by identifying yourself (and your website) on the user-agent # Firefox # USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0' # Edge USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 6 # The download delay setting will honor only one of: CONCURRENT_REQUESTS_PER_DOMAIN = 1 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) # COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: # DEFAULT_REQUEST_HEADERS = { # 'Upgrade-Insecure-Requests': '1', # 'Connection': 'keep-alive', # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', # } # Enable or disable spider middlewares # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'scraper.middlewares.ScraperSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'scraper.middlewares.MyCustomDownloaderMiddleware': 543, #} # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'scraper.pipelines.ScraperPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings HTTPCACHE_ENABLED = True HTTPCACHE_EXPIRATION_SECS = 0 HTTPCACHE_DIR = 'httpcache' HTTPCACHE_IGNORE_HTTP_CODES = [416] HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' ########################################################## # Uncomment the following if using scrapy-rotating-proxies ########################################################## # DOWNLOADER_MIDDLEWARES = { # 'rotating_proxies.middlewares.RotatingProxyMiddleware': 610, # 'rotating_proxies.middlewares.BanDetectionMiddleware': 620, # } # def load_lines(path): # with open(path, 'rb') as f: # return [line.strip() for line in # f.read().decode('utf8').splitlines() # if line.strip()] # ROTATING_PROXY_LIST = load_lines('proxies.txt') ############################################ ## Uncomment the following if using Scrapoxy ############################################ CONCURRENT_REQUESTS_PER_DOMAIN = 1 RETRY_TIMES = 3 # PROXY PROXY = 'http://127.0.0.1:8888/?noconnect' # SCRAPOXY API_SCRAPOXY = 'http://127.0.0.1:8889/api' API_SCRAPOXY_PASSWORD = 'password' # BLACKLISTING BLACKLIST_HTTP_STATUS_CODES = [ 500, 416 ] DOWNLOADER_MIDDLEWARES = { 'scrapoxy.downloadmiddlewares.proxy.ProxyMiddleware': 100, 'scrapoxy.downloadmiddlewares.wait.WaitMiddleware': 101, 'scrapoxy.downloadmiddlewares.scale.ScaleMiddleware': 102, 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': None, 'scrapoxy.downloadmiddlewares.blacklist.BlacklistDownloaderMiddleware': 950, }
class TotoInterface: def machin(self): raise NotImplementedError
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'build/file', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/step', 'recipe_engine/time', ]
def isPrime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n % f == 0: return False if n % (f+2) == 0: return False f += 6 return True def isPal(n): og = n rev = 0 while(n!=0): digit = n%10 rev = rev*10 + digit n = n//10 return(rev==og) maxNineDigit = 999999999 minNineDigit = 100000000 palPrimeList = [] for i in range(maxNineDigit,minNineDigit,-1): if(isPal(i)): if(isPrime(i)): palPrimeList.append(i) if(len(palPrimeList)==3): break print(palPrimeList)
# Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome “SANTO”. cidade = str(input('Digite o nome de uma cidade: ')) maiusc = cidade.upper() listacidade = maiusc.split() primeiro_termo = listacidade[0] resultado = primeiro_termo.find('SANTO') print('Se retornar 0: a cidade começa com Santo;\nSe retornar -1: não começa com Santo. \nResultado: {}'.format(resultado)) # outra forma: resultado_2 = "SANTO" in primeiro_termo print('A cidade começa com a palavra Santo:',resultado_2) # outra forma: #cid = str(input('Digite o nome de uma cidade: ')).strip() #usa-se o strip para retirar os espaços #print(cid[:5].upper() == 'SANTO') # Santo possui 5 letras, na str vai de 0 a 4. Logo, esse programa irá analisar as 5 letras.
# Copyright 2019 FMR LLC <opensource@fidelity.com> # SPDX-License-Identifer: Apache-2.0 __version__ = "1.3.2"
class WhiteBalanceModifier: white_value = None
# Constants without private static final look...wrong. CASCADE_DIR = 'cascade_files' DATA_DIR = './data/' CASCADE_FILE = 'haarcascade_frontalface_default.xml' DATA_IMAGE_FILE = 'converted_images.npy' DATA_LABEL_FILE = 'converted_labels.npy' DATASET_CSV_FILENAME = 'fer2013.csv' FACE_SIZE = 48 EMOTIONS = ['angry', 'disgusted', 'fearful', 'happy', 'sad', 'surprised', 'neutral']
#!/usr/bin/env python # -*- coding: utf-8 -*- """ *What is this pattern about? The Borg pattern (also known as the Monostate pattern) is a way to implement singleton behavior, but instead of having only one instance of a class, there are multiple instances that share the same state. In other words, the focus is on sharing state instead of sharing instance identity. *What does this example do? To understand the implementation of this pattern in Python, it is important to know that, in Python, instance attributes are stored in a attribute dictionary called __dict__. Usually, each instance will have its own dictionary, but the Borg pattern modifies this so that all instances have the same dictionary. In this example, the __shared_state attribute will be the dictionary shared between all instances, and this is ensured by assigining __shared_state to the __dict__ variable when initializing a new instance (i.e., in the __init__ method). Other attributes are usually added to the instance's attribute dictionary, but, since the attribute dictionary itself is shared (which is __shared_state), all other attributes will also be shared. For this reason, when the attribute self.state is modified using instance rm2, the value of self.state in instance rm1 also chages. The same happends if self.state is modified using rm3, which is an instance from a subclass. Notice that even though they share attributes, the instances are not the same, as seen by their ids. *Where is the pattern used practically? Sharing state is useful in applications like managing database connections: https://github.com/onetwopunch/pythonDbTemplate/blob/master/database.py *References: https://fkromer.github.io/python-pattern-references/design/#singleton *TL;DR80 Provides singletone-like behavior sharing state between instances. """ class Borg(object): __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state self.state = 'Init' def __str__(self): return self.state class YourBorg(Borg): pass if __name__ == '__main__': rm1 = Borg() rm2 = Borg() rm1.state = 'Idle' rm2.state = 'Running' print('rm1: {0}'.format(rm1)) print('rm2: {0}'.format(rm2)) rm2.state = 'Zombie' print('rm1: {0}'.format(rm1)) print('rm2: {0}'.format(rm2)) print('rm1 id: {0}'.format(id(rm1))) print('rm2 id: {0}'.format(id(rm2))) rm3 = YourBorg() print('rm1: {0}'.format(rm1)) print('rm2: {0}'.format(rm2)) print('rm3: {0}'.format(rm3)) ### OUTPUT ### # rm1: Running # rm2: Running # rm1: Zombie # rm2: Zombie # rm1 id: 140732837899224 # rm2 id: 140732837899296 # rm1: Init # rm2: Init # rm3: Init
print('=' * 12 + 'Desafio 56' + '=' * 12) nomehomem = 'Não' idadetotal = 0 idadevelho = 0 mulheres = 0 for i in range(0, 4): print('=' * 28) nome = input(f'Digite o nome da pessoa {i + 1}: ').strip() idade = int(input(f'Digite a idade da pessoa {i + 1}: ')) sexo = input(f'Digite o sexo da pessoa {i + 1} (M ou F): ').strip().upper() idadetotal += idade if sexo == 'F' and idade < 20: mulheres += 1 if sexo == 'M' and idade > idadevelho: nomehomem = nome idadevelho = idade print('===Resultado===') print(f'A média das 4 idades é {idadetotal / 4:.1f} anos.') if nomehomem == 'Não': print('Não há homens.') else: print(f'O nome do homem mais velho é {nomehomem} e ele tem {idadevelho} anos.') print(f'Existem {mulheres} mulheres com menos de 20 anos.')
class WriteEncoder: def __init__(self, tokenDictionary): self.tokenDictionary = tokenDictionary self.streamStarted = False def reset(self): self.streamStarted = False def getStreamStartBytes(self, domain, resource): data = [] self.streamStarted = True data.append(87) data.append(65) data.append(1) data.append(5) streamOpenAttributes = {"to": domain, "resource": resource} self.writeListStart(len(streamOpenAttributes) * 2 + 1, data) data.append(1); self.writeAttributes(streamOpenAttributes, data) return data def protocolTreeNodeToBytes(self, node): outBytes = [] self.writeInternal(node, outBytes) return outBytes def writeInternal(self, node, data): x = 1 + (0 if node.attributes is None else len(node.attributes) * 2) + (0 if not node.hasChildren() else 1) + (0 if node.data is None else 1) self.writeListStart(1 + (0 if node.attributes is None else len(node.attributes) * 2) + (0 if not node.hasChildren() else 1) + (0 if node.data is None else 1), data) self.writeString(node.tag, data) self.writeAttributes(node.attributes, data); if node.data is not None: self.writeBytes(node.data, data) if node.hasChildren(): self.writeListStart(len(node.children), data); for c in node.children: self.writeInternal(c, data); def writeAttributes(self, attributes, data): if attributes is not None: for key, value in attributes.items(): self.writeString(key, data); self.writeString(value, data); def writeBytes(self, bytes, data): length = len(bytes) if length >= 256: data.append(253) self.writeInt24(length, data) else: data.append(252) self.writeInt8(length, data) for b in bytes: if type(b) is int: data.append(b) else: data.append(ord(b)) def writeInt8(self, v, data): data.append(v & 0xFF) def writeInt16(self, v, data): data.append((v & 0xFF00) >> 8); data.append((v & 0xFF) >> 0); def writeInt24(self, v, data): data.append((v & 0xFF0000) >> 16) data.append((v & 0xFF00) >> 8) data.append((v & 0xFF) >> 0) def writeListStart(self, i, data): if i == 0: data.append(0) elif i < 256: data.append(248) self.writeInt8(i, data) else: data.append(249) self.writeInt16(i, data) def writeToken(self, intValue, data): if intValue < 245: data.append(intValue) elif intValue <=500: data.append(254) data.append(intValue - 245) def writeString(self, tag, data): tok = self.tokenDictionary.getIndex(tag) if tok: index, secondary = tok if secondary: self.writeToken(236, data) self.writeToken(index, data) else: at = '@'.encode() if type(tag) == bytes else '@' try: atIndex = tag.index(at) if atIndex < 1: raise ValueError("atIndex < 1") else: server = tag[atIndex+1:] user = tag[0:atIndex] self.writeJid(user, server, data) except ValueError: self.writeBytes(self.encodeString(tag), data) def encodeString(self, string): res = [] if type(string) == bytes: for char in string: res.append(char) else: for char in string: res.append(ord(char)) return res; def writeJid(self, user, server, data): data.append(250) if user is not None: self.writeString(user, data) else: self.writeToken(0, data) self.writeString(server, data)
""" Tenemos que tener en cuenta: Tenemos dos partes: real e imaginaria Positivo / negativo CON / SIN decimales Ilimitado Podemos mostrar con un guión bajo para leer mejor los miles Podemos trabajar con números cientificos """ x = 34 + 56j y = -34.45 + 56.56j z = -34.45 - 56.56j print(type(x)) print(type(y)) print(type(z)) print("Real: " + str(z.real) + " / Imaginario: " + str(z.imag)) print("Final del programa")
first_name = [ 'Jack', 'Tom', ] second_name = [ 'Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Davis', 'Miller', 'Wilson', 'Moore', 'Taylor', 'Anderson', 'Thomas', 'Jackson', 'White', 'Harris', 'Martin', 'Thompson', 'García', 'Martínez', 'Robinson' ]
''' ## Question ### 4. [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 ''' ## Solutions class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: i = j = 0 k = len(nums1) l = len(nums2) new_array = [] while i < k and j < l: if nums1[i] > nums2[j]: new_array.append(nums2[j]) j = j+1 else: new_array.append(nums1[i]) i = i + 1 while i < k: new_array.append(nums1[i]) i = i + 1 while j < l: new_array.append(nums2[j]) j = j + 1 i = len(new_array) if i%2 == 0: median = new_array[int(i/2)-1] + new_array[int(i/2)] return median/2.0 else: return new_array[int(i/2)]/1.0 # Runtime: 60 ms # Memory Usage: 13.3 MB
# 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. # based on full set of fields payload version 1.0 NODE_MAPPING = { 'dynamic': False, 'properties': { # "id" field does not present in ironic API resource, this is a # copy of "uuid" 'id': {'type': 'string', 'index': 'not_analyzed'}, 'uuid': {'type': 'string', 'index': 'not_analyzed'}, 'name': { 'type': 'string', 'fields': { 'raw': {'type': 'string', 'index': 'not_analyzed'} } }, 'chassis_uuid': {'type': 'string', 'index': 'not_analyzed'}, 'instance_uuid': {'type': 'string', 'index': 'not_analyzed'}, 'driver': {'type': 'string', 'index': 'not_analyzed'}, 'driver_info': {'type': 'object', 'dynamic': True, 'properties': {}}, 'clean_step': {'type': 'object', 'dynamic': True, 'properties': {}}, 'instance_info': {'type': 'object', 'dynamic': True, 'properties': {}}, # mapped "properties" field 'node_properties': { 'type': 'object', 'dynamic': True, 'properties': {} }, 'power_state': {'type': 'string', 'index': 'not_analyzed'}, 'target_power_state': {'type': 'string', 'index': 'not_analyzed'}, 'provision_state': {'type': 'string', 'index': 'not_analyzed'}, 'target_provision_state': {'type': 'string', 'index': 'not_analyzed'}, 'provision_updated_at': {'type': 'date'}, 'maintenance': {'type': 'boolean'}, 'maintenance_reason': {'type': 'string'}, 'console_enabled': {'type': 'boolean'}, 'last_error': {'type': 'string'}, 'resource_class': {'type': 'string', 'index': 'not_analyzed'}, 'inspection_started_at': {'type': 'date'}, 'inspection_finished_at': {'type': 'date'}, 'extra': {'type': 'object', 'dynamic': True, 'properties': {}}, 'network_interface': {'type': 'string', 'index': 'not_analyzed'}, 'created_at': {'type': 'date'}, 'updated_at': {'type': 'date'} } } PORT_MAPPING = { 'dynamic': False, 'properties': { # "id" field does not present in ironic API resource, this is # copy of "uuid" 'id': {'type': 'string', 'index': 'not_analyzed'}, 'uuid': {'type': 'string', 'index': 'not_analyzed'}, # "name" field does not present in ironic API resource, this is a # copy of "uuid" 'name': { 'type': 'string', 'fields': { 'raw': {'type': 'string', 'index': 'not_analyzed'} } }, 'node_uuid': {'type': 'string', 'index': 'not_analyzed'}, 'address': {'type': 'string', 'index': 'not_analyzed'}, 'extra': {'type': 'object', 'dynamic': True, 'properties': {}}, 'local_link_connection': { 'type': 'object', 'properties': { 'switch_id': {'type': 'string', 'index': 'not_analyzed'}, 'port_id': {'type': 'string', 'index': 'not_analyzed'}, 'switch_info': {'type': 'string', 'index': 'not_analyzed'} } }, 'pxe_enabled': {'type': 'boolean'}, 'created_at': {'type': 'date'}, 'updated_at': {'type': 'date'} } } CHASSIS_MAPPING = { 'dynamic': False, 'properties': { # "id" field does not present in ironic API resource, this is a # copy of "uuid" 'id': {'type': 'string', 'index': 'not_analyzed'}, 'uuid': {'type': 'string', 'index': 'not_analyzed'}, # "name" field does not present in ironic API resource, this is a # copy of "uuid" 'name': { 'type': 'string', 'fields': { 'raw': {'type': 'string', 'index': 'not_analyzed'} } }, 'extra': {'type': 'object', 'dynamic': True, 'properties': {}}, 'description': {'type': 'string'}, 'created_at': {'type': 'date'}, 'updated_at': {'type': 'date'} } } NODE_FIELDS = NODE_MAPPING['properties'].keys() PORT_FIELDS = PORT_MAPPING['properties'].keys() CHASSIS_FIELDS = PORT_MAPPING['properties'].keys()
class NodeException(Exception): def __reduce__(self): return type(self), () class NodeStopException(NodeException): pass class RPCError(Exception): def __init__(self, *args, node=None, **kwargs): self.node = node super().__init__(*args, **kwargs) # def __reduce__(self): # return type(self), () class ServiceNotAvailableErr(RPCError): pass class RPCRuntimeException(RPCError): def __init__(self, *args, original=None): super().__init__(*args) self.exception = original class RPCNotFoundError(RPCError): pass class RPCTimeoutError(RPCError): pass class RPCConnectionError(RPCError): pass class RPCConnectionTimeoutError(RPCConnectionError): pass
def remove_protocol(addr): """ Removes the first occurrence of the protocol string ('://') from the string `addr` Parameters ---------- addr : str The address from which to remove the address prefix. Returns ------- str """ name = addr.split("://", 1) # maxsplit = 1... removes only the first occurrence name = ''.join(name[1:]) if len(name) > 1 else addr return name
def compare_with_none(x, y, func): if x is None and y is None: return None elif x is None and y is not None: return y elif x is not None and y is None: return x return func(x, y) def max_with_none(x, y): return compare_with_none(x, y, max) def min_with_none(x, y): return compare_with_none(x, y, min) def get_digits(num): if num == 0: return 1 num = abs(num) digits = 0 while num: digits += 1 num //= 10 return digits
class Node: def __init__(self, data, next=None): self.data = data self.next = next class Queue: def __init__(self, head=None, tail=None): self.head = head self.tail = tail def enqueue(self, data): node = Node(data) if not self.head: self.head = self.tail = node else: last_node = self.tail last_node.next = node self.tail = last_node.next def dequeue(self): if not self.head: raise ValueError("Queue is empty.") elif not self.head.next: deleted_data = self.head.data self.head = self.tail = None else: deleted_data = self.head.data self.head = self.head.next return deleted_data def __repr__(self): print_str = "|Head| -> " node = self.head while node: print_str += str(node.data) + " -> " node = node.next return print_str + "|Tail|" queue = Queue() queue.enqueue(3) print(queue) queue.enqueue(6) print(queue) queue.enqueue(4) print(queue) print(queue.dequeue()) print(queue) print(queue.dequeue()) print(queue) print(queue.dequeue()) print(queue) print(queue.dequeue()) print(queue)
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class ArchivalExternalTarget(object): """Implementation of the 'ArchivalExternalTarget' model. Specifies settings about the Archival External Target (such as Tape or AWS). Attributes: vault_id (long|int): Specifies the id of Archival Vault assigned by the Cohesity Cluster. vault_name (string): Name of the Archival Vault. vault_type (VaultTypeEnum): Specifies the type of the Archival External Target such as 'kCloud', 'kTape' or 'kNas'. 'kCloud' indicates the archival location as Cloud. 'kTape' indicates the archival location as Tape. 'kNas' indicates the archival location as Network Attached Storage (Nas). """ # Create a mapping from Model property names to API property names _names = { "vault_id":'vaultId', "vault_name":'vaultName', "vault_type":'vaultType' } def __init__(self, vault_id=None, vault_name=None, vault_type=None): """Constructor for the ArchivalExternalTarget class""" # Initialize members of the class self.vault_id = vault_id self.vault_name = vault_name self.vault_type = vault_type @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary vault_id = dictionary.get('vaultId') vault_name = dictionary.get('vaultName') vault_type = dictionary.get('vaultType') # Return an object of this model return cls(vault_id, vault_name, vault_type)
class Solution: def optimalDivision(self, nums: List[int]) -> str: nums = list(map(str, nums)) if len(nums) <= 2: return '/'.join(nums) else: return nums[0] + '/(' + '/'.join(nums[1:]) + ')'
"""Top-level package for Aion Client.""" __author__ = """Brent Sanders""" __email__ = 'brent@brentsanders.io' __version__ = '0.4.0'
# # PySNMP MIB module A3COM-AUDL-R1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/A3COM-AUDL-R1-MIB # Produced by pysmi-0.3.4 at Fri Jan 31 21:29:15 2020 # On host bier platform Linux version 5.4.0-3-amd64 by user tin # Using Python version 3.7.6 (default, Jan 19 2020, 22:34:52) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Integer32, ModuleIdentity, NotificationType, Gauge32, Counter32, MibIdentifier, enterprises, Unsigned32, IpAddress, TimeTicks, ObjectIdentity, iso, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Integer32", "ModuleIdentity", "NotificationType", "Gauge32", "Counter32", "MibIdentifier", "enterprises", "Unsigned32", "IpAddress", "TimeTicks", "ObjectIdentity", "iso", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") a3Com = MibIdentifier((1, 3, 6, 1, 4, 1, 43)) brouterMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 2)) a3ComAuditLog = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 2, 29)) a3ComAudlControl = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 2, 29, 1)) a3ComAudlConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 2, 29, 2)) a3ComAudlControlAuditTrail = MibScalar((1, 3, 6, 1, 4, 1, 43, 2, 29, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("auditTrail", 1), ("noAuditTrail", 2))).clone('noAuditTrail')).setMaxAccess("readwrite") if mibBuilder.loadTexts: a3ComAudlControlAuditTrail.setStatus('mandatory') a3ComAudlControlConfig = MibScalar((1, 3, 6, 1, 4, 1, 43, 2, 29, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("config", 1), ("noConfig", 2))).clone('noConfig')).setMaxAccess("readwrite") if mibBuilder.loadTexts: a3ComAudlControlConfig.setStatus('mandatory') a3ComAudlControlMessages = MibScalar((1, 3, 6, 1, 4, 1, 43, 2, 29, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("messages", 1), ("noMessages", 2))).clone('noMessages')).setMaxAccess("readwrite") if mibBuilder.loadTexts: a3ComAudlControlMessages.setStatus('mandatory') a3ComAudlControlSecurity = MibScalar((1, 3, 6, 1, 4, 1, 43, 2, 29, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("security", 1), ("noSecurity", 2))).clone('noSecurity')).setMaxAccess("readwrite") if mibBuilder.loadTexts: a3ComAudlControlSecurity.setStatus('mandatory') a3ComAudlLogServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 43, 2, 29, 2, 1), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: a3ComAudlLogServerAddr.setStatus('mandatory') a3ComAudlPriorityLevel = MibScalar((1, 3, 6, 1, 4, 1, 43, 2, 29, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("log_EMERG", 1), ("log_ALERT", 2), ("log_CRITICAL", 3), ("log_ERROR", 4), ("log_WARNING", 5), ("log_NOTICE", 6), ("log_INFO", 7), ("log_DEBUG", 8))).clone('log_INFO')).setMaxAccess("readwrite") if mibBuilder.loadTexts: a3ComAudlPriorityLevel.setStatus('mandatory') a3ComAudlMaxLog = MibScalar((1, 3, 6, 1, 4, 1, 43, 2, 29, 2, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 30)).clone(10)).setMaxAccess("readwrite") if mibBuilder.loadTexts: a3ComAudlMaxLog.setStatus('mandatory') a3ComAudlIdleTime = MibScalar((1, 3, 6, 1, 4, 1, 43, 2, 29, 2, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 480)).clone(5)).setMaxAccess("readwrite") if mibBuilder.loadTexts: a3ComAudlIdleTime.setStatus('mandatory') mibBuilder.exportSymbols("A3COM-AUDL-R1-MIB", a3ComAudlIdleTime=a3ComAudlIdleTime, a3ComAudlControl=a3ComAudlControl, a3Com=a3Com, a3ComAudlControlMessages=a3ComAudlControlMessages, a3ComAudlLogServerAddr=a3ComAudlLogServerAddr, brouterMIB=brouterMIB, a3ComAudlControlConfig=a3ComAudlControlConfig, a3ComAudlControlSecurity=a3ComAudlControlSecurity, a3ComAudlConfig=a3ComAudlConfig, a3ComAuditLog=a3ComAuditLog, a3ComAudlPriorityLevel=a3ComAudlPriorityLevel, a3ComAudlMaxLog=a3ComAudlMaxLog, a3ComAudlControlAuditTrail=a3ComAudlControlAuditTrail)
#creating empty list lis = [] #enter the number of elements in list noofelements = int(input('How many numbers? ')) # iterating till count to append all input elements in list for n in range(noofelements): number = int(input('Enter number: ')) lis.append(number) # displaying largest number print("Largest number in list is :", max(lis))
#----------------------------------------------------------------------------- # Copyright (c) 2005-2015, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- if __file__ != 'pyi_filename.py': raise ValueError(__file__)
#!/usr/bin/env python class ChatAction(object): TYPING = 'typing' UPLOAD_PHOTO = 'upload_photo' RECORD_VIDEO = 'upload_video' RECORD_AUDIO = 'upload_audio' UPLOAD_DOCUMENT = 'upload_document' FIND_LOCATION = 'find_location'
fin = open('../mbox-short.txt') for line in fin: s = line.strip() if s.startswith('From '): print(s.split()[2])
class Solution: def isAnagram(self, s: str, t: str) -> bool: """ 该题可以等价于字符串1和字符2中的所有字符都可以在对方中找到,且字符串1中字符出现的次数等于字符串2中出现的此数 :param s: :param t: :return: """ tmp1 = {} for i in range(len(s)): tmp1[s[i]] = 1 if s[i] not in tmp1 else tmp1[s[i]] + 1 tmp2 = {} for i in range(len(t)): tmp2[t[i]] = 1 if t[i] not in tmp2 else tmp2[t[i]] + 1 for key in tmp1.keys(): if key not in tmp2 or tmp1[key] != tmp2[key]: return False for key in tmp2.keys(): if key not in tmp1 or tmp1[key] != tmp2[key]: return False return True
project_folder = "/Users/au194693/projects/biomeg_class/" data_folder = project_folder + "data/" class_data = project_folder + "class_data/"
class SubmissionSpreadsheetAlreadyExists(Exception): pass class SubmissionSpreadsheetDoesntExist(Exception): def __init__(self, submission_uuid: str, missing_path: str): super().__init__(f'No spreadsheet found for submission with uuid {submission_uuid}') self.submission_uuid = submission_uuid self.missing_path = missing_path pass
n = input("What days of the week is today ? ") #ask user for todays day of the week if n == "Tuesday": #first possible answer print("Yes, today begins with a T.") elif n == "Thursday": #second possible answer print("Yes, today begins with a T.") else: #any other answer is incorrect then this is an output print("No, today does not begin with a T.")
# Задача: Количество сущностей ''' Условие: Создайте класс User и добавьте способ для проверки количества пользователй (количество сущностей), которые были созданы. Примеры: u1 = User("johnsmith10") User.user_count ➞ 1 u2 = User("marysue1989") User.user_count ➞ 2 u3 = User("milan_rodrick") User.user_count ➞ 3 Также добавьте возможность доступа к имени через атрибуты класса. u1.username ➞ "johnsmith10" u2.username ➞ "marysue1989" u3.username ➞ "milan_rodrick" ''' # Первый Вариант (и последние:)): Успех class User: user_count=0 def __init__(self,u): self.username = u User.user_count+=1 u1 = User("johnsmith10") u2 = User("marysue1989") u3 = User("milan_rodrick") u4 = User("isaacwolf") u5 = User("yura_muchin2808") print(User.user_count) user_nike = u1.username, u2.username, u3.username, u4.username, u5.username print(user_nike)
class OutputTooLargeError(Exception): """Raised when a message is too long to send to Discord""" pass
order = 1 scoopCost = 0.0 extraCost = 0.0 flavScoop = {} toppings = [] print("Welcome to John Doe's famous creamery!") print("~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~") print("Classic Flavors:") print("One scoop: 2/ Two scoop: 3.5") print("Vanilla/ Chocolate/ Strawberry/ Coffee/ Mint") print("~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~") print("Specialty Flavors:") print("One scoop: 2.4/ Two scoop: 4.2") print("FACP/ Caramel/ Lemon Scone/ Beetlejuice") print("~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~") print("Cone Selection:") print("Sugar: 50/ Waffle: 75") print("+ Chocolate : 50/ + ChocSprinkles: 75") print("~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~") print("Topping Selection (25 each):") print("Sprinkles/ Cherries/ Chocolate Syrup/ Strawberry Syrup") print("M&M's/ Oreo/ Salt/ Toffee") c1 = input("What is your first flavor?").lower() c2 = int(input("How many scoops?")) flavScoop[c1] = c2 loop = input("Would you like another flavor?").lower() while loop not in ["no","n","nope"]: loop = input("Would you like another flavor?").lower() c1 = input("What is your next flavor?").lower() c2 = int(input("How many scoops?")) flavScoop[c1] = c2 loop = input("Would you like another flavor?").lower() c3 = input("Cone or bowl?").lower() if c3 == "cone": c4 = input("Sugar or waffle?").lower if c4 == "sugar": extraCost += .50 else: extraCost += .75 dipped = input("Would you like your cone dipped?") if dipped in ["yes","y","sure"]: c5 = input("Chocolate or chocolate with sprinkles?").lower if c5 == "chocolate": extraCost += .50 else: extraCost += .75 loopFrequency = 0 c6 = input("Would you like toppings?").lower while c6 not in ["no","n","nope"]: topping = input("What topping would you like?").lower toppings.append(topping) extraCost += .25 c6 = input("Would you like another topping?") loopFrequency += 1 for c1 in flavScoop: if c1 in ["vanilla" , "chocolate" , "strawberry" , "coffee" , "mint"]: if c2 % 2 == 0: scoopCost += float(c2) * 1.75 else: scoopCost += float(c2 - 1) * 1.75 + 2.0 else: if c2 % 2 == 0: scoopCost += float(c2) * 2.1 else: scoopCost += float(c2 - 1) * 2.1 + 2.4 for c1 in flavScoop: print("You ordered "+ str(c2) +" scoop(s) of "+ c1 +".") print("Your ice cream came with "+ str(loopFrequency) +" topping(s).") for i in range(loopFrequency): print("You asked for extra "+ str(toppings[i]) +".") print("Your total is: "+ str(extraCost + scoopCost))
number1 = 10 number2 = 20 number4 = 40 number3 = 30
n = bool(input('Digite um número. Se for não digitar vai dar falso: ')) print(n) n = (input('Digite algo: ')) print(n.isnumeric()) n = (input('Digite algo ')) print(n.upper()) n = (input('Digite algo ')) print(n.isalpha())
# -*- coding: utf-8 -*- __author__ = 'Michael Ingrisch' __email__ = 'michael.ingrisch@gmail.com' __version__ = '0.1.0'
""" Entradas mesanterior->int-->mesant kwhmesanterior-->float-->kwhgas kwhmesactual-->float-->kwsact salidas total-->int-->dinerototal """ #entrada mesant=int(input("ingrese monto pagado en el mes anterior: ")) kwhgas=float(input("digite kWh Gastados en el mes anterior: ")) kwsact=float(input("ingrese lectura actual de kWh: ")) #caja negra precio1kwh=(kwhgas/mesant) pagoactual=(precio1kwh*kwsact) #salidas print("el monto total a pagar es: ""{:.0F}".format(pagoactual))
i = 0 print(i) def test(): global i i = i+1 print(i) test() print(i)
# gameresults.py # Copyright 2008 Roger Marsh # Licence: See LICENCE (BSD licence) """Constants used in the results of games. """ # Game score identifiers. # h... refers to first-named player usually the home player in team context. # a... refers to second-named player usually the away player in team context. # No assumption is made about which player has the white or black pieces. hwin = "h" awin = "a" draw = "d" hdefault = "hd" adefault = "ad" doubledefault = "dd" drawdefault = "=d" hbye = "hb" abye = "ab" hbyehalf = "hbh" abyehalf = "abh" tobereported = None void = "v" notaresult = "not a result" defaulted = "gd" # Commentary on printed results tbrstring = "to be reported" # ECF score identifiers. # Results are reported to ECF as '10' '01' or '55'. # Only hwin awin and draw are reported. ecfresult = {hwin: "10", awin: "01", draw: "55"} # Particular data entry modules may wish to use their own versions # of the following maps. # But all must use the definitions above. # Display score strings. # Results are displayed as '1-0' '0-1' etc. # Use is "A Player 1-0 A N Other". displayresult = { hwin: "1-0", awin: "0-1", draw: "draw", hdefault: "1-def", adefault: "def-1", doubledefault: "dbldef", hbye: "bye+", abye: "bye+", hbyehalf: "bye=", abyehalf: "bye=", void: "void", drawdefault: "drawdef", defaulted: "defaulted", } # Score tags. Comments displayed after a game result. # Use is "A Player A N Other to be reported". displayresulttag = { tobereported: tbrstring, notaresult: notaresult, } # Map of all strings representing a result to result. # Where the context implies that a string is a result treat as "void" # if no map exists i.e. resultmap.get(resultstring, resultmap['void']). # resultstring may have been initialised to None and not been set. # Thus the extra entry None:tobereported. resultmap = { "1-0": hwin, "0-1": awin, "draw": draw, "void": void, "tbr": tobereported, "": tobereported, None: tobereported, "def+": hdefault, "def-": adefault, "dbld": doubledefault, "def=": drawdefault, "default": defaulted, } # Map game results to the difference created in the match score match_score_difference = { hwin: 1, awin: -1, draw: 0, hdefault: 1, adefault: -1, doubledefault: 0, drawdefault: 0, hbye: 1, abye: -1, hbyehalf: 0.5, abyehalf: -0.5, tobereported: 0, void: 0, notaresult: 0, } # Map game results to the contribution to the total match score match_score_total = { hwin: 1, awin: 1, draw: 1, hdefault: 1, adefault: 1, doubledefault: 0, drawdefault: 0.5, hbye: 1, abye: 1, hbyehalf: 0.5, abyehalf: 0.5, tobereported: 0, void: 0, notaresult: 0, } # Games with following results are stored on database # Maybe move to gameresults # Not sure if the mapping is needed _loss = "0-1" _draw = "draw" _win = "1-0" _storeresults = {awin: _loss, draw: _draw, hwin: _win} # Duplicate game report inconsistency flags NULL_PLAYER = "null" HOME_PLAYER_WHITE = "home player white" RESULT = "result" BOARD = "board" GRADING_ONLY = "grading only" SOURCE = "source" SECTION = "section" COMPETITION = "competition" HOME_TEAM_NAME = "home team name" AWAY_TEAM_NAME = "away team name" HOME_PLAYER = "home player" AWAY_PLAYER = "away player" ROUND = "round" GAME_COUNT = "game count" MATCH_SCORE = "match and game scores in earlier reports" ONLY_REPORT = "match and game scores in only report" AUTHORIZATION = "authorization"
username = None password = None first_run = True port = "22" password_len = 50 connections = {} ssh_host_pwd_map = {} ssh_config_keys = ('HostName', 'User', 'Port', 'IdentityFile') use_ssh_config = False ssh_config_path = None keepass_db_path = None keepass_pwd = None
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: def iterr(root): if not root : return root if root.val>high: return iterr(root.left) elif root.val<low: return iterr(root.right) else: root.left=iterr(root.left) root.right=iterr(root.right) return root return iterr(root)
def upl(s): upper = 0 lower = 0 for i in s: if i.isupper(): upper += 1 elif i.islower(): lower += 1 print(f'No. of Upper case characters : {upper}') print(f'No. of Lower case characters : {lower}') upl("sss sss sss S")
class Player: def __init__(self): self.name = "TeamOne" self.prec = {} self.prec['3'] = 1 self.prec['4'] = 2 self.prec['5'] = 3 self.prec['6'] = 4 self.prec['7'] = 5 self.prec['8'] = 6 self.prec['9'] = 7 self.prec['10'] = 8 self.prec['J'] = 9 self.prec['Q'] = 10 self.prec['K'] = 11 self.prec['A'] = 12 self.prec['2'] = 13 pass def newGame(self, hand1, hand2, opponent): self.myHand = hand1 self.yourHand = hand2 self.opponent = opponent def beat(self, t, yt): if len(t) == 1 and len(yt) == 1 : return self.prec[t[0]] > self.prec[yt[0]] return not yt def play(self, t): for c in t: self.yourHand.remove(c) if not self.myHand: return [] if not t: return [self.myHand[0]] if len(t) == 1: for c in self.myHand: if self.beat([c], t): return [c] return [] def ack(self, t): #print("ack: {}".format(self.myHand)) for c in t: self.myHand.remove(c) def teamName(self): return self.name
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ res = [] self.generate('', n, n, res) return res def generate(self, v, left, right, res): if left == 0: res.append(v + ')' * right) return self.generate(v + '(', left - 1, right, res) if left != right: self.generate(v + ')', left, right - 1, res) def test_generate_parenthesis(): s = Solution() assert ["()"] == s.generateParenthesis(1) r = s.generateParenthesis(2) assert 2 == len(r) assert "(())" in r assert "()()" in r
''' https://leetcode.com/contest/weekly-contest-155/problems/minimum-absolute-difference/ ''' class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() min_diff = 10**7 for i in range(1, len(arr)): min_diff = min(min_diff, arr[i] - arr[i - 1]) sarr = set(arr) return [[a, a + min_diff] for a in arr if a + min_diff in sarr]
print("Let's practice everything.") print('You\'d need to know \'bout escapes with \\ that do:') print('\n new lines and \t tabs.') poem= """ \t The lovely world with logic so firmly planted cannot discern \n the needs of love nore comprehend passion from intutiion and requires an explanation \n \t \t where there is none. """ print("--------------") print(poem) print("--------------") five = 10-2+3-6 print(f"This should be five: {five}") def secret_formula(started): jelly_beans= started *500 jars= jelly_beans/1000 crates = jars/100 return jelly_beans, jars, crates start_point=10000 beans, jars, crates = secret_formula(start_point) #remember that this is another way to format a string print("with a starting point of: {}".format(start_point)) #it's just like with a f"" string print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.") start_point= start_point/10 print("We can also do that this way:") formula=secret_formula(start_point) #this is an easy way to apply a list to a format string print("We'd have {} beans, {} jars, and {} crates".format(*formula))
SECRET_KEY = 'dev' SITES_DICT = { 'www.iie.cas.cn': 'xgs', 'www.is.cas.cn': 'rjs', } ############################################### MYSQL_HOST = 'localhost' MYSQL_PORT = 6761 MYSQL_DB_NAME = 'crawling_db' MYSQL_USER = 'root' MYSQL_PASSWORD = 'mysql' ############################################### SCRAPY_PATH = '../ScrapyBased/'
#!/usr/bin/env python # -*- coding: utf-8 -*- """ config_file_test.py Tests for the config_file module. Created by Chandrasekhar Ramakrishnan on 2015-08-08. Copyright (c) 2015 Chandrasekhar Ramakrishnan. All rights reserved. """ def test_config_basics(smet_bundle): config = smet_bundle.config assert config is not None race_configs = config.race_configs assert len(race_configs) == 1 chicago = race_configs[0] assert chicago['race'] == "Chicago Mayor Runoff 2015" assert chicago['year'] == '2015' candidates = chicago['candidates'] assert len(candidates) == 2 rahm = candidates[0] assert rahm['name'] == 'Rahm Emanuel' chuy = candidates[1] assert len(chuy['search']) == 2 def test_creds_basics(smet_bundle): creds = smet_bundle.credentials assert creds is not None assert creds.app_key == 'an_app_key_string' assert creds.access_token == 'an_access_token_string'
print("\nYou are alone in the frigged woods of a hidden country.\nYou where sent here by the CLIA (Central Linux Intelligence Authority) to find out about this new world.\nYou have a computer running Servbuntu v.0.0.1 with a IRC server which you plan to contact the CLIA with.\nIt is off\nThe night is getting colder and you need help") def end_game(reason): exit(reason) class q: def fasas(): fasa = input("\nWhat would you like to do? [start a fire/turn on the computer]: ").lower() if(fasa == "start a fire"): print("\nYou look around and find no wood") q.knkls() elif(fasa == "turn on the computer"): print("\nThe computer is too cold to start\nYou have lost your last way to find help") end_game("You die of hypothermia") else: print("Command not understood!") q.fasas() def knkls(): knkl = input("What would you like to do? [find wood/turn on the computer]: ").lower() if(knkl == "find wood"): print("\nYou walk into the forest bringing you computer with you\nEventually you find wood, but you also find a strange badge that looks simmilair to the following:") print(""" ,-~¨^ ^¨-, _, / / ;^-._...,¨/ / / / / / / / / / / / / /,.-:''-,_ / / / _,.-:--._ ^ ^:-._ __../ /^ / /¨:.._¨__.; / / / ^ / / / / / / / / / /_,.--:^-._/ / / ^ ^¨¨-.___.:^""") q.llls() elif(knkl == "turn on the computer"): print("\nThe computer is too cold to start\nYou have lost your last way to find help") end_game("You die of hypothermia") else: print("Command not understood!") q.knkls() def llls(): lll = input("What would you like to do? [sus it out/take the wood]: ").lower() if(lll == "sus it out"): print("\nYou spend hours in a fruitless search and you are about to turn around when you see a logo:") print(""" .8 .888 .8888' .8888' 888' 8' .88888888888. .88888888888. .8888888888888888888888888888888. .8888888888888888888888888888888888. .&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&' &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&' &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%. `%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%. `00000000000000000000000000000000000' `000000000000000000000000000000000' `0000000000000000000000000000000' `###########################' `#######################' `#########''########' `\"\"\"\"\"\"' `\"\"\"\"\"\'""") q.sdfbs() elif(lll == "take the wood"): print("\nYou take the wood and successfully start a fire\nYou turn on the computer and make it back home safely.") end_game("The CLIA is very disappointed in you but at least you live to tell the tale.") else: print("Command not understood!") q.llls() def sdfbs(): sdfb = input("What would you like to do? [continue search/go back]: ").lower() if(sdfb == "continue search"): print("\nYou continue your search until you find a corparate looking building bearing the flag of the first badge.") q.sutfs() elif(sdfb == "go back"): print("\nYou take the wood and successfully start a fire\nYou turn on the computer and make it back home safely.") end_game("The CLIA is very disappointed in you but at least you live to tell the tale.") else: print("Command not understood!") q.sdfbs() def sutfs(): sutf = input("What would you like to do? [enter/go back]: ").lower() if(sutf == "enter"): end_game("You enter and immediately have all your rights and freedoms taken away.\nLike ruthless animals the employees enslave you and force you to develop their OS which in anti-trust levels they force people to use.") elif(sutf == "go back"): print("\nYou take the wood and successfully start a fire\nYou turn on the computer and make it back home safely.") end_game("The CLIA is very disappointed in you but at least you live to tell the tale.") else: print("Command not understood!") q.sutfs() q.fasas()
# Create a recursive method that mirrors how a # factorial would work in math. def factorial(n): if n == 0: # add here and remove "pass" pass else: # add here and remove "pass" pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 15 09:40:31 2021 @author: martin # This script converts the imperial units for fuel salt and coolant salt of # the MSRE into metric units. Parameters are taken from (bibtex): @article{osti_4676587, title = {MOLTEN-SALT REACTOR PROGRAM SEMIANNUAL PROGRESS REPORT FOR PERIOD ENDING JULY 31, 1964}, author = {Briggs, R. B.}, abstractNote = {}, doi = {10.2172/4676587}, url = {https://www.osti.gov/biblio/4676587}, journal = {}, number = , volume = , place = {United States}, year = {1964}, month = {11} } found here (https://www.osti.gov/biblio/4676587-molten-salt-reactor-program-semiannual-progress-report-period-ending-july) or here (https://energyfromthorium.com/pdf/ORNL-3708.pdf) """ class Constants(): def __init__(self): self.btu_to_J = 1055.06 self.lb_to_g = 453.59237 self.ft_to_m = 0.3048 self.Delta_F_to_Delta_K = 5/9 self.hour_to_s = 60*60 def FahrenheitToCelsius(T_F): return (T_F-32)*5/9 def ImperialDensityToMetric(density_lb_per_ft3): const = Constants() density_g_per_cm3 = const.lb_to_g/(const.ft_to_m*100)**3*density_lb_per_ft3 return density_g_per_cm3 def ImperialHeatCapacityToJ_per_g_K(heat_capacity_Btu_per_lb_F): const = Constants() heat_capacity_imperial_to_J_per_g_K = const.btu_to_J/(const.lb_to_g*const.Delta_F_to_Delta_K) return heat_capacity_Btu_per_lb_F*heat_capacity_imperial_to_J_per_g_K def ImperialThermalConductivityTo_W_per_m_K(thermal_conductivity_Btu_per_ft_hr_F): const = Constants() thermal_conductivity_W_per_m_K = thermal_conductivity_Btu_per_ft_hr_F*const.btu_to_J/(const.ft_to_m*const.hour_to_s*const.Delta_F_to_Delta_K) return thermal_conductivity_W_per_m_K class salt(): def __init__(self,name,composition,liquidus_temperature_F,physical_properties_temperature_F,density_lb_per_ft3,heat_capacity_Btu_per_lb_F,viscosity_cP,thermal_conductivity_Btu_per_ft_hr_F): self.name = name self.composition = composition self.liquidus_temperature_F = liquidus_temperature_F # degrees F self.physical_properties_temperature_F = physical_properties_temperature_F self.density_lb_per_ft3 = density_lb_per_ft3 self.heat_capacity_Btu_per_lb_F = heat_capacity_Btu_per_lb_F self.viscosity_cP = viscosity_cP self.thermal_conductivity_Btu_per_ft_hr_F = thermal_conductivity_Btu_per_ft_hr_F self.liquidus_temperature_C = FahrenheitToCelsius(liquidus_temperature_F) self.physical_properties_temperature_C = FahrenheitToCelsius(physical_properties_temperature_F) self.density_g_per_cm3 = ImperialDensityToMetric(density_lb_per_ft3) self.heat_capacity_J_per_g_K = ImperialHeatCapacityToJ_per_g_K(heat_capacity_Btu_per_lb_F) self.viscosity_mPa_s = viscosity_cP self.thermal_conductivity_W_per_m_K = ImperialThermalConductivityTo_W_per_m_K(self.thermal_conductivity_Btu_per_ft_hr_F) self.volumetric_heat_capacity_J_per_cm3_K = self.heat_capacity_J_per_g_K*self.density_g_per_cm3 def PrintMetricParameters(self): print(self.name) print('composition = {}'.format(self.composition)) print('liquidus_temperature = {:.2f} degree C'.format(self.liquidus_temperature_C)) print('physical_properties_temperature = {:.2f} degree C'.format(self.physical_properties_temperature_C)) print('density = {:.3f} g/cm^3'.format(self.density_g_per_cm3)) print('heat_capacity = {:.3f} J/(g K)'.format(self.heat_capacity_J_per_g_K)) print('viscosity = {:.3f} mPa s'.format(self.viscosity_mPa_s)) print('thermal_conductivity = {:.3f} W/(m K)\n'.format(self.thermal_conductivity_W_per_m_K)) fuel_salt = salt(name = 'fuel_salt', composition='LiF-BeF2-ZrF4-UF4 (65-29.1-5-0.9 mole %)', liquidus_temperature_F = 842, physical_properties_temperature_F = 1200, density_lb_per_ft3 = 146, heat_capacity_Btu_per_lb_F = 0.455, viscosity_cP = 7.6, thermal_conductivity_Btu_per_ft_hr_F = 3.2,) coolant_salt = salt(name = 'coolant_salt', composition='LiF-BeF2 (66-34 mole %)', liquidus_temperature_F = 851, physical_properties_temperature_F = 1062, density_lb_per_ft3 = 120.5, heat_capacity_Btu_per_lb_F = 0.526, viscosity_cP = 8.3, thermal_conductivity_Btu_per_ft_hr_F = 3.5) if __name__ == "__main__": fuel_salt.PrintMetricParameters() coolant_salt.PrintMetricParameters()
# # Copyright 2021 Splunk 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. # """Default config for cloud connect""" timeout = 120 # request timeout is two minutes disable_ssl_cert_validation = False # default enable SSL validation success_statuses = (200, 201) # statuses be treated as success. # response status which need to retry. retry_statuses = (429, 500, 501, 502, 503, 504, 505, 506, 507, 509, 510, 511) # response status which need print a warning log. warning_statuses = ( 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 306, 307, 308, ) retries = 3 # Default maximum retry times. max_iteration_count = 100 # maximum iteration loop count charset = "utf-8" # Default response charset if not found in response header
def sortNums(nums): counts = {} for n in nums: counts[n] = counts.get(n, 0) + 1 return ([1] * counts.get(1, 0) + counts.get(2, 0) + counts.get(3, 0)) def sortNums2(nums): one_index = 0 three_index = len(nums) - 1 index = 0 while index <= three_index: if nums[index] == 1: nums[index], nums[one_index] = nums[one_index], nums[index] one_index += 1 index += 1 if nums[index] == 2: one_index += 1 if nums[index] == 3: nums[index], nums[three_index] = nums[three_index], nums[index] three_index -= 1 return nums
_base_ = [ '../cascade_rcnn/cascade_rcnn_x101_64x4d_fpn_20e_coco.py' ] dataset_type = 'DefectDataset' classes = ( "边异常", "角异常", "白色点瑕疵", "浅色块瑕疵", "深色点块瑕疵", "光圈瑕疵" ) data_root = '/media/samba/weiqiang/Datasets/dataset/' data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict( type=dataset_type, classes=classes, data_root=data_root + 'tile_round1_train_20201231/', ann_file=data_root + 'tile_round1_train_20201231/train_annos.json', img_prefix=data_root + 'tile_round1_train_20201231/train_imgs/', ), val=dict( type=dataset_type, classes=classes, data_root=data_root + 'tile_round1_train_20201231/', ann_file=data_root + 'tile_round1_train_20201231/train_annos.json', img_prefix=data_root + 'tile_round1_train_20201231/train_imgs/', ), test=dict( type=dataset_type, classes=classes, data_root=data_root + 'tile_round1_testA_20201231/', ann_file=None, img_prefix=data_root + 'tile_round1_testA_20201231/testA_imgs/', ), ) model = dict( roi_head=dict( bbox_head=[ dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=6, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=6, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=6, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) ] ) ) optimizer = dict( lr=0.02/4, ) evaluation = dict( metric='mAP', ) load_from = 'checkpoints/cascade_mask_rcnn_x101_64x4d_fpn_20e_coco_20200512_161033-bdb5126a.pth'
# automatically generated by the FlatBuffers compiler, do not modify # namespace: DeepSeaVectorDraw class FillRule(object): EvenOdd = 0 NonZero = 1
# Error List def ImportLib(): raise RuntimeError("\n\n>> Erro ao importar biblioteca: Verifique se as bibliotecas do sistema estão instaladas e execute o programa novamente.`")
class Solution: def isIsomorphic(self, s, t): if len(s) != len(t): return False s2t, t2s = {}, {} for p, w in zip(s, t): if p not in s2t and w not in t2s: s2t[p] = w t2s[w] = p elif p not in s2t or s2t[p] != w: return False return True if __name__ == "__main__": s = "badc" t = "baba" g = Solution() print(g.isIsomorphic(s, t))
class Population: """ Class contians info on population of candidate solutions Instance Members : ---------------- population_size : int members : List containing the members of population new_members : List containing members of population after each iteration Methods : ---------- createMembers() : Generates initial members of population by invoking one of the methods from ChromosomeFactory.py module """ def __init__(self,factory,population_size): self.population_size = population_size self.members = [] self.new_members = [] self.createMembers(factory) def createMembers(self,factory): """ Generates initial members of population by invoking one of the methods from ChromosomeFactory.py module Parameters : ------------- factory : Reference to a method from ChromosomeFactory.py module """ for i in range(self.population_size): self.members.append(factory.createChromosome())
word=input().lower() summ=0 d=0 L=list(word) for ele in L: num=int(ord(ele)-96) summ+=num for i in range (0,summ): if i*(i+1)/2==summ: print("triangle word") d+=1 if d==0: print("not a triangle word")
class Solution(object): def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ ticketmap = {} self.tickets = tickets for f, t in tickets: if f not in ticketmap: ticketmap[f] = [t] else: ticketmap[f].append(t) for k, v in ticketmap.items(): v.sort() return self.recurse(ticketmap, "JFK", ["JFK"]) def recurse(self, tmap, start, it): if len(it) == len(self.tickets) + 1: return it if start not in tmap or not tmap[start]: return None for i, next in enumerate(tmap[start]): del tmap[start][i] r = self.recurse(tmap, next, it[:] + [next]) if r: return r else: tmap[start].insert(i, next) return None
def get_close_sim_for_box(sim): def func(): sim.close() return func class Simulation: def __init__(self): self.boxes = {} self.signals = {} self.advance_order = [] self.running = False def __str__(self): return 'Simulation' def print_diagram(self): for box_key in self.advance_order: for signal_key in self.boxes[box_key].inputs_keys: print(self.signals[signal_key]) print(self.boxes[box_key]) for signal_key in self.boxes[box_key].outputs_keys: print(self.signals[signal_key]) def add_box(self, box, initial_signals_dict={}): # add a box, check correct signals, consider order of forward # With each box, signals are created for each output # Total: # initial existing signals # add box -> create new signals with initial values # add to position on in adavane order (somehow) if type(box) is not SimulationBox and \ not issubclass(type(box), SimulationBox): raise Exception( "'box' argument must be of class " + "'SimulationBox' or inherit from it") if box.key in self.boxes: raise Exception( "key of box is already used, please use a unique key... ") # add box to boxes self.boxes[box.key] = box self.advance_order.append(box.key) # add input signals for signal_key in box.inputs_keys: # verify: signals exist # if dont exist, then must have intial value if signal_key not in self.signals: if signal_key not in initial_signals_dict: raise Exception(f"if '{signal_key}' hasn't been added, " + "then inital values must be provided") if (not isinstance( initial_signals_dict[signal_key], float) and not isinstance( initial_signals_dict[signal_key], int)): raise Exception("inital values must be 'int' or 'float'") self.signals[signal_key] = SimulationSignal( signal_key, None, initial_values=initial_signals_dict[signal_key]) for signal_key in box.outputs_keys: # verify signals dont exist # if exist, check if origin is None (edit), else raise error if signal_key in self.signals: if self.signals[signal_key].origin_box_key is not None: raise Exception( f"signal '{signal_key}' already has origin...") print(f"signal {signal_key} already in...") self.signals[signal_key].origin_box_key = box.key else: self.signals[signal_key] = SimulationSignal( signal_key, box.key) print(f"new signal {signal_key} created...") def advance(self): signals_dict = { s_key: self.signals[s_key].value for s_key in self.signals} # print('signals_dict', signals_dict) for box_key in self.advance_order: # print(box_key, 'signals_dict', signals_dict) outputs = self.boxes[box_key].advance(signals_dict) # print(box_key, 'outputs', outputs) for signal_key in outputs: self.signals[signal_key].update_value(outputs[signal_key]) signals_dict[signal_key] = outputs[signal_key] def run(self): iteration = 0 self.running = True while self.running: # print(f'it: {iteration}') self.advance() iteration += 1 def close(self): self.running = False class SimulationBox: def __init__(self, key, inputs_keys, outputs_keys): self.key = key self.inputs_keys = inputs_keys self.outputs_keys = outputs_keys def __str__(self): return '({})\t -> \t[{}]\t -> \t({})'.format( ';\t'.join(self.inputs_keys), self.key, ';\t'.join(self.outputs_keys) ) def advance(self, input_values): # uses values of signals # returns values of output signals for i_key in self.inputs_keys: if i_key not in input_values: raise Exception( "'input_values' must include box's input keys") return {} class SimulationSignal: def __init__(self, key, origin_box_key, initial_values=None): self.key = key self.origin_box_key = origin_box_key self.initial_values = initial_values self.value = initial_values def update_value(self, value): self.value = value def __str__(self): return 'S([{}] -> {})'.format( self.origin_box_key, self.key )
# Server id server_id = 90564452600745770 # Role assigned by default to every member that joins. # Set it to `None` to not assign any role. default_role = 'Test' # Role name or None. # Roles that can be assigned with the `role` command. assignable_roles = ['Test'] # List of role names. welcome_channel_id = 201392153884694762 # Channel id role_codes = { 'secret_code': 749046557054301980 # Role id. }
# -*- coding: utf-8 -*- """ Tests for the model. """ __author__ = 'Yves-Noel Weweler <y.weweler@fh-muenster.de>'
valores = [] valoresPares = [] valoresImpares = [] while True: valores.append(int(input('Digite um número: '))) condicao = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if condicao == 'N': break elif condicao == 'S': continue else: condicao = str(input('ERRO! Digite SIM ou NÃO! : ')).strip().upper()[0] for i, valor in enumerate(valores): if valor % 2 == 0: valoresPares.append(valor) else: valoresImpares.append(valor) print('==-' * 10) print(f'A lista completa é {valores}') print(f'A lista de pares é {valoresPares}') print(f'A lista de ímpares é {valoresImpares}')
angou = "he.elk.set.to" kaidoku = angou.split("e") print(kaidoku[-1])
class Error(Exception): """Base class for other customized errors.""" pass class StockNotFoundError(Error): """Raised when the desired stock is not found within the currently recognized stocks in the system.""" pass class InsufficientFundsError(Error): """Raised when the player does not have enough liquid cash to buy the stocks or to pay the required taxes.""" pass class NotEnoughAssetsError(Error): """Raised when the player does not have enough assets to sell.""" pass class InvalidValueError(Error): """Raised when an invalid value is submitted.""" pass class IncompatibleSettingError(Error): """Raised when a setting value is incompatible with another setting value.""" pass
""" Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. Example : Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. Rain water trapped: Example 1 The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. """ class Solution: # @param A : tuple of integers # @return an integer def trap(self, arr): l = len(arr) lmax = [0] * l rmax = [0] * l water = 0 lmax[0] = arr[0] for i in xrange(1, l): if arr[i] > lmax[i - 1]: lmax[i] = arr[i] else: lmax[i] = lmax[i - 1] rmax[l - 1] = arr[l - 1] for i in xrange(l - 2, -1, -1): if arr[i] > rmax[i + 1]: rmax[i] = arr[i] else: rmax[i] = rmax[i + 1] for i in xrange(l): water += min(lmax[i], rmax[i]) - arr[i] return water
"""Top level description of your module.""" class TemplateClass(object): """ The template class does nothing. See https://numpydoc.readthedocs.io/en/latest/format.html. For how this docstring is layed out. Attributes ---------- foo : int A useless attribute. bar : int Another useless attribute. Parameters ---------- foo : float, optional The first number to multiply by, default is 0 bar : float, optional The second number to multiply by, default is 0 Methods ------- __add__(self, other) return (self.foo * self.bar) + (other.foo * other.bar) """ def __init__(self, foo=0, bar=0): """See your_package.your_module.TemplateClass.""" self.bar = bar self.foo = foo def __add__(self, other): return (self.foo * self.bar) + (other.foo * other.bar)
""" Using a search cursor to print all the feature classes in our PGH.gdb Writing the name of the gdb and all its feature classes to a text file """ # Import modules # Set variables # Execute operation(s)
# Aula 07 - Desafio 15: Aluguel de carros # Ler os Km rodados por um carro alugado e quantos dias ficou alugado e calcular o valor a ser pago # O valor do aluguel por dia é R$60,00 e o valor por KM rodado é R$0,15 d = int(input('Informe a quantidade de dias em que o carro ficou alugado: ')) km = int(input('Informe quanto Km foram percorridos nesse periodo: ')) p = d * 60 + km * 0.15 print(f'O valor a ser pago pelo aluguel no periodo de {d} dias com {km}km rodados eh de R${p:.2f}')
""" Constants used by the protocol """ # messages MSG_REQUEST = 1 MSG_REPLY = 2 MSG_EXCEPTION = 3 # boxing LABEL_VALUE = 1 LABEL_TUPLE = 2 LABEL_LOCAL_REF = 3 LABEL_REMOTE_REF = 4 # action handlers HANDLE_PING = 1 HANDLE_CLOSE = 2 HANDLE_GETROOT = 3 HANDLE_GETATTR = 4 HANDLE_DELATTR = 5 HANDLE_SETATTR = 6 HANDLE_CALL = 7 HANDLE_CALLATTR = 8 HANDLE_REPR = 9 HANDLE_STR = 10 HANDLE_CMP = 11 HANDLE_HASH = 12 HANDLE_DIR = 13 HANDLE_PICKLE = 14 HANDLE_DEL = 15 HANDLE_INSPECT = 16 HANDLE_BUFFITER = 17 HANDLE_OLDSLICING = 18 HANDLE_CTXEXIT = 19 # optimized exceptions EXC_STOP_ITERATION = 1 # DEBUG #for k in globals().keys(): # globals()[k] = k
DEBUG = True SLACK_POST_URL = "https://slack.com/api/chat.postMessage" SLACK_TOKEN = "" WEATHER_TOKEN = "" WEATHER_URL = "https://api.openweathermap.org/data/2.5/weather?q={text}&appid={token}"
numero = int(input('digite um número')) for multiplo in range(1, 11): # print(numero) # print(multiplo) print('{} = {} vezes {}'.format(numero * multiplo, numero, multiplo)) # print(numero * multiplo, '=', numero, 'vezes', multiplo) # a1 = n*1 # a2 = n*2 # a3 = n*3 # a4 = n*4 # a5 = n*5 # a6 = n*6 # a7 = n*7 # a8 = n*8 # a9 = n*9 # a10 = n*10 # # for n in range(1, 2): # print(a1) # print(a2) # print(a3) # print(a4) # print(a5) # print(a6) # print(a7) # print(a8) # print(a9) # print(a10)
# -*- coding: utf-8 -*- def main(): n, t = map(int, input().split()) ans = n remain = t diff = [0 for _ in range(n)] for i in range(n): ai, bi = map(int, input().split()) remain -= bi diff[i] = ai - bi if remain < 0: print(-1) else: for d in sorted(diff): remain -= d if remain >= 0: ans -= 1 else: print(ans) exit() print(ans) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- lights = ["red","yellow","pink"] currentLight = lights[2] print(currentLight) if currentLight == "red": print("STOP!") elif currentLight == "yellow": #elif i değilse gibi düşünebiliriz. print("READY!") else: #if ve elifle bi işlem gerçekleşmezse else kullanılır. print("GO!")