content
stringlengths
7
1.05M
word1 = input() word2 = input() # How many letters does the longest word contain? len_word1 = len(word1) len_word2 = len(word2) max_len = 0 if len_word1 >= len_word2: max_len = len_word1 else: max_len = len_word2 print(max_len)
def _(line): new_indent = 0 for section in line: if (section != ''): break new_indent = new_indent + 1 return new_indent
class Something: def __eq__(self, other: object) -> bool: pass class Reference: pass __book_url__ = "dummy" __book_version__ = "dummy" associate_ref_with(Reference)
""" # COURSE SCHEDULE II There are a total of n courses you have to take labelled from 0 to n - 1. Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai. Given the total number of courses numCourses and a list of the prerequisite pairs, return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai, bi < numCourses ai != bi All the pairs [ai, bi] are distinct. """ class Solution: def __init__(self): self.flag = True def findOrder(self, numCourses: int, prerequisites): d = {} for x in prerequisites: if x[0] not in d: d[x[0]] = [x[1]] else: d[x[0]].append(x[1]) perm = [] for x in range(numCourses): temp = set() if x in perm: continue self.check(x, perm, temp, d) if not self.flag: return [] return perm def check(self, n, perm, temp, d): if n in perm: return if n in temp: self.flag = False return temp.add(n) if n in d: for m in d[n]: self.check(m, perm, temp, d) temp.remove(n) perm.append(n)
class RSI(object): def __init__(self, OHLC, period): self.OHLC = OHLC self.period = period self.gain_loss = self.gain_loss_calc() def gain_loss_calc(self): data = self.OHLC["close"] gain_loss = [] for i in range(1, len(data)): change = float(data[i]) - float(data[i-1]) if change >= 0: gain_loss.append({"gain": change, "loss": 0}) else: gain_loss.append({"gain": 0, "loss": abs(change)}) return gain_loss def first_avg_calc(self): gain_loss = self.gain_loss gain = 0 loss = 0 for i in range(0, self.period): gain += gain_loss[i]["gain"] loss += gain_loss[i]["loss"] gain = gain / self.period loss = loss / self.period return {"gain": gain, "loss": loss} def rsi_calc(self): gain_loss = self.gain_loss prev_avg_gain_loss = self.first_avg_calc() avg_gain = 0 avg_loss = 0 for i in range(self.period, len(gain_loss)): avg_gain = ((prev_avg_gain_loss["gain"] * (self.period - 1)) + gain_loss[i]["gain"]) / self.period prev_avg_gain_loss["gain"] = avg_gain avg_loss = ((prev_avg_gain_loss["loss"] * (self.period - 1)) + gain_loss[i]["loss"]) / self.period prev_avg_gain_loss["loss"] = avg_loss rs = avg_gain / avg_loss rsi = 100 - (100 / (1 + rs)) return rsi
class Recipe(object): """ This class provides a Recipe for an Order. It is a list (or dictionary) of tuples (str machineName, int timeAtMachine). """ def __init__(self): """ recipe is a list (or dictionary) that contains the tuples of time information for the Recipe. """ self.recipe = [] def indexOfMachine(self, machineName): """ Returns the index of the Machine with machineName in the recipe list. """ for i, r in enumerate(self.recipe): if r[0] == machineName: return i return -1 def calcMinProcTime(self, plant, machineName = None): """ This method calculates the minimum processing time of the Recipe starting from Machine with machineName (Considers the constant plant delays for the crane movement time between machines). """ if machineName == None or machineName == "": index = 0 else: index = self.indexOfMachine(machineName) res = (len(self.recipe) - 1 - index) * plant.craneMoveTime while index < len(self.recipe): res += self.recipe[index][1] if self.recipe[index][1] == 0: res -= plant.craneMoveTime index += 1 return res def __getitem__(self, key): """ Returns the time in the Recipe at Machine with name key. """ assert type(key) == str or type(key) == unicode for r in self.recipe: if r[0] == key: return r[1] return None def __setitem__(self, key, value): """ Adds a Recipe item (a tuple of (str machineName, int time)) to the Recipe list (or dictionary). It will not add the item if machineName is already in the list. """ assert type(key) == str or type(key) == unicode assert type(value) == int if self.__getitem__(key) == None: self.recipe.append([key, value]) else: for i, r in enumerate(self.recipe): if r[0] == key: del self.recipe[i] self.recipe.insert(i, [key, value]) return @staticmethod def fromXml(element): """ A static method that creates a Recipe instance from an XML tree node and returns it. """ recipe = Recipe() for e in element.getElementsByTagName("machine"): recipe[e.getAttribute("name").lower()] = int(e.getAttribute("time")) return recipe
# -*- coding: utf8 -*- __author__ = 'D. Belavin' class NodeTree: __slots__ = ['key', 'payload', 'parent', 'left', 'right', 'height'] def __init__(self, key, payload, parent=None, left=None, right=None): self.key = key self.payload = payload self.parent = parent self.left = left self.right = right self.height = 1 def has_left_child(self): return self.left def has_right_child(self): return self.right def is_left_knot(self): return self.parent and self.parent.left == self def is_right_knot(self): return self.parent and self.parent.right == self def is_root(self): return not self.parent def has_leaf(self): return not(self.left or self.right) def has_any_children(self): return self.left or self.right def has_both_children(self): return self.left and self.right def replace_node_date(self, key, payload, left, right): # swap root and his child (left or right) self.key = key self.payload = payload self.left = left self.right = right if self.has_left_child(): self.left.parent = self if self.has_right_child(): self.right.parent = self def find_min(self): curr = self while curr.has_left_child(): curr = curr.left return curr def find_successor(self): succ = None # has right child if self.has_right_child(): succ = self.right.find_min() else: if self.parent: # self.parent.left == self if self.is_left_knot(): succ = self.parent else: self.parent.right = None # say that there is no right child succ = self.parent.find_successor() # from the left of the parent self.parent.right = self # return the right child to the place return succ def splice_out(self): # cut off node if self.has_leaf(): # self.parent.left == self if self.is_left_knot(): self.parent.left = None # self.parent.right == self else: self.parent.right = None # self has left or right child elif self.has_any_children(): # has left child if self.has_left_child(): # self.parent.left == self if self.is_left_knot(): self.parent.left = self.left # self.parent.right == self else: self.parent.right = self.left # give away parent self.left.parent = self.parent # has right child else: # self.parent.left == self if self.is_left_knot(): self.parent.left = self.right # self.parent.right == self else: self.parent.right = self.right # give away parent self.right.parent = self.parent def __iter__(self): if self: if self.has_left_child(): for element in self.left: yield element yield self.key if self.has_right_child(): for element in self.right: yield element class AVLTree: def __init__(self): self.root = None self.size = 0 def _height(self, node): if node: return node.height return 0 def _get_balance(self, node): if node: return self._height(node.left) - self._height(node.right) return 0 def _height_up(self, node): # exhibit the height return 1 + max(self._height(node.left), self._height(node.right)) def _left_rotate(self, rot_node): # rot_node.right = rot_node.right.left new_node = rot_node.right rot_node.right = new_node.left # give away left child if new_node.has_left_child(): new_node.left.parent = rot_node # give away parent new_node.parent = rot_node.parent # rot_node == self.root if rot_node.is_root(): self.root = new_node new_node.parent = None else: # rot_node.parent.left == rot_node if rot_node.is_left_knot(): rot_node.parent.left = new_node # rot_node.parent.right == rot_node else: rot_node.parent.right = new_node # rot_node is left child new_node new_node.left = rot_node rot_node.parent = new_node # exhibit the height rot_node.height = self._height_up(rot_node) new_node.height = self._height_up(new_node) def _right_rotate(self, rot_node): # rot_node.left = rot_node.left.right new_node = rot_node.left rot_node.left = new_node.right # give away right child if new_node.has_right_child(): new_node.right.parent = rot_node # give away parent new_node.parent = rot_node.parent # rot_node == self.root if rot_node.is_root(): self.root = new_node new_node.parent = None else: # rot_node.parent.left == rot_node if rot_node.is_left_knot(): rot_node.parent.left = new_node # rot_node.parent.right == rot_node else: rot_node.parent.right = new_node # rot_node is right child new_node new_node.right = rot_node rot_node.parent = new_node # exhibit the height rot_node.height = self._height_up(rot_node) new_node.height = self._height_up(new_node) def _fix_balance(self, node): node.height = self._height_up(node) balance = self._get_balance(node) if balance > 1: # big left rotate if self._get_balance(node.left) < 0: self._left_rotate(node.left) self._right_rotate(node) # small right rotate else: self._right_rotate(node) elif balance < -1: # big right rotate if self._get_balance(node.right) > 0: self._right_rotate(node.right) self._left_rotate(node) # small left rotate else: self._left_rotate(node) def _insert(self, key, payload, curr_node): # Important place. Responsible for inserting duplicate keys. # If you remove these conditions, you can set duplicate keys. # If we leave, we get the structure of a dict (map). # If we leave this condition, and remove the payload, # then we get the basis for the "set" structure. if key == curr_node.key: curr_node.payload = payload else: # go to the left if key < curr_node.key: if curr_node.has_left_child(): self._insert(key, payload, curr_node.left) else: # curr_node.left == None curr_node.left = NodeTree(key, payload, parent=curr_node) self.size += 1 # go to the right else: if curr_node.has_right_child(): self._insert(key, payload, curr_node.right) else: # curr_node.right == None curr_node.right = NodeTree(key, payload, parent=curr_node) self.size += 1 self._fix_balance(curr_node) def insert(self, key, payload): if self.root: self._insert(key, payload, self.root) else: self.root = NodeTree(key, payload) self.size += 1 def _get(self, key, curr_node): # find not key, stop recursion if not curr_node: return None # find key, stop recursion elif key == curr_node.key: return curr_node # go to the left elif key < curr_node.key: return self._get(key, curr_node.left) # go to the right else: return self._get(key, curr_node.right) def get(self, key): if self.root: res = self._get(key, self.root) if res: return res.payload else: return None # can be replaced by an "raise KeyError" else: return None # can be replaced by an "raise KeyError" def _delete(self, node): if node.has_leaf(): # node not has children # node.parent.left == node if node.is_left_knot(): node.parent.left = None # node.parent.right == node else: node.parent.right = None self._fix_balance(node.parent) elif node.has_both_children(): # node has two children succ = node.find_successor() succ.splice_out() node.key = succ.key node.payload = succ.payload self._fix_balance(succ.parent) else: # node has any child if node.has_any_children(): # has left child if node.has_left_child(): # node.parent.left == node if node.is_left_knot(): node.parent.left = node.left node.left.parent = node.parent self._fix_balance(node.parent) # node.parent.right == node elif node.is_right_knot(): node.parent.right = node.left node.left.parent = node.parent self._fix_balance(node.parent) else: # node has not parent, means node == self.root # but node has left child node.replace_node_date(node.left.key, node.left.payload, node.left.left, node.left.right) self._fix_balance(node) # has right child else: # node.parent.left == node if node.is_left_knot(): node.parent.left = node.right node.right.parent = node.parent self._fix_balance(node.parent) # node.parent.right == node elif node.is_right_knot(): node.parent.right = node.right node.right.parent = node.parent self._fix_balance(node.parent) else: # node has not parent, means node == self.root # but node has right child node.replace_node_date(node.right.key, node.right.payload, node.right.left, node.right.right) self._fix_balance(node) def delete(self, key): if self.size > 1: remove_node = self._get(key, self.root) if remove_node: self._delete(remove_node) self.size -= 1 else: raise KeyError('key not in tree.') elif self.size == 1 and self.root.key == key: self.root = None self.size -= 1 else: raise KeyError('key not in tree.') def __len__(self): return self.size def __setitem__(self, key, payload): self.insert(key, payload) def __delitem__(self, key): self.delete(key) def __getitem__(self, key): return self.get(key) def __contains__(self, key): if self._get(key, self.root): return True else: return False def __iter__(self): if self.root: return self.root.__iter__() return iter([]) def clear_tree(self): self.root = None self.size = 0
class Member(object): def __init__(self, interval, membership): self.interval = interval self.membership = membership def is_max(self): return self.membership == 1.0 def __str__(self): return str(self.membership) + "/" + str(self.interval) def __hash__(self): return self.interval
class SparkConstants: SIMPLE_CRED = 'org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider' TEMP_CRED = 'org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider' CRED_PROVIDER_KEY = 'spark.hadoop.fs.s3a.aws.credentials.provider' CRED_ACCESS_KEY = 'spark.hadoop.fs.s3a.access.key' CRED_SECRET_KEY = 'spark.hadoop.fs.s3a.secret.key' CRED_TOKEN_KEY = 'spark.hadoop.fs.s3a.session.token'
"""Check if string is blank. Set boolean _blank to _true if string _s is empty, or null, or contains only whitespace ; _false otherwise. Source: programming-idioms.org """ # Implementation author: TinyFawks # Created on 2016-02-18T16:58:03.22685Z # Last modified on 2019-09-26T20:40:16.940019Z # Version 6 blank = s.strip() == ""
""" Test no choices given .. ignored: """
#!/usr/bin/env python """ _JobSplitting_ A set of algorithms to allocate work to a set of jobs split along lines like event, run, lumi, file. """ __all__ = []
load(":providers.bzl", "PrismaDataModel") def _prisma_datamodel_impl(ctx): return [ PrismaDataModel(datamodels = ctx.files.srcs), DefaultInfo( files = depset(ctx.files.srcs), runfiles = ctx.runfiles(files = ctx.files.srcs), ), ] prisma_datamodel = rule( implementation = _prisma_datamodel_impl, attrs = { "srcs": attr.label_list( allow_files = [".prisma"], allow_empty = False, mandatory = True, ), }, )
instr = input() deviate = int(input()) for x in instr: if x.isalpha(): uni = ord(x) if x.islower(): x = chr(97 + ((uni + deviate) - 97) % 26) elif x.isupper(): x = chr(65 + ((uni + deviate) - 65) % 26) print(x, end="") print()
def centered_average(nums): """ take out 1 value of the smallest and largst compute and return the mean of the rest int div --> truncate the floating part? ASSUME: +3 ints pos/neg unsorted dupes possible Intutition: - computing an average (sum / # of points) Approach: 1. Simple - compute the min - compute the max - sum the whole list - subtract (min), and subtract max - return (remaining_sum) by (len = 2) Edge Cases: - all negatives --> normal - if in prod and saw input that broke constraints --> Error """ # - compute the min # - compute the max min_val, max_val = min(nums), max(nums) # - sum the whole list total = sum(nums) # - subtract (min), and subtract max remaining_sum = total - (min_val + max_val) # - return (remaining_sum) by (len = 2) return int(remaining_sum / (len(nums) - 2))
dd, mm, aa = input().split('/') print(f'{dd}-{mm}-{aa}') print(f'{mm}-{dd}-{aa}') print(f'{aa}/{mm}/{dd}')
''' Instructions Write a program that switches the values stored in the variables a and b. Warning. Do not change the code on lines 1-4 and 12-18. Your program should work for different inputs. e.g. any value of a and b. Example Input a: 3 b: 5 Example Output a: 5 b: 3 ''' # 🚨 Don't change the code below 👇 a = input("a: ") b = input("b: ") # 🚨 Don't change the code above 👆 #################################### # Write your code below this line 👇 a, b = b, a ''' or the more traditional way: c = a a = b b = c ''' # Write your code above this line 👆 #################################### # 🚨 Don't change the code below 👇 print("a: " + a) print("b: " + b)
#Programa que pede 10 números à escolha do usuário e mostra o somatório dos números pedidos" n = 1 soma = 0 while n<=10: x = int (input(f'{n} número: ')) soma = soma+x n = n+1 print('A soma dos números digitados é: ',soma)
MODULUS_NUM = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787 MODULUS_BITS = 381 LIMB_SIZES = [55, 55, 51, 55, 55, 55, 55] WORD_SIZE = 64 # Check that MODULUS_BITS is correct assert(2**MODULUS_BITS > MODULUS_NUM) assert(2**(MODULUS_BITS - 1) < MODULUS_NUM) # Check that limb sizes are correct tmp = 0 for i in range(0, len(LIMB_SIZES)): assert(LIMB_SIZES[i] < WORD_SIZE) tmp += LIMB_SIZES[i] assert(tmp == MODULUS_BITS) # Compute the value of the modulus in this representation MODULUS = [] tmp = MODULUS_NUM print("MODULUS = [") for i in range(0, len(LIMB_SIZES)): this_modulus_num = tmp & ((2**LIMB_SIZES[i]) - 1) MODULUS.append(this_modulus_num) tmp = tmp >> LIMB_SIZES[i] print("\t", hex(this_modulus_num), ",") print("]") # Each word in our representation has an associated "magnitude" M # in which the word is guaranteed to be less than or equal to (2^LIMB_SIZE - 1)*M # Initialize LARGEST_MAGNITUDE_CARRIES to some high number LARGEST_MAGNITUDE_CARRIES = 2**WORD_SIZE - 1 for i in range(0, len(LIMB_SIZES)): largest_mag = int(2**WORD_SIZE / (2**LIMB_SIZES[i])) assert((((2**LIMB_SIZES[i]) - 1)*largest_mag) < 2**WORD_SIZE) assert((((2**LIMB_SIZES[i]) - 1)*(largest_mag+1)) > 2**WORD_SIZE) if LARGEST_MAGNITUDE_CARRIES > largest_mag: LARGEST_MAGNITUDE_CARRIES = largest_mag print("Largest magnitude allowed for carries:", LARGEST_MAGNITUDE_CARRIES) NEGATION_MULTIPLES_OF_MODULUS = 0 for i in range(0, len(LIMB_SIZES)): tmp = 0 while (tmp * MODULUS[i]) <= ((2**LIMB_SIZES[i]) - 1): tmp = tmp + 1 if NEGATION_MULTIPLES_OF_MODULUS < tmp: NEGATION_MULTIPLES_OF_MODULUS = tmp print("Scale necessary for negations:", NEGATION_MULTIPLES_OF_MODULUS)
DICTIONARY = {'A': 'awesome', 'C': 'confident', 'B': 'beautiful', 'E': 'eager', 'D': 'disturbing', 'G': 'gregarious', 'F': 'fantastic', 'I': 'ingestable', 'H': 'hippy', 'K': 'klingon', 'J': 'joke', 'M': 'mustache', 'L': 'literal', 'O': 'oscillating', 'N': 'newtonian', 'Q': 'queen', 'P': 'perfect', 'S': 'stylish', 'R': 'rant', 'U': 'underlying', 'T': 'turn', 'W': 'weird', 'V': 'volcano', 'Y': 'yogic', 'X': 'xylophone', 'Z': 'zero'} def make_backronym(acronym): return ' '.join(DICTIONARY[a] for a in acronym.upper())
# 钻石继承搜索模式 """ 这是Python的新式类,也就是有一个以上的超类会通往同一个跟高级的超类 python的经典类继承搜索绝对是深度优先,然后是才左向右。一路向上搜索,深入树的左侧,返回后,才开始右侧 在新式类中,相对于说是宽度优先的,Python现寻找第一个搜索的右侧的所有超类,然后才一路往上搜索至顶端的共同的超类 当从多个子类访问超类的时候,新式搜索规则避免重复访问同一个超类 """ class A: attr = 1 class B(A): pass class C(A): attr = 2 class D(B, C): pass # attr = C.attr(明确解决冲突) if __name__ == "__main__": """ 经典类来说搜索顺序是:D -> B -> A -> C (继承搜索是先往上搜索到最高,然后返回在往右搜索 Python先搜索D、B、A,然后才是C(但是,当attr在A中找到时,B之上的就会停止)) """ """ 新式类(python3.0都是):D -> C -> B -> A 新式类这样做的原因是程序员当写D的继承的时候,会想当然的认为C会覆盖A的属性,但是按照经典的 继承并不会先继承C """ x = D() print(x.attr) # python2.6是1 Python3 是2
_ALLOWED_VOLUME_KEYS = ["claim_name", "mount_path"] def parse(volume_str): """Parse combined k8s volume string into a dict. Args: volume_str: The string representation for k8s volume, e.g. "claim_name=c1,mount_path=/path1". Return: A Python dictionary parsed from the given volume string. """ kvs = volume_str.split(",") volume_keys = [] parsed_volume_dict = {} for kv in kvs: k, v = kv.split("=") if k not in volume_keys: volume_keys.append(k) else: raise ValueError( "The volume string contains duplicate volume key: %s" % k ) if k not in _ALLOWED_VOLUME_KEYS: raise ValueError( "%s is not in the allowed list of volume keys: %s" % (k, _ALLOWED_VOLUME_KEYS) ) parsed_volume_dict[k] = v return parsed_volume_dict
print('====== DESAFIO 02 ======') dia = int(input('Dia = ')) mes = input('Mês = ') ano = int(input('Ano = ')) print('Você nasceu no dia ',dia,' de ',mes,'de',ano,'. Correto?' )
# find the non-repeating integer in an array # set operations (including 'in' operation) are O(1) on average, and one loop that runs n times makes O(n) def single(array): repeated = set() not_repeated = set() for i in array: if i in repeated: continue elif i in not_repeated: repeated.add(i) not_repeated.remove(i) else: not_repeated.add(i) return not_repeated array1 = [2, 'a', 'l', 3, 'l', 5, 4, 'k', 2, 3, 4, 'a', 6, 'c', 4, 'm', 6, 'm', 'k', 9, 10, 9, 8, 7, 8, 10, 7] print(single(array1)) # {'c', 5}
def lstrip0(iterable, obj): i = 0 iterable_list = list(iterable) while i < len(iterable_list): if iterable_list[i] != obj: break i += 1 for k in range(i, len(iterable_list)): yield iterable_list[k] def lstrip(iterable, obj, key_func=None): if not key_func: key_func = lambda x: x == obj i = 0 iterable_list = list(iterable) while i < len(iterable_list): if key_func(iterable_list[i]) is False: break i += 1 for k in range(i, len(iterable_list)): yield iterable_list[k] if __name__ == "__main__": lstrip0([1,1,1], 1) lstrip([1,1,1], 1)
def extendList(val, lst=[]): lst.append(val) return lst list1 = extendList(10) list2 = extendList(123,[]) list3 = extendList('a') print("list1 = %s" % list1) print("list2 = %s" % list2) print("list3 = %s" % list3)
# Given an array nums of integers, # return how many of them contain an even number of digits. def find_numbers_easy(nums): even_number_count = 0 for num in nums: if len(str(num)) % 2 == 0: even_number_count += 1 return even_number_count def find_numbers_hard(nums): even_number_count = 0 for num in nums: digit_count = 0 while num > 0: digit_count += 1 print(digit_count) num = num // 10 # normal integer division print(num) if digit_count % 2 == 0: even_number_count += 1 return even_number_count nums = [12, 345, 2, 6, 7896] find_numbers_easy(nums) # ? find_numbers_hard(nums) # ?
# GENERATED VERSION FILE # TIME: Tue Sep 28 14:27:47 2021 __version__ = '1.0rc1+c42460f' short_version = '1.0rc1'
#!/usr/bin/env python3 bag_of_words = __import__('0-bag_of_words').bag_of_words sentences = ["Holberton school is Awesome!", "Machine learning is awesome", "NLP is the future!", "The children are our future", "Our children's children are our grandchildren", "The cake was not very good", "No one said that the cake was not very good", "Life is beautiful"] E, F = bag_of_words(sentences) print(E) print(F)
x=4 itersLeft=x Sum=0 while(itersLeft!=0): Sum=Sum+x itersLeft=itersLeft-1 print(Sum) print(itersLeft) print(str(x)+"**"+" 2 = "+str(Sum))
class Solution: def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ i, j, size, sum, min_len = 0, 0, len(nums), 0, len(nums) if size == 0: return 0 while j < size: sum += nums[j] while sum >= s: sum -= nums[i] i += 1 min_len = min(min_len, j - i + 2) j += 1 return min_len if i != 0 else 0
QUIP_ACCESS_TOKEN = "1ee2demdo33=|03e39j94r4|komes234mfmf+wapdmeodmemdfg2y6hMfAHko=" # This is a fake token :D QUIP_BASE_URL = "https://platform.quip.com" ENV = "DEBUG" LOGS_PREFIX = ":quip.quip:" USER_JSON = { "name": "John Doe", "id": "1234", "is_robot": False, "affinity": 0.0, "desktop_folder_id": "abc1234", "archive_folder_id": "abc5678", "starred_folder_id": "abc9101", "private_folder_id": "abc1121", "trash_folder_id": "abc3141", "shared_folder_ids": ["abc5161", "abc7181"], "group_folder_ids": ["abc9202", "abc1222"], "profile_picture_url": f"{QUIP_BASE_URL}/pic.jpg", "subdomain": None, "url": QUIP_BASE_URL, } FOLDER_JSON = { "children": [{"thread_id": "abc7181"}, {"folder_id": "abc5161"}], "folder": { "created_usec": 1606998498297926, "creator_id": "1234", "id": "abc9101", "title": "Starred", "updated_usec": 1609328575547507, }, "member_ids": ["1234"], } THREAD_JSON = { "access_levels": { "1234": {"access_level": "OWN"}, }, "expanded_user_ids": ["1234"], "thread": { "author_id": "1234", "thread_class": "document", "id": "567mnb", "created_usec": 1608114559763651, "updated_usec": 1609261609357637, "link": f"{QUIP_BASE_URL}/abcdefg12345", "type": "spreadsheet", "title": "My Spreadsheet", "document_id": "9876poiu", "is_deleted": False, }, "user_ids": [], "shared_folder_ids": ["abc1234"], "invited_user_emails": [], "html": "<h1 id='9876poiu'>My Spreadsheet</h1>", } SPREADSHEET_CONTENT = """<h1 id='9876poiu'>My Spreadsheet</h1> <div data-section-style='13'> <table id='Aec9CAvyP44' title='Sheet1' style='width: 237.721em'> <thead> <tr> <th class='empty' style='width: 2em'/> <th id='Aec9CAACdyH' class='empty' style='width: 1.8em'>A<br/></th> <th id='Aec9CAH7YBR' class='empty' style='width: 7.46667em'>B<br/></th> <th id='Aec9CAwvN9F' class='empty' style='width: 19.9333em'>C<br/></th> <th id='Aec9CAe1yQ0' class='empty' style='width: 6.71634em'>D<br/></th> <th id='Aec9CAAIaj1' class='empty' style='width: 6em'>T<br/></th> <th id='Aec9CAWcoFU' class='empty' style='width: 6em'>U<br/></th> <th id='Aec9CAkrCad' class='empty' style='width: 6em'>V<br/></th> </tr> </thead> <tbody> <tr id='Aec9CAmLjDE'> <td style='background-color:#f0f0f0'>1</td> <td id='s:Aec9CAmLjDE_Aec9CA0oPBj' style='background-color:#FFDF99;' class='bold'> <span id='s:Aec9CAmLjDE_Aec9CA0oPBj'>TECH TRACK</span> <br/> </td> <td id='s:Aec9CAmLjDE_Aec9CAWFNOe' style=''> <span id='s:Aec9CAmLjDE_Aec9CAWFNOe'>\u200b</span> <br/> </td> <td id='s:Aec9CAmLjDE_Aec9CAHOMxq' style=''> <span id='s:Aec9CAmLjDE_Aec9CAHOMxq'>\u200b</span> <br/> </td> <td id='s:Aec9CAmLjDE_Aec9CAf7d0s' style=''> <span id='s:Aec9CAmLjDE_Aec9CAf7d0s'>\u200b</span> <br/> </td> <td id='s:Aec9CAmLjDE_Aec9CAEwmwC' style=''> <span id='s:Aec9CAmLjDE_Aec9CAEwmwC'>\u200b</span> <br/> </td> <td id='s:Aec9CAmLjDE_Aec9CA0lijP' style=''> <span id='s:Aec9CAmLjDE_Aec9CA0lijP'>\u200b</span> <br/> </td> <td id='s:Aec9CAmLjDE_Aec9CA003da' style=''> <span id='s:Aec9CAmLjDE_Aec9CA0lijP'>\u200b</span> <br/> </td> </tr> <tr id='Aec9CAITZFz'> <td style='background-color:#f0f0f0'>2</td> <td id='s:Aec9CAITZFz_Aec9CA0oPBj' style='background-color:#FFDF99;' class='bold'> <span id='s:Aec9CAITZFz_Aec9CA0oPBj'>\u200b</span> <br/> </td> <td id='s:Aec9CAITZFz_Aec9CAWFNOe' style='background-color:#FFDF99;' class='bold'> <span id='s:Aec9CAITZFz_Aec9CAWFNOe'>Date</span> <br/> </td> <td id='s:Aec9CAITZFz_Aec9CAHOMxq' style='background-color:#FFDF99;' class='bold'> <span id='s:Aec9CAITZFz_Aec9CAHOMxq'>Title</span> <br/> </td> <td id='s:Aec9CAITZFz_Aec9CAf7d0s' style='background-color:#FFDF99;' class='bold'> <span id='s:Aec9CAITZFz_Aec9CAf7d0s'>Location</span> <br/> </td> <td id='s:Aec9CAITZFz_Aec9CAwdFrL' style='background-color:#FFDF99;' class='bold'> <span id='s:Aec9CAITZFz_Aec9CAwdFrL'>Language</span> <br/> </td> <td id='s:Aec9CAITZFz_Aec9CAEwmwC' style='background-color:#FFDF99;' class='bold'> <span id='s:Aec9CAITZFz_Aec9CAEwmwC'>Capacity</span> <br/> </td> <td id='s:Aec9CAITZFz_Aec9CA0lijP' style='background-color:#FFDF99;' class='bold'> <span id='s:Aec9CAITZFz_Aec9CA0lijP'>Owner</span> <br/> </td> </tr> <tr id='Aec9CADeBjI'> <td style='background-color:#f0f0f0'>3</td> <td id='s:Aec9CADeBjI_Aec9CA0oPBj' style='background-color:#AFEFA9;'> <span id='s:Aec9CADeBjI_Aec9CA0oPBj'>\u200b</span> <br/> </td> <td id='s:Aec9CADeBjI_Aec9CAWFNOe' style=''> <span id='s:Aec9CADeBjI_Aec9CAWFNOe'>Date</span> <br/> </td> <td id='s:Aec9CADeBjI_Aec9CAHOMxq' style=''> <span id='s:Aec9CADeBjI_Aec9CAHOMxq'>Intro to ML on AWS</span> <br/> </td> <td id='s:Aec9CADeBjI_Aec9CAf7d0s' style=''> <span id='s:Aec9CADeBjI_Aec9CAf7d0s'>Virtual (Chime)</span> <br/> </td> <td id='s:Aec9CADeBjI_Aec9CAwdFrL' style=''> <span id='s:Aec9CADeBjI_Aec9CAwdFrL'>ES</span> <br/> </td> <td id='s:Aec9CADeBjI_Aec9CAEwmwC' style=''> <span id='s:Aec9CADeBjI_Aec9CAEwmwC'>50</span> <br/> </td> <td id='s:Aec9CADeBjI_Aec9CA0lijP' style=''> <span id='s:Aec9CADeBjI_Aec9CA0lijP'>John Doe</span> <br/> </td> </tr> </tbody> </table> </div>"""
#!/usr/bin/env python # -*- coding: utf-8 -*- class InvalidTemplateError(Exception): """ Raised when a CloudFormation template fails the Validate Template call """ pass
class BinarySearch: def __init__(self, arr, target): self.arr = arr self.target = target def binary_search(self): lo, hi = 0, len(self.arr) while lo<hi: mid = lo + (hi-lo)//2 # dont use (lo+hi)//2. Integer overflow. # https://en.wikipedia.org/wiki/Binary_search_algorithm#Implementation_issues if self.arr[mid] == self.target: return mid if self.arr[mid] > self.target: hi = mid-1 else: lo = mid+1 return -1 # input in python3 returns a string n = int(input('Enter the size of array')) # example of using map # a = ['1', '2'] conver it into int # a = list(map(int, a)) in python2 this will work a=map(int,a) # in python3 map returns a map object which is a generator where as in py2 map returns a list # n is used so that even if we enter n+1 numbers list will only contain n number arr = list(map(int, input("Enter the number").strip().split()))[:n] target = int(input("Enter the number to be searched")) print(BinarySearch(arr, target).binary_search())
class Solution(object): # def validPalindrome(self, s): # """ # :type s: str # :rtype: bool # """ # def is_pali_range(i, j): # return all(s[k] == s[j - k + i] for k in range(i, j)) # for i in xrange(len(s) / 2): # if s[i] != s[~i]: # j = len(s) - 1 - i # return is_pali_range(i + 1, j) or is_pali_range(i, j - 1) # return True # Actually we can make this solution more general def validPalindrome(self, s): return self.validPalindromeHelper(s, 0, len(s) - 1, 1) def validPalindromeHelper(self, s, left, right, budget): # Note that budget can be more than 1 while left < len(s) and right >= 0 and left <= right and s[left] == s[right]: left += 1 right -= 1 if left >= len(s) or right < 0 or left >= right: return True if budget == 0: return False budget -= 1 return self.validPalindromeHelper(s, left + 1, right, budget) or self.validPalindromeHelper(s, left, right - 1, budget)
class connectionFinder: def __init__(self, length): self.id = [0] * length self.size = [0] * length for i in range(length): self.id[i] = i self.size[i] = i # Id2 will become a root of Id1 : def union(self, id1, id2): rootA = self.find(id1) rootB = self.find(id2) self.id[rootA] = rootB print(self.id) # Optimization to remove skewed tree and construct weighted binary tree: def weightedUnion(self, id1, id2): root1 = self.find(id1) root2 = self.find(id2) size1 = self.size[root1] size2 = self.size[root2] if size1 < size2: # Make small one child self.id[root1] = root2 self.size[root2] += self.size[root1] else: self.id[root2] = root1 self.size[root1] += self.size[root2] def find(self, x): if self.id[x] == x: return x x = self.id[self.id[x]] # To cut the overhead next when we call this find method for the same root self.id[x] = x return self.find(x) def isConnected(self, id1, id2): return self.find(id1) == self.find(id2) uf = connectionFinder(10) uf.union(1, 2) print(" check ", uf.isConnected(1, 2))
# Delicka # Napíšte funkciu Delicka, ktorá bude prijímať parameter text a voliteľný parameter separator (defaultný separátor = ';'). Rozdeľuje text podľa parametra separator, prevedie prvé dva prvky na reálne čísla a vráti ich podiel. # Sample Input 1: # delicka('1;2;haha') # Sample Output 1: # 0.5 # Sample Input 2: # delicka('3 2 ... ... ...', separator=' ') # Sample Output 2: # 1.5 def delicka(text: str, separator: str = ';') -> float: prvy, druhy, *_ = text.split(separator) return float(prvy) / float(druhy) print(delicka('1;2;haha')) # # Alternatívne riešenie: # def delicka(text: str, separator: str = ';') -> float: # prvky = text.split(separator) # return float(prvky[0]) / float(prvky[1]) # print(input())
expected_output = { "vrf": { "vrf1": { "lib_entry": { "10.11.0.0/24": { "rev": "7", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}} } } }, }, "10.12.0.0/24": { "label_binding": {"label": {"17": {}}}, "rev": "8", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}} } } }, }, "10.0.0.0/24": { "rev": "6", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}} } } }, }, } }, "default": { "lib_entry": { "10.11.0.0/24": { "label_binding": {"label": {"imp-null": {}}}, "rev": "15", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.131.0.1": {"label_space_id": {0: {}}}} } } }, }, "10.0.0.0/24": { "label_binding": {"label": {"imp-null": {}}}, "rev": "4", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.131.0.1": {"label_space_id": {0: {}}}} } } }, }, } }, } }
nmr = int(input("Digite um numero: ")) if nmr %2 == 0: print("Numero par") else: print("Numero impar")
class DefaultConfig(object): # Flask Settings # ------------------------------ # There is a whole bunch of more settings available here: # http://flask.pocoo.org/docs/0.11/config/#builtin-configuration-values DEBUG = False TESTING = False
n = int(input()) ss = input().split() s = int(ss[0]) a = [] for i in range(n): ss = input().split() a.append((int(ss[0]), int(ss[1]))) a.sort(key=lambda x: x[0] * x[1]) ans = 0 for i in range(n): if (s // (a[i])[1] > ans): ans = s // (a[i])[1] s *= (a[i])[0] print(ans)
def city_formatter(city, country): formatted = f"{city.title()}, {country.title()}" return formatted print(city_formatter('hello', 'world'))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' with open('1.txt', 'a', encoding='cp1251') as f: f.write('фотки\n') with open('1.txt', 'a', encoding='utf-8') as f: f.write('фотки\n') # OR... with open('2.txt', 'ab') as f: f.write('фотки\n'.encode('cp1251')) with open('2.txt', 'ab') as f: f.write('фотки\n'.encode('utf-8'))
''' Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Example: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Constraints: - 1 <= arr.length <= 10^4 - 0 <= arr[i] <= 10^5 ''' #Difficulty: Easy #18 / 18 test cases passed. #Runtime: 120 ms #Memory Usage: 15.9 MB #Runtime: 120 ms, faster than 14.93% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array. #Memory Usage: 15.9 MB, less than 12.26% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array. class Solution: def findSpecialInteger(self, arr: List[int]) -> int: length = len(arr) nums = set(arr) if length == 1: return arr[0] for num in nums: n = self.binarySearch(arr, num, length) if n: return n def binarySearch(self, arr: int, num: int, length: int) -> int: l = 0 r = length - 1 q = length // 4 while l < r: m = (l+r) // 2 if arr[m] == num and arr[min(length-1, m+q)] == num: return num elif num > arr[m]: l = m + 1 else: r = m - 1
class json_to_csv(): def __init__(self): self.stri='' self.st='' self.a=[] self.b=[] self.p='' def read_js(self,path): self.p=path l=open(path,'r').readlines() for i in l: i=i.replace('\t','') i=i.replace('\n','') self.stri+=i self.st=self.stri def write_cs(self,path=None,head=None): self.st=self.stri self.st=self.st.replace('{','') self.st=self.st.replace('}','') while len(self.st)!=0: try: i=self.st.index(':') k=self.st[:i] k=k.replace(' ','') if k not in self.a: self.a.append(k) self.st=self.st[i+1:] try : i=self.st.index(',') self.b.append(self.st[:i]) self.st=self.st[i+1:] except : self.b.append(self.st[:]) self.st='' except: self.st='' for i in range(len(self.b)): self.b[i]=self.b[i].replace(' ','') if path==None: m=self.p.index('.') self.p=(self.p[:m]+'.csv') f=open(self.p,'w') else : f=open(path,'w') if head==None: for i in self.a: if self.a.index(i)!=len(self.a)-1: f.write(i) f.write(',') else: f.write(i) f.write('\n') for i in range(len(self.b)): if i%len(self.a)!=len(self.a)-1: f.write(self.b[i]) f.write(',') else: f.write(self.b[i]) f.write('\n') else : for i in head: if head.index(i)!=len(head)-1: f.write(i) f.write(',') else: f.write(i) f.write('\n') for i in self.b: if self.b.index(i)%len(self.a)!=len(self.a)-1: f.write(i) f.write(',') else: f.write(i) f.write('\n')
def es5(tree): # inserisci qui il tuo codice d={} for x in tree.f: d1=es5(x) for x in d1: if x in d: d[x]=d[x] | d1[x] else: d[x]=d1[x] y=len(tree.f) if y in d: d[y]=d[y]| {tree.id} else: d[y]= {tree.id} return d
#!/home/jepoy/anaconda3/bin/python def main(): x = dict(Buffy = 'meow', Zilla = 'grrr', Angel = 'purr') kitten(**x) def kitten(**kwargs): if len(kwargs): for k in kwargs: print('Kitten {} says {}'.format(k, kwargs[k])) else: print('Meow.') if __name__ == '__main__': main()
def resolve(): ''' code here ''' x, y = [int(item) for item in input().split()] res = 0 if x < 0 and abs(y) - abs(x) >= 0: res += 1 elif x > 0 and abs(y) - abs(x) <= 0: res += 1 res += abs(abs(x) - abs(y)) if y > 0 and abs(y) - abs(x) < 0: res += 1 elif y < 0 and abs(y) - abs(x) > 0: res += 1 print(res) if __name__ == "__main__": resolve()
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : 1410.py @Contact : huanghoward@foxmail.com @Modify Time : 2022/4/12 16:18 ------------ """ class Solution: def entityParser(self, text: str) -> str: l = 0 r = 0 reading = False result = "" convert = { "&quot;": "\"", "&apos;": "\'", "&amp;": "&", "&gt;": ">", "&lt;": "<", "&frasl;": "/" } for i, char in enumerate(text): if reading: if char == ";": r = i if text[l:r + 1] not in convert.keys(): result += text[l:r + 1] else: result += convert[text[l:r + 1]] r = 0 l = 0 reading = False elif char == "&": r = i result += text[l:r] l = i continue else: if char == "&": l = i reading = True continue result += char return result if __name__ == '__main__': s = Solution() print(s.entityParser("&&&"))
def asm2(param_1, param_2): # push ebp # mov ebp,esp # sub esp,0x10 eax = param_2 # mov eax,DWORD PTR [ebp+0xc] local_1 = eax # mov DWORD PTR [ebp-0x4],eax eax = param_1 # mov eax,DWORD PTR [ebp+0x8] local_2 = eax # mov eax,DWORD PTR [ebp+0x8] while param_1 <= 0x9886:# cmp DWORD PTR [ebp+0x8],0x9886 # jle part_a local_1 += 0x1 # add DWORD PTR [ebp-0x4],0x1 param_1 += 0x41 # add DWORD PTR [ebp+0x8],0x41 eax = local_1 # mov eax,DWORD PTR [ebp-0x4] return eax # mov esp,ebp # pop ebp # ret print(hex(asm2(0xe, 0x21)))
class _SpeechOperation(): def add_done_callback(callback): pass
class BaseHyperParameter: """ This is a base class for all hyper-parameters. It should not be instantiated. Use concrete implementations instead. """ def __init__(self, name): self.name = name
def main(): a = 1 if True else 2 print(a) if __name__ == '__main__': main()
# Birth should occur before death of an individual def userStory03(listOfPeople): flag = True def changeDateToNum(date): # date format must be like "2018-10-06" if date == "NA": return 0 # 0 will not larger than any date, for later comparison else: tempDate = date.split('-') return int(tempDate[0] + tempDate[1] + tempDate[2]) for people in listOfPeople: if people.Death != "NA": BirthdayNum = changeDateToNum(people.Birthday) DeathNum = changeDateToNum(people.Death) if BirthdayNum > DeathNum: print("ERROR: INDIVIDUAL: US03: Birthday of " + people.ID + " occur after Death") flag = False return flag
name = input("Enter your name: ") age = input("Enter your age: ") print("Hello " + name + " ! Your are " + age + " Years old now.") num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = num1 + num2 print(result) # We need int casting number num1 and num2 result = int(num1) + int(num2) print(result) # Adding two Float number num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = float(num1) + float(num2) print(result)
# -*- coding: utf-8 -*- def find_message(message: str) -> str: result: str = "" for i in list(message): if i.isupper(): result += i return result # another pattern return ''.join(i for i in message if i.isupper()) if __name__ == '__main__': print("Example:") print(find_message(('How are you? Eh, ok. Low or Lower? ' + 'Ohhh.'))) # These "asserts" are used for self-checking and not for an auto-testing assert find_message(('How are you? Eh, ok. Low or Lower? ' + 'Ohhh.')) == 'HELLO' assert find_message('hello world!') == '' assert find_message('HELLO WORLD!!!') == 'HELLOWORLD' print("Coding complete? Click 'Check' to earn cool rewards!")
# # Copyright 2019 Delphix # # 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. # """This module contains the "sdb.Error" exception.""" class Error(Exception): """ This is the superclass of all SDB error exceptions. """ text: str = "" def __init__(self, text: str) -> None: self.text = 'sdb: {}'.format(text) super().__init__(self.text) class CommandNotFoundError(Error): # pylint: disable=missing-docstring command: str = "" def __init__(self, command: str) -> None: self.command = command super().__init__("cannot recognize command: {command}") class CommandError(Error): # pylint: disable=missing-docstring command: str = "" message: str = "" def __init__(self, command: str, message: str) -> None: self.command = command self.message = message super().__init__(f"{command}: {message}") class CommandInvalidInputError(CommandError): # pylint: disable=missing-docstring argument: str = "" def __init__(self, command: str, argument: str) -> None: self.argument = argument super().__init__(command, f"invalid input: {argument}") class SymbolNotFoundError(CommandError): # pylint: disable=missing-docstring symbol: str = "" def __init__(self, command: str, symbol: str) -> None: self.symbol = symbol super().__init__(command, f"symbol not found: {symbol}") class CommandArgumentsError(CommandError): # pylint: disable=missing-docstring def __init__(self, command: str) -> None: super().__init__(command, 'invalid input. Use -h to get argument description') class CommandEvalSyntaxError(CommandError): # pylint: disable=missing-docstring def __init__(self, command: str, err: SyntaxError) -> None: msg = f"{err.msg}:\n\t{err.text}" if err.offset is not None and err.text is not None: nspaces: int = err.offset - 1 spaces_str = list(' ' * len(err.text)) spaces_str[nspaces] = '^' indicator = ''.join(spaces_str) msg += f"\n\t{indicator}" super().__init__(command, msg)
# Copyright 2020 The Bazel Authors. All rights reserved. # # 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. """`dtrace_compile` Starlark tests.""" load( ":rules/output_text_match_test.bzl", "output_text_match_test", ) def dtrace_compile_test_suite(name): """Test suite for `dtrace_compile`. Args: name: the base name to be used in things created by this macro """ output_text_match_test( name = "{}_generates_expected_header_contents".format(name), target_under_test = "//test/starlark_tests/targets_under_test/dtrace:dtrace", files_match = { "folder1/probes.h": ["PROVIDERA_MYFUNC"], "folder2/probes.h": ["PROVIDERB_MYFUNC"], }, tags = [name], ) native.test_suite( name = name, tags = [name], )
class Vector(object): SHORTHAND = 'V' def __init__(self, **kwargs): super(Vector, self).__init__() self.vector = kwargs def dot(self, other): product = 0 for member, value in self.vector.items(): product += value * other.member(member) return product def apply(self, other): for member, effect in other.vector.items(): value = self.member(member) self.vector[member] = value + effect def member(self, name, default=0): return self.vector.get(name, default) def __str__(self): return '%s(%s)' % (self.SHORTHAND, ','.join(['%s=%.3f' % (key, value) for key, value in self.vector.items()]))
#!/usr/bin/env python3 def first(iterable, default=None, key=None): if key is None: for el in iterable: if el is not None: return el else: for el in iterable: if key(el) is not None: return el return default
class Foo: def qux2(self): z = 12 x = z * 3 self.baz = x for q in range(10): x += q lst = ["foo", "bar", "baz"] lst = lst[1:2] assert len(lst) == 2, 201 def qux(self): self.baz = self.bar self.blah = "hello" self._priv = 1 self._prot = self.baz def _prot2(self): pass class Bar(Foo): def something(self): super()._prot2() def something2(self): self._prot = 12 class SpriteKind(Enum): Player = 0 Projectile = 1 Enemy = 2 Food = 3 ii = img(""" . . . . . a . . . b b . """) hbuf = hex("a007") hbuf2 = b'\xB0\x07' asteroids = [sprites.space.space_small_asteroid1, sprites.space.space_small_asteroid0, sprites.space.space_asteroid0, sprites.space.space_asteroid1, sprites.space.space_asteroid4, sprites.space.space_asteroid3] ship = sprites.create(sprites.space.space_red_ship, SpriteKind.Player) ship.set_flag(SpriteFlag.STAY_IN_SCREEN, True) ship.bottom = 120 controller.move_sprite(ship, 100, 100) info.set_life(3) def player_damage(sprite, other_sprite): scene.camera_shake(4, 500) other_sprite.destroy(effects.disintegrate) sprite.start_effect(effects.fire, 200) info.change_life_by(-1) sprites.on_overlap(SpriteKind.Player, SpriteKind.Enemy, player_damage) if False: player_damage(ship, ship) def enemy_damage(sprite:Sprite, other_sprite:Sprite): sprite.destroy() other_sprite.destroy(effects.disintegrate) info.change_score_by(1) sprites.on_overlap(SpriteKind.Projectile, SpriteKind.Enemy, enemy_damage) def shoot(): projectile = sprites.create_projectile_from_sprite(sprites.food.small_apple, ship, 0, -140) projectile.start_effect(effects.cool_radial, 100) controller.A.on_event(ControllerButtonEvent.PRESSED, shoot) def spawn_enemy(): projectile = sprites.create_projectile_from_side(asteroids[math.random_range(0, asteroids.length - 1)], 0, 75) projectile.set_kind(SpriteKind.Enemy) projectile.x = math.random_range(10, 150) game.on_update_interval(500, spawn_enemy)
class Pessoa: olhos=2 def __init__(self, *filhos, nome=None,idade=28): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Olá{id(self)}' if __name__ == '__main__': andrew = Pessoa(nome='Andrew') waschington = Pessoa(andrew, nome='Waschington') print(Pessoa.cumprimentar(waschington)) print(id(waschington)) print(waschington.cumprimentar()) print(waschington.nome) print(waschington.idade) for filho in waschington.filhos: print(filho.nome) waschington.sobrenome = 'Procopio' del waschington.filhos waschington.olhos = 1 del waschington.olhos print(waschington.__dict__) print(andrew.__dict__) Pessoa.olhos = 3 print(Pessoa.olhos) print(andrew.olhos) print(waschington.olhos) print(id(Pessoa.olhos), id(andrew.olhos), id(waschington.olhos))
pattern_zero=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] pattern_odd=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] pattern_even=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] averages_even={0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]} averages_odd={0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]}
class Solution(object): def isReflected(self, points): """ :type points: List[List[int]] :rtype: bool """ if not points: return True positions=set() sumk=0 for p in points: positions.add((p[0],p[1])) # avoid duplicate points for p in positions: sumk+=p[0] pivot=float(sumk)/float(len(positions)) for p in positions: if (int(2*pivot-p[0]),p[1]) not in positions: return False return True
Pathogen = { 'name': 'pathogen', 'fields': [ {'name': 'reported_name'}, {'name': 'drug_resistance'}, {'name': 'authority'}, {'name': 'tax_order'}, {'name': 'class'}, {'name': 'family'}, {'name': 'genus'}, {'name': 'species'}, {'name': 'sub_species'} ] }
def merge(di1, di2, fu=None): di3 = {} for ke in sorted(di1.keys() | di2.keys()): if ke in di1 and ke in di2: if fu is None: va1 = di1[ke] va2 = di2[ke] if isinstance(va1, dict) and isinstance(va2, dict): di3[ke] = merge(va1, va2) else: di3[ke] = va2 else: di3[ke] = fu(di1[ke], di2[ke]) elif ke in di1: di3[ke] = di1[ke] elif ke in di2: di3[ke] = di2[ke] return di3
def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] N, Q = read_list(int) array = read_list(int) C = [[0, 0, 0]] for a in array: c = C[-1][:] c[a % 3] += 1 C.append(c) for _ in range(Q): l, r = read_list(int) c1, c2 = C[l-1], C[r] if c2[0] - c1[0] == 1: print(0) else: print(2 if (c2[2]-c1[2]) % 2 == 1 else 1)
arr=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] n=4#col m=4#row #print matrix in spiral form loop=0 while(loop<n/2): for i in range(loop,n-loop-1): print(arr[loop][i],end=" ") for i in range(loop,m-loop-1): print(arr[i][m-loop-1],end=" ") for i in range(n-1-loop,loop-1+1,-1): print(arr[m-loop-1][i],end=" ") for i in range(m-loop-1,loop,-1): print(arr[i][loop],end=" ") loop+=1
class Color: red = None green = None blue = None white = None bit_color = None def __init__(self, red, green, blue, white=0): self.red = red self.green = green self.blue = blue self.white = white def get_rgb(self): return 'rgb(%d,%d,%d)' % (self.red, self.green, self.blue) def get_hex(self): return '#%02x%02x%02x' % (self.red, self.green, self.blue) def get_hsv(self): red = self.red / 255.0 green = self.green / 255.0 blue = self.blue / 255.0 median_max = max(red, green, blue) median_min = min(red, green, blue) difference = median_max - median_min if median_max == median_min: hue = 0 elif median_max == red: hue = (60 * ((green - blue) / difference) + 360) % 360 elif median_max == green: hue = (60 * ((blue - red) / difference) + 120) % 360 elif median_max == blue: hue = (60 * ((red - green) / difference) + 240) % 360 else: hue = 0 if median_max == 0: saturation = 0 else: saturation = difference / median_max value = median_max return 'hsv(%d,%d,%d)' % (hue, saturation, value) def get_bit(self): return (self.white << 24) | (self.red << 16) | (self.green << 8) | self.blue def __str__(self): return '%d,%d,%d' % (self.red, self.green, self.blue)
N = int(input()) ano = N // 365 resto = N % 365 mes = resto // 30 dia = resto % 30 print(str(ano) + " ano(s)") print(str(mes) + " mes(es)") print(str(dia) + " dia(s)")
r, c = (map(int, input().split(' '))) for row in range(r): for col in range(c): print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ') print()
'''Colocando cores no terminal do python''' # \033[0;033;44m codigo para colocar as cores # tipo de texto em cod (estilo do texto) # 0 - sem estilo nenhum # 1 - negrito # 4 - sublinhado # 7 - inverter as confgs # cores em cod (cores do texto) # 30 - branco # 31 - vermelho # 32 - verde # 33 - amarelo # 34 - azul # 35 - lilas # 36 - ciano # 37 - cinza # back em cod (cores de fundo) # 40 - branco # 41 - vermelho # 42 - verde # 43 - amarelo # 44 - azul # 45 - lilas # 46 - ciano # 47 - cinza
""" An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic. Example 1: Input: [1,2,2,3] Output: true Example 2: Input: [6,5,4,4] Output: true Example 3: Input: [1,3,2] Output: false Example 4: Input: [1,2,4,5] Output: true Example 5: Input: [1,1,1] Output: true Note: 1 <= A.length <= 50000 -100000 <= A[i] <= 100000 Solution: 1. Two variables. One for increasing, one for decreasing. """ class Solution: def isMonotonic(self, A: List[int]) -> bool: increase = True decrease = True for i in range(len(A)-1): if A[i] > A[i+1]: increase = False if A[i] < A[i+1]: decrease = False return increase or decrease
valid_passport = 0 invalid_passport = 0 def get_key(p_line): keys = [] for i in p_line.split(): keys.append(i.split(':')[0]) return keys def check_validation(keys): for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])) # CID is optional if 'cid' in keys: keys.remove('cid') keys = ' '.join(sorted(keys)) if for_valid == keys: return True else: return False with open('passport.txt') as file: passport_line = '' current_line = True while current_line: current_line = file.readline() if current_line != '\n': passport_line += ' ' + current_line[:-1] else: passport_line = get_key(passport_line) if check_validation(passport_line): valid_passport += 1 else: invalid_passport += 1 passport_line = '' passport_line = get_key(passport_line) if check_validation(passport_line): valid_passport += 1 else: invalid_passport += 1 passport_line = '' print(f'Valid Passport : {valid_passport}') print(f'Invalid Passport : {invalid_passport}')
# Copyright 2017 The Forseti Security Authors. All rights reserved. # # 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. """Fake folders data.""" FAKE_FOLDERS_DB_ROWS = [ {'folder_id': '111111111111', 'name': 'folders/111111111111', 'display_name': 'Folder1', 'lifecycle_state': 'ACTIVE', 'create_time': '2015-09-09 00:01:01', 'parent_id': '9999', 'parent_type': 'organization'}, {'folder_id': '222222222222', 'name': 'folders/222222222222', 'display_name': 'Folder2', 'lifecycle_state': 'ACTIVE', 'create_time': '2015-10-10 00:02:02', 'parent_id': None, 'parent_type': None}, ] FAKE_FOLDERS_RESPONSE = { 'folders': [ { 'name': 'folders/1111111111', 'display_name': 'Folder1', 'lifecycleState': 'ACTIVE', 'parent': 'organizations/9999', }, { 'name': 'folders/2222222222', 'display_name': 'Folder2', 'lifecycleState': 'ACTIVE', }, { 'name': 'folders/3333333333', 'display_name': 'Folder3', 'lifecycleState': 'ACTIVE', } ] } EXPECTED_FAKE_FOLDERS_FROM_API = FAKE_FOLDERS_RESPONSE['folders'] FAKE_FOLDERS_OK_IAM_DB_ROWS = [ {'folder_id': '1111111111', 'display_name': 'Folder1', 'lifecycle_state': 'ACTIVE', 'parent_id': '9999', 'parent_type': 'organizations', 'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:a@b.c"]}]}'}, {'folder_id': '2222222222', 'display_name': 'Folder2', 'lifecycle_state': 'ACTIVE', 'parent_id': None, 'parent_type': None, 'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:d@e.f"]}]}'}, ] FAKE_FOLDERS_BAD_IAM_DB_ROWS = [ {'folder_id': '1111111111', 'display_name': 'Folder1', 'lifecycle_state': 'ACTIVE', 'parent_id': '9999', 'parent_type': 'organizations', 'iam_policy': '{"bindings": [{"role": "roles/viewer", "members": ["user:a@b.c"]}]}'}, {'folder_id': '2222222222', 'display_name': 'Folder2', 'lifecycle_state': 'ACTIVE', 'parent_id': None, 'parent_type': None, 'iam_policy': ''}, ] FAKE_FOLDERS_API_RESPONSE1 = { 'folders': [ { 'displayName': 'folder-1', 'name': 'folders/111', 'parent': 'folders/1111111', 'lifecycleState': 'ACTIVE', 'parent': 'organizations/9999' }, { 'displayName': 'folder-2', 'name': 'folders/222', 'parent': 'folders/2222222', 'lifecycleState': 'DELETE_REQUESTED' }, { 'displayName': 'folder-3', 'name': 'folders/333', 'parent': 'folders/3333333', 'lifecycleState': 'ACTIVE' }, ] } EXPECTED_FAKE_FOLDERS1 = FAKE_FOLDERS_API_RESPONSE1['folders'] FAKE_FOLDERS_LIST_API_RESPONSE1 = { 'folders': [ f for f in FAKE_FOLDERS_API_RESPONSE1['folders'] if f['parent'] == 'organizations/9999' ] } EXPECTED_FAKE_FOLDERS_LIST1 = FAKE_FOLDERS_LIST_API_RESPONSE1['folders'] FAKE_ACTIVE_FOLDERS_API_RESPONSE1 = { 'folders': [ f for f in FAKE_FOLDERS_API_RESPONSE1['folders'] if f['lifecycleState'] == 'ACTIVE' ] } EXPECTED_FAKE_ACTIVE_FOLDERS1 = FAKE_ACTIVE_FOLDERS_API_RESPONSE1['folders']
class Security: def __init__(self, name, ticker, country, ir_website, currency): self.name = name.strip() self.ticker = ticker.strip() self.country = country.strip() self.currency = currency.strip() self.ir_website = ir_website.strip() @staticmethod def summary(name, ticker): return f"{name} ({ticker})" @staticmethod def example_input(): return "Air-Products APD.US US http://investors.airproducts.com/upcoming-events USD"
def plot_frames(motion, ax, times=1, fps=0.01): joints = [j for j in motion.joint_names() if not j.startswith('ignore_')] x, ys = [], [] for t, frame in motion.frames(fps): x.append(t) ys.append(frame.positions) if t > motion.length() * times: break for joint in joints: ax.plot(x, [y[joint] for y in ys], label=joint)
# Copyright 2016 Google Inc. All Rights Reserved. # # 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. """Wait messages for the compute instance groups managed commands.""" _CURRENT_ACTION_TYPES = ['abandoning', 'creating', 'creatingWithoutRetries', 'deleting', 'recreating', 'refreshing', 'restarting', 'verifying'] _PENDING_ACTION_TYPES = ['creating', 'deleting', 'restarting', 'recreating'] def IsGroupStable(igm_ref): """Checks if IGM is has no current actions on instances. Args: igm_ref: reference to the Instance Group Manager. Returns: True if IGM has no current actions, false otherwise. """ return not any(getattr(igm_ref.currentActions, action, 0) for action in _CURRENT_ACTION_TYPES) def IsGroupStableAlpha(igm_ref): """Checks if IGM is has no current or pending actions on instances. Args: igm_ref: reference to the Instance Group Manager. Returns: True if IGM has no current actions, false otherwise. """ no_current_actions = not any(getattr(igm_ref.currentActions, action, 0) for action in _CURRENT_ACTION_TYPES) no_pending_actions = not any(getattr(igm_ref.pendingActions, action, 0) for action in _PENDING_ACTION_TYPES) return no_current_actions and no_pending_actions def CreateWaitText(igm_ref): """Creates text presented at each wait operation. Args: igm_ref: reference to the Instance Group Manager. Returns: A message with current operations count for IGM. """ text = 'Waiting for group to become stable' current_actions_text = _CreateActionsText( ', current operations: ', igm_ref.currentActions, _CURRENT_ACTION_TYPES) return text + current_actions_text def CreateWaitTextAlpha(igm_ref): """Creates text presented at each wait operation. Args: igm_ref: reference to the Instance Group Manager. Returns: A message with current and pending operations count for IGM. """ text = 'Waiting for group to become stable' current_actions_text = _CreateActionsText( ', current operations: ', igm_ref.currentActions, _CURRENT_ACTION_TYPES) pending_actions_text = _CreateActionsText( ', pending operations: ', igm_ref.pendingActions, _PENDING_ACTION_TYPES) return text + current_actions_text + pending_actions_text def _CreateActionsText(text, igm_field, action_types): """Creates text presented at each wait operation for given IGM field. Args: text: the text associated with the field. igm_field: reference to a field in the Instance Group Manager. action_types: array with field values to be counted. Returns: A message with given field and action types count for IGM. """ actions = [] for action in action_types: action_count = getattr(igm_field, action, 0) if action_count > 0: actions.append('{0}: {1}'.format(action, action_count)) return text + ', '.join(actions) if actions else ''
default_vimrc = "\ set fileencoding=utf-8 fileformat=unix\n\ call plug#begin('~/.vim/plugged')\n\ Plug 'prabirshrestha/async.vim'\n\ Plug 'prabirshrestha/vim-lsp'\n\ Plug 'prabirshrestha/asyncomplete.vim'\n\ Plug 'prabirshrestha/asyncomplete-lsp.vim'\n\ Plug 'mattn/vim-lsp-settings'\n\ Plug 'prabirshrestha/asyncomplete-file.vim'\n\ Plug 'prabirshrestha/asyncomplete-buffer.vim'\n\ Plug 'vim-airline/vim-airline'\n\ Plug 'vim-airline/vim-airline-themes'\n\ Plug 'elzr/vim-json'\n\ Plug 'cohama/lexima.vim'\n\ Plug '{}'\n\ Plug 'cespare/vim-toml'\n\ Plug 'tpope/vim-markdown'\n\ Plug 'kannokanno/previm'\n\ Plug 'tyru/open-browser.vim'\n\ Plug 'ryanoasis/vim-devicons'\n\ Plug 'scrooloose/nerdtree'\n\ Plug 'mattn/emmet-vim'\n\ Plug 'vim/killersheep'\n\ \n\ call plug#end()\n\ \n\ syntax enable\n\ colorscheme {}\n\ set background=dark\n\ \n\ set hlsearch\n\ set cursorline\n\ set cursorcolumn\n\ set number\n\ set foldmethod=marker\n\ set backspace=indent,eol,start\n\ set clipboard^=unnamedplus\n\ set nostartofline\n\ noremap <silent><C-x> :bdelete<CR>\n\ noremap <silent><C-h> :bprevious<CR>\n\ noremap <silent><C-l> :bnext<CR>\n\ set ruler\n\ set noerrorbells\n\ set laststatus={}\n\ set shiftwidth={}\n\ set tabstop={}\n\ set softtabstop={}\n\ set expandtab\n\ set smarttab\n\ set cindent\n\ " indent_setting_base = "\ augroup {}Indent\n\ autocmd!\n\ autocmd FileType {} set tabstop={} softtabstop={} shitwidth={}\n\ augroup END\n\ "
extensions = ["myst_parser"] exclude_patterns = ["_build"] copyright = "2020, Executable Book Project" myst_enable_extensions = ["deflist"]
# encoding: utf-8 """ Configuration file. Please prefix application specific config values with the application name. """ # Slack settings SLACKBACK_CHANNEL = '#feedback' SLACKBACK_EMOJI = ':goberserk:' SLACKBACK_USERNAME = 'TownCrier' # These values are necessary only if the app needs to be a client of the API FEEDBACK_SLACK_END_POINT = 'https://hooks.slack.com/services/TOKEN/TOKEN' GOOGLE_RECAPTCHA_ENDPOINT = 'https://www.google.com/recaptcha/api/siteverify' GOOGLE_RECAPTCHA_PRIVATE_KEY = 'MY_RECAPTCHA_KEY' # Log settings SLACKBACK_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(levelname)s\t%(process)d ' '[%(asctime)s]:\t%(message)s', 'datefmt': '%m/%d/%Y %H:%M:%S', } }, 'handlers': { 'file': { 'formatter': 'default', 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': '/tmp/slackback.log', }, 'console': { 'formatter': 'default', 'level': 'DEBUG', 'class': 'logging.StreamHandler' } }, 'loggers': { '': { 'handlers': ['file', 'console'], 'level': 'DEBUG', 'propagate': True, }, }, }
# Given a list and a num. Write a function to return boolean if that element is not in the list. def check_num_in_list(alist, num): for i in alist: if num in alist and num%2 != 0: return True else: return False sample = check_num_in_list([2,7,3,1,6,9], 6) print(sample)
z = 10 y = 0 x = y < z and z > y or y > z and z < y print(x) # X = True
# 输入:[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]] # 目标是找到上下左右相连的1,即为连续岛屿 # 第一遍 class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 row = len(grid) col = len(grid[0]) cnt = 0 # 自顶向下编程 def dfs(i, j): # terminator if grid[i][j] == "0": return # process current logic grid[i][j] = "0" # drill down for x, y in [[-1, 0], [1, 0], [0, -1], [0, 1]]: # 向此点的上下左右做深度搜索 tmp_i = i + x tmp_j = j + y if 0 <= tmp_i < row and 0 <= tmp_j < col and grid[tmp_i][tmp_j] == "1": # 边界条件 dfs(tmp_i, tmp_j) for i in range(row): # 这段代码体现总体思路:dfs作用是把1以及上下左右连环炸平,斩草除根,执行dfs完毕之后cnt加1,记作岛的数量 for j in range(col): if grid[i][j] == "1": dfs(i, j) cnt += 1 return cnt
""" Global constants. """ # Instrument message fields INSTRUMENTS = 'instruments' INSTRUMENT_ID = 'instrumentID' EXCHANGE_ID = 'exchangeID' INSTRUMENT_SYMBOL = 'symbol' INSTRUMENT_TRADING_HOURS = 'instrument_trading_hours' UNIT_SIZE = 'unit_size' # future's contract unit size TICK_SIZE = 'tick_size' MARGIN_TYPE = 'margin_type' MARGIN_RATE = 'margin_rate' OPEN_COMM_TYPE = 'open_comm_type' OPEN_COMM_RATE = 'open_comm_rate' CLOSE_COMM_TYPE = 'close_comm_type' CLOSE_COMM_RATE = 'close_comm_rate' CLOSE_TODAY_COMM_TYPE = 'close_today_comm_type' CLOSE_TODAY_COMM_RATE = 'close_today_comm_rate' # Tick message fields ASK = 'ask' BID = 'bid' ASK_VOLUME = 'askVolume' BID_VOLUME = 'bidVolume' HIGH_LIMIT = 'highLimit' LOW_LIMIT = 'lowLimit' # Order and trade message fields PRICE = 'price' VOLUME = 'volume' DIRECTION_LONG = 'long' DIRECTION_SHORT = 'short' DIRECTION = 'direction' BUY = '0' SELL = '1' ORDER_ID = 'orderID' TRADE_ID = 'tradeID' QTY = 'qty' TRADED_QTY = 'traded_qty' TAG = 'tag' ORDER_ACTION = 'order_action' ORDER_STATUS = 'order_status' ORDER_CREATE_DATE = 'order_create_date' ORDER_EXPIRATION_DATE = 'order_expiration_date' ORDER_ACCEPT_FLAG = 'order_accept_flag' BUY_ORDERS = 'buy_orders' SELL_ORDERS = 'sell_orders' ORDER_IDS = 'order_ids' # Order cancel type CANCEL_TYPE = 'cancel_type' CANCEL_ALL = 0 CANCEL_OPEN_ORDERS = 1 CANCEL_CLOSE_ORDERS = 2 CANCEL_STOPLOSS_ORDERS = 3 CANCEL_ORDERS = 4 # Order status ORDER_ACCEPTED = 'order_status_accepted' ORDER_OPEN = 'order_status_open' ORDER_CLOSED = 'order_status_closed' ORDER_CLOSED_ALIAS = 'order_status_executed' ORDER_REJECTED = 'order_status_rejected' ORDER_CANCELLED = 'order_status_cancelled' ORDER_CANCEL_SUBMITTED = 'order_status_cancel_submitted' ORDER_PARTIAL_CLOSED = 'order_status_partial_closed' ORDER_NO_CANCEL = 'order_status_no_cancel' ORDER_REPEAT_CANCEL = 'order_status_repeat_cancel' # Broker data fields PORTFOLIO_ID = 'portfolioID' ACCOUNT_ID = 'accountID' # Strategy debug log message strings STRATEGY_CONFIG = "The strategy has been configured." STRATEGY_OPEN = "The strategy opens a position. Params: [%s]" STRATEGY_CLOSE = "The strategy closes a position. Params: [%s]" STRATEGY_START = "The strategy is starting..." STRATEGY_STOP = "The strategy is stopping..." STRATEGY_SUSPEND = "The strategy is suspending..." STRATEGY_RESUME = "The strategy is resuming..." STRATEGY_STOPPED = "The strategy has stopped." STRATEGY_SETTING_PARAMS = "The strategy parameters: [%s]" ON_TICK = "onTick triggered with the event: [%s]" ON_UPDATE_ORDER_STATUS = "Updating order status. Params [%s]" ON_PROFIT_CHANGE = "EVENT_PROFITCHANGED triggered. Params: [%s]" ON_BUY = "EVENT_BUY triggered. Params: [%s]" ON_SELL = "EVENT_SELL triggered. Params: [%s]" # Misc COMPARED_FLOAT = 0.0000001 INVALID_VALUE = -1.0 TAG_DEFAULT_VALUE = '' APP_ID = 'app_id'
# Merge Sort: D&C Algo, Breaks data into individual pieces and merges them, uses recursion to operate on datasets. Key is to understand how to merge 2 sorted arrays. items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53] def mergesort(dataset): if len(dataset) > 1: mid = len(dataset) // 2 leftarr = dataset[:mid] rightarr = dataset[mid:] # TODO: Recursively break down the arrays mergesort(leftarr) mergesort(rightarr) # TODO: Perform merging i = 0 # index into the left array j = 0 # index into the right array k = 0 # index into the merger array while i < len(leftarr) and j < len(rightarr): if(leftarr[i] <= rightarr[j]): dataset[k] = leftarr[i] i += 1 else: dataset[k] = rightarr[j] j += 1 k += 1 while i < len(leftarr): dataset[k] = leftarr[i] i += 1 k += 1 while j < len(rightarr): dataset[k] = rightarr[j] j += 1 k += 1 print(items) mergesort(items) print(items)
def nameCreator(playerName): firstLetter = playerName.split(" ")[1][0] try: lastName = playerName.split(" ")[1][0:5] except: lastNameSize = len(playerName.split(" ")[1]) lastName = playerName.split(" ")[1][len(lastNameSize)] firstName = playerName[0:2] return lastName + firstName + '0', firstLetter
# Copyright: 2005-2008 Brian Harring <ferringb@gmail.com> # License: GPL2/BSD """ exceptions thrown by repository classes. Need to extend the usage a bit further still. """ __all__ = ("TreeCorruption", "InitializationError") class TreeCorruption(Exception): def __init__(self, err): Exception.__init__(self, "unexpected tree corruption: %s" % (err,)) self.err = err class InitializationError(TreeCorruption): def __str__(self): return "initialization failed: %s" % str(self.err)
class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ ret = [[0 for j in range(len(B[0]))] for i in range(len(A))] for i, row in enumerate(A): for k, a in enumerate(row): if a: for j, b in enumerate(B[k]): if b: ret[i][j] += a * b return ret
# Author : Aniruddha Krishna Jha # Date : 22/10/2021 '''********************************************************************************** Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. **********************************************************************************''' class Solution: def maxEqualFreq(self, nums: List[int]) -> int: cnt,freq,maxF,res = collections.defaultdict(int), collections.defaultdict(int),0,0 for i,num in enumerate(nums): cnt[num] += 1 freq[cnt[num]-1] -= 1 freq[cnt[num]] += 1 maxF = max(maxF,cnt[num]) if maxF*freq[maxF] == i or (maxF-1)*(freq[maxF-1]+1) == i or maxF == 1: res = i + 1 return res
def truthTable(n): # 主函數 p = [] # p 代表已經排下去的,一開始還沒排,所以是空的 return tableNext(n, p) # 呼叫 tableNext 遞迴下去排出所有可能 def tableNext(n, p):# n : n個變數的真值表, p :代表已經排下去的 i = len(p) if i == n: # 全部排好了 print(p) # 印出排列 return binary=[0,1] for x in binary: p.append(x) # 把 x 放進表 #print("append:",p) tableNext(n, p) # 繼續遞迴尋找下一個排列 p.pop() # 把 x 移出表 #print("pop:",p) a = input("請輸入想要幾個變數:") truthTable(int(a))
#!/usr/bin/env python3 """ Write a function called sed that takes as arguments a pattern string, a replacement string, and two filenames; it should read the first file and write the contents into the second file (creating it if necessary). If the pattern string appears anywhere in the file, it should be replaced with the replacement string. If an error occurs while opening, reading, writing or closing files, your program should catch the exception, print an error message, and exit. """ def sed(patern, replacement, s_file, d_file): try: source_f = open(s_file, mode='r') dest_f = open(d_file, mode='a') content = source_f.read() dest_f.write(content.replace(patern, replacement)) except: print("Something went wrong") if __name__ == "__main__": sed("gosho", "ilian", "file_s", "file_d")
# invertFontSelection.py """ Inverts selection in the current font """ for glyph in CurrentFont(): if glyph.selected: glyph.selected = False else: glyph.selected = True
class BTNode: '''Binary Tree Node class - do not modify''' def __init__(self, value, left, right): '''Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None.''' self.value = value self.left = left self.right = right class BST: def __init__(self): # reference to root node - do not modify self.root = None def insert(self, value): '''Takes a numeric value as argument. Inserts value into tree, maintaining correct ordering. Returns nothing.''' if self.root is None: self.root = BTNode(value, None, None) return self.insert2(self.root, value) def insert2(self, node, value): if value < node.value: if node.left is None: node.left = BTNode(value, None, None) return self.insert2(node.left, value) elif value > node.value: if node.right is None: node.right = BTNode(value, None, None) return self.insert2(node.right, value) else: return def search(self, value): '''Takes a numeric value as argument. Returns True if its in the tree, false otherwise.''' return self.search2(self.root, value) def search2(self, node, value): if node is None: return False if value == node.value: return True elif value < node.value: return self.search2(node.left, value) else: return self.search2(node.right, value) def height(self): '''Returns the height of the tree. A tree with 0 or 1 nodes has a height of 0.''' return self.height2(self.root) - 1 def height2(self, node): if node is None: return 0 return max(self.height2(node.left), self.height2(node.right)) + 1 def preorder(self): '''Returns a list of the values in the tree, in pre-order order.''' return self.preorder2(self.root, []) def preorder2(self, node, lst): if node is not None: lst.append(node.value) self.preorder2(node.left, lst) self.preorder2(node.right, lst) return lst #bst = BST() #for value in [4, 2, 5, 3, 1, 6, 7]: # bst.insert(value) ## BST now looks like this: ## 4 ## / \ ## 2 5 ## / \ \ ## 1 3 6 ## \ ## 7 #print(bst.search(5)) # True #print(bst.search(8)) # False #print(bst.preorder()) # [4, 2, 1, 3, 5, 6, 7] #print(bst.height()) # 3
checksum = 0 with open("Day 2 - input", "r") as file: for line in file: row = [int(i) for i in line.split()] result = max(row) - min(row) checksum += result print(f"The checksum is {checksum}")
def bytes_to(bytes_value, to_unit, bytes_size=1024): units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6} return round(float(bytes_value) / (bytes_size ** units[to_unit]), 2) def convert_to_human(value): if value < 1024: return str(value) + 'b' if value < 1048576: return str(bytes_to(value, 'k')) + 'k' if value < 1073741824: return str(bytes_to(value, 'm')) + 'm' return str(bytes_to(value, 'g')) + 'g' def convert_to_human_with_limits(value, limit): if value < limit: return convert_to_human(value) return "[bold magenta]" + convert_to_human(value) + "[/]"
TLDS = [ "ABB", "ABBOTT", "ABOGADO", "AC", "ACADEMY", "ACCENTURE", "ACCOUNTANT", "ACCOUNTANTS", "ACTIVE", "ACTOR", "AD", "ADS", "ADULT", "AE", "AEG", "AERO", "AF", "AFL", "AG", "AGENCY", "AI", "AIG", "AIRFORCE", "AL", "ALLFINANZ", "ALSACE", "AM", "AMSTERDAM", "AN", "ANDROID", "AO", "APARTMENTS", "AQ", "AQUARELLE", "AR", "ARCHI", "ARMY", "ARPA", "AS", "ASIA", "ASSOCIATES", "AT", "ATTORNEY", "AU", "AUCTION", "AUDIO", "AUTO", "AUTOS", "AW", "AX", "AXA", "AZ", "AZURE", "BA", "BAND", "BANK", "BAR", "BARCLAYCARD", "BARCLAYS", "BARGAINS", "BAUHAUS", "BAYERN", "BB", "BBC", "BBVA", "BD", "BE", "BEER", "BERLIN", "BEST", "BF", "BG", "BH", "BHARTI", "BI", "BIBLE", "BID", "BIKE", "BING", "BINGO", "BIO", "BIZ", "BJ", "BLACK", "BLACKFRIDAY", "BLOOMBERG", "BLUE", "BM", "BMW", "BN", "BNL", "BNPPARIBAS", "BO", "BOATS", "BOND", "BOO", "BOUTIQUE", "BR", "BRADESCO", "BRIDGESTONE", "BROKER", "BROTHER", "BRUSSELS", "BS", "BT", "BUDAPEST", "BUILD", "BUILDERS", "BUSINESS", "BUZZ", "BV", "BW", "BY", "BZ", "BZH", "CA", "CAB", "CAFE", "CAL", "CAMERA", "CAMP", "CANCERRESEARCH", "CANON", "CAPETOWN", "CAPITAL", "CARAVAN", "CARDS", "CARE", "CAREER", "CAREERS", "CARS", "CARTIER", "CASA", "CASH", "CASINO", "CAT", "CATERING", "CBA", "CBN", "CC", "CD", "CENTER", "CEO", "CERN", "CF", "CFA", "CFD", "CG", "CH", "CHANNEL", "CHAT", "CHEAP", "CHLOE", "CHRISTMAS", "CHROME", "CHURCH", "CI", "CISCO", "CITIC", "CITY", "CK", "CL", "CLAIMS", "CLEANING", "CLICK", "CLINIC", "CLOTHING", "CLOUD", "CLUB", "CM", "CN", "CO", "COACH", "CODES", "COFFEE", "COLLEGE", "COLOGNE", "COM", "COMMBANK", "COMMUNITY", "COMPANY", "COMPUTER", "CONDOS", "CONSTRUCTION", "CONSULTING", "CONTRACTORS", "COOKING", "COOL", "COOP", "CORSICA", "COUNTRY", "COUPONS", "COURSES", "CR", "CREDIT", "CREDITCARD", "CRICKET", "CROWN", "CRS", "CRUISES", "CU", "CUISINELLA", "CV", "CW", "CX", "CY", "CYMRU", "CYOU", "CZ", "DABUR", "DAD", "DANCE", "DATE", "DATING", "DATSUN", "DAY", "DCLK", "DE", "DEALS", "DEGREE", "DELIVERY", "DEMOCRAT", "DENTAL", "DENTIST", "DESI", "DESIGN", "DEV", "DIAMONDS", "DIET", "DIGITAL", "DIRECT", "DIRECTORY", "DISCOUNT", "DJ", "DK", "DM", "DNP", "DO", "DOCS", "DOG", "DOHA", "DOMAINS", "DOOSAN", "DOWNLOAD", "DRIVE", "DURBAN", "DVAG", "DZ", "EARTH", "EAT", "EC", "EDU", "EDUCATION", "EE", "EG", "EMAIL", "EMERCK", "ENERGY", "ENGINEER", "ENGINEERING", "ENTERPRISES", "EPSON", "EQUIPMENT", "ER", "ERNI", "ES", "ESQ", "ESTATE", "ET", "EU", "EUROVISION", "EUS", "EVENTS", "EVERBANK", "EXCHANGE", "EXPERT", "EXPOSED", "EXPRESS", "FAIL", "FAITH", "FAN", "FANS", "FARM", "FASHION", "FEEDBACK", "FI", "FILM", "FINANCE", "FINANCIAL", "FIRMDALE", "FISH", "FISHING", "FIT", "FITNESS", "FJ", "FK", "FLIGHTS", "FLORIST", "FLOWERS", "FLSMIDTH", "FLY", "FM", "FO", "FOO", "FOOTBALL", "FOREX", "FORSALE", "FORUM", "FOUNDATION", "FR", "FRL", "FROGANS", "FUND", "FURNITURE", "FUTBOL", "FYI", "GA", "GAL", "GALLERY", "GARDEN", "GB", "GBIZ", "GD", "GDN", "GE", "GENT", "GENTING", "GF", "GG", "GGEE", "GH", "GI", "GIFT", "GIFTS", "GIVES", "GL", "GLASS", "GLE", "GLOBAL", "GLOBO", "GM", "GMAIL", "GMO", "GMX", "GN", "GOLD", "GOLDPOINT", "GOLF", "GOO", "GOOG", "GOOGLE", "GOP", "GOV", "GP", "GQ", "GR", "GRAPHICS", "GRATIS", "GREEN", "GRIPE", "GS", "GT", "GU", "GUGE", "GUIDE", "GUITARS", "GURU", "GW", "GY", "HAMBURG", "HANGOUT", "HAUS", "HEALTHCARE", "HELP", "HERE", "HERMES", "HIPHOP", "HITACHI", "HIV", "HK", "HM", "HN", "HOCKEY", "HOLDINGS", "HOLIDAY", "HOMEDEPOT", "HOMES", "HONDA", "HORSE", "HOST", "HOSTING", "HOTELES", "HOTMAIL", "HOUSE", "HOW", "HR", "HT", "HU", "IBM", "ICBC", "ICU", "ID", "IE", "IFM", "IL", "IM", "IMMO", "IMMOBILIEN", "IN", "INDUSTRIES", "INFINITI", "INFO", "ING", "INK", "INSTITUTE", "INSURE", "INT", "INTERNATIONAL", "INVESTMENTS", "IO", "IQ", "IR", "IRISH", "IS", "IT", "IWC", "JAVA", "JCB", "JE", "JETZT", "JEWELRY", "JLC", "JLL", "JM", "JO", "JOBS", "JOBURG", "JP", "JUEGOS", "KAUFEN", "KDDI", "KE", "KG", "KH", "KI", "KIM", "KITCHEN", "KIWI", "KM", "KN", "KOELN", "KOMATSU", "KP", "KR", "KRD", "KRED", "KW", "KY", "KYOTO", "KZ", "LA", "LACAIXA", "LAND", "LASALLE", "LAT", "LATROBE", "LAW", "LAWYER", "LB", "LC", "LDS", "LEASE", "LECLERC", "LEGAL", "LGBT", "LI", "LIAISON", "LIDL", "LIFE", "LIGHTING", "LIMITED", "LIMO", "LINK", "LK", "LOAN", "LOANS", "LOL", "LONDON", "LOTTE", "LOTTO", "LOVE", "LR", "LS", "LT", "LTDA", "LU", "LUPIN", "LUXE", "LUXURY", "LV", "LY", "MA", "MADRID", "MAIF", "MAISON", "MANAGEMENT", "MANGO", "MARKET", "MARKETING", "MARKETS", "MARRIOTT", "MBA", "MC", "MD", "ME", "MEDIA", "MEET", "MELBOURNE", "MEME", "MEMORIAL", "MEN", "MENU", "MG", "MH", "MIAMI", "MICROSOFT", "MIL", "MINI", "MK", "ML", "MM", "MMA", "MN", "MO", "MOBI", "MODA", "MOE", "MONASH", "MONEY", "MONTBLANC", "MORMON", "MORTGAGE", "MOSCOW", "MOTORCYCLES", "MOV", "MOVIE", "MOVISTAR", "MP", "MQ", "MR", "MS", "MT", "MTN", "MTPC", "MU", "MUSEUM", "MV", "MW", "MX", "MY", "MZ", "NA", "NADEX", "NAGOYA", "NAME", "NAVY", "NC", "NE", "NEC", "NET", "NETBANK", "NETWORK", "NEUSTAR", "NEW", "NEWS", "NEXUS", "NF", "NG", "NGO", "NHK", "NI", "NICO", "NINJA", "NISSAN", "NL", "NO", "NP", "NR", "NRA", "NRW", "NTT", "NU", "NYC", "NZ", "OFFICE", "OKINAWA", "OM", "OMEGA", "ONE", "ONG", "ONL", "ONLINE", "OOO", "ORACLE", "ORG", "ORGANIC", "OSAKA", "OTSUKA", "OVH", "PA", "PAGE", "PANERAI", "PARIS", "PARTNERS", "PARTS", "PARTY", "PE", "PF", "PG", "PH", "PHARMACY", "PHILIPS", "PHOTO", "PHOTOGRAPHY", "PHOTOS", "PHYSIO", "PIAGET", "PICS", "PICTET", "PICTURES", "PINK", "PIZZA", "PK", "PL", "PLACE", "PLAY", "PLUMBING", "PLUS", "PM", "PN", "POHL", "POKER", "PORN", "POST", "PR", "PRAXI", "PRESS", "PRO", "PROD", "PRODUCTIONS", "PROF", "PROPERTIES", "PROPERTY", "PS", "PT", "PUB", "PW", "PY", "QA", "QPON", "QUEBEC", "RACING", "RE", "REALTOR", "REALTY", "RECIPES", "RED", "REDSTONE", "REHAB", "REISE", "REISEN", "REIT", "REN", "RENT", "RENTALS", "REPAIR", "REPORT", "REPUBLICAN", "REST", "RESTAURANT", "REVIEW", "REVIEWS", "RICH", "RICOH", "RIO", "RIP", "RO", "ROCKS", "RODEO", "RS", "RSVP", "RU", "RUHR", "RUN", "RW", "RYUKYU", "SA", "SAARLAND", "SALE", "SAMSUNG", "SANDVIK", "SANDVIKCOROMANT", "SAP", "SARL", "SAXO", "SB", "SC", "SCA", "SCB", "SCHMIDT", "SCHOLARSHIPS", "SCHOOL", "SCHULE", "SCHWARZ", "SCIENCE", "SCOR", "SCOT", "SD", "SE", "SEAT", "SENER", "SERVICES", "SEW", "SEX", "SEXY", "SG", "SH", "SHIKSHA", "SHOES", "SHOW", "SHRIRAM", "SI", "SINGLES", "SITE", "SJ", "SK", "SKI", "SKY", "SKYPE", "SL", "SM", "SN", "SNCF", "SO", "SOCCER", "SOCIAL", "SOFTWARE", "SOHU", "SOLAR", "SOLUTIONS", "SONY", "SOY", "SPACE", "SPIEGEL", "SPREADBETTING", "SR", "ST", "STARHUB", "STATOIL", "STUDY", "STYLE", "SU", "SUCKS", "SUPPLIES", "SUPPLY", "SUPPORT", "SURF", "SURGERY", "SUZUKI", "SV", "SWATCH", "SWISS", "SX", "SY", "SYDNEY", "SYSTEMS", "SZ", "TAIPEI", "TATAR", "TATTOO", "TAX", "TAXI", "TC", "TD", "TEAM", "TECH", "TECHNOLOGY", "TEL", "TELEFONICA", "TEMASEK", "TENNIS", "TF", "TG", "TH", "THD", "THEATER", "TICKETS", "TIENDA", "TIPS", "TIRES", "TIROL", "TJ", "TK", "TL", "TM", "TN", "TO", "TODAY", "TOKYO", "TOOLS", "TOP", "TORAY", "TOSHIBA", "TOURS", "TOWN", "TOYS", "TR", "TRADE", "TRADING", "TRAINING", "TRAVEL", "TRUST", "TT", "TUI", "TV", "TW", "TZ", "UA", "UG", "UK", "UNIVERSITY", "UNO", "UOL", "US", "UY", "UZ", "VA", "VACATIONS", "VC", "VE", "VEGAS", "VENTURES", "VERSICHERUNG", "VET", "VG", "VI", "VIAJES", "VIDEO", "VILLAS", "VISION", "VISTA", "VISTAPRINT", "VLAANDEREN", "VN", "VODKA", "VOTE", "VOTING", "VOTO", "VOYAGE", "VU", "WALES", "WALTER", "WANG", "WATCH", "WEBCAM", "WEBSITE", "WED", "WEDDING", "WEIR", "WF", "WHOSWHO", "WIEN", "WIKI", "WILLIAMHILL", "WIN", "WINDOWS", "WME", "WORK", "WORKS", "WORLD", "WS", "WTC", "WTF", "XBOX", "XEROX", "XIN", "XN--1QQW23A", "XN--30RR7Y", "XN--3BST00M", "XN--3DS443G", "XN--3E0B707E", "XN--45BRJ9C", "XN--45Q11C", "XN--4GBRIM", "XN--55QW42G", "XN--55QX5D", "XN--6FRZ82G", "XN--6QQ986B3XL", "XN--80ADXHKS", "XN--80AO21A", "XN--80ASEHDB", "XN--80ASWG", "XN--90A3AC", "XN--90AIS", "XN--9ET52U", "XN--B4W605FERD", "XN--C1AVG", "XN--CG4BKI", "XN--CLCHC0EA0B2G2A9GCD", "XN--CZR694B", "XN--CZRS0T", "XN--CZRU2D", "XN--D1ACJ3B", "XN--D1ALF", "XN--ESTV75G", "XN--FIQ228C5HS", "XN--FIQ64B", "XN--FIQS8S", "XN--FIQZ9S", "XN--FJQ720A", "XN--FLW351E", "XN--FPCRJ9C3D", "XN--FZC2C9E2C", "XN--GECRJ9C", "XN--H2BRJ9C", "XN--HXT814E", "XN--I1B6B1A6A2E", "XN--IMR513N", "XN--IO0A7I", "XN--J1AMH", "XN--J6W193G", "XN--KCRX77D1X4A", "XN--KPRW13D", "XN--KPRY57D", "XN--KPUT3I", "XN--L1ACC", "XN--LGBBAT1AD8J", "XN--MGB9AWBF", "XN--MGBA3A4F16A", "XN--MGBAAM7A8H", "XN--MGBAB2BD", "XN--MGBAYH7GPA", "XN--MGBBH1A71E", "XN--MGBC0A9AZCG", "XN--MGBERP4A5D4AR", "XN--MGBPL2FH", "XN--MGBX4CD0AB", "XN--MXTQ1M", "XN--NGBC5AZD", "XN--NODE", "XN--NQV7F", "XN--NQV7FS00EMA", "XN--NYQY26A", "XN--O3CW4H", "XN--OGBPF8FL", "XN--P1ACF", "XN--P1AI", "XN--PGBS0DH", "XN--Q9JYB4C", "XN--QCKA1PMC", "XN--RHQV96G", "XN--S9BRJ9C", "XN--SES554G", "XN--UNUP4Y", "XN--VERMGENSBERATER-CTB", "XN--VERMGENSBERATUNG-PWB", "XN--VHQUV", "XN--VUQ861B", "XN--WGBH1C", "XN--WGBL6A", "XN--XHQ521B", "XN--XKC2AL3HYE2A", "XN--XKC2DL3A5EE0H", "XN--Y9A3AQ", "XN--YFRO4I67O", "XN--YGBI2AMMX", "XN--ZFR164B", "XXX", "XYZ", "YACHTS", "YANDEX", "YE", "YODOBASHI", "YOGA", "YOKOHAMA", "YOUTUBE", "YT", "ZA", "ZIP", "ZM", "ZONE", "ZUERICH", "ZW", ]
class Bank: def __init__(self): self.inf = 0 self._observers = [] def register_observer(self, observer): self._observers.append(observer) def notify_observers(self): print("Inflacja na poziomie: ", format(self.inf, '.2f')) for observer in self._observers: observer.notify(self)
fruta = 'kiwi' if fruta == 'kiwi': print("El valor es kiwi") elif fruta == 'manzana': print("Es una manzana") elif fruta == 'manzana2': pass #si no sabemos que poner y no marque error else: print("No son iguales") mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False print(mensaje)
# Status code API_HANDLER_OK_CODE = 200 API_HANDLER_ERROR_CODE = 400 # REST parameters SERVICE_HANDLER_POST_ARG_KEY = "key" SERVICE_HANDLER_POST_BODY_KEY = "body_key"