content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
def insert_after(self, value):
pass
def insert_before(self, value):
pass
def delete(self):
pass
class DoublyLinkedList:
def __init__(self, node=None):
self.head... | class Listnode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
def insert_after(self, value):
pass
def insert_before(self, value):
pass
def delete(self):
pass
class Doublylinkedlist:
def __in... |
"""Class for converter models."""
class InverterModels:
"""
SwitcInverter class.
Attributes:
():
"""
def ODE_model_single_phase_EMT(self,y,t,signals,grid,sim):
"""ODE model of inverter branch."""
self.ia,dummy = y # unpack current values of y... | """Class for converter models."""
class Invertermodels:
"""
SwitcInverter class.
Attributes:
():
"""
def ode_model_single_phase_emt(self, y, t, signals, grid, sim):
"""ODE model of inverter branch."""
(self.ia, dummy) = y
vdc = 100.0
control_si... |
def count(start=0, step=1):
while True:
yield start
start += step
def cycle(p):
try:
len(p)
except TypeError:
# len() is not defined for this type. Assume it is
# a finite iterable so we must cache the elements.
cache = []
for i in p:
yie... | def count(start=0, step=1):
while True:
yield start
start += step
def cycle(p):
try:
len(p)
except TypeError:
cache = []
for i in p:
yield i
cache.append(i)
p = cache
while p:
yield from p
def repeat(el, n=None):
if n ... |
'''
Assembling your data
Here, three DataFrames have been pre-loaded: g1800s, g1900s, and g2000s. These contain the Gapminder life expectancy data for, respectively, the 19th century, the 20th century, and the 21st century.
Your task in this exercise is to concatenate them into a single DataFrame called gapminder. Th... | """
Assembling your data
Here, three DataFrames have been pre-loaded: g1800s, g1900s, and g2000s. These contain the Gapminder life expectancy data for, respectively, the 19th century, the 20th century, and the 21st century.
Your task in this exercise is to concatenate them into a single DataFrame called gapminder. Th... |
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.data.append(x)
def pop(self):
"""
:rtype: void
... | class Minstack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.data.append(x)
def pop(self):
"""
:rtype: void
... |
description = 'collimator setup'
group = 'lowlevel'
devices = dict(
tof_io = device('nicos.devices.generic.ManualSwitch',
description = 'ToF',
states = [1, 2, 3],
lowlevel = True,
),
L = device('nicos.devices.generic.Switcher',
description = 'Distance',
moveable = '... | description = 'collimator setup'
group = 'lowlevel'
devices = dict(tof_io=device('nicos.devices.generic.ManualSwitch', description='ToF', states=[1, 2, 3], lowlevel=True), L=device('nicos.devices.generic.Switcher', description='Distance', moveable='tof_io', mapping={10: 1, 13: 2, 17: 3}, unit='m', precision=0), collima... |
inf = 2**33
DEBUG = 0
def bellmanFord(graph, cost, loop, start):
parent = [-1] * len(graph)
cost[start] = 0
for i in range(len(graph) - 1):
for u in range(len(graph)):
for v, c in graph[u]:
if (cost[u] + c < cost[v] and cost[u] != inf):
parent[v] = u
... | inf = 2 ** 33
debug = 0
def bellman_ford(graph, cost, loop, start):
parent = [-1] * len(graph)
cost[start] = 0
for i in range(len(graph) - 1):
for u in range(len(graph)):
for (v, c) in graph[u]:
if cost[u] + c < cost[v] and cost[u] != inf:
parent[v] =... |
def chop(t):
del t[0], t[-1]
return None
def middle(t):
return t[1:-1]
letters = ['a', 'b', 'c', 'd', 'e']
print(middle(letters))
| def chop(t):
del t[0], t[-1]
return None
def middle(t):
return t[1:-1]
letters = ['a', 'b', 'c', 'd', 'e']
print(middle(letters)) |
"""Build extension to generate j2cl-compatible protocol buffers.
Usage:
j2cl_proto: generates a j2cl-compatible java_library for an existing
proto_library.
Example usage:
load("//java/com/google/protobuf/contrib/j2cl:j2cl_proto.bzl", "j2cl_proto_library")
proto_library(
name = "accessor",... | """Build extension to generate j2cl-compatible protocol buffers.
Usage:
j2cl_proto: generates a j2cl-compatible java_library for an existing
proto_library.
Example usage:
load("//java/com/google/protobuf/contrib/j2cl:j2cl_proto.bzl", "j2cl_proto_library")
proto_library(
name = "accessor",... |
# Day 20: http://adventofcode.com/2016/day/20
inp = [(5, 8), (0, 2), (4, 7)]
def allowed(blocked, n):
rng, *blocked = sorted([*r] for r in blocked)
for cur in blocked:
if cur[0] > n:
break
elif cur[0] > rng[-1] + 1:
yield from range(rng[-1] + 1, cur[0])
rng... | inp = [(5, 8), (0, 2), (4, 7)]
def allowed(blocked, n):
(rng, *blocked) = sorted(([*r] for r in blocked))
for cur in blocked:
if cur[0] > n:
break
elif cur[0] > rng[-1] + 1:
yield from range(rng[-1] + 1, cur[0])
rng = cur
else:
rng[-1] = m... |
'''
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
... | """
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
... |
test = { 'name': 'q5_2',
'points': 1,
'suites': [ { 'cases': [ { 'code': '>>> # Hint: If you are getting 47 as your answer, you might be computing the biggest change rather than biggest decrease!;\n'
'>>> biggest_decrease != 47\n'
... | test = {'name': 'q5_2', 'points': 1, 'suites': [{'cases': [{'code': '>>> # Hint: If you are getting 47 as your answer, you might be computing the biggest change rather than biggest decrease!;\n>>> biggest_decrease != 47\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> # Hint: biggest decrease is above 30, but n... |
def best_sum_tab(n, a):
table = [None for i in range(n + 1)]
table[0] = []
for i in range(n + 1):
if table[i] is not None:
for j in a:
if (i + j) < len(table):
temp = table[i] + [j]
if table[i + j] is None:
... | def best_sum_tab(n, a):
table = [None for i in range(n + 1)]
table[0] = []
for i in range(n + 1):
if table[i] is not None:
for j in a:
if i + j < len(table):
temp = table[i] + [j]
if table[i + j] is None:
tab... |
if opt.save_every > 0 and num_updates % opt.save_every == -1 % opt.save_every:
valid_loss = self.eval(self.valid_data)
valid_ppl = math.exp(min(valid_loss, 100))
print('Validation perplexity: %g' % valid_ppl)
ep = float(epoch) - 1. + ((float(i) + 1.) / n_samples)
self.save(ep, valid_ppl, batch_ord... | if opt.save_every > 0 and num_updates % opt.save_every == -1 % opt.save_every:
valid_loss = self.eval(self.valid_data)
valid_ppl = math.exp(min(valid_loss, 100))
print('Validation perplexity: %g' % valid_ppl)
ep = float(epoch) - 1.0 + (float(i) + 1.0) / n_samples
self.save(ep, valid_ppl, batch_order... |
FEATURES = set(
[
"five_prime_utr",
"three_prime_utr",
"CDS",
"exon",
"intron",
"start_codon",
"stop_codon",
"ncRNA",
]
)
NON_CODING_BIOTYPES = set(
[
"Mt_rRNA",
"Mt_tRNA",
"miRNA",
"misc_RNA",
"rRNA",
... | features = set(['five_prime_utr', 'three_prime_utr', 'CDS', 'exon', 'intron', 'start_codon', 'stop_codon', 'ncRNA'])
non_coding_biotypes = set(['Mt_rRNA', 'Mt_tRNA', 'miRNA', 'misc_RNA', 'rRNA', 'scRNA', 'snRNA', 'snoRNA', 'ribozyme', 'sRNA', 'scaRNA', 'lncRNA', 'ncRNA', 'Mt_tRNA_pseudogene', 'tRNA_pseudogene', 'snoRNA... |
# Runtime: 20 ms
# Beats 100% of Python submissions
class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
if s.count("LLL") > 0:
return False
if s.count("A") > 2:
return False
return True
# A more worked ... | class Solution(object):
def check_record(self, s):
"""
:type s: str
:rtype: bool
"""
if s.count('LLL') > 0:
return False
if s.count('A') > 2:
return False
return True |
#Donald Hobson
#A program to make big letters out of small ones
#storeage of pattern to make large letters.
largeLetter=[[" A ",
" A A ",
" AAA ",
"A A",
"A A",],
["BBBB ",
"B B",
"BBBBB",
"B B",
"BBB... | large_letter = [[' A ', ' A A ', ' AAA ', 'A A', 'A A'], ['BBBB ', 'B B', 'BBBBB', 'B B', 'BBBB '], [' cccc', 'c ', 'c ', 'c ', ' cccc'], ['DDDD ', 'D D', 'D D', 'D D', 'DDDD '], ['EEEEE', 'E ', 'EEEE ', 'E ', 'EEEEE'], ['FFFFF', 'F ', 'FFFF ', 'F ', 'F '], [' GGG ', 'G ', 'G ... |
EGAUGE_API_URLS = {
'stored' : 'http://%s.egaug.es/cgi-bin/egauge-show',
'instantaneous' : 'http://%s.egaug.es/cgi-bin/egauge',
}
| egauge_api_urls = {'stored': 'http://%s.egaug.es/cgi-bin/egauge-show', 'instantaneous': 'http://%s.egaug.es/cgi-bin/egauge'} |
t = int(input())
for i in range(t):
n=int(input())
l=0
h=100000
while l<=h:
mid =(l+h)//2
r= (mid*(mid+1))//2
if r>n:
h=mid - 1
else:
ht=mid
l=mid+1
print(ht)
| t = int(input())
for i in range(t):
n = int(input())
l = 0
h = 100000
while l <= h:
mid = (l + h) // 2
r = mid * (mid + 1) // 2
if r > n:
h = mid - 1
else:
ht = mid
l = mid + 1
print(ht) |
"""
Hello world application.
Mostly just to test the Python setup on current computer.
"""
MESSSAGE = "Hello World"
print(MESSSAGE)
| """
Hello world application.
Mostly just to test the Python setup on current computer.
"""
messsage = 'Hello World'
print(MESSSAGE) |
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
dict_val = {}
result1 = []
result2 = []
for val in nums:
dict_val[val] = dict_val.get(val, 0) + 1
if dict_val[val] > 1:
result1.append(val)
else:
... | class Solution:
def single_number(self, nums: List[int]) -> List[int]:
dict_val = {}
result1 = []
result2 = []
for val in nums:
dict_val[val] = dict_val.get(val, 0) + 1
if dict_val[val] > 1:
result1.append(val)
else:
... |
# (c) 2012-2019, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
... | survey_fi_el_ds = ('docs', 'ease_of_use', 'does_what_it_says', 'works_as_is', 'used_in_production')
def calculate_survey_score(surveys):
"""
:var surveys: queryset container all of the surveys for a collection or a
repository
"""
score = 0
answer_count = 0
survey_score = 0.0
for survey ... |
__author__ = 'arid6405'
class SfcsmError(Exception):
def __init__(self, status, message):
self.status = status
self.message = message
def __str__(self):
return "Error {}: {} ".format(self.status, self.message) | __author__ = 'arid6405'
class Sfcsmerror(Exception):
def __init__(self, status, message):
self.status = status
self.message = message
def __str__(self):
return 'Error {}: {} '.format(self.status, self.message) |
"""
The core calculation, ``work_hours+hol_hours- 13*7.4``,
translates as 'the total number of hours minus the number
of mandatory leave days times by the number of hours in the
average working day, which is :math:`\\frac{37}{5}=7.4`, which
altogether gives the total number of hours available to be worked.
Dividin... | """
The core calculation, ``work_hours+hol_hours- 13*7.4``,
translates as 'the total number of hours minus the number
of mandatory leave days times by the number of hours in the
average working day, which is :math:`\\frac{37}{5}=7.4`, which
altogether gives the total number of hours available to be worked.
Dividin... |
def decode(s):
dec = dict()
def dec_pos(x,e):
for i in range(x+1):
e=dec[e]
return e
for i in range(32,127):
dec[encode(chr(i))] = chr(i)
a=''
for index,value in enumerate(s):
a+=dec_pos(index,value)
return a | def decode(s):
dec = dict()
def dec_pos(x, e):
for i in range(x + 1):
e = dec[e]
return e
for i in range(32, 127):
dec[encode(chr(i))] = chr(i)
a = ''
for (index, value) in enumerate(s):
a += dec_pos(index, value)
return a |
print("---------- numero de discos ----------")
def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n - 1 to helper:
hanoi(n - 1, source, target, helper)
print(source, helper, target)
# move disk from source peg to target peg
if source:
target.a... | print('---------- numero de discos ----------')
def hanoi(n, source, helper, target):
if n > 0:
hanoi(n - 1, source, target, helper)
print(source, helper, target)
if source:
target.append(source.pop())
print(source, helper, target)
hanoi(n - 1, helper, source... |
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
k = 0
while n != m:
n >>= 1
m >>= 1
k += 1
return n << k
| class Solution(object):
def range_bitwise_and(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
k = 0
while n != m:
n >>= 1
m >>= 1
k += 1
return n << k |
__author__ = 'schlitzer'
__all__ = [
'AdminError',
'AlreadyAuthenticatedError',
'AuthenticationError',
'BaseError',
'CredentialError',
'DuplicateResource',
'FlowError',
'InvalidBody',
'InvalidFields',
'InvalidName',
'InvalidPaginationLimit',
'InvalidParameterValue',
... | __author__ = 'schlitzer'
__all__ = ['AdminError', 'AlreadyAuthenticatedError', 'AuthenticationError', 'BaseError', 'CredentialError', 'DuplicateResource', 'FlowError', 'InvalidBody', 'InvalidFields', 'InvalidName', 'InvalidPaginationLimit', 'InvalidParameterValue', 'InvalidSelectors', 'InvalidSortCriteria', 'InvalidUUI... |
class Solution:
def twoSum(self, nums: [int], target: int) -> [int]:
d = {int: int}
for i in range(len(nums)):
if target - nums[i] in d:
return [d[target-nums[i]], i]
else:
d[nums[i]] = i
return []
if __name__ == "__main__":
solut... | class Solution:
def two_sum(self, nums: [int], target: int) -> [int]:
d = {int: int}
for i in range(len(nums)):
if target - nums[i] in d:
return [d[target - nums[i]], i]
else:
d[nums[i]] = i
return []
if __name__ == '__main__':
sol... |
#
# PySNMP MIB module HH3C-VSI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-VSI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:15:32 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,... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint) ... |
class RemoveStoryboard(ControllableStoryboardAction):
"""
A trigger action that removes a System.Windows.Media.Animation.Storyboard.
RemoveStoryboard()
"""
| class Removestoryboard(ControllableStoryboardAction):
"""
A trigger action that removes a System.Windows.Media.Animation.Storyboard.
RemoveStoryboard()
""" |
vals = [0,10,-30,173247,123,19892122]
formats = ['%o','%020o', '%-20o', '%#o', '+%o', '+%#o']
for val in vals:
for fmt in formats:
print(fmt+":", fmt % val)
| vals = [0, 10, -30, 173247, 123, 19892122]
formats = ['%o', '%020o', '%-20o', '%#o', '+%o', '+%#o']
for val in vals:
for fmt in formats:
print(fmt + ':', fmt % val) |
class RoutedCommand(object,ICommand):
"""
Defines a command that implements System.Windows.Input.ICommand and is routed through the element tree.
RoutedCommand()
RoutedCommand(name: str,ownerType: Type)
RoutedCommand(name: str,ownerType: Type,inputGestures: InputGestureCollection)
"""
def CanExecut... | class Routedcommand(object, ICommand):
"""
Defines a command that implements System.Windows.Input.ICommand and is routed through the element tree.
RoutedCommand()
RoutedCommand(name: str,ownerType: Type)
RoutedCommand(name: str,ownerType: Type,inputGestures: InputGestureCollection)
"""
def can_execu... |
# File: gcloudcomputeengine_consts.py
#
# Copyright (c) 2021 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
# Define your constants here
COMPUTE = 'compute'
COMPUTE_VERSION = 'v1'
# Error message handling constants
ERR_CODE_MSG = "Error code unavailable"
ERR_MSG_UNAVAILABL... | compute = 'compute'
compute_version = 'v1'
err_code_msg = 'Error code unavailable'
err_msg_unavailable = 'Error message unavailable. Please check the asset configuration and|or action parameters'
parse_err_msg = 'Unable to parse the error message. Please check the asset configuration and|or action parameters' |
#!/usr/bin/env python3
def byterize(obj):
objdict = obj.__dict__['fields']
def do_encode(dictio, key):
if isinstance(dictio[key], str) and len(dictio[key]) > 0 and key not in ['SecondaryAddr']:
dictio[key] = dictio[key].encode('latin-1')
elif hasattr(dictio[key], '__dict__'):
... | def byterize(obj):
objdict = obj.__dict__['fields']
def do_encode(dictio, key):
if isinstance(dictio[key], str) and len(dictio[key]) > 0 and (key not in ['SecondaryAddr']):
dictio[key] = dictio[key].encode('latin-1')
elif hasattr(dictio[key], '__dict__'):
subdictio = dic... |
"""Settings for the kytos/storehouse NApp."""
# Path to serialize the objects, this is relative to a venv, if a venv exists.
CUSTOM_DESTINATION_PATH = "/var/tmp/kytos/storehouse"
| """Settings for the kytos/storehouse NApp."""
custom_destination_path = '/var/tmp/kytos/storehouse' |
class DaftException(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return "Error: " + self.reason
| class Daftexception(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return 'Error: ' + self.reason |
class Solution:
def transformArray(self, arr: List[int]) -> List[int]:
na = arr[:]
stable = False
while not stable:
stable = True
for i in range(1, len(arr) - 1):
if arr[i] < arr[i-1] and arr[i] < arr[i+1]:
na[i] = arr[i] + 1
... | class Solution:
def transform_array(self, arr: List[int]) -> List[int]:
na = arr[:]
stable = False
while not stable:
stable = True
for i in range(1, len(arr) - 1):
if arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
na[i] = arr[i] + 1
... |
try:
p=8778
b=56434
#f = open("ab.txt")
p = b/0
f = open("ab.txt")
for line in f:
print(line)
except FileNotFoundError as e:
print( e.filename)
except Exception as e:
print(e)
except ZeroDivisionError as e:
print(e)
#except (FileNotFoundError , ZeroDivisionError):
... | try:
p = 8778
b = 56434
p = b / 0
f = open('ab.txt')
for line in f:
print(line)
except FileNotFoundError as e:
print(e.filename)
except Exception as e:
print(e)
except ZeroDivisionError as e:
print(e) |
# ***************************************************************************************
# ***************************************************************************************
#
# Name : errors.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 9th December 2018
# Purpose : Error classes
#
# *********... | class Compilerexception(Exception):
def __init__(self, message):
self.message = message
def get(self):
return '{0} ({1}:{2})'.format(self.message, CompilerException.FILENAME, CompilerException.LINENUMBER)
CompilerException.FILENAME = 'test'
CompilerException.LINENUMBER = 42
if __name__ == '__m... |
"""Unit tests for image_uploader.bzl."""
load(
"//skylark:integration_tests.bzl",
"SutComponentInfo"
)
load(
":image_uploader.bzl",
"image_uploader_sut_component",
)
load("//skylark:unittest.bzl", "asserts", "unittest")
load("//skylark:toolchains.bzl", "toolchain_container_images")
# image_uploader_su... | """Unit tests for image_uploader.bzl."""
load('//skylark:integration_tests.bzl', 'SutComponentInfo')
load(':image_uploader.bzl', 'image_uploader_sut_component')
load('//skylark:unittest.bzl', 'asserts', 'unittest')
load('//skylark:toolchains.bzl', 'toolchain_container_images')
def _image_uploader_sut_component_basic_t... |
def get_options_ratio(options, total):
return options / total
def get_faculty_rating(get_options_ratio):
if get_options_ratio > .9 and get_options_ratio < 1:
return "Excellent"
if get_options_ratio > .8 and get_options_ratio < .9:
return "Very Good"
if get_options_ratio > .7 and get_opt... | def get_options_ratio(options, total):
return options / total
def get_faculty_rating(get_options_ratio):
if get_options_ratio > 0.9 and get_options_ratio < 1:
return 'Excellent'
if get_options_ratio > 0.8 and get_options_ratio < 0.9:
return 'Very Good'
if get_options_ratio > 0.7 and get... |
"""Exceptions and Error Handling"""
def assert_(condition, message='', exception_type=AssertionError):
"""Like assert, but with arbitrary exception types."""
if not condition:
raise exception_type(message)
# ------ VALUE ERRORS ------
class ShapeError(ValueError):
pass
class FrequencyValueEr... | """Exceptions and Error Handling"""
def assert_(condition, message='', exception_type=AssertionError):
"""Like assert, but with arbitrary exception types."""
if not condition:
raise exception_type(message)
class Shapeerror(ValueError):
pass
class Frequencyvalueerror(ValueError):
pass
class D... |
'''
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in ... | """
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in ... |
# See readme.md for instructions on running this code.
class HelpHandler(object):
def usage(self):
return '''
This plugin will give info about Zulip to
any user that types a message saying "help".
This is example code; ideally, you would flesh
this out for m... | class Helphandler(object):
def usage(self):
return '\n This plugin will give info about Zulip to\n any user that types a message saying "help".\n\n This is example code; ideally, you would flesh\n this out for more useful help pertaining to\n your Zuli... |
'''
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo... | """
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo... |
"""Top-level package for Railyard."""
__author__ = """Konstantin Taletskiy"""
__email__ = 'konstantin@taletskiy.com'
__version__ = '0.1.0'
| """Top-level package for Railyard."""
__author__ = 'Konstantin Taletskiy'
__email__ = 'konstantin@taletskiy.com'
__version__ = '0.1.0' |
#
# PySNMP MIB module NMS-EPON-ONU-SERIAL-PORT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NMS-EPON-ONU-SERIAL-PORT
# Produced by pysmi-0.3.4 at Mon Apr 29 20:12:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) ... |
# A simple color module I wrote for my projects
# Feel free to copy this script and use it for your own projects!
class Color:
purple = '\033[95m'
blue = '\033[94m'
green = '\033[92m'
yellow = '\033[93m'
red = '\033[91m'
white = '\033[0m'
class textType:
bold = '\033[1m'
underline = ... | class Color:
purple = '\x1b[95m'
blue = '\x1b[94m'
green = '\x1b[92m'
yellow = '\x1b[93m'
red = '\x1b[91m'
white = '\x1b[0m'
class Texttype:
bold = '\x1b[1m'
underline = '\x1b[4m' |
# LC 1268
class TrieNode:
def __init__(self):
self.next = dict()
self.words = list()
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
# node = node.next.setdefault(char, TrieNode())
... | class Trienode:
def __init__(self):
self.next = dict()
self.words = list()
class Trie:
def __init__(self):
self.root = trie_node()
def insert(self, word):
node = self.root
for char in word:
if char not in node.next:
node.next[char] = tr... |
x = int(input())
y = int(input())
print(y % x)
| x = int(input())
y = int(input())
print(y % x) |
class OutputBase:
def __init__(self):
self.output_buffer = []
def __call__(self, obj):
self.write(obj)
def write(self, obj):
pass
def clear(self):
self.output_buffer = []
| class Outputbase:
def __init__(self):
self.output_buffer = []
def __call__(self, obj):
self.write(obj)
def write(self, obj):
pass
def clear(self):
self.output_buffer = [] |
#!/usr/bin/python
# https://po.kattis.com/problems/vandrarhem
class Bed(object):
def __init__(self, price, available_beds):
""" Constructor for Bed """
self.price = int(price)
self.available_beds = int(available_beds)
def is_full(self):
""" Checks if there is a bed of this ty... | class Bed(object):
def __init__(self, price, available_beds):
""" Constructor for Bed """
self.price = int(price)
self.available_beds = int(available_beds)
def is_full(self):
""" Checks if there is a bed of this type available """
return self.available_beds == 0
de... |
DEBUG = False
# if False, "0" will be used
ENABLE_STRING_SEEDING = True
# use headless evaluator
HEADLESS = False
# === Emulator ===
DEVICE_NUM = 1
AVD_BOOT_DELAY = 30
AVD_SERIES = "api19_"
EVAL_TIMEOUT = 120
# if run on Mac OS, use "gtimeout"
TIMEOUT_CMD = "timeout"
# === Env. Paths ===
# path should end with a '/... | debug = False
enable_string_seeding = True
headless = False
device_num = 1
avd_boot_delay = 30
avd_series = 'api19_'
eval_timeout = 120
timeout_cmd = 'timeout'
android_home = '/home/shadeimi/Software/android-sdk-linux/'
working_dir = '/home/shadeimi/Software/eclipseWorkspace/sapienz/'
sequence_length_min = 20
sequence_... |
""" Remove metainfo files in folders, only if they're associated with torrents registered in Transmission.
Usage:
clutchless prune folder [--dry-run] <metainfo> ...
Arguments:
<metainfo> ... Folders to search for metainfo files to remove.
Options:
--dry-run Doesn't delete any files, only outputs w... | """ Remove metainfo files in folders, only if they're associated with torrents registered in Transmission.
Usage:
clutchless prune folder [--dry-run] <metainfo> ...
Arguments:
<metainfo> ... Folders to search for metainfo files to remove.
Options:
--dry-run Doesn't delete any files, only outputs w... |
class InvalidDataFrameException(Exception):
pass
class InvalidCheckTypeException(Exception):
pass
| class Invaliddataframeexception(Exception):
pass
class Invalidchecktypeexception(Exception):
pass |
#!/usr/bin/python
# vim: set ts=4:
# vim: set shiftwidth=4:
# vim: set expandtab:
#-------------------------------------------------------------------------------
#---> Elections supported
#-------------------------------------------------------------------------------
# election id - base_url - election type - year -... | elections = [('20150920', 'http://ekloges.ypes.gr/current', 'v', 2015, True), ('20150125', 'http://ekloges-prev.singularlogic.eu/v2015a', 'v', 2015, True), ('20150705', 'http://ekloges-prev.singularlogic.eu/r2015', 'e', 2015, True), ('20140525', 'http://ekloges-prev.singularlogic.eu/may2014', 'e', 2014, False), ('20120... |
def ortho_locs(row, col):
offsets = [(-1,0), (0,-1), (0,1), (1,0)]
for row_offset, col_offset in offsets:
yield row + row_offset, col + col_offset
def adj_locs(row, col):
offsets = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]
for row_offset, col_offset in offsets:
yiel... | def ortho_locs(row, col):
offsets = [(-1, 0), (0, -1), (0, 1), (1, 0)]
for (row_offset, col_offset) in offsets:
yield (row + row_offset, col + col_offset)
def adj_locs(row, col):
offsets = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for (row_offset, col_offset) in off... |
def GetByTitle(type, title):
type = type.upper()
if type != 'ANIME' and type != 'MANGA':
return False
variables = {
'type' : type,
'search' : title
}
return variables | def get_by_title(type, title):
type = type.upper()
if type != 'ANIME' and type != 'MANGA':
return False
variables = {'type': type, 'search': title}
return variables |
class BaseModel(object):
@classmethod
def connect(cls):
"""
Args:
None
Returns:
None
"""
raise NotImplementedError('model.connect not implemented!')
@classmethod
def create(cls, data):
"""
Args:
data(dict)
... | class Basemodel(object):
@classmethod
def connect(cls):
"""
Args:
None
Returns:
None
"""
raise not_implemented_error('model.connect not implemented!')
@classmethod
def create(cls, data):
"""
Args:
data(dict)
... |
def queryValue(cur, sql, fields=None, error=None) :
row = queryRow(cur, sql, fields, error);
if row is None : return None
return row[0]
def queryRow(cur, sql, fields=None, error=None) :
row = doQuery(cur, sql, fields)
try:
row = cur.fetchone()
return row
except Exception as e:
... | def query_value(cur, sql, fields=None, error=None):
row = query_row(cur, sql, fields, error)
if row is None:
return None
return row[0]
def query_row(cur, sql, fields=None, error=None):
row = do_query(cur, sql, fields)
try:
row = cur.fetchone()
return row
except Exception... |
HEADERS_FOR_HTTP_GET = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
AGE_CATEGORIES = [
'JM10', 'JW10',
'JM11-14', 'JW11-14',
'JM15-17', 'JW15-17',
'SM18-19', 'SW18-19',
'SM20-24', 'SW20-24',
'SM25... | headers_for_http_get = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
age_categories = ['JM10', 'JW10', 'JM11-14', 'JW11-14', 'JM15-17', 'JW15-17', 'SM18-19', 'SW18-19', 'SM20-24', 'SW20-24', 'SM25-29', 'SW25-29', 'SM30-34', 'SW... |
#
# PySNMP MIB module MICOM-IFDNA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MICOM-IFDNA-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) ... |
a = 5
b = 3
def timeit_1():
print(a + b)
c = 8
def timeit_2():
print(a + b + c)
| a = 5
b = 3
def timeit_1():
print(a + b)
c = 8
def timeit_2():
print(a + b + c) |
def some_but_not_all(seq, pred):
has = [False,False]
for it in seq:
has[bool(pred(it))] = True
# exit as fast as possible
if all(has):
return True
# sequennce is scanned with only True or False predictions.
return False | def some_but_not_all(seq, pred):
has = [False, False]
for it in seq:
has[bool(pred(it))] = True
if all(has):
return True
return False |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' A short description of this file
A slightly longer description of this file
can be found under the shorter desription.
'''
def get_code():
''' Get mysterious code... '''
return '100111011111101010110110101100'
| """ A short description of this file
A slightly longer description of this file
can be found under the shorter desription.
"""
def get_code():
""" Get mysterious code... """
return '100111011111101010110110101100' |
class StdoutMock():
def __init__(self, *args, **kwargs):
self.content = ''
def write(self, content):
self.content += content
def read(self):
return self.content
def __str__(self):
return self.read()
| class Stdoutmock:
def __init__(self, *args, **kwargs):
self.content = ''
def write(self, content):
self.content += content
def read(self):
return self.content
def __str__(self):
return self.read() |
"""
uci_bootcamp_2021/examples/functions.py
examples on how to use functions
"""
def y(x, slope, initial_offset):
"""
This is a docstring. it is a piece of living documentation that is attached to the function.
Note: different companies have different styles for docstrings, and this one doesn't fit any o... | """
uci_bootcamp_2021/examples/functions.py
examples on how to use functions
"""
def y(x, slope, initial_offset):
"""
This is a docstring. it is a piece of living documentation that is attached to the function.
Note: different companies have different styles for docstrings, and this one doesn't fit any of... |
def flatten(list):
final = []
for item in list:
final += item
return final
def flattenN(list):
if type(list[0]) != type([]):
return list
return flattenN(flatten(list))
list = [[[1,2],[3,4]],[[3,4],["hello","there"]]]
result = flattenN(list)
print(result)
| def flatten(list):
final = []
for item in list:
final += item
return final
def flatten_n(list):
if type(list[0]) != type([]):
return list
return flatten_n(flatten(list))
list = [[[1, 2], [3, 4]], [[3, 4], ['hello', 'there']]]
result = flatten_n(list)
print(result) |
def imp_notas(quantidade, valor):
return '{:.0f} nota(s) de R$ {:.2f}'.format(quantidade, valor)
def imp_moedas(quantidade, valor):
return '{:.0f} moeda(s) de R$ {:.2f}'.format(quantidade, valor)
numero = float(input())
numero += 0.0001
if numero >= 0 or numero <= 1000000.00:
notas = [100.00, 50.00, 20.... | def imp_notas(quantidade, valor):
return '{:.0f} nota(s) de R$ {:.2f}'.format(quantidade, valor)
def imp_moedas(quantidade, valor):
return '{:.0f} moeda(s) de R$ {:.2f}'.format(quantidade, valor)
numero = float(input())
numero += 0.0001
if numero >= 0 or numero <= 1000000.0:
notas = [100.0, 50.0, 20.0, 10.... |
class Wizard:
def __init__(self, app):
self.app = app
def skip_wizard(self):
driver = self.app.driver
driver.find_element_by_class_name("skip").click()
| class Wizard:
def __init__(self, app):
self.app = app
def skip_wizard(self):
driver = self.app.driver
driver.find_element_by_class_name('skip').click() |
def linked_sort(a_to_sort, a_linked, key=str):
res = sorted(zip(a_to_sort, a_linked), key=key)
for i in range(len(a_to_sort)):
a_to_sort[i], a_linked[i] = res[i]
return a_to_sort | def linked_sort(a_to_sort, a_linked, key=str):
res = sorted(zip(a_to_sort, a_linked), key=key)
for i in range(len(a_to_sort)):
(a_to_sort[i], a_linked[i]) = res[i]
return a_to_sort |
# -*- coding: utf-8 -*-
# :copyright: (c) 2011 - 2015 by Arezqui Belaid.
# :license: MPL 2.0, see COPYING for more details.
__version__ = '1.0.3'
__author__ = "Arezqui Belaid"
__contact__ = "info@star2billing.com"
__homepage__ = "http://www.star2billing.org"
__docformat__ = "restructuredtext"
| __version__ = '1.0.3'
__author__ = 'Arezqui Belaid'
__contact__ = 'info@star2billing.com'
__homepage__ = 'http://www.star2billing.org'
__docformat__ = 'restructuredtext' |
def print_stats(num_broke, num_profitors, sample_size, profits, loses, type):
broke_percent = (num_broke / sample_size) * 100
profit_percent = (num_profitors / sample_size) * 100
try:
survive_profit_percent = (num_profitors / (sample_size - num_broke)) * 100
except ZeroDivisionError:
... | def print_stats(num_broke, num_profitors, sample_size, profits, loses, type):
broke_percent = num_broke / sample_size * 100
profit_percent = num_profitors / sample_size * 100
try:
survive_profit_percent = num_profitors / (sample_size - num_broke) * 100
except ZeroDivisionError:
survive_p... |
class Similarity:
def __init__(self, path, score):
self.path = path
self.score = score
@classmethod
def from_dict(cls, adict):
return cls(
path=adict['path'],
score=adict['score'],
)
def to_dict(self):
return {
'path':... | class Similarity:
def __init__(self, path, score):
self.path = path
self.score = score
@classmethod
def from_dict(cls, adict):
return cls(path=adict['path'], score=adict['score'])
def to_dict(self):
return {'path': self.path, 'score': self.score}
def __eq__(self, ... |
EFFICIENTDET = {
'efficientdet-d0': {'input_size': 512,
'backbone': 'B0',
'W_bifpn': 64,
'D_bifpn': 2,
'D_class': 3},
'efficientdet-d1': {'input_size': 640,
'backbone': 'B1',
... | efficientdet = {'efficientdet-d0': {'input_size': 512, 'backbone': 'B0', 'W_bifpn': 64, 'D_bifpn': 2, 'D_class': 3}, 'efficientdet-d1': {'input_size': 640, 'backbone': 'B1', 'W_bifpn': 88, 'D_bifpn': 3, 'D_class': 3}, 'efficientdet-d2': {'input_size': 768, 'backbone': 'B2', 'W_bifpn': 112, 'D_bifpn': 4, 'D_class': 3}, ... |
month = int(input("Enter month: "))
year = int(input("Enter year: "))
if month == 1:
monthName = "January"
numberOfDaysInMonth = 31
elif month == 2:
monthName = "February"
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
numberOfDaysInMonth = 29
else:
numberOfDa... | month = int(input('Enter month: '))
year = int(input('Enter year: '))
if month == 1:
month_name = 'January'
number_of_days_in_month = 31
elif month == 2:
month_name = 'February'
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
number_of_days_in_month = 29
else:
number_of_da... |
# Problem: Given as an input two strings, X = x_{1} x_{2}... x_{m}, and Y = y_{1} y_{2}... y_{m}, output the alignment of the strings, character by character,
# so that the net penalty is minimised.
gap_penalty = 3 # cost of gap
mismatch_penalty = 2 # cost of mismatch
memoScore = {}
memoSe... | gap_penalty = 3
mismatch_penalty = 2
memo_score = {}
memo_sequence = {}
def sequence_alignment(seq1, seq2):
if (seq1, seq2) in memoScore:
return memoScore[seq1, seq2]
if seq1 == '' and seq2 == '':
memoSequence[seq1, seq2] = ['', '']
return 0
elif seq1 == '' or seq2 == '':
ma... |
A = int(input())
B = set("aeiou")
for i in range(A):
S = input()
count = 0
for j in range(len(S)):
if S[j] in B:
count += 1
print(count)
| a = int(input())
b = set('aeiou')
for i in range(A):
s = input()
count = 0
for j in range(len(S)):
if S[j] in B:
count += 1
print(count) |
# Configuration for running the Avalon Music Server under Gunicorn
# http://docs.gunicorn.org
# Note that this configuration omits a bunch of features that Gunicorn
# has (such as running as a daemon, changing users, error and access
# logging) because it is designed to be used when running Gunicorn
# with supervisord... | bind = 'localhost:8000'
workers = 3
preload_app = True |
"""
Generator expressions are lazily evaluated, which means that they generate and
return each value only when the generator is iterated. This is often useful when
ITERATING THROUGH LARGE DATEBASES, avoiding the need to create a duplicate of
the dataset in memory.
"""
for square in (x**2 for x in range(100)):
prin... | """
Generator expressions are lazily evaluated, which means that they generate and
return each value only when the generator is iterated. This is often useful when
ITERATING THROUGH LARGE DATEBASES, avoiding the need to create a duplicate of
the dataset in memory.
"""
for square in (x ** 2 for x in range(100)):
pri... |
#check if number is prime or not
n = int(input("enter a number "))
for i in range(2, n):
if n % i == 0:
print("not a prime number")
break
else:
print("it is a prime number") | n = int(input('enter a number '))
for i in range(2, n):
if n % i == 0:
print('not a prime number')
break
else:
print('it is a prime number') |
#
# PySNMP MIB module EXTREME-EAPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-BASE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:07:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) ... |
# -*- coding: utf-8 -*-
operation = input()
total = 0
for i in range(144):
N = float(input())
line = i // 12
if (i > (13 * line)):
total += N
answer = total if (operation == 'S') else (total / 66)
print("%.1f" % answer) | operation = input()
total = 0
for i in range(144):
n = float(input())
line = i // 12
if i > 13 * line:
total += N
answer = total if operation == 'S' else total / 66
print('%.1f' % answer) |
# -*- coding: utf-8 -*-
"""Top-level package for light_tester."""
__author__ = """Gary Cremins"""
__email__ = 'gary.cremins1@ucdconnect.ie'
__version__ = '0.1.0'
| """Top-level package for light_tester."""
__author__ = 'Gary Cremins'
__email__ = 'gary.cremins1@ucdconnect.ie'
__version__ = '0.1.0' |
S = [3, 1, 3, 1]
N = len(S)-1
big_val = 1 << 62 # left bitwise shift is equivalent to raising 2 to the power of the positions shifted. so, big_val = 2 ^ 62.
A = [[big_val for i in range(N+1)] for j in range(N+1)]
def matrix_chain_cost(i, j):
global A
if i == j:
return 0
if A[i][j] != big_val:
... | s = [3, 1, 3, 1]
n = len(S) - 1
big_val = 1 << 62
a = [[big_val for i in range(N + 1)] for j in range(N + 1)]
def matrix_chain_cost(i, j):
global A
if i == j:
return 0
if A[i][j] != big_val:
return A[i][j]
for k in range(i, j):
A[i][j] = min(A[i][j], matrix_chain_cost(i, k) + ma... |
# Function: flips a pattern by mirror image
# Input:
# string - string pattern
# direction - flip horizontally or vertically
# Ouput: modified string pattern
def flip(st, direction):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
st_out = ''
if (direction == 'Flip Horizo... | def flip(st, direction):
row_strings = st.split('\n')
row_strings = row_strings[:-1]
st_out = ''
if direction == 'Flip Horizontally':
row_strings = row_strings[::-1]
for row in row_strings:
st_out += row + '\n'
else:
for row in row_strings:
st_out += r... |
matrix = [[dot == '#' for dot in line.strip()] for line in open('input.txt')]
diffs = [(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1) if (x, y) != (0, 0)]
corners = [(x, y) for x in (0, len(matrix)-1) for y in (0, len(matrix[0])-1)]
for x, y in corners:
matrix[x][y] = True
def neighbors(matrix, x, y):
for i, j... | matrix = [[dot == '#' for dot in line.strip()] for line in open('input.txt')]
diffs = [(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1) if (x, y) != (0, 0)]
corners = [(x, y) for x in (0, len(matrix) - 1) for y in (0, len(matrix[0]) - 1)]
for (x, y) in corners:
matrix[x][y] = True
def neighbors(matrix, x, y):
fo... |
def multiply(a, b):
c = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
for k in range(3):
c[i][j] += a[i][k] * b[k][j]
return c
q = int(input())
for _ in range(q):
x, y, z, t = input().split()
x = float(x)
y = float(y)
z = float(z)
... | def multiply(a, b):
c = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
for k in range(3):
c[i][j] += a[i][k] * b[k][j]
return c
q = int(input())
for _ in range(q):
(x, y, z, t) = input().split()
x = float(x)
y = float(y)
z = float(z)
... |
"""
exchanges. this acts as a routing table
"""
BITMEX = "BITMEX"
DERIBIT = "DERIBIT"
DELTA = "DELTA"
BITTREX = "BITTREX"
KUCOIN = "KUCOIN"
BINANCE = "BINANCE"
KRAKEN = "KRAKEN"
HITBTC = "HITBTC"
CRYPTOPIA = "CRYPTOPIA"
OKEX = "OKEX"
NAMES = [BITMEX, DERIBIT, DELTA, OKEX, BINANCE]
def exchange_exists(name):
retu... | """
exchanges. this acts as a routing table
"""
bitmex = 'BITMEX'
deribit = 'DERIBIT'
delta = 'DELTA'
bittrex = 'BITTREX'
kucoin = 'KUCOIN'
binance = 'BINANCE'
kraken = 'KRAKEN'
hitbtc = 'HITBTC'
cryptopia = 'CRYPTOPIA'
okex = 'OKEX'
names = [BITMEX, DERIBIT, DELTA, OKEX, BINANCE]
def exchange_exists(name):
return... |
# Exercise 3.1: Rewrite your pay computation to give the employee 1.5 times the
# rate for hours worked above 40 hours.
# Enter Hours: 45
# Enter Rate: 10
# Pay: 475.0
# Python for Everybody: Exploring Data Using Python 3
# by Charles R. Severance
hours = float(input("Enter hours: "))
rate_per_hour = float(input("En... | hours = float(input('Enter hours: '))
rate_per_hour = float(input('Enter rate per hour: '))
additional_hours = hours - 40
gross_pay = 0
if additional_hours > 0:
hours_with_rate_per_hour = hours - additional_hours
gross_pay = hours_with_rate_per_hour * rate_per_hour
modified_rate_per_hour = rate_per_hour * 1... |
class BaseEmployee():
"The base class for an employee."
# Note: Unlike c#, on initiliazing a child class, the base contructor is not called
# unless specifically called.
def __init__(self, id, city):
"Constructor for the base employee class."
print('Base constructor called.');
s... | class Baseemployee:
"""The base class for an employee."""
def __init__(self, id, city):
"""Constructor for the base employee class."""
print('Base constructor called.')
self.id = id
self.city = city
def __del__(self):
"""Will be called on destruction of employee obj... |
ix.enable_command_history()
app = ix.application
clarisse_win = app.get_event_window()
ix.application.open_edit_color_space_window(clarisse_win)
ix.disable_command_history()
| ix.enable_command_history()
app = ix.application
clarisse_win = app.get_event_window()
ix.application.open_edit_color_space_window(clarisse_win)
ix.disable_command_history() |
distanca = int(input())
tempo = (2 * distanca)
print('%d minutos' %tempo) | distanca = int(input())
tempo = 2 * distanca
print('%d minutos' % tempo) |
def sayhello(name=None):
if name is None:
return "Hello World, Everyone!"
else:
return f"Hello World, {name}"
| def sayhello(name=None):
if name is None:
return 'Hello World, Everyone!'
else:
return f'Hello World, {name}' |
def binary_and(a: int , b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
"""
if a < 0 or b < 0:
raise ValueError('The value of both number must be positive')
a_bin = str(b... | def binary_and(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
"""
if a < 0 or b < 0:
raise value_error('The value of both number must be positive')
a_bin = str(bin(a... |
def imgcd(m,n):
for i in range(1,min(m,n)+1):
if m%i==0 and n%i==0:
mcrf=i
return mcrf
a=input()
b=input()
c=imgcd(int(a),int(b))
print(c) | def imgcd(m, n):
for i in range(1, min(m, n) + 1):
if m % i == 0 and n % i == 0:
mcrf = i
return mcrf
a = input()
b = input()
c = imgcd(int(a), int(b))
print(c) |
class Tape(object):
blank = " "
def __init__(self, tape):
self.tape = tape
self.head = 0
| class Tape(object):
blank = ' '
def __init__(self, tape):
self.tape = tape
self.head = 0 |
''''
Problem:
Determine if two strings are permutations.
Assumptions:
String is composed of lower 128 ASCII characters.
Capitalization matters.
'''
def isPerm(s1, s2):
if len(s1) != len(s2):
return False
arr1 = [0] * 128
arr2 = [0] * 128
for c, d in zip(s1, s2):
arr1[ord(c... | """'
Problem:
Determine if two strings are permutations.
Assumptions:
String is composed of lower 128 ASCII characters.
Capitalization matters.
"""
def is_perm(s1, s2):
if len(s1) != len(s2):
return False
arr1 = [0] * 128
arr2 = [0] * 128
for (c, d) in zip(s1, s2):
arr1[ord(c)] += 1
... |
#Write a function to find the longest common prefix string amongst an array of strings.
#If there is no common prefix, return an empty string "".
def longest_common_prefix(strs) -> str:
common = ""
strs.sort()
for i in range(0, len(strs[0])):
if strs[0][i] == strs[-1][i]:
common +=... | def longest_common_prefix(strs) -> str:
common = ''
strs.sort()
for i in range(0, len(strs[0])):
if strs[0][i] == strs[-1][i]:
common += strs[0][i]
if strs[0][i] != strs[-1][i]:
break
return common
print(longest_common_prefix(['flow', 'flower', 'flowing'])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.