content
stringlengths
7
1.05M
def _expand_batchnorm_weights(model_dict, state_dict, num_splits): """Expands the weights of the BatchNorm2d to the size of SplitBatchNorm. """ running_mean = 'running_mean' running_var = 'running_var' for key, item in model_dict.items(): # not batchnorm -> continue if not runnin...
# Databricks notebook source BGBQHOWGGFSMHPYXGTO NZPBFOKMJLRQHTARPERJDKKJQZPZKYQCWGGKJLOJJGHLJABIYDVAYNJVEYPYNYHIEWTJHFMDBEJXY YGPGFWXAJUKFLCXFPXDGXTEVNVRFKDXIYKLYACCVXBWTDQOQHXDNIJXRLNXBFSLJYR EDQHGMWXXKNBGRPVWTVEYCIQJCENTCTADVYPELTBKBMSXQNCRTZGCMFGGEJIGIVKMIEBSWQPJOGQNEXRUEGOALGKVKQPTOZMLVQKCNKLQHNWIZOPPYI VPOCQGWW...
des = 'Desafio-023 strings-002' print ('{}'.format(des)) #...Faça um programa que leia um número de 0 a 9999 e mostre na telacada um dos digitos separados. ex: unidade; dezena; centena; milhar num = int(input('Digite um número: ')) u = num // 1 % 10 d = num // 10 % 10 c = num // 100 % 10 m = num // 1000 % 10 print ...
def test_correct_message(): pass def test_incorrect_field(): pass
class Edge: def __init__(self, v1: int, v2: int, f1: int, f2: int, p1: int, p2: int): self.v1 = v1 self.v2 = v2 self.f1 = f1 self.f2 = f2 self.p1 = p1 self.p2 = p2 def __repr__(self): return f'<Edge v=({self.v1}, {self.v2}) f=({self.f1}, {self.f2}) p=({se...
""" Copyright 2020 InfAI (CC SES) 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...
# 値からindex番号を取得 if nums[i] != nums[P]: return [copy_nums.index(nums[i]), copy_nums.index(nums[P])] # 被りなし,被っていたら一番最初のもの,無いものはエラー else: ans = [i for i, x in enumerate(copy_nums) if x == nums[i]] # 被りあり,全て取り出す return ans[:2] # 無いものに対応 def my_index2(l, x, default=False): return l.index(x) if x in l else...
def min_max_from_inputV2(): inp_list = [] while True: string_num = input('Enter a number: ') if string_num == 'done': break try: num = int(string_num) except: print('Invalid input') continue inp_list.append(num) ...
""" Quiz: Create Usernames Write a for loop that iterates over the names list to create a usernames list. To create a username for each name, make everything lowercase and replace spaces with underscores. Running your for loop over the list: names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"...
""" TESTS is a dict with all you tests. Keys for this will be categories' names. Each test is dict with "input" -- input data for user function "answer" -- your right answer "explanation" -- not necessary key, it's using for additional info in animation. """ TESTS = { "Basics": [ { ...
message = { "0001": "login success, welcome {}", "0002": "login fail,your username or password is error", "0003": "logout success !!!", "0004": "bye {}", "0005": "Please input add messages:", "0006": "Your input messages invalid!", "0007": "Username is already !!!", "0008": "add username...
# # PySNMP MIB module RFC-HIPPI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC-HIPPI-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:56:15 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...
TASK_URL = "calc-1.ctf.sicamp.ru 50002" TITLE = "Простой калькулятор" STATEMENT_TEMPLATE = f''' Весьма ленивый компьютер не хочет считать. Поговорите с ним `nc {TASK_URL}` Ваш токен: `{{0}}` ''' def generate(context): participant = context['participant'] token = tokens[participant.id % len(tok...
n,k=list(map(int,input().split())) s=list(map(int,input().split())) ans=int(len([i for i in s if 5-i>=k])/3) print(ans)
def add(a, b): return a + b add() def add(a, b): print(a+b) def say_hello(): print("hello") say_hello()
"""Common utilities for creating J2CL targets and providers.""" load(":j2cl_transpile.bzl", "J2CL_TRANSPILE_ATTRS", "j2cl_transpile") load(":j2cl_js_common.bzl", "J2CL_JS_ATTRS", "JS_PROVIDER_NAME", "j2cl_js_provider") # Constructor for the Bazel provider for J2CL. # Note that data under "_private_" considered privat...
class Goods(object): __slots__ = ('id', 'name', 'price') def __init__(self,id,name,price): self.id=id self.name=name self.price=price
# configuration file for interface "jms_1" # this file exists as a reference for configuring JMS interfaces # # copy this file to your own cage, possibly renaming into # config_interface_YOUR_INTERFACE_NAME.py, then modify the copy # # this particular configuration works with OpenMQ and file-based JNDI config = dict \...
class RecordBatchUpdate: """ Event generated each time when record is created/update with new release """ def __init__(self, request, records): self.request = request self.records = records
''' Created on May 1, 2016 @author: Drew ''' PlayBtnPos = (0, 0, 0.0) PlayBtnHidePos = (0, 0, -1.1) OptionsBtnPos = (-.9, 0, -0.6) OptionsBtnHidePos = (-.9, 0, -1.7) DiscordBtnPos = (-.3, 0, -0.6) DiscordBtnHidePos = (-.3, 0, -1.7) CreditsBtnPos = (.3, 0, -0.6) CreditsBtnHidePos = (.3, 0, -1.7) QuitBtnPos = (.9, ...
# @Author: Ozan YILDIZ@2022 # Boolean Variable Literal Examples booleanTrue = True booleanFalse = False four = True + 3 two = False - 0 trueResult = (four == 4) falseResult = (two == 3) if __name__ == '__main__': print("Boolean True (True)", booleanTrue) print("Boolean False (False)", booleanFalse) print("F...
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, 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 requi...
#! /usr/bin/env python3 # Largest product in a series # Problem 8 # Find the greatest product of five consecutive digits in the 1000-digit number. digits = """ 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540...
# Employees salute when they "cross". # Hallway exits do not count. # Key algorithms: regular expression, counting, indexing # For each > (right-going employee), # count < (left-going employee). # Then double the total encounters (because they greet "each other"). # string.count("char") # list.index(element) # stri...
#Criando um algoritmo para somar duas variáveis a = int(input('Digite um valor:')) b = int(input('Digite outro valor: ')) soma = a+b print(f'A soma entre {a} e {b} é {soma}.')
tweet_at = '@Attribution' tweet_url = 'https://example.com/additional-url' tweet_hashtag = '#MyHashtag' tweet_data = [ { 'image': 'https://example.com/image.jpg', 'id': 'image_id', 'title': 'Example title', 'desc': 'Example description with lots of text that probably goes well over the 280 character lim...
def rabbit_pairs(n,k): if(n==1): return 1 if(n==2): return 1 else: return k*rabbit_pairs(n-2,k)+rabbit_pairs(n-1,k) def main(): with open('datasets/rosalind_fib.txt') as input_data: n,k=map(int,input_data.read().strip().split()) # n=5 # k=3 pairs=str...
def digits_product(product): if product<10: return 10+product res=factorization(product) for i in res: if i>=10: return -1 reduce(res) total=0 for i,j in enumerate(res): total+=10**(len(res)-i-1)*j return total def factorization(n): res=[] factor=2...
# 面向过程的程序设计,把计算机程序视为一系列的命令集合,即一组函数的顺序执行。为了简化程序设计,面向过程把函数继续切分为子函数, # 即把大块函数通过切割成小块函数来降低系统的复杂度。 # 面向对象编程,OOP,Object Oriented Programming,一种程序设计思想。OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数。 # 面向对象的程序设计把计算机程序视为一组对象的集合,而每个对象都可以接收其他对象发过来的消息,并处理这些消息, # 计算机程序的执行就是一系列消息在各个对象之间传递。 # 所以,面向对象的设计思想是抽象出Class,根据Class创建Instance,面向对象的抽象程度又比函...
a=10 b=20 a+b #addition a/b #divde a-b #substraction a*b #multiplication a%b #reminder a**b #exponent a//b #floor devision
NEW_FEATURES = [3, 5, 6, 7] FEATURES = [ 1, # L 2, # S 4, # B 8, # A 3, # LS 5, # LB 6, # SB 9, # LA 9, # LA 9, # LA 9, # LA 9, # LA 10, # SA 10, # SA 10, # SA 10, # SA 10, # SA 12, # BA 12, # BA 12, # BA 12, # BA ...
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: res = [] if not nums: return nums nums = nums + [nums[-1]+2] head = nums[0] for i in range(1,len(nums)): if nums[i]-nums[i-1]>1: if head ==nums[i-1]: ...
# chapter 04-02 # 시퀀스 형 # 파이썬의 자료구조 형태 : 컨테이너형 / 플랫 또는 가변형 / 불변형 # 자료형 1. 컨테이너(Container) : 서로 다른 자료형을 담을 수 있음 (리스트, 튜플, collections.deque) # 컨테이너 ex) a = [3, 3.0, 'a', [1,2]] # 자료형 2. 플랫(Flat) : 한 개의 자료형을 담을 수 있음 (str, bytes, bytearray, array.array, memoryview) # 자료형 1. 가변 : 리스트, bytearray, array.array, memoryview,...
""" Class which holds loop data regarding stamp names and accumulated times on a per-iteration basis. """ class Loop(object): """Hold info for name checking and assigning.""" def __init__(self, name=None, rgstr_stamps=None, save_itrs=True): self.name = None if name is None else str(name) sel...
lista1 = [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52] lista2 = [] lista3 = [] print(lista1) print('O número de elementos da lista é: {}'.format(len(lista1))) print('O maior numero da lista é {}.'.format(max(lista1))) print('O menor numero da lista é {}.'.format(min(lista1))) for valor in lista1: if v...
class Solution: """ @param candidates: A list of integers @param target: An integer @return: A list of lists of integers """ def combinationSum(self, candidates, target): candidates.sort() n = len(candidates) solutions = [] self.dfs(candidates, n, 0, target, [], s...
#!/usr/bin # -*- coding: utf-8 -*- """ DelftStack Python Tkinter Tutorial Author: Jinku Hu URL: https://www.delftstack.com/tutorial/python-3-basic-tutorial/namescape-and-scope/ Website: https://www.delftstack.com """ x = 1 y = 2 stringX = "String X" def globalTest(): for (key, value) in globals().items(): ...
""" 27 Petya and Strings - https://codeforces.com/problemset/problem/112/A """ one = input().lower() two = input().lower() if one < two: print("-1") elif one > two: print("1") else: print("0")
def quick_sort(arr, a, b): if a >= b: return pivot = arr[(a+b)//2] left = a right = b while True: while arr[left] < pivot: left += 1 while pivot < arr[right]: right -= 1 if left >= right: break arr[left], arr[right] = arr[right], arr[left] left += 1 ...
# This file serves as an example for what's needed in your secrets.py file. # You can make a copy of this and rename it secrets.py. # Create an application at https://discord.com/developers/applications # Then go to the `bot` section of your app and see the token. DISCORD_TOKEN = 'YOUR TOKEN HERE' # Create a client ...
class Curve_Colors(): ##! ##! Set colors ##! def Curve_Colors_Take(self,colordefs): bcolor=self.BackGround_Color() for color in colordefs.keys(): self.Color_Schemes[ bcolor ][ color ]=colordefs[ color ] ##! ##! Sets Analytical Evolute colors. ##! ...
valores = [] while True: valores.append(int(input('Digite um valor:'))) resp = str(input('Quer continuar: ')).upper()[0] if resp == 'N': break pares = [] impares = [] for v in valores: if v % 2 == 0: pares.append(v) else: impares.append(v) print(f'Os valores digitados foram {...
# SWEA 2050 string = input() for c in string: print(ord(c) - ord("A") + 1, end=" ")
''' Write a Python function named printAsterisks that is passed a positive integer value n, and prints out a line of n asterisks. If n is greater than 75, then only 75 asterisks should be displayed. ''' def printAsterix(n): return '*'*(n if n<75 else 75) print(printAsterix(int(input("Enter number: "))))
def consecutive_elements_opt(arr,k): window_sum=0 for i in range(k): window_sum+=arr[i] max_sum=window_sum for j in range(k,len(arr)): window_sum=window_sum-arr[j-k]+arr[j] print(arr[j-k],arr[j]) max_sum=max(max_sum,window_sum) return max_sum ...
""" FILE: assign02.py AUTHOR: Carlos W. Mercado PROCESSING: - Informs the average commercial rate in a file. - Informs data about the utility companies with the highest and lowest commercial rates. """ def average_comm_rate(filename): ''' INPUT: The name of a file. PROCESSING: ...
#refaça o desafio 009, mostrando a tabuada de um número que o usuario escolher, #usando laço de repetição calc = int(input('Digite um número inteiro: ')) for c in range (0, 11): tabuada = calc*c print(f'A tabuada de {calc} é {calc}X{c} = {tabuada}')
# # PySNMP MIB module REDSTONE-TEMPLATE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDSTONE-TEMPLATE-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:55:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
"""Script containing the base detector kernel class.""" class KernelDetector(object): """Docstring """ def __init__(self, master_kernel): """DocString """ self.master_kernel = master_kernel self.kernel_api = None def pass_api(self, kernel_api): """DocString ...
class Field: """Klasa reprezentująca jedno pole na planszy""" CLOSED_STATE = 0 FLAGGED_STATE = 1 MAYBE_STATE = 2 OPENED_STATE = 3 def __init__(self, x, y): self._x = x self._y = y self._mines_nearby = 0 self._is_mine = False self._state = ...
# -------------- def palindrome(num): if num < 9: num = num+1 return num else: while(str(num) != str(num)[::-1]): num = num + 1 return int(num) palindrome(13456) # -------------- def a_scramble(str_1,str_2): result=True for i in (str_2.lower()): ...
class Auth(object): def __init__(self, values=None): self.values = values or {} def __setattr__(self, name, value): if name != "values": self.values[name] = value else: super().__setattr__(name, value) def __getattribute__(self, key): if key != "valu...
d = int(input()) a, b = map(int, input().split()) result = 10 ** 15 for i in range(d + 1): result = min(result, i * a + (d - i) * b) print(result)
# -*- coding: utf-8 -*- # O código funciona descontando gastos e adicionando ganhos a uma variável de saldo. Cada valor citado é # adicionado ou descontado ao saldo da UFSC, no final é checado se o saldo é negativo, positivo ou igual a 0. # Quando o saldo é posivivo ou igual a 0 a greve para, caso contrário ela cont...
# import sys # print(sys.version) ok_result = ['to','be','or','not','to','be','that','is','the','question'] initial = [ 'not','to','be', 'is','that','the','question'] # add missing result=['to','be','or'] result.extend(initial) # miss.reverse() # for m in miss: # result.insert(0,m) # flip 6,7 flip=result[6] resul...
""" worldcup2014.mat It is the playing ground model of soccer. points: N * 2, points in the model, for example, line intersections line_segment_index: N * 2, line segment start/end point index grid_points: a group of 2D points uniformly sampled inside of the playing ground. It is used to approximate the a...
# Faça um programa que leia o peso de cinco # pessoas. No final, # mostre qual foi o maior e o menor peso lidos. pmai = 0 pmen = 300 for c in range(1, 6): peso = float(input('Qual eh o {}o peso: ' .format(c))) if peso > pmai: pmai = peso elif peso < pmen: pmen = peso print('A pessoa mais pes...
""" PUP Plugin defining Windows packaging stages. """ class Steps: @staticmethod def usable_in(ctx): return ( (ctx.pkg_platform == 'win32') and (ctx.tgt_platform == 'win32') ) def __call__(self, ctx, _dsp): return ( 'pup.python-runtime', ...
#!/usr/bin/python # -*- coding: UTF-8 -*- DATA_HEAD_LENGTH = 16 def encode_image_array(image_shape=None): if image_shape is not None: # TODO: return None return None def data_receive_length(data_head=None): if data_head is not None: # TODO: return 0 return 0 def de...
########################## # 141. Linked List Cycle ########################## # # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # class Solution(object): # def hasCycle(self, head): # """ # :type head: Li...
class Solution: def Rob(self, nums, m, n) -> int: prev, curr = nums[m], max(nums[m], nums[m + 1]) for i in range(m + 2, n): prev, curr = curr, max(prev + nums[i], curr) return curr def rob(self, nums: List[int]) -> int: if len(nums) == 0: return 0 ...
# TODO def test_DAI(DAI, accounts): assert DAI.decimals() == 18 DAI._mint_for_testing(10000000, {'from': accounts[0]}) assert DAI.balanceOf(accounts[0]) == 10000000 tx = DAI.transfer(accounts[1], 1000, {'from': accounts[0]}) assert tx.return_value is True def test_USDT(USDT, accounts): as...
# HTML tag to default to if no prefix is found md_default_tag = "p" # Markdown to HTML key md_html = [ ("#", "h1"), ("##", "h2"), ("###", "h3"), ("####", "h4"), ("#####", "h5"), ("######", "h6"), ("`", "code"), ("*", "i"), ("**", "strong"), ("~~", "strike"), ("-", "li") ...
def solve(string): z, o = 0, 0 for c in string: if c == '0': z+=1 else: o+=1 if z == 1 or o == 1: return "Yes" else: return "No" if __name__ == "__main__": T = int(input()) for t in range(0,T): D = input() print(solve(D))...
class Solution: def setZeroes(self, matrix): dummy1=[1]*len(matrix) dummy2=[1]*len(matrix[0]) for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j]==0: dummy1[i]=0 dummy2[j]=0 for i in range...
N=int(input("Enter the number of test cases:")) for i in range(0,N): L,D,S,C=map(int,input().split()) for i in range(1,D): if(S>=L): S+=C*S break if L<= S: print("ALIVE AND KICKING") else: print("DEAD AND ROTTING")
class Solution: def increasingTriplet(self, nums: List[int]) -> bool: first = second = math.inf for i in nums: if i <=first: first = i elif i<=second: second = i else: return True return False
DynamoTable # unused import (dynamo_query/__init__.py:8) DynamoRecord # unused variable (dynamo_query/__init__.py:12) create # unused function (dynamo_query/data_table.py:119) memo # unused variable (dynamo_query/data_table.py:137) filter_keys # unused function (dynamo_query/data_table.py:299) get_column # unused...
preamble = [int(input()) for _ in range(25)] for _ in range(975): x = int(input()) valid = False for i, a in enumerate(preamble[:-1]): for b in preamble[i+1:]: if a + b == x: valid = True if not valid: print(x) break preamble = preamble[1:] + [...
# https://www.codechef.com/AUG21C/problems/SPCTRIPS for T in range(int(input())): n,c=int(input()),0 for x in range(1,n+1): for y in range(x,n+1,x): c+=((n-(x+y))//y+1) print(c)
""" Taller 2.3 Distancia mas corta # Tu nombre aquí Mayo xx-XX """ # Definición de Funciones (Dividir) #====================================================================== # E S P A C I O D E T R A B A J O A L U M N O # =====================================================================...
class QuizBrain: def __init__(self, a_list): self.question_number = 0 self.question_list = a_list self.score = 0 def still_has_questions(self): """Checks if their still have more questions""" if self.question_number < 12: """Checks if their still have more qu...
ignore_validation = { "/api/v1/profile": ("POST", "PUT"), "/api/v1/exchange": "GET", "/api/v1/validation": "GET", "/api/v1/meals/search" : "GET", "/api/v1/meals/browse" : "GET" }
n, q = map(int, input().split()) graph = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) a, b = a - 1, b - 1 graph[a].append(b) graph[b].append(a) # graph, n and root is necessary idx = 0 root = 0 def dfs(start, graph): global idx par = [-1] * n depth = [-...
class Node(object): def __init__(self, id, x, y): self.__id = id self.__x = x self.__y = y self.reset() @property def id(self): return self.__id @property def x(self): return self.__x @property def y(self): return self.__y @prop...
# -*- coding: utf-8 -*- """ Author : Chris Azzara Purpose : A simple number guessing game. This program will try to guess a secret number between 1 - 100 The user will enter whether the guess is too high or too low or correct. The program uses the binary search algorithm to narrow the search space. """ prin...
load("//bazel/rules/image:png_to_xpm.bzl", "png_to_xpm") load("//bazel/rules/image:xpm_to_ppm.bzl", "xpm_to_ppm") load("//bazel/rules/image:ppm_to_mask.bzl", "ppm_to_mask") load("//bazel/rules/image:ppm_to_xpm.bzl", "ppm_to_xpm") load("//bazel/rules/image:xpm_to_xbm.bzl", "xpm_to_xbm") load("//bazel/rules/image:png_mir...
# Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados. number = int(input('Digite um número de 0 a 9999: ')) unitys = number // 1 % 10 dozens = number // 10 % 10 hundreds = number // 100 % 10 thousands = number // 1000 % 10 print('Unidades:', unitys) print('Dezenas:', dozens...
# -*- coding: utf-8 -*- """ fairsearchdeltr.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power fairsearchdeltr. """ class TrainStep(object): """The :class:`TrainStep` object, which is a representation of the parameters in each step of the training. Contains a `timestamp`, `omega`, `om...
a = {'a': 1, 'b': 2} b = a del b['a'] print(a) print(b) c = 5 del a del b, c
class Keys(): ERROR = 'ERROR' DEBUG = 'DEBUG' WARN = 'WARN' INFO = 'INFO' URL = 'url' TAG = 'tag' MESSAGE = 'message' LOG_LEVEL = 'level' REQUEST_METHOD = 'method' RESPONSE_STATUS = 'status' PAGE = 'page' SHOW = 'show' ALL = 'all'
# # Copyright(c) 2019-2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # class PresentationPolicy: def __init__(self, standard_log, group_begin_func): self.standard = standard_log self.group_begin = group_begin_func def std_log_entry(msg_id, msg, log_result, html_node): p...
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return '0' if numerator ^ denominator < 0: result = '-' else: result = '' numerator = abs(numerator) denominator = abs(denomin...
#可以继承父类,默认的父类为object,单继承 class Foo(object): version = 1.0 #self是类实例的引用,类似其他语言中的this def __init__(self, name = 'zhang'): self.name = name print('这个方法类似构造函数,但不同于其他语言,此处是类实例在创建后自动执行的第一个方法而已') def show(self): print(self.name) def addMe2Me3(self, x): print(str(x + x)) f...
class Tags(object): """A class to manage various AirWatch device tag functionalities""" def __init__(self, client): self.client = client def get_id_by_name(self, name, og_id): # mdm/tags/search?name={name} response = self._get(path='/tags/search', params={'name':str(name), 'organiz...
def factors(x): result = [] i = 1 while i*i <= x: if x % i == 0: result.append(i) if x//i != i: result.append(x//i) i += 1 return result for _ in range(int(input())): a, b = [int(i) for i in input().split()] m = 0 x = 0 for i in range(a, b + 1): result = factors(i) if ...
# 92. Reverse Linked List II # Runtime: 59 ms, faster than 5.80% of Python3 online submissions for Reverse Linked List II. # Memory Usage: 14.7 MB, less than 5.82% of Python3 online submissions for Reverse Linked List II. # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=No...
def conta_letras(frase, contar="vogais"): ''' Account the amount of consonants or vowels that the sentence has''' lista_ord_vogais = [65, 69, 73, 79, 85, 97, 101, 105, 111, 117] lista_ord_cosoantes = [66, 67, 68, 70, 71, 72, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 98, 99, 100, 102,...
class SingletonMeta(type): def __init__(cls, name, bases, namespace): super().__init__(name, bases, namespace) cls.instance = None def __call__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super().__call__(*args, **kwargs) return cls.instance cla...
# Solution by PauloBA def digital_root(n): n = str(n) ls = [] ans = 0 for i in n: ls.append(int(i)) for i in ls: ans = ans + i if ans < 10: return ans else: return digital_root(ans) print(digital_root(24))
def gcd(a, b): if min(a, b) == 0: return max(a, b) a_1 = max(a, b) % min(a, b) return gcd(a_1, min(a, b)) def lcm(a, b): return (a * b) // gcd(a, b)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author : pengj @ date : 2019/10/31 18:48 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : pengjianbiao@hotmail.com ---------------...
def car_information (fabricante, modelo, **car_info): """Constrói um dicionário com tudo que sabemos sobre o carro""" settings={} settings['fabricante_carro']=fabricante settings['modelo_carro']=modelo for key,value in car_info.items(): settings[key]=value return settings car = car_in...
class HelloMixin: def display(self): print('HelloMixin hello') class SuperHelloMixin: def display(self): print('SuperHello hello') class A(SuperHelloMixin, HelloMixin): pass if __name__ == '__main__': a = A() a.display()
# # @lc app=leetcode.cn id=1 lang=python3 # # [1] 两数之和 # # https://leetcode-cn.com/problems/two-sum/description/ # # algorithms # Easy (44.30%) # Total Accepted: 243.9K # Total Submissions: 547.9K # Testcase Example: '[2,7,11,15]\n9' # # 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 # # 你可以假设每种输入只会...
def isPalindrome(string): return string == string[::-1] # OR # left_pos = 0 # right_pos = len(string) - 1 # # while right_pos >= left_pos: # if(string[left_pos] != string[right_pos]): # return False # left_pos += 1 # right_pos -= 1 # # re...
# Dict02.py a = {'사과' : 'apple', '포도' : 'grape', '바나나' : 'banana', '컵' : 'cup', '물' : 'water'} a['강'] = 'river' print(a) a['자바'] = 'Java' a.pop('강') # 강 지우기 print(a) del a['자바'] print(a) # 자바 지우기 # keys에서 바나나가 존재하는지 궁금 print("바나나" in a) # values에서 grape 존재하는지 궁금 print('grape' in a.values())...
# Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: #A) Quantas vezes apareceu o valor 9. #B) Em que posição foi digitado o primeiro valor 3. #C) Quais foram os números pares. valores=tuple(int(input("Digite um numero: ")) for n in range(1,5)) print(f"Os valores ...
def select_rows(df, where): """Performs a series of rows selection in a DataFrame Pandas provides several methods to select rows. Using lambdas allows to select rows in a uniform and more flexible way. Parameters ---------- df: DataFrame DataFrame whose rows should be selected ...
# Semigroup = non-empty set with an associative binary operation # using addition print((2 + 3) + 4 == 2 + (3 + 4) == 9) # We get a property of closure, because the number we get is still a number of the same set, # natural numbers, including 0 # (2 + 3) + 4 # 2 + (3 + 4) # 9