content
stringlengths
7
1.05M
""" 1. 引用计数 最简单直接的办法, 对每个对象维护一个引用计数, 起始为1. 缺点: 维护引用计数消耗资源 循环引用有内存泄漏 """ class A: def __init__(self, b): self.a = 10 self.b = b class B: def __init__(self, a): self.b = 10 self.a = a
"""Constants""" DOMAIN = "grocy" DOMAIN_DATA = "{}_data".format(DOMAIN) DOMAIN_EVENT = "grocy_updated" DOMAIN_SERVICE = "{}" # Integration local data DATA_GROCY = "grocy" DATA_DATA = "data" DATA_ENTITIES = "entities" DATA_STORE_CONF = "store_conf" # Domain events EVENT_ADDED_TO_LIST='added_to_list' EVENT_SUBTRACT_FROM_LIST='subtract_from_list' EVENT_PRODUCT_REMOVED='product_removed' EVENT_PRODUCT_ADDED='product_added' EVENT_PRODUCT_UPDATED='product_updated' EVENT_SYNC_DONE='sync_done' EVENT_GROCY_ERROR='error' # Configuration CONF_APIKEY = "apikey" CONF_AMOUNT = "amount" CONF_NAME = "name" CONF_VALUE = "value" CONF_SHOPPING_LIST_ID = 'shopping_list' CONF_PRODUCT_DESCRIPTION = 'product_description' CONF_PRODUCT_GROUP_ID = 'product_group_id' CONF_PRODUCT_LOCATION_ID = 'product_location_id' CONF_STORE = 'store' CONF_BARCODE = 'barcode' CONF_UNIT_OF_MEASUREMENT = 'unit_of_measurement' # Defaults DEFAULT_AMOUNT = 1 DEFAULT_STORE = '' DEFAULT_SHOPPING_LIST_ID = 1 DEFAULT_PRODUCT_DESCRIPTION = "" # Services ADD_TO_LIST_SERVICE = DOMAIN_SERVICE.format('add_to_list') SUBTRACT_FROM_LIST_SERVICE = DOMAIN_SERVICE.format('subtract_from_list') ADD_PRODUCT_SERVICE = DOMAIN_SERVICE.format('add_product') REMOVE_PRODUCT_SERVICE = DOMAIN_SERVICE.format('remove_product') ADD_FAVORITE_SERVICE = DOMAIN_SERVICE.format('add_favorite') REMOVE_FAVORITE_SERVICE = DOMAIN_SERVICE.format('remove_favorite') FILL_CART_SERVICE = DOMAIN_SERVICE.format('fill_cart') EMPTY_CART_SERVICE = DOMAIN_SERVICE.format('empty_cart') SYNC_SERVICE = DOMAIN_SERVICE.format('sync') DEBUG_SERVICE = DOMAIN_SERVICE.format('debug') # Device classes STOCK_NAME = "stock" CHORES_NAME = "chores" PRODUCTS_NAME = "products" SHOPPING_LIST_NAME = "shopping_list" SHOPPING_LISTS_NAME = "shopping_lists" LOCATIONS_NAME = "locations" QUANTITY_UNITS_NAME = "quantity_units" PRODUCT_GROUPS_NAME = "product_groups"
number_for_fibonacci = int(input("Enter Fibonacci number: ")) first_num = 0 second_num = 1 while second_num <= number_for_fibonacci: print(second_num) first_num, second_num = second_num, first_num + second_num print("Fibonacci number")
def collected_materials(key_materials_dict:dict, junk_materials_dict:dict, material:str, quantity:int): if material=="shards" or material=="fragments" or material=="motes": key_materials_dict[material]+=quantity else: if material not in junk_materials.keys(): junk_materials[material]=quantity else: junk_materials[material]+=quantity key_materials = {"shards": 0, "fragments": 0, "motes": 0} junk_materials={} items_obtained="" while items_obtained == "": current_line=input().split() for i in range (0,len(current_line),2): material_quantity=int(current_line[i]) material_name=current_line[i+1].lower() collected_materials(key_materials,junk_materials,material_name,material_quantity) if key_materials['shards']>=250: items_obtained="Shadowmourne" key_materials["shards"]-=250 break elif key_materials['fragments']>=250: items_obtained="Valanyr" key_materials['fragments']-=250 break elif key_materials['motes']>=250: items_obtained="Dragonwrath" key_materials['motes']-=250 break print(f"{items_obtained} obtained!") for (material_name,material_quantity) in sorted(key_materials.items(),key=lambda kvp:(-kvp[1],kvp[0])): print(f"{material_name}: {material_quantity}") for (junk_materials_name,junk_materials_quantity) in sorted(junk_materials.items(), key=lambda kvp: kvp[0]): print(f"{junk_materials_name}: {junk_materials_quantity}")
t_host = "localhost" t_port = "5432" t_dbname = "insert_db_name" t_user = "insert_user" t_pw = "insert_pw" photo_request_data = { "CAD6E": { "id": 218, "coords_x": -5.9357153, "coords_y": 54.5974748, "land_hash": "1530850C9A6F5FF56B66AC16301584EC" }, "TEST1": { "id": 1, "coords_x": 11.111111, "coords_y": 22.222222, "land_hash": "11111111111111111111111" } }
def pad_in(string: str, space: int) -> str: """ >>> pad_in('abc', 0) 'abc' >>> pad_in('abc', 2) ' abc' """ return "".join([" "] * space) + string def without_ends(string: str) -> str: """ >>> without_ends('abc') 'b' """ return string[1:-1] def without_first(string: str) -> str: """ >>> without_first('abc') 'bc' """ return string[1:] def without_last(string: str) -> str: """ >>> without_last('abc') 'ab' """ return string[:-1] def quote(string: str) -> str: """ >>> quote('abc') '\"abc\"' >>> quote('"abc"') '\"abc\"' """ return string if string.startswith('"') and string.endswith('"') else f'"{string}"' def handle(string: str) -> str: """ >>> handle('https://github.com/user/repo') 'user/repo' >>> handle('user/repo') 'user/repo' >>> handle('') '' """ splt = string.split("/") return "/".join(splt[-2:] if len(splt) >= 2 else splt) def pluralize(count: int, unit: str) -> str: """ Pluralize a count and given its units. >>> pluralize(1, 'file') '1 file' >>> pluralize(2, 'file') '2 files' >>> pluralize(0, 'file') '0 files' """ return f"{count} {unit}{'s' if count != 1 else ''}" def remove_prefix(string: str, prefix: str) -> str: """ >>> remove_prefix('abc', 'ab') 'c' >>> remove_prefix('abc', 'd') 'abc' >>> remove_prefix('abc', 'abcd') 'abc' """ return string[len(prefix) :] if string.startswith(prefix) else string
def algorithm(K1,K2, B, weight_vec, datapoints, true_labels, lambda_lasso, penalty_func_name='norm1', calculate_score=False): ''' Outer loop is gradient ascent algorithm, the variable 'new_weight_vec' here is the dual variable we are interested in Inner loop is still our Nlasso algorithm :param K1,K2 : the number of iterations :param D: the block incidence matrix :param weight_vec: a list containing the edges's weights of the graph :param datapoints: a dictionary containing the data of each node in the graph needed for the algorithm 1 :param true_labels: a list containing the true labels of the nodes :param samplingset: the sampling set :param lambda_lasso: the parameter lambda :param penalty_func_name: the name of the penalty function used in the algorithm :return new_w: the predicted weigh vectors for each node ''' ''' Sigma: the block diagonal matrix Sigma ''' Sigma = np.diag(np.full(weight_vec.shape, 0.9 / 2)) T_matrix = np.diag(np.array((1.0 / (np.sum(abs(B), 0)))).ravel()) ''' T_matrix: the block diagonal matrix T ''' E, N = B.shape ''' shape of the graph ''' m, n = datapoints[1]['features'].shape ''' shape of the feature vectors of each node in the graph ''' # # define the penalty function # if penalty_func_name == 'norm1': # penalty_func = Norm1Pelanty(lambda_lasso, weight_vec, Sigma, n) # elif penalty_func_name == 'norm2': # penalty_func = Norm2Pelanty(lambda_lasso, weight_vec, Sigma, n) # elif penalty_func_name == 'mocha': # penalty_func = MOCHAPelanty(lambda_lasso, weight_vec, Sigma, n) # else: # raise Exception('Invalid penalty name') new_w = np.array([np.zeros(n) for i in range(N)]) new_u = np.array([np.zeros(n) for i in range(E)]) new_weight_vec = weight_vec # starting algorithm 1 Loss = {} iteration_scores = [] for j in range(K1): new_B = np.dot(np.diag(new_weight_vec),B) T_matrix = np.diag(np.array((1.0 / (np.sum(abs(new_B), 0)))).ravel()) T = np.array((1.0 / (np.sum(abs(new_B), 0)))).ravel() for iterk in range(K2): # if iterk % 100 == 0: # print ('iter:', iterk) prev_w = np.copy(new_w) # line 2 algorithm 1 hat_w = new_w - np.dot(T_matrix, np.dot(new_B.T, new_u)) for i in range(N): optimizer = datapoints[i]['optimizer'] new_w[i] = optimizer.optimize(datapoints[i]['features'], datapoints[i]['label'], hat_w[i], T[i]) # line 9 algortihm 1 tilde_w = 2 * new_w - prev_w new_u = new_u + np.dot(Sigma, np.dot(new_B, tilde_w)) penalty_func = Norm1Pelanty(lambda_lasso, new_weight_vec, Sigma, n) new_u = penalty_func.update(new_u) new_weight_vec = new_weight_vec +0.1*np.linalg.norm(np.dot(B, new_w),ord=1,axis=1) # # calculate the MSE of the predicted weight vectors # if calculate_score: # Y_pred = [] # for i in range(N): # Y_pred.append(np.dot(datapoints[i]['features'], new_w[i])) # iteration_scores.append(mean_squared_error(true_labels.reshape(N, m), Y_pred)) Loss[j] = total_loss(datapoints,new_w,new_B,new_weight_vec) return new_w, new_weight_vec,Loss,iteration_scores
#!/usr/bin/env python2 class RDHSSet: def __init__(self, path): with open(path, 'r') as f: self.regions = [ tuple(line.strip().split()[:4]) for line in f ] self.indexmap = { x: i for i, x in enumerate(self.regions) } self.accessionIndexMap = { x[-1]: i for i, x in enumerate(self.regions) } def __len__(self): return len(self.regions) def indexesForChromosome(self, chromosome): return { self.indexmap[x] for x in self.regions if x[0] == chromosome } def indexesForChromosomes(self, chromosomes): r = set() for x in chromosomes: r = r.union(self.indexesForChromosome(x)) return r def accessionsForChromosome(self, chromosome): return { x[-1] for x in self.regions if x[0] == chromosome }
def getLeapYear(year): while True: if year%400==0: return year elif year%4==0 and year%100!=0: return year else: year +=1 if __name__=='__main__': leap_year_list = [] cur_year = int(input("Enter any year :")) leap_year = getLeapYear(cur_year) for i in range(15): leap_year_list.append(leap_year) leap_year +=4 print(leap_year_list)
for number in range(1, 101): if number % 3 == 0 and number % 5 == 0: print(f"{number} FizzBuzz") elif number % 3 == 0: print(f"{number} Fizz") elif number % 5 == 0: print(f"{number} Buzz") else: print(number)
{{notice}} workers = 4 errorlog = "{{proj_root}}/run/log/gunicorn.error" accesslog = "{{proj_root}}/run/log/gunicorn.access" loglevel = "debug" bind = ["127.0.0.1:9001"]
class Relevance(object): '''Incooperation with result file and qrels file Attributes: qid, int, query id judgement_docid_list: list of list, judged docids in TREC qrels supervised_docid_list: list, top docids from unsupervised models, e.g. BM25, QL. ''' def __init__(self, qid, judged_docid_list, supervised_docid_list, supervised_score_list): self._qid = qid self._judged_docid_list = judged_docid_list self._supervised_docid_list = supervised_docid_list self._supervised_score_list = supervised_score_list def get_qid(self): return self._qid def get_judged_docid_list(self): return self._judged_docid_list def get_supervised_docid_list(self): return self._supervised_docid_list def get_supervised_score_list(self): return self._supervised_score_list
# -*- coding: utf-8 -*- """ @author: Ing. Víctor Fabián Castro Pérez """ def imprimealgo(): print ("Esta es la cadena que se imprime de la funcion MiFuncion\n")
astr = '\thello ' astr.strip() # 去除两端空白字符 astr.lstrip() # 去除左端空白字符 astr.rstrip() # 去除右端空白字符 'hello.tar.gz'.split('.') hi = 'hello world' hi.title() hi.upper() hi.lower() hi.islower() 'hao123'.isdigit() hi.isidentifier() hi.center(50) hi.center(50, '#') hi.ljust(50) hi.rjust(50) hi.startswith('he') hi.endswith('d')
#!/usr/bin/env python # encoding: utf-8 """ @author: Bocheng.Zhang @license: Apache Licence @contact: bocheng0000@gmail.com @file: config.py @time: 2019/11/6 10:35 """ # [environment] ela_url = "coreservices-mainchain-privnet.elastos.org" did_url = "coreservices-didsidechain-privnet.elastos.org" # faucet account faucet = {"address": "EVpUKLScc3BmTyJ9xnd6aGSv3o8eAtFKNw", "publickey": "0359762e6e27e6119cf041ea0cb5046869c78f3a72549f4061d63dc48d91117957", "privatekey": "f384428447fd58fc0525494bd0f6f3df23fcb49098f4b5a50a9e97a71c6d2880"} tx_fee = 100 # sela
def our_range(*args): start = 0 end = 10 step = 1 if len(args) == 1: end = args[0] elif 2 <= len(args) <= 3: start = args[0] end = args[1] if len(args) == 3: step = args[2] elif len(args) > 3: raise SyntaxError i = start while i < end: yield i i += step for j in our_range(5): print(j) print() for j in our_range(2, 6): print(j) print() for j in our_range(3, 30, 9): print(j)
################################################## # 基本設定 # 変更した設定は次回起動時から適用されます ################################################## # 接続するチャンネル channel = "__Your_Channel__" # Botのカラー 下の中から選択 # 'Red','Blue','Green','Firebrick','Coral','YellowGreen', # 'OrengeRed','SeaGreen','GoldenRod','Chocolate','CadetBlue', # 'DodgerBlue','HotPink','BlueViolet','SpringGreen' bot_color = "HotPink" # 送信するメッセージの先頭に何か付けたいときは設定 # 何もつけないときは = "" send_message_prefix = "🐻<" # 送信するメッセージに/meをつける場合はTrue、つけない場合はFalse send_me = False # 翻訳を有効にするときはTrue、無効にしたいときはFalse # 翻訳の設定詳細なはconfig_translator.pyでできます。 translate = True ################################################## # メッセージタイマーの設定 ################################################## # メッセージタイマー(一定時間ごとに定型文を流す)を有効にするときはTrue、無効にするときはFalse timer = False # メッセージタイマーの間隔(分) timer_interval = 15 # 流すメッセージ timer_message = "I'm using a translator so don't hesitate to comment!" ################################################## # 棒読みちゃんの設定 # # 棒読みちゃんの # 「設定→システム→アプリケーション連携→HTTP連携→ローカルHTTPサーバー機能を使う」 # がTrueになってることを確認してください。 ################################################## # メッセージを棒読みちゃんに送りたいときはTrue、無効にしたいときはFalse bouyomi = False # 棒読みちゃんのHTTP連携ポート(棒読みちゃんの設定→アプリケーション連携→HTTP連携→ポート番号) bouyomi_port = 50080 # 棒読みちゃんにBotのコメントを読ませるときはTrue、読ませないときはFalse bouyomi_bot = False # 棒読みちゃんに読み上げさせる文章(Botのコメント用) # # {bot_name} = ボットのログインID # {bot_disp} = ボットのディスプレイネーム # {sender_name} = 発言者のログインID # {sender_disp} = 発言者のディスプレイネーム # {msg} = コメント # # 棒読みちゃんに「(ボットの名前)さん、(コメント)」と読ませるときは # bouyomi_bot_content = "{disp_name}さん、{message}" # となります。 bouyomi_bot_content = "{msg}" # 棒読みちゃんに読み上げさせる文章(受信したコメント用) # 整形、未整形は翻訳と同じ設定になります。 # # {sender_name} = ログインID # {sender_disp} = ディスプレイネーム # {raw_msg} = 未整形(受信したメッセージそのまま)メッセージ # {emote_del_msg} = 整形済(NGワードやエモートを取り除いた)メッセージ # # 要領は上と同じ。 bouyomi_content = "{sender_disp}さん、 {emote_del_msg}"
""" Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false. """ # 2018-6-27 # Word Serch class Solution: def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ for i in range(len(board)): for j in range(len(board[0])): if self.dfs(board,word,i,j,{},0): return True return False def dfs(self,board,word,i,j,visited,pos): if pos == len(word): return True # 结束搜索条件 if i < 0 or j < 0 or i == len(board) or j == len(board[0]) or visited.get((i,j)) or word[pos] != board[i][j]: return False visited[(i,j)] = True res = self.dfs(board,word,i+1,j,visited,pos+1) or self.dfs(board,word,i,j+1,visited,pos+1) or self.dfs(board,word,i-1,j,visited,pos+1) or self.dfs(board,word,i,j-1,visited,pos+1) visited[(i,j)] = False return res # test board =[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] word = "A" test = Solution() res = test.exist(board,word) print(res)
def part1(input_data): numbers, boards = parse_input(input_data) for number in numbers: # Put number on all boards for board in boards: for row in board: for i in range(len(row)): if number == row[i]: row[i] = "x" # Check for bingo for board in boards: for row in board: if "".join(row) == "xxxxx": return int(number) * unmarked_sum(board) for column in zip(*board): if "".join(column) == "xxxxx": return int(number) * unmarked_sum(board) def part2(input_data): numbers, boards = parse_input(input_data) board_scores = [0 for x in boards] last_index = None for number in numbers: # Put number on all boards for board in boards: for row in board: for i in range(len(row)): if number == row[i]: row[i] = "x" # Check for bingo for i, board in enumerate(boards): for row in board: if "".join(row) == "xxxxx" and board_scores[i] == 0: board_scores[i] = int(number) * unmarked_sum(board) last_index = i for column in zip(*board): if "".join(column) == "xxxxx" and board_scores[i] == 0: board_scores[i] = int(number) * unmarked_sum(board) last_index = i return board_scores[last_index] def unmarked_sum(board): return sum( map( lambda x: sum(map(lambda y: int(y) if y != "x" else 0, x)), board, ) ) def parse_input(input_data): numbers = input_data[0].split(",") boards = [] for i in range(1, len(input_data), 6): rows = input_data[i + 1 : i + 6] rows = list( map(lambda x: list(filter(lambda y: len(y) > 0, x.split(" "))), rows) ) boards.append(rows) return numbers, boards if __name__ == "__main__": with open("input", "r") as input_file: input_data = list(map(lambda x: x.strip(), input_file.readlines())) print(part1(input_data)) print(part2(input_data))
load("@bazel_skylib//lib:paths.bzl", "paths") load( "//caffe2/test:defs.bzl", "define_tests", ) def define_pipeline_tests(): test_files = native.glob(["**/test_*.py"]) TESTS = {} for test_file in test_files: test_file_name = paths.basename(test_file) test_name = test_file_name.replace("test_", "").replace(".py", "") TESTS[test_name] = [test_file] define_tests( pytest = True, tests = TESTS, external_deps = [("pytest", None)], resources = ["conftest.py"], )
# definitions.py IbConfig = { 'telepotChatId': '572145851', 'googleServiceKeyFile' : 'GoogleCloudServiceKey.json', 'telepotToken' : '679545486:AAEbCBdedlJ1lxFXpN1a-J-6LfgFQ4cAp04', 'startMessage' : 'Hallo, ich bin unsere dolmetschende Eule. Stelle mich bitte auf deine Handflaeche und ich sage dir, was dein tauber Gegenueber schreibt. Wenn du etwas sagst, teile ich das deinem Gegenueber mit', 'listenLanguage' : 'de_DE', # de_DE, en_US, en_UK, en_AU, etc. See https://cloud.google.com/speech-to-text/docs/languages 'speakLanguage' : 'de', # de, en_US, en_UK, en_AU. See gtts-cli --all 'micDeviceIndex' : 0, }
class Graph: def __init__(self,nodes,edges): self.graph=[] for i in range(nodes+1): self.graph.append([]) self.visited=[False]*(len(self.graph)) def addEdge(self,v1,v2): self.graph[v1].append(v2) def dfs(self,source): self.visited[source]=True print(source) for i in self.graph[source]: if not self.visited[i]: self.dfs(i) def dfs_stack(self,source): stack=[] stack.append(source) self.visited[source] = True while stack: top=stack.pop() print(top) for i in self.graph[top]: if not self.visited[i]: stack.append(i) self.visited[i]=True g=Graph(4,5) g.addEdge(1,2) g.addEdge(1,3) g.addEdge(1,4) g.addEdge(3,4) g.addEdge(4,2) g.dfs_stack(1)
grupo = [] somai = 0 dados = {} while True: dados.clear() dados['nome'] = str(input('Nome: ')).strip().capitalize() while True: dados['sexo'] = str(input('Sexo [M/F]: ')).upper().strip()[0] if dados['sexo'] in 'MF': break print('Por favor digite apenas M ou F.') dados['idade'] = int(input('Idade: ')) grupo.append(dados.copy()) somai += dados['idade'] while True: continuar = str(input('Quer continuar? [S/N]: ')).strip().upper()[0] if continuar == 'N' or continuar == 'S': break if continuar == 'N': break print(f'O grupo tem {len(grupo)} pessoas.') print(f'A média de idade é {somai / len(grupo):5.2f}') print(f'A mulheres cadastradas foram: ', end='') for p in grupo: if p['sexo'] == 'F': print(p['nome'], end=', ') print() print(f'Lista das pessoas que estão acima da média: ', end='') for p in grupo: if p['idade'] >= somai / len(grupo): print(p['nome'], end=', ') print() print('<< ENCERRANDO >>')
inp = list(map(float, input().split())) inp.sort(reverse=True) a, b, c = inp if a >= b + c: print('NAO FORMA TRIANGULO') else: if a ** 2 == b ** 2 + c ** 2: print('TRIANGULO RETANGULO') elif a ** 2 > b ** 2 + c ** 2: print('TRIANGULO OBTUSANGULO') else: print('TRIANGULO ACUTANGULO') if a == b and b == c: print('TRIANGULO EQUILATERO') elif a == b or a == c or b == c: print('TRIANGULO ISOSCELES')
__all__ = ['CONFIG', 'get'] CONFIG = { 'model_save_dir': "./output/MicroExpression", 'num_classes': 7, 'total_images': 17245, 'epochs': 20, 'batch_size': 32, 'image_shape': [3, 224, 224], 'LEARNING_RATE': { 'params': { 'lr': 0.00375 } }, 'OPTIMIZER': { 'params': { 'momentum': 0.9 }, 'regularizer': { 'function': 'L2', 'factor': 0.000001 } }, 'LABEL_MAP': [ "disgust", "others", "sadness", "happiness", "surprise", "repression", "fear" ] } def get(full_path): for id, name in enumerate(full_path.split('.')): if id == 0: config = CONFIG config = config[name] return config
n=str(input("Enter the string")) le=len(n) dig=0 alp=0 for i in range(le): if n[i].isdigit(): dig=dig+1 elif n[i].isalpha(): alp=alp+1 else: continue print("Letters count is : %d"%alp) print("Digits count is : %d"%dig)
# Author: Will Killian # https://www.github.com/willkill07 # # Copyright 2021 # All Rights Reserved class Lab: _all = dict() lab_id = 200 def min_id(): """ Returns the maximum number for the lab IDs (always 200) """ return 200 def max_id(): """ Returns the maximum number for the lab IDs """ return Lab.lab_id - 1 def get(id): """ Given an ID of a lab, return the instance """ return Lab._all[id] def __init__(self, name: str): # update id to be a unique identifier self.id = Lab.lab_id Lab.lab_id += 1 self.name = name Lab._all[self.id] = self def __repr__(self): """ Pretty Print representation of a course is its subject, number, and section """ return f'{self.name}'
# -*- coding: utf-8 -*- class GeocoderException(Exception): """Base class for all the reverse geocoder module exceptions.""" class InitializationError(GeocoderException): """Catching this error will catch all initialization-related errors.""" class CsvReadError(InitializationError): """Could not open the locations csv file.""" class CsvParseError(InitializationError): """Could not parse the locations csv file."""
#Given a decimal number n, your task is to convert it #to its binary equivalent using a recursive function. #The binary number output must be of length 8 bits. def binary(n): if n == 0: return 0 else: return (n % 2 + 10*binary(int(n // 2))) def convert_8_bit(n): s = str(n) while len(s)<8: s = '0' + s return s def dec_to_binary(n): return convert_8_bit(binary(n)) def main(): T = int(input()) n = [] for _ in range(0,T): temp = int(input()) n.append(dec_to_binary(temp)) print(*n,sep="\n") if __name__=='__main__': try: main() except: pass
''' Author: Shuailin Chen Created Date: 2021-09-14 Last Modified: 2021-12-29 content: ''' # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005) optimizer_config = dict() # learning policy lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False) # runtime settings runner = dict(type='MyIterBasedRunner', max_iters=10000) # runner = dict(type='IterBasedRunner', max_iters=20000) checkpoint_config = dict(by_epoch=False, interval=100000) # evaluation = dict(interval=50, metric='mIoU', pre_eval=True) evaluation = dict(interval=1000, metric='mIoU', pre_eval=True)
keys = { "accept": 30, "add": 107, "apps": 93, "attn": 246, "back": 8, "browser_back": 166, "browser_forward": 167, "cancel": 3, "capital": 20, "clear": 12, "control": 17, "convert": 28, "crsel": 247, "decimal": 110, "delete": 46, "divide": 111, "down": 40, "end": 35, "ereof": 249, "escape": 27, "execute": 43, "exsel": 248, "f1": 112, "f10": 121, "f11": 122, "f12": 123, "f13": 124, "f14": 125, "f15": 126, "f16": 127, "f17": 128, "f18": 129, "f19": 130, "f2": 113, "f20": 131, "f21": 132, "f22": 133, "f23": 134, "f24": 135, "f3": 114, "f4": 115, "f5": 116, "f6": 117, "f7": 118, "f8": 119, "f9": 120, "final": 24, "hangeul": 21, "hangul": 21, "hanja": 25, "help": 47, "home": 36, "insert": 45, "junja": 23, "kana": 21, "kanji": 25, "lbutton": 1, "lcontrol": 162, "left": 37, "lmenu": 164, "lshift": 160, "lwin": 91, "mbutton": 4, "media_next_track": 176, "media_play_pause": 179, "media_prev_track": 177, "menu": 18, "modechange": 31, "multiply": 106, "next": 34, "noname": 252, "nonconvert": 29, "numlock": 144, "numpad0": 96, "numpad1": 97, "numpad2": 98, "numpad3": 99, "numpad4": 100, "numpad5": 101, "numpad6": 102, "numpad7": 103, "numpad8": 104, "numpad9": 105, "oem_clear": 254, "pa1": 253, "pagedown": 34, "pageup": 33, "pause": 19, "play": 250, "print": 42, "prior": 33, "processkey": 229, "rbutton": 2, "rcontrol": 163, "return": 13, "right": 39, "rmenu": 165, "rshift": 161, "rwin": 92, "scroll": 145, "select": 41, "separator": 108, "shift": 16, "snapshot": 44, "space": 32, "subtract": 109, "tab": 9, "up": 38, "volume_down": 174, "volume_mute": 173, "volume_up": 175, "xbutton1": 5, "xbutton2": 6, "zoom": 251, "/": 191, ";": 218, "[": 219, "\\": 220, "]": 221, "'": 222, "=": 187, "-": 189, ";": 186, } modifiers = {"alt": 1, "control": 2, "shift": 4, "win": 8}
N = int(input()) A = list(map(int, input().split())) A.sort() left, right = 0, 2*N-1 moist = A.count(0) // 2 while left < right and A[left] < 0 and A[right] > 0: if abs(A[left]) == A[right]: moist += 1 left += 1 right -= 1 elif abs(A[left]) > A[right]: left += 1 else: right -= 1 left, right = 0, 2*N-1 wet = 0 while left < right: if A[left] + A[right] <= 0: left += 1 else: wet += 1 left += 1 right -= 1 left, right = 0, 2*N-1 dry = 0 while left < right: if A[left] + A[right] >= 0: right -= 1 else: dry += 1 left += 1 right -= 1 print(dry, wet, moist)
def printSlope(equation): xIndex = equation.find('x') if xIndex == -1: print(0) elif xIndex == 2: print(1) else: slopeString = equation[2:xIndex] if slopeString == "-": print(-1) else: print(slopeString) printSlope("y=2x+5") #prints 2 printSlope("y=-1299x+5") #prints -1299 printSlope("y=x+5") #prints 1 printSlope("y=-x+5") #prints -1 printSlope("y=5") #prints 0
#!/usr/bin/env python #-*- coding: utf-8 -*- """ __title__ = 'replace' __author__ = 'JieYuan' __mtime__ = '2019-05-06' """ def replace(s, dic): return s.translate(str.maketrans(dic)) if __name__ == '__main__': print(replace('abcd', {'a': '8', 'd': '88'}))
# Everytime you make changes in this file, you have to run Reco again (reco.pyw). webhook_restricter_list=[ #(copy starts from here) { #1️⃣ Replace webhook Name 'webhookName':'Temp webhook', # Here you can enter the Webhook name, so you can identify easily in this file. #2️⃣ Replace webhook URL & ID 'webhookURL':'https://discord.com/api/webhooks/841227223729700866/aW4XpuFTUfweJIcQAqTSgikXZu6r5r6Q8MK_rOawf6qj_dyAUVQUCzbTm6Is0Bs8bQFG', 'webhookId':'841227223729700866', # You can obtain the "webhook id" by looking at the webhook URL, the number after https://discord.com/api/webhooks/ is the "id" , and the part after that is the token. #3️⃣ Before sharing your Webhook URL to others. you can set permission to each commands as you wish🥳 # "True" => means Permission granted to use the command. # "False" => means Permission Denied to use the command. # For safety and security purposes we have set False as default for all commands and you can override by mentioning command permission down here. # ⚠ Powerfull Commands: (All powerfull commands will be "False" by default) '!abort':False, '!appquitter':False, '!cmd':False, '!file': False, '!hibernate':False, '!lock':False, '!logoff':False, 'media_Close&QuitKeys':False, # !media key-close, !media key-quit '!powershell':False, '!restart':False, '!shutdown':False, '!sleep':False, # Moderate Commands: '!camera':True, '!clip':True, '!launch':True, '!screenshot':True, # Media Commands: (!media) 'media_Function_Keys':True, # next, prev, stop, play, pause 'media_Volume_Keys':True, # vol-up, vol-down, vol-mute 'media_ArrowKeys':True, # key-up, key-down, key-left, key-right 'media_Tab,Space&EnterKeys':True, # key-tab, key-space, key-enter 'music_Controls_Keys':True, # key-f, ey-shuffle, key-loop # Other Commands: '!batterylevel':True, '!batteryreport':True, '!echo':True, '!log':True, '!music':True, '!m':True, '!notification':True, '!say':True, '!search':True, '!systeminfo':True, '!url':True, '!version':True, '!whatsapp':True, '!wlansignal':True, '!youtube':True, '!queue':True, '!play':True, }, #(copy ends here) # If you have multiple webhooks to set permission. Copy { Everthing including Curly braces }. # And paste down here. ]
def profile_most_probable_kmer(text, k, profile): highest_prob = -1 most_probable_kmer = "" for i in range(len(text) - k + 1): kmer = text[i : i+k] prob = 1 for index, nucleotide in enumerate(kmer): prob *= profile[nucleotide][index] if prob > highest_prob: highest_prob = prob most_probable_kmer = kmer return most_probable_kmer if __name__ == '__main__': with open("dataset_159_3.txt") as f: text = f.readline().strip() k = int(f.readline().strip()) profile = {} for letter in ['A', 'C', 'G', 'T']: profile[letter] = [float(item) for item in f.readline().strip().split()] print(profile_most_probable_kmer(text, k, profile))
ROW_COUNT = 128 COLUMN_COUNT = 8 def solve(input): return max(map(lambda i: BoardingPass(i).seat_id, input)) class BoardingPass: def __init__(self, data, row_count=ROW_COUNT, column_count=COLUMN_COUNT): self.row = self._search( data = data[:7], low_char='F', high_char='B', i=0, min_value=0, max_value=row_count ) self.column = self._search( data = data[7:], low_char='L', high_char='R', i=0, min_value=0, max_value=column_count ) self.seat_id = Seat(self.row, self.column).id def _search(self, data, low_char, high_char, i, min_value, max_value): if i == len(data) - 1: assert max_value - min_value == 2 if data[i] == low_char: return min_value elif data[i] == high_char: return max_value - 1 else: raise Exception(f'Expected {low_char} or {high_char} got {data[i]}') mid_value = int((max_value - min_value) / 2) + min_value if data[i] == low_char: return self._search(data, low_char, high_char, i + 1, min_value, mid_value) elif data[i] == high_char: return self._search(data, low_char, high_char, i + 1, mid_value, max_value) else: raise Exception(f'Expected {low_char} or {high_char} got {data[i]}') class Seat: def __init__(self, row, column): self.id = (row * 8) + column
f = open('day3.txt', 'r') data = f.readlines() oneCount = 0 threeCount = 0 fiveCount = 0 sevenCount = 0 evenCount = 0 pos1 = 0 pos3 = 0 pos5 = 0 pos7 = 0 posEven = 0 even = True for line in data: line = line.replace("\n", '') if line[pos1 % len(line)] == '#': oneCount += 1 if line[pos3 % len(line)] == '#': threeCount += 1 if line[pos5 % len(line)] == '#': fiveCount += 1 if line[pos7 % len(line)] == '#': sevenCount += 1 if line[posEven % len(line)] == '#' and even: evenCount += 1 pos1 += 1 pos3 += 3 pos5 += 5 pos7 += 7 if not even: posEven += 1 even = not even print(str(evenCount * oneCount * threeCount * fiveCount * sevenCount))
def porrada(seq, passo): atual = 0 while len(seq) > 1: atual += passo - 1 while atual > len(seq) - 1: atual -= len(seq) seq.pop(atual) return seq[0] + 1 quantidade_de_casos = int(input()) for c in range(quantidade_de_casos): entrada = input().split() n = list(range(int(entrada[0]))) m = int(entrada[1]) print(f'Case {c + 1}: {porrada(n, m)}')
n = int(input()) arr = list(map(int, input().split(' '))) arr.sort(reverse=True) res = 0 for i in range(n): res += arr[i]*2**i print(res)
def run_example(): # Taką samą listę z numerami jak w poprzednim przykładzie możemy zapisać krócej za pomocą list comprehensions # numbers = [] # for number in range(15): # numbers.append(number) numbers = [number for number in range(15)] print(numbers) # List comprehensions zawiera również opcjonalną część if numbers = [number for number in range(15) if number % 2 == 0] print(numbers) # Odpowiadająca pętla for # numbers = [] # for number in range(15): # if number % 2 == 0: # numbers.append(number) # print(numbers) # W analogiczny sposób możemy wybrać co drugi smak favourite_flavours = [ "malinowy", "truskawkowy", "czekoladowy", "pistacjowy", "kokosowy", ] flavours = [flavour for index, flavour in enumerate(favourite_flavours) if index % 2 == 0] print(flavours) # W list comprehensions możemy użyć również pełnego wyrażenia if else flavours = [flavour if index % 2 == 0 else "---" for index, flavour in enumerate(favourite_flavours)] print(flavours) # Odpowiadająca pętla for # flavours = [] # for index, flavour in enumerate(favourite_flavours): # if index % 2 == 0: # flavours.append(flavour) # else: # flavours.append("---") # print(flavours) # Możemy również zagnieżdżać je w sobie rows_and_cols = [[row for row in range(5)] for column in range(4)] print(rows_and_cols) # Odpowiadająca pętla for # rows_and_cols = [] # for column in range(4): # rows_and_cols.append([]) # for row in range(5): # rows_and_cols[column].append(row) # print(rows_and_cols) if __name__ == '__main__': run_example()
class Solution: def minInsertions(self, s: str) -> int: right = count = 0 for c in s: if c == '(': if right & 1: right -= 1 count += 1 right += 2 else: right -= 1 if right < 0: right = 1 count += 1 return right + count
# Given an array of integers, return indices of the two numbers such that they add up to a specific target. # You may assume that each input would have exactly one solution, and you may not use the same element twice. # Example: # Given nums = [2, 7, 11, 15], target = 9, # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1]. class Solution(object): def twoSum(self, nums, target): """ O(m) O(m) :type nums: List[int] :type target: int :rtype: List[int] """ dic = {} for i in range(len(nums)): if nums[i] in dic: return [dic[nums[i]], i] else: dic[target- nums[i]] = i return []
S = input() N = len(S) A = [0]*(N+1) B = [0]*(N+1) for i in range(N): if S[i] == '<': A[i+1] = A[i]+1 else: A[i+1] = 0 for i in range(N): if S[N-i-1] == '>': B[N-i-1] = B[N-i]+1 else: B[N-i-1] = 0 ans = 0 for i in range(N+1): ans += max(A[i], B[i]) print(ans)
# https://leetcode.com/problems/add-two-numbers/ # You are given two non-empty linked lists representing two non-negative integers. # The digits are stored in reverse order and each of their nodes contain a single digit. # Add the two numbers and return it as a linked list. # # You may assume the two numbers do not contain any leading zero, except the number 0 itself. # # Example: # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 0 -> 8 # Explanation: 342 + 465 = 807. # # Related Topics Linked List Math # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def add_two_numbers(left, right): # 记录进数 carry = 0 tmp = ListNode(0) root = tmp while left or right: # 当前层级两节点的值,加上低层级的进位 total = carry + left.val + right.val # 循环到更高层级 left = left.next right = right.next # 计算进数 carry = total // 10 # 余数作为当前层级的计算结果 tmp.next = ListNode(total % 10) # 将临时节点当做游标,用于暂存更高层级的节点 tmp = tmp.next return root.next n1 = ListNode(2) n1.next = ListNode(4) n1.next.next = ListNode(3) n2 = ListNode(5) n2.next = ListNode(6) n2.next.next = ListNode(4) res = ListNode(7) res.next = ListNode(0) res.next.next = ListNode(8) def check(left, right): while left or right: if left and not right or not left and right: return False if left.val != right.val: return False left = left.next right = right.next return True assert not check(n1, n2) assert check(add_two_numbers(n1, n2), res)
A = int(input()) B = int(input()) if B % A == 0 or A % B == 0: print("São Múltiplos \n") else: print("Não são Múltiplos \n")
''' Write a program that takes an integer argument and retums all the primes between 1 and that integer. For example, if the input is 18, you should return [2, 3, 5, 7, 11, 13, 17]. ''' def generate_primes(n): # Time: O(n log log n) | Space: O(n) primes = [] # is_prime[p] represents if p is prime or not. # Initially, set each to true, except for 0 and 1. # Then use sieving to eliminate non-primes. is_prime = [False, False] + [True] * (n - 1) for p in range(2, n + 1): if is_prime[p]: primes.append(p) # Turn false all multiples of p. for i in range(p, n+1, p): is_prime[i] = False return primes assert(generate_primes(18) == [2, 3, 5, 7, 11, 13, 17]) # Ignore even numbers and eliminate multiples of p2 # This will give better performance, but does not # reflect on complexity def generate_primes_square(n): # Time: O(n log log n) | Space: O(n) if n < 2: return [] primes = [2] # Store the first prime number # is_prime[p] represents if (2i + 3) is prime or not. # Initially, set each to true. # Then use sieving to eliminate non-primes. size = (n - 3) // 2 + 1 is_prime = [True] * size for i in range(size): if is_prime[i]: p = i * 2 + 3 primes.append(p) # Sieving fron p^2, where p^2 = (4i^2 + 12i + 9). # The index in is_prime is (2i^2 + 6i + 3) because # is_prime[i] represents 2i + 3. # Note that we need to use long for j because p^2 might overflow. for j in range(2 * i**2 + 6 * i + 3, size, p): is_prime[j] = False return primes assert(generate_primes_square(18) == [2, 3, 5, 7, 11, 13, 17])
""" gdcdatamodel.migrations.update_case_cache -------------------- Functionality to fix stale case caches in _related_cases edge tables. """ def update_related_cases(driver, node_id): """Removes and re-adds the edge between the given node and it's parent to cascade the new relationship to _related_cases through the graph """ with driver.session_scope() as session: node = driver.nodes().ids(node_id).one() edges_out = node.edges_out for edge in edges_out: edge_cls = edge.__class__ copied_edge = edge_cls( src_id=edge.src_id, dst_id=edge.dst_id, properties=dict(edge.props), system_annotations=dict(edge.sysan), ) # Delete the edge driver.edges(edge_cls).filter( edge_cls.src_id == copied_edge.src_id, edge_cls.dst_id == copied_edge.dst_id, ).delete() session.expunge(edge) # Re-add the edge to force a refresh of the stale cache session.add(copied_edge) # Assert the edge was re-added or abort the session driver.edges(edge_cls).filter( edge_cls.src_id == copied_edge.src_id, edge_cls.dst_id == copied_edge.dst_id, ).one() def update_cache_cache_tree(driver, case): """Updates the _related_cases case cache for all children in the :param:`case` tree """ visited = set() with driver.session_scope(): for neighbor in case.edges_in: if neighbor.src_id in visited: continue update_related_cases(driver, neighbor.src_id) visited.add(neighbor.src_id)
""" Métodos mágicos são todos os métodos que utilizam o dunder __method__ """ # Construtor (__init__) class Livro: def __init__(self, titulo, autor, paginas): self.__titulo = titulo self.__autor = autor self.__pagina = paginas def __repr__(self): #__repr__ É a representasão do objeto. return self.__titulo def __str__(self): #__str__ É a string que é a representação inicial para usuário. return self.__titulo def __len__(self): #__len__ o tamanho do objeto. return self.__paginas
n = int(input()) l = [] for i in range(0, n): l.append(int(input())) for orig_num in l: count = 0 num = orig_num while num != 0: digit = num % 10 if digit == 0: pass elif orig_num % digit == 0: count += 1 num = int(num / 10) print (count)
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre sua média. n1 = int(input('Digite sua primeira nota:')) n2 = int(input('Digite sua segunda nota:')) media = float (n1+n2)/2 print('A média do aluno é {}'.format(media))
class Qseq(str): def __init__(self, seq): self.qkey = None self.parent = None self.parental_id = None self.parental_class = None self.name = None self.item = None def __getitem__(self, item): value = super().__getitem__(item) if self.parental_class == "QUEEN" and self.parent is not None and self.parent.topology == "circular": if type(item) == slice: if item.start is None: start = 0 elif item.start < 0: start = len(self) + item.start else: start = item.start if item.stop is None: stop = len(self) elif item.stop < 0: stop = len(self) + item.stop else: stop = item.stop if item.step is None: step = 1 if start > stop: value = str(self)[start:] + str(self)[:stop] value = value[::step] else: value = super().__getitem__(item) else: pass value = Qseq(value) else: value = Qseq(value) value.qkey = self.qkey value.parent = self.parent value.parental_id = self.parental_id value.parental_class = self.parental_class value.name = self.name if value.item is None: value.item = item else: value.item = slice(value.item.start + item.start, value.item.start + item.stop) return value
rios = { 'nilo' : 'egito', 'rio grande' : 'brasil', 'rio parana' : 'brasil' } for key,value in rios.items(): print(' O rio ' + key.title() + ' corre pelo ' + value.title()) for key in rios.keys(): print(key.title()) for value in rios.values(): print(value.title())
# coding: utf-8 # In[ ]: class Solution: def searchRange(self, nums, target): #算法思路: #首先写下一个可以找到第一个出现的target的indice的binary search的方程 #在这个方程里,如果mid的大小大于或等于target,则hi变成现在的mid #如果mid的大小小于了target了,则lo变为现在的mid+1 #可以注意的是,因为我们在一个sorted list nums寻找,当这个方程的target变为target+1后 #这个方程会返回在nums中最后一个的target的indice+1 def search(n): lo, hi = 0, len(nums) while lo < hi: mid = int((lo + hi) / 2) if nums[mid] >= n: hi = mid else: lo = mid + 1 return lo lo = search(target) return [lo, search(target+1)-1] if target in nums[lo:lo+1] else [-1, -1] #注意应对nums=[]的情况
def hello(name): """Generate a friendly greeting. Greeting is an important part of culture. This function takes a name and generates a friendly greeting for it. Parameters ---------- name : str A name. Returns ------- str A greeting. """ return 'Hello {name}'.format(name=name)
vowels2 = set('aeiiiouuu') word = input('Provide a word to search for vowels:').lower() found = vowels2.intersection(set(word)) for v in found: print(v)
#!/usr/bin/env python2.7 """ Read the file agents.raw and output agents.txt, a readable file """ if __name__=="__main__": with open("agents.raw","r") as f: with open("agents.txt","w") as out: for line in f: if(line[0] in '+|'): out.write(line)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : metaclass_0.py # @Author: yubo # @Date : 2019/11/18 # @Desc : class Meta(type): """ 自定义元类 """ def __new__(cls, name, bases, d): """ 使用自定义元类,最终都是要调用 type 生成类实例 return super(Meta, cls).__new__(cls, name, bases, d) 等同于 type.__new__(cls, name, bases, d) """ print("call Meta __new__") d["a"] = "a" return super(Meta, cls).__new__(cls, name, bases, d) def __init__(self, *args, **kwargs): print("call Meta __init__") super(Meta, self).__init__(*args, **kwargs) class MetaNormal0(object): """ 我们写下如下代码时: class Foo(object): pass 实际上,解释器将其解释为: Foo = type('Foo', (object,), {}) """ pass class MetaNormal1(metaclass=Meta): """ 如果定义了元类 class MyMetaType(type): pass class Foo(metaclass=MyMetaType): pass 解释器解释到class Foo(...)的时候,就会转换为: Foo = MyMetaType('Foo', (object,), {}) 此时调用 MyMetaType.__new__, MyMetaType.__init__, 生成类MyMetaType 的实例化对象:Foo """ pass """ MetaNormal1 的元类是 Meta, 父类是 object """ print(type(MetaNormal1)) print(MetaNormal1.__mro__) """ call Meta __new__ call Meta __init__ <class '__main__.Meta'> (<class '__main__.MetaNormal1'>, <class 'object'>) """
idades = [11, 43, 55, 41, 85, 43, 43, 5] # Forma manual for indice in range(len(idades)): print(indice, "|", idades[indice]) print() # Forma com tuplas usando enumerate for tupla in enumerate(idades): print(tupla) print() # Forma com desempacotamento de tuplas for indice, idade in enumerate(idades): print(indice, "|", idade) print() # Forma com desempacotamento e ignorando posições for indice, _ in enumerate(idades): print(indice)
# -*- coding: utf-8 -*- """mul.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fvc_bX8oobfbr_O2r1pCpgOd2CTckXe9 """ def mul(num1, num2): print('Result is: ', num1 * num2)
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: table = {} mapped = set() words = str.split() if len(words) != len(pattern): return False for i, word in enumerate(words): if word in table: if table[word] != pattern[i]: return False else: if pattern[i] in mapped: return False table[word] = pattern[i] mapped.add(pattern[i]) return True
HOST = 'localhost' PORT = 61613 VERSION = '1.2' BROKER = 'activemq' LOGIN, PASSCODE, VIRTUALHOST = { 'activemq': ('', '', ''), 'apollo': ('admin', 'password', 'mybroker'), 'rabbitmq': ('guest', 'guest', '/') }[BROKER]
# python3.7 """Configuration for testing StyleGAN on FF-HQ (1024) dataset. All settings are particularly used for one replica (GPU), such as `batch_size` and `num_workers`. """ runner_type = 'StyleGANRunner' gan_type = 'stylegan' resolution = 1024 batch_size = 16 data = dict( num_workers=4, # val=dict(root_dir='data/ffhq', resolution=resolution), val=dict(root_dir='data/ffhq.zip', data_format='zip', resolution=resolution), ) modules = dict( discriminator=dict( model=dict(gan_type=gan_type, resolution=resolution), kwargs_val=dict(), ), generator=dict( model=dict(gan_type=gan_type, resolution=resolution), kwargs_val=dict(trunc_psi=0.7, trunc_layers=8, randomize_noise=False), ) )
def Num2581(): M = int(input()) N = int(input()) minPrimeNum = 0 sumPrimeNum = 0 primeNums = [] for dividend in range(M, N+1): if dividend == 1: continue primeNums.append(dividend) sumPrimeNum += dividend for divisor in range(2, dividend): if dividend % divisor == 0: primeNums.pop() sumPrimeNum -= dividend break if len(primeNums) == 0: print("-1") else: minPrimeNum = primeNums[0] sumPrimeNum = sum(primeNums) print(str(sumPrimeNum)) print(str(minPrimeNum)) Num2581()
#takes a list of options as input which will be printed as a numerical list #Also optionally takes messages as input to be printed after the options but before input request #Ultimately the users choice is returned def selector(options,*messages): rego = 'y' while rego.lower() == "y": n=1 for x in options: print(str(n) + ". " + str(x)) n = n + 1 n=1 print("") for arg in messages: print(arg) choice = input( " :> ") if choice == "": return False try: i_choice = int(choice) except ValueError: print("\nError: Sorry, that's not a valid entry, please enter a number from the list.") rego = input("\nWould you like to try again? Type Y for yes or N for no :> ") if rego.lower() == "y": pass else: break print("") p=1 for x in options: if int(choice) == p: value = x p = p + 1 p=1 if value in options: return value else: if not value: print("\nError: Sorry, that's not a valid entry, please enter a number from the list") rego = input("Would you like to try again? Type Y for yes or N for no :> ") return False
"""A module to keep track of a relinearization key.""" class BFVRelinKey: """An instance of a relinearization key. The relinearization key consists of a list of values, as specified in Version 1 of the BFV paper, generated in key_generator.py. Attributes: base (int): Base used in relinearization in Version 1. keys (list of tuples of Polynomials): List of elements in the relinearization key. Each element of the list is a pair of polynomials. """ def __init__(self, base, keys): """Sets relinearization key to given inputs. Args: base (int): Base used for relinearization. keys (list of tuples of Polynomials): List of elements in the relinearization key. """ self.base = base self.keys = keys def __str__(self): """Represents RelinKey as a string. Returns: A string which represents the RelinKey. """ return 'Base: ' + str(self.base) + '\n' + str(self.keys)
class Wrapping(object): def __init__(self, klass, wrapped_klass, dependency_functions): self._klass = klass self._wrapped_klass = wrapped_klass self._dependency_functions = dependency_functions def wrap(self): for dependency_method in self._dependency_functions: self._access_class_dependency(dependency_method) setattr(self._klass, '__getattr__', self._getattr()) setattr(self._klass, '__init__', self._init()) return self._klass def _access_class_dependency(self, method_name): def _call_dependency_method(wrapper_instance, *args, **kwargs): method = getattr(wrapper_instance._wrapped, method_name) return method(wrapper_instance._dependency, *args, **kwargs) setattr(self._klass, method_name, _call_dependency_method) def _getattr(self): def _inner(wrapper_instance, name): if hasattr(wrapper_instance._wrapped, name): return getattr(wrapper_instance._wrapped, name) raise AttributeError(self._missing_attribute_message(name)) return _inner def _missing_attribute_message(self, name): return "'{}' object has no attribute '{}'".format(self._klass.__name__, name) def _init(self): def _inner(wrapper_instance, dependency): wrapper_instance._dependency = dependency wrapper_instance._wrapped = self._wrapped_klass() return _inner def wrap_class_with_dependency(wrapped_klass, *dependency_functions): def _wrap(klass): return Wrapping(klass, wrapped_klass, dependency_functions).wrap() return _wrap
""" templates for urls """ URL = """router.register(r'%(path)s', %(model)sViewSet) """ VIEWSET_IMPORT = """from %(app)s.views import %(model)sViewSet """ URL_PATTERNS = """urlpatterns = [ path("", include(router.urls)), ]""" SETUP = """from rest_framework import routers from django.urls import include, path router = routers.DefaultRouter() """
# Desafio 005 - Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor inteiro = int(input('Digite um número inteiro: ')) antecessor = inteiro - 1 sucessor = inteiro + 1 print('O antecessor de {} é {}. \nO sucessor de {} é {}.'. format(inteiro, antecessor, inteiro, sucessor)) # alternativa 1 inteiro = int(input('Digite um número inteiro: ')) print('O antecessor de {} é {}. \nO sucessor de {} é {}.'. format(inteiro, (inteiro - 1), inteiro, (inteiro + 1))) # quanto menos variável for utilizada, mais memória será economizada
def roman_number(num): if num > 3999: print("enter number less than 3999") return #take 2 list symbol and value symbol having roman of each integer in list value value = [1000,900,500,400,100,90,50,40,10,9,5,4,1] symbol = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] roman = "" i=0 while num>0: #then we have to check the the range of value #divide the number with all values starting from zero div = num//value[i] #mod to get part of number num = num%value[i] while div: roman = roman+symbol[i] #loop goes till div become zero div = div-1 i=i+1 return roman num = int(input("enter an integer number: ")) print(f" Roman Numeral of {num} is {roman_number(num)}")
def radixSort(data): if not data: return [] max_num = max(data) # 获取当前数列中最大值 max_digit = len(str(abs(max_num))) # 获取最大的位数 dev = 1 # 第几位数,个位数为1,十位数为10··· mod = 10 # 求余数的除法 for i in range(max_digit): radix_queue = [list() for k in range(mod * 2)] for j in range(len(data)): radix = int(((data[j] % mod) / dev) + mod) radix_queue[radix].append(data[j]) pos = 0 for queue in radix_queue: for val in queue: data[pos] = val pos += 1 dev *= 10 mod *= 10 return data if __name__ == '__main__': nums = [334, 5, 67, 345, 7, 99, 4, 23, 78, 45, 1, 3453, 23424] print(radixSort(nums))
AN_ESCAPED_NEWLINE = "\n" AN_ESCAPED_TAB = "\t" A_COMMA = "," A_QUOTE = "'" A_TAB = "\t" DOUBLE_QUOTES = "\"" NEWLINE = "\n"
#!/usr/bin/env python3 # # Copyright 2019 Google LLC # # 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 # # https://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. class ScholarshipBuilder: @staticmethod def setName(scholarship, name): scholarship["scholarshipName"] = name @staticmethod def setId(scholarship, id): scholarship["id"] = str(int(id)) @staticmethod def setSchoolsList(scholarship, schoolsList): scholarship["schoolsList"] = schoolsList.split(",") @staticmethod def setURL(scholarship, url): scholarship["URL"] = url @staticmethod def setYear(scholarship, year): scholarship["year"] = year @staticmethod def setIntroduction(scholarship, intro): scholarship["introduction"] = intro @staticmethod def setIsRenewable(scholarship, isRenewable): scholarship["isRenewable"] = isRenewable == "yes" or isRenewable == "Yes" @staticmethod def setNumberOfYears(scholarship, years): scholarship["numberOfYears"] = years @staticmethod def setAmountPerYear(scholarship, amount): scholarship["amountPerYear"] = amount @staticmethod def setLocationRequirements(scholarship, locationRequirements): scholarship["locationRequirements"] = locationRequirements.split(';') @staticmethod def setAcademicRequirements(scholarship, academicRequirements): scholarship["academicRequirements"] = academicRequirements.split(';') @staticmethod def setEthnicityRaceRequirements(scholarship, ethnicityRaceRequirements): scholarship["ethnicityRaceRequirements"] = ethnicityRaceRequirements.split(';') @staticmethod def setGenderRequirements(scholarship, genders): scholarship["genderRequriements"] = genders.split(';') @staticmethod def setNationalOriginRequirements(scholarship, nations): scholarship["nationalOriginRequirements"] = nations.split(';') @staticmethod def setOtherRequirements(scholarship, otherRequirements): scholarship["otherRequirements"] = otherRequirements.split(';') @staticmethod def setFinancialRequirements(scholarship, financialRequirements): scholarship["financialRequirements"] = financialRequirements.split(';') @staticmethod def setApplicationProcess(scholarship, applicationProcess): scholarship["applicationProcess"] = applicationProcess @staticmethod def setSchoolsNameToIDMap(scholarship): nameToIDMap = {} for school in scholarship["schoolsList"]: nameToIDMap[school] = "" scholarship["schoolIdList"] = nameToIDMap
class MyClass: def __init__(self, name): self.__name = name def Show(self): print(self.__name) c1 = MyClass('c1') c2 = MyClass('c2') c3 = MyClass('c3') c4 = MyClass('c4') a = {x.Show() for x in {c1, c2, c3, c4} if x not in {c1, c2}}
SUB_GROUP = [ (0, "Нет подгруппы"), (1, "Подгруппа 1"), (2, "Подгруппа 2"), (3, "Подгруппа 3"), (4, "Подгруппа 4"), (5, "Подгруппа 5"), (6, "Подгруппа 6"), (7, "Подгруппа 7"), (8, "Подгруппа 8"), (9, "Подгруппа 9"), ] FORM_OF_EDUCATION = [ (0, "Очная"), (1, "Заочая"), (2, "Очно-заочная"), ] LEVEL_OF_EDUCATION = [ (0, "Бакалавриат/Специалитет"), (1, "Магистратура"), (2, "Аспирантура"), ] ORDER_LESSON = [ (1, "8:30 - 10:00"), (2, "10:10 - 11:40"), (3, "11:50 - 13:20"), (4, "13:50 - 15:20"), (5, "15:30 - 17:00"), (6, "17:10 - 18:40"), (7, "18:45 - 20:15"), (8, "20:20 - 21:50"), ] DAY_OF_WEEK = [ (1, "Понедельник"), (2, "Вторник"), (3, "Среда"), (4, "Четверг"), (5, "Пятница"), (6, "Суббота"), ] PARITY_WEEK = [ (1, "Нечетная"), (2, "Четная"), ]
@metadata_reactor def install_git(metadata): return { 'apt': { 'packages': { 'git': { 'installed': True, }, } }, }
if __name__ == '__main__': n,m = map(int,input().split()) l = map(int,input().split()) a = set(map(int,input().split())) b = set(map(int,input().split())) happy = 0 for i in l: if i in a: happy += 1 elif i in b: happy -= 1 print(happy) # print(sum([(i in a) - (i in b) for i in l]))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################ # File Name: upper_lower_convert.py # Author: One Zero # Mail: zeroonegit@gmail.com # Created Time: 2015-12-28 01:10:28 ############################ str = 'www.zeroonecloud.com' print(str.upper()) # 把所有字符中的小写字母转换成大写字母 print(str.lower()) # 把所有字符中的大写字母转换成小写字母 print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写 print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写
#!/usr/bin/env python """Python-LCS Algorithm, Author: Matt Nichols Copied from https://github.com/man1/Python-LCS/blob/master/lcs.py Modified for running LCS inside P4SC merging algorithm """ ### solve the longest common subsequence problem # get the matrix of LCS lengths at each sub-step of the recursive process # (m+1 by n+1, where m=len(list1) & n=len(list2) ... it's one larger in each direction # so we don't have to special-case the x-1 cases at the first elements of the iteration def lcs_mat(list1, list2): m = len(list1) n = len(list2) # construct the matrix, of all zeroes mat = [[0] * (n+1) for row in range(m+1)] # populate the matrix, iteratively for row in range(1, m+1): for col in range(1, n+1): if list1[row - 1] == list2[col - 1]: # if it's the same element, it's one longer than the LCS of the truncated lists mat[row][col] = mat[row - 1][col - 1] + 1 else: # they're not the same, so it's the the maximum of the lengths of the LCSs of the two options (different list truncated in each case) mat[row][col] = max(mat[row][col - 1], mat[row - 1][col]) # the matrix is complete return mat # backtracks all the LCSs through a provided matrix def all_lcs(lcs_dict, mat, list1, list2, index1, index2): # if we've calculated it already, just return that if (lcs_dict.has_key((index1, index2))): return lcs_dict[(index1, index2)] # otherwise, calculate it recursively if (index1 == 0) or (index2 == 0): # base case return [[]] elif list1[index1 - 1] == list2[index2 - 1]: # elements are equal! Add it to all LCSs that pass through these indices lcs_dict[(index1, index2)] = [prevs + [list1[index1 - 1]] for prevs in all_lcs(lcs_dict, mat, list1, list2, index1 - 1, index2 - 1)] return lcs_dict[(index1, index2)] else: lcs_list = [] # set of sets of LCSs from here # not the same, so follow longer path recursively if mat[index1][index2 - 1] >= mat[index1 - 1][index2]: before = all_lcs(lcs_dict, mat, list1, list2, index1, index2 - 1) for series in before: # iterate through all those before if not series in lcs_list: lcs_list.append(series) # and if it's not already been found, append to lcs_list if mat[index1 - 1][index2] >= mat[index1][index2 - 1]: before = all_lcs(lcs_dict, mat, list1, list2, index1 - 1, index2) for series in before: if not series in lcs_list: lcs_list.append(series) lcs_dict[(index1, index2)] = lcs_list return lcs_list # return a set of the sets of longest common subsequences in list1 and list2 def lcs(list1, list2): # mapping of indices to list of LCSs, so we can cut down recursive calls enormously mapping = dict() # start the process... return all_lcs(mapping, lcs_mat(list1, list2), list1, list2, len(list1), len(list2));
# // This is a generated file, modify: generate/templates/binding.gyp. { "targets": [{ "target_name": "nodegit", "dependencies": [ "<(module_root_dir)/vendor/libgit2.gyp:libgit2" ], "sources": [ "src/nodegit.cc", "src/wrapper.cc", "src/functions/copy.cc", "src/attr.cc", "src/blame.cc", "src/blame_hunk.cc", "src/blame_options.cc", "src/blob.cc", "src/branch.cc", "src/branch_iterator.cc", "src/buf.cc", "src/checkout.cc", "src/checkout_options.cc", "src/cherry.cc", "src/cherry_pick_options.cc", "src/clone.cc", "src/clone_options.cc", "src/commit.cc", "src/config.cc", "src/cred.cc", "src/cred_default.cc", "src/cred_userpass_payload.cc", "src/diff.cc", "src/diff_delta.cc", "src/diff_file.cc", "src/diff_hunk.cc", "src/diff_line.cc", "src/diff_options.cc", "src/diff_perfdata.cc", "src/diff_stats.cc", "src/error.cc", "src/filter.cc", "src/filter_list.cc", "src/giterr.cc", "src/graph.cc", "src/ignore.cc", "src/index.cc", "src/index_conflict_iterator.cc", "src/index_entry.cc", "src/index_time.cc", "src/indexer.cc", "src/libgit2.cc", "src/mempack.cc", "src/merge.cc", "src/merge_file_input.cc", "src/merge_head.cc", "src/merge_options.cc", "src/merge_result.cc", "src/message.cc", "src/note.cc", "src/note_iterator.cc", "src/object.cc", "src/odb.cc", "src/odb_object.cc", "src/oid.cc", "src/oid_shorten.cc", "src/packbuilder.cc", "src/patch.cc", "src/pathspec.cc", "src/pathspec_match_list.cc", "src/push.cc", "src/push_options.cc", "src/refdb.cc", "src/reference.cc", "src/reflog.cc", "src/reflog_entry.cc", "src/refspec.cc", "src/remote.cc", "src/remote_callbacks.cc", "src/repository.cc", "src/repository_init_options.cc", "src/revert.cc", "src/revert_options.cc", "src/revparse.cc", "src/revwalk.cc", "src/signature.cc", "src/smart.cc", "src/stash.cc", "src/status.cc", "src/status_list.cc", "src/strarray.cc", "src/submodule.cc", "src/tag.cc", "src/threads.cc", "src/time.cc", "src/trace.cc", "src/transfer_progress.cc", "src/transport.cc", "src/tree.cc", "src/tree_entry.cc", "src/treebuilder.cc", ], "include_dirs": [ "vendor/libv8-convert", "<!(node -e \"require('nan')\")" ], "cflags": [ "-Wall", "-std=c++11" ], "conditions": [ [ "OS=='mac'", { "xcode_settings": { "GCC_ENABLE_CPP_EXCEPTIONS": "YES", "MACOSX_DEPLOYMENT_TARGET": "10.7", "WARNING_CFLAGS": [ "-Wno-unused-variable", "-Wint-conversions", "-Wmissing-field-initializers" ], "OTHER_CPLUSPLUSFLAGS": [ "-std=gnu++11", "-stdlib=libc++" ], "OTHER_LDFLAGS": [ "-stdlib=libc++" ] } } ] ] }] }
# Text for QML styles chl_style = """ <!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'> <qgis version="2.4.0-Chugiak" minimumScale="0" maximumScale="1e+08" hasScaleBasedVisibilityFlag="0"> <pipe> <rasterrenderer opacity="1" alphaBand="0" classificationMax="1.44451" classificationMinMaxOrigin="CumulativeCutFullExtentEstimated" band="1" classificationMin="0.01504" type="singlebandpseudocolor"> <rasterTransparency/> <rastershader> <colorrampshader colorRampType="INTERPOLATED" clip="0"> <item alpha="255" value="0.01504" label="0.015040" color="#0000ff"/> <item alpha="255" value="0.486765" label="0.486765" color="#02ff00"/> <item alpha="255" value="0.95849" label="0.958490" color="#fffa00"/> <item alpha="255" value="1.44451" label="1.444510" color="#ff0000"/> </colorrampshader> </rastershader> </rasterrenderer> <brightnesscontrast brightness="0" contrast="-6"/> <huesaturation colorizeGreen="128" colorizeOn="0" colorizeRed="255" colorizeBlue="128" grayscaleMode="0" saturation="0" colorizeStrength="100"/> <rasterresampler maxOversampling="2"/> </pipe> <blendMode>0</blendMode> </qgis> """ sst_style = """ <!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'> <qgis version="2.4.0-Chugiak" minimumScale="0" maximumScale="1e+08" hasScaleBasedVisibilityFlag="0"> <pipe> <rasterrenderer opacity="1" alphaBand="-1" classificationMax="29.129" classificationMinMaxOrigin="CumulativeCutFullExtentEstimated" band="1" classificationMin="-1.66383" type="singlebandpseudocolor"> <rasterTransparency/> <rastershader> <colorrampshader colorRampType="INTERPOLATED" clip="0"> <item alpha="255" value="-1.66383" label="-1.663830" color="#2c7bb6"/> <item alpha="255" value="6.03438" label="6.034378" color="#abd9e9"/> <item alpha="255" value="13.7326" label="13.732585" color="#ffffbf"/> <item alpha="255" value="21.4308" label="21.430792" color="#fdae61"/> <item alpha="255" value="29.129" label="29.129000" color="#d7191c"/> </colorrampshader> </rastershader> </rasterrenderer> <brightnesscontrast brightness="0" contrast="0"/> <huesaturation colorizeGreen="128" colorizeOn="0" colorizeRed="255" colorizeBlue="128" grayscaleMode="0" saturation="0" colorizeStrength="100"/> <rasterresampler maxOversampling="2"/> </pipe> <blendMode>0</blendMode> </qgis> """ def makeqml(pth, style): f = open('{}/style.qml'.format(pth), 'w') f.write(style) f.close() return '{}/style.qml'.format(pth)
a = 10 b = 20 c = 300000
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ if not root: return [] result = [] level = [root] while level: new_level = [] total = 0 for node in level: total += node.val if node.left: new_level.append(node.left) if node.right: new_level.append(node.right) result.append(total/len(level)) level = new_level return result
class Solution: def addBinary(self, a: str, b: str) -> str: x=int(a,2) y=int(b,2) return bin(x+y)[2:]
#母音を変数に vowel = 'aeiouAEIOU' #標準入力 name = input() #cname変数に母音じゃないものをjoinしていって出力 #'間に挿入する文字列'.join([連結したい文字列のリスト]) cname = ''.join(s for s in name if s not in vowel) print(cname) #複数行の入出力 input_line = int(input()) for i in range(input_line): n = input() print(n) # 繰り返し出力 input_line = 'one two three four five' n = input_line.split() for i in n: print(i) # tomato_counter lerning = 25 rest = 5 tomato = lerning + rest print("トータル勉強トマト") tomats = int(input()) total_tomato = tomato * tomats print(str(tomato / 60) + "時間勉強した") # 配列内配列動くけど力技過ぎて納得行かない n = int(input()) m = [input().split() for _ in range(n)] for i in range(n): # m[i]のままだと上手くdelできないので別の変数に o = m[i] # listの先頭を除去(求められた仕様) del o[0] # listを並列して出力するおまじない o=' '.join(o) print(o) # 1 - 100 までの数値を間に空白をあけつつ出力する。ただし最後の数値には空白をつけない。 for i in range(100): if i != 99: print(i + 1, end=" ") else: print(i + 1) # 標準入力からの100の文字列を空listに追加する。 str = [] for i in range(100): str.append(input()) # 3行3列を出力するコード。自分で書いてクソみたいだなと思ってたらほぼ正解で困惑。 n = input().split() for i in range(len(n)): if (i+1) % 3 == 0: print(n[i]) else: print(str(n[i])+' ', end='') # 2重ループで9*9出力するコード i = 1 while i <= 9: j = 1 while j <= 9: print(i * j, end=" ") j = j + 1 #空printは改行 print() i = i + 1 # 同じく for i in range(1,10): for j in range(1,10): if j == 9: print(i*j) else: print(i*j, end=" ") # 自分ではクソコードだと思ってるのにほぼあってたときの悲しみ n = input().split() for i in range(1,int(n[0])+1): if i % int(n[0]) == 0: print(n[0]) else: print(i, end=" ") for j in range(1,int(n[1])+1): if j % int(n[1]) == 0: print(n[1]) else: print(j, end=" ") # なんか納得行かないw N = int(input()) for i in range(1, N+1): for j in range(1, i+1): if j == i: print(j) else: print(j, end=" ") # 微妙に納得行かないw N = int(input()) M = [0] * N values = input().split() # listにintでvaluesを代入していく(listをint化するため?) for i in range(N): M[i] = int(values[i]) # 二重ループ処理、以降は前の問題と同じ for i in range(N): for j in range(1, M[i] + 1): # 最大値を比較する対象がM[i]の値となる if j == M[i]: print(j) else: print(j, end=" ") # B相当の問題らしい↑の問題の応用で解ける※変数名がクソなのはいつものこと N = input().split() #標準入力1行目(N[1]のみ使った) M = input().split() #標準入力2行目 K = [0] * int(N[1]) # [0, 0, 0, 0] # 標準入力3行目をlistにする(split()を使用するためにこの時点ではstr) values = input().split() # int型listに変換してる感じ for i in range(int(N[1])): K[i] = int(values[i]) # 出力用カウント変数 L = 0 # 今回のハマリポイントややこしいことせずにこれだけで解ける # 他の言語で言うところのforeachでイテラブルオブジェクトK[2, 6, 1, 1]が順に代入される for i in K: for j in range(i): if j == i - 1: print(M[L]) else: print(M[L], end=" ") L += 1 # 辞書を使った文字変換 m = {'A':'4', 'E':'3', 'G':'6'} t = ''.join(m.get(c, c) for c in s) # 罫線あり九九 i = 1 for i in range(1,10): for j in range(1,10): if j == 9: k = i * j print("{: >2}".format(k)) else: k = i * j print("{: >2} | ".format(k), end="") # こういう手もある # print("{: >2}".format(i * j), end="") # if j == 9: # print() # else: # print(end=" | ") if i < 9: print("=" * (9 * 2 + 3 * (9-1))) ### in演算子 if 0 in a: print("NO") else: print("YES") ### ソートする問題 n = int(input()) num = [int(x) for x in input().split()] num.sort() print(*num, sep=', ') ### 内包表記でかいけつ text= input() def n_gram(text, n): return [ text[idx:idx + n] for idx in range(len(text) -n + 1)] print(n_gram(text, 1)) print(n_gram(text, 2)) print(n_gram(text, 3)) ## 力技 text = input() ret = [] ret2 = [] ret3 = [] for i in range(len(text)): ret.append(text[i]) print(ret) for i in range(len(text) -1): ret2.append(text[i:i+2]) print(ret2) for i in range(len(text) -2): ret3.append(text[i:i+3]) print(ret3) ## while 2で何回割り切れるか n = int(input()) even = 0 while n % 2 == 0: even += 1 n /= 2 print(even) ## n進数に変換 N,M=map(int,input().split()) array=[] while N>=1: array.append(N%M) N/=M N=int(N) array=list(reversed(array)) answer=0 for num in array: answer*=10 answer+=num print(answer) ## n!の末尾に0がいくつ付くか? ###実は因数分解の問題のためn/5がいくつあるかをカウントする n = int(input()) count_zero = 0 while n > 0: count_zero += int(n / 5) n /= 5 print(count_zero) ### enumarate enemies = ["スライム", "モンスター", "ゾンビ", "ドラゴン", "魔王"] # ここに、要素をループで表示するコードを記述する for (i, number) in enumerate(enemies): print(str(i+1) + "番目の"+ number +"が現れた") ### append # 各要素を3倍にして新しいリストを作成する numbers = [12, 34, 56, 78, 90] # ここに、各要素を3倍にして新しいリストを作成するコードを記述する numbers2 = [] for i in numbers: numbers2.append(i * 3) print(numbers2) # ドットで文字を出力しよう letter_A = [[0,0,1,1,0,0], [0,1,0,0,1,0], [1,0,0,0,0,1], [1,1,1,1,1,1], [1,0,0,0,0,1], [1,0,0,0,0,1]] # ここに、ドットを表示するコードを記述する for list in letter_A: for dot in list: if dot == 1: print("@", end="") elif dot == 0: print(" ", end="") print("") print() # 2次元リストで画像を配置 # 標準入力内容 1,1,1,1 0,0,0,0 2,3,4,2 _ # 画像用リスト players_img = [ "Empty.png", "Dragon.png", "Crystal.png", "Hero.png", "Heroine.png"] team = [] while True: line = input() if line == "_": break team.append(line.split(",")) print("<table>") for line in team: print("<tr>") for person in line: print("<td><img src='" + players_img[int(person)] + "'></td>") print("</tr>") print("</table>") # list初期化して値を入れてく方法 N = int(input()) A = [0] * N values = input().split() for i in range(N): A[i] = int(values[i]) for a in A: print(a) # flagで判定 n = [10, 13, 21, 1, 6, 51, 10, 8, 15, 6] flag = False for i in n: if i == 6: print("Yes") flag = True break if not flag: print("No") # 二次元配列を二重ループで出力 li = [[6, 5, 4, 3, 2, 1], [3, 1, 8, 8, 1, 3]] for i in range(len(li)): for j in range(len(li[i])): print(li[i][j], end="") if j < len(li[i]) - 1: print(end=" ") else: print() # 二次元配列の入力など n, m, k, l = map(int, input().split()) # 二次元配列のから配列を作成 list = [[0] * m for i in range(n)] # 空の二次配列に標準入力から値を入れていく for i in range(n): value = input().split() for j in range(m): list[i][j] = int(value[j]) # 完成した二次元配列から指定された部分を表示 print(list[k-1][l-1]) # tmpを使って入れ替え a, b = map(int, input().split()) tmp = a a = b b = tmp print(a, b) # 配列内で入れ替え A, B, N = map(int, input().split()) a = [int(x) for x in input().split()] a[A-1], a[B-1] = a[B-1], a[A-1] for ele in a: print(ele) # スライスを用いる A, B, N = map(int, input().split()) a = [int(x) for x in input().split()] # A-1からBの範囲をスライスして出力 for ele in a[A-1:B]: print(ele) # 配列を逆に n = int(input()) list = [int(x) for x in input().split()] lists = reversed(list) for i in lists: print(i) # count関数使えってことだったらしい N, M = map(int, input().split()) A = [int(x) for x in input().split()] print(A.count(M)) # 要素の削除 n, m = map(int, input().split()) list = [int(x) for x in input().split()] del list[m-1] for i in list: print(i) # 要素の挿入 N, M, K = map(int, input().split()) list = [int(x) for x in input().split()] list.insert(M-1, K) for i in list: print(i) # 並び替えて重複を除くsortしてset list = [1, 3, 5, 1, 2, 3, 6, 6, 5, 1, 4] sort = sorted(set(list)) for i in sort: print(i) # マンハッタン距離とか言うのを使用し点2.3からの各点の距離を求める N = int(input()) x = [0] * N y = [0] * N for i in range(N): value = input().split() x[i] = int(value[0]) y[i] = int(value[1]) for i in range(N): print(abs(x[i]-2) + abs(y[i]-3)) # フィボナッチ数 # リスト数入力と初期化 N = int(input()) list = [0] * N # 1以下はこういう決まり list[0] = 0 list[1] = 1 for i in range(2, N): # 2以降はこういう決まり list[i] = list[i-2] + list[i-1] for i in list: print(i) # ブランク明けて横並び出力 n = int(input()) for i in range(1, n + 1): if i != n: print(i, end=" ") else: print(i) # N行K列出力する二重ループ N, K = map(int, input().split()) for i in range(1, K+1): for i in range(1, N+1): if i == N: print(i) else: print(i, end=" ") print() # 二次元配列、なんか2行目のKは_でもいけるっぽい習った気がするけど忘れた… # この場合戻り地を保存しないとのこと N, K = map(int, input().split()) list = [input().split() for K in range(N)] # list = [input().split() for _ in range(N)] for i in range(N): for j in range(K): if j == K-1: print(list[i][j]) else: print(list[i][j], end=" ") print() # なんかしらんけどnとk逆にしててはまってた n, k = map(int, input().split()) a = [input().split() for _ in range(n)] for i in range(n): for j in range(k): if a[i][j] == "1": print(i + 1, j + 1) break # 正解したもののもうちょいスマートにやれる模様 N, K = map(int, input().split()) # ここを工夫するとint化するためにvalue変数作らずにすむ list = [input().split() for _ in range(N)] maxvalue = 0 for i in range(N): for j in range(K): value = int(list[i][j]) if value >= maxvalue: maxvalue = value print(maxvalue) # sum使わない模様 N, K = map(int, input().split()) list = [[int(i) for i in input().split()] for _ in range(N)] for i in range(N): print(sum(list[i])) # 1列目を除外するのにifを使った N = int(input()) list = [[int(i) for i in input().split()] for _ in range(N)] for i in list: value = 0 for j in range(len(i)): if j != 0: value += i[j] print(value) #スライスを使う方法もある模様 n = int(input()) for _ in range(n): k_a = [int(i) for i in input().split()] # nで良かろうものをkとして定義 k = k_a[0] # 配列の1~をaに代入 a = k_a[1:] # (列の)合計値初期化 s = 0 for i in range(k): s += a[i] print(s) # Nの階段作るやつ N = int(input()) for i in range(1, N+1): # 列をiまで繰り返す(範囲を1~i(i+1)とする) for j in range(1, i+1): # 最大範囲が列の末となる if j == i: print(j) else: print(j, end=" ") # 掛けた数字が0以下のこともあるんやでwとかいうクソトラップにハマったが取りうる最大値(最小値)を初期化するすべを学んだ N, K = map(int, input().split()) listN = [int(i) for i in input().split()] listK = [int(i) for i in input().split()] maxvalue = -10000 for i in range(N): for j in range(K): value = listN[i] * listK[j] if value > maxvalue: maxvalue = value print(maxvalue) # てっきり配列の行列を入れ替える問題かと思ったら出力を入れ替えるだけの問題だった N, K = map(int, input().split()) list = [input().split() for _ in range(N)] for i in range(K): for j in range(N): if j == N -1: print(list[j][i]) else: print(list[j][i], end=" ") # かけ算表を作る問題 listの宣言方法をミスっていた。知識として0ではなくnoneを指定する方法があることを学んだ。 n = int(input()) a = [int(i) for i in input().split()] # 0ではなくnoneでも可 list = [[0]*n for _ in range(n)] for i in range(n): for j in range(n): list[i][j] = a[i] * a[j] for i in range(n): for j in range(n): if j == n-1: print(list[i][j]) else: print(list[i][j], end=" ") # 素数カウント n = int(input()) # カウント変数の初期化 ans = 0 # 1は素数の条件に含まれるので2からSTART for i in range(2, n + 1): # ループ完了管理フラグ is_prime = True # i ** (1/2) で割り切れなければ素数 for j in range(2, int(i ** (1 / 2)) + 1): # Nの値まで2重ループを回したのでループ終了 if i % j == 0: is_prime = False break if is_prime: ans += 1 print(ans) # log2 2が素数であることを利用した解き方 n = int(input()) ans = 0 for i in range(1, n + 1): now = i # 2で割り切れる時にカウントする while now % 2 == 0: now //= 2 ans += 1 print(ans) # ただのFIZZBUZZ hour = 24 minit = 60 for i in range(hour): for j in range(minit): if (i + j) % 3 == 0 and (i + j) % 5 == 0: print('FIZZBUZZ') elif (i + j) % 3 == 0: print('FIZZ') elif (i + j) % 5 == 0: print('BUZZ') else: print() # 突然の格子点 max = 0 for x in range(1, 99): for y in range(1, 99 - x): if max < x * y and x ** 3 + y ** 3 < 100000: max = x * y print(max) # 通貨の最小支払い枚数を求める X, Y, Z = map(int, input().split()) # 1白石で支払う場合(最大枚数だがXとYが0の場合最小枚数になり得る) minmai = Z # 2重ループで通過XとYの枚数をカウント for i in range(Z // X + 1): # 0ということもあり得る for j in range(Z // Y + 1): # X、Y通貨で支払った残りをvalueとして求める if i * X + j * Y <= Z: value = Z - i * X - j * Y # 最小枚数の更新ループ if i + j + value < minmai: minmai = i + j + value print(minmai) # フラグ使って直角三角形あるかどうか探すやつ N = int(input()) flag = False for b in range(1, N): for c in range(1, N - b): a = N - b - c # ここで颯爽と三平方の定理さんが登場! if a ** 2 == b ** 2 + c **2: flag = True # フラグ管理について新たな知見を得た if flag: print("YES") else: print("NO") # ただカウントしただけ n = int(input()) list = [int(i) for i in input().split()] k = int(input()) count = 0 for i in range(n): if list[i] == k: count += 1 print(count) # flagもvalueも不要な冗長版クソコード n = int(input()) a = [int(x) for x in input().split()] k = int(input()) flag = False for i in range(n): if a[i] == k: flag = True value = i + 1 break if flag: print(value) else: print(0) # list.index()を使うと楽かもしれん n = int(input()) a = [int(x) for x in input().split()] k = int(input()) if k in a: print(a.index(k) + 1) else: print(0) # index_kは最終的に条件にあったものに上書きされるからこれでええやろとおもったら正解するも微妙に違うぽい n = int(input()) list = [int(i) for i in input().split()] k = int(input()) index_k = 0 for i in range(n): if list[i] == k: index_k = i+1 print(index_k) # rangeで逆向きに指定? n = int(input()) a = [int(x) for x in input().split()] k = int(input()) index_of_k = 0 # range(start, stop[, step]) for i in range(n - 1, -1, -1): if a[i] == k: index_of_k = i + 1 break print(index_of_k) # 簡単 n = int(input()) list = [int(i) for i in input().split()] k = int(input()) for i in range(n): if list[i] == k: print(i+1) # max, min list = [int(i) for i in input().split()] print(max(list), min(list)) # list.sort()を使うと最小値が左先頭に来る[0]、最大値は最後になる[-1] n = int(input()) a = [int(x) for x in input().split()] a.sort() print(a[-1], a[0]) # iではなく変数噛ませたほうが無難 n = int(input()) list = [int(x) for x in input().split()] for i in range(n): if list[i] % 2 == 0: break print(i+1)
# Copyright © 2020, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. # All rights reserved. # # The DELTA (Deep Earth Learning, Tools, and Analysis) platform is # 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. """ Custom layers provided by DELTA. """
for i in range(int(input())): n = int(input()) s = input() a,b = [-1 for j in range(26)],[1e5 for j in range(26)] for j in range(n): if(a[ord(s[j])-97]==-1): a[ord(s[j])-97] = j else: if(j-a[ord(s[j])-97]<b[ord(s[j])-97]): b[ord(s[j])-97] = j-a[ord(s[j])-97] a[ord(s[j])-97] = j print(max(n-min(b),0))
class Solution: def minDistance(self, word1: str, word2: str) -> int: edits = [[x for x in range(len(word1) + 1)] for y in range(len(word2) + 1)] for i in range(1, len(word2) + 1): edits[i][0] = edits[i - 1][0] + 1 for i in range(1, len(word2) + 1): for j in range(1, len(word1) + 1): if word2[i - 1] == word1[j - 1]: edits[i][j] = edits[i - 1][j - 1] else: edits[i][j] = 1 + min(edits[i][j - 1], edits[i - 1][j - 1], edits[i - 1][j]) return edits[-1][-1]
ENHANCED_PEER_MOBILIZATION = 'enhanced_peer_mobilization' CHAMP_CAMEROON = 'champ_client_forms' TARGET_XMLNS = 'http://openrosa.org/formdesigner/A79467FD-4CDE-47B6-8218-4394699A5C95' PREVENTION_XMLNS = 'http://openrosa.org/formdesigner/DF2FBEEA-31DE-4537-9913-07D57591502C' POST_TEST_XMLNS = 'http://openrosa.org/formdesigner/E2B4FD32-9A62-4AE8-AAB0-0CE4B8C28AA1' ACCOMPAGNEMENT_XMLNS = 'http://openrosa.org/formdesigner/027DEB76-422B-434C-9F53-ECBBE21F890F' SUIVI_MEDICAL_XMLNS = 'http://openrosa.org/formdesigner/7C8BC256-0E79-4A96-9ECB-D6D8C50CD69E'
def attack(state, attacking_moves_sequence): new_state = state.__deepcopy__() ATTACKING_TERRITORY_INDEX = 0 ENEMY_TERRITORY_INDEX = 1 for attacking_move in attacking_moves_sequence: print("in attack attacking move",attacking_move) print("new state map in attack", len(new_state.map)) print("enemy",attacking_move[ENEMY_TERRITORY_INDEX].territory_name) attacking_territory = new_state.get_territory(attacking_move[ATTACKING_TERRITORY_INDEX]) enemy_territory = new_state.get_territory(attacking_move[ENEMY_TERRITORY_INDEX]) # print("in attack attacking and enemy",attacking_territory, enemy_territory ) # print("in attack ", len(new_state.get_owned_territories(attacking_territory.owner)), attacking_territory.number_of_armies, enemy_territory.number_of_armies) # print("attacking army before ",attacking_territory.number_of_armies) # print("enemy army before ",enemy_territory.number_of_armies) attacking_territory.number_of_armies -= 1 enemy_territory.number_of_armies = 1 if attacking_territory.number_of_armies <= 0 or enemy_territory.number_of_armies <= 0 : raise(ValueError("Not valid attack move sequence")) enemy_territory.owner = attacking_territory.owner print("owner",enemy_territory.owner, attacking_territory.owner) print("owned territories after attacking",len(new_state.get_owned_territories(attacking_territory.owner))) return new_state def reinforce_territory(state, territory, additional_armies): """ Used to add reinforcement armies to a territory. Args: territory: The territory that will have the reinforcement. additional_armies: the armies which will be added to the territory. """ keys = state.adjacency_list.keys() for key in keys: if key.territory_name == territory.territory_name: key.number_of_armies += additional_armies return
# You may need this if you really want to use a recursive solution! # It raises the cap on how many recursions can happen. Use this at your own risk! # sys.setrecursionlimit(100000) def read_lines(filename): try: f = open(filename,"r") lines = f.readlines() f.close() filtered_contents = [] for line in lines: line = line.rstrip("\n") filtered_contents.append(list(line)) #read lines converted to cells objects in list of lists return filtered_contents except FileNotFoundError: print("{} does not exist!".format(filename)) exit() def some(grid): i = 0 while i < len(grid): k = 0 while k < len(grid[i]): if (grid[i][k] == "X" ): #Find X row = int(i) col = int(k) return row,col k += 1 i += 1 def solve(filename): grid = read_lines(filename) start_pos = some(grid) x = start_pos[0] y = start_pos[1] ls = ["u","d","r","l"] pass # Base Cases # # if (x,y outside maze) return false # # if (x,y is goal) return true # # if (x,y is wall) return false # # if (x,y is air) return true def solve(mode): pass if __name__ == "__main__": solution_found = False if solution_found: pass # Print your solution... else: print("There is no possible path.")
class MultiFilterCNNModel(object): def __init__(self, max_sequences, word_index, embed_dim, embedding_matrix, filter_sizes, num_filters, dropout, learning_rate, beta_1, beta_2, epsilon, n_classes): sequence_input = Input(shape=(max_sequences,), dtype='int32') embedding_layer = Embedding(len(word_index)+1, embed_dim, input_length=max_sequences, weights=[embedding_matrix], trainable=True, mask_zero=False)(sequence_input) filter_sizes = filter_sizes.split(',') #embedding_layer_ex = K.expand_dims(embedding_layer, ) #embedding_layer_ex = Reshape()(embedding_layer) conv_0 = Conv1D(num_filters, int(filter_sizes[0]), padding='valid', kernel_initializer='normal', activation='relu')(embedding_layer) conv_1 = Conv1D(num_filters, int(filter_sizes[1]), padding='valid', kernel_initializer='normal', activation='relu')(embedding_layer) conv_2 = Conv1D(num_filters, int(filter_sizes[2]), padding='valid', kernel_initializer='normal', activation='relu')(embedding_layer) maxpool_0 = MaxPooling1D(pool_size=max_sequences - int(filter_sizes[0]) + 1, strides=1, padding='valid')(conv_0) maxpool_1 = MaxPooling1D(pool_size=max_sequences - int(filter_sizes[1]) + 1, strides=1, padding='valid')(conv_1) maxpool_2 = MaxPooling1D(pool_size=max_sequences - int(filter_sizes[2]) + 1, strides=1, padding='valid')(conv_2) merged_tensor = merge([maxpool_0, maxpool_1, maxpool_2], mode='concat', concat_axis=1) flatten = Flatten()(merged_tensor) # average_pooling = AveragePooling2D(pool_size=(sequence_length,1),strides=(1,1), # border_mode='valid', dim_ordering='tf')(inputs) # # reshape = Reshape()(average_pooling) #reshape = Reshape((3*num_filters,))(merged_tensor) dropout_layer = Dropout(dropout)(flatten) softmax_layer = Dense(output_dim=n_classes, activation='softmax')(dropout_layer) # this creates a model that includes model = Model(inputs=sequence_input, outputs=softmax_layer) adam = Adam(lr=learning_rate, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon) #sgd = optimizers.SGD(lr=0.001, decay=1e-5, momentum=0.9, nesterov=True) model.compile(optimizer="adam", loss='categorical_crossentropy', metrics=["accuracy"]) self.model = model
#!usr/bin/python # -*- coding: utf-8 -*- class Database(object): """Database class holding information about node/label relationships, mappings from nodes to images and from images to status.""" def __init__(self, root_name="core"): """Constuctor for the Database class. Args: root_name (str, optional): Name given to the reference abstract category. Defaults to "core". """ # Create the graph as a dict naming descendants of each node self.graph = {root_name: set()} # Mapping between each node/label and the images referencing it self.nodes_images = {root_name: set()} # Dict holding the current status of each image self.images_status = dict() def add_nodes(self, nodes): """Method to add nodes to the Database graph, given a parent-child relationship. Args: nodes (list): List of tuples describing nodes and their parent, to be added to the graph. """ for (name, parent) in nodes: """Possible improvements here: - Introduce a hard check that each parent must exist - Pre-sort the node list for dependencies / find the source(s) node(s) + ordering in a DAG. e.g. [("core", None), ("A1", "A"), ("A", "core")] wouldn't be an issue. """ # Notify the parent node that the granularity has changed self.notify_granularity(parent) # Notify sibling nodes (parent's other children) that the coverage has changed for sibling in self.graph[parent]: self.notify_coverage(sibling) # Formally add node to the graph (as itself + child of its parent) and create entry in mapping self.graph[parent].add(name) self.graph[name] = set() self.nodes_images[name] = set() def add_extract(self, images): """Method to add image labeling information in the Database. Args: images (dict): Mappings of each image to one or multiple labels/nodes. """ for image, nodes in images.items(): # Flag keeping track of whether the current image has referenced only known nodes so far. valid_nodes = True """Nested loop for this reason: we need to update the status of an image if it references an invalid node. Therefore we need to iterate both on images and nodes. """ for node in nodes: """ From the description, it is not explicit whether invalid references to non-existent nodes should be kept. e.g. if `img003` references node `E` that is not in the graph, should this reference be kept in case node `E` is added later on. Here we choose not to keep it, however in the opposite case, we can easily move the content of the if-statement outside. """ if node in self.graph: self.nodes_images[node].add(image) else: # Report that an invalid reference was found for this image valid_nodes = False # Update the image status accordingly self.images_status[image] = "valid" if valid_nodes else "invalid" def get_extract_status(self): """Retrieve the status associated to each image, which was maintained on the fly as we updated the Database. Returns: [dict]: A dictionary of image names and their associated status. """ return self.images_status def notify_granularity(self, node): """Helper method allowing to change the status of an image if there was an extension in granularity (only on valid images, no precendence over coverage changes). Args: node (string): Name of the node whose status needs an update """ for image in self.nodes_images[node]: if self.images_status[image] == "valid": self.images_status[image] = "granularity_staged" def notify_coverage(self, node): """Helper method allowing to change the status of an image if there was an extension in coverage (only on valid images or images that have had their granularity changed). Args: node (string): Name of the node whose status needs an update """ for image in self.nodes_images[node]: if self.images_status[image] in ["valid", "granularity_staged"]: self.images_status[image] = "coverage_staged"
norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='open-mmlab://resnet50_v1c', backbone=dict( type='ResNetV1c', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), dilations=(1, 1, 2, 4), strides=(1, 2, 1, 1), norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, style='pytorch', contract_dilation=True), decode_head=dict( type='PSPHead', in_channels=2048, in_index=3, channels=512, pool_scales=(1, 2, 3, 6), dropout_ratio=0.1, num_classes=6, norm_cfg=dict(type='BN', requires_grad=True), align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=dict( type='FCNHead', in_channels=1024, in_index=2, channels=256, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=6, norm_cfg=dict(type='BN', requires_grad=True), align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), train_cfg=dict(), test_cfg=dict(mode='whole')) dataset_type = 'CardDataset' data_root = '../card_dataset' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) crop_size = (256, 256) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations'), dict(type='Resize', img_scale=(500, 500), ratio_range=(0.5, 2.0)), dict(type='RandomCrop', crop_size=(256, 256), cat_max_ratio=0.75), dict(type='RandomFlip', flip_ratio=0.5), dict(type='PhotoMetricDistortion'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size=(256, 256), pad_val=0, seg_pad_val=255), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_semantic_seg']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(500, 500), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=8, train=dict( type='CardDataset', data_root='../card_dataset', img_dir='images', ann_dir='labels', pipeline=[ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations'), dict(type='Resize', img_scale=(500, 500), ratio_range=(0.5, 2.0)), dict(type='RandomCrop', crop_size=(256, 256), cat_max_ratio=0.75), dict(type='RandomFlip', flip_ratio=0.5), dict(type='PhotoMetricDistortion'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size=(256, 256), pad_val=0, seg_pad_val=255), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_semantic_seg']) ], split='splits/train.txt'), val=dict( type='CardDataset', data_root='../card_dataset', img_dir='images', ann_dir='labels', pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(500, 500), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ], split='splits/val.txt'), test=dict( type='CardDataset', data_root='../card_dataset', img_dir='images', ann_dir='labels', pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(500, 500), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ], split='splits/val.txt')) log_config = dict( interval=10, hooks=[dict(type='TextLoggerHook', by_epoch=False)]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = 'checkpoints/pspnet_r50-d8_512x1024_40k_cityscapes_20200605_003338-2966598c.pth' resume_from = None workflow = [('train', 1)] cudnn_benchmark = True optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005) # optimizer=dict( # paramwise_cfg = dict( # custom_keys={ # 'head': dict(lr_mult=10.)})) optimizer_config = dict(type='OptimizerHook') lr_config = dict(policy='poly', power=0.9, min_lr=0.0001, by_epoch=False) runner = dict(type='IterBasedRunner', max_iters=200) checkpoint_config = dict(by_epoch=False, interval=200, type='CheckpointHook') evaluation = dict(interval=200, metric='mIoU', by_epoch=False) work_dir = './work_dirs/tutorial' seed = 0 gpu_ids = range(0, 1)
class Solution: def longestAwesome(self, s: str) -> int: table = {0 : -1} mask = maxLen = 0 for i, c in enumerate(s): mask ^= (1 << int(c)) for j in range(10): mask2 = mask ^ (1 << j) if mask2 in table: maxLen = max(maxLen, i - table[mask2]) if mask in table: maxLen = max(maxLen, i - table[mask]) else: table[mask] = i return maxLen
# This is what gets created by TextField.as_tensor with a SingleIdTokenIndexer # and a TokenCharactersIndexer; see the code snippet above. This time we're using # more intuitive names for the indexers and embedders. token_tensor = { 'tokens': {'tokens': torch.LongTensor([[2, 4, 3, 5]])}, 'token_characters': {'token_characters': torch.LongTensor( [[[2, 5, 3], [4, 0, 0], [2, 1, 4], [5, 4, 0]]])} } # This is for embedding each token. embedding = Embedding(num_embeddings=6, embedding_dim=3) # This is for encoding the characters in each token. character_embedding = Embedding(num_embeddings=6, embedding_dim=3) cnn_encoder = CnnEncoder(embedding_dim=3, num_filters=4, ngram_filter_sizes=[3]) token_encoder = TokenCharactersEncoder(character_embedding, cnn_encoder) embedder = BasicTextFieldEmbedder( token_embedders={'tokens': embedding, 'token_characters': token_encoder}) embedded_tokens = embedder(token_tensor) print(embedded_tokens) # This is what gets created by TextField.as_tensor with a SingleIdTokenIndexer, # a TokenCharactersIndexer, and another SingleIdTokenIndexer for PoS tags; # see the code above. token_tensor = { 'tokens': {'tokens': torch.LongTensor([[2, 4, 3, 5]])}, 'token_characters': {'token_characters': torch.LongTensor( [[[2, 5, 3], [4, 0, 0], [2, 1, 4], [5, 4, 0]]])}, 'pos_tag_tokens': {'tokens': torch.tensor([[2, 5, 3, 4]])} } vocab = Vocabulary() vocab.add_tokens_to_namespace( ['This', 'is', 'some', 'text', '.'], namespace='token_vocab') vocab.add_tokens_to_namespace( ['T', 'h', 'i', 's', ' ', 'o', 'm', 'e', 't', 'x', '.'], namespace='character_vocab') vocab.add_tokens_to_namespace( ['DT', 'VBZ', 'NN', '.'], namespace='pos_tag_vocab') # Notice below how the 'vocab_namespace' parameter matches the name used above. # We're showing here how the code works when we're constructing the Embedding from # a configuration file, where the vocabulary object gets passed in behind the # scenes (but the vocab_namespace parameter must be set in the config). If you are # using a `build_model` method (see the quick start chapter) or instantiating the # Embedding yourself directly, you can just grab the vocab size yourself and pass # in num_embeddings, as we do above. # This is for embedding each token. embedding = Embedding(embedding_dim=3, vocab_namespace='token_vocab', vocab=vocab) # This is for encoding the characters in each token. character_embedding = Embedding(embedding_dim=4, vocab_namespace='character_vocab', vocab=vocab) cnn_encoder = CnnEncoder(embedding_dim=4, num_filters=5, ngram_filter_sizes=[3]) token_encoder = TokenCharactersEncoder(character_embedding, cnn_encoder) # This is for embedding the part of speech tag of each token. pos_tag_embedding = Embedding(embedding_dim=6, vocab_namespace='pos_tag_vocab', vocab=vocab) # Notice how these keys match the keys in the token_tensor dictionary above; # these are the keys that you give to your TokenIndexers when constructing # your TextFields in the DatasetReader. embedder = BasicTextFieldEmbedder( token_embedders={'tokens': embedding, 'token_characters': token_encoder, 'pos_tag_tokens': pos_tag_embedding}) embedded_tokens = embedder(token_tensor) print(embedded_tokens)
#!/usr/bin/python # -*- coding: utf-8 -*- """ Image tags """ img_tag = '[Ваше_изображение]' img_group_tag, img_group_closing_tag = '[Ряд_изображений]', '[/Ряд_изображений]' group_img_tag = '[Рядовый_элемент]'
pessoas = [['João', 15],['Maria', 22], ['Messias', 35]] print(pessoas[0][1]) print(pessoas[1][0]) print(pessoas[2][1]) print(pessoas) print(pessoas[1]) ############################################################# teste = list() teste.append('Leonardo') teste.append(17) galera = list() galera.append(teste[:]) teste[0] = 'João' teste[1] = 16 galera.append(teste[:]) print(galera) ############################################################## galera = [['Leo', 17],['Kleberson', 18],['oaquem', 56]] for p in galera: print(f'{p[0]} tem {p[1]} anos de idade') ########################################################## galera2 = [] dado = [] menor = mai = 0 for c in range (0,3): dado.append(str(input('Nome: '))) dado.append(int(input('Idade: '))) galera2.append(dado[:]) dado.clear() for p in galera2: if p[1] >= 21: print(f'O(a) {p[0]} é maior de idade') mai += 1 else: print(f'O(a) {p[0]} é menor de idade') menor += 1 print(f'{menor} menores e {mai} maiores')
{ "targets": [ { "target_name": "decompressor", "sources": ["decompressor.cpp"] }, { "target_name": "pow_solver", "sources": ["pow_solver.cpp"] } ] }
class C4FileIO(): red_wins = 0 blue_wins = 0 def __init__(self): try: f = open("c4wins.txt", "r") lines = f.readlines() f.close() if type(lines) == list: self.deserialize_file(lines) except FileNotFoundError: print("File not found, writing new file.") def deserialize_file(self, lines): for line in lines: line = line.strip("\n") w = line.split(",") if w[0] == "red_wins": self.red_wins = int(w[1]) elif w[0] == "blue_wins": self.blue_wins = int(w[1]) def serialize_file(self): f = open("c4wins.txt", "w") f_str = "" f_str += "red_wins," + str(self.red_wins) + " \n" f_str += "blue_wins," + str(self.blue_wins) + " \n" print(f_str) f.write(f_str) f.close()