content
stringlengths
7
1.05M
# V1 : DEV # V2 # https://blog.csdn.net/fuxuemingzhu/article/details/80778651 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def generateTrees(self, n): """ ...
menor = 0 c = 1 s = float(input("Digite o 1 salário")) while(c<=14): c+=1 s = float(input(f"Digite o {c} salário")) if(s<menor): menor = s print(f"O menor salário entre os {c} foi R${menor:.2f}")
trunk_capacity = float(input()) is_trunk_full = False number_of_baggage = 0 command = input() while command != 'End': current_luggage = float(command) trunk_capacity -= current_luggage number_of_baggage += 1 if number_of_baggage % 3 == 0: trunk_capacity -= current_luggage * 0.1 if trunk_ca...
name1 = input("Write your name: ").lower() name2 = input("Write other person's name: ").lower() joinedName = name1 + name2 def loveCounter(countParameter): count1 = 0 for i in countParameter: count1 += joinedName.count(i) return count1 trueCount = loveCounter("true") loveCount = loveCounter("lov...
#VÊ A MÉDIA DA CRIANÇA REBELDE def notas_loukas(num1a,num2a,num3a,num4a): peso1 = 2 peso2 = 3 media = ((num1a*peso1)+(num2a*peso1)+(num3a*peso2)+(num4a*peso2))/10 print(f"A média é de {media}") if media < 3: print("REPROVADO!") elif media >= 3 and media < 5: print("RECUPERAÇÃO")...
class PontiacError(Exception): """Base class for error conditions defined for this application""" pass class ConfigurationError(PontiacError): """Exception class to denote an error in application configuration""" pass class DataValidationError(PontiacError): """Exception class to denote an erro...
n = int(input()) w = [(list(map(int, input().split()))) for i in range(n)]#x,y,h w.sort(key=lambda x:(x[2]),reverse=True) hcon1 = 0 hcon2 = 0 for cx in range(101): for cy in range(101): for i in range(n): if w[i][2] > 0: if i == 0: hcon1 = abs(w[i][0] - cx) +...
# 使用多个循环 pizzas = [['shuiguo', 'kaorou'], ['bingqiling', 'regou']] for pizza in pizzas: for v in pizza: print('I love '+v+' pizza.')
def add3(x, y=0, z=0): return x + y + z def mul3(x=1, y=1, z=1): return x * y * z def doubler_premier_kwds(votre, signature): # TODO: votre code pass
""" Problem: https://www.hackerrank.com/challenges/find-a-string/problem Max Score: 10 Difficulty: Easy Author: Ric Date: Nov 13, 2019 """ def count_substring(string, sub_string): occ = 0 lenth_A = len(string) lenth_B = len(sub_string) for i in range(lenth_A - lenth_B + 1): if string[i: i + le...
name_list= ['Sharon','Mic','Josh','Hannah','Hansel'] height_list = [172,166,187,200,166] weight_list = [59.5,65.6,49.8,64.2,47.5] size_list = ['M','L','S','M','S']\ details_list = [['Sharon', 'F', 33], ['Mic', 'M', 24], ['Josh', 'M', 25 ], ['Hannah', 'F', 30], ['Hanzel', 'M', 26]] gender = [] age = [] bmi_list = [] b...
# -*- coding: utf-8 -*- """ Created on Thu Oct 21 18:31:48 2021 @author: User """ class Camion: def __init__(self): self.lotes = [] def __iter__(self): return self.lotes.__iter__() #%% camion = Camion() for c in camion: print(c) #%% a = [1, 9, 4, 25, 16] i = a.__iter__() i.__next__()...
def fib(n): if (n <= 2): return 1 else: return fib(n-1) + fib(n-2)
i, j, k = (int(x) for x in input().split()) day = 0 for num in range(i, j+1): rev_num = int(str(num)[::-1]) if (num - rev_num) % k == 0: day += 1 print(day)
"""Advent of Code 2018 Day 8.""" def main(file_input='input.txt'): numbers = [int(num) for num in get_file_contents(file_input)[0].strip().split()] tree, _ = parse_tree(numbers) print(f'Sum of all metadata entries: {sum_metadata(tree)}') print(f'Value of root node: {root_value(tree)}') ...
# Paths # Fill this according to own setup BACKGROUND_DIR = 'input/backgrounds/' BACKGROUND_GLOB_STRING = '*.jpg' POISSON_BLENDING_DIR = './pb' SELECTED_LIST_FILE = 'input/selected.txt' DISTRACTOR_LIST_FILE = 'input/neg_list.txt' DISTRACTOR_DIR = 'input/distractor_objects_dir/' DISTRACTOR_GLOB_STRING = '*.jpg' INVERTE...
""" Funções (def) em python - *args **kwargs (quando não sabe a quantidade de argumentos que a função irá receber) """ def func(*args, **kwargs): print(args) idade = kwargs.get('idade') if idade is not None: print(idade) else: print('idade não existe') lista = [1,2,3,4,5] lista2...
def poiEmails(): ''' find e-mail list ''' email_list = ["kenneth_lay@enron.net", "kenneth_lay@enron.com", "klay.enron@enron.com", "kenneth.lay@enron.com", "klay@enron.com", "layk@enron.com", "chairman.ken@enron.com", "jeffr...
def alternatives(expected_result, indices): return { idx: expected_result for idx in indices } class ExpectedResult: def __init__(self, segment_list, non_empty): self.segment_list = segment_list self.non_empty = {} for index_type in ['a', 'ab', 'abc', 'tuple']: if index_typ...
class GPIO: PUD_UP = 0 BCM = 1000 FALLING = 2000 IN = 3000 # This is the GPIO state: add a value [16, 20, 21, 26] to simulate a # button that is pressed, remove it to indicate release. clear_gpios = set() @classmethod def setup(cls, port, mode, pull_up_down): pass @c...
test = { 'name': 'q1f', 'points': 2, 'suites': [ { 'cases': [ { 'code': '>>> ' 'FGpercent_table.index.values\n' 'array([1, 2, 3, 4, 5])', 'hidden': False, ...
types_of_people = 10 # number x = f"There are {types_of_people} types of people." # f-string binary = "binary" # string do_not = "don't" # string y = f"Those who know {binary} and those who {do_not}." # f-string print(x) # print f-string print(y) # print f-string print(f"I said: {x}") # capsule f-string in f...
class Solution: def numComponents(self, head: ListNode, G: List[int]) -> int: ans = 0 G = set(G) while head: if head.val in G and (head.next == None or head.next.val not in G): ans += 1 head = head.next return ans
_ERROR_BOOTSTRAP_CSS = """/*! * Bootstrap v4.0.0 (https://getbootstrap.com) * Copyright 2011-2018 The Bootstrap Authors * Copyright 2011-2018 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3...
""" 172. Factorial Trailing Zeroes Given an integer n, return the number of trailing zeroes in n!. Explanation the number of zeros is the minimum of the number of 2 and the number of 5. Since multiple of 2 is more than multiple of 5, the number of zeros is dominant by the number of 5. """ class Solution(object): ...
class SimpleIter: def __init__(self): pass def __iter__(self): return 'Nope' s = SimpleIter() print('__iter__' in dir(s) ) # => True def is_iterable(obj): try: iter(obj) return True except TypeError: return False obj = 100 if is_iterable(obj): for i in o...
def firstDuplicate(a): counts = {} for c in a: if c in counts: return c counts[c] = 1 return -1 # a = [2, 1, 3, 5, 3, 2]
description = 'memograph readout' tango_base = 'tango://ictrlfs.ictrl.frm2.tum.de:10000/memograph09/KWS123/' devices = dict( t_in_memograph_kws123 = device('nicos.devices.entangle.Sensor', description = 'inlet temperature memograph', tangodevice = tango_base + 'T_in', ), t_out_memograph_kw...
dist = float(input('Digite o valor da distância da viagem em KM: ')) valorPassagem = 0.00 if dist <= 200: valorPassagem = (dist * 0.5) else: valorPassagem = (dist * 0.45) print('O valor de sua passagem é de R${:.2f}'.format(valorPassagem)) print('FIM PROGRAMA')
print('\033[1;36m-=\033[m'*16) x = float(input('\033[1;35mEscreva a sua primeira nota:\033[m ')) y = float(input('\033[1;35mEscreva a sua segunda nota:\033[m ')) print('\033[1;36m-=\033[m'*16) z = (x+y)/2 if z > 5.0 and z < 6.9: print('RECUPERAÇÃO') elif z < 5.0: print('REPROVADO') elif z >= 7.0: print('A...
num = int(input('Digite um número:')) if int(num) % 2 == 0: print('O número {} é par'.format(num)) else: print('O número {} é ímpar'.format(num))
def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 def chinese_remainder(n, a, lena): p = i = prod = 1; sm = 0 for i in range(lena): prod *= n[i] for i in ran...
def treat_results(result_file, out_file, begin_index): out = open(out_file, 'w') ind = begin_index out.write('ID;intention\n') with open(result_file, 'r') as f: for line in f: new_line = line.replace('\n', '') out.write(str(ind) + ';' + new_line) out.write('\n...
class Base: def __init__(self, func=None): if func is not None: self.execute = func def execute(self): print("Original execution") def constantFunction(self): print("This function won't change across derived classes") class DerivedA(Base): def __init__(self): super().__init__(executeReplacement1) cla...
# El método private parece privado, pero vemos que realmente no lo es... class MiClase: def public(self): print("Hola, soy un método público") def __private(self): print("Soy un método privado y no me puedes llamar, mwahahahaha") c = MiClase() c.public() # Esta llamada nos dará un AttributeEr...
x = input().split() horainicial, minutoinicial, horafinal, minutofinal = x horainicial = int(x[0]) minutoinicial = int(x[1]) horafinal = int(x[2]) minutofinal = int(x[3]) if horainicial < horafinal: h = horafinal - horainicial if minutoinicial < minutofinal: m = minutofinal - minutoinicial if m...
QB_NAME = input("What is the QB's name?") print(QB_NAME) RUSH_ATTEMPTS = 0 PASS_ATTEMPTS = 0 PASS_YARDS = 0 CURRENT_PASS_YARDS = 0 RUSH_YARDS = 0 CURRENT_RUSH_YARDS = 0 PASS_TD = 0 RUSH_TD = 0 SACKS = 0 SS = 0 INTC = 0 INC = 0 COM = 0 FUM = 0 TD = 0 QBR = 0 SACK_LIST = ["Number", "Of", "Sacks", "="]...
''' A list rotation consists of taking the last element and moving it to the front. For instance, if we rotate the list [1,2,3,4,5], we get [5,1,2,3,4]. If we rotate it again, we get [4,5,1,2,3]. Write a Python function rotatelist(l,k) that takes a list l and a positive integer k and returns the list l after k rotation...
# # PySNMP MIB module CISCO-SME-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SME-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:12:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
"""text example of implicit loop iterators Author: Dr. Jan Pearce, Berea College Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. """ def main(): list=[10, 20, 30, 40] for num in list: print(num) main()
default_az_parameters = { "azure_cluster" : { "subscription": "Bing DLTS", "infra_node_num": 1, "worker_node_num": 2, "mysqlserver_node_num": 0, "nfs_node_num": 1, "azure_location": "westus2", "infra_vm_size" : "Standard_D1_v2", "worker_vm_size": "Sta...
train_config = {} # # MODEL PARAMETERS ## # # MNIST train_config['A'] = 28 # image width train_config['B'] = 28 # image height train_config['img_size'] = train_config['B'] * train_config['A'] # the canvas size train_config['draw_with_white'] = True # draw with white ink or black ink train_config['enc_rnn_mod...
def required_fuel(mass): return int(mass / 3) - 2 def fuel_calc(initial_fuel): fuel_on_fuel = required_fuel(initial_fuel) if (fuel_on_fuel) > 0: return fuel_on_fuel + fuel_calc(fuel_on_fuel) else: return 0 def calc(modules): return sum(required_fuel(int(x)) for x in modules) de...
#!/usr/bin/env python3.8 def infinite_dict_to_tuple(i_dict): """ given infinite dictionary convert to dictionary with key tuples """ list_out = [] for key in dict_a.keys(): s_dict = {"key":None, "value":None} sub_list = [key] new_dict = dict_a[key] if type(new_dict) is not dict: s_dict["...
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" ...
class Board: def __init__(self, row = 6, column = 7): self.board = [['.' for x in range(column)]for y in range(row)] self.__row = row self.__column = column def __str__(self): string = "" for item in self.board: for position in item: string += position string += ' ' string += "\n" return s...
## ## # File auto-generated against equivalent DynamicSerialize Java class # Jul 27, 2015 4654 skorolev Added filters class AlertVizRequest(object): def __init__(self): self.message = None self.machine = None self.priority = None self.sourceKey = None self.category...
def calculate_rewards(grades: [float]): """given a list of grades represented by positive integers returns rewards number that suits the students grades in the same given orders """ # Runtime: O(n), space: O(n) # initializing the rewards with minimum of 1 for each grade rewards = [1 for _ in gra...
def get_button_info(number): with open("songs.csv", "r") as fp: for i, line in enumerate(fp, start=1): if i == number: line = line.strip() line = line.split(", ") return line def create_empty_file(): with open("songs.csv", "w") as f...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ pyprometheus.const ~~~~~~~~~~~~~~~~~~ Prometheus instrumentation library for Python applications :copyright: (c) 2017 by Alexandr Lispython. :license: , see LICENSE for more details. :github: http://github.com/Lispython/pyprometheus """ class Types(object): BAS...
# String concatenation # Suppose we want to create a string that says "subscript to ____" # Few ways to do this # youtuber = "FreeCodeCamp" # print("Subscribe to " + youtuber) # print("Subscribe to {}".format(youtuber)) # print(f"Subscribe to {youtuber}") adj = input("Adjective: ") verb1 = input("Verb 1: ") verb2 = i...
# -*- coding: utf-8 -*- class AbstractNode(object): def _generic_find(self, node_list_name, **kvargs): found_nodes = self._generic_recursion(node_list_name, kvargs, [], []) return self._check_found_nodes(found_nodes) def _generic_recursion(self, node_list_name, search_clauses, found_nodes, ...
''' Failed complexity test, the code below returt O(N*N) yet the question wants O(N) ''' # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 lengthy = len(A) if (lengthy == 0 or lengthy == 1): return 0 ...
# # PySNMP MIB module CISCO-DATA-COLLECTION-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DATA-COLLECTION-CAPABILITY # Produced by pysmi-0.3.4 at Mon Apr 29 17:36:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pyt...
# # PySNMP MIB module APPIAN-PPORT-COMMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPIAN-PPORT-COMMON-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:07:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
"""Constants Module.""" IS = 0.2 VAT = 0.21 SEMESTRAL = 2 MENSUAL = 12 ANUAL = 1 CUATRIMESTRAL = 3 TRIMESTRAL = 4 BIANUAL = 0.5 BIMENSUAL = 6
class MidasConfig(object): def __init__(self, linked: bool): self.linked = linked IS_DEBUG = True
# Python program showing # a use of input() val = input("Enter your value: ") print(val) # Program to check input # type in Python num = input("Enter number :") print(num) name1 = input("Enter name : ") print(name1) # Printing type of input value print("type of number", type(num)) print("type of name", type(name1))...
#!/usr/bin/env python3 """Implements disjoint-set data structures (so-called union-find data structures). Verification: [Union Find](https://judge.yosupo.jp/submission/11774) """ class UnionFind(object): """A simple implementation of disjoint-set data structures. """ def __init__(self, number_of_nodes...
listOfIntegers = [1, 2, 3, 4, 5, 6] for integer in listOfIntegers: if (integer % 2 == 0): print (integer) print ("All done.")
TYPES = ['exact', 'ava', 'like', 'text'] PER_PAGE_MAX = 50 DBS = ['dehkhoda', 'moein', 'amid', 'motaradef', 'farhangestan', 'sareh', 'ganjvajeh', 'wiki', 'slang', 'quran', 'name', 'thesis', 'isfahani', 'bakhtiari', 'tehrani', 'dezfuli', 'gonabadi', 'mazani'] ERROR_CODES = { "400": "f...
""" 고양이 출력하기 핵심은 첫줄에 carriage return을 쓰는 것이지만 f 처럼 r 옵션을 주어서 __repr__ 로 주어진 문자를 그대로 표현할 수도 있다. https://shoark7.github.io/programming/python/difference-between-__repr__-vs-__str__ """ print(r"""\ /\ ) ( ') ( / ) \(__)|""")
# Script: software_sales # Description: A software company sells a package that retails for $99. # This program asks the user to enter the number of packages purchased. The program # should then display the amount of the discount (if any) and the total amount of the # purchase aft...
""" 144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,2,3] Follow up: Recursive solution is trivial, could you do it iteratively? """ class Solution: def preorder...
# https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/dB9drnfWzpiWznESA/ def alphanumericLess(s1, s2): tokens_1 = list(re.findall(r"[0-9]+|[a-z]", s1)) tokens_2 = list(re.findall(r"[0-9]+|[a-z]", s2)) idx = 0 # Tie breakers, if all compared values are the same then the first # diffe...
""" *Pixel* A pixel is a color in point space. """ class Pixel( Point, Color, ): pass
# coding:utf-8 def redprint(str): print("\033[1;31m {0}\033[0m".format(str)) def greenprint(str): print("\033[1;32m {0}\033[0m".format(str)) def blueprint(str): print("\033[1;34m {0}\033[0m".format(str)) def yellowprint(str): print("\033[1;33m {0}\033[0m".format(str))
"""Settings for the ``cmsplugin_blog`` app.""" JQUERY_JS = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js' JQUERY_UI_JS = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js' JQUERY_UI_CSS = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css'
# ----------------------------------------------------- # Trust Game # Licensed under the MIT License # Written by Ye Liu (ye-liu at whu.edu.cn) # ----------------------------------------------------- cfg = { # Initial number of coins the user has 'initial_coins': 100, # Number of total rounds 'num_ro...
class Piece: def __init__(self, t, s): self.t = t self.blocks = [] rows = s.split('\n') for i in range(len(rows)): for j in range(len(rows[i])): if rows[i][j] == '+': self.blocks.append((i, j)) def get_color(t, active=False): return...
# Enter your code here. Read input from STDIN. Print output to STDOUT def getMean(list): sum = 0 for i in list: sum += i mean = float(sum) / len(list) return mean def getMedian(list): median = 0.0 list.sort() if (len(list) % 2 == 0): median = float(list[len(list)//2 - 1] + li...
#! python3 # -*- encoding: utf-8 -*- ''' Current module: winuidriver.__about__ Rough version history: v1.0 Original version to use ******************************************************************** @AUTHOR: Administrator-Bruce Luo(罗科峰) MAIL: luokefeng@163.com RCS: winuidriver.__a...
# -*- coding: utf-8 -*- """ Created on Sun Jan 3 09:43:06 2021 @author: SethHarden """ # SLICING ------------------------------------------------ x = 'computer' #[start : end : step] print(x[1:6:2]) print(x[1:4]) #1 - 4 print(x[3:]) #3 - end print(x[:5]) #0 - 5 print(x[-1]) #gets from right side print(x[:-2]) #fro...
# Enumerated constants for voice tokens. SMART, STUPID, ORCISH, ELVEN, DRACONIAN, DWARVEN, GREEK, KITTEH, GNOMIC, \ HURTHISH = list(range( 10))
{ 'model_dir': '{this_dir}/model_data/', 'out_dir': 'output/masif_peptides/shape_only/', 'feat_mask': [1.0, 1.0, 0.0, 0.0, 0.0], }
#!/usr/bin/python3 # -*- coding:utf-8 -*- # Project: http://plankton-toolbox.org # Copyright (c) 2010-2018 SMHI, Swedish Meteorological and Hydrological Institute # License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit). # import toolbox_utils # import plankton_core class DataImportUti...
def to_rna(dna_strand): rna_dict = { 'C':'G', 'G':'C', 'T':'A', 'A':'U' } ret = '' for char in dna_strand: ret += rna_dict[char] return ret
class Subtraction: print('Test Subtraction class') def __init__(self, x, y): self.x = x self.y = y print('This is Subtraction function and result of your numbers is : ', x-y)
# number = input('Enter a Number') # w, x, y, z = 5, 10, 10, 20 # if w > x: # print('x equals y') # elif w < y: # print('Second Condition') # elif x == y: # print('Third Condition') # else: # print('Everything is False') # username = 'qaidjohar' # password = 'qwerty' # if not 5 == 5: # if (usern...
paths = \ [dict(steering_angle = -20, target_angle = -20, coords = \ [[0, 53, 91, 97], [0, 64, 97, 107], [15, 76, 107, 119], [33, 86, 119, 132], [47, 95, 132, 146], [59, 102, 146, 160], [69, 108, 160, 175], [76, 112, 175, 190]]), dict(st...
tests = int(input()) for _ in range(tests): data = [float(num) for num in input().split()] sum = 2*data[0]+3*data[1]+5*data[2] print("%0.1f" % (sum/10))
""" This module contains some helper functions for printing actions and boards. Feel free to use and/or modify them to help you develop your program. """ def print_move(n, x_a, y_a, x_b, y_b, **kwargs): """ Output a move action of n pieces from square (x_a, y_a) to square (x_b, y_b), according to the forma...
# Append at the end of /etc/mailman/mm_cfg.py DEFAULT_ARCHIVE = Off DEFAULT_REPLY_GOES_TO_LIST = 1 DEFAULT_SUBSCRIBE_POLICY = 3 DEFAULT_MAX_NUM_RECIPIENTS = 30 DEFAULT_MAX_MESSAGE_SIZE = 10000 # KB
class Palindrome: def __init__(self, word, start, end): self.word = word self.start = int(start / 2) self.end = int(end / 2) def __str__(self): return self.word + " " + str(self.start) + " " + str(self.end) + "\n"
# -*- coding: utf-8 -*- dictTempoMusica = dict({"W":1,"H":1/2,"Q":1/4,"E":1/8,"S":1/16,"T":1/32,"X":1/64}) listSeqCompasso = list(map(str, input().split("/"))) while listSeqCompasso[0] != "*": listSeqCompasso.pop(0) listSeqCompasso.pop(-1) qntCompassoDuracaoCorreta = 0 for compasso in listSeqCompasso:...
def decode(message): first_4 = message[:4] first = add_ordinals(message[0], message[-1]) second = add_ordinals(message[1], message[0]) third = add_ordinals(message[2], message[1]) fourth = add_ordinals(message[3], message[2]) fifth = add_ordinals(message[-4], message[-5]) sixth = add_ordin...
_empty = [] _simple = [1, 2, 3] _complex = [{"value": 1}, {"value": 2}, {"value": 3}] _locations = [ ("Scotland", "Edinburgh", "Branch1", 20000), ("Scotland", "Glasgow", "Branch1", 12500), ("Scotland", "Glasgow", "Branch2", 12000), ("Wales", "Cardiff", "Branch1", 29700), ("Wales", "Cardiff", "Branc...
def hamming_distance(x: int, y: int): """ Calculate the number of bits that are different between 2 numbers. Args: x: first integer to calculate distance on Y: second integer to calculate distance on Returns: An integer representing the number of bits that are different ...
""" Objective 14 - Perform basic dictionary operations """ """ Add "Herb" to the phonebook with the number 7653420789. Remove "Bill" from the phonebook. """ phonebook = { "Abe": 4569874321, "Bill": 7659803241, "Barry": 6573214789 } # YOUR CODE HERE phonebook['Herb'] = 7653420789 del phonebook['Bill...
MYSQL_DB = 'edxapp' MYSQL_USER = 'root' MYSQL_PSWD = '' MONGO_DB = 'edxapp' MONGO_DISCUSSION_DB = 'cs_comments_service_development'
# coding: utf-8 class DataBatch: def __init__(self, torch_module): self._data = [] self._label = [] self.torch_module = torch_module def append_data(self, new_data): self._data.append(self.__as_tensor(new_data)) def append_label(self, new_label): self._label.appen...
""" Problem: Given an integer n, return the length of the longest consecutive run of 1s in its binary representation. For example, given 156, you should return 3. """ def get_longest_chain_of_1s(num: int) -> int: num = bin(num)[2:] chain_max = 0 chain_curr = 0 for char in num: if char == "1...
input = """ p cnf 3 4 -1 2 3 0 1 -2 0 1 -3 0 -1 -2 0 """ output = """ SAT """
"""A programe which will find all such numers between 1000 and 3000 such that each digit of the number is an even number""" #num1=0 #num2=0 #num3=0 #num4=0 #real=0 #lresult=[] #def even(num,num1,num2,num3,real): # if (num%2==0) and (num1%2==0) and (num2%2==0) and (num3%2==0): # lresult.append(real) #for value in ran...
def find(A): low = 0 high = len(A) - 1 while low < high: mid = (low + high) // 2 if A[mid] > A[high]: low = mid + 1 elif A[mid] <= A[high]: high = mid return low A = [4, 5, 6, 7, 1, 2, 3] idx = find(A) print(A[idx])
class ladder: def __init__(self): self.start=0 self.end=0
#$Id: embed_pythonLib.py,v 1.3 2010/10/05 19:24:18 jrb Exp $ def generate(env, **kw): if not kw.get('depsOnly',0): env.Tool('addLibrary', library = ['embed_python']) if env['PLATFORM'] == 'posix': env.AppendUnique(LINKFLAGS = ['-rdynamic']) if env['PLATFORM'] == "win32" and env.get('CONTAIN...
class Solution: def letterCasePermutation(self, s: str) -> List[str]: """ Time complexity O(N!) - factorial time need to generate all permutations Space complexity O(N!) Approach: Using BFS generate new permutations by append one more char to all previous generat...
# -*- coding: utf-8 -*- # Copyright by BlueWhale. All Rights Reserved. class ValidateError(ValueError): def __init__(self, val, msg: str, *args): super().__init__(val, msg, *args) self.__val = val self.__msg = msg @property def val(self): return self.__val @property ...
# V0 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ def str2treeHelper(s, i): start = i if...