content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python3
inp = "01111010110010011"
def solve(target_len):
# translate input into numbers
state = [int(c) for c in inp]
# generate data
while len(state) < target_len:
state += [0] + [1-i for i in state[::-1]]
# compute checksujm
state = state[:target_len]
while len(s... |
class Solution(object):
def countBinarySubstrings(self, s):
"""
:type s: str
:rtype: int
"""
N = len(s)
curlen = 1
res = []
for i in range(1, N):
if s[i] == s[i - 1]:
curlen += 1
else:
res.append(... |
# Data Center URL
DATA_FILES_BASE_URL = "https://www.meps.ahrq.gov/mepsweb/data_files/pufs/"
DATA_STATS_BASE_URL = "https://www.meps.ahrq.gov/data_stats/download_data/pufs/"
# Base Year List
DATA_FILES_YEARS = [
2018,
2017,
2016,
2015,
2014,
2013,
2012,
2011,
2010,
2009,
200... |
class CompositorNodeFlip:
axis = None
def update(self):
pass
|
"""utility functions manipulating object data attributes"""
def get_params(imputer):
"""return general parameters of an imputer object
input
an imputer obj
output:
a dict of parameters"""
return {
'max_iter' : imputer.max_iter,
'init_imp' : imputer.init_i... |
def add_native_methods(clazz):
def flattenAlternative__com_sun_org_apache_xalan_internal_xsltc_compiler_Pattern__com_sun_org_apache_xalan_internal_xsltc_compiler_Template__java_util_Map_java_lang_String__com_sun_org_apache_xalan_internal_xsltc_compiler_Key___(a0, a1, a2, a3, a4):
raise NotImplementedError()... |
"""
8-9 code
"""
# c = 50
# def add(x,y):
# c = x + y
# print(c)
#
#
# add(1, 2)
# print(c)
# c = 10
# def demo():
# print(c)
#
#
# demo()
# def demo():
# c = 50
# for i in range(0,9):
# a = 'a'
# c += 1
# print(c)
# print(a)
#
#
# demo()
c = 1
def func1():
c = 2... |
entrada = str(input()).split(' ')
p = int(entrada[0])
j1 = int(entrada[1])
j2 = int(entrada[2])
r = int(entrada[3])
a = int(entrada[4])
if r == 0 and a == 0:
if (j1 + j2) % 2 == 0 and p == 1: print('Jogador 1 ganha!')
elif (j1 + j2) % 2 != 0 and p == 0: print('Jogador 1 ganha!')
else: print('Jogador 2 ganha... |
with open("cells_to_link.txt", "r") as f:
lines = f.readlines()
def formTuples(x):
x = x.split()
return zip(x[0::2], x[1::2])
tuples_by_line = map(formTuples, lines)
vba = """Public loc_map As Collection
Private Sub Workbook_Open()
Set loc_map = New Collection"""
for index, tuples in enumerate(tu... |
class CatalogPage:
"""
Class for page in Catalog tree
"""
name = ''
url = ''
is_index = False
parent = None
subpages_cache = []
def get_subpages_internal(self):
return []
def get_subpages(self):
if not self.subpages_cache:
subpages_cache = self... |
# -*- coding:utf-8 -*-
#https://leetcode.com/problems/valid-parentheses/description/
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for ch in s:
if ch == '(':
stack.append(')')
... |
# -*- coding: utf-8 -*-
class VariableTypeAlreadyRegistered(Exception):
pass
class InvalidType(Exception):
pass
|
"""
Operadores Lógicos - Aula 4
and = comparação entre dois argumentos e ambas precisam ser verdadeiras (Verdadeiro + Verdadeiro = True
or = comparação entre dois argumentos e uma delas precisa ser verdadeira (Verdadeiro + Falso ou vice-versa = True
not = inverte o valor do argumento ou expressão (Verdadeiro1 + Fa... |
# Find Pivot Index
'''
Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index.
If no such index exists, we should re... |
#!/usr/local/bin/python3.5 -u
answer = 42
print(answer)
|
"""
from datetime import datetime
from django.db import models
from workflow.models import Program, ProjectAgreement
from .service import StartEndDates
class TrainingAttendance(StartEndDates):
training_name = models.CharField(max_length=255)
program = models.ForeignKey(
Program, null=True, blank=True, ... |
#!/bin/python3
h = list(map(int, input().strip().split(' ')))
word = input().strip()
max_height = 0
for w in word:
i = ord(w)-97
max_height = max(max_height, h[i])
print (len(word)*max_height)
|
def hangman(word, letters):
result = 0
a = 0
for item in letters:
if 6 <= a:
return False
b = word.count(item)
if 0 == b:
a += 1
else:
result += b
return len(word) == result
|
class AreaKnowledge:
def __init__(self, text=None):
self.text = text
self._peoples_names = set()
self.peoples_info = list()
def set_text(self, text):
self.text = text
def update_people_photos(self, persons):
for person in persons:
self.update_people_phot... |
class PTestException(Exception):
pass
class ScreenshotError(PTestException):
pass
|
# -*- coding: utf-8 -*-
"""
smallparts.text
text subpackage
"""
# vim:fileencoding=utf-8 autoindent ts=4 sw=4 sts=4 expandtab:
|
#
# PySNMP MIB module BFD-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BFD-STD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:46 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, 0... |
class Solution:
def judgeCircle(self, moves: str) -> bool:
x_axis = y_axis = 0
for move in moves:
if move == "U":
y_axis += 1
elif move == "D":
y_axis -= 1
elif move == "R":
x_axis += 1
elif move == "L":
... |
with open("EX10.txt","r") as fp:
words = 0
for data in fp:
lines=data.split()
for line in lines:
words += 1
print("Total No.of Words:",words) |
"""
Hello, World!
"""
# 1. Print a string
print("This line will be printed.")
# 2. Indentation for blocks (four spaces)
x = 1
if x == 1:
# indented four spaces
print("x is 1.")
|
__author__ = 'zoulida'
class people(object):
def __new__(cls, *args, **kargs):
return super(people, cls).__new__(cls)
def __init__(self, name):
self.name = name
def talk(self):
print("hello,I am %s" % self.name)
class student(people):
def __new__(cls, *args, **kargs):
... |
#Crie um pgm que leia varios numeros inteiros pelo teclado. No final da execução, mostre a média entre todos os valores e qual foi o maior e menor valores lidos. O pgm deve perguntar ao usr se ele quer ou não continuar a digitar valores.
continuar = 's'
contador = soma = media = maior = menor = 0
while continuar in 's'... |
nombres=[]
sueldo=[]
totalsueldos=[]
for x in range(3):
nombres.append(input("Cual es tu nombre? "))
mes1=int(input("Cual fue tu sueldo de Junio? "))
mes2=int(input("Cual fue tu sueldo de Julio? "))
mes3=int(input("Cual fue tu sueldo de Agosto? "))
sueldo.append([mes1,mes2,mes3])
totalsueldos.a... |
# contains hyperparameters for our seq2seq model. you can add some more
config = {
'batch_size': 200,
'max_vocab_size': 20000,
'max_seq_len': 26, # decided based on the sentence length distribution of amazon corpus
'embedding_dim': 100, # we had trained a 100-dim w2v vecs in tut 1
}
|
class Solution:
def isValid(self, s: str) -> bool:
stack = []
other_half = {")": "(", "]": "[", "}": "{"}
for char in s:
if char in "{[(":
stack.append(char)
elif char in ")]}" and stack and stack[-1] == other_half[char]:
stack.pop()
... |
skills = [
{
"id": "0001",
"name": "Liver of Steel",
"type": "Passive",
"isPermable": False,
"effects": {"maximumInebriety": "+5"},
},
{"id": "0002", "name": "Chronic Indigestion", "type": "Combat", "mpCost": 5},
{
"id": "0003",
"name": "The Smile ... |
load("@bazel_gazelle//:deps.bzl", "go_repository")
def go_repositories():
go_repository(
name = "co_honnef_go_tools",
build_extra_args = ["-exclude=**/testdata", "-exclude=go/packages/packagestest"],
importpath = "honnef.co/go/tools",
sum = "h1:MNh1AVMyVX23VUHE2O27jm6lNj3vjO5DexS4A1... |
def main(shot_name):
# load air shot behind Microbone to Getter NP-10H
info('extracting {}'.format(shot_name))
#for testing just sleep a few seconds
#sleep(5)
# this action blocks until completed
extract_pipette(shot_name)
#isolate microbone
close(description='Microbone to Turbo')
... |
# Enquete: Utilize o codigo em favorite_language.py
# Crie uma lista de pessoas que devam participar da enquete sobre linguagem favorita. Inclua alguns nomes que ja' estejam no dicionario e outros que nao estao.
# Percorra a lista de pessoas que devem participar da enquete. Se elas ja tiverem respondido `a enquete, mos... |
def reverse_filter( s ):
return s[ ::-1 ]
def string_trim_upper( value ):
return value.strip().upper()
def string_trim_lower( value ):
return value.strip().lower()
def datetimeformat( value, format='%H:%M / %d-%m-%Y' ):
return value.strftime( format )
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def bazel_sonarqube_repositories(
sonar_scanner_cli_version = "4.5.0.2216",
sonar_scanner_cli_sha256 = "a271a933d14da6e8705d58996d30afd0b4afc93c0bfe957eb377bed808c4fa89"):
http_archive(
name = "org_sonarsource_scanner_cli... |
rawInstructions = [line.rstrip() for line in open("day12_input.txt")]
instructions=[]
for line in rawInstructions:
instructions.append([line[0], int(line[1:])])
orientations = [[0,1], [1,0], [0,-1], [-1,0]]
position = [0, 0, 1]
def makeMove1(position, instruction):
x = position[0]
y = position[1... |
class DebugHeaders(object):
# List of headers we want to display
header_filter = (
'CONTENT_TYPE',
'HTTP_ACCEPT',
'HTTP_ACCEPT_CHARSET',
'HTTP_ACCEPT_ENCODING',
'HTTP_ACCEPT_LANGUAGE',
'HTTP_CACHE_CONTROL',
'HTTP_CONNECTION',
'HTTP_HOST',
... |
"""
Demonstration #2
Given a non-empty array of integers `nums`, every element appears twice except except for one. Write a function that finds the element that only appears once.
Examples:
- single_number([3,3,2]) -> 2
- single_number([5,2,3,2,3]) -> 5
- single_number([10]) -> 10
"""
def single_number(nums):
... |
class Solution:
def plusOne(self, digits: 'List[int]') -> 'List[int]':
fl = 1
for i in range(len(digits)-1,-1,-1):
if digits[i] == 9 and fl == 1:
fl = 1
digits[i] = 0
else:
digits[i] += 1
fl = 0
b... |
dictionary = {
"CSS": "101",
"Python": ["101", "201", "301"]
}
print(dictionary.get("CSS", None))
print(dictionary.get("HTML", None)) |
# edit the following parameters which control the benchmark
mincpus = 16
maxcpus = 128
nsteps_cpus = 6
multigpu = (1,2,3,)
multithread = (1,2,4,8)
multithread = (8,)
multithread_gpu = (42,)
if (maxcpus < max(multigpu)):
raise ValueError('increase the number of processors')
systems = ['interface','lj']
runconfig ... |
''' This file is a lookup table for The OpenQASM instructions '''
''' Ref: https://github.com/qevedo/openqasm/tree/master/src/libs '''
''' Tutorial: https://quantum-computing.ibm.com/docs/iqx/operations-glossary '''
''' TODO:
1. we should have a simple exclude/include mechanism for this colleciton so that o... |
values = {
frozenset(("hardQuotaSize=1", "id=1", "hardQuotaUnit=TB")): {
"status_code": "200",
"text": {
"responseData": {},
"responseHeader": {
"now": 1492551097041,
"requestId": "WPaFuAoQgF4AADVcf4kAAAAz",
"status": "ok",
... |
def rangoEdad(edad):
if edad <18:
return 'menor'
elif edad <65:
return 'mayor'
elif edad <=120:
return 'jubilado'
def catalogoPorEdad(condicion):
if condicion == 'menor':
return catalogoParaMenor()
elif condicion == 'mayor':
return catalogoParaMayor()
els... |
#
# Copyright (c) 2011 Daniel Truemper truemped@googlemail.com
#
# sink.py 02-Feb-2011
#
# 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
#
# Unl... |
input_file = __file__.split("/")
input_file[-1] = "input.txt"
with open("/".join(input_file)) as f:
actions = [entry.strip().split() for entry in f]
curr_aim = curr_depth = curr_horiz = 0
for direction, num in actions:
if direction in {"up", "down"}:
aim_change = int(num) if direction == "down" else... |
__author__ = 'hvishwanath'
class CAMPModel(object):
def __init__(self):
pass
class Artifact(CAMPModel):
def __init__(self, atype, content, requirements):
self.type = atype
self.content = content
self.requirements = requirements
@classmethod
def create_from_dict(cls, d... |
# To merge 2 array into a third array.
arr1 = []
arr2 = []
arr = []
n=int(input())
for i in range(0,n):
arr1.append(int(input()))
m=int(input())
for i in range(0,m):
arr2.append(int(input()))
"""
for i in range(0,n):
arr.append(arr1[i])
for i in range(0,m):
arr.append(arr2[i])
"""
arr = arr1 + ... |
#
# PySNMP MIB module Juniper-PPPOE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-PPPOE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:53:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
n=int(input())
s=[str(input()) for a in range(n)]
for i in range(n):
c=0
for j in range(len(s[i])):
if s[i][j] == "W":
for k in range(max(0,j-2),min(len(s[i]),j+2)):
if s[i][k]=="B":
c+=1
break
print(c)
|
t = int(input())
for _ in range(t):
n = int(input())
l1 = set(list(map(int,input().split())))
l2 = set(list(map(int,input().split())))
if l1==l2:
print(1)
else:
print(0) |
"""
sentry_twilio
~~~~~~~~~~~~~
:copyright: (c) 2012 by Matt Robenolt.
:license: BSD, see LICENSE for more details.
"""
try:
VERSION = __import__('pkg_resources') \
.get_distribution('sentry-twilio').version
except Exception as e:
VERSION = 'unknown'
|
#/* *** ODSATag: Sequential *** */
# Return the position of an element in a list.
# If the element is not found, return -1.
def sequentialSearch(elements, e):
for i in range(len(elements)): # For each element
if elements[i] == e: # if we found it
return i # return this po... |
##############################################################################
# 01: Is Unique?
##############################################################################
def caseAndSpaceTreat(inputString, caseSensitive=True, spaces=True):
'''
Returns a lowercase string if case insensitive, and removes sp... |
d = 3255
f = d // 15-17
z = d // (f*5)
d = d % (z+1)
print("d = ", d) |
"""The objective function to optimize using the GSO algorithm"""
class ObjectiveFunction(object):
"""Objective functions interface"""
def __call__(self, coordinates):
raise NotImplementedError()
|
def title_case(text):
"""
Funkcija pārveido tekstu "virsrakstu formātā" -
visi vārdi sākas ar lielo burtu.
Arguments:
x {string} -- pārveidojamais teksts
Returns:
string -- pārveidotais teksts
"""
return text.capitalize()
|
"""
Escopo de Variáveis
Dois casos de escopo:
1 - Variáveis globais:
- Variáveis globais são reconhecidas, ou seja, seu escopo compreende
, todo o programa.
2 - Variáveis locais:
- Variáveis locais são reconhecidas apenas no bloco onde foram declaradas,
ou seja, seu escopo está limitado ao bloco onde... |
message = "o"
def scope():
global message
message = "p"
scope()
print(message)
|
# This file is part of the faebryk project
# SPDX-License-Identifier: MIT
class lazy:
def __init__(self, expr):
self.expr = expr
def __str__(self):
return str(self.expr())
def __repr__(self):
return repr(self.expr())
def kw2dict(**kw):
return dict(kw)
class hashable_dict:
... |
def Sum_Divisors(x):
s = 0
for i in range(1,(x // 2) + 1):
if x % i == 0:
s += i
return s
def Amicable(x,y):
if x!=y:
if Sum_Divisors(x) == y and Sum_Divisors(y) == x :
return True
return False
def Sum_Amicable():
l=[]
for i in range(284,10000):
... |
def is_odd(n):
'''Return True if the number is odd and False otherwise.'''
if n % 2 != 0:
odd = True
else:
odd = False
return odd
def main():
'''Define main function.'''
# Prompt the user for a number
number = float(input('Please enter a number: '))
... |
def ans(x):
if len(x) == 2 or len(x) == 10:
return False
return True
|
# Autogenerated config.py
# Documentation:
# qute://help/configuring.html
# qute://help/settings.html
# Uncomment this to still load settings configured via autoconfig.yml
config.load_autoconfig()
config.source('colors_qutebrowser.py')
|
'''
there are two strings at same lenght
s1 = ABCD
s2 = ABDC
lets say we delete C
1. ABD
we delete the 3th char
2. ABD
we delete the 4th char
or we delete D
1. ABC
we delete the 4th char
2. ABC
we delete the 3th char
in both outcomes we get the same result and same length from two strings,
in both exampl... |
L, R = map(int, input().split())
L -= 1
R -= 1
S = input()
print(S[:L] + ''.join(reversed(S[L:R+1])) + S[R+1:len(S)]) |
# https://codeforces.com/problemset/problem/339/A
s = [x for x in input().split("+")]
if len(s) == 1:
print(s[0])
else:
s.sort()
print("+".join(s))
|
GIT_BRANCH_MASTER = "master"
GIT_BRANCH_MAIN = "main"
GITHUB_PUBLIC_DOMAIN_NAME = "github.com"
KNOWN_DEFAULT_BRANCHES = (GIT_BRANCH_MASTER, GIT_BRANCH_MAIN)
|
#
# PySNMP MIB module AC-V5-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AC-V5-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:54:49 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, 09:23... |
"""
You are playing a simplified Pacman game. You start at the point (0, 0), and your destination is (target[0], target[1]). There are several ghosts on the map, the i-th ghost starts at (ghosts[i][0], ghosts[i][1]).
Each turn, you and all ghosts simultaneously *may* move in one of 4 cardinal directions: north, eas... |
# coding=utf-8
"""
백준 1629번 : 곱셈
분할 정복 이용하기
"""
a, b, c = map(int, input().split())
def power(a, b):
if b == 1:
return a % c
temp = power(a, b // 2)
if b % 2 == 0:
# 짝수인 경우
return (temp * temp) % c
else:
return (temp * temp * a) % c
print(power(a, b))
|
# Name:COLLIN FRANCE
# Date:JULY 11 17
# proj02: sum
# Write a program that prompts the user to enter numbers, one per line,
# ending with a line containing 0, and keep a running sum of the numbers.
# Only print out the sum after all the numbers are entered
# (at least in your final version). Each time you read in a ... |
#cons(a,b) constructs a pair, and car(pair) returns the first and cdr(pair) returns the last element of the pair.
#For example , car(cons(3,4)) returns 3, and cdr(cons(3,4)) returns 4.
#Given this implementation of cons:
'''def cons(a,b):
def pair(f):
return f(a,b)
return pair()
'''
#Implement... |
def rotateImage(a):
w = len(a)
h = w
img = [0] * h
for col in range(h):
img_row = [0] * w
for row in range(w):
img_row[h - row - 1] = a[row][col]
img[col] = img_row
return img
|
"""
def strange_counter(t):
cur_start = 3
counter = 3
for i in range(1, t):
counter -= 1
if counter == 0:
cur_start *= 2
counter = cur_start
return counter
"""
def strange_counter(t):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/strange-code/... |
def ajuda(msg):
help(msg)
n=str(input('Digite um comando para ver a ajuda: '))
ajuda(n) |
def show_magicians(wizar): #lista original que se estara modificando
for magician in wizar:
print(magician)
def make_great(wizar): #en esta funcion agregaremos "great" al inicio de los nombre de los wizar en la lista
great_wizar = [] #se crea la lista de grean wizar
# while wizar:
# magician... |
def tower_of_hanoi(num_of_disks, mv_from, mv_to, tmp_bar):
if num_of_disks == 1:
print(f'Move disk 1 from {mv_from} to {mv_to}')
return
tower_of_hanoi(num_of_disks - 1, mv_from, tmp_bar, mv_to)
print(f'Move disk {num_of_disks} from {mv_from} to {mv_to}')
tower_of_hanoi(num_of_disks - 1,... |
# https://www.codewars.com/kata/5a2d70a6f28b821ab4000004/
'''
Instructions :
This kata is part of the collection Mary's Puzzle Books.
Zero Terminated Sum
Mary has another puzzle book, and it's up to you to help her out! This book is filled with zero-terminated substrings, and you have to find the substring with the... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
@author: syenpark
Python Version: 3.6
"""
def lowest_payment(balance, annual_interest_rate):
'''
inputs
returns lowest payment
'''
epsilon = 0.01
lower = balance / 12.0
upper = (balance * (1 + annual_interest_rate / 12.0)**12) / 12.0
def ... |
class PPO:
def get_specs(env=None):
specs = {
"type": "ppo_agent",
"states_preprocessing": {
"type":"flatten"
},
"subsampling_fraction": 0.1,
"optimization_steps": 50,
"entropy_regularization": 0.01,
"gae_... |
class Solution:
# This will technically work, but it's slow as all get-out.
# Worst case would be O(n^2) as you have to traverse your
# entire list of n numbers k times, which if k is 1 less
# than the length of nums, is effectively n.
def rotate(self, nums, k):
start = end = len(nums)
... |
ACCESS_DENIED = "access_denied"
INVALID_CLIENT = "invalid_client"
INVALID_GRANT = "invalid_grant"
INVALID_REQUEST = "invalid_request"
INVALID_SCOPE = "invalid_scope"
INVALID_STATE = "invalid_state"
INVALID_RESPONSE = "invalid_response"
SERVER_ERROR = "server_error"
TEMPORARILY_UNAVAILABLE = "temporarily_unavailable"
UN... |
def sum(n):
return n * (n + 1) // 2
print(sum(46341))
|
pessoas = {'nome':'Gilson', 'Idade':55, 'Sexo': 'M'}
print(pessoas)
print(pessoas['nome'])
print(pessoas['Idade'])
print(f'{pessoas["nome"]}')
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
for k in pessoas.values():
print(k)
for k ,v in pessoas.items():
print(f'{k} = {v}')
brasil = []
es... |
# simple inheritance
# base class
class student:
def __init__(self, name, age):
self.name = name
self.age = age
def getdata(self):
self.name = input('enter name')
self.age = input('enter age')
def putdata(self):
print(self.name, self.age)
# Derived class or sub... |
#!/user/bin/env python
'''rWork.py:
This filter returns True if the r_work value for this structure is within the
specified range
'''
__author__ = "Mars (Shih-Cheng) Huang"
__maintainer__ = "Mars (Shih-Cheng) Huang"
__email__ = "marshuang80@gmail.com"
__version__ = "0.2.0"
__status__ = "Done"
class RWork(object):
... |
#%%
# nums = [-1,2,1,-4]
# target = 1
# nums = [0, 1, 2]
# target = 0
nums = [1, 1, 1, 0]
target = 100
nums = [0, 2, 1, -3, -5]
target = 1
def threeSumClosest(nums: list, target: int)->int:
nums.sort()
ptrLow = 0
ptrHigh = len(nums) - 1
bestEstimate = 10e10
#remember that we are dealing with thre... |
"""
None
"""
class Solution:
def isOneEditDistance(self, s: str, t: str) -> bool:
if abs(len(s) - len(t)) > 1:
return False
if len(s) < len(t):
s, t = t, s
i, j = 0, 0
seen_change = False
while i < len(s) and j < len(t):
if s[i] != t[j]:... |
# md5 : 696999570c6da88ed87e96e1014f4fd0
# sha1 : bbf782f04e4b5dafbfe1afef6b08ab08a1777852
# sha256 : 8d6c894aeb73da24ba8c8af002f7299211c23a616cccf18443c6f38b43c33b3e
ord_names = {
102: b'ChooseColorA',
103: b'ChooseColorW',
104: b'ChooseFontA',
105: b'ChooseFontW',
106: b'CommDlgExtendedError',
... |
# Copyright 2014 The Bazel Authors. All rights reserved.
#
# 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 la... |
first = int(input())
i = 0
list = []
outputval = 0
if(first>0 and first<11):
while(i<first):
i+=1
f, s = map(int, input().split())
list.append(int(s/f))
if (min(list)<0):
print(0)
else:
print(min(list)) |
# Simple recursion program in python
def fun(n):
""" This method prints the number in reverse order n to 1"""
if n==0:
return
print(n)
fun(n-1)
if __name__ == '__main__':
n = int(input("Enter Number:"))
fun(n) |
n = str(input('Digite um número entre 0 e 9999: '))
print('Analisando o número...')
n = n.split()
print(f'Unidade: {(n[0][3])}')
print(f'Dezena: {(n[0][2])}')
print(f'Centena: {(n[0][1])}')
print(f'Milhar: {(n[0][0])}')
|
def remplir_sac(poids_max, liste_objets):
liste_choisis = []
poids_sac = 0
i = 0
i_max = len(liste_objets) - 1
while poids_sac < poids_max and i <= i_max and liste_objets != []:
if poids_sac + liste_objets[i][1] <= poids_max:
liste_choisis.append(liste_objets[i])
poi... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python
# encoding: utf-8
'''
#-------------------------------------------------------------------#
# CONFIDENTIAL --- CUSTOM STUDIOS #
#-------------------------------------------------------------------#
# ... |
class Solution:
# O(n^2) time | O(1) space - where n is the length of the input array
def maxDistance(self, colors: List[int]) -> int:
maxDist = 0
for i in range(len(colors)):
for j in range(i, len(colors)):
if colors[i] != colors[j]:
maxDist = max... |
'''
@File : init.py
@Author : Zehong Ma
@Version : 1.0
@Contact : zehongma@qq.com
@Desc : None
'''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.