content
stringlengths
7
1.05M
#program to find the position of the second occurrence of a given string in another given string. def find_string(txt, str1): return txt.find(str1, txt.find(str1)+1) print(find_string("The quick brown fox jumps over the lazy dog", "the")) print(find_string("the quick brown fox jumps over the lazy dog", "the"))
lines = [] header = "| " for multiplikator in range(1,11): line = "|" + f"{multiplikator}".rjust(3) header += "|" + f"{multiplikator}".rjust(3) for multiplikand in range(1,11): line += "|" + f"{multiplikator * multiplikand}".rjust(3) lines.append("|---" + "+---"*10 + "|") lines.append(lin...
def foo(a, b): return a + b print("%d" % 10, end='')
def test_training(): pass
""" [2017-05-18] Challenge #315 [Intermediate] Game of life that has a twist https://www.reddit.com/r/dailyprogrammer/comments/6bumxo/20170518_challenge_315_intermediate_game_of_life/ So for the first part of the description I am borrowing /u/Elite6809 challenge of a while ago [link](https://www.reddit.com/r/dailypro...
files = "newsequence.txt" write = "compress.txt" reverse = "reversed.txt" seq = dict() global key_max #Stores the sequence in a dictionary def store_seq(key, value): if key not in seq: seq.update({key:value}) #breaks each line down into sequences and counts the number of occurence of each sequence def c...
man = 1 wives = man * 7 madai = wives * 7 cats = madai * 7 kitties = cats * 7 total = man + wives + madai + cats + kitties print(total)
ES_HOST = 'localhost:9200' ES_INDEX = 'pending-gwascatalog' ES_DOC_TYPE = 'variant' API_PREFIX = 'gwascatalog' API_VERSION = ''
def sumall(upto): sumupto = 0 for i in range(1, upto + 1): sumupto = sumupto + i return sumupto print("The sum of the values from 1 to 50 inclusive is: ", sumall(50)) print("The sum of the values from 1 to 5 inclusive is: ", sumall(5)) print("The sum of the values from 1 to 10 inclusive is: ", s...
class BatchClassifier: # Implement methods of this class to use it in main.py def train(self, filenames, image_classes): ''' Train the classifier. :param filenames: the list of filenames to be used for training :type filenames: [str] :param image_classes: a mapping of...
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # # (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # # Find the minimum element. # # You may assume no duplicate exists in the array. # # Example 1: # # Input: [3,4,5,1,2] # Output: 1 # Example 2: # # Input: [4,5,6...
carros = ["audi", "bmw", "ferrari","honda"] for carro in carros: if carro == "bmw": print(carro.upper()) else: print(carro.title())
setup( name="earthinversion", version="1.0.0", description="Go to earthinversion blog", long_description=README, long_description_content_type="text/markdown", url="https://github.com/earthinversion/", author="Utpal Kumar", author_email="office@earthinversion.com", license="MIT", ...
API_LOGIN = "/users/sign_in" API_DEVICE_RELATIONS = "/device_relations" API_SYSTEMS = "/systems" API_ZONES = "/zones" API_EVENTS = "/events" # 2020-04-18: extracted from https://airzonecloud.com/assets/application-506494af86e686bf472b872d02048b42.js MODES_CONVERTER = { "0": {"name": "stop", "description": "Stop"}...
''' The MADLIBS QUIZ Use string concatenation (putting strings together) Ex: I ama traveling to ____ using ___ and its carrying ____ passegers for ____ kilometers Thank you for watching ________ channel please ________ ''' youtube_channel = "" print("thank you for watching " + youtube_channel + "Channel ") prin...
# PEMDAS is followed for calculations. # Exponentiation print("2^2 = " + str(2 ** 2)) # Division always returns a float print ("1 / 2 = " + str(1 / 2)) # For integer division, use double forward-slashes print ("1 // 2 = " + str(1 // 2)) # Modulo is like division except it returns the remainder print ("10 % 3 = " + ...
""" Demonstrates a try...except statement """ #Prompts the user to enter a number. line = input("Enter a number: ") try: #Converts the input to an int. number = int(line) #Prints the number the user entered. print(number) except ValueError: #This statement will execute if the input could not be #convert...
#!/usr/bin/env python3 # Write a program that compares two files of names to find: # Names unique to file 1 # Names unique to file 2 # Names shared in both files """ python3 checklist.py --file1 --file2 """
class Solution: def fib(self, n: int) -> int: prev, cur = 0, 1 if n == 0: return prev if n == 1: return cur for i in range(n): prev, cur = cur, prev + cur return prev
""" django-faktura Homepage: https://github.com/ricco386/django-faktura See the LICENSE file for copying permission. """ __version__ = "0.1" __author__ = "Richard Kellner" default_app_config = "faktura.apps.FakturaConfig"
def test_countries_and_timezones(app_adm): app_adm.home_page.open_countries() country_page = app_adm.country_page countries_list = country_page.get_countries() sorted_countries = sorted(countries_list) for country in range(len(countries_list)): assert countries_list[country] == sorted_countr...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.node_count = 0 def __str__(self): curr = self.head temp = [] while curr is not None: temp.append(str(curr....
class HowLongToBeatEntry: def __init__(self,detailId,gameName,description,playableOn,imageUrl,timeLabels,gameplayMain,gameplayMainExtra,gameplayCompletionist): self.detailId = detailId self.gameName = gameName self.description = description self.playableOn = playableOn self.i...
''' You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place? ''' class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify m...
class MyDeque: def __init__(self, max_size): self.max_size = max_size self.items = [None] * self.max_size self.size = 0 self.head = 0 self.tail = 0 def push_back(self, value): if self.size == self.max_size: raise IndexError('error') self.item...
""" Collection of miscellaneous functions and utilities for admin tasks. """ __version__ = '0.1.0dev2'
def findadjacent(y,x): global horizontal global vertical global map countlocal=0 for richtingy in range(-1,2): for richtingx in range(-1,2): if richtingx!=0 or richtingy!=0: offsetcounter=0 found=0 while found==0: ...
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() ans=[] st=set() for i in range(0,len(nums)-2): for j in range(i+1,len(nums)-2): l=j+1 r=len(nums)-1 while(l<r): ...
Alonso_Position=1 if (Alonso_Position==1): print("Espectacular Alonso, se ha hecho justicia a pesar del coche") print("Ya queda menos para ganar el mundal") elif (Alonso_Position>1): print("Gran carrera de Alonso, lástima que el coche no esté a la altura") else: print("No ha podido terminar la carrera p...
n = int(input("Please enter a positive integer : ")) print(n) while n != 1: n = n // 2 if n % 2 == 0 else 3*n + 1 print(n)
class A : pass class B(A): pass print(issubclass(B,A)) print(issubclass(A,object)) # issubclass(b,a)判断a是不是b的子类 # 所有的类都是object类的子类 # isinstance (b,B)判断是不是该类的实例化对象,第二个元素可以是一个元组 class C: def __init__(self,x,y): self.x=x self.y=y b=B() print(isinstance(b,B)) print(isinstance(b,C)) print(isinstance(b,(A,B,C)...
print('Vamos analisar 3 números para saber qual será o menor e o maior deles. ') numero = float(input('Informe o primeiro número: ')) maior = numero menor = numero numero = float(input('Informe o segundo número: ')) if numero > maior: maior = numero else: menor = numero numero = float(input('Informe o terceiro ...
def hip(a, b, c): if b < a > c and a ** 2 == b ** 2 + c ** 2: return True elif a < b > c and b ** 2 == a ** 2 + c ** 2: return True elif a < c > b and c ** 2 == a ** 2 + b ** 2: return True else: return False e = str(input()).split() a = int(e[0]) b = int(e[1]) c = int(e[2]) if(a < b + c and b < a + c...
class CNF: def __init__(self, n_variables, clauses, occur_list, comments): self.n_variables = n_variables self.clauses = clauses self.occur_list = occur_list self.comments = comments def __str__(self): return f"""Number of variables: {self.n_variables} Clauses: {str(self...
# 1573. Алхимия # solved # reagents amount reagents_amount = input().split(' ') # blue b = int(reagents_amount[0]) # red r = int(reagents_amount[1]) # yellow y = int(reagents_amount[2]) # recipe k = int(input()) result = 1 for i in range(k): color = input() if color == 'Blue': result *= b if co...
#!/usr/bin/env python3 def left_join(phrases): return ','.join(phrases).replace("right", "left") if __name__ == '__main__': print(left_join(["right", "right", "left", "left", "forward"])) assert left_join(["right", "right", "left", "left", "forward"]) == "left,left,left,left,forward" assert left_join(...
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author: Lu Chong @file: __init__.py @time: 2021/8/17/11:38 """
DATABASE_NAME = "lzhaoDemoDB" TABLE_NAME = "MarketPriceGTest" HT_TTL_HOURS = 24 CT_TTL_DAYS = 7 ONE_GB_IN_BYTES = 1073741824
# -*- encoding=utf-8 -*- """ # ********************************************************************************** # Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. # [openeuler-jenkins] is licensed under the Mulan PSL v1. # You can use this software according to the terms and conditions of t...
class Solution: def recursion(self,idx,arr,n,maxx,size,k): if idx == n: return maxx * size if (idx,size,maxx) in self.dp: return self.dp[(idx,size,maxx)] ch1 = self.recursion(idx+1,arr,n,max(maxx,arr[idx]),size+1,k) if size < k else 0 ch2 = self.recursion(idx+1,arr,n,ar...
class Action: def do(self) -> None: raise NotImplementedError def undo(self) -> None: raise NotImplementedError def redo(self) -> None: raise NotImplementedError
# ------------------------------------------------------------------------------- # Name: palindromes # # Author: mourad mourafiq # ------------------------------------------------------------------------------- def longest_subpalindrome(string): """ Returns the longest subpalindrome string from ...
# 这是一段空代码,仅创建一个循环并输出log log("接下来将输出3次”Hello Love!“") for k in range (3): log("Hello Love!") wait(800)
""" Description: Provides ESPA specific exceptions to the processing code. License: NASA Open Source Agreement 1.3 """ class ESPAException(Exception): """Provides an ESPA specific exception specifically for ESPA processing""" pass
# # PySNMP MIB module INCOGNITO-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INCOGNITO-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:42:01 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...
def arraySumAdjacentDifference(inputArray): answer = 0 for i in range(1, len(inputArray)): answer += abs(inputArray[i] - inputArray[i-1]) return answer ''' Given array of integers, find the sum of absolute differences of consecutive numbers. Example For inputArray = [4, 7, 1, 2], the output shoul...
""" Events are called by the :class:`libres.db.scheduler.Scheduler` whenever something interesting occurs. The implementation is very simple: To add an event:: from libres.modules import events def on_allocations_added(context_name, allocations): pass events.on_allocations_added.append(on_alloc...
#list example for insertion order and the dupicates l1 = [] print(type(l1)) l1.append(1) l1.append(2) l1.append(3) l1.append(4) l1.append(1) print(l1)
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython En una estación de servicio se conoce la cantidad de nafta común y super vendida en el corriente mes. El usuario deberá ingresar las ventas totales de cada tipo de nafta por cada día del mes. Al finalizar debe informar la venta total del mes y el porcentaje...
class Shodan: """Get any Shodan information """ def __init__(self): # TODO: move key to config self.api_key = 'yKIZ2L54cQxIfnebD4V2qgPp0QQsJLpK' # TODO: add shodan api def request(self): pass
def maximum_subarray_sum(lst): '''Finds the maximum sum of all subarrays in lst in O(n) time and O(1) additional space. >>> maximum_subarray_sum([34, -50, 42, 14, -5, 86]) 137 >>> maximum_subarray_sum([-5, -1, -8, -101]) 0 ''' current_sum = 0 maximum_sum = 0 for value in lst: ...
""" * Use an input_boolean to change between views, showing or hidding groups. * Check some groups with a connectivity binary_sensor to hide offline devices. """ # Groups visibility (expert_view group / normal view group): GROUPS_EXPERT_MODE = { 'group.salon': 'group.salon_simple', 'group.estudio_rpi2h': 'gro...
''' 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树 A: 3 / \ 4 5 / \ 1 2 给定的树 B: 4 / 1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true 限制: 0 <= 节点个数 <= 10000 ''' # Definition for a binary...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Ce module permet d'obtenir la liste des pays valides, a partir d'un fichier donnee. """ __auteur__ = "Thefuture2092" def obtenirListePays(langue): """ cette fonction prend un argument langue et retourne la liste de pays dans cette langue. ...
""" Lab 8 """ #3.1 demo='hello world!' def cal_words(input_str): return len(input_str.split()) #3.2 demo_str='Hello world!' print(cal_words(demo_str)) #3.3 def find_min(inpu_list): min_item = inpu_list[0] for num in inpu_list: if type(num) is not str: if min_item >= num: ...
# Alternative solution using compound conditional statement in_class_test = int(input('Please enter your mark for the In Class Test: ')) exam_mark = int(input('Please input your mark for the exam: ')) coursework_mark = int(input('Please enter your mark for Component B: ')) # Calculating mark by adding the marks toget...
class SarlaccPlugin: def __init__(self, logger, store): """Init method for SarlaccPlugin. Args: logger -- sarlacc logger object. store -- sarlacc store object. """ self.logger = logger self.store = store def run(self): """Runs the plugi...
#%% """ - Reverse Nodes in k-group - https://leetcode.com/problems/reverse-nodes-in-k-group/ - Hard Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a mult...
def leiaint(txt): while True: try: num = int(input(txt)) except (ValueError, TypeError): print('\033[31mERRO. Digite um número inteiro válido.\033[m') continue else: return num
# Implementation of a singly linked list data structure # By: Jacob Rockland # node class for linked list class Node(object): def __init__(self, data): self.data = data self.next = None # implementation of singly linked list class SinglyLinkedList(object): # initializes linked list def ...
def print_formatted(number): width = len("{0:b}".format(number)) for num in range(1, number+1): print("{0:{w}}\t{0:{w}o}\t{0:{w}X}\t{0:{w}b}".format(num, w=width)) if __name__ == '__main__': n = int(input()) print_formatted(n)
####################################################### # Author: Mwiza Simbeye # # Institution: African Leadership University Rwanda # # Program: Playing Card Sorting Algorithm # ####################################################### cards = [9, 10, 'J', 'K', 'Q', 'Q', 4, ...
# Copyright: 2005-2008 Brian Harring <ferringb@gmail.com> # License: GPL2/BSD """ repository subsystem """
def create_image_annotation(file_name, width, height, image_id): # file_name = file_name.split('/')[-1] # ~~~.jpg가 file_name이 되도록 문자열 split images = { 'file_name': file_name[2:], 'height': height, 'width': width, 'id': image_id } return images def create_annotation_yolo_...
def DPLL(B, I): if len(B) == 0: return True, I for i in B: if len(i) == 0: return False, [] x = B[0][0] if x[0] != '!': x = '!' + x Bp = [[j for j in i if j != x] for i in B if not(x[1:] in i)] Ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': '...
#multiplicar a nota pelo peso, depois divide a soma das notas pela soma dos pesos nota1=float(input())*2 nota2=float(input())*3 nota3=float(input())*5 media=float((nota1+nota2+nota3))/10 print("MEDIA =","%.1f"%media)
VALUES_CONSTANT = "values" PREVIOUS_NODE_CONSTANT = "previous_vertex" START_NODE = "A" END_NODE = "F" # GRAPH IS 1A graph = { "A": { "B" : 5, "C" : 2 }, "B": { "E" : 4 , "D": 2 , }, "C" : { "B" : 8, "D" : 7 }, "E" : { "F" : 3 , "D" : 6 }, "D" : { "F" : ...
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the...
sal = float(input('Qual o seu salario? ')) if sal > 1250.00: print('Com o aumento seu salario sera R${:.2f}'.format(sal + (sal / 100) * 10)) else: print('Com o aumento seu salario sera R${:.2f}'.format(sal + (sal / 100) * 15))
""" Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Note: You may assume that the string is well-formed: String is non-empty. String does not contain white spaces. String...
class QuizQuestion: def __init__(self, text, answer): self.text = text self.answer = answer @property def text(self): return self.__text @text.setter def text(self, text): self.__text = text @property def answer(self): return self.__answer ...
class Model: def __init__(self): self._classes = {} self._relations = {} self._generalizations = {} self._associationLinks = {} def addClass(self, _class): self._classes[_class.uid()] = _class def classByUid(self, uid): return self._classes[uid]...
''' 08 - Finding ambiguous datetimes At the end of lesson 2, we saw something anomalous in our bike trip duration data. Let's see if we can identify what the problem might be. The data is loaded as onebike_datetimes, and tz has already been imported from dateutil. Instructions - Loop over the trips in onebike_date...
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/openBrand_detection.py', '../_base_/default_runtime.py' ] data = dict( samples_per_gpu=4, workers_per_gpu=2, ) # model settings model = dict( neck=[ dict( type='FPN', in_channels=[256, 512...
''' Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. ''' class Node: # Constructor to create a new Node def __init__(self, data): self.data = data ...
# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. inas = [('ina219', '0x40', 'pp1050_s', 1.05, 0.010, 'rem', True), ('ina219', '0x41', 'pp1800_a', 1.80, 0.010, 'rem', True), ('ina219'...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. load("//antlir/bzl:shape.bzl", "shape") conf_t = shape.shape( nameservers = shape.list(str), search_domains = shape.list(str), )
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, self.next) class Solution: def deleteDuplicates(self, head): """ :type head: ListNod...
# Sudoku problem solved using backtracking def solve_sudoku(array): is_empty_cell_found = False; # Finding if there is any empty cell for i in range(0, 9): for j in range(0, 9): if array[i][j] == 0: row, col = i, j is_empty_cell_found = True ...
# All rights reserved by forest fairy. # You cannot modify or share anything without sacrifice. # If you don't agree, keep calm and don't look at code bellow! __author__ = "VirtualV <https://github.com/virtualvfix>" __date__ = "03/22/18 15:40" class InstallError(Exception): """ Install exception base class. ...
""" /* * * Crypto.BI Toolbox * https://Crypto.BI/ * * Author: José Fonseca (https://zefonseca.com/) * * Distributed under the MIT software license, see the accompanying * file COPYING or http://www.opensource.org/licenses/mit-license.php. * */ """ class CBInfoNode: def __init__(self, cin_id, block_has...
#SetExample4.py ------difference between discard() & remove() #from both remove() gives error if value not found nums = {1,2,3,4} #remove using discard() nums.discard(5) print("After discard(5) : ",nums) #reove using remove() try: nums.remove(5) print("After remove(5) : ",nums) except KeyErr...
class Item: def __init__(self, name, price, quantity): self._name = name self.set_price(price) self.set_quantity(quantity) def get_name(self): return self._name def get_price(self): return self._price def get_quantity(self): return self._quantity ...
""" Constants for django Organice. """ ORGANICE_DJANGO_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', ] ORGANICE_CMS_APPS = [ 'cms', 'm...
""" dp """ class Solution: def uniquePaths(self, row: int, col: int) -> int: """ Since only 2 options are possible, either from the cell above or left, it is a dp problem. """ def is_valid(i, j): if i >= row or j >= col or i < 0 or j < 0: return False ...
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n-1: return -1 adjacency = [set() for _ in range(n)] for x,y in connections: adjacency[x].add(y) adjacency[y].add(x) components = 0...
class Config: Sector = [ "Food", "Agriculture", "Clothing", "Construction", "Health", "Services", "Retail", "Arts", "Housing", "Transportation", "Manufacturing", "Entertainment", "Wholesale", "Education"...
class Solution: def bitwiseComplement(self, N: int) -> int: if N == 0: return 1 ans = 0 i = 0 while N: r = N % 2 ans += 2 ** i * (1 - r) i += 1 N //= 2 return ans
"""Utils related to urls.""" def uri_scheme_behind_proxy(request, url): """ Fix uris with forwarded protocol. When behind a proxy, django is reached in http, so generated urls are using http too. """ if request.META.get("HTTP_X_FORWARDED_PROTO", "http") == "https": url = url.replace("...
a, b, c = input().split(' ') d, e, f = input().split(' ') g, h, i = input().split(' ') a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) f = int(f) g = int(g) h = int(h) i = int(i) def resto(a, b, c): return (a + b) % c resultado_1 = resto(a, b, c) resultado_2 = resto(d, e, f) resultado_3 = resto(g, h, ...
jogador = {} time = [] lista = [] total = 0 while True: jogador.clear() jogador['Nome'] = input('Nome do jogador: ') quantidade = int(input('Quantas partidas {} jogou ? '.format(jogador['Nome']))) lista.clear() for i in range(0, quantidade): gol_quantidade = int(input('Quantos gols na partid...
def df_restructure_values(data, structure='list', destructive=False): '''Takes in a dataframe, and restructures the values so that the output dataframe consist of columns where the value is coupled with the column header. data | DataFrame | a pandas dataframe structure | str | 'list', 'str', '...
""" Автор: Моисеенко Павел, группа № 1, подгруппа № 2. Задание: вывести таблицу истинности для and, or, xor, equality. Таблица введена с помощью символа "*", int и bool преведены к строкам, и выведены результаты для коньюнкции, дизюнкции, строгой дизъюнкции и эквиваленции. """ logical_false = 0 logical_...
T,R=int(input('Enter no. Test Cases: ')),[] while(T>0): P=[int(x) for x in input('Enter No. Cases,Sum: ').split()] A=sorted([int(x) for x in input('Enter Numbers(A): ').split()][:P[0]]) B=sorted([int(x) for x in input('Enter Numbers(B): ').split()][:P[0]]) for i in range(P[0]): if A[i]+B[-(i+1)]...
# Copyright 2012 Justas Sadzevicius # Licensed under the MIT license: http://www.opensource.org/licenses/MIT # Notes library for Finch buzzer #("Middle C" is C4 ) frequencies = { 'C0': 16.35, 'C#0': 17.32, 'Db0': 17.32, 'D0': 18.35, 'D#0': 19.45, 'Eb0': 19.45, 'E0': 20.6, 'F0': 21.83, ...
class Solution: def findMaximumXOR(self, nums: List[int]) -> int: L = len(bin(max(nums))) - 2 nums = [[(num >> i) & 1 for i in range(L)][::-1] for num in nums] maxXor, trie = 0, {} for num in nums: currentNode, xorNode, currentXor = trie, trie, 0 for bit in nu...
""" Implementing DefaultErrorHandler. Object default_error_handler is used as global object to register a callbacks for exceptions in asynchronous operators, """ def _default_error_callback(exc_type, exc_value, exc_traceback): """ Default error callback is printing traceback of the exception """ raise exc...
''' 2969 6299 9629 ''' def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: #vsa liha ostanejo d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True for x in range(100...
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython 1. Escribe un programa que solicité al usuario ingresar cuatro números para luego mostrar el promedio de los tres. 2. Tres personas deciden invertir su dinero para fundar una empresa. Cada una de ellas invierte una cantidad distinta. Obtener el por...
class Rectangle: pass rect1 = Rectangle() rect2 = Rectangle() rect1.height = 30 rect1.width = 10 rect2.height = 5 rect2.width = 10 rect1.area = rect1.height * rect1.width rect2.area = rect2.height * rect2.width print(rect2.area)