content
stringlengths
7
1.05M
# O(NlogM) / O(1) class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: def count(t): ans, cur = 1, 0 for w in weights: cur += w if cur > t: ans += 1 cur = w return ans...
x=oi() q=x z(q)
# 점프와 순간이동 def solution(n): ans = 0 while n > 0: if n % 2 != 0: ans+= 1 n //= 2 return ans ''' 채점을 시작합니다. 정확성 테스트 테스트 1 〉 통과 (0.00ms, 10.2MB) 테스트 2 〉 통과 (0.00ms, 10.1MB) 테스트 3 〉 통과 (0.00ms, 10.2MB) 테스트 4 〉 통과 (0.00ms, 10.2MB) 테스트 5 〉 통과 (0.01ms, 10.2MB) 테스트 6 〉 통과 (0.00ms, 10.2...
#!/usr/bin/env python """ Author: Gianluca Biccari Description: Implementation of an Hash Table with string keys """ class HashTable(object): """ Do-it by yourself implemenation in case you don't want to use the built in data structure dictionary. """ def __init__(self): ...
class Output: def __init__(self, race_nr, winner, loser, ): self.race_nr = race_nr self.winner = winner self.loser = loser def get_output_template(self): if self.winner == 'O' or 'X': results = f'\nR...
#-*- coding:utf-8 -*- # <component_name>.<environment>[.<group_number>] HostGroups = { 'web.dev': ['web.dev.example.com'], 'ap.dev': ['ap.dev.example.com'], 'web.prod.1': ['web001.example.com'], 'web.prod.2': ['web{:03d}.example.com'.format(n) for n in range(2,4)], 'web.prod.3': ['web{:03d}...
class NewsValidator: def __init__(self, config): self._config = config def validate_news(self, news): news = news.as_dict() assert self.check_languages(news), "Wrong language!" assert self.check_null_values(news), "Null values!" assert self.check_description_length(new...
# -*- coding: utf-8 -*- """ Created on Tue Dec 12 01:33:05 2017 @author: Mayur """ # ============================================================================= # Exercise: coordinate # # Consider the following code from the last lecture video: # # class Coordinate(object): # def __init__(self, x...
#https://programmers.co.kr/learn/courses/30/lessons/42860 def solution(name): answer = 0 name_length = len(name) move = [1 if name[i]=='A' else 0 for i in range(name_length)] for i in range(name_length): now_str = name[i] answer += get_move_num_alphabet(now_str, 'A') a...
#code def SelectionSort(arr,n): for i in range(0,n): minpos = i for j in range(i,n): if(arr[j]<arr[minpos]): minpos = j arr[i],arr[minpos] = arr[minpos],arr[i] #or #temp = arr[minpos] #arr[minpos] = arr[i] #arr[i] = temp #driver ar...
ES_HOST = 'localhost:9200' ES_INDEX = 'pending-pseudocap_go' ES_DOC_TYPE = 'gene' API_PREFIX = 'pseudocap_go' API_VERSION = ''
def aumentar(numero, taxa=10, f=False): numero += ((numero * taxa)/100) if f==True: return moeda(numero) else: return numero def diminuir(numero, taxa=10, f=False): numero-=((numero*taxa)/100) if f == True: return moeda(numero) else: return numero def metade(num...
# V1.43 messages # PID advanced # does not include feedforward data or vbat sag comp or thrust linearization # pid_advanced = b"$M>2^\x00\x00\x00\x00x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x007\x00\xfa\x00\xd8\x0e\x00\x00\x00\x00\x01\x01\x00\n\x14H\x00H\x00H\x00\x00\x15\x1a\x00(\x14\x00\xc8\x0fd\x04\x00\xb1" p...
N = int(input()) swifts = [int(n) for n in input().split(' ')] semaphores = [int(n) for n in input().split(' ')] swift_sum = 0 semaphore_sum = 0 largest = 0 for k in range(N): swift_sum += swifts[k] semaphore_sum += semaphores[k] if swift_sum == semaphore_sum: largest = k + 1 print(largest)
"""Firehose resource for AWS Cloudformation.""" __version__ = "0.0.6" __author__ = "German Gomez-Herrero, FindHotel BV"
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 17 09:54:02 2020 @author: AzureD Formatting tools for displaying HELP inside the MUD clients. """ def docstring_to_help(name: str, docstring: str): """ Converts a function docstring to a more viewable format for MUD clients. Mainly use...
# Iterate over the enitre array. Insert counts only if != 1. Pop repeated occurances of characters. class Solution: def compress(self, chars: List[str]) -> int: run = 1 prev = chars[0] i = 1 while i<len(chars): c = chars[i] if c==prev: ...
# 字符模拟二进制计算 class Solution: def addBinary(self, a: str, b: str) -> str: # 1补齐长度 # 2从尾部到头部模拟加法 # 3进位处理、头部进位 # 4输出切片 d = abs(len(a) - len(b)) if len(a) > len(b): b = '0' * d + b else: a = '0' * d + a l = len(a) s = '' ...
# Escriba un programa que calcule el máximo y el mínimo de dos números usando funciones. # Con tal fin, proceda como sigue: # • Escriba un procedimiento Leer que lea un número. # • Escriba una función que dados dos números, devuelva el máximo de ellos. # • Escriba una función que dados dos números, devuelva el mínimo d...
{ "targets": [{ "target_name": "pifacecad", "sources": ["piface.cc"], "include_dirs": ["./src/"], "link_settings": { "libraries": [ "../lib/libpifacecad.a", "../lib/libmcp23s17.a" ] }, "cflags": ["-std=c++11"] }] }
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: pre = ListNode(0) pre.next = head head1, head2 = pre, pre for i in range(n)...
with open("day10/input.txt", encoding='utf-8') as file: data = file.read().splitlines() opening_chars = '([{<' closing_chars = ')]}>' sum_of_corrupted = 0 mapping_dict = {'(' : [')', 3], '[' : [']', 57], '{' : ['}', 1197], '<' : ['>', 25137]} mapping_dict_sums = {')' : 3, ']' : 57, '}' : 1197, '>' : 25137} mappin...
class StairsEditScope(EditScope,IDisposable): """ StairsEditScope allows user to maintain a stairs-editing session. StairsEditScope(document: Document,transactionName: str) """ def Dispose(self): """ Dispose(self: EditScope,A_0: bool) """ pass def ReleaseUnmanagedResources(self,*args): """ R...
{ 'application':{ 'type':'Application', 'name':'Template', 'backgrounds': [ { 'type':'Background', 'name':'bgTemplate', 'title':'Standard Template with File->Exit menu', 'size':( 400, 300 ), 'style':['resizeable'], 'statusBar':0, 'menubar': { 'type':'MenuBar'...
def menu_selection_error(a): """if input is not a valid menu choice, throw an error""" print("'\033[91m'ERROR:'\033[92m'Invalid input! Please select from the menu'\033[0m'") def handle_division(a): """makes sure number is not zero""" if a == 0: print("'\033[91m'ERROR:'\033[92m'Cannot divide ...
class ErosionStatus: is_running: bool # signalize that the erosion (usually in other thread) should stop stop_requested: bool = False progress: int def __init__(self, is_running: bool = False, progress: int = 0): self.is_running = is_running self.progress = progress
# 1. Quais são os dados de entrada necessários? #   * um valor de reais N do tipo float(). # 2. Que devo fazer com estes dados? #   * converter no formato de cédulas e moedas. # 3. Quais são as restrições deste problema? #   * entrada em float(). # 4. Qual é o resultado esperado? #   * NOTAS: # * ? nota(s) de R$ #...
# Any recipe starts with a list of ingredients. Below is an extract # from a cookbook with the ingredients for some dishes. Write a # program that tells you what recipe you can make based on the # ingredient you have. # The input format: # A name of some ingredient. # The ouput format: # A message that says "food ti...
PROXIES = [ {'protocol':'http', 'ip_port':'118.193.26.18:8080'}, {'protocol':'http', 'ip_port':'213.136.77.246:80'}, {'protocol':'http', 'ip_port':'198.199.127.16:80'}, {'protocol':'http', 'ip_port':'103.78.213.147:80'}, {'protocol':'https', 'ip_port':'61.90.73.10:8080'}, {'protocol':'http', 'ip_port'...
""" GTSAM Copyright 2010-2020, Georgia Tech Research Corporation, Atlanta, Georgia 30332-0415 All Rights Reserved See LICENSE for the license information Various common utilities. Author: Varun Agrawal """ def collect_namespaces(obj): """ Get the chain of namespaces from the lowest to highest for the given...
def notas(*n, sit=False): """ -> Funcao para analisar notas e situacoes de alunos :param n: uma ou mais notas de alunos :param sit: valor opcional, indicando se deve ou nao adicionar a situacao :return: dicionario com varias informacoes sobre a situacao da turma """ r = dict() r['total']...
""" This package is for adding officially supported integrations with other libraries. The goal of the integrations is to make it easy to get started with dbx combined with other frameworks. Features that an integration might add are: - automatic loggic - automatic checkpoints - pause/resume functionality integrated ...
def dict_words(string): dict_word={} list_words=string.split() for word in list_words: if(dict_word.get(word)!=None): dict_word[word]+=1 else: dict_word[word]=1 return dict_word def main(): with open('datasets/rosalind_ini6.txt...
SORTIE_PREFIXE = "God save" def get_enfants(parent, liens_parente, morts): return [f for p, f in liens_parente if (p == parent) and (f not in morts)] def get_parent(fils, liens_parente): for p, f in liens_parente: if f == fils: return p def get_heritier(mec_mort, liens_parente, morts)...
############################################### # # # Created by Youssef Sully # # Beginner python # # While Loops 3 # # # ################################...
""" Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão. """ ptermo = int(input('Digite o primeiro termo da PA: ')) razao = int(input('Digite a razão: ')) for c in range(ptermo, ptermo + (10 * razao), razao): print(c, end=' ')
class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: text = text.split(' ') return [text[i] for i in range(2, len(text)) if text[i - 2] == first and text[i - 1] == second]
## Python INTRO for TD Users ## Kike Ramírez ## May, 2018 ## Understanding string variables concatenation ## CASE 1 ## Declare two string variables a = "Hola " b = "Barcelona!" ## Concatenate it using + operator print(a+b) ## CASE 2 ## BUT! Declare to number variables a = 99 b = 1.326584 ## Not concatenation, but...
# Swap Pairs using Recursion ''' Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list's nodes, only nodes itself may be changed. Example: Given 1->2->3->4, you should return the list as 2->1->4->3. ''' # Definition for singly-linked list. # class ListNod...
# coding=utf-8 class ListMetaclass(type): # 定义一个元类,类名默认以Metaclass结尾;元类是由“type”衍生而出,所以必须从type类型派生 def __new__(mcs, name, bases, attrs): # 自定义__new__()方法 attrs['add'] = lambda self, value: self.append(value) return super().__new__(mcs, name, bases, attrs) # 返回新创建的类 # return type....
class BaseMixin(object): @property def blocks(self): return self.request.GET.getlist('hierarchy_block', []) @property def awcs(self): return self.request.GET.getlist('hierarchy_awc', []) @property def gp(self): return self.request.GET.getlist('hierarchy_gp', None) def...
n, k = input().strip().split(' ') n, k = int(n), int(k) imp_contests = 0 imp = [] nimp = [] for i in range(n): l, t = input().strip().split(' ') l, t = int(l), int(t) if t == 1: imp.append([l,t]) else: nimp.append([l,t]) imp.sort() ans = 0 ans_subtract = 0 for i in ran...
def f(a): s = 0 for i in range(1,a): if a%i == 0: s+=i return "Perfect" if s==a else ("Abundant" if s > a else "Deficient") T = int(input()) L = list(map(int,input().split())) for i in L: print(f(i))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 13 19:35:17 2019 @author: abhijithneilabraham """ name='katran'
#!/usr/bin/python class Block(object): def __init__(self): print("Block") class Chain(object): def __init__(self): print("Chain") def main(): b = Block() c = Chain() if __name__ == "__main__": main()
class Config: DEBUG = True SQLALCHEMY_DATABASE_URI = "mysql+mysqldb://taewookim:1234@173.194.86.171:3306/roompi2_db" SQLALCHEMY_TRACK_MODIFICATION = True @classmethod def init_app(cls, app): # config setting for flask app instance app.config.from_object(cls) return app
""" Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path. In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any mu...
# -*- coding: utf-8 -*- # segundo link: dobro do terceiro # segundo link: metade do primeiro clicks_on_3 = int(input()) clicks_on_2 = clicks_on_3 * 2 clicks_on_1 = clicks_on_2 * 2 print(clicks_on_1)
#Coded by Ribhu Sengupta. def solveKnightMove(board, n, move_no, currRow, currCol): #solveKnightMove(board, dimesion of board, Moves_already_done, currRoe, currCol) if move_no == n*n: #Lets say n=8, if no of moves knight covered 64 then it will stop further recursion. return True rowDir = [+...
# https://leetcode.com/problems/jewels-and-stones/description/ # input: J = "aA" | S = "aAAbbbb" # output: 3 # input: J = "z", S = "ZZ" # output: 0 # Solution: O(N^2) def num_jewels_in_stones(J, S): jewels = 0 for j in J: for s in S: if s == j: jewels += 1 return j...
def writeList(l,name): wptr = open(name,"w") wptr.write("%d\n" % len(l)) for i in l: wptr.write("%d\n" % i) wptr.close()
# DEFAULT ROUTE ROUTE_SANDBOX = 'https://sandbox.boletobancario.com/api-integration' ROUTE_SANDBOX_AUTORIZATION_SERVER = "https://sandbox.boletobancario.com/authorization-server/oauth/token" ROUTE_PRODUCAO = 'https://api.juno.com.br' ROUTE_PRODUCAO_AUTORIZATION_SERVER = "https://api.juno.com.br/authorization-server/oa...
user_input = input("Enter maximum number: ") number = int(user_input) spaces_amount = number // 2 f = open("my_tree.txt", "w") while (spaces_amount >= 0): if (spaces_amount*2 == number): spaces_amount -= 1 continue for j in range(spaces_amount): f.write(" ") # print(" ", sep="", end="") for ...
# Copyright (c) 2020. JetBrains s.r.o. # Use of this source code is governed by the MIT license that can be found in the LICENSE file. # from .corr import * # from .im import * # __all__ = (im.__all__ + # corr.__all__) # 'bistro' packages must be imported explicitly. __all__ = []
"""This class is a *very basic* way of building and manipulating CNF formulas and helps to output them in the DIMACS-format. This file is part of the concealSATgen project. Copyright (c) 2021 Jan-Hendrik Lorenz and Florian Wörz Institute of Theoretical Computer Science Ulm University, Germany """ class CNF(object): d...
if __name__ == "__main__": net_amount=0 while(True): person = input("Enter the amount that you want to Deposit/Withdral ? ") transaction = person.split(" ") type = transaction[0] amount =int( transaction[1]) if type =="D" or type =='d': net_amount += ...
# Put the token you got from https://discord.com/developers/applications/ here token = 'x' # Choose the prefix you'd like for your bot prefix = "?" # Copy your user id on Discord to set you as the owner of this bot myid = 0 # Change None to the id of your logschannel (if you want one) logschannelid = None # Change 0 to...
# course = "Python's course for Beginners" # print(course[0]) # print(course[-1]) # print(course[-2]) # print(course[0:3]) # print(course[0:]) # print(course[1:]) # print(course[:5]) # print(course[:]) # copy string # # another = course[:] # print(another) ####################################### # f...
class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # default load test intervals, in milliseconds INTERVAL_DEFAULT = 200 # load test speed, txs per second TXS_PER_SE...
# -*- coding: utf-8 -*- # @Time : 2020/1/23 13:38 # @Author : jwh5566 # @Email : jwh5566@aliyun.com # @File : if_example.py def check_if(): a = int(input("Enter a number \n")) if (a == 100): print("a is equal 100") else: print("a is not equal 100") return a
amount_of_dancers = int(input()) amount_of_points = float(input()) season = input() place = input() money_left = 0 charity = 0 dancers_point_won = amount_of_dancers * amount_of_points dancers_point_won_aboard = dancers_point_won + (dancers_point_won * 0.50) money_per_dancer = 0 if place == "Bulgaria": if season =...
nome = input("Qual seu nome: ") idade = int(input("Qual sua idade: ")) altura = float(input("Qual sua altura: ")) peso = float(input("Qual seu peso: ")) op= int(input("Estado civil:\n1.Casado\n2.Solteiro\n")) if op==1: op = True else: op = False eu = [nome, idade, altura, peso, op] for c in eu: print(c,...
#Example: grocery = 'Milk\nChicken\r\nBread\rButter' print(grocery.splitlines()) print(grocery.splitlines(True)) grocery = 'Milk Chicken Bread Butter' print(grocery.splitlines())
class Document: # general info about document class Info: def __init__(self): self.author = "unknown" self.producer = "unknown" self.subject = "unknown" self.title = "unknown" self.table_of_contents = [] def __init__(self, path: str, is_pd...
class Solution: def removeElement(self, nums: [int], val: int) -> int: i = 0 j = len(nums) while i < j: if nums[i] == val: nums[i] = nums[j - 1] j -= 1 else: i += 1 return i
class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: def dfs(graph, u, res): while(len(graph[u])): dfs(graph, graph[u].pop(), res) res.append(u) graph = defaultdict(list) res = [] for ticket in tickets: ...
SKULLTAG_FREQS = [ 0.14473691, 0.01147017, 0.00167522, 0.03831121, 0.00356579, 0.03811315, 0.00178254, 0.00199644, 0.00183511, 0.00225716, 0.00211240, 0.00308829, 0.00172852, 0.00186608, 0.00215921, 0.00168891, 0.00168603, 0.00218586, 0.00284414, 0.00161833, 0.00196043, 0.00151029, 0...
''' Description: X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rot...
# Python - 2.7.6 Test.describe('Basic tests') Test.assert_equals(logical_calc([True, False], 'AND'), False) Test.assert_equals(logical_calc([True, False], 'OR'), True) Test.assert_equals(logical_calc([True, False], 'XOR'), True) Test.assert_equals(logical_calc([True, True, False], 'AND'), False) Test.assert_equals(lo...
# -*- coding: utf-8 -*- class INITIALIZE(object): def __init__(self, ALPHANUMERIC=' ', NUMERIC=0): self.alphanumeric = ALPHANUMERIC self.numeric = NUMERIC def __call__(self, obj): self.initialize(obj) def initialize(self, obj): if isinstance(obj, dict): for k, ...
class User: userdetail = ["layersony","Samuel", "Maingi", "0796727706", "sm@gmail.com", "123456", '123456'] """ class for register user have to firstname, lastname, phonenumber, email, password, confirm password """ def __init__(self, username ,first_name, last_name, phone_number, email, password, con_pas...
#!/usr/bin/env python # Created by Bruce yuan on 18-1-31. # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def isPalindrome(self, head): """ 这题我想不到怎么 O(1) space :type head: ListNode :rtyp...
class Config: SECRET_KEY = 'hard to guess string' SQLALCHEMY_COMMIT_ON_TEARDOWN = True MAIL_SERVER = 'smtp.qq.com' MAIL_PORT = 465 MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_USERNAME = '536700549@qq.com' MAIL_PASSWORD = 'mystery123.' FLASKY_MAIL_SUBJECT_PREFIX = '[Flasky]' FLA...
""" This script learns about escape characters. Even more practice on the document string """ SPLIT_STRING = "This string has been \nsplit over\nseveral\nlines" print(SPLIT_STRING) TABBED_STRING = "1\t2\t3\t4\t5" print(TABBED_STRING) print('The pet shop owner said "No, no, \'e\'s uh,...he\'s resting".') # or print("T...
numeros = [1,3,6,9] while True: numero = int( input("Escribe un número del 0 al 9: ")) if numero >= 0 and numero <= 9: break if numero in numeros: print("El número", numero, "se encuentra en la lista", numeros) else: print("El número", numero, "no se encuentra en la lista", numeros)
n = int(input()) lst = [float('inf') for _ in range(n+1)] lst[1] = 0 for i in range(1,n): if 3*i<=n:lst[3*i]=min(lst[3*i],lst[i]+1) if 2*i<=n:lst[2*i]=min(lst[2*i],lst[i]+1) lst[i+1]=min(lst[i+1],lst[i]+1) print(lst[n])
Till=int(input("Enter the upper limit\n")) From=int(input("Enter the lower limit\n")) i=1 print("\n") while(From<=Till): if((From%4==0)and(From%100!=0))or(From%400==0): print(From) From+=1 input()
class BaseKeyMap(): """docstring for BaseKeyMap.""" def __init__(self, arg): self.arg = arg
class Square: piece = None promoting = False def __init__(self, promoting=False): self.promoting = promoting def set_piece(self, piece): self.piece = piece def remove_piece(self): self.piece = None def get_piece(self): return self.piece def is_empty(self)...
# -*- coding: utf-8 -*- # @Time : 2022/2/14 13:50 # @Author : ZhaoXiangPeng # @File : __init__.py class Monitor: def update(self): pass
print("Welcome to the tip calculator!!") total_bill = float(input("What was the total bill? ")) percent = int(input("What percentage tip you would like to give: 10%, 12%, or 15%? ")) people = int(input("How many people to split the bill? ")) pay = round((total_bill/people) + ((total_bill*percent)/100)/people,2) print(f...
''' Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a...
__version__ = "0.19.2" # NOQA if __name__ == "__main__": print(__version__)
# Copyright 2015 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 = [ 'depot_tools/bot_update', 'depot_tools/gclient', 'depot_tools/infra_paths', 'infra_checkout', 'recipe_engine/buildbucket', 'recipe_engin...
input_image = itk.imread('data/BrainProtonDensitySlice.png', itk.ctype('unsigned char')) isolated_connected = itk.IsolatedConnectedImageFilter.New(input_image) isolated_connected.SetSeed1([98, 112]) isolated_connected.SetSeed2([98, 136]) isolated_connected.SetUpperValueLimit( 245 ) isolated_connected.FindUpperThreshold...
number=0 list1=[] wnumber=0 lnumber=0 while number<7: winnumber=input().upper() number+=1 list1.append(winnumber) for i in list1: if 'W' == i: wnumber+=1 else: lnumber+=1 if wnumber>=5: print('1') elif wnumber<=4 and wnumber>=3: print('2') elif wnum...
#!/usr/bin/env python3 steps = 316 circ_buffer = [0] pos = 0 num = 0 for cnt in range(1, 50000001): pos = (pos + steps) % cnt if pos == 0: num = cnt pos += 1 print(num)
# 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 writing, software # distributed under th...
#Kunal Gautam #Codewars : @Kunalpod #Problem name: Sum of Odd Numbers #Problem level: 7 kyu def row_sum_odd_numbers(n): return n**3
# # @lc app=leetcode id=854 lang=python3 # # [854] K-Similar Strings # # @lc code=start class Solution: ''' 思路: 1. 此题最开始我想用DFS来实现,问题在于不一定能保证最短路径,超时 2. 使用BFS+MEMO来实现,通过记录看到过的替换字符串,避免重复计算 3. 在进行替换的时候只需要找到第一个不同的字符,同时找到后续所有满足j位置上不直接和Bj相等的元素生成替换字符串 4. 见到B被生成出来,即刻返回答案 5. BFS保证...
class Solution: def XXX(self, nums: List[int]) -> None: rgb = [0, 0, 0] for i in nums: rgb[i] += 1 nums[:rgb[0]] = [0 for _ in range(rgb[0])] nums[rgb[0]:rgb[0] + rgb[1]] = [1 for _ in range(rgb[1])] nums[rgb[0] + rgb[1]:] = [2 for _ in range(rgb[2])]
new_occupations = [ {'occupation': 'Språkstödjare', 'concept_id': '6gi1_3Ss_E8c'}, {'occupation': 'Elkraftingenjör', 'concept_id': '7Yn2_NLJ_oa2'}, {'occupation': 'Special Effects Artist/SFX Artist', 'concept_id': 'YBxu_4hV_dNB'}, {'occupation': 'Forskare, agronomi', 'concept_id': 'aeJj_czs_5Tq'}, {...
"""Constants used in the library.""" EMAIL_HEADER_SUBJECT = "email-header-subject" EMAIL_HEADER_DATE = "email-header-date"
def main(): # 単位ベクトル (一次元タプル) identity_vector = (1, 0, 0) print(identity_vector) # 単位行列 (多次元タプル) identity_matrix = ( (1, 0, 0), (0, 1, 0), (0, 0, 1), ) print(identity_matrix) if __name__ == '__main__': main()
v = float(input('Qual é a velocidade do carro? ')) if v > 80: print('MULTADO! Você excedeu o limite permitido que é de 80km/h!') m = (v - 80) * 7 print('Você deve pagar uma multa de R${:.2f}'.format(m)) else: print('Tenha um bom dia, dirija com segurança!')
num = int(input('Digite qualquer número:')) a = num - 1 s = num + 1 print('O antecessor de', num, 'é,', a, 'e seu sucessor é', s, '.')
def orelse(*iters): found = False for iter in iters: for elem in iter: found = True yield elem if found: break def extract(it, pred): extracted = [] def filtered_it(): nonlocal extracted for elem in it: if pred(elem): ...
# -*- coding: utf-8 -*- competidores, n_voltas = list(map(int, input().split())) competidor_1 = list(map(int, input().split())) melhor_tempo = sum(competidor_1) vencedor = 1 for i in range(1, competidores): competidor_i = list(map(int, input().split())) tempo_i = sum(competidor_i) if (tempo_i < melhor_tem...
CURSOR_TO_BOTTOM = 0 CURSOR_TO_CENTER = 1 CURSOR_TO_TOP = 2 VIEWPORT_LINE_UP = 3 VIEWPORT_LINE_DOWN = 4 HERE = 0 ELSEWHERE = 1 class ViewportNote(object): pass class ViewportContextChange(ViewportNote): def __init__(self, context, change_source): """`change_source` is either HERE or ELSEWHERE; the...
#-*- coding: utf-8 -*- swiftsure_item = { "description": u"Земля для військовослужбовців", "classification": { "scheme": u"CPV", "id": u"66113000-5", "description": u"Земельні ділянки" }, "additionalClassifications": [{ "scheme": "CAV", "id": "39513200-3", ...