content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
14 / 14 test cases passed.
Runtime: 40 ms
Memory Usage: 15.1 MB
"""
class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
used, bank = set(), set(bank)
if end not in bank: return -1
# current gene, steps
que = collections.deque([(start, 0)])
... | """
14 / 14 test cases passed.
Runtime: 40 ms
Memory Usage: 15.1 MB
"""
class Solution:
def min_mutation(self, start: str, end: str, bank: List[str]) -> int:
(used, bank) = (set(), set(bank))
if end not in bank:
return -1
que = collections.deque([(start, 0)])
while que:... |
# -*- coding: utf-8 -*-
"""Version information for this package."""
__version__ = "4.10.9"
VERSION: str = __version__
"""Version of package."""
__url__ = "https://github.com/Axonius/axonius_api_client"
URL: str = __url__
"""URL of package."""
__author__ = "Axonius"
AUTHOR: str = __author__
"""Auth of package."""
__t... | """Version information for this package."""
__version__ = '4.10.9'
version: str = __version__
'Version of package.'
__url__ = 'https://github.com/Axonius/axonius_api_client'
url: str = __url__
'URL of package.'
__author__ = 'Axonius'
author: str = __author__
'Auth of package.'
__title__ = 'axonius_api_client'
title: st... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root):
# DFS
def solve(node, level):
if not node: return level - 1
elif node.left and n... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def min_depth(self, root):
def solve(node, level):
if not node:
return level - 1
elif node.left and node.right:
retur... |
def is_polygon(way):
"""Checks if the way is a polygon.
Args
way: the osmium.osm.Way to check.
Returns:
True if the way is a polygon, False otherwise.
Note: The geometry shape can still be invalid (e.g. self-intersecting).
"""
if not way.is_closed():
return False
if ... | def is_polygon(way):
"""Checks if the way is a polygon.
Args
way: the osmium.osm.Way to check.
Returns:
True if the way is a polygon, False otherwise.
Note: The geometry shape can still be invalid (e.g. self-intersecting).
"""
if not way.is_closed():
return False
if le... |
class Room:
def __init__(self):
pass
def intro_text(self):
raise NotImplementedError()
def adjacent_moves(self):
pass
def available_actions(self):
pass
class StartingRoom(Room):
def __init__(self, ):
super().__init__()
def intro_text(self):
r... | class Room:
def __init__(self):
pass
def intro_text(self):
raise not_implemented_error()
def adjacent_moves(self):
pass
def available_actions(self):
pass
class Startingroom(Room):
def __init__(self):
super().__init__()
def intro_text(self):
... |
list1, list2 = [123, 567, 343, 611], [456, 700, 200]
print("Max value element : ", max(list1))
print("Max value element : ", max(list2))
print("min value element : ", min(list1))
print("min value element : ", min(list2))
| (list1, list2) = ([123, 567, 343, 611], [456, 700, 200])
print('Max value element : ', max(list1))
print('Max value element : ', max(list2))
print('min value element : ', min(list1))
print('min value element : ', min(list2)) |
# splitting_list_elements.py
print("""
{original_code}
json_data = ["abc", "bcd/chg", "sdf", "bvd", "wer/ewe", "sbc & osc"]
separators = ['/', '&', 'and']
title = []
for i in json_data:
k = 0
while k < len(separators):
if separators[k] in i:
t = i.split(separators[k])
title.ext... | print('\n{original_code}\njson_data = ["abc", "bcd/chg", "sdf", "bvd", "wer/ewe", "sbc & osc"]\nseparators = [\'/\', \'&\', \'and\']\ntitle = []\n\nfor i in json_data:\n k = 0\n while k < len(separators):\n if separators[k] in i:\n t = i.split(separators[k])\n title.extend(t)\n ... |
def seq(hub, low, running):
'''
Return the sequence map that should be used to execute the lowstate
The sequence needs to identify:
1. recursive requisites
2. what chunks are free to run
3. Bahavior augments for the next chunk to run
'''
ret = {}
for ind, chunk in enumerate(low):
... | def seq(hub, low, running):
"""
Return the sequence map that should be used to execute the lowstate
The sequence needs to identify:
1. recursive requisites
2. what chunks are free to run
3. Bahavior augments for the next chunk to run
"""
ret = {}
for (ind, chunk) in enumerate(low):
... |
#!/usr/bin/env python3
# Day 6: Queue Reconstruction by Height
#
# Suppose you have a random list of people standing in a queue. Each person is
# described by a pair of integers (h, k), where h is the height of the person
# and k is the number of people in front of this person who have a height
# greater than or equal... | class Solution:
def reconstruct_queue(self, people: [[int]]) -> [[int]]:
height = lambda person: person[0]
taller_in_front = lambda person: person[1]
sorted_people = sorted(people, key=lambda person: (-height(person), taller_in_front(person)))
queue = []
for person in sorted... |
"""
Descriptions
Advantages:
Tab auto complete.
Historical log to archieve.
Edit with in a line.
Use $run to call external python script.
Support system cmds.
Support pylab module.
Debug Python code and profiler.
"""
"""
cmds for ipython
ipython --pylab
... | """
Descriptions
Advantages:
Tab auto complete.
Historical log to archieve.
Edit with in a line.
Use $run to call external python script.
Support system cmds.
Support pylab module.
Debug Python code and profiler.
"""
'\ncmds for ipython\n ipython --pylab\n ... |
class Tool: pass
class Documentation(Tool): pass
class Frustration(Tool): pass
class Dwf(Documentation, Frustration, Tool): pass
| class Tool:
pass
class Documentation(Tool):
pass
class Frustration(Tool):
pass
class Dwf(Documentation, Frustration, Tool):
pass |
class roiData:
def __init__(self, roistates, numberOfROIs, dicomsPath=None):
self.layers = []
self.roistates = []
self.dicomsPath=dicomsPath
self.originalLenght = len(roistates)
self.numberOfROIs = numberOfROIs
for i, roistate in enumerate(roistates):
... | class Roidata:
def __init__(self, roistates, numberOfROIs, dicomsPath=None):
self.layers = []
self.roistates = []
self.dicomsPath = dicomsPath
self.originalLenght = len(roistates)
self.numberOfROIs = numberOfROIs
for (i, roistate) in enumerate(roistates):
... |
def stringify(token):
if token.orth_ == 'I':
return token.orth_
elif token.is_quote and token.i != 0 and token.nbor(-1).is_space:
return ' ' + token.orth_
elif token.ent_type_ == '':
return token.lower_
else:
return token.orth_
def parse_stack(token):
stack = []
... | def stringify(token):
if token.orth_ == 'I':
return token.orth_
elif token.is_quote and token.i != 0 and token.nbor(-1).is_space:
return ' ' + token.orth_
elif token.ent_type_ == '':
return token.lower_
else:
return token.orth_
def parse_stack(token):
stack = []
... |
def configure(name):
if name == 'compute_mfcc':
return {"--allow-downsample":["false",str],
"--allow-upsample":["false",str],
"--blackman-coeff":[0.42,float],
"--cepstral-lifter":[22,int],
"--channel":[-1,int],
"--debug-mel":["false",str],
"--dither":[1,int],
"--energy-floor":[0,int],
... | def configure(name):
if name == 'compute_mfcc':
return {'--allow-downsample': ['false', str], '--allow-upsample': ['false', str], '--blackman-coeff': [0.42, float], '--cepstral-lifter': [22, int], '--channel': [-1, int], '--debug-mel': ['false', str], '--dither': [1, int], '--energy-floor': [0, int], '--fra... |
class XForwardedHostMiddleware( object ):
"""
A WSGI middleware that changes the HTTP host header in the WSGI environ
based on the X-Forwarded-Host header IF found
"""
def __init__( self, app, global_conf=None ):
self.app = app
def __call__( self, environ, start_response ):
x_fo... | class Xforwardedhostmiddleware(object):
"""
A WSGI middleware that changes the HTTP host header in the WSGI environ
based on the X-Forwarded-Host header IF found
"""
def __init__(self, app, global_conf=None):
self.app = app
def __call__(self, environ, start_response):
x_forwar... |
def sorter(item):
return item['name']
presenters=[
{'name': 'Arthur', 'age': 9},
{'name': 'Nathaniel', 'age': 11}
]
presenters.sort(key=sorter)
print(presenters) | def sorter(item):
return item['name']
presenters = [{'name': 'Arthur', 'age': 9}, {'name': 'Nathaniel', 'age': 11}]
presenters.sort(key=sorter)
print(presenters) |
class FakeCUDAContext(object):
'''
This stub implements functionality only for simulating a single GPU
at the moment.
'''
def __init__(self, device):
self._device = device
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def __str__(... | class Fakecudacontext(object):
"""
This stub implements functionality only for simulating a single GPU
at the moment.
"""
def __init__(self, device):
self._device = device
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def __str_... |
# do NOT import these models here.
# from .model import Word as WordModel
# from .model import Definition as DefinitionModel
class Word(object):
def __init__(self, model):
self.model = model
def set_definition(self, definitions: list):
"""
Replace the existing definition set by the one... | class Word(object):
def __init__(self, model):
self.model = model
def set_definition(self, definitions: list):
"""
Replace the existing definition set by the one given in argument
:param definition:
:return:
"""
for d in definitions:
if not i... |
"""
https://leetcode.com/problems/valid-mountain-array/
Given an array A of integers, return true if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:
A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > ... | """
https://leetcode.com/problems/valid-mountain-array/
Given an array A of integers, return true if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:
A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > ... |
#
# PySNMP MIB module WWP-EXT-BRIDGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-EXT-BRIDGE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:37:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
"""Custom exceptions for the punter package."""
class PunterException(Exception):
def __init__(self, *args, **kwargs):
super(PunterException, self).__init__(*args, **kwargs)
class InvalidAPIKeyException(PunterException):
pass
class InvalidQueryStringException(PunterException):
pass
| """Custom exceptions for the punter package."""
class Punterexception(Exception):
def __init__(self, *args, **kwargs):
super(PunterException, self).__init__(*args, **kwargs)
class Invalidapikeyexception(PunterException):
pass
class Invalidquerystringexception(PunterException):
pass |
n, q = map(int, input().split())
d = {}
init = input().split()
for i in range(1, n+1):
d[i] = init[i-1]
for j in range(q):
line = input().split()
req = line[0]
if req == '1':
d[int(line[1])] = line[2]
else:
print(abs(int(d[int(line[1])]) - int(d[int(line[2])]))) | (n, q) = map(int, input().split())
d = {}
init = input().split()
for i in range(1, n + 1):
d[i] = init[i - 1]
for j in range(q):
line = input().split()
req = line[0]
if req == '1':
d[int(line[1])] = line[2]
else:
print(abs(int(d[int(line[1])]) - int(d[int(line[2])]))) |
"""Work in Progress Template based on Shoelace"""
# import pathlib
# import jinja2
# import panel as pn
# ROOT = pathlib.Path(__file__).parent
# JS = (ROOT / "index.js").read_text()
# CSS = (ROOT / "index.css").read_text()
# TEMPLATES_FOLDER = str(ROOT / "templates")
# bokehLoader = jinja2.PackageLoader... | """Work in Progress Template based on Shoelace""" |
# Link to problem : https://leetcode.com/problems/remove-element/
class Solution:
def removeElement(self, nums ,val):
count = 0
for i in range(len(nums)):
if(nums[i] != val):
nums[count] = nums[i]
count += 1
return count | class Solution:
def remove_element(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
return count |
"""
@file
@brief Shortcut to *parsers*.
"""
| """
@file
@brief Shortcut to *parsers*.
""" |
while True:
n = int(input())
if not n: break
s = 0
for i in range(n):
s += [int(x) for x in input().split()][1] // 2
print(s//2)
| while True:
n = int(input())
if not n:
break
s = 0
for i in range(n):
s += [int(x) for x in input().split()][1] // 2
print(s // 2) |
new_minimum_detection = input("What is the minimum confidence?: ")
with open('object_detection_webcam.py', 'r') as file:
lines = file.readlines()
for line in lines:
if line[0:18] == ' min_detection_':
line = ' min_detection_confidence = '+new_minimum_detection+' ###EDITE... | new_minimum_detection = input('What is the minimum confidence?: ')
with open('object_detection_webcam.py', 'r') as file:
lines = file.readlines()
for line in lines:
if line[0:18] == ' min_detection_':
line = ' min_detection_confidence = ' + new_minimum_detection + ' ###EDITED B... |
# class Student(object):
# def __init__(self, name, score):
# self.name = name
# self.score = score
# def print_score(self):
# print('%s: %s' % (self.name, self.score))
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score... | class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
fyp = student('fyp', 59)
print('fyp===>', fyp)
print('fyp===>', fyp.name)
print('fyp===>', fyp.score) |
"""Demonstrate module statements being executed on first import."""
print("Initialise", __name__)
def fib(n: int) -> None:
"""Write Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=" ")
a, b = b, a + b
print()
| """Demonstrate module statements being executed on first import."""
print('Initialise', __name__)
def fib(n: int) -> None:
"""Write Fibonacci series up to n."""
(a, b) = (0, 1)
while a < n:
print(a, end=' ')
(a, b) = (b, a + b)
print() |
#
# 359. Logger Rate Limiter
#
# Q: https://leetcode.com/problems/logger-rate-limiter/
# A: https://leetcode.com/problems/logger-rate-limiter/discuss/473779/Javascript-Python3-C%2B%2B-hash-table
#
class Logger:
def __init__(self):
self.m = {}
def shouldPrintMessage(self, t: int, s: str) -> bool:
... | class Logger:
def __init__(self):
self.m = {}
def should_print_message(self, t: int, s: str) -> bool:
m = self.m
if not s in m or 10 <= t - m[s]:
m[s] = t
return True
return False |
"""
dp[i][k] := the minimal number of characters that needed to change for s[:i] with k disjoint substrings
"""
class Solution(object):
def palindromePartition(self, s, K):
def count(r, l):
c = 0
while r>l:
if s[r]!=s[l]: c += 1
r -= 1
... | """
dp[i][k] := the minimal number of characters that needed to change for s[:i] with k disjoint substrings
"""
class Solution(object):
def palindrome_partition(self, s, K):
def count(r, l):
c = 0
while r > l:
if s[r] != s[l]:
c += 1
... |
for t in range(int(input())):
a=int(input())
s=input()
L=[]
for i in range(0,a*8,8):
b=s[i:i+8]
k=0
for i in range(8):
if b[i] == 'I':
k += 2**(7-i)
L.append(k)
print("Case #"+str(t+1),end=": ")
for i in L:
print(chr(i),end="")
... | for t in range(int(input())):
a = int(input())
s = input()
l = []
for i in range(0, a * 8, 8):
b = s[i:i + 8]
k = 0
for i in range(8):
if b[i] == 'I':
k += 2 ** (7 - i)
L.append(k)
print('Case #' + str(t + 1), end=': ')
for i in L:
... |
# A program to display a number of seconds in other units
data = 75475984
changedData = data
years = 0
days = 0
hours = 0
minutes = 0
seconds = 0
now = 0
if data == 0:
now = 1
for i in range(100):
if changedData >= 31556952:
years += 1
changedData -= 31556952
for i in range(365):
if cha... | data = 75475984
changed_data = data
years = 0
days = 0
hours = 0
minutes = 0
seconds = 0
now = 0
if data == 0:
now = 1
for i in range(100):
if changedData >= 31556952:
years += 1
changed_data -= 31556952
for i in range(365):
if changedData >= 86400:
days += 1
changed_data -= ... |
nombre=input("nombre del archivo? ")
f=open(nombre,"r")
palabras=[]
for linea in f:
palabras.extend(linea.split())
print(palabras)
| nombre = input('nombre del archivo? ')
f = open(nombre, 'r')
palabras = []
for linea in f:
palabras.extend(linea.split())
print(palabras) |
# %% [278. First Bad Version](https://leetcode.com/problems/first-bad-version/)
class Solution:
def firstBadVersion(self, n):
lo, up = 0, n
while up - lo > 1:
mid = (lo + up) // 2
if isBadVersion(mid):
up = mid
else:
lo = mid
... | class Solution:
def first_bad_version(self, n):
(lo, up) = (0, n)
while up - lo > 1:
mid = (lo + up) // 2
if is_bad_version(mid):
up = mid
else:
lo = mid
return up |
# dataset settings
data_root = 'data/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (256, 512)
train_pipeline = [
dict(type='LoadImageFromFile_Semi'),
dict(type='LoadAnnotations_Semi'),
dict(type='RandomCrop_Semi', crop_size=crop_size, cat_max_rat... | data_root = 'data/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (256, 512)
train_pipeline = [dict(type='LoadImageFromFile_Semi'), dict(type='LoadAnnotations_Semi'), dict(type='RandomCrop_Semi', crop_size=crop_size, cat_max_ratio=0.75), dict(type='RandomFlip_... |
"""
You are going to be given a word. Your job is to return the middle character of the word.
If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("m... | """
You are going to be given a word. Your job is to return the middle character of the word.
If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("m... |
P, T = map(int, input().split())
solved = 0
for _ in range(P):
flag = True
for _ in range(T):
test1 = input().strip()
test = test1[0].lower() + test1[1:]
if test == test1.lower():
continue
else:
flag = False
if flag:
solved += 1
print(solved) | (p, t) = map(int, input().split())
solved = 0
for _ in range(P):
flag = True
for _ in range(T):
test1 = input().strip()
test = test1[0].lower() + test1[1:]
if test == test1.lower():
continue
else:
flag = False
if flag:
solved += 1
print(solved) |
# accounts.tests
# Tests for the account app
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Wed May 02 15:41:44 2018 -0400
#
# ID: __init__.py [0395481] benjamin@bengfort.com $
"""
Tests for the account app
"""
| """
Tests for the account app
""" |
def nb_year(p0, percent, aug, p):
year = 0
while p0 < p:
p0 = int(p0 + p0*(percent/100) + aug)
year += 1
print(p0)
return year
print(nb_year(1000, 2, 50, 1200)) | def nb_year(p0, percent, aug, p):
year = 0
while p0 < p:
p0 = int(p0 + p0 * (percent / 100) + aug)
year += 1
print(p0)
return year
print(nb_year(1000, 2, 50, 1200)) |
# custom exceptions for ElasticSearch
class SearchException(Exception):
pass
class IndexNotFoundError(SearchException):
pass
class MalformedQueryError(SearchException):
pass
class SearchUnavailableError(SearchException):
pass
| class Searchexception(Exception):
pass
class Indexnotfounderror(SearchException):
pass
class Malformedqueryerror(SearchException):
pass
class Searchunavailableerror(SearchException):
pass |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 14 08:35:11 2019
@author: NOTEBOOK
"""
def main():
print ('First Rectangle Details')
length1 = float(input('Enter length: '))
width1 = float(input('Enter width: '))
area_1 = length1 * width1
print('The area of the Rectangle is',format(area_1,'.2f'))
... | """
Created on Sat Dec 14 08:35:11 2019
@author: NOTEBOOK
"""
def main():
print('First Rectangle Details')
length1 = float(input('Enter length: '))
width1 = float(input('Enter width: '))
area_1 = length1 * width1
print('The area of the Rectangle is', format(area_1, '.2f'))
print('second Rectan... |
print("Digite um numero...")
numero = int(input()); numero
numeroSucessor = print(numero + 1);
numeroAntecessor = print(numero - 1);
print("o seu valor eh {}, seu sucessor eh {} e o seu antecessor eh {}".format(numero, numeroSucessor, numeroAntecessor));
| print('Digite um numero...')
numero = int(input())
numero
numero_sucessor = print(numero + 1)
numero_antecessor = print(numero - 1)
print('o seu valor eh {}, seu sucessor eh {} e o seu antecessor eh {}'.format(numero, numeroSucessor, numeroAntecessor)) |
host_='127.0.0.1'
port_=8086
user_='user name'
pass_ ='user password'
protocol='line'
air_api_key="air api key"
weather_api_key="weather_api_key" | host_ = '127.0.0.1'
port_ = 8086
user_ = 'user name'
pass_ = 'user password'
protocol = 'line'
air_api_key = 'air api key'
weather_api_key = 'weather_api_key' |
MASTER_KEY = "masterKey"
BASE_URL = "http://127.0.0.1:7700"
INDEX_UID = "indexUID"
INDEX_UID2 = "indexUID2"
INDEX_UID3 = "indexUID3"
INDEX_UID4 = "indexUID4"
INDEX_FIXTURE = [
{"uid": INDEX_UID},
{"uid": INDEX_UID2, "options": {"primaryKey": "book_id"}},
{"uid": INDEX_UID3, "options": {"uid": "wrong", "pr... | master_key = 'masterKey'
base_url = 'http://127.0.0.1:7700'
index_uid = 'indexUID'
index_uid2 = 'indexUID2'
index_uid3 = 'indexUID3'
index_uid4 = 'indexUID4'
index_fixture = [{'uid': INDEX_UID}, {'uid': INDEX_UID2, 'options': {'primaryKey': 'book_id'}}, {'uid': INDEX_UID3, 'options': {'uid': 'wrong', 'primaryKey': 'boo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Inyourshoes(object):
def __init__(self, nlp, object):
self.object = object
self.matcher = object.matcher.Matcher(nlp.vocab)
self.matcher.add("Inyourshoes", None,
#what i would do
[{'LOWER': 'what'... | class Inyourshoes(object):
def __init__(self, nlp, object):
self.object = object
self.matcher = object.matcher.Matcher(nlp.vocab)
self.matcher.add('Inyourshoes', None, [{'LOWER': 'what'}, {'LOWER': 'i'}, {'LOWER': 'would'}, {'LOWER': 'do'}], [{'LOWER': 'if'}, {'LOWER': 'i'}, {'LOWER': 'were... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_len = start = 0
m = {}
for end, char in enumerate(s):
if m.get(char, -1) >= start: # if in the current range
start = m[char] + 1
max_len = max(max_len, end - start + 1)
... | class Solution:
def length_of_longest_substring(self, s: str) -> int:
max_len = start = 0
m = {}
for (end, char) in enumerate(s):
if m.get(char, -1) >= start:
start = m[char] + 1
max_len = max(max_len, end - start + 1)
m[char] = end
... |
if __name__ == "__main__":
null = "null"
placeholder = null
undefined = "undefined"
| if __name__ == '__main__':
null = 'null'
placeholder = null
undefined = 'undefined' |
# optimized_primality_test : O(sqrt(n)) - if x divide n then n/x = y which divides n as well, so we need to check only
# numbers from 1 to sqrt(n). sqrt(n) is border because sqrt(n) * sqrt(n) gives n, which then implies that values after
# sqrt(n) need to be multiplied by values lesser then sqrt(n) which we already che... | def primality_test(num):
i = 2
while i * i <= num:
if num % i == 0:
return False
i += 1
return True
print(primality_test(6793)) |
Elements_Symbols_Reverse = {
"H":"Hydrogen",
"He":"Helium",
"Li":"Lithium",
"Be":"Beryllium",
"B":"Boron",
"C":"Carbon",
"N":"Nitrogen",
"O":"Oxygen",
"F":"Fluorine",
"Ne":"Neon",
"Na":"Sodium",
"Mg":"Magnesium",
"Al":"Aluminium",
"Si":"Silicon",
"P":"Phosphorus",
"S":"Sulphur",
"Cl":"Chlorine",
"Ar":"Argon",
"K":"Pota... | elements__symbols__reverse = {'H': 'Hydrogen', 'He': 'Helium', 'Li': 'Lithium', 'Be': 'Beryllium', 'B': 'Boron', 'C': 'Carbon', 'N': 'Nitrogen', 'O': 'Oxygen', 'F': 'Fluorine', 'Ne': 'Neon', 'Na': 'Sodium', 'Mg': 'Magnesium', 'Al': 'Aluminium', 'Si': 'Silicon', 'P': 'Phosphorus', 'S': 'Sulphur', 'Cl': 'Chlorine', 'Ar':... |
# 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 ... | """
Created on Jan 8, 2020
@author: ballance
"""
class Testdata(object):
def __init__(self, teststatus, toolcategory: str, date: str, simtime: float=0.0, timeunit: str='ns', runcwd: str='.', cputime: float=0.0, seed: str='0', cmd: str='', args: str='', compulsory: int=0, user: str='user', cost: float=0.0):
... |
def even_numbers(numbers):
even = []
for num in numbers:
if num % 2 == 0:
even.append(num)
return even
def odd_numbers(numbers):
odd = []
for num in numbers:
if num % 2 != 0:
odd.append(num)
return odd
def sum_numbers(numbers):
sum = 0
for num ... | def even_numbers(numbers):
even = []
for num in numbers:
if num % 2 == 0:
even.append(num)
return even
def odd_numbers(numbers):
odd = []
for num in numbers:
if num % 2 != 0:
odd.append(num)
return odd
def sum_numbers(numbers):
sum = 0
for num in... |
'''
disjoint set forest implementation, uses union by rank and path compression
worst case T.C for find_set is O(logn) in first find_set operation
T.C for union and create_set is O(1)
'''
class Node:
# the identity of node(member of set) is given by data, parent_link, rank
def __init__(self, data=None, rank=N... | """
disjoint set forest implementation, uses union by rank and path compression
worst case T.C for find_set is O(logn) in first find_set operation
T.C for union and create_set is O(1)
"""
class Node:
def __init__(self, data=None, rank=None, parent_link=None):
self.data = data
self.rank = rank
... |
'''# from app.game import determine_winner
# FYI normally we'd have this application code (determine_winner()) in another file,
# ... but for this exercise we'll keep it here
def determine_winner(user_choice, computer_choice):
return "rock" # todo: write logic here to make the tests pass!
if user_choice == com... | """# from app.game import determine_winner
# FYI normally we'd have this application code (determine_winner()) in another file,
# ... but for this exercise we'll keep it here
def determine_winner(user_choice, computer_choice):
return "rock" # todo: write logic here to make the tests pass!
if user_choice == com... |
N = int(input())
a = list(map(int, input().split()))
for i, _ in sorted(enumerate(a), key=lambda x: x[1], reverse=True):
print(i + 1)
| n = int(input())
a = list(map(int, input().split()))
for (i, _) in sorted(enumerate(a), key=lambda x: x[1], reverse=True):
print(i + 1) |
class Environment:
def __init__(self, width=1000, height=1000):
self.width = width
self.height = height
self.agent = None
self.doors = []
def add_door(self, door):
self.doors.append(door)
def get_env_size(self):
size = (self.height, self.width)
return size
| class Environment:
def __init__(self, width=1000, height=1000):
self.width = width
self.height = height
self.agent = None
self.doors = []
def add_door(self, door):
self.doors.append(door)
def get_env_size(self):
size = (self.height, self.width)
retu... |
# custom exceptions
class PybamWarn(Exception):
pass
class PybamError(Exception):
pass
| class Pybamwarn(Exception):
pass
class Pybamerror(Exception):
pass |
################################################################################
# Copyright (c) 2015-2018 Skymind, Inc.
#
# This program and the accompanying materials are made available under the
# terms of the Apache License, Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0.
#
# Unless... | class Optype(object):
transform = 0
accumulation = 1
index_accumulation = 2
scalar = 3
broadcast = 4
pairwise = 5
accumulation3 = 6
summarystats = 7
shape = 8
aggregation = 9
random = 10
custom = 11
graph = 12
variable = 30
boolean = 40
logic = 119 |
'''Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise.
For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3.
Note that ... | """Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise.
For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3.
Note that ... |
class UndergroundSystem(object):
def __init__(self):
# record the customer's starting trip
# card ID: [station, t]
self.customer_trip = {}
# record the average travel time from start station to end station
# (start, end): [t, times]
self.trips = {}
def checkIn(... | class Undergroundsystem(object):
def __init__(self):
self.customer_trip = {}
self.trips = {}
def check_in(self, id, stationName, t):
self.customer_trip[id] = [stationName, t]
def check_out(self, id, stationName, t):
(start_station, start_t) = self.customer_trip[id]
... |
# Black list for auto vote cast
Blacklist_team = ["Royal Never Give Up", "NAVI"]
Blacklist_game = ["CSGO"]
Blacklist_event = []
# Program debug
debugLevel = 0
# Switch of auto vote cast function
autoVote = True
# Cycle of tasks (seconds)
cycleTime = 1800
| blacklist_team = ['Royal Never Give Up', 'NAVI']
blacklist_game = ['CSGO']
blacklist_event = []
debug_level = 0
auto_vote = True
cycle_time = 1800 |
print("Calorie Calulator")
FAT = float(input("Enter grams of fat: "))
CARBOHYDRATES = float(input("Enter grams of Carbohydrates: "))
PROTEIN= float(input("Enter grams of Protein: "))
Fatg = 9 * FAT
print("Number of calories from Fat is: " + str(Fatg))
Protieng = 4 * PROTEIN
print("Number of calories from Prote... | print('Calorie Calulator')
fat = float(input('Enter grams of fat: '))
carbohydrates = float(input('Enter grams of Carbohydrates: '))
protein = float(input('Enter grams of Protein: '))
fatg = 9 * FAT
print('Number of calories from Fat is: ' + str(Fatg))
protieng = 4 * PROTEIN
print('Number of calories from Protein is: '... |
# sudoku solver with backtracking algorithm...
board = [[4,0,0,0,1,0,3,0,0],
[0,6,0,4,0,7,0,0,0],
[0,5,0,0,3,2,1,4,0],
[9,0,4,0,0,1,0,8,5],
[0,0,6,0,0,0,9,0,0],
[3,1,0,7,0,0,6,0,4],
[0,4,9,5,7,0,0,3,0],
[0,0,0,1,0,4,0,7,0],
[0,0,1,0,9,0,0,0,2]]
... | board = [[4, 0, 0, 0, 1, 0, 3, 0, 0], [0, 6, 0, 4, 0, 7, 0, 0, 0], [0, 5, 0, 0, 3, 2, 1, 4, 0], [9, 0, 4, 0, 0, 1, 0, 8, 5], [0, 0, 6, 0, 0, 0, 9, 0, 0], [3, 1, 0, 7, 0, 0, 6, 0, 4], [0, 4, 9, 5, 7, 0, 0, 3, 0], [0, 0, 0, 1, 0, 4, 0, 7, 0], [0, 0, 1, 0, 9, 0, 0, 0, 2]]
def find_empty():
for i in range(0, 9):
... |
# https://www.hackerrank.com/challenges/ctci-is-binary-search-tree
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_binary_search_tree_(root):
# To check if its a binary search tree, do an inorder search
#... | """ Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_binary_search_tree_(root):
def in_order(node):
arr = []
if node is None:
return []
arr.extend(in_order(node.left))
... |
class Solution(object):
def searchInsert(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length=len(nums)
l=0
r=length-1
while l<=r:
if l==r:
return l if nums[l]>=target else l+1
... | class Solution(object):
def search_insert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
l = 0
r = length - 1
while l <= r:
if l == r:
return l if nums[l] >= targ... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 Thom Janssen <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, w... | empty_bytes = bytes(4)
print(type(empty_bytes))
print(empty_bytes)
mutable_bytes = bytearray(empty_bytes)
print(mutable_bytes)
mutable_bytes = bytearray(b'\x00\x0f')
mutable_bytes[0] = 255
mutable_bytes.append(255)
print(mutable_bytes)
immutable_bytes = bytes(mutable_bytes)
print(immutable_bytes)
s = b'bla'
print(s.dec... |
# import math
# import numpy as np
def lagrange(f, xs, x):
ys = [f(i) for i in xs]
n = len(xs)
y = 0
for k in range(0, n):
t = 1
for j in range(0, n):
if j != k:
s = (x - xs[j]) / (xs[k] - xs[j])
t = t * s
y = y + t * ys[k]
retur... | def lagrange(f, xs, x):
ys = [f(i) for i in xs]
n = len(xs)
y = 0
for k in range(0, n):
t = 1
for j in range(0, n):
if j != k:
s = (x - xs[j]) / (xs[k] - xs[j])
t = t * s
y = y + t * ys[k]
return y
def difference_quotient(f, xs):
... |
def find_neighbors(index, width, height, costmap, orthogonal_step_cost):
"""
Identifies neighbor nodes inspecting the 8 adjacent neighbors
Checks if neighbor is inside the map boundaries and if is not an obstacle according to a threshold
Returns a list with valid neighbour nodes as [index, step_cost] pairs
""... | def find_neighbors(index, width, height, costmap, orthogonal_step_cost):
"""
Identifies neighbor nodes inspecting the 8 adjacent neighbors
Checks if neighbor is inside the map boundaries and if is not an obstacle according to a threshold
Returns a list with valid neighbour nodes as [index, step_cost] pairs
... |
#! /usr/bin/env python3
'''
Problem 52 - Project Euler
http://projecteuler.net/index.php?section=problems&id=052
'''
def samedigits(x,y):
return set(str(x)) == set(str(y))
if __name__ == '__main__':
maxn = 6
x = 1
while True:
for n in range(2, maxn+1):
if not samedigits(x, x * n):
... | """
Problem 52 - Project Euler
http://projecteuler.net/index.php?section=problems&id=052
"""
def samedigits(x, y):
return set(str(x)) == set(str(y))
if __name__ == '__main__':
maxn = 6
x = 1
while True:
for n in range(2, maxn + 1):
if not samedigits(x, x * n):
break
... |
##Write code to assign the number of characters in the string rv to a variable num_chars.
rv = """Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore,
While I nodded, nearly napping, suddenly there came a tapping,
As of some one gently rapp... | rv = "Once upon a midnight dreary, while I pondered, weak and weary,\n Over many a quaint and curious volume of forgotten lore,\n While I nodded, nearly napping, suddenly there came a tapping,\n As of some one gently rapping, rapping at my chamber door.\n 'Tis some visitor, I muttered, tapping at my chamber... |
"""
Leetcode
209. Minimum Size Subarray Sum
Given an array of positive integers nums and a positive integer target, return the minimal length
of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than
or equal to target. If there is no such subarray, return 0 instead.
... | """
Leetcode
209. Minimum Size Subarray Sum
Given an array of positive integers nums and a positive integer target, return the minimal length
of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than
or equal to target. If there is no such subarray, return 0 instead.
... |
# 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... | def dump(obj):
s = ''
for attr in dir(obj):
if not attr.startswith('__'):
s += 'obj.%s = %s\n' % (attr, getattr(obj, attr))
return s
def merge_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
if not y:
return x
z = x.copy()
z.upda... |
'''
Given an array of integers what is the length of the longest subArray containing no more than two
distinct values such that the distinct values differ by no more than 1
For Example:
arr = [0, 1, 2, 1, 2, 3] -> length = 4; [1,2,1,2]
arr = [1, 2, 3, 4, 5] -> length = 2; [1,2]
arr = [1, 1, 1, 3, 3, 2, 2] -> length = ... | """
Given an array of integers what is the length of the longest subArray containing no more than two
distinct values such that the distinct values differ by no more than 1
For Example:
arr = [0, 1, 2, 1, 2, 3] -> length = 4; [1,2,1,2]
arr = [1, 2, 3, 4, 5] -> length = 2; [1,2]
arr = [1, 1, 1, 3, 3, 2, 2] -> length = ... |
#!/usr/bin/env python3
#
# --- Day 21: Dirac Dice / Part Two ---
#
# Now that you're warmed up, it's time to play the real game.
#
# A second compartment opens, this time labeled Dirac dice. Out of it falls
# a single three-sided die.
#
# As you experiment with the die, you feel a little strange. An informational
# bro... | input_file = 'input.txt'
goal = 21
player_1 = 0
player_2 = 1
cache = {}
def game(possibilities, positions, scores, turn=0):
uuid = (tuple(positions), tuple(scores), turn)
if uuid in CACHE:
return CACHE[uuid]
player = PLAYER_1 if turn % 2 == 0 else PLAYER_2
turn = (turn + 1) % 2
wins = [0, 0... |
# write recursively
# ie
# 10 > 7+3 or 5+5
# 7+3 is done
# 5+5 -> 3 + 2 + 5
# 3+ 2 + 5 -> 3 + 2 + 3 + 2 is done
# if the number youre breaking is even you get 2 initially, if its odd you get 1 more sum
def solve():
raise NotImplementedError
if __name__ == '__main__':
print(solve())
| def solve():
raise NotImplementedError
if __name__ == '__main__':
print(solve()) |
# -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2020 IBM Corp. 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
#
#... | """Trestle core errors module."""
class Trestleerror(RuntimeError):
"""
General framework (non-application) related errors.
Attributes:
msg (str): Human readable string describing the exception.
"""
def __init__(self, msg: str):
"""Intialization for TresleError.
Args:
... |
guest = input()
host = input()
pile = input()
print("YES" if sorted(pile) == sorted(guest + host) else "NO")
| guest = input()
host = input()
pile = input()
print('YES' if sorted(pile) == sorted(guest + host) else 'NO') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Bellkor.Utils
"""
| """ Bellkor.Utils
""" |
# -*- coding: utf-8 -*-
def write_out(message):
with open('/tmp/out', 'w') as f:
f.write("We have triggered.")
f.write(message)
| def write_out(message):
with open('/tmp/out', 'w') as f:
f.write('We have triggered.')
f.write(message) |
class Arithmatic:
#This function does adding to integer
def Add(self, x, y):
return x + y
#This fnction does su
def Subtraction(self, x, y):
return x - y
| class Arithmatic:
def add(self, x, y):
return x + y
def subtraction(self, x, y):
return x - y |
def category(cat):
def set_cat(cmd):
cmd.category = cat.title()
return cmd
return set_cat | def category(cat):
def set_cat(cmd):
cmd.category = cat.title()
return cmd
return set_cat |
'''
File to calculate the Budget associated with new motorcycle
'''
class Budget(object):
def __init__(self):
self.price = 13000
self.years = 5
self.interet = 7
def pvtx(self):
"""Calcul of the provincial tax on sale price"""
return self.price * 0.0975
def fdtx(sel... | """
File to calculate the Budget associated with new motorcycle
"""
class Budget(object):
def __init__(self):
self.price = 13000
self.years = 5
self.interet = 7
def pvtx(self):
"""Calcul of the provincial tax on sale price"""
return self.price * 0.0975
def fdtx(se... |
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module contains utility functions."""
def sorted_by_key(x, i, reverse=False):
"""For a list of lists/tuples, return list sorted by the ith
component of the list/tuple,
Examples:
Sort on first entry of tuple:
... | """This module contains utility functions."""
def sorted_by_key(x, i, reverse=False):
"""For a list of lists/tuples, return list sorted by the ith
component of the list/tuple,
Examples:
Sort on first entry of tuple:
>>> sorted_by_key([(1, 2), (5, 1)], 0)
[(1, 2), (5, ... |
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
def isValid(str1, str2, num):
if not num:
return True
res = str(int(str1) + int(str2))
# print(str1, str2, res, num)
str1, str2 = str2, res
l = len(res)
retur... | class Solution:
def is_additive_number(self, num: str) -> bool:
def is_valid(str1, str2, num):
if not num:
return True
res = str(int(str1) + int(str2))
(str1, str2) = (str2, res)
l = len(res)
return num.startswith(res) and is_vali... |
if __name__ == '__main__':
if (1!=1) : print("IF")
else : print("InnerElse")
else: print("OuterElse")
| if __name__ == '__main__':
if 1 != 1:
print('IF')
else:
print('InnerElse')
else:
print('OuterElse') |
num = int(input())
lista = [[0] * num for i in range(num)]
for i in range(num):
for j in range(num):
if i < j:
lista[i][j] = 0
elif i > j:
lista[i][j] = 2
else:
lista[i][j] = 1
for r in lista:
print(' '.join([str(elem) for elem in r]))
| num = int(input())
lista = [[0] * num for i in range(num)]
for i in range(num):
for j in range(num):
if i < j:
lista[i][j] = 0
elif i > j:
lista[i][j] = 2
else:
lista[i][j] = 1
for r in lista:
print(' '.join([str(elem) for elem in r])) |
def aumentar(preco=0, taxa=0, formato=False):
res = preco + (preco * taxa/100)
return res if formato is False else moeda(res)
def diminuir(preco=0, taxa=0, formato=False):
res = preco - (preco * taxa/100)
return res if formato is False else moeda(res)
def dobro(preco=0, formato=False):
res = pre... | def aumentar(preco=0, taxa=0, formato=False):
res = preco + preco * taxa / 100
return res if formato is False else moeda(res)
def diminuir(preco=0, taxa=0, formato=False):
res = preco - preco * taxa / 100
return res if formato is False else moeda(res)
def dobro(preco=0, formato=False):
res = preco... |
# Copyright 2014 Metaswitch Networks
#
# 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 w... | class Stubnetworksubscriber(object):
"""
Stub version of the Network Subscriber class.
The methods prefixed test_ are for unit test script use.
"""
def __init__(self, network_store):
self.network_store = network_store
def test_update_group(self, group_uuid, members, rules):
""... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... | def test():
assert first_author_name == dataset_description['Authors'][0]['Name'], 'That is not the authors name from the original dictionary'
assert 'first_author_name = output' in __solution__, 'Did you just typed the name in?'
__msg__.good('Well done!') |
class PartyAnimal:
x = 0
def party(self):
self.x = self.x + 1
print(f'So far {self.x}')
an = PartyAnimal()
an.party()
an.party()
an.party()
print(dir(an))
| class Partyanimal:
x = 0
def party(self):
self.x = self.x + 1
print(f'So far {self.x}')
an = party_animal()
an.party()
an.party()
an.party()
print(dir(an)) |
with open("./build-scripts/opcodes.txt", "r") as f:
opcodes = f.readlines()
opcodes_h = open("./src/core/bc_data/opcodes.txt", "w")
opcodes_h.write("enum au_opcode {\n")
callbacks_h = open("./src/core/bc_data/callbacks.txt", "w")
callbacks_h.write("static void *cb[] = {\n")
dbg_h = open("./src/core/bc_data/dbg.t... | with open('./build-scripts/opcodes.txt', 'r') as f:
opcodes = f.readlines()
opcodes_h = open('./src/core/bc_data/opcodes.txt', 'w')
opcodes_h.write('enum au_opcode {\n')
callbacks_h = open('./src/core/bc_data/callbacks.txt', 'w')
callbacks_h.write('static void *cb[] = {\n')
dbg_h = open('./src/core/bc_data/dbg.txt'... |
"""
Iterable - __iter__() or __getitem__()
Iterator - __next__()
Iteration -
"""
def gen(n):
for i in range(n):
yield i
#g = gen(89765456432165464988789465456421321564578979874654654613216547897894654) # dont print number upto n number print location
# print(g)
g = gen(4)
print(g.__ne... | """
Iterable - __iter__() or __getitem__()
Iterator - __next__()
Iteration -
"""
def gen(n):
for i in range(n):
yield i
g = gen(4)
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__()) |
# lets make a Player class
class Player:
def __init__(self, name, starting_room):
self.name = name
self.current_room = starting_room
| class Player:
def __init__(self, name, starting_room):
self.name = name
self.current_room = starting_room |
#!/usr/local/bin/python3
# Frequency queries
def freqQuery(queries):
result = []
numbers = {}
occurrences = {}
for operation, value in queries:
if operation == 1:
quantity = numbers.get(value, 0)
if quantity > 0:
occurrences[quantity] = occurrences[quantity] - 1
numbers[value] = numbers.get(value... | def freq_query(queries):
result = []
numbers = {}
occurrences = {}
for (operation, value) in queries:
if operation == 1:
quantity = numbers.get(value, 0)
if quantity > 0:
occurrences[quantity] = occurrences[quantity] - 1
numbers[value] = number... |
#GuestList:
names = ['tony','steve','thor']
message = ", You are invited!"
print(names[0]+message)
print(names[1]+message)
print(names[2]+message)
| names = ['tony', 'steve', 'thor']
message = ', You are invited!'
print(names[0] + message)
print(names[1] + message)
print(names[2] + message) |
general = {
'provide-edep-targets' : True,
}
edeps = {
'zmdep-b' : {
'rootdir': '../zmdep-b',
'export-includes' : '../zmdep-b',
'buildtypes-map' : {
'debug' : 'mydebug',
'release' : 'myrelease',
},
},
}
subdirs = [ 'libs/core', 'libs/engine' ]
ta... | general = {'provide-edep-targets': True}
edeps = {'zmdep-b': {'rootdir': '../zmdep-b', 'export-includes': '../zmdep-b', 'buildtypes-map': {'debug': 'mydebug', 'release': 'myrelease'}}}
subdirs = ['libs/core', 'libs/engine']
tasks = {'main': {'features': 'cxxprogram', 'source': 'main/main.cpp', 'includes': 'libs', 'use'... |
#exercicio 63
termos = int(input('Quantos termos vc quer na sequencia de fibonacci? '))
c = 1
sequencia = 1
sequencia2 = 0
while c != termos:
fi = (sequencia+sequencia2) - ((sequencia+sequencia2)-sequencia2)
print ('{}'.format(fi), end='- ')
sequencia += sequencia2
sequencia2 = sequencia - sequencia2
... | termos = int(input('Quantos termos vc quer na sequencia de fibonacci? '))
c = 1
sequencia = 1
sequencia2 = 0
while c != termos:
fi = sequencia + sequencia2 - (sequencia + sequencia2 - sequencia2)
print('{}'.format(fi), end='- ')
sequencia += sequencia2
sequencia2 = sequencia - sequencia2
c += 1 |
##Create a target array in the given order
def generate_target_array(nums, index):
length_of_num = len(nums)
target_array = []
for i in range(0, length_of_num):
if index[i] >= length_of_num:
target_array.append(nums[i])
else:
target_array.insert(index[i], nums[i])
... | def generate_target_array(nums, index):
length_of_num = len(nums)
target_array = []
for i in range(0, length_of_num):
if index[i] >= length_of_num:
target_array.append(nums[i])
else:
target_array.insert(index[i], nums[i])
return target_array
if __name__ == '__main... |
class ExtractedItem:
def __init__(self, _id=None, field_name=None, data=None):
self.data = data if data else None
self._id = _id
self.field_name = field_name
def get_dict(self):
"""
returns the data in json format
:return:
"""
if self.field_name:... | class Extracteditem:
def __init__(self, _id=None, field_name=None, data=None):
self.data = data if data else None
self._id = _id
self.field_name = field_name
def get_dict(self):
"""
returns the data in json format
:return:
"""
if self.field_name:... |
"""
Module: 'uasyncio.core' on pyboard 1.13.0-95
"""
# MCU: (sysname='pyboard', nodename='pyboard', release='1.13.0', version='v1.13-95-g0fff2e03f on 2020-10-03', machine='PYBv1.1 with STM32F405RG')
# Stubber: 1.3.4
class CancelledError:
''
class IOQueue:
''
def _dequeue():
pass
def _enqueue(... | """
Module: 'uasyncio.core' on pyboard 1.13.0-95
"""
class Cancellederror:
""""""
class Ioqueue:
""""""
def _dequeue():
pass
def _enqueue():
pass
def queue_read():
pass
def queue_write():
pass
def remove():
pass
def wait_io_event():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.