content
stringlengths
7
1.05M
class TransactionError(Exception): def __init__(self, message): self.message = message # Call the base class constructor with the parameters it needs super().__init__(message) class UserError(Exception): def __init__(self, message): self.message = message # Call the base...
""" Python solution for challenge: "Tennis Game Points" To start the tests, type from CLI: python test_solution_sum_of_missing_numbers.py """ def tennis_game_points(score): # From call to points call_points = {"love": 0, "15": 1, "30": 2, "40": 3} # From string to list (using the separator "-") calls ...
def e_sum(x, y): return x + y def e_sub(x, y): return x - y
s = set(); print(s, type(s)) s = set([1,2,3]); print(s, type(s)) s = set([1,2,3,2,1]); print(s, type(s)) s = {}; print(s, type(s))#dict s = {1,2,3,2,1}; print(s, type(s))
class EventRecorder(object): def __init__(self): super(EventRecorder, self).__init__() self.events = {} self.timestamp = 0 def record(self, event_name, **kwargs): assert event_name not in self.events, "Event {} already recorded".format(event_name) self.timestamp += 1 ...
level = [ (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 0, 0, 0, 0, 0, 2, 1), (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), #0-2 (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), #3-5 (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 0, 0, 0, 0, 0, 2, 1), #6-8 (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1,...
# -*- coding: utf-8 -*- class ScraperError(Exception): pass
PYTHON = "python" CPP = "cpp" CSHARP = "csharp" JAVA = 'java' CHOICES = ( (PYTHON, 'Python3'), (CPP, 'C++'), (CSHARP, 'C#'), (JAVA, 'Java') )
# %% Building out get asset events limit = 50 collection_slug, token_id, ='gutter-cat-gang', None asset_contract_addresses, offset, only_opensea, auction_type, occurred_before, occurred_after = None, None, None, None, None, None account_address = None # initiatie query with limit: query = {"limit" : str(limit)} # C...
class AWSCloudWatchAlarmPermissions: def get_permissions(self, resname, res): alarmname = self._get_property_or_default(res, "*", "AlarmName") alarmactions = self._get_property_or_default(res, None, "AlarmActions") insufficientdataactions = self._get_property_or_default(res, None, "Insuffici...
""" Configurations for local development and production """ class Config: """ Standard configurations """ DEBUG = False class DevelopmentConfig(Config): """ Configuration for local development """ FLASK_PORT = 5000 FLASK_HOST = '0.0.0.0' class ProductionConfig(Config): """ Configuration for p...
"""import nltk import re #import numpy as np #import pandas as pd from nltk.corpus import stopwords from nltk.stem import * #from textblob.classifiers import NaiveBayesClassifier #from sklearn.cross_validation import KFold from nltk.classify.naivebayes import NaiveBayesClassifier #from llda import LLDA #from word_prob_...
#!/usr/bin/env python3 distro={ } library=[] distro["name"]="RedHat" distro["versions"]=["4.0","5.0","6.0","7.0","8.0"] library.append(distro.copy()) distro["name"]="Suse" distro["versions"]=["10.0","11.0","15.0","42.0"] library.append(distro.copy()) print(library)
class Method(): def __init__(self): self.methodDefinition = None self.locals = [] self.instructions = [] self.maxStack = -1 self.returnType = None self.parameters = [] self.attributes = []
class Elevator: occupancy_limit = 8 def __init__(self, occupants): if occupants > self.occupancy_limit: print("The maximum occupancy limit has been exceeded." f" {occupants - self.occupancy_limit} occupants must exit the elevator.") self.occupants = occupants ele...
first = ['Aousnik', 'Ronodeep', 'Anirban'] last = ['Gupta', 'Gupta', 'Chaudhuri'] names = zip(first, last) # joins the first and last list in the tuples 'names' for a, b in names: print(a, b) ''' this function just basically makes a list of tuples like: [('Aousnik', 'Gupta'), ('Ronodeep', Gup...
# SPDX-FileCopyrightText: 2019 Nicholas Tollervey, written for Adafruit Industries # # SPDX-License-Identifier: MIT """A simple directory based Python module that's missing metadata.""" def hello(): """A hello function""" return "Hello, World!"
# x = 5 # y = 10 # z = 20 # x, y, z = 5, 16, 20 # x, y = y, x # x += 5 #x = x + 5 # x -= 5 #x = x - 5 # x *= 5 #x = x * 5 # x /= 5 #x = x / 5 # x %= 5 #x = x % 5 # y //= 5 #y = y // 5 # y **= z #y = y ** z values ...
hght = 420 wdth = 1188 #size(1188,420) #define window size - doesnt work unless in setup inix = int(random(10,50)) #define x as first value for loop iniy1 = int(random(0,hght)) #define y1 as random between 0 and 420=height, no global value yet #iniy2 = iniy1 iniy2 = int(random(...
class InvalidWithdrawal(Exception): pass raise InvalidWithdrawal("You don't have $50 in your account")
n1 = float(input('Primeira nota do aluno:')) n2 = float(input('Segunda nota do aluno:')) n3 = float(input('Terceira nota do aluno:')) m = (n1 + n2 + n3) / 3 print('A mΓ©dia entre {:.1f} e {:.1f} e {:.1f} Γ© de {:.1f}'.format(n1, n2, n3, m))
speed_light_si = 299792458.0 electron_mass_si = 9.10938215e-31 elementary_charge_si = 1.602176487e-19 mu_0_si = 4.0*math.pi*1e-7 epsilon_0_si = 1.0/(mu_0_si*speed_light_si**2) planck_si = 6.62606896e-34 hbar_si = planck_si / (2.0 * math.pi) fine_structure_si = elementary_charge_si**2/(4.0*math.pi*epsilon_0_si*hbar_si*s...
def print_sum(*values): s = 0 for number in values: s += number print(f'The sum of {values} is {s}') print_sum(5, 2) print_sum(2, 9, 4)
#!/usr/bin/env python # *-* coding: UTF-8 *-* """Stabileste daca o expresie de paranteze este corecta.""" def este_corect(expresie): """Apreciaza corectitudinea expresiei.""" memo = [] for _, val in enumerate(expresie): if val not in '([)]': return False if val == '(' or val =...
x = 0 soma = 0 i = 0 while x != -1: x = int(input('digite uma idade: ')) if x != -1: soma += x i += 1 print(soma/i)
if __name__ == '__main__': n = int(input()) output = "" for i in range(1, n+1): output = output + str(i) print(output)
""" Calibration following https://casaguides.nrao.edu/index.php?title=EVLA_6cmWideband_Tutorial_SN2010FZ https://casaguides.nrao.edu/index.php/EVLA_high_frequency_Spectral_Line_tutorial_-_IRC%2B10216-CASA4.5#Bandpass_and_Delay """ vis = '16B-202.sb32532587.eb32875589.57663.07622001157.ms' line_vis = '16B-202.lines.ms'...
# # arr1 = [100,100,200,300,300,400,400] # # arr2 = [14,90,100,100,200,200,450,450,0,0,0,0,0,0,0] # # arr1 = [1,3,5] # # arr2 = [2,4,6,0,0,0] # arr1 = [1,1,1,1,1,1] # arr2 = [12,1,1,1,1,1,2,0,0,0,0,0,0] # # arr1_ptr, arr2_ptr = 0,0 # # while arr2_ptr <= len(arr1) - 1: # # if arr2[arr2_ptr] <= arr1[arr1_ptr]: # # ...
def factorize(x: int): d = 2 while x != 1: if x % d == 0: print('Hello') yield d x //= d else: d += 1 A = factorize(1023) print(A) for x in map(str, A): print('Factor:', x)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Π‘ΠΎΠ·Π΄Π°Ρ‚ΡŒ класс Money для Ρ€Π°Π±ΠΎΡ‚Ρ‹ с Π΄Π΅Π½Π΅ΠΆΠ½Ρ‹ΠΌΠΈ суммами. Число Π΄ΠΎΠ»ΠΆΠ½ΠΎ Π±Ρ‹Ρ‚ΡŒ прСдставлСно двумя полями: Ρ‚ΠΈΠΏΠ° int для Ρ€ΡƒΠ±Π»Π΅ΠΉ ΠΈ ΠΊΠΎΠΏΠ΅Π΅ΠΊ. Дробная Ρ‡Π°ΡΡ‚ΡŒ (ΠΊΠΎΠΏΠ΅ΠΉΠΊΠΈ) ΠΏΡ€ΠΈ Π²Ρ‹Π²ΠΎΠ΄Π΅ Π½Π° экран Π΄ΠΎΠ»ΠΆΠ½Π° Π±Ρ‹Ρ‚ΡŒ ΠΎΡ‚Π΄Π΅Π»Π΅Π½Π° ΠΎΡ‚ Ρ†Π΅Π»ΠΎΠΉ части запятой. Π Π΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Ρ‚ΡŒ слоТСниС, Π²Ρ‹Ρ‡ΠΈΡ‚Π°Π½ΠΈΠ΅, Π΄Π΅Π»Π΅Π½ΠΈΠ΅ сумм...
#Desafio: Criptografando e descriptografando mensagens #lista de letras para criptografar alfabeto = 'abcdefghijklmnopqrstuvwxyz' #capture a mensagem do usuΓ‘rio mensagem = input("Por favor, entre com a mensagem a ser criptografada: ").lower() mensagemCriptografada = '' #captura a chave secreta chave = int(input("Di...
def insertion_sort(v): for i in range (1, len(v)): x = v[i] j = i-1 while j>=0 and x< v[j]: v[j+1] = v[j] j -= 1 v[j+1] = x print() b = [8,3,9,2,1,10,7,5,4,6] print(b) print() a = insertion_sort(b) print() a = b print(a) print()
""" ==== KEY POINTS ==== - Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. - Do the above modifications to the input array in place, do not return anything from your function. - arr.length <= 10000 - arr[i] <= 9 """ """ ==== BRUTE FORCE SOL...
op = 0 n1 = int(input('NΓΊmero 1: ')) n2 = int(input('NΓΊmero 2: ')) while op != 5: print('---------------------') print(' [1] Somar') print(' [2] Multiplicar') print(' [3] Maior') print(' [4] Novos NΓΊmeros') print(' [5] Sair') print('---------------------') op = int(input(' OpΓ§Γ£o: ')...
""" Escribir un programa que guarde en un diccionario los precios de las frutas de la tabla, pregunte al usuario por una fruta, un nΓΊmero de kilos y muestre por pantalla el precio de ese nΓΊmero de kilos de fruta. Si la fruta no estΓ‘ en el diccionario debe mostrar un mensaje informando de ello. Fru...
class User(): def __init__(self , Name , userName , username_type , Game , data_dict): self.index = data_dict.getIndex()+1 self.name = Name self.username = userName self.username_type = username_type self.game = Game self.data = data_dict self.data.AddU...
class Time60(object): 'Time60 - track hours and minutes' def __init__(self, hr, min): self.hr = hr self.min = min def __str__(self): return '%d:%d' %(self.hr, self.min) __repr__ = __str__ def __add__(self, other): return self.__class__(self.hr + other.hr, self.min...
#!/usr/bin/env python # -*- coding: utf-8 -*- # AUTHOR = 'gauravssnl' SITENAME = 'Gauravssnl Tech Blog' SITEURL = 'https://gauravssnl.github.io' # Legal SITE_LICENSE = """ &copy; Copyright 2020 by Gaurav (@gauravssnl) and licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/"> <img al...
""" bilibili_api.utils.aid_bvid_transformer av ε·ε’Œ bv ε·δΊ’θ½¬οΌŒδ»£η ζ₯源:https://www.zhihu.com/question/381784377/answer/1099438784。 """ def bvid2aid(bvid: str): """ BV 号转 AV 号。 Args: bvid (str): BV 号。 Returns: int: AV 号。 """ table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4x...
# internal flags TRANS_FLIPX = 1 TRANS_FLIPY = 2 TRANS_ROT = 4 # Tiled gid flags GID_TRANS_FLIPX = 1 << 31 GID_TRANS_FLIPY = 1 << 30 GID_TRANS_ROT = 1 << 29
INSTALLED_APPS += ( "django_mailbox", # "social", 'reversion', # "social_django", 'django_outlook', )
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 17:05:02 2020 @author: fcosta """
#Cleansing #remove urls, usernames, NA, special charactars, and numbers class TwitterCleanuper: def iterate(self): for cleanup_method in [self.remove_urls, self.remove_usernames, self.remove_na, self.remove_specia...
class TweetCriteria: """Search parameters class""" def __init__(self): self.max_tweets = 0 self.top_tweets = False self.within = "15mi" self.username = None self.since = None self.until = None self.near = None self.query_search = None self...
def get_right(pat, r=256): right = [-1] * r for i in range(len(pat)): right[ord(pat[i])] = i return right def boyemoore_search(txt, pat): right = get_right(pat) skip = 0 i = 0 while i <= len(txt) - len(pat): skip = 0 j = len(pat) - 1 while j >=...
# This is a comment! ''' This isn't technically a comment, but no program can execute between the quotes, and it's fun! ''' """ Same goes here! """ # I am so excited for everything we will learn in this course. # 🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍 # To any of my fellow peers reading this, have you heard of pyLadies? # There's...
def validate_empty(field, name=None): if not field: raise ValueError('This field is Required.') if name and not field: raise validate_empty('{} is Required'.format(name))
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'chromium', 'chromium_android', 'recipe_engine/json', 'recipe_engine/properties', ] def RunSteps(api): api.chromium.set_config('chromium...
# coded in python3 # video : text = input("Enter your text : ") check = True etext = "" for chars in text: if(ord(chars)) <= 90 and ord(chars) <= 65: if((ord(chars) + 13) > 90): x = 64 + ((ord(chars) + 13) - 90) else: x = ord(chars) + 13 elif(ord(chars) <= 122 and o...
a = [74,-72,94,-53,-59,-3,-66,36,-13,22,73,15,-52,75] def maxSubArraySum(a): current_sequence = 0 best_sequence = a[0] for x in a: current_sequence = max(x,current_sequence+x) best_sequence = max(best_sequence,current_sequence) return best_sequence print("Largest sum con...
class Pic16f15356DeviceInformationArea: def __init__(self, address, dia): if len(dia) != 32: raise ValueError('dia', f'PIC16F15356 DIA is 32 words but received {len(dia)} words') self._address = address self._raw = dia.copy() self._device_id = ''.join(['{:04x}'.format(id_byte) for id_byte in dia[0x00:0x09]...
arduino = Runtime.createAndStart("arduino","Arduino") arduino.setBoardMega() arduino.connect("COM7") arduino1 = Runtime.createAndStart("arduino1","Arduino") arduino1.setBoardNano() #connecting arduino1 to arduino Serial1 instead to a COMX arduino1.connect(arduino,"Serial1") servo = Runtime.createAndStart("servo","Se...
# Copyright (c) 2015 Intel Corporation # # 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 ...
##Patterns: W0199 assert (1 == 1, 2 == 2), "no error" ##Warn: W0199 assert (1 == 1, 2 == 2) assert 1 == 1, "no error" assert (1 == 1,), "no error" assert (1 == 1,) assert (1 == 1, 2 == 2, 3 == 5), "no error" assert () ##Warn: W0199 assert (True, 'error msg')
class Parameters(object): def __init__(self, *, p, q, g): if isinstance(p, bytes): p = int.from_bytes(p, 'big') self.p = p if isinstance(q, bytes): q = int.from_bytes(q, 'big') self.q = q if isinstance(g, bytes): g = int.from_bytes(g, 'bi...
############################################## ## CONFIG BLOCK ## ############################################## # @string token - API Token # @string user - This is found in Zendesk under Admin > Channels > API, Commonly your login_email/token # @list user_defined_list - List of emails comm...
# define the time range we are interested in end_time = datetime(2017, 9, 12, 0) start_time = end_time - timedelta(days=2) # build the query query = ncss.query() query.lonlat_point(-155.1, 19.7) query.time_range(start_time, end_time) query.variables('altimeter_setting', 'temperature', 'dewpoint', 'wind...
# Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The integer B denotes that from any place (suppose the index is i) in the array A, you can jump to any one of the place in the array A indexed i+1, i+2, …, i+B if this place can be jumped to. Also, if you step on the inde...
#Fixed by overriding. This does not change behavior, but makes it explicit and comprehensible. class ThreadingTCPServerOverriding(ThreadingMixIn, TCPServer): def process_request(self, request, client_address): #process_request forwards to do_work, so it is OK to call ThreadingMixIn.process_request ...
# -*- coding: utf-8 -*- class Announce: def __init__(self, data=None): self.guild_id: str = "" self.channel_id: str = "" self.message_id: str = "" if data: self.__dict__ = data class CreateAnnounceRequest: def __init__(self, channel_id: str, message_id: str): ...
#!/usr/bin/python3.4 # This program """ Print main text 2 with Exit, List characteristics, Change characteristics, Change characteristics Ask me to choice one of them if choice "Exit": Exit game elif choice "List characteristics": show all characteristics and return to main menu elif choice "Change characte...
num1 = input('Değer Giriniz: ') unit1 = input('Hangi Birimden Dânüştürmek İstersiniz?') unit2 = input('Hangi Birime Dânüştürmek İstersiniz?') if unit1 == "cm" and unit2 == "m": ans = float(num1)/100 print(ans) elif unit1 == "mm" and unit2 == "cm": ans = float(num1)/10 print(ans) elif unit1 ...
__all__ = ['class_in_class_factory'] def class_in_class_factory(parent_class, name, bases=None, **fields): if not (isinstance(bases, tuple) or bases is None): raise TypeError('`bases` must be tuple.') fields['__module__'] = '{parent_class_module_name}.{parent_class_name}'.format( parent_class...
class Tree(object): def __init__(self, x): self.value = x self.left = None self.right = None def balancedBinaryTree(root): def get_height(root): if root is None: return 0 return max(get_height(root.left), get_height(root.right)) + 1 if root is None: ...
#Project Euler Question 54 #Poker hands poker_file = open(r"C:\Users\Clayton\Documents\Python Other Files\p054_poker.txt") content = poker_file.read() content = content.replace(" ", "") content = content.split("\n") card_values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 11, "Q": ...
def did_from_credential_definition_id(credential_definition_id: str) -> str: parts = credential_definition_id.split(":") return parts[0]
def solve_knapsack(profits, weights, capacity): n = len(profits) if capacity <= 0 or n == 0 or len(weights) != n: # basic checks return 0 # We only need one previous row to find the optimal solution, # Overall we need '2' rows, the solution is similar to the previous solution, the only differe...
# Chapter 4 # 60 sec/min * 60 min/hr * 24 hr/day # seconds_per_day = 86400 seconds_per_day = 86400 # 60 sec/min * 60 min/hr * 24 hr/day # Continue Lines with \ alphabet = 'abcdefg' + \ 'hijklmnop' + \ 'qrstuv' + \ 'wxyz' print(alphabet) # Compare with if, elif, and else disaster = True if disaster: p...
# Parent class 1 class Person: def person_info(self, name, age): print('Inside Person class') print('Name:', name, 'Age:', age) # Parent class 2 class Company: def company_info(self, company_name, location): print('Inside Company class') print('Name:', company_name, 'location:'...
BINDIR = '/usr/local/bin' BLOCK_MESSAGE_KEYS = [] BUILD_TYPE = 'app' BUNDLE_NAME = 'pebble-World-Cup.pbw' DEFINES = ['RELEASE'] LIBDIR = '/usr/local/lib' LIB_DIR = 'node_modules' MESSAGE_KEYS = {} MESSAGE_KEYS_HEADER = '/root/hello-pebblejs/pebble-World-Cup/build/include/message_keys.auto.h' NODE_PATH = '/root/.pebble-...
# -*- coding: utf-8 -*- __author__ = 'viruzzz-kun' class OptionsFinish(Exception): pass
cube = lambda x: pow(x,3) def fibonacci(n): if n >= 0: lst = [0] if n >= 1: lst.append(1) if n >= 2: for i in range(2,n+1): lst.append(lst[-1]+ lst[-2]) return lst[:n] if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
def wire(data): x, y = (0, 0) for dir, step in [(x[0], int(x[1:])) for x in data.split(",")]: for _ in range(step): x += -1 if dir == "L" else 1 if dir == "R" else 0 y += -1 if dir == "D" else 1 if dir == "U" else 0 yield x, y def aoc(data): wires = [set(wire(li...
"""Template python project""" def factorial(n: int) -> int: # pylint: disable=invalid-name """Calculates factorial Example: >>> factorial(10) 3628800 """ return [1, 0][n > 1] or factorial(n-1) * n
def find_tree(row, index): if index > len(row): row = row * ((index // len(row)) + 1) if row[index] == '#': return 1 return 0 if __name__ == '__main__': with open('input.txt') as f: data = [r.strip() for r in f.readlines()] indices = range(0, len(data) * 3, 3) tree_cou...
class BufferToLines(object): def __init__(self): self._acc_buff = "" self._last_line = "" self._in_middle_of_line = False def add(self, buff): self._acc_buff += buff.decode() self._in_middle_of_line = False if self._acc_buff[-1] == '\n' else True def lines(self): ...
"""Contains name, version, and description.""" NAME = "saltant-py" VERSION = "0.4.0" DESCRIPTION = "saltant SDK for Python"
""" Tema: Funciones decoradoras. Curso: Curso de python, video 74. Plataforma: Youtube. Profesor: Juan diaz - Pildoras informaticas. Alumno: @edinsonrequena. """ def funcion_decoradora(funcion_como_parametro): def funcion_interior(*args, **kwargs): print('Codigo que se ejecutara antes de llamar a la fu...
GET_ACTION_LIST = 'get_action_list' EXECUTE_ACTION = 'execute_action' GET_FIELD_OPTIONS = 'get_field_options' GET_ELEMENT_STATUS = 'get_element_status' message_handlers = {} def add_handler(message_name, func): message_handlers[message_name] = func def get_handler(message_name): return message_handlers.ge...
""" Parameters for etl & mondrian """ Patient = { "resourceType" : "Patient", "QI": {"resourceType" : 0, "birthDate" : 1, "address" : 1, "gender" : 0, "ord_latitude" : 1, "ord_logitude" : 1, "version" : 0}, "CATEGORICAL": { "resourceType" : 1, "birthDate" : 0, "address" : 1, "gender" : 1, ...
# Write a program that asks the number of kilometers a car has driven and the number of days it has been hired. # Calculate the price to pay, knowing that the car costs US$ 60 per day and US$ 0.15 per km driven. k = float(input('Enter how many kilometers the car has traveled: ')) d = float(input('Enter how many days t...
#!/usr/bin/env python ## ============================================================================= jsonStr = """[{"DT":"\/Date(1495333623000-0700)\/", "ST":"\/Date(1495337144000)\/", "Trend":8, "Value":245, "WT":"\/Date(1495326471000)\/"}, ...
# Copyright (c) 2020-2021 CJ Kucera (cj@apocalyptech.com) # # This software is provided 'as-is', without any express or implied warranty. # In no event will the authors be held liable for any damages arising from # the use of this software. # # Permission is granted to anyone to use this software for any purpose, # ...
asci = """ ╔════╗╔╗ β•”β•— ╔═══╗ ╔══╗╔═══╗ ╔═══╗╔╗ ╔╗╔═╗ β•‘β•”β•—β•”β•—β•‘β•‘β•‘ β•”β•β•šβ•— ║╔═╗║ β•šβ•£β• β•β•‘β•”β•β•—β•‘ ║╔══╝║║ ║║║╔╝ β•šβ•β•‘β•‘β•šβ•β•‘β•šβ•β•—β•”β•β•β•—β•šβ•—β•”β•β•”β•β•β•— β•‘β•šβ•β•β•‘β•”β•β•—β•”β•—β•”β•—β•”β•—β•”β•β•β•— β•‘β•‘ β•‘β•‘ β•‘β•‘ ╔═╗ β•‘β•šβ•β•β•—β•‘β•‘ β•”β•— ╔╗╔╗╔═╗ ╔══╗ β•‘β•šβ•β•...
class BaseMemory(object): def __init__(self, max_num=20000, key_num=2000, sampling_policy='random', updating_policy='random', ): super(BaseMemory, self).__init__() self.max_num = max_num self.key_num = key_num self.s...
commands = input().split(" ") my_list = [] team_a_count = 11 team_b_count = 11 condition = False for i in commands: if i not in my_list: my_list.append(i) if "A" in i: team_a_count -= 1 if "B" in i: team_b_count -= 1 if team_a_count < 7 or team_b_count < 7: ...
""" Utilities. """ def init_params(model, scip_limits, scip_params): """ :param model: scip.Model(), model instantiation :param scip_limits: dict, specifying SCIP parameter limits :param scip_params: dict, specifying SCIP parameter setting :return: - Initialize SCIP parameters for the mode...
class ActivePlan(object): def __init__(self, join_observer_list, on_next, on_completed): self.join_observer_list = join_observer_list self.on_next = on_next self.on_completed = on_completed self.join_observers = {} for join_observer in self.join_observer_list: sel...
""" Datos de entrada Temperatura = t = float Datos de salida Deporte = d = str """ # Entradas t=float(input(" Digite temperatura ")) # Caja Negra deporte= '' if(t>85 and t< 120): deporte= "Natacion " elif(t>70 and t<= 85 ): deporte= "Tenis " elif(t>32 and t<= 70 ): deporte = "Golf " elif(t>10 and t<=...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Title : Lists Subdomain : Basic Data Types Author : Vincent Celis Created : 19 July 2018 https://www.hackerrank.com/challenges/python-lists/problem """ methods = { 'insert': lambda *args: args[0].insert(int(args[1]), int(args[2])), '...
vel = int(input('Qual foi a velocidade do carro? ')) if vel > 80: print('Seu carro estΓ‘ acima da velocidade permitida que Γ© 80km/h!!') multa = (vel - 80) * 7 print('VocΓͺ serΓ‘ multado em R${} reais'.format(multa)) print('Boa viagem!')
COINS = ( (25, 'Quarters'), (10, 'Dimes'), (5, 'Nickels'), (1, 'Pennies') ) def loose_change(cents): change = {'Pennies': 0, 'Nickels': 0, 'Dimes': 0, 'Quarters': 0} cents = int(cents) if cents <= 0: return change for coin_value, coin_name in COINS: q, r = divmod(cents,...
""" time: n^3 space: n """ class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [True] + [False] * len(s) for i in range(1, len(s)+1): for w in wordDict: if s[:i].endswith(w): dp[i] |= dp[i-len(w)] return dp[-1] """ t...
class Alert: def __init__(self, name): self.name = name self.enabled = False def load(self, values): for k, v in values.items(): if str(k).startswith('_') or k == 'name' or k not in vars(self): continue # !cover setattr(self, k, v) # self.__dict__.update(**values) def get_save_obj(self): ret =...
'''input 97 89 20000 25899 10 5 8 10 97 89 8634 17266 97 89 8633 8633 100 100 101 200 1 1 1 1 1 1 20000 20000 100 100 20000 20000 12 8 25 48 2 3 8 12 2 2 2 2 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__...
def count_largest_group(n: int) -> int: hash_ = {} for i in range(1, n + 1): num = i count = 0 while num >= 10: count += num % 10 num //= 10 count += num if count in hash_: hash_[count] += 1 else: has...
code=r"""function whos_f() %Static variables %persistent l %cellFile counter %persistent m %cellFunc counter %persistent cellFile %persistent cellFunc %initialize counter k %if isempty(l) % l = 1; % m = 1; %end %Get info about caller, filename ST = dbstack(); ...
# -*- coding: utf-8 -*- """ pylite ~~~~~~~~~ :copyright: (c) 2014 by Dariush Abbasi. :license: MIT, see LICENSE for more details. """ __version__ = "0.1.0"
"""Answer to Question 3 goes here. Author: Dylan Blanchard, Sloan Anderson, and Stephen Johnson Class: CSI-480-01 Assignment: PA 5 -- Supervised Learning Due Date: Nov 30, 2018 11:59 PM Certification of Authenticity: I certify that this is entirely my own work, except where I have given fully-documented references to...
num = cont = 0 s = 0 num = int(input('Digite um nΓΊmero [999 para PARAR]: ')) while num != 999: s = s + num cont += 1 num = int(input('Digite um nΓΊmero [999 para PARAR]: ')) print(f'VocΓͺ digitou {cont} nΓΊmeros e a soma deles Γ© {s}')