content
stringlengths
7
1.05M
class Calc: """Simple calculator.""" def __init__(self, a, b): self.a = a self.b = b def do(self): """Perform calculation.""" return self.a + self.b
""" É importante estabelecer uma linguagem comum para que todos consigam consumir dados. Essa "linguagem comum" é o que chamamos de API: Application Programming Interface. A organização que disponibiliza os dados estabelece algumas "regrinhas" para fazermos requisições, e em contrapartida ela garante que os recursos f...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- class WikiBase(object): WikiLineSep = '\r\n' def __init__(self, wikiId, client): self.client = client self.wikiPage = client.wiki(wikiId) def writeWikiPage(self, content, mailNotify=False): wikiName = self.wikiPage['name'] para...
# The final segments are shown by calling the property ``t_masked`` which returns the # target data as an ndarray with NaN values for areas not found to be segments. plt.figure(figsize=(15,3)) # doctest: +SKIP plt.plot(s.t_masked.T) # doctest: +SKIP plt.xlabel("time in s") # doctest: +SKIP plt.ylabel("ECG in mV") ...
def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] # python3 #return ["Hello World"] # python2 # uwsgi --http :8000 --wsgi-file test.py # uwsgi --http :8000 --home /home/ubuntu/venv --chdir /home/ubuntu/ShirtGeeks/src/ --module conf.wsgi
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Initialization module for NAAS. Sets version """ __version__ = "0.6.2" __base_response__ = {"app": "naas", "version": __version__}
def count_bags(balls, diff): count = 0 target = diff while balls >= target: print(f"Target {target} Balls {balls}") count += 1 balls -= target target += diff return count if __name__ == '__main__': bags, balls, diff = map(int, input().split()) print(bags - co...
class AddrStats: """A simple class detailing stats on the read addresses ... Keeps track of address info AND writes to the results file specified, no parsing in this class""" # Constructor def __init__(self, resultsFile='results.txt', hasOffset=True, debug=False, debugAll=False): ...
""" Copyright 2021 DataDistillr Inc. 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...
class TestReportAxis: def __init__(self, stat, label, unit): self.stat = stat self.label = label self.unit = unit class TestReport: def __init__(self, x_axis, y_axis): self.x_axis = x_axis self.y_axis = y_axis class TestCase: def __init__(self, i...
#Delegar acesso a atributos class A: def fazer_algo(self): pass def outro_metodo(self): pass def algum_metodo(self, nome): print(nome) class B: def __init__(self): self.a = A() # Instancia da classe A def fazer_algo(self): #delega para self.a ...
""" Copyright 2020 Andrew Brown (aka SherpDaWerp) 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 appl...
# https://www.codewars.com/kata/54ff3102c1bad923760001f3/train/python def get_count(input_str): num_vowels = 0 list_vowels=["a","e","i","o","u"] for i in range(len(input_str)): if input_str[i] in list_vowels: num_vowels+=1 i+=1 return num_vowels #sentence=input("Sentence: ") #print(get...
year2010 = [["Wonder Girls", "2 Different Tears"], ["miss A", "Bad Girl Good Girl"], ["소녀시대_(Girls%27_Generation)", "Run Devil Run"], ["f(x)", "Nu_예삐오_(Nu_Abo)"]] year2011 = [["G.NA", "Black&White"], ["Miss A", "Good-bye Baby"], ["Big Bang", "Love Song"], ["Wonder Girls", "Be My Baby"], ["소녀시대_(Girls%27_Generatio...
"""Total brought This program totals everything being brought to a picnic by storing the guest's names and items brought as a :obj:`dict` of :obj:`dicts <dict>`. Attributes: allGuests (dict): Dictionary of dictionaries with guest names as keys and values of dictionaries with items as keys and number of it...
class CheckException(Exception): def __init__(self, message, exceptions=[]): super(Exception, self).__init__(message) self.errors = exceptions class ParamMissingException(CheckException): type = 'config-param-missing' class NonExistentRuntimeVariableException(CheckException): type = 'c...
""" Moonstream library and API version. """ MOONSTREAM_VERSION = "0.0.1"
def print_paper(_paper): for i in range(max([*zip(*_paper)][0]) + 1): for j in range(max([*zip(*_paper)][1]) + 1): print( '█' if (i, j) in _paper else ' ', end="" ) print() def fold_paper(paper, folds): for step, fold in enumerate(folds): fold_idx = int(fold.split('=')[-1]) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- rabbitmq = {} runs = []
def sum_two_nums(num1, num2): return num1 + num2 number1 = int(input('Enter first num: ')) number2 = int(input('Enter second num: ')) result = sum_two_nums(number1, number2) print(f'{number1} + {number2} = {result}')
#!/usr/bin/env python3 # Write a program that prints out the position, frame, and letter of the DNA # Try coding this with a single loop # Try coding this with nested loops s = 'ATGGCCTTT' x = 0 print('Nested Loop:') for i in range (0, len(s), 3): for j in range (0,3): print (x, j, s[x]) x += 1 pr...
s,n=map(int,input().split()) a=[] for _ in range(n): a.append(list(map(int,input().split()))) b=sorted(a) for x,y in b: if s<=x: print('NO') break else: s+=y else: print('YES')
################################################################# # # # Solution to find the maximum sum of elements in whole # # hourglass shapes of an two dimensional array # # ...
class Solution(object): def minMeetingRooms(self, intervals): """ :type intervals: List[Interval] :rtype: int """ meetings = [] for i in intervals: meetings.append((i.start, 1)) meetings.append((i.end, 0)) meetings.sort() ...
class Solution(object): def findMaxLength(self, nums): dic = {0: -1} count = 0 maxlen = 0 for x in range(0, len(nums)): count += (1 if nums[x] == 1 else - 1) if count not in dic: dic[count] = x else: maxlen = max(max...
class PredictionsHandler: def __init__(self): pass def get_prediction(self, current_value): pass
USER_TYPES = [ ('admin', 'Admin'), ('buyer', 'Buyer'), ('seller', 'Seller'), ]
"""Job Class """ class Job(object): def __init__(self, salary=50000, salary_growth_rate=0.01, savings_rate=0.05): self.salary = salary self.salary_growth_rate = salary_growth_rate self.savings_rate = savings_rate def to_dict(self): return { 'salary': self.salary,...
class BadInputError(Exception): pass class InvalidComponentError(Exception): pass class InvalidEngineError(Exception): pass
def clef(inst): clef='treble' if inst=='flute': clef='treble' elif inst=='alto_flute': clef='treble' elif inst=='baritone_generic': clef='bass' elif inst=='bassoon': clef='bass' elif inst=='bass_cl': clef='bass' elif inst=='bass_drum': clef='tr...
def solution(arrangement: str) -> int: arrangement = arrangement.replace('()', '0') uncut = 0 cutted = 0 for element in arrangement: if element == '(': # 새로운 쇠막대가 놓여 있냐? uncut += 1 cutted += 1 elif element == '0': # 레이저 포인터 지졈이냐? cutted += uncut ...
#Program to check if given string is palindrome or not. string=input(("Enter your string:")) if(string==string[::-1]): print("The string is a palindrome") else: print("The string is not a palindrome")
# # PySNMP MIB module CTRON-FRONTPANEL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-FRONTPANEL-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:44:24 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
# Space: O(n) # Time: O(n) # DFS approach # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root, sum): def dfs(root, target): ...
"""Collection of benchmarks and downstream tasks on embeddings .. autosummary:: :toctree: _autosummary analogy """
FETCH_ALL_DEVICE_STATUS = "5" FETCH_SINGLE_DEVICE_STATUS = "4" GET_ALL_DEVICE_DESCRIPTION = "1" BROADCAST_ALL_DEVICE = "9" BROADCAST_SINGLE_DEVICE = "8" EOF = "_;" DELIMITER = "," SPACE = " " LIST_OF_KEYS = ["message", "device_id", "device_name", "device_type", "device_status"] SUCCESS_MESSSAGE = "success" FAILURE_ME...
hrs = input("Enter Hours:") h = float(hrs) rph = input("enter rate per hour:") r = float(rph) if h <= 40: result = h * r else: o = h - 40 result = o * (r * 1.50) + 40 * r print(result) # desired output # 498.75
''' Дублирование фрагмента ''' inp_str = input() f = -1 l = -1 f = inp_str.find('h') l = inp_str[::-1].find('h') l = len(inp_str) - l - 1 print(inp_str[0:f + 1], inp_str[f + 1:l] * 2, inp_str[l:], sep='')
class Solution: def isOneBitCharacter(self, bits: List[int]) -> bool: visited = False i = 0 while i<len(bits): if bits[i] ==0: if i==len(bits)-1: return True i+=1 else:...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def sum_node(self, node, low, high): if node.val >= low and node.val <= high: ...
# configure me config = { 'pytan_dir': '/Users/jolsen/gh/pytan/lib', 'tanium_username': 'Tanium User', 'tanium_password': 'T@n!um', 'tanium_host': '172.16.31.128', 'max_data_age': 60, 'pct_complete_threshold': 98.00, 'sync_scan_name': 'Run Patch Scan Synchronously', 'sync_scan_opts': { ...
# # PySNMP MIB module Inverter-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Inverter-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:47:27 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,...
class BaseValidator: """ Base class for all the validators """ def __init__(self): pass @staticmethod def eq(first, second): return first == second @staticmethod def neq(first, second): return first != second @staticmethod def lt(first, second): ...
def max(param_list, meta): ret = None if (not len(param_list)): return None items = param_list[0].obj_list() if (not len(items)): return None max_val = items[0].anchor_value() ret = items[0] for i in items: if(i.anchor_value() > max_val): ret = i ...
# # PySNMP MIB module ONEACCESS-VOICE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-VOICE-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:34:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
set_name(0x80079688, "GetTpY__FUs", SN_NOWARN) set_name(0x800796A4, "GetTpX__FUs", SN_NOWARN) set_name(0x800796B0, "Remove96__Fv", SN_NOWARN) set_name(0x800796E8, "AppMain", SN_NOWARN) set_name(0x80079788, "MAIN_RestartGameTask__Fv", SN_NOWARN) set_name(0x800797B4, "GameTask__FP4TASK", SN_NOWARN) set_name(0x8007989C, "...
""" Laventine distance Given two string how many operation like addition, substraction and substitution required to change one word to other word. solving using dynamic problems """ def calcLaventenstineDistance(str1, str2, m, n): """ Calculate the Laventenstine Distance of between two strings """...
class BaseException(Exception): """ Sub-class this with your custom exceptions. """ def __init__(self, message, *args): """ :param str message: The message to show in the exception's string representation. """ Exception.__init__(self, message, *args) #...
if __name__ == "__main__": t = int(input()) while t>0: lst = [] lst_sorted = [] m = int(input()) lst = list(input().split()) for i in range(m): lst[i] = int(lst[i]) lst_sorted = lst.copy() lst_sorted.sort(reverse = True) count = 0 for i in range(m): if lst[i] == lst_sorted[i]: cou...
""" https://leetcode.com/problems/reverse-integer/ Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit sig...
#encoding:utf-8 subreddit = 'completeanarchy' t_channel = '@completeanarchy_tg' def send_post(submission, r2t): return r2t.send_simple(submission)
class Solution: def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ for i in range(0, len(board)): if not board: return False for j in range(0, len(board[0])): ...
class Solution: def groupAnagrams(self, strs: 'List[str]') -> 'List[List[str]]': dict, result, n = {}, [], 0 for item in strs: standard = tuple(sorted(item)) idx = dict.get(standard) if idx is None: dict[standard] = n result.append(...
Months = set(["January","February", "March", "April", "May", "June"]) print("printing the original set ... ") print(Months) print("Removing some months from the set..."); Months.discard("January"); Months.discard("aaa"); print("Printing the modified set..."); print(Months) print("looping through the set elements ....
''' A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary ...
# -*- coding: utf-8 -*- """ @author: krakowiakpawel9@gmail.com @site: e-smartdata.org """ raw_data = '345!23!3234!43434' clean_data = '' for char in raw_data: if char != '!': clean_data += char else: clean_data += ',' print(clean_data) # %% suma = 0 for i in range(10): suma += i print(su...
def run() -> int: last_factor, current = 1, 2 target = 600851475143 while target > 1: if target % current == 0: target //= current last_factor, current = current, 2 else: current += 1 if current == 2 else 2 return last_factor if __name__ == '__main__...
# # @lc app=leetcode id=1431 lang=python3 # # [1431] Kids With the Greatest Number of Candies # # @lc code=start class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: return list(map(lambda c: max(candies) <= c+extraCandies, candies)) # @lc code=end
class FlatData(object): def __init__(self, data, order=None): self.data = data self.columns = [] self.table = {} self.headers = [] self.rows = [] self.order = order self.flatten_data() def flatten_data(self): row_count = 0 if isinstance(...
class ListNode: def __init__(self,x): self.value = x self.next = None class Solution: def deleteDuplicates(self,head): # type head: Linked Node # rtype: ListNode slow = head if slow == None: return head fast = head.next while(fast != N...
# -*- coding: utf-8 -*- def main(): n, m, k, e = map(int, input().split()) a = sorted(list(map(int, input().split()))) b = [e] + sorted(list(map(int, input().split())), reverse=True) sum_a = sum(a) sum_b = sum(b[:k + 1]) count = 0 total = 0 if sum_b >= sum_a: prin...
# -*- coding: utf-8 -*- { 'name' : 'tareassos', 'summary' : 'Módulo realizado por SOS, SGE 18-19', 'version' : '1.0', 'licence' : 'AGPL-3', 'website' : 'https://www.orantes.com', 'category' : 'Tools', 'author' : 'Sebastián Orantes Solera', 'description' : 'Con este módulo administraremos tareas', ...
FORM = '[To:1528718] Dinh Tungさん\n\ [To:2047081] Hoang Van Cuongさん\n\ [To:1719660] Nguyen Thanh Luan (▰˘◡˘▰)さん\n\ [info][title]【Memvo_Lab】I would like to send daily report({date})[/title]\n\ ● 1. Today plan:\n\ {plan}\ \n\ ● 2. Actual archivement:\n\ {actually}\ \n\ ● 3. Issues:\n\ - Nothing\n\ \n\ ● 4. Lines of code: ...
load("@io_bazel_rules_scala//scala:scala.bzl", uppstream_lib = "scala_library", uppstream_macro = "scala_macro_library", uppstream_bin = "scala_binary", uppstream_test = "scala_test", uppstream_scala_library_suite = "scala_library_suite") _default_scalac_opts = [ "-Ywarn-dead-code", "-...
# # PySNMP MIB module Unisphere-Data-ISIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-ISIS-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:31:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
"""Token representation.""" INTEGER = 'INTEGER' REAL = 'REAL' INTEGER_CONST = 'INTEGER_CONST' REAL_CONST = 'REAL_CONST' PLUS = 'PLUS' MINUS = 'MINUS' MUL = 'MUL' INTEGER_DIV = 'INTEGER_DIV' FLOAT_DIV = 'FLOAT_DIV' LPAREN = 'LPAREN' RPAREN = 'RPAREN' ID = 'ID' ASSIGN = 'ASSIGN' BEGIN = 'BEGIN' END = 'END' SEMI = 'SEMI'...
Time = float TimeInterval = float StepCount = int def repr_time(time: Time) -> str: return '{:.2e}'.format(time)
class DecisionTree: """ :brief: This class is the implementation of the Decision Tree CART algorithm. """ headers = [] def __init__(self, max_depth=float('inf'), min_samples_split=2, min_samples_leaf=1): """ :brief: Trivial constructor. :param max_depth: is the ...
_base_ = "./ss_mlBCE_MaskFull_PredDouble_PBR05_woCenter_woDepth_edgeLower_refinePM10_01_02MasterChefCan.py" OUTPUT_DIR = ( "output/self6dpp/ssYCBV/ss_mlBCE_MaskFull_PredDouble_PBR05_woCenter_woDepth_edgeLower_refinePM10/09_10PottedMeatCan" ) DATASETS = dict( TRAIN=("ycbv_010_potted_meat_can_train_real_aligned_K...
# # PySNMP MIB module CONTROL-SUNMANAGEMENTCENTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CONTROL-SUNMANAGEMENTCENTER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:11:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
# Logic to Select the Block that has Crime News def is_crime_news(tag): # Find All the Div's with section-title as class blocks = tag.findAll('div', {'class': 'section-title'}) if blocks: for block in blocks: # check if the Block is a Crime News Block return block and block...
## fonctionnemnet de la fonction: ## fonction qui prend un hash et un score et le range dans matching score ## parametre d'entree: ## hash: hash dont on a calcule le score ## score: score de mathcing du hash ## matching score: [[hash1, score1],[hash2, score2],[hash3, score3]] ## retour fonction:: ## nouveau triplet d...
# a predicate returns True or False and can raise ReductionDone to halt processing class ReductionDone(Exception): pass def reduce_list(list_to_reduce, predicate): reduced = [] for item in list_to_reduce: try: if predicate(item): reduced.append(item) except Re...
#!/usr/bin/env python # -*- coding: utf-8 -*- def check_setup(bboxes, setup): valid_setup = True computed_setup = {} valid_boxes = {} for item, item_nb in setup.items(): if bboxes[0][item] is None: valid_setup = False else: if bboxes[0][item].ndim == 2: ...
# -*- coding: utf-8 -*- """ Some functions to handle data intended to be plotted through matplotlib """ __title__ = "filefunctions" __author__ = "Juliano Fischer Naves" __license__ = "Apache License 2.0" #date: Dec., 11, 2016 def extract_lines(myfile): """Returns the lines of a space separated file as a ...
## Count the Monkeys! ## 8 kyu ## https://www.codewars.com//kata/56f69d9f9400f508fb000ba7 def monkey_count(n): return list(range(1,n+1))
""" [C] [u] [r] [s] [o] [ ] [e] [m] [ ] [V] [í ] [d ] [e ] [o ] [ ] [P ] [y ] [t ] [h ] [o ] [n ] [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] NOTA: Para o Python, por exemplo, "V" maiúsculo é diferente de "v" minúsculo. Exemplos de Estruturas de Fatiamento: variavel...
class Cuboid:#the Cuboid is the name of the class name = "Cuboid" #class attribute def __init__(self,lenght,breath,height,weight):#here we have given parameters which is l,b,h,w self.length = lenght self.breath = breath self.height = height self.weight = weight # Adding up a method, which is volume to cal...
def removeLetter(word, letter): return word.replace(letter, "") print(removeLetter("ban", "a"))
#################################################################################################### ########################################### vtools.vimg ############################################ ############################################ config.py ############################################# #################...
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: # Normal Solution # if len(set(nums))==len(nums): # <--- Just comparing the number of element present in the list vs its set # return False # else: # return True #Using ...
""" Author: Resul Emre AYGAN """ """ Project Description: Vowel Count Return the number (count) of vowels in the given string. We will consider a, e, i, o, u as vowels for this Kata (but not y). The input string will only consist of lower case letters and/or spaces. """ def get_count(input_str): return sum(ma...
# Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See L...
i=0 lista=[] soma=0 print ("Digite 4 números: ") while len(lista) < 4: item = (int(input())) lista.append(item) for i in lista: soma+=i soma / 4 print("A soma dos Números é:", soma) if soma > 1: print ("O número é positivo") else: print ("O número é negativo")
def group_services(feed, distinct_by_pattern=False): service_groups = get_groupable_services(feed, distinct_by_pattern) to_replace = {} for master, children in service_groups.items(): for child in children: to_replace.update({child: master}) # Replace in feed feed.trips['service_...
r, n = map(int, input().split()) l = [] found = False for i in range(n): l.append(int(input())) for i in range(1, r+1): if i not in l: print(i) found = True break if not found: print("too late")
#Implementation of the Sieve of Eratosthenes for enumerating all of the primes less than some integer n. Also includes a minor variant of it, #written for a Project Euler problem, which sums up the primes below n instead of returning a list of them. def primeSieve(n): boolList = [True] * (n + 1); primeList = []...
def Get_model(num_medical_conditions, num_drugs, layers=[16, 8], reg_layers=[0, 0]): assert len(layers) == len(reg_layers) num_layer = len(layers) # Number of layers in the MLP medical_condition_input = Input( shape=(1,), dtype='int32', name='user_input') drug_input = Input(shape=(1,), dty...
class MusicalKeyboard: def __init__(self, brand, model, color, keys): self.brand = brand.upper() self.model = model.upper() self.color = color.capitalize() self.keys = keys def display_brand(self): return self.brand def display_model(self): return self.mode...
# Time: O(n) # Space: O(h) # We want to use quad trees to store an N x N boolean grid. # Each cell in the grid can only be true or false. # The root node represents the whole grid. For each node, # it will be subdivided into four children nodes until the values # in the region it represents are all the same. # # Each...
SSID1 = 'WiFi1' SALASANA1 = 'Salari1' SSID2 = 'WiFi2' SALASANA2 = 'Salari2' MQTT_SERVERI = 'ip' MQTT_PORTTI = '1883' MQTT_KAYTTAJA = 'useri' MQTT_SALASANA = 'salari' CLIENT_ID = "ESP32-etelaPIR1" DHCP_NIMI = "ESP32-etelaPIR" PIR_PINNI = 22 PIR_LIIKE_NOLLAUSAIKA = 5 AIHE_LIIKETUNNISTIN = 'koti/ulko/etela/pir...
''' Now You Code 3: Shopping Cart In this program you will implement an online shopping cart using a Python list of dictionary. The program should start by allowing the user to enter: - Product name - Product price - Product quantity until the user enters a product name of 'checkout' after checkout the program s...
''' Title : Introduction to Sets Subdomain : Sets Domain : Python Author : codeperfectplus Created : 17 January 2020 ''' def average(array): # your code goes here array = set(array) return sum(array)/len(array) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().spli...
# python + maths are wonderful for j in range(int(input())): n = int(input()) ans = ((((2 * n + 3) * (n + 2) * (n + 1) // 6)) - (((2 + n + 1) // 2) * (n // 2 + 1)) * 2 + (n // 2 + 1)) * 2 - ((2 + n - 1) // 2) * (n // 2) * 6 - 3 print(ans % (10 ** 9 + 7))
class MangaListResult(list): def __init__(self, data) -> None: super().__init__(data.get('data')) self._limit = data.get('limit') self._offset = data.get('offset') self._total = data.get('total')
#!/usr/bin/env python3 def part1(): checksum = 0 with open('day02input.txt') as f: for line in f: line = line.split() l = list(map(int, line)) checksum += max(l) - min(l) print(checksum) def part2(): checksum = 0 with open('day02input.txt') as f: ...
#! /usr/bin/env python3 # # Scrabble Game # Author: Chris Lyon # Contact: chris@cplyon.ca class Tile: def __init__(self, letter, score): self.letter = letter self.score = score def __str__(self): return f"({self.letter},{self.score})"
""" Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example 1: Input: s = "aab", Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. Example 2: Input: s = "a", Output...
""" Das Program so, dass den User nach seinem Namen fragt und ihn mit diesem Namen begrüßt. """ name = input("Was heißen Sie?: ") print("Hallo ", name)
class MyLightCycleBot(LightCycleBaseBot): def get_next_step(self, arena, x, y): # Should return north, south, east or west return