content
stringlengths
7
1.05M
MODEL_FOLDER_NAME = 'models' FASTTEXT_MODEL_NAME = 'fasttext.magnitude' GLOVE_MODEL_NAME = 'glove.magnitude' WORD2VEC_MODEL_NAME = 'word2vec.magnitude' ELMO_MODEL_NAME = 'elmo.magnitude' BERT_MODEL_NAME = '' UNIVERSAL_SENTENCE_ENCODER_MODEL_NAME = 'https://tfhub.dev/google/universal-sentence-encoder/1' DB_STORAGE_TYPE ...
def CHECK(UNI, PWI, usernameArray, PasswordArray): for UN in usernameArray: if UN == UNI: for PW in PasswordArray: if PW == PWI: if usernameArray.index(UNI) == PasswordArray.index(PWI): return True def login(correctMessage,...
m = [ 'common', 'leap' ] y = 2024 # outside in if y%4 ==0: if y%100 ==0: if y%400 ==0: y=1 else: y=0 else: y=1 else: y=0 print(m[y]) # inside out y=2024 if y%400==0: y=1 elif y%100==0: y=0 elif y%4==0: y=1 else: y=0 print(m[y])...
def create_markdown_content( input_file: str, import_list: list[str], global_import_table: dict[str,str], mermaid_diagrams: list[str], debug_dump: str, ) -> str: debug_block = create_markdown_debug_dump_block(debug_content=debug_dump) import_block = turn_out_the_import_list( import_...
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
class Stack: """Klasa stosu używana do tworzenia labiryntu""" def __init__(self): self.__st = [] def push(self, val_1, val_2): self.__st.append((val_1, val_2)) def pop(self): if len(self.__st) != 0: return self.__st.pop() else: return [-1] d...
'''4.Faça um programa que leia uma palavra e some 1 no valor ASCII de cada caractere da palavra. Imprima a string resultante.''' sermo = list(input("Digite uma palavra:")) for i,p in enumerate(sermo): sermo[i] = chr((ord(p))+1) sermo = "".join(sermo) print(f"Nova string: {sermo}")
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. class ADOConstants: """ Constants specific to Azure Devops API clients and classes """ work_item_relations = { 'parent': 'System.LinkTypes.Hierarchy-Reverse', 'child': 'System.LinkTypes.Hierarchy-Forward' }
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: cum_sum = [0] for num in nums: cum_sum.append(num+cum_sum[-1]) cum_sum.pop(0) seen_map = {0:1} ans = 0 for csum in cum_sum: if csum-k in seen_map: ans+=s...
height = float(input("Please enter the height in m: \n")) weight = float(input("Please enter the weight in kg: \n")) bmi = weight / height ** 2 print(int(bmi))
#The file contains only the CTC function and the proposed model format. (Not the complete code) def ctc_lambda_func(args): y_pred, labels, input_length, label_length = args y_pred = y_pred[:, 2:, :] return K.ctc_batch_cost(labels, y_pred, input_length, label_length) def train(img_w, load=False): # I...
# -*- coding: utf-8 -*- __title__ = 'ahegao' __description__ = 'Ahegao API wrapper' __url__ = 'https://github.com/AhegaoTeam/AhegaoAPI' __version__ = '1.0.1' __build__ = 11 __author__ = 'SantaSpeen' __author_email__ = 'admin@ahegao.ovh' __license__ = "MIT" __copyright__ = 'Copyright 2022 Ahegao Team'
# design in each module class Cube(object): def __init__(self): pass class Rhombic(object): def __init__(self): pass class Sphere(object): def __init__(self): pass
# write a program to print out all the numbers from 0 to 100 that are divisble by 7 for i in range(0, 101, 7): print(i)
class Solution: def solve(self, matrix): pq = [[0, i] for i in range(len(matrix[0]))] for r in range(len(matrix)): new_pq = [] for c in range(len(matrix[0])): if pq[0][1] == c: top = heappop(pq) heappush(new_pq, [pq[0]...
def rotate(text, key): num_letters = 26 key = key % num_letters l_min = ord('a') u_min = ord('A') text = list( map((lambda s: s if not s.isalpha() else chr(l_min + (((ord(s) - l_min) + key) % num_letters)) ...
# coding: utf-8 def sumSquare(n): '''takes a positive integer n and returns sum of dquares of all the positive integers smaller than n''' if n < 0: return 'Needs a positive number. But Negative given' else: return sum([x**2 for x in range(1, n)]) print(sumSquare(4))
#test = [] #test.append('Gustavo') #test.append(40) #guys = [] #guys.append(test[:]) #test[0] = 'Maria' #test[1] = 22 #print(test, guys[0][1]) galera = list() dado = [] for c in range(0, 5): dado.append(str(input('Qual é o seu nome? '))) dado. append(int(input('Qual é a sua idade?'))) galera.append(dado[:])...
# # @lc app=leetcode id=327 lang=python3 # # [327] Count of Range Sum # # https://leetcode.com/problems/count-of-range-sum/description/ # # algorithms # Hard (35.94%) # Likes: 995 # Dislikes: 116 # Total Accepted: 48.9K # Total Submissions: 135.4K # Testcase Example: '[-2,5,-1]\n-2\n2' # # Given an integer array...
# Author: btjanaka (Bryon Tjanaka) # Problem: (HackerRank) the-minion-game # Title: The Minion Game # Link: https://www.hackerrank.com/challenges/the-minion-game/ # Idea: The basic idea is to count all substrings for each player, but we can't # just list out all the substrings because that is O(n^2), and the string can...
class LevenshteinCostCalculator: """ Cost calculator using Levenshtein minimum edit distance costs of 1 for insertion and deletion and 2 for substitution (given a letter is not substituted for itself). Can also be used as a basic cost calculator for non-letter inputs. """ def insertion_cost(sel...
class APIException(OSError): def __init__(self, message = None, url="https://Bungie.net/"): msg = "There was an error when accessing the Destiny API" if message is not None: msg += ": " + message super().__init__(msg) self._url = url self._message = msg...
IN_PREFIXES = { 'BA', 'BS', 'BUS MS', 'Certificate', 'Graduate Certificate', 'MA', 'Master of Arts', 'Master\'s', 'MBA/MA', 'ME Certificate', 'ME MD/PhD Program', 'ME Program', 'MS', 'P.B.C.', 'Post Bacc Certificate', 'Post Baccalaureate Certificate', ...
class Disc: _instance_count = 0 def __init__(self, name, symbol, code=None): cls = type(self) self.code = cls._instance_count if code is None else code self.name = name self.symbol = symbol cls._instance_count += 1 if cls._instance_count < 1000 else 0 def __int__(se...
# Problem 1 # Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. count = 0 for x in range(1000): if (not x % 3) or (not x % 5): count += x # Альте...
def list_towers(): raise NotImplementedError def create_tower(body): raise NotImplementedError def get_tower(tower_id): raise NotImplementedError def update_tower(tower_id, body): raise NotImplementedError def delete_tower(tower_id): raise NotImplementedError
# sample input array = [ 2, 1, 2, 2, 2, 3, 4, 2 ] to_move = 2 expected = [4, 1, 3, 2, 2, 2, 2, 2] # Simple testing function def test(expected, actual): if expected == actual: print('Working') else: print('Not working, expected:', expected, 'actual:', actual) # O(n) solution def move_element_to_...
# # @lc app=leetcode.cn id=72 lang=python3 # # [72] edit-distance # None # @lc code=end
""" Update Index """ name = "02_upgrade_users_unique_email" dependencies = ["01_upgrade_users"] def upgrade(db): db.users.create_index([('email', 1)], unique=True) def downgrade(db): pass
# # PySNMP MIB module HM2-NETCONFIG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-NETCONFIG-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:19:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
def binary_search(A, target): A = str(A) lo = 0 hi = len(A) index = None while lo <= hi: mid = round(lo + (hi - lo) / 2) mid_ele = int(A[mid]) if mid_ele == target: index = mid break if mid_ele < target: lo = mid + 1 else:...
tree = PipelineElement('DecisionTreeClassifier', hyperparameters={'criterion': ['gini'], 'min_samples_split': IntegerRange(2, 4)}) svc = PipelineElement('LinearSVC', hyperparameters={'C': FloatRange(0.5, 25)}) my_pipe += Stack('fin...
class Solution: def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: ans = [] free = [] # (weight, index, freeTime) used = [] # (freeTime, weight, index) for i, weight in enumerate(servers): heapq.heappush(free, (weight, i, 0)) for i, executionTime in enumerate(tasks...
# # PySNMP MIB module XYLAN-IP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XYLAN-IP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:38:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example 'A man, a plan, a canal: Panama' is a palindrome while 'race a car' is not. """ def is_palindrome(sentence): def normalize(): alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '...
def sign_out() -> str: return """ public func signOut() { SessionManager.shared.session = nil } """.strip() + '\n'
# for em dicionário personInformation = { 'nome':'Marcelo', 'sexo': 'Masculino', 'idade': 25, 'peso': 68 } for person in personInformation: print('{}: {}'.format(person, personInformation[person]))
class IBANValidationException(Exception): """The IBAN did not validate""" class BankDoesNotExistException(IBANValidationException): """The Bank does not exists"""
# from test_mpu65c02.py, 71 tests class Common65C02Tests: """CMOS 65C02 Tests""" # Reset def test_reset_clears_decimal_flag(self): # W65C02S Datasheet, Apr 14 2009, Table 7-1 Operational Enhancements # NMOS 6502 decimal flag = indetermine after reset, CMOS 65C02 = 0 mpu = self._mak...
# Time: O(nlogn + nlogw), n = len(nums), w = max(nums)-min(nums) # Space: O(1) # Given an integer array, return the k-th smallest distance among all the pairs. # The distance of a pair (A, B) is defined as the absolute difference between A and B. # # Example 1: # Input: # nums = [1,3,1] # k = 1 # Output: 0 # Explanat...
class A: def f(self): print("f() in A") class B: def f(self): print("f() in B") class D(A,B): pass class E(B,A): pass print(D.mro()) print(E.mro()) d = D() d.f() e = E() e.f()
def is_pangram(text): """ Checks if a string is a pangram. """ alphabet = 'abcdefghijklmnopqrstuvwxyz' text = text.lower() for letter in alphabet: if letter not in text: return False return True print(is_pangram('The quick brown fox jumps over the lazy dog.')) def needl...
''' * @Author: csy * @Date: 2019-04-28 13:50:45 * @Last Modified by: csy * @Last Modified time: 2019-04-28 13:50:45 ''' digits = list(range(0, 10)) print(digits) print(min(digits)) print(max(digits)) print(sum(digits))
class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ colZeroFlag = False for i in range(0, len(matrix)): if matrix[i][0] == 0: colZeroFlag = True for j in range(1, len...
class constants: NONE = 0 X = 1 O = 2 class variables: explored = 0 def print_board(board): print(simbol(board[0])+"|"+simbol(board[1])+"|"+simbol(board[2])) print("-----") print(simbol(board[3])+"|"+simbol(board[4])+"|"+simbol(board[5])) print("-----") print(simbo...
RequiredKeyIsMissing = \ "No value was found for the required key `{key_name}`" RequiredKeyIsWrongType = ( "Required key `{key_name}` has the wrong " + "type of `{invalid_type}`. The value of this key " + "should have the type `{expected_type}`" ) DirectiveStructureError = ( "The following directi...
def source(): pass def sink(x): pass def alarm(): x = source() sink(x)
# from: http://www.rosettacode.org/wiki/Babbage_problem#Python def main(): print([x for x in range(30000) if (x * x) % 1000000 == 269696][0]) if __name__ == "__main__": main()
print ('making summary table....') #Adjust "Summary" dataframe Summary.rename(columns={'RSL_ID':'WALIS_ID'},inplace=True) Summary['WALIS_ID']='RSL_' + Summary['WALIS_ID'].astype(str) Summary.insert(loc=13, column='Paleo water depth estimate (m)', value='') Summary.insert(loc=14, column='Upper limit of living range (m)'...
def song_decoder(song): result = song.replace("WUB" , " ") result = ' '.join(result.split()) return result
# -*- coding: utf-8 -*- def platform2str(platform: str) -> str: """ get full platform name """ if platform == "amd": return "AMD Tahiti 7970" elif platform == "nvidia": return "NVIDIA GTX 970" else: raise LookupError def escape_suite_name(g: str) -> str: """ format benchma...
#Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. n = float(input('Digite o valor em metros: ')) km = n / 1000 hm = n / 100 dam = n / 10 dm = n*10 cm = n*100 mm = n*1000 print('Você digitou {} metros.'.format(n)) print('Este valor, corresponde a: ') print('{}km...
def print_row(star_count): for _ in range(star_count, size - 1): print(' ', end='') for _ in range(star_count): print('*', end=' ') print('*') size = int(input()) for star_count in range(size): print_row(star_count) for star_count in range(size - 2, -1, -1): print_row(star_count...
def recur_fibo(n): if n <= 1: return n else: return (recur_fibo(n - 1) + recur_fibo(n - 2)) nterms = int(input('You want output many elements ')) if nterms < 0: print('Enter the positive number') else: print("fibonacci sequence") for i in range(nterms): print(recur_fibo(i))...
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: n = len(numbers) last_num = None for i in range(n): num1 = numbers[i] if num1 != last_num: for j in range(i+1, n): num2 = numbers[j] ...
NInput = int(input()) xcoor = [] ycoor = [] for i in range(NInput): x, y = map(int, input().split()) xcoor.append(x) ycoor.append(y) for i in range(0, len(xcoor)): minIndex = i for j in range(i+1, len(xcoor)): if xcoor[j] < xcoor[minIndex]: xcoor[j], xcoor[minIndex] = xcoor[minIn...
# Should only need to modify these paths in this file: # - BTFM_BASE # - LSP_DATASET_DIR # - LSPET_DATASET_DIR # - COCO_DATASET_DIR # - MPII_DATASET_DIR # - TDPW_DATASET_DIR # - MI3_DATASET_DIR # - MI3_PP_DATASET_DIR # - UPI_S1H_DATASET_DIR # Note that this relies on a filesystem that supports symli...
class Solution: def calPoints(self, ops: List[str]) -> int: array = [] for op in ops: if op == 'C': array.pop() elif op == 'D': array.append(array[-1]*2) elif op == "+": array.append(array[-1] + array[-2]) ...
# stringparser.py # # Ronald Rihoo def findFirstQuotationMarkFromTheLeft(string): for i in xrange(len(string) - 1, 0, -1): if string[i] == '"': return i def findFirstQuotationMarkFromTheRight(string): for i in range(len(string)): if string[i] == '"': return i def splitLeftAspect_toChar(stri...
#!/usr/bin/python # coding=utf-8 class Fibs(object): def __init__(self): self.a = 0 self.b = 1 def next(self): self.a, self.b = self.b, self.a + self.b return self.a def __iter__(self): return self if __name__ == "__main__": fibs = Fibs() for fib in fibs:...
# This sample tests that arbitrary expressions (including # subscripts) work for decorators. This support was added # in Python 3.9. my_decorators = (staticmethod, classmethod, property) class Foo: # This should generate an error if version < 3.9. @my_decorators[0] def my_static_method(): return 3...
largura=l=int(input("digite a largura: ")) altura=a=int(input("digite a altura: ")) while altura>0: largura=l while largura >0: if (altura==a or altura ==1): print("#", end="") else: if largura==1 or largura ==l: print("#", end="") else: ...
''' Author: jianzhnie Date: 2021-11-08 18:25:03 LastEditTime: 2022-02-25 11:12:28 LastEditors: jianzhnie Description: '''
#String Rotation:Assumeyou have a method isSubstringwhich checks if oneword is a substring of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). #do special caracters as spaces are in the strign or ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Withdraw Views Created on Tue Aug 17 14:16:44 2021 Version: 1.0 Universidad Santo Tomás Tunja Simulation @author: Juana Valentina Mendoza Santamaría @author: Alix Ivonne Chaparro Vasquez presented to: Martha Susana Contreras Ortiz """ def showWithdrawal(): prin...
def fibbs(n): """ Input: the nth number. Output: the number of the Fibonacci sequence via iteration. """ sequence = [] for i in range(n+1): if i == 0: sequence.append(0) elif i == 1: sequence.append(1) else: total = sequence[i - 2] + se...
def fromETH(amt, px): return amt*px def toETH(amt, px): return amt/px def toOVL(amt, px): return fromETH(amt, px) def fromOVL(amt, px): return toETH(amt, px) def px_from_ret(px0: float, ret: float) -> float: '''get the new price given a return''' ret = ret/100 return (ret + 1)*px0 def pn...
def simpleornot(n, out=0): """ Функция определяет простое или нет число :param n: натурально число от 1 до 1000 :param out: 1 - выводим 1 или 0, 0 - печатает :return: 1 для простого, 0 для непростого """ if type(n) == int: if 0 < n < 1001: if n == 1 and n ...
class Results: def __init__(self, error, error_type, description, sequence, activity=None, activity_class=None): self.error = error self.error_type = error_type self.description = description self.sequence = sequence self.activity = activity self.activity_class = acti...
n=3 z=65 for i in range(n): k=z for j in range(n-i): print(' ',end='') for j in range(2*i+1): print(chr(k),end='') k-=1 z=z+2 print() for i in range(1,n): c=z-4 for j in range(i): print(' ',end='') for j in range((2*n)-2*i-1): prin...
with open("pos_tweets.txt") as input_file: text = input_file.read() text_set = set(text.split(" ")) for word in text_set: print(word,text.count(word))
#coding=utf-8 __all__ = ["ModelConfig", "TrainerConfig"] class ModelConfig(object): vocab_size = 104810 embedding_dim = 300 embedding_droprate = 0.3 lstm_depth = 3 lstm_hidden_dim = 300 lstm_hidden_droprate = 0.3 passage_indep_embedding_dim = 300 passage_aligned_embedding_dim = 300 ...
a0 = 27.5 a4 = a0 * 2 ** 4 default_key = "c" match_roman = "[ivIV]?[ivIV]?[iI]?" intervals = {"P1": 0, "m2": 1, "M2": 2, "m3": 3, "M3": 4, "P4": 5, "TT": 6, "P5": 7, "m6": 8, "M6": 9, "m7": 10, "M7": 11, "P8": 12, "m9": 13, "M9": 14, "m10": 15, "M10": 16, "P11": 17, "d12": 18, "P12": 19, "m13": 20, "M13": 21, "m14": 22...
def cipher(): user_input = input("Please provide a word: ")
# -*- coding: utf-8 -*- usr_number = int(input("Enter a number to calculate: ")) if usr_number > 1: for n in range(2, usr_number): if (usr_number % n == 0): print(f'{n} is not a prime number') else: print(f'{n} is a prime number')
date_fullyear = '[0-9]{4}' date_mday = '[0-9]{2}' date_month = '[0-9]{2}' full_date = f'{date_fullyear}-{date_month}-{date_mday}' time_hour = '[0-9]{2}' time_minute = '[0-9]{2}' time_second = '[0-9]{2}' time_secfrac = '\\.[0-9]+' partial_time = f'{time_hour}:{time_minute}:{time_second}({time_secfrac})?' time_numoffset ...
''' Verifique se uma determinada string tem todos os símbolos em maiúsculas. Se a string estiver vazia ou não tiver nenhuma letra, a função deve retornar True. Entrada: uma string. Saída: um booleano. ''' def remove_space(text): text_space = [] for item in text: if item != ' ': text_sp...
__author__ = 'schien' INSTALLED_APPS += ('storages',) STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' S3_URL = 'https://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME STATIC_URL = S3_URL AWS_LOCATION = '/static' AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'E...
class SubMerchant: def __init__(self): self.cardAcceptorID = None self.country = None self.phoneNumber = None self.address1 = None self.postalCode = None self.locality = None self.name = None self.administrativeArea = None self.region = None ...
environment = 'MountainCar-v0' bin_count = 9 goal_positon = 0.5 position_min = -1.2 position_max = 0.6 velocity_min = -0.07 velocity_max = 0.07 num_episodes = 10000 max_steps_in_episode = 200 verbose = 100 learning_rate = 10e-3 eps = 1 discount_factor = 0.9 panelty = -300 test_episodes = 100 bonus = 500 q_table_pa...
#!/usr/bin/python def BubbleSort(val): for passnum in range(len(val)-1,0,-1): for i in range(passnum): if val[i]>val[i+1]: temp = val[i] val[i] = val[i+1] val[i+1] = temp DaftarAngka = [23,7,32,99,4,15,11,20] BubbleSort(DaftarAngka) print(DaftarAngka)
"""Slack toolbox""" def make_slack_response( response_type="ephemeral", text="", attachments=None, blocks=None ): return { "response_type": response_type, "text": text, "attachments": [attachments] if attachments else [], "blocks": blocks if blocks else [], }
# Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def paired_digits_count(data, skip): return sum([int(d) for i, d in enumerate(data) if data[i - skip] == d]) with open("day01.txt") as f: data = f.readline() half = int(len(data) / 2) print("2017 day 1 part 1: %d" % paired_digits_count(data, 1)) print("2017 day 1 part 2: %d" % paired_digits_count(d...
print("Please enter how many marbles you would like: ", end = "") n = int(input()) while n != 0: print("Please enter the how many marbles player one is taking: ", end = "") take = int(input()) if n <= 5: print("Player one wins!") break elif take > n or take > 5 or take == 0: print("You're entering a number t...
# Soultion for Project Euler Problem #8 - https://projecteuler.net/problem=8 # (c) 2017 dpetker TEST_VAL = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950...
""" Sponge Knowledge Base Demo - action context actions """ class ActionWithContextActions(Action): def onConfigure(self): self.withLabel("Action with context actions").withArgs([ StringType("arg1").withLabel("Argument 1"), StringType("arg2").withLabel("Argument 2") ]).withN...
city = "narva" estonianPopulation = [ ["tallinn", 441000], ["tartu", 94000], ["narva", 58000], ["parnu", 41000] ] for p in estonianPopulation: if p[0] == city: print("Population of " + p[0].capitalize() + ": " + str(p[1])) break
""" def my_function(): print("I'm inside function") def function1(): var2 = 5 print(var1) def function2(): var3 = 7 print(var3) print(var1) #print(var2) """ def func(): var4 = 6 if var4 > var1: print("var4 is bigger in func") else: print("var4 is smaller in func") def my_...
def iter_rings(data, pathcodes): ring = [] # TODO: Do this smartly by finding when pathcodes changes value and do # smart indexing on data, instead of iterating over each coordinate for point, code in zip(data, pathcodes): if code == 'M': # Emit the path and start a new one ...
text = 'hello' fileName = 'data.txt' file=open(fileName, 'w') file.write(text) file.close() file = open(fileName, 'r') input_text = file.readline() file.close() print(input_text)
class SearchNode: def __init__(self, pos, parent=None, cost_to_origin=0, cost_to_target=0): self.pos = pos # Might have to change to tuple self.parent = parent self.neighbours = [] self.cost_to_origin = cost_to_origin self.cost_to_target = cost_to_target def get_total_...
class Node(object): """二叉树节点""" def __init__(self, elem=-1, lchild=None, rchild=None): self.elem = elem self.lchild = lchild self.rchild = rchild class CompleteBinaryTree(object): """完全二叉树""" def __init__(self, root=None): self.root = root def add(self, elem): ...
def sl_a_func(): pass def sl_a_func2(): pass class SlAClass(): def __init__(self): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- def new_tips(argv): def tips(func): def nei(a, b): print("start %s %s" %(argv, func.__name__)) func(a, b) print("stop") return nei return tips @new_tips('add_modules') def add(a, b): print(a + b) @new_ti...
def spacify(string, spaces=2): """Add spaces to the beginning of each line in a multi-line string.""" return spaces * " " + (spaces * " ").join(string.splitlines(True)) def multilinify(sequence, sep=","): """Make a multi-line string out of a sequence of strings.""" sep += "\n" return "\n" + sep.jo...
def tail(filepath, n): """Similate Unix' tail -n, read in filepath, parse it into a list, strip newlines and return a list of the last n lines""" with open(filepath) as f: file = f.read() tail_result = file.split('\n')[-n:] return tail_result
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param two ListNodes @return a ListNode """ def mergeTwoLists(self, l1, l2): if l1 is None: return l2 if l2...
N, M = map(int, input().split()) A = list(map(int, input().split())) days = N - sum(A) if days < 0: print(-1) else: print(days)