content stringlengths 7 1.05M |
|---|
PPTIK_GRAVITY = 9.77876
class StationKind:
V1 = 'L'
STATIONARY = 'S'
MOBILE = 'M'
class StationState:
ALERT = 'A'
READY = 'R'
ECO = 'E'
HIGH_RATE = 'H'
NORMAL_RATE = 'N'
LOST = 'L' |
# 1st solution
class Solution:
def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
if not firstList or not secondList:
return []
first, second = 0, 0
result = []
while first < len(firstList) and second < len(secondLi... |
#
# PySNMP MIB module WWP-VOIP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-VOIP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:32:08 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,... |
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# List for visited nodes.
visited = []
#Initialize a queue
queue = []
# distance initialization (dict)
dist = {}
#function for BFS
def bfs_shortest_path(visited, graph, start_node, end_node):... |
#!/usr/bin/env python
"""Example of raising an exception where b() has a finally clause and a()
catches the exception.
Created on Aug 19, 2011
@author: paulross
"""
class ExceptionNormal(Exception):
pass
class ExceptionCleanUp(Exception):
pass
def a():
try:
b()
except ExceptionNormal as err... |
def star():
print("How Much Rows You Want")
n = int(input())
print("Enter 1 or Non Zero for True and 0 For False")
n2 = int(input())
n1 = bool((n2))
if n1 is True:
for i in range(n):
i = i+1
print(i*"*")
elif n1 is False:
for i in range(n):
... |
"""
"""
# This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def sumOfLinkedLists(linkedListOne, linkedListTwo):
tmp = 0
node1 = linkedListOne
node2 = linkedListTwo
while node1 is not None:
if node2 is no... |
#!/usr/bin/env python3
with open("input.txt", "r") as f:
num = []
for elem in f.read().split(","):
num.append(int(elem))
positions = set(num)
steps = -1
for position in positions:
current = 0
for elem in num:
current += abs(elem - position)
if steps < 0 or... |
"""Remove item from list, by its value.
Remove at most 1 item from list _items, having value _x.
This will alter the original list or return a new list, depending on which is more idiomatic. If there are several occurrences of _x in _items, remove only one of them.
Source: programming-idioms.org
"""
# Implementatio... |
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
s, res = {}, []
for i in range(len(numbers)):
if numbers[i] in s.keys():
res.append(s[numbers[i]] + 1)
res.append(i + 1)
return res
s[target - numbe... |
# historgram
def histogram(s):
d = dict()
for c in s:
a = d.get(c, 0)
d[c] = 1+a
return sorted(d)
h = histogram("brantosaurus")
print(h)
|
class FirmwareGPIO:
def __init__(self, scfg):
crtl_inputs = scfg.analog_ctrl_inputs + scfg.digital_ctrl_inputs
ctrl_outputs = scfg.analog_ctrl_outputs + scfg.digital_ctrl_outputs
self.getter_dict = {}
for probe in ctrl_outputs:
if probe.o_addr is not None:
... |
# -*- coding: utf-8 -*-
NOT_IMPLEMENTED_ERROR_MSG = ('This method must be implemented by classes'
' inheriting from BaseSerializer.')
class BaseSerializer(object):
"""
Base Serializer class that provides an interface for other serializers.
Usage:
.. code-block:: python
... |
def new_seating_chart(size=22):
"""Create a new seating chart.
:param size: int - number if seats in the seating chart.
:return: dict - with number of seats specified, and placeholder values.
"""
return {number: None for number in range(1, size + 1)}
def arrange_reservations(guests=None):
""... |
def Articles():
articles = [
{
'id' : 1,
'title' : 'Article one',
'body' : 'Now ParseHub will call this handler every time the status of a run changes. It doesnt matter how long the run takes, or if it queued up on our servers for a while. Itll just work',
'auther': 'Refuge',
'create_date' : ... |
DOMAIN = "ble_mesh"
PLATFORM_LIGHT = "light"
HANDLE_ID = 14
CMD_FUNCTION = 0xFB
CMD_GPIO_CONTROL = 0xE7
CMD_OUT_1 = 0xF1
CMD_ON = 0x01
CMD_OFF = 0x00
|
for _ in range(int(input())):
a, b = [int(i) for i in input().split()]
if a > b: print(">")
elif a < b: print("<")
else: print("=") |
a = list(input())
cnt = 0
x = 0
for i in range(len(a)-1):
if a[i] == a[i+1]:
cnt += 1
if x <= cnt:
x = cnt
elif a[i] != a[i+1]:
cnt = 0
print(x+1) |
# Test proper handling of exceptions within generator across yield
def gen():
try:
yield 1
raise ValueError
print("FAIL")
raise SystemExit
except ValueError:
pass
yield 2
for i in gen():
print(i)
# Test throwing exceptions out of generator
def gen2():
yield... |
with open("testfile.txt", "wb") as f1:
for i in range(0, 65536):
a = i//256
b = i%256
f1.write(bytes([a, b]))
|
# Array (mutable, resizable)
class Array:
# Declare the necessary values used for the Array
_capacity = None
_size = None
_array = None
# Initialize these values with the capacity chosen
def __init__(self, capacity):
self._capacity = capacity
self._size = 0
self._array ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 21:31:18 2020
@author: krishan
"""
class Mammal:
def __init__(self, age):
self.age = age
def legs(self):
print("Two Legs")
def run(self):
print("Slow")
class Men(Mammal):
... |
class Solution:
def nextGreaterElements(self, nums: list) -> list:
if not nums:
return []
monotonic_stack = [(nums[0], 0)]
nums = nums + nums
next_greater = {}
for i, num in enumerate(nums[1:], 1):
while monotonic_stack:
... |
# List of rooms, characters, and weapons
room_list = ['Study','Hall','Lounge','Library','Billiard','Dining','Conservatory','Ballroom','Kitchen']
hall_list = ['Hall A','Hall B','Hall C','Hall D','Hall E','Hall F','Hall G','Hall H','Hall I','Hall J','Hall K','Hall L']
character_list = ['Miss Scarlet','Mrs. Peacock','Prof... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
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, p... |
class MetadataNotFound(Exception):
pass
class MetadataCorruption(Exception):
pass
class NotYetImplemented(Exception):
pass
class SPConfigurationMissing(Exception):
pass
|
inp = input()
arr = inp.split(' ')
L = int(arr[0])
N = int(arr[1])
dic = []
for i in range(0,L):
st = input()
stri = st.split(' ')
dic.append(stri)
for i in range(0,N):
inp = input()
tr = False
for j in range(0,L):
temp = dic[j]
if(inp == temp[0]):
print(temp[1])
tr = T... |
__all__ = (
'decode_int',
'decode_str',
'decode_lst'
)
def decode_int(data, pos):
end = data[pos:].index(b'e')
if data[pos+1] == ord('-'):
return (int(data[pos + 2:pos + end]) * -1, end)
else:
return (int(data[pos + 1:pos + end]), end + pos)
# return data as raw byte... |
def seat_decode(seat):
row = int(seat[:7].replace("F", "0").replace("B", "1"), 2)
column = int(seat[7:].replace("L", "0").replace("R", "1"), 2)
return row * 8 + column
if __name__ == "__main__":
with open("input.txt", "r") as f:
ids = {seat_decode(line.strip()) for line in f.readlines()}
... |
__all__ = ['MODEL_URL', 'MODEL_VIEW']
MODEL_URL = """from rest_framework.routers import SimpleRouter
from {{ app }}.api import views
router = SimpleRouter()
{% for model in models %}
router.register(r'{{ model | lower }}', views.{{ model }}ViewSet){% endfor %}
urlpatterns = router.urls
"""
MODEL_VIEW = """from ... |
dicio = {"Nome": str(input('Nome do jogador: '))}
partidas = int(input(f'Quantas partidas {dicio["Nome"]} jogou? '))
lista = []
for c in range(partidas):
dicio["Gols"] = int((input(f'Quantos gols na partida {c+1}: ')))
lista.append(dicio["Gols"])
dicio["Gols"] = lista
total = int()
for c in lista:
total += ... |
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 1
if n == 1:
return 10
ans, base = 10, 9
for i in range(1, n):
base *= (10 - i)
ans +=... |
print("Welcome to my Game")
print("Instructions: During this game you will use somethings keywords for continue with the story. You can play again to know the different endings.")
print()
start = input("Type, START ")
print()
print("Wake Up")
print("Yo me desperte en la calle, a mi alrededor escuchaba gritos y veia fue... |
def data():
return {
"test": {
"min/layer2/weights": {
"displayName": "min/layer2/weights",
"description": ""
}
},
"train": {
"min/layer2/weights": {
"displayName": "min/layer2/weights",
"desc... |
#!/usr/bin/env/ python
# encoding: utf-8
__author__ = 'aldur'
|
# -*- coding: utf-8 -*-
"""Data literal storing emoji French names and Unicode codes."""
__all__ = ['EMOJI_UNICODE_FRENCH', 'UNICODE_EMOJI_FRENCH',]
EMOJI_UNICODE_FRENCH = {
u':visage_rieur:': u'\U0001F600',
u':visage_souriant_avec_de_grands_yeux:': u'\U0001F603',
u':visage_très_souriant_aux_yeux_rieurs... |
# Python 3.6.1
with open("input.txt", "r") as f:
puzzle_input = []
for line in f:
puzzle_input.append(line.strip().split(" "))
total = 0
for phrase in puzzle_input:
bad = False
for word in phrase:
if phrase.count(word) > 1:
bad = True
break
if not bad:
... |
def Select_sort1():
A = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0]
for i in range(len(A)):
minimum = i
for j in range(i+1, len(A)):
if A[minimum] > A[j]:
minimum = j
A[i], A[minimum] = A[minimum], A[i]
print("After sort:")
print(A)
def ... |
class Formatter:
"""
Inherit this class and override format function
"""
def format(self, text: str):
"""Override this function in inherited subclass. return text after formatting"""
return text
@property
def name(self):
return self.__class__.__name__
@classmethod
... |
"""
Documentation, License etc.
@package X-EDEN Toolchain generation
"""
|
tempF = input('Informe a temperatura em graus Fahrenheit ')
c = float(tempF) -32
c = c * 5 / 9
print(f'A temperatura em graus Celsius é {c}ºC')
|
"""
CRM system
task: display a user record in the following format: 'John Smith (California)'. However, if you don't have a location in your system, you want just to see "John Smith."
"""
def format_customer(first, last, location=None):
full_name = '%s %s' % (first, last)
if location:
return '%s (%s)... |
emails = sorted(set([line.strip() for line in open("email_domains.txt")]))
for email in emails:
print("'{email}',".format(email=email))
|
class ResourceMixin(object):
def check_user(self, role=None, id=None, User_class=None):
if not User_class.check_role(id):
return {
"msg": "Sie haben nicht die nötigen Rechte."
}, 403
def save_or_except(self, obj_instance):
try:
... |
for _ in range(int(input())):
string = input()
new_str= ""
new_str += string[0]
for i in range(1, len(string)):
if string[i] == "L":
on = string[i-1]
elif string[i] == "R":
on = string[i+1]
else:
on = string[i]
new_str += on
print(... |
# https://www.hackerrank.com/challenges/any-or-all/problem
def is_palindrome(number):
return number == number[::-1]
N = int(input())
array = list(input().split())
print(
all(int(element) >= 0 for element in array)
and any(is_palindrome(element) for element in array)
)
|
# Question Link : https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3594/
# Level : Medium
# Solution Right Below :-
class Solution(object):
def findKthPositive(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype... |
"""
In-place quicksort implementation
"""
def quicksort(lst, b=0, e=None):
if e == None:
e = len(lst) - 1
p = e
i = b
while i < p:
if lst[p] < lst[i]:
# bring lst[i] after lst[p] through two swaps
lst[i], lst[p - 1] = lst[p - 1], lst[i]
lst[p - 1], ... |
def flownet_v1_s(input):
pass
|
prime = [2,3]
i = 4
while len(prime)<10001:
s = True
for j in prime:
if i%j == 0:
s = False
break
if s:
prime.append(i)
i = i + 1
print(prime[-1]) |
def rotation_string(str):
l = []
#str = ""
for i in str:
l.append(i)
#print(l)
for j in range(len(l) // 2):
a = l[j]
b = l[-(j+1)]
l[j] = b
l[-(j+1)] = a
return l |
# Refazer o exercício 35 dos triângulos.
# Mostarndo desta vez se o triângulo é:
# 1) Equilátero: Todos os lados iguais
# 2) Isósceles: Dois lados iguais
# 3) Escaleno: Todos os lados diferentes
print('=-=' * 20)
print('ANALISADOR DE TEXTO')
print('=-=' * 20)
r1 = float(input('Digite o 1° valor: '))
r2 = float(input('... |
def descending(x,n):
t=0
# by selection sorting
for i in range(0,n-1,1):
for j in range(i+1,n,1):
if x[i]<x[j]:
t=x[i]
x[i]=x[j]
x[j]=t
return (x)
# To sort a list in descending order
print("This programme sorts a list in d... |
config = {'MAX_BOUND':512.0,
'MIN_BOUND':-1024.0,
'PIXEL_MEAN':0.25,
'NORM_CROP':True
} |
# -*- coding: iso-8859-15 -*-
class Conjugator():
# Present Conjugations
# Past Conjugations
def conjugate(self,root_verb,tense,mood,pronoun):
tense = tense.lower()
mood = mood.lower()
pronoun = pronoun.lower()
if tense == "imperfect":
if mood == "imperitive":... |
#
# PySNMP MIB module ELTEX-ULD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-ULD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:48:10 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... |
word = input('Digite uma palavra para testar ou exit para sair: ').lower().strip()
while (word != 'exit'):
index = len(word) -1
contrario = word
numero = 0
for c in range(0, index+1, 1):
if contrario[c] == word[index - c]:
numero += 1
if numero == len(word):
print('A pa... |
n = int(input('Enter a Value for N:\n'))
count = 1
while count <= n:
v1 = count
v2 = count + 1
if count +2 < n:
v3 = count + 2
else:
v3 = ' '
print(f'{v1} {v2} {v3}')
count += 3 |
# encoding: utf-8
# module RevitServices.Transactions calls itself Transactions
# from RevitServices, Version=1.2.1.3083, Culture=neutral, PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class AutomaticTransactionStrategy(object, ITransactionStrategy):
""" Auto... |
# https://www.codewars.com/kata/578553c3a1b8d5c40300037c/python
# Given an array of ones and zeroes, convert the equivalent binary value to an integer.
# Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
# Examples:
# Testing: [0, 0, 0, 1] ==> 1
# Testing: [0, 0, 1, 0] ==> 2
# Testing: [0, ... |
OCTICON_COMMENT_DISCUSSION = """
<svg class="octicon octicon-discussion" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M1.5 2.75a.25.25 0 01.25-.25h8.5a.25.25 0 01.25.25v5.5a.25.25 0 01-.25.25h-3.5a.75.75 0 00-.53.22L3.5 11.44V9.25a.75.75 0 00-.75-.75h-1a.25... |
# Interactive Help
help()
# Alternative Interactive Help
print(input.__doc__)
# Docstrings
def count(s,e,i):
"""
It's a counter that show in the touch:
s is the start of count;
e is the end of count;
i is the time's interval.
no exist return
by @e.mmmorais
"""
c = ... |
def gap_sort(x):
gap = len(x)
swap= True
while gap > 1 or swap:
gap = max(1, int(gap / 1.3))
swap= False
for i in range(len(x) - gap):
j = i+gap
if x[i] > x[j]:
x[i], x[j] = x[j], x[i]
swap= True
lst = [3,6,4,8,9,0,6,5,2,10,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
modelChemistry = "CBS-QB3"
useHinderedRotors = True
useBondCorrections = False
species('CH2CHOOH', 'CH2CHOOH.py')
statmech('CH2CHOOH')
thermo('CH2CHOOH', 'Wilhoit')
|
#: Module purely exists to test patching things.
thing = True
it = lambda: False
def get_thing():
global thing
return thing
def get_it():
global it
return it
|
class Invitation():
def __init__(self, row):
LANG, MAIL, NAME, SENDER, FIELD, ONE_SEN, DATE, DESC, DONE, ETC = range(10)
self.lang = row[LANG]
self.mail = row[MAIL]
self.name = row[NAME]
self.sender = row[SENDER]
self.field = row[FIELD]
self.one_sen = row[ONE_... |
_URL = "https://www.jetbrains.com/intellij-repository/releases/com/jetbrains/intellij/idea/ideaIU/{version}/ideaIU-{version}.zip"
_BUILD_FILE = """
load("@rules_java//java:defs.bzl", "java_import")
java_import(
name = "idea",
jars = [
"lib/extensions.jar",
"lib/jdom.jar",
"lib/guava-28... |
li=[]
n=int(input("Enter Number of Elements in List"))
print("Enter Numbers")
for i in range(n):
ele=int(input())
li.append(ele)
l1=[]
for i in li:
l1.insert(len(l1)-1,i)
print(l1)
|
phone_book = dict()
enough = False
while True:
if enough:
break
command = input()
if command == 'stop':
break
elif command == 'search':
while True:
person = input()
if person == 'stop':
enough = True
break
... |
def clean_col(col):
"""
This function cleans the column names and add the year information
"""
if col == 'Unnamed: 0': # Special case for contry column
return 'Country'
elif col[0] == 'U': # Take care for the annual summary column
return 'Total, {}'.format(str(int(col.split(':')[1... |
"""The `models` module contains routines for updating the
*parameters.json* file of the ILAMB component in PBS.
"""
model_template = { "group": { "name": "pbs_models_group", "members":
1, "leader": False }, "name": "{model_name}", "global": False,
"value": { "default": "Off", "type": "choice", "choices": [ "On... |
#In this program we will enter a number and get its factors as the output in a list format.
num = int(input("Enter number: "))
def factors(n):
flist = []
for i in range(1,n+1):
if n%i == 0:
flist.append(i)
return flist
print(factors(num))
|
class initial():
def solution(self, nums):
prefix = [1] * len(nums)
suffix = [1] * len(nums)
for i in range(1, len(nums)):
prefix[i] = prefix[i-1] * nums[i-1]
for j in range(len(nums)-2, -1, -1):
suffix[j] = suffix[j+1] * nums[j+1]
return [prefix[i]... |
def parse(filename: str) -> list[int]:
with open(filename) as file:
line = file.read()
return list(map(int, line.split(',')))
def solve(fishes: list[int], days: int) -> int:
for _ in range(days):
for i in range(len(fishes)):
fishes[i] -= 1
if fishes[i] < 0:
... |
#leia o tamanho do lado de um quadrado e
#imprima como resultado a area.
lado=float(input("Informe o lado do quadrado: "))
area=lado*lado
print(f"A area do quadrado eh {area}") |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
maxi = 0
... |
# faça um programa que calcule a soma entre todos os numeros impares que são
# multiplos de 3
# que se encontram no intervalo de 1 até 500
soma = 0
conta = 0
for mult in range(1, 501, 2):
if mult % 3 == 0:
conta = conta + 1
soma = mult + soma
else:
continue
print(soma)
print(conta)
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
t = int(input())
for _ in range(t):
x1,... |
class dotHierarchicList_t(object):
# no doc
aObjects = None
ModelFatherObject = None
nObjects = None
ObjectsLeftToGet = None
OperationType = None
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return head
tem... |
RED = images.create_image("""
. # # # .
. # # # .
. . . . .
. . . . .
. . . . .
""")
RED_YELLOW = images.create_image("""
. # # # .
. # # # .
. # # # .
. . . . .
. . . . .
""")
YELLOW = images.create_image("""
. . . . .
. # # # .
. # # # .
. . . . .
. . . . .
""")
GREEN = images.create_image("""
. . . . .
. . . . .
. ... |
# Lemoneval Project
# Author: Abhabongse Janthong <6845502+abhabongse@users.noreply.github.com>
"""Validator classes for each parameter in exercise frameworks."""
class BaseValidator(object):
"""Defines a callable object which checks if the given value is valid."""
__slots__ = ("name",)
def __init__(sel... |
# Source found at: https://datatables.net/extensions/scroller/examples/initialisation/large_js_source.html
def generate_html_page(file_path, prj_name, title, df):
"""
Write a dataframe to a HTML page.
:param file_path: File path to save the HTML file.
:param prj_name: Project name for the title.
... |
pytest_plugins = "pytester"
LEAKING_TEST = """
import threading
import time
def test_leak():
for i in range(2):
t = threading.Thread(
target=time.sleep,
args=(0.5,),
name="leaked-thread-%d" % i)
t.daemon = True
t.start()
"""
INI_ENABLED = """
[pytest]
t... |
'''
Factorial (hacker challenge). Write a function factorial() that returns the
factorial of the given number. For example, factorial(5) should return 120.
Do this using recursion; remember that factorial(n) = n * factorial(n-1).
'''
def factorial(n):
if n == 1 or n == 0:
return 1
if n == 2:
... |
def infini(y : int) -> int:
x : int = y
while x >= 0:
x = x + 1
return x
def f(x : int) -> int:
return x + 1
|
def changeConf(xmin=2., xmax=16., resolution=2, Nxx=1000, Ntt=20000, \
every_scalar_t=10, every_aaray_t=100, \
amplitud=0.1, sigma=1, x0=9., Boundaries=0, Metric=1):
conf = open('input.par','w')
conf.write('¶meters')
conf.write('xmin = ' + str(xmin) + '\n... |
class Day3:
def part1(self):
with open(r'C:\Coding\AdventOfCode\AOC2019\Data\Data3.txt') as f:
lines = f.read().splitlines()
firstPath = lines[0].split(',')
secondPath = lines[1].split(',')
firstPathCoordinates = self.wiresPositionsDictionary(firstPath)
secondPa... |
# @Title: 移除元素 (Remove Element)
# @Author: KivenC
# @Date: 2018-07-13 15:47:14
# @Runtime: 28 ms
# @Memory: N/A
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
count = 0
for i in range(len(... |
def leiadinheiro(txt):
while True:
din = str(input(f'{txt}')).replace(',', '.').strip()
if din.isalpha() or din == '':
print(f'\033[31mErro! "{din}" é um preço invalido\033[m')
else:
break
return float(din)
|
# --------------------------------------
#! /usr/bin/python
# File: 283. Move Zeros.py
# Author: Kimberly Gao
class Solution:
def _init_(self,name):
self.name = name
# My 1st solution: (Run time: 68ms(29.57%)) (2 pointer)
# Memory Usage: 15.4 MB (61.79%)
def moveZeros1(self, nums):
slo... |
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
d... |
'''
Created on Nov 3, 2018
@author: nilson.nieto
'''
list_numeros =input("Ingrese varios numeros separados por espacio : ").split(" , ")
for i in list_numeros:
print(i) |
def getVariableType(v):
""" Replacing bools with ints for Python compatibility """
vType = v['Type']
vType = vType.replace('bool', 'int')
vType = vType.replace('std::function<void(korali::Sample&)>', 'std::uint64_t')
return vType
def getCXXVariableName(v):
cVarName = ''
for name in v:
cVarName += na... |
def get_fuel(mass):
return int(mass / 3) - 2
def get_fuel_including_fuel(mass):
total = 0
while True:
fuel = get_fuel(mass)
if fuel <= 0:
break
total += fuel
mass = fuel
return total
# Part one
with open('input') as f:
print(sum(
get_fuel(
... |
class Manager:
def __init__(self):
self.worker = None
def set_worker(self, worker):
assert "Worker" in [el.__name__ for el in worker.__class__.__mro__], "'worker' must be of type Worker"
self.worker = worker
def manage(self):
if self.worker is not None:
self.wo... |
N, K = map(int, input().split())
A = [0]
total = 0
a = list(map(int, input().split()))
ans = 0
m = {0: 1}
for x in a:
total += x
count = m.get(total - K, 0)
ans += count
m[total] = m.get(total, 0) + 1
A.append(total)
print(ans) |
"""
This module will be having the locators of all the
food listing page which comes after clicks on
start ordering button
"""
class FoodSelectionPageLocators:
""" food selection class """
place_order_dialog_box_button = "//button[text()='Ok! Place Order']"
total_product_items = "//div/div/div[contains(@cl... |
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
# sliding window, O(N) time, O(1) space
globMax = tempMax = sum(nums[:k])
for i in range(k, len(nums)):
tempMax += (nums[i] - nums[i-k])
globMax = max(tempMax, globMax)
return globMax ... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class ChangeEnum(object):
"""Implementation of the 'Change' enum.
TODO: type enum description here.
Attributes:
KPROTECTIONJOBNAME: TODO: type description here.
KPROTECTIONJOBDESCRIPTION: TODO: type description here.
KPROTECT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.