content stringlengths 7 1.05M |
|---|
def even_odd(*args):
if "even" in args:
return list(filter(lambda x: x % 2 == 0, [args[i] for i in range(len(args) - 1)]))
return list(filter(lambda x: x % 2 == 1, [args[i] for i in range(len(args) - 1)]))
# print(even_odd(1, 2, 3, 4, 5, 6, "even"))
# print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "od... |
# swift_build_support/build_graph.py ----------------------------*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.tx... |
pkgname = "python-sphinxcontrib-serializinghtml"
pkgver = "1.1.5"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools"]
checkdepends = ["python-sphinx"]
depends = ["python"]
pkgdesc = "Sphinx extension which outputs serialized HTML document"
maintainer = "q66 <q66@chimera-linux.org>"
license ... |
"""
MIT License
Copyright (c) 2019 Michael Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publis... |
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
index_stack = []
if len(s) <= 1:
return 0
dp = [0] * len(s)
for i in range(len(s)):
if s[i] == '(':
dp[i] ... |
lis = [1, 2, 3, 4, 2, 6, 7, 8, 9]
without_duplicates = []
ok = True
for i in range(0,len(lis)):
if lis[i] in without_duplicates:
ok = False
break
else:
without_duplicates.append(lis[i])
if ok:
print("There are no duplicates")
else:
print("Things are not ok") |
# model settings
model = dict(
type='CenterNet2',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg=dict(... |
""" Constants file for Auth0's seed project
"""
ACCESS_TOKEN_KEY = 'access_token'
API_ID = 'API_ID'
APP_JSON_KEY = 'application/json'
AUTH0_CLIENT_ID = 'uL61M0bVYCd72QwsrvGioOHotcRlqw35'
AUTH0_CLIENT_SECRET = '3dtMdBV5P4jtohyJCtwk0P0HBoOk_hv_oHYzEkYtHCOWjFR59MBBphTPIYf6tucz'
# AUTH0_CALLBACK_URL = 'http://127.0.0.1:500... |
# Copyright 2014 0xc0170
#
# 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, soft... |
class Escritor:
def __init__(self, nome):
self.nome = nome
self.ferramenta = None
class Caneta:
def __init__(self, marca):
self.marca = marca
self.escrevendo = False
def escrever(self, nome=None):
if nome == None:
self.escrevendo = True
prin... |
aux = 0
num = int(input("Ingrese un numero entero positivo: "))
opc = int(input("1- Sumatoria, 2-Factorial: "))
if opc == 1:
for x in range(0,num+1):
aux = aux + x
print (aux)
elif opc == 2:
if num == 0:
print("1")
elif num > 0:
aux = 1
for x in range(1,num+1):
aux = aux*x
print (aux)
elif num < 0:
... |
#Give a single command that computes the sum from Exercise R-1.6,relying
#on Python's comprehension syntax and the built-in sum function
n = int(input('please input an positive integer:'))
result = sum(i**2 for i in range(1,n) if i&1!=0)
print(result) |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/189/A
#n分为a,b,c三个长度; 求最常分法.
#典型DP: 递归/记忆化搜索容易些? 或者用更适合py的构建?
#或许用bfs/BFS? 但和bfs相比,DP只需一层层记录,所以还是更像DP
n,a,b,c = list(map(int,input().split())) #<4000
ss = set([a,b,c])
ii = 0
while min(ss)<n:
l = list(ss)
ss = set([i+j for i in l... |
# coding=utf-8
"""
Exceptions for AVWX package
"""
class AVWXError(Exception):
"""Base AVWX exception"""
class AVWXRequestFailedError(AVWXError):
"""Raised when request failed"""
class StationNotFound(AVWXError):
"""
Raised when a ICAO station isn't found
"""
def __init__(self, icao: str)... |
# Aula 24 - Desempacotamento de listas em Python
lista = ['Luiz', 'João', 'Maria', 'Marcos', 'Julia']
n1, n2, n3, n4, n5 = lista # A quantidade variveis tem que ser igual ao quantidad de elementos
print(n2)
v1, *outraLista, ultimoLista = lista # O restante dos valores da lista vai para uma nova lista, precisa us... |
"""https://www.educative.io/courses/grokking-the-coding-interview/xl2g3vxrMq3
"""
def find_string_anagrams(input_str: str, pattern: str) -> list[str]:
"""Find all anagrams of a specified pattern in the given string.
Anagram is actually a Permutation of a string.
For example, “abc” has the following six ... |
def twoSum(self, n: List[int], target: int) -> List[int]:
N = len(n)
l = 0
r = N-1
while l<r:
s = n[l] + n[r]
if s == target:
return [l+1,r+1]
elif s < target:
l += 1
else:
r -= 1
|
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License,
# attached with Common Clause Condition 1.0, found in the LICENSES directory.
def __bytes2ul(b):
return int.from_bytes(b, byteorder='little', signed=False)
def mmh2(bstr, seed=0xc70f6907, signed=True)... |
"""
author : Ali Emre SAVAS
Link : https://www.hackerrank.com/challenges/py-check-subset/problem
"""
if __name__ == "__main__":
for _ in range(int(input())):
numberOfA = int(input())
setA = set(map(int, input().split()))
numberOfA = int(input())
setB = set(map(int, input().sp... |
def init(n,m):
state_initial = [n] + [1] * m
state_current = state_initial
state_final = [n] * (m + 1)
return state_initial, state_current, state_final
def valid_transition(currentState, tower_i, tower_j):
k = 0
t = 0
if tower_i == tower_j: # same tower not allowed
return False
... |
class Vector:
'''Vector class modeling Vectors'''
def __init__(self,initialise_param):
'''constructor:-create list of num length'''
if isinstance(initialise_param,(Vector,list)):
self._coords=[i for i in initialise_param]
elif isinstance(initialise_param,(int)):
... |
def createList():
fruitsList = ["apple", "banana", "cherry"]
print("Fruit List : ", fruitsList)
# Iterate the list of fruits
for i in fruitsList:
print("Value : ", i)
# Add to fruits list
fruitsList.append("kiwi")
fruitsList.append("Grape")
fruitsList.append("Orange")
... |
# Crie um programa que leia dois números e mostre a soma entre eles.
num1 = int(input('Digite o primeiro valor: '))
num2 = int(input('Digite o segundo valor: '))
soma = num1 + num2
print('O resultado da soma entre {} e {} é: {}'.format(num1, num2, soma))
|
class SlopeGradient:
def __init__(self, rightSteps, downSteps):
self.rightSteps = rightSteps
self.downSteps = downSteps
|
S = input()
is_no = False
for s in S:
if S.count(s) != 2:
is_no = True
break
if is_no:
print("No")
else:
print("Yes")
|
class WeekSchedule():
def __init__(self, dates=[], codes=[]):
self.weeknum = 0
self.dates = dates
self.codes = codes |
a=10
print(type(a))
a='Python'
print(type(a))
a=False
print(type(a)) |
''' Code for training and evaluating Self-Explaining Neural Networks.
Copyright (C) 2018 David Alvarez-Melis <dalvmel@mit.edu>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of ... |
# 1. Реализовать класс «Дата», функция-конструктор которого должна принимать
# дату в виде строки формата «день-месяц-год». В рамках класса реализовать
# два метода. Первый, с декоратором @classmethod, должен извлекать число,
# месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором
# @staticmethod, д... |
nume1 = "Gabinete_Cooler_master"
nume2 = "Geforce_RTX_2080TI"
nume3 = (input("Digite uma peça"))
nume4 = (input("Digite uma peça"))
Carrinho = [nume1,nume2,nume3,nume4]
print(Carrinho)
Remove = int(input("Oh não! os preços estão altos demais!, deseja remover o gabinete e a placa de video? 1- sim 2-não"))
if Remove is 1... |
load("@io_bazel_rules_docker//container:container.bzl", "container_pull")
def image_deps():
container_pull(
name = "python3.7",
digest = "sha256:57c7d7161fdaa79b61f107b8a480c50657d64dca37295d67db2f675abe38b45a",
registry = "index.docker.io",
repository = "library/python",
ta... |
#!/usr/bin/python
ADMIN_SCHEMA_FOLDER = "admin/schemas/"
ADMIN_SCHEMA_CHAR_SEPARATOR = "_"
ADD_COIN_METHOD = "addcoin"
GET_COIN_METHOD = "getcoin"
REMOVE_COIN_METHOD = "removecoin"
UPDATE_COIN_METHOD = "updatecoin"
|
class HandledEventArgs(EventArgs):
"""
Provides data for events that can be handled completely in an event handler.
HandledEventArgs()
HandledEventArgs(defaultHandledValue: bool)
"""
@staticmethod
def __new__(self,defaultHandledValue=None):
"""
__new__(cls: type)
__new__(cls: type,defa... |
# Ler dois números inteiros e compare eles
# mostrando na tela a mensagem:
# - o primeiro valor é maior
# - o segundo valor é maior
# não existe valor maior, os dois são iguais
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
if n1 > n2:
print('O primeiro número é maior')... |
exp_name = 'glean_ffhq_16x'
scale = 16
# model settings
model = dict(
type='GLEAN',
generator=dict(
type='GLEANStyleGANv2',
in_size=64,
out_size=1024,
style_channels=512,
pretrained=dict(
ckpt_path='http://download.openmmlab.com/mmgen/stylegan2/'
... |
#1 Create countries dictionary
countries = __________________
#2 Print out the capital of egypt
print(__________________) |
# -*- coding:utf-8 -*-
__author__ = [
'wufang'
]
|
"""Farmer classes.
:author: Someone
:email: someone@pnnl.gov
License: BSD 2-Clause, see LICENSE and DISCLAIMER files
"""
class FarmerOne:
"""This is the first Farmer agent.
:param age: Age of farmer
:type age: int
CLASS ATTRIBUTES:
:param AGE_M... |
# ------------------------------------------------------------------------------
# Access to the CodeHawk Binary Analyzer Analysis Results
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
#
#... |
"""hxlm.core.urn
Author: 2021, Emerson Rocha (Etica.AI) <rocha@ieee.org>
License: Public Domain / BSD Zero Clause License
SPDX-License-Identifier: Unlicense OR 0BSD
"""
# __all__ = [
# 'get_entrypoint_type'
# ]
# from hxlm.core.io.util import ( # noqa
# get_entrypoint_type
# )
|
"""
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity
O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".
If there... |
a = int(input())
b = int(input())
def rectangle_area(a, b):
return '{:.0f}'.format(a * b)
print(rectangle_area(a, b))
|
# -*- coding: utf-8 -*-
"""
KM3NeT Data Definitions v2.0.0-9-gbae3720
https://git.km3net.de/common/km3net-dataformat
"""
# daqdatatypes
data = dict(
DAQSUPERFRAME=101,
DAQSUMMARYFRAME=201,
DAQTIMESLICE=1001,
DAQTIMESLICEL0=1002,
DAQTIMESLICEL1=1003,
DAQTIMESLICEL2=1004,
DAQTIMESLICESN=1005,... |
class Solution:
def minSteps(self, n: int) -> int:
res, m = 0, 2
while n > 1:
while n % m == 0:
res += m
n //= m
m += 1
return res |
# Example, do not modify!
print(5 / 8)
# Put code below here
5 / 8
print( 7 + 10 )
# Just testing division
print(5 / 8)
# Addition works too.
print(7 + 10)
# Addition and subtraction
print(5 + 5)
print(5 - 5)
# Multiplication and division
print(3 * 5)
print(10 / 2)
# Exponentiation
print(4 ** 2)
# Modulo
print(... |
# -*- coding: utf-8 -*-
name = 'smsapi-client'
version = '2.3.0'
lib_info = '%s/%s' % (name, version) |
f = open('day6.txt', 'r')
data = f.read()
groups = data.split('\n\n')
answer = 0
for group in groups:
people = group.split('\n')
group_set = set(people[0])
for person in people:
group_set = group_set & set(person)
answer += len(group_set)
print(answer)
|
#!/bin/python3
def day12(lines):
registers = {'a': 0, 'b': 0, 'c': 1, 'd': 0}
i = 0
k = 0
while i < len(lines):
if k > 0:
i += 1
k -= 1
continue
line = lines[i].strip('\n').split(' ')
print('[%d, %d, %d, %d], %s' % (registers['a'],
... |
"""Used to make pytest functions available globally"""
# Copyright (c) 2020 zfit
#
#
# def pytest_generate_tests(metafunc):
# if metafunc.config.option.all_jit_levels:
#
# # We're going to duplicate these tests by parametrizing them,
# # which requires that each test has a fixture to accept the pa... |
km = int(input('Qual a quantidade de km percorridos?'))
dias = int(input('Por quantos dias você alugou o carro?'))
pago = (dias * 60) + (km * 0.15)
print(f'O total do seu aluguel tem valor de R${pago :.2f}.')
|
mutables_test_text_001 = '''
def function(
param,
):
pass
'''
mutables_test_text_002 = '''
def function(
param=0,
):
pass
'''
mutables_test_text_003 = '''
def function(
param={},
):
pass
'''
mutables_test_text_004 = '''
def function(
param=[],
):
pass
'''
mutables_test_text_005 = '''
def... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Solution:
def merge(self, nums1, m: int, nums2, n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
for i in range(m):
nums1[-1-i] = nums1[m-1-i]
i = 0
j = 0
k = 0
... |
#
# PySNMP MIB module CISCO-ENTITY-FRU-CONTROL-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-FRU-CONTROL-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 11:57:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Usi... |
#!/usr/bin/env python
""" Imprimir matriz
Escreva uma função imprime_matriz(matriz),
que recebe uma matriz como parâmetro e imprime a matriz,
linha por linha.
Note que NÃO se deve imprimir espaços após o último elemento de cada linha!
Exemplos:
minha_matriz = [[1], [2], [3]]
imprime_matriz(minha_matriz)
... |
"""
Eventually we'll probably want to add some decent serialization support.
For now - this is a pass through. Patches accepted :)
"""
class Serializer(object):
def serialize(cls, obj):
return obj
def is_valid(self):
return True
|
"""
Implement a Queue by linked list. Support the following basic methods:
1.enqueue(item). Put a new item in the queue.
2.dequeue(). Move the first item out of the queue, return it.
Example 1:
Input:
enqueue(1)
enqueue(2)
enqueue(3)
dequeue() // return 1
enqueue(4)
dequeue() // return 2
Solution:
做一些必要的初始化,在 MyQ... |
name = "openimageio"
version = "2.0.0"
authors = [
"Larry Gritz"
]
description = \
"""
OpenImageIO is a library for reading and writing images, and a bunch of
related classes, utilities, and applications.
"""
private_build_requires = [
'cmake-3.2.2+',
"boost-1.55",
"gcc-4.8.2+",
... |
def finan():
i = 0
tot_renda = 0
print('Ok mas antes de financiar preciso de algumas informações')
pess_rend = int(input('Quantas pessoas possuem renda na sua casa?'))
while pess_rend > i: #tem que usar 'for' porque se não fica no looping infinito
rend_familia = int(input('Valor da r... |
"""
57 / 57 test cases passed.
Runtime: 104 ms
Memory Usage: 14.9 MB
"""
class Solution:
def largestTriangleArea(self, points: List[List[int]]) -> float:
def triangleArea(x1, y1, x2, y2, x3, y3):
return abs(x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2) / 2
return max(triangl... |
#
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
# @lc code=start
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for i, num in enumerate(nums):
if hashmap.get(target - num) is not None:
return [hashmap.get(... |
class User:
user_list = []
def __init__(self,f_name,l_name,password):
"""function that creates user object"""
self.f_name = f_name
self.l_name = l_name
self.password = password
def save_user(self):
"""function that saves users"""
User.user_list.append(self)
... |
# validated: 2018-01-14 DV a68a0c3ebf0b libraries/driver/include/ctre/phoenix/MotorControl/Faults.h
__all__ = ['FaultsBase']
class FaultsBase:
fields = []
def __init__(self, bits = 0):
mask = 1
for field in self.fields:
setattr(self, field, bool(bits & mask))
mask <<... |
# Databricks notebook source
HLRIOWYITKFDP
GOQFOEKSZNF
BQRYZYCEYRHRVDKCQSN
BELVHHTEWWKFYTNTWJIIYUQTBHUMOCJNDBBIPBOVCDIKTUPVXZRIUC
AUVGECGGHDZPJPMFEZWDFYYDXYGEMHXRHYXXGEMXTCZOPGPGSRCIQNPHCUONPPCBOWTFOZEYCXCQKKUNDSXSBAKSMWIPUKICUWX
HDCWKJXOZHPPXWBBPLIGLXMBATYPTDTCAACKEEWURDREVIIUPRJXDFNDLSHBZEBMWQOMYFWARMGERQAXVLFREGTYUX... |
# 2次配列で格納して、学生(i)を基準に各チェックポイント(m)とのマンハッタン距離を見ていく
# dis_lstに格納し、一番小さかった数字が格納されている配列番号を取ってくる。その番号に+1をし各チェックポイントの番号として、表示する。
# https://note.nkmk.me/python-list-index/
n, m = map(int, input().split())
s_lst = [list(map(int, input().split())) for _ in range(n)]
c_lst = [list(map(int, input().split())) for _ in range(m)]
di... |
"""!
@brief Colors used by pyclustering library for visualization.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
class color:
"""!
@brief Consists titles of colors that are used by pyclustering for visualization.
"""
@staticmetho... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Function to print the list
def printList(self):
node = self
output = ''
while node is not None:
output += str(node.val)
output += " "
node =... |
# My Script:
hrs=input('Enter Hours: ')
hrs=float(hrs)
rph=input('Enter your rate per hour: ')
rph=float(rph)
pay=hrs*rph
print('Pay:', pay)
|
#!/usr/bin/python
def twosum(list, target):
for i in list:
for j in list:
if i != j and i + j == target:
return True
return False
with open('xmas.txt') as fh:
lines = fh.readlines()
nums = [int(l.strip()) for l in lines]
idx = 25
while(True):
last25 = nums[idx-25... |
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums) <= 2:
return max(nums)
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max... |
class Solution:
# Max to Min distance pair, O(n^2) time, O(1) space
def maxDistance(self, colors: List[int]) -> int:
for dist in range(len(colors)-1, 0, -1):
for i in range(len(colors)-dist):
if colors[i] != colors[i+dist]:
return dist
# Max dist from... |
#Functions
def userFunction(): #Putting Function
print("Hello, User :)")
print("Have a nice day!")
#Calling Function
userFunction()
|
"""Define docstring substitutions.
Text to be replaced is specified as a key in the returned dictionary,
with the replacement text defined by the corresponding value.
Special docstring substitutions, as defined by a class's
`_docstring_special_substitutions` method, may be used in the
replacement text, and will be su... |
num_of_lines = int(input())
def cold_compress(cum, rs):
N = len(cum)
# exit
if (rs == ""):
output_string = ""
for s in cum:
output_string += str(s) + " "
return output_string
# iteration
if (N >= 2 and cum[N-1] == rs[0]):
cnt = cum[N-2]
cnt += 1
... |
# arr = [2, 3, -4, -9, -1, -7, 1, -5, -6]
arr = [0, 0, 0, 0]
def next_p(arr, l, x):
print("px0", x)
while x <= l - 1 and arr[x] < 0:
x += 1
print("px1", x)
print("px2", x)
return x
def next_n(arr, l, x):
print("nx0", x)
while x <= l - 1 and arr[x] >= 0:
x += 1
... |
# -*- coding: utf-8 -*-
# OPENID URLS
URL_WELL_KNOWN = "realms/{realm-name}/.well-known/openid-configuration"
URL_TOKEN = "realms/{realm-name}/protocol/openid-connect/token"
URL_USERINFO = "realms/{realm-name}/protocol/openid-connect/userinfo"
URL_LOGOUT = "realms/{realm-name}/protocol/openid-connect/logout"
URL_CERTS... |
#DEFAULT ARGS
print('Default Args : ')
def sample(a, b = 0, c = 1) :
print(a, b, c)
sample(10)
sample(10, 20)
sample(10, 20, 30)
#VARIABLE NUMBER OF ARGS
print('VARIABLE NUMBER OF ARGS : ')
def add(a, b, *t) :
s = a + b
for x in t :
s = s + x
return s
print(add(1, 2, 3, 4))
#KEY - WORD ARGS
print('KEY - WORD... |
string = 'b a '
newstring = string[-1::-1]
length = 0
print(newstring)
for i in range(0, len(newstring)):
if newstring[i] == ' ':
if i == 0:
continue
if newstring[i-1] == ' ':
continue
break
length += 1
print(length) |
NEPS_URL = 'https://neps.academy'
ENGLISH_BUTTON = '/html/body/div/div/div/div[2]/div/div/a/div[2]/div'
LOGIN_PAGE_BUTTON = '//*[@id="app"]/div/div/div/div[1]/div/header/div/div/div[3]/div/div/nav/ul/li[6]/button'
EMAIL_INPUT = '/html/body/div/div/div/div[3]/div/div/div/form/div[1]/div/div[1]/div/input'
PASSWORD_INPUT ... |
class Account:
"""Store login information(username and password)."""
def __init__(self, username='', password=''):
"""Store username and password."""
self.username = username
self.password = password
|
class Car(object):
"""A car class"""
def __init__(self, model, make, color):
self.model = model
self.make = make
self.color = color
self.price = None
def get_price(self):
return self.price
def set_price(self, value):
self.price = value
availableCars = ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件 :collection_utils.py
@说明 :
@时间 :2020/07/13 17:54:21
@作者 :Riven
@版本 :1.0.0
'''
def get_first_existing(dict, *keys, default=None):
for key in keys:
if key in dict:
return dict[key]
return default
def ... |
"""
URL: https://leetcode.com/explore/learn/card/linked-list/219/classic-problems/1207/
Problem Statement:
------------------
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6... |
class Solution:
def __init__(self):
self.ret = []
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
# dp[i][j] means starting from [i for j ele can be slice
dp = [[0 for _ in range(len(s)+1)] for _ in ... |
password = input()
alpha = False
upalpha = False
digit = False
for i in password:
if i.isspace():
print("NOPE")
break
if i.isdigit():
digit = True
if i.isalpha():
if i.isupper():
upalpha = True
if i.islower():
alpha = True
else:
if alpha an... |
"""
Best Solution
Space : O(1)
Time : O(n log n)
"""
class Solution:
def smallestRangeII(self, A: List[int], K: int) -> int:
A.sort()
ans = A[-1] - A[0]
for x, y in zip(A, A[1:]):
ans = min(ans, max(A[-1]-K, x+K) - min(A[0]+K, y-K))
return ans
|
# como adicionar itens em dicionario + lista em um looping + formatação
estado = {} # {} = dicionário
brasil = [] # [] lista
for c in range (0,3):
estado['uf']= str(input('Unidade Federativa: '))
estado['Sigla']=str(input('Sigla do Estado: '))
brasil.append(estado.copy()) # quando temos esse misto de dicio... |
###########################
# 6.0002 Problem Set 1b: Space Change
# Name:
# Collaborators:
# Time:
# Author: charz, cdenise
#================================
# Part B: Golden Eggs
#================================
# Problem 1
# Method 1
# def dp_make_weight(egg_weights, target_weight, memo = {}):
# ... |
def mensaje(): # Declaración de la función
print("Estamos aprendiendo Python.")
print("Estamos aprendiendo instrucciones básicas.")
print("Poco a poco iremos avanzando.")
mensaje() # Llamada a la función
print("Ejecutando código fuera de función")
mensaje()
|
"""Miscellaneous stuff for Coverage."""
def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
... |
# Ideas
"""
server = dkeras.DataServer()
model1.link(model3)
model1.postprocess = lambda z: np.float16(z)
server = model1 + model2 + model3
server.add(camera1, dest=('m1', 'm2'))
server.add_address('192.168.1.42')
"""
|
#!/usr/bin/env python3
class IndexCreator:
def __init__(self):
self._index = 0
def generate(self):
r = self._index
self._index += 1
return r
def clear(self):
self._index = 0
if __name__ == "__main__":
i = IndexCreator()
print(i.generate(), i.genera... |
#Drinklist by Danzibob Credits to him!
drink_list = [{
'name': 'Vesper',
'ingredients': {
'gin': 60,
'vodka': 15.0,
'vermouth': 7.5
},
},
{
'name': 'Bacardi',
'ingredients': {
'whiteRum': 45.0,
'lij': 20,
... |
lista = [1, 13, 15, 7]
lista_animal = ['cachorro', 'gato', 'elefante', 'arara']
# Convertendo lista em tupla
tupla_animal = tuple(lista_animal)
print(lista_animal)
print(tupla_animal)
# Convertendo tupla em lista
tupla = (1, 13, 15, 7)
lista_numerica = list(tupla)
print(tupla)
print(lista_numerica)
# Daí dá para alt... |
'''
Thanks to "Primo" for the amazing code found in this .py.
'''
# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
return pow(a, (m-1) >> 1, m)
# strong probable prime
def is_sprp(n, b=2):
d = n-1
s = 0
while d & 1 == 0:
s... |
a = "Hello World"
b = a[3]
c = a[-2]
d = a[5::]
e = a[:5]
print(b)
print(c)
print(d)
print(e)
|
class TagLoaderException(Exception):
pass
def str2int(s: str, default=0) -> int:
try:
return int(s)
except ValueError:
return default
def get_or_default(d, k, default=""):
if k in d:
return d[k]
else:
return default
def bytes2str(buffer: bytes) -> [str, bytes]:... |
overlapped_classes = ["Alarm clock",
"Backpack",
"Banana",
"Band Aid",
"Basket",
"Bath towel",
"Beer bottle",
"Bench",
"Bicycle",
"Binder (closed)",
"Bottle cap",
"Bread loaf",
"Broom",
"Bucket",
"Butcher's knife",
"Can opener",
"Candle",
"Cellphone",
"Chair",
"Clothes hamper",
"Combination lock",
"Computer mouse",
"De... |
indexes = range(5)
same_indexes = range(0, 5)
print("indexes are:")
for i in indexes:
print(i)
print("same_indexes are:")
for i in same_indexes:
print(i)
special_indexes = range(5, 9)
print("special_indexes are:")
for i in special_indexes:
print(i) |
print('\nCalculate the midpoint of a line :')
x1 = float(input('The value of x (the first endpoint) '))
y1 = float(input('The value of y (the first endpoint) '))
x2 = float(input('The value of x (the first endpoint) '))
y2 = float(input('The value of y (the first endpoint) '))
x_m_point = (x1 + x2)/2
y_m_point = (y1... |
ts = [
# example tests
14,
16,
23,
# small numbers
5,
4,
3,
2,
1,
# random bit bigger numbers
10,
20,
31,
32,
33,
46,
# perfect squares
25,
36,
49,
# random incrementally larger numbers
73,
89,
106,
132,
182,
258,
299,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.