content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# @desc This is a code that determines whether a number is positive, negative, or just 0
# @desc by Merrick '23
def positive_negative(x):
if x > 0:
return "pos"
elif x == 0:
return "0"
else:
return "neg"
def main():
print(positive_negative(5))
print(positive_negative(-1))
... | def positive_negative(x):
if x > 0:
return 'pos'
elif x == 0:
return '0'
else:
return 'neg'
def main():
print(positive_negative(5))
print(positive_negative(-1))
print(positive_negative(0))
print(positive_negative(21))
print(positive_negative(-100))
if __name__ ==... |
__all__ = [
'resp',
'user'
]
| __all__ = ['resp', 'user'] |
# ------------------------------------------------ EASTER EGG ------------------------------------------------
# Congratulations on finding this file! Please use the following methods below to decrypt the given cipher.
def decrypt(cipher, multiple):
text = ""
for idx, ch in enumerate(cipher):
if ch.isa... | def decrypt(cipher, multiple):
text = ''
for (idx, ch) in enumerate(cipher):
if ch.isalpha():
shift = multiple * idx % 26
new_char = ord(ch) + shift
if newChar > ord('z'):
new_char -= 26
text += chr(newChar)
return text
def encrypt(text, m... |
while True:
n = int(input())
if n == -1:
break
s = 0
last = 0
for i in range(n):
a,b=map(int,input().split())
s += a*(b-last)
last = b
print(s,"miles") | while True:
n = int(input())
if n == -1:
break
s = 0
last = 0
for i in range(n):
(a, b) = map(int, input().split())
s += a * (b - last)
last = b
print(s, 'miles') |
no_of_adults = float(input())
no_of_childrens = float(input())
total_passenger_cost = 0
service_tax = 7/100
discount = 10/100
rate_per_adult = no_of_adults * 37550.0 + service_tax
rate_per_children = no_of_childrens * (37550.0/3.0) + service_tax
total_passenger_cost = (rate_per_adult + rate_per_children) - discount
... | no_of_adults = float(input())
no_of_childrens = float(input())
total_passenger_cost = 0
service_tax = 7 / 100
discount = 10 / 100
rate_per_adult = no_of_adults * 37550.0 + service_tax
rate_per_children = no_of_childrens * (37550.0 / 3.0) + service_tax
total_passenger_cost = rate_per_adult + rate_per_children - discount... |
class Status(object):
SHUTTING_DOWN = 'Shutting Down'
RUNNING = 'Running'
class __State(object):
def __init__(self):
self._shutting_down = False
def set_to_shutting_down(self):
self._shutting_down = True
def is_shutting_down(self):
return self._shutting_down
@propert... | class Status(object):
shutting_down = 'Shutting Down'
running = 'Running'
class __State(object):
def __init__(self):
self._shutting_down = False
def set_to_shutting_down(self):
self._shutting_down = True
def is_shutting_down(self):
return self._shutting_down
@propert... |
"""Python Wavelet Imaging
PyWI is an image filtering library aimed at removing additive background noise
from raster graphics images.
* Input: a FITS file containing the raster graphics to clean (i.e. an image
defined as a classic rectangular lattice of square pixels).
* Output: a FITS file containing the cleaned r... | """Python Wavelet Imaging
PyWI is an image filtering library aimed at removing additive background noise
from raster graphics images.
* Input: a FITS file containing the raster graphics to clean (i.e. an image
defined as a classic rectangular lattice of square pixels).
* Output: a FITS file containing the cleaned r... |
class DynGraph():
def node_presence(self, nbunch=None):
raise NotImplementedError("Not implemented")
def add_interaction(self,u_of_edge,v_of_edge,time):
raise NotImplementedError("Not implemented")
def add_interactions_from(self, nodePairs, times):
raise NotImplementedError("Not i... | class Dyngraph:
def node_presence(self, nbunch=None):
raise not_implemented_error('Not implemented')
def add_interaction(self, u_of_edge, v_of_edge, time):
raise not_implemented_error('Not implemented')
def add_interactions_from(self, nodePairs, times):
raise not_implemented_error... |
def smallest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor)
def largest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor, low=False)
def is_palindrome(mn, mx, low=True):
"""
Throughout the method all ranges' upper bound is extended because in python it's ex... | def smallest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor)
def largest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor, low=False)
def is_palindrome(mn, mx, low=True):
"""
Throughout the method all ranges' upper bound is extended because in python it's excl... |
def get_sql(company, conn, gl_code, start_date, end_date, step):
# start_date = '2018-02-28'
# end_date = '2018-03-01'
# step = 1
sql = (
"WITH RECURSIVE dates AS "
f"(SELECT CAST('{start_date}' AS {conn.constants.date_cast}) AS op_date, "
f"{conn.constants.func_prefix}da... | def get_sql(company, conn, gl_code, start_date, end_date, step):
sql = f"""WITH RECURSIVE dates AS (SELECT CAST('{start_date}' AS {conn.constants.date_cast}) AS op_date, {conn.constants.func_prefix}date_add('{start_date}', {step - 1}) AS cl_date UNION ALL SELECT {conn.constants.func_prefix}date_add(cl_date, 1) AS o... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
curr = self
vals = []
while curr:
vals.append(curr.val)
curr = curr.next
return str(vals)
@classmethod
def from_list(cls, vals):
head ... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
curr = self
vals = []
while curr:
vals.append(curr.val)
curr = curr.next
return str(vals)
@classmethod
def from_list(cls, vals):
head... |
num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 == num2 and num2 == num3:
print("yes")
else:
print("no")
print("let's see", end="")
print("?") | num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 == num2 and num2 == num3:
print('yes')
else:
print('no')
print("let's see", end='')
print('?') |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
def test_simple(qipy_action, record_messages):
qipy_action.add_test_project("a_lib")
qipy_action.add_test_project("big_project")
qipy_acti... | def test_simple(qipy_action, record_messages):
qipy_action.add_test_project('a_lib')
qipy_action.add_test_project('big_project')
qipy_action.add_test_project('foomodules')
qipy_action('list')
assert record_messages.find('\\*\\s+a')
assert record_messages.find('\\*\\s+big_project') |
# Copyright Alexander Baranin 2016
Logging = None
EngineCore = None
def onLoad(core):
global EngineCore
EngineCore = core
global Logging
Logging = EngineCore.loaded_modules['engine.Logging']
Logging.logMessage('TestFIFOModule1.onLoad()')
EngineCore.schedule_FIFO(run1, 10)
EngineCore.sche... | logging = None
engine_core = None
def on_load(core):
global EngineCore
engine_core = core
global Logging
logging = EngineCore.loaded_modules['engine.Logging']
Logging.logMessage('TestFIFOModule1.onLoad()')
EngineCore.schedule_FIFO(run1, 10)
EngineCore.schedule_FIFO(run2, 30)
def on_unload(... |
'''
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
668966489504... | """
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
668966489504... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 Daniel Rodriguez
# Use of this source code is governed by the MIT License
###############################################################################... | __all__ = []
def _generate(cls, bases, dct, **kwargs):
grps = dct.get('group', ()) or getattr(cls, 'group', ())
if isinstance(grps, str):
grps = (grps,)
cls.group = grps |
#! /usr/bin/python3
# product.py -- This script prints out a product and it's price.
# Author -- Prince Oppong Boamah<regioths@gmail.com>
# Date -- 10th September, 2015
class Product:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
# The program starts runn... | class Product:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
p = product('Lenovo')
p.price = '2000gh cedis or 400 pounds or 600 dollars to be precise.'
print('p is a %s' % p.__class__)
print('This is a Laptop called %s and the price is %s' % (p.name, p.price)) |
# constantly ask the user for new names and phone numbers
# to add to the phone book, then save them
phone_book = {}
| phone_book = {} |
key_words = ["Trending", "Fact", "Reason", "Side Effect", "Index", "Stock", "ETF"]
knowledge_graph_dict = {
"Value Investing": {},
"Risk Management": {},
"Joe Biden": {
"Tax Increase Policy": {
"Tech Company": {
"Trending": "Negative",
},
"Corpora... | key_words = ['Trending', 'Fact', 'Reason', 'Side Effect', 'Index', 'Stock', 'ETF']
knowledge_graph_dict = {'Value Investing': {}, 'Risk Management': {}, 'Joe Biden': {'Tax Increase Policy': {'Tech Company': {'Trending': 'Negative'}, 'Corporate Tax': {'Trending': 'Negative'}, 'Capital Gain Tax': {'Trending': 'Negative'}... |
# encoding: utf-8
'''
@author: developer
@software: python
@file: run8.py
@time: 2021/7/28 22:35
@desc:
'''
str1 = input()
str2 = input()
output_str1 = str2[0:2] + str1[2:]
output_str2 = str1[0:2] + str2[2:]
print(output_str1)
print(output_str2)
| """
@author: developer
@software: python
@file: run8.py
@time: 2021/7/28 22:35
@desc:
"""
str1 = input()
str2 = input()
output_str1 = str2[0:2] + str1[2:]
output_str2 = str1[0:2] + str2[2:]
print(output_str1)
print(output_str2) |
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def tomlplusplus_repository():
maybe(
http_archive,
name = "tomlplusplus",
urls = [
"https://github.com/marzer/tomlplusplus/archive/v2.5.0.zip",
... | load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def tomlplusplus_repository():
maybe(http_archive, name='tomlplusplus', urls=['https://github.com/marzer/tomlplusplus/archive/v2.5.0.zip'], sha256='887dfb7025d532a3485e1269ce5102d9e62... |
#! /usr/bin/env python3
# hjjs.py - write some HJ J-sequences
EXTENSION = ".hjjs.txt"
MODE = "w"
J_MAX = 2 ** 32 - 1
def i22a(f, m):
n = 0
js = []
while True:
j = 2 ** (2 * n + m) - 2 ** n
if j > J_MAX:
break
js.append(j)
n += 1
print(*js, file = f)
for m in range(10):
with open... | extension = '.hjjs.txt'
mode = 'w'
j_max = 2 ** 32 - 1
def i22a(f, m):
n = 0
js = []
while True:
j = 2 ** (2 * n + m) - 2 ** n
if j > J_MAX:
break
js.append(j)
n += 1
print(*js, file=f)
for m in range(10):
with open('i22a' + str(m) + EXTENSION, MODE) as f... |
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
"""Stack.
Running time: O(n) where n == len(s).
"""
d = {c: i for i, c in enumerate(s)}
st = []
seen = set()
for i, c in enumerate(s):
if c in seen:
continue
... | class Solution:
def remove_duplicate_letters(self, s: str) -> str:
"""Stack.
Running time: O(n) where n == len(s).
"""
d = {c: i for (i, c) in enumerate(s)}
st = []
seen = set()
for (i, c) in enumerate(s):
if c in seen:
continue
... |
# This should be subclassed within each
# class that gets registered with the API
class BaseContext:
def __init__(self, instance=None, serial=None):
pass
def serialized(self):
return ()
def instance(self, global_context):
return None
# This is actually very different from a contex... | class Basecontext:
def __init__(self, instance=None, serial=None):
pass
def serialized(self):
return ()
def instance(self, global_context):
return None
class Globalcontext:
def __init__(self, universes, network):
self.universes = universes
self.network = netw... |
def pageCount(n, p):
print(min(p//2,n//2-p//2))
if __name__ == '__main__':
n = int(input())
p = int(input())
pageCount(n, p)
| def page_count(n, p):
print(min(p // 2, n // 2 - p // 2))
if __name__ == '__main__':
n = int(input())
p = int(input())
page_count(n, p) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pseudoPalindromicPaths (self, root: TreeNode) -> int:
self.a = [0] * 10
self.count = 0
... | class Solution:
def pseudo_palindromic_paths(self, root: TreeNode) -> int:
self.a = [0] * 10
self.count = 0
self.dfs(root, [])
return self.count
def dfs(self, root, path):
if root is None:
return
self.a[root.val] += 1
if root.left is None and... |
"""
Programming for linguists
Implementation of the class Circle
"""
class Circle:
"""
A class for circles
"""
def __init__(self, uid: int, radius: int):
pass
def get_area(self):
"""
Returns the area of a circle
:return int: the area of a circle
"""
... | """
Programming for linguists
Implementation of the class Circle
"""
class Circle:
"""
A class for circles
"""
def __init__(self, uid: int, radius: int):
pass
def get_area(self):
"""
Returns the area of a circle
:return int: the area of a circle
"""
... |
class FLAGS:
data_url = ""
data_dir = None
background_volume = 0.1
background_frequency = 0
silence_percentage = 10.0
unknown_percentage = 10.0
time_shift_ms = 0
use_custom_augs = False
testing_percentage = 10
validation_percentage = 10
sample_rate = 16000
clip_duration_ms = 1000
window_size_ms = 30
wi... | class Flags:
data_url = ''
data_dir = None
background_volume = 0.1
background_frequency = 0
silence_percentage = 10.0
unknown_percentage = 10.0
time_shift_ms = 0
use_custom_augs = False
testing_percentage = 10
validation_percentage = 10
sample_rate = 16000
clip_duration_m... |
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
returnList = [0] * len(nums)
temp = 0
for i in range(0,n):
returnList[temp] = nums[i]
returnList[temp+1] = nums[n]
n+=1
temp+=2
return returnList
... | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return_list = [0] * len(nums)
temp = 0
for i in range(0, n):
returnList[temp] = nums[i]
returnList[temp + 1] = nums[n]
n += 1
temp += 2
return returnList |
def get_player_score():
score = []
for i in range(0, 5):
while True:
try:
s = float(input('Enter golf scores between 78 and 100: '))
if 78 <= s <= 100:
score.append(s)
break
raise ValueError
e... | def get_player_score():
score = []
for i in range(0, 5):
while True:
try:
s = float(input('Enter golf scores between 78 and 100: '))
if 78 <= s <= 100:
score.append(s)
break
raise ValueError
e... |
# Unneeded charting code that was removed from a jupyter notebook. Stored here as an example for later
# Draws a chart with the total area of multiple protin receptors at each time step
tmpdf = totals65.loc[(totals65['Receptor'].isin(['M1', 'M5', 'M7', 'M22', 'M26'])) &
(totals65['Experiment Step... | tmpdf = totals65.loc[totals65['Receptor'].isin(['M1', 'M5', 'M7', 'M22', 'M26']) & (totals65['Experiment Step'] == '-nl-post')]
pal = ['black', 'blue', 'red', 'orange', 'green']
g = sns.FacetGrid(tmpdf, col='Time Point', col_wrap=3, size=5, ylim=(0, 100), xlim=(0, 100), palette=pal, hue='Receptor', hue_order=['M1', 'M5... |
whitespace = " \t\n\r\v\f"
ascii_lowercase = "abcdefghijklmnopqrstuvwxyz"
ascii_uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ascii_letters = ascii_lowercase + ascii_uppercase
digits = "0123456789"
hexdigitx = digits + "abcdef" + "ABCDEF"
octdigits = "01234567"
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
p... | whitespace = ' \t\n\r\x0b\x0c'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigitx = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
printabl... |
with open("pattern.txt") as file:
inputs = file.readlines()
BUFFER = 10
ITERATIONS = 50_000_000_000
state = '.' * BUFFER + "..##.#######...##.###...#..#.#.#..#.##.#.##....####..........#..#.######..####.#.#..###.##..##..#..#" + '.' * 102
gives_empty = {line[:5] for line in inputs if line[-2] == '.'}
pattern_ite... | with open('pattern.txt') as file:
inputs = file.readlines()
buffer = 10
iterations = 50000000000
state = '.' * BUFFER + '..##.#######...##.###...#..#.#.#..#.##.#.##....####..........#..#.######..####.#.#..###.##..##..#..#' + '.' * 102
gives_empty = {line[:5] for line in inputs if line[-2] == '.'}
pattern_iterations... |
all_sales = dict()
try:
with open(".\\.\\sales.csv") as file:
for line in file:
string_args = line.split()
string_date = string_args[0]
string_price = string_args[1].split(",")
price = all_sales[string_date]
all_sales[string_date] = price + string... | all_sales = dict()
try:
with open('.\\.\\sales.csv') as file:
for line in file:
string_args = line.split()
string_date = string_args[0]
string_price = string_args[1].split(',')
price = all_sales[string_date]
all_sales[string_date] = price + string_... |
# Copyright (c) 2017, 2018 Jae-jun Kang
# See the file LICENSE for details.
class Config(object):
heartbeat_interval = 5 # in seconds
class Coroutine(object):
default_timeout = 60 # in seconds | class Config(object):
heartbeat_interval = 5
class Coroutine(object):
default_timeout = 60 |
__all__ = (
"__title__", "__summary__", "__uri__",
"__download_url__", "__version__", "__author__",
"__email__", "__license__",)
__title__ = "gpxconverter"
__summary__ = ("gpx to csv converter. it supports waypoint elements except "
"extensions. Values in extensions will be ignored.")
__ur... | __all__ = ('__title__', '__summary__', '__uri__', '__download_url__', '__version__', '__author__', '__email__', '__license__')
__title__ = 'gpxconverter'
__summary__ = 'gpx to csv converter. it supports waypoint elements except extensions. Values in extensions will be ignored.'
__uri__ = 'https://github.com/linusyoung/... |
def count(s, t, loc, lst):
return sum([(loc + dist) >= s and (loc + dist) <= t for dist in lst])
def countApplesAndOranges(s, t, a, b, apples, oranges):
print(count(s, t, a, apples))
print(count(s, t, b, oranges))
| def count(s, t, loc, lst):
return sum([loc + dist >= s and loc + dist <= t for dist in lst])
def count_apples_and_oranges(s, t, a, b, apples, oranges):
print(count(s, t, a, apples))
print(count(s, t, b, oranges)) |
"""
This module provides utility functions that are used within socket-py
"""
def get_packet_request(content_name):
message = struct.pack('>I', 1) + struct.pack(len(content_name))
message = message + content_name
message = struct.pack('>I', len(message)) + message
def get_packet_reply(content_name, conte... | """
This module provides utility functions that are used within socket-py
"""
def get_packet_request(content_name):
message = struct.pack('>I', 1) + struct.pack(len(content_name))
message = message + content_name
message = struct.pack('>I', len(message)) + message
def get_packet_reply(content_name, conten... |
# Ticket numbers usually consist of an even number of digits.
# A ticket number is considered lucky if the sum of the first
# half of the digits is equal to the sum of the second half.
#
# Given a ticket number n, determine if it's lucky or not.
#
# Example
#
# For n = 1230, the output should be
# isLucky(n) = true;
# ... | n = 239017
(firstpart, secondpart) = (str(n)[:len(str(n)) // 2], str(n)[len(str(n)) // 2:])
n1 = sum(map(int, firstpart))
n2 = sum(map(int, secondpart))
print(n1, n2) |
f = open('input.txt')
data = [int(num) for num in f.read().split("\n")[:-1]]
for i, num1 in enumerate(data):
for num2 in data[i+1:]:
if num1 + num2 == 2020:
print(num1 * num2)
| f = open('input.txt')
data = [int(num) for num in f.read().split('\n')[:-1]]
for (i, num1) in enumerate(data):
for num2 in data[i + 1:]:
if num1 + num2 == 2020:
print(num1 * num2) |
print("Welcome to Alexander's Tic-Tac-Toe Game", "\n")
board = [" "for i in range(9)]
def cls():
print('\n'*20)
def printBoard():
row1 = "|{}|{}|{}|".format(board[0], board[1], board[2])
row2 = "|{}|{}|{}|".format(board[3], board[4], board[5])
row3 = "|{}|{}|{}|".format(board[6], board[7], board[8]... | print("Welcome to Alexander's Tic-Tac-Toe Game", '\n')
board = [' ' for i in range(9)]
def cls():
print('\n' * 20)
def print_board():
row1 = '|{}|{}|{}|'.format(board[0], board[1], board[2])
row2 = '|{}|{}|{}|'.format(board[3], board[4], board[5])
row3 = '|{}|{}|{}|'.format(board[6], board[7], board[8... |
"""
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the l... | """
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the l... |
# We want to make a row of bricks that is goal inches long. We have a number
# of small bricks (1 inch each) and big bricks (5 inches each). Return True
# if it is possible to make the goal by choosing from the given bricks.
# This is a little harder than it looks and can be done without any loops.
# make_bricks(3, 1... | def make_bricks(small, big, goal):
num_fives = goal // 5
num_ones = goal - 5 * num_fives
if num_fives <= big and num_ones <= small:
return True
elif num_fives >= big and goal - 5 * big <= small:
return True
else:
return False
print(make_bricks(3, 1, 8))
print(make_bricks(3, 1... |
burgers=[]
quan=[]
def PrintHead():
print(" ABC Burgers")
print(" Pakistan Road,Karachi")
print("=====================================")
# Data Entry:
rates = {"cheese": 110, "zinger": 160, "abc special": 250, "chicken": 120}
# Front-End:
def TakeInputs():
b = input("Burger Type:").... | burgers = []
quan = []
def print_head():
print(' ABC Burgers')
print(' Pakistan Road,Karachi')
print('=====================================')
rates = {'cheese': 110, 'zinger': 160, 'abc special': 250, 'chicken': 120}
def take_inputs():
b = input('Burger Type:').lower()
if b not ... |
cql = {
"and": [
{"lte": [{"property": "eo:cloud_cover"}, "10"]},
{"gte": [{"property": "datetime"}, "2021-04-08T04:39:23Z"]},
{
"or": [
{"eq": [{"property": "collection"}, "landsat"]},
{"lte": [{"property": "gsd"}, "10"]},
]
},... | cql = {'and': [{'lte': [{'property': 'eo:cloud_cover'}, '10']}, {'gte': [{'property': 'datetime'}, '2021-04-08T04:39:23Z']}, {'or': [{'eq': [{'property': 'collection'}, 'landsat']}, {'lte': [{'property': 'gsd'}, '10']}]}, {'lte': [{'property': 'id'}, 'l8_12345']}]}
cql_multi = {'and': [{'lte': [{'property': 'eo:cloud_c... |
def combinationSum(candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
#Firstly we sort the candidates so we can keep track of our progression
candidates = sorted(candidates)
def backTrack(left, curre... | def combination_sum(candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates = sorted(candidates)
def back_track(left, current, results):
if not left:
results += [current]
return
for... |
"""
Holds lists of different types of events
"""
# pylint: disable=line-too-long
def get(ids = False):
"""holds different stack events"""
cases = [{
"name": "new_stack_create_failed",
"success": False,
"StackEvents": [
{
"StackId": "arn:aws:cloudformation:us-... | """
Holds lists of different types of events
"""
def get(ids=False):
"""holds different stack events"""
cases = [{'name': 'new_stack_create_failed', 'success': False, 'StackEvents': [{'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'Ev... |
'''
A boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.
Example 1:
Input: [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: [[1,1],[2,2],[3,3]]
Output: false
Note:
points.length == 3
points... | """
A boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.
Example 1:
Input: [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: [[1,1],[2,2],[3,3]]
Output: false
Note:
points.length == 3
points... |
def definition():
"""View of component groups, with fields additional to the cgroup object."""
sql = """
SELECT c.cgroup_id, c.description, c.strand, c.notes, c.curriculum_id,
s.description as strand_name,
c.cgroup_id id,
c.description as short_name,
ISNULL(conf.child_count,0) as child_count... | def definition():
"""View of component groups, with fields additional to the cgroup object."""
sql = '\nSELECT c.cgroup_id, c.description, c.strand, c.notes, c.curriculum_id, \n s.description as strand_name, \n c.cgroup_id id, \n c.description as short_name, \n ISNULL(conf.child_count,0) as child_co... |
class AnnotaVO:
def __init__(self):
self._entry = None
self._label = None
self._points = None
self._kind = None
@property
def points(self):
return self._points
@points.setter
def points(self, value):
self._points = value
@property
def entry(... | class Annotavo:
def __init__(self):
self._entry = None
self._label = None
self._points = None
self._kind = None
@property
def points(self):
return self._points
@points.setter
def points(self, value):
self._points = value
@property
def entry... |
# Accounts
USER_DOES_NOT_EXIST = 1000
INCORRECT_PASSWORD = 1001
USER_INACTIVE = 1002
INVALID_SIGN_UP_CODE = 1030
SOCIAL_DOES_NOT_EXIST = 1100
INCORRECT_TOKEN = 1101
TOKEN_ALREADY_IN_USE = 1102
SAME_PASSWORD = 1200
# Common
FORM_ERROR = 9000
| user_does_not_exist = 1000
incorrect_password = 1001
user_inactive = 1002
invalid_sign_up_code = 1030
social_does_not_exist = 1100
incorrect_token = 1101
token_already_in_use = 1102
same_password = 1200
form_error = 9000 |
class Sigmoid(Node):
"""
Represents a node that performs the sigmoid activation function.
"""
def __init__(self, node):
# The base class constructor.
Node.__init__(self, [node])
def _sigmoid(self, x):
"""
This method is separate from `forward` because it
will... | class Sigmoid(Node):
"""
Represents a node that performs the sigmoid activation function.
"""
def __init__(self, node):
Node.__init__(self, [node])
def _sigmoid(self, x):
"""
This method is separate from `forward` because it
will be used with `backward` as well.
... |
names = ["kara", "jackie", "Theophilus"]
for name in names:
print(names)
print("\n")
for index in range(len(names)):
print(names[index]) | names = ['kara', 'jackie', 'Theophilus']
for name in names:
print(names)
print('\n')
for index in range(len(names)):
print(names[index]) |
''' Python name attribute
Every module in Python has a special variable called name.
The value of the nsme attribute is set
'''
| """ Python name attribute
Every module in Python has a special variable called name.
The value of the nsme attribute is set
""" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python implementation of permute utility with Numpy backend from the MATLAB Tensor Toolbox [1].
References
========================================
[1] General software, latest release: Brett W. Bader, Tamara G. Kolda and others, Tensor Toolbox for MATLAB, Version 3.2... | """
Python implementation of permute utility with Numpy backend from the MATLAB Tensor Toolbox [1].
References
========================================
[1] General software, latest release: Brett W. Bader, Tamara G. Kolda and others, Tensor Toolbox for MATLAB, Version 3.2.1, www.tensortoolbox.org, April 5, 2021.
"""
... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 16 19:37:39 2019
@author: Parikshith.H
"""
str="hello"
if str=="hi":
print("true")
else:
print("false")
# =============================================================================
# #output:
# false
# ==========================================================... | """
Created on Thu May 16 19:37:39 2019
@author: Parikshith.H
"""
str = 'hello'
if str == 'hi':
print('true')
else:
print('false')
if str < 'hi':
print('true')
else:
print('false')
if 'e' in 'hello':
print('true')
else:
print('false')
s = 'welcome'
for ch in s:
print(ch)
for val in 'hello':... |
people = [
('Alice', 32), # one tuple
('Bob', 51), # another tuple
('Carol', 15),
('Dylan', 5),
('Erin', 25),
('Frank', 48)
]
i= 0
yuanzu = (' ', 999)
while i < len(people):
if people[i][1] <= yuanzu[1]:
yuanzu = people[i]
i += 1
print('Youngest person: {}, {} years old. '.format(yuanzu[0], yuanzu[1]))
... | people = [('Alice', 32), ('Bob', 51), ('Carol', 15), ('Dylan', 5), ('Erin', 25), ('Frank', 48)]
i = 0
yuanzu = (' ', 999)
while i < len(people):
if people[i][1] <= yuanzu[1]:
yuanzu = people[i]
i += 1
print('Youngest person: {}, {} years old. '.format(yuanzu[0], yuanzu[1]))
print(people(people[i][1] == ... |
#!/usr/bin/env python
'''
Description: these are the default parameters to use for processing secrets data
Author: Rachel Kalmar
'''
# ------------------------------------ #
# Set defaults for parameters to be used in secretReaderPollyVoices
datapath_base = '/Users/kalmar/Documents/code/secrets/secrets_data/' # Whe... | """
Description: these are the default parameters to use for processing secrets data
Author: Rachel Kalmar
"""
datapath_base = '/Users/kalmar/Documents/code/secrets/secrets_data/'
mp3path_base = '/Users/kalmar/Documents/code/secrets/audio/'
shuffle_secrets = False
speak = True
ssml = True
whisper_freq = 0.15
mp3_paddi... |
a = "0,0,0,0,0,0"
b = "0,-1,-2,0"
c = "-1,-3,-4,-1,-2"
d = "qwerty"
e = ",,3,,4"
f = "1,2,v,b,3"
g = "0,7,0,2,-12,3,0,2"
h = "1,3,-2,1,2"
def sum_earnings(str_earn):
next_value = 0
total = 0
neg_sum = 0
if any(char.isalpha() for char in str_earn):
return 0
for s in str_earn.split(','... | a = '0,0,0,0,0,0'
b = '0,-1,-2,0'
c = '-1,-3,-4,-1,-2'
d = 'qwerty'
e = ',,3,,4'
f = '1,2,v,b,3'
g = '0,7,0,2,-12,3,0,2'
h = '1,3,-2,1,2'
def sum_earnings(str_earn):
next_value = 0
total = 0
neg_sum = 0
if any((char.isalpha() for char in str_earn)):
return 0
for s in str_earn.split(','):
... |
def main():
n, k = map(int, input().split())
l = []
for i in range(n):
a, b = map(int, input().split())
l.append((a, b))
l.sort()
prev = 0
for i in range(n):
prev += l[i][1]
if k <= prev:
print(l[i][0])
break
if __name__ == '__mai... | def main():
(n, k) = map(int, input().split())
l = []
for i in range(n):
(a, b) = map(int, input().split())
l.append((a, b))
l.sort()
prev = 0
for i in range(n):
prev += l[i][1]
if k <= prev:
print(l[i][0])
break
if __name__ == '__main__':
... |
class Solution:
def minimumLength(self, s: str) -> int:
if len(s)==1:
return 1
i=0
j=len(s)-1
while i<j:
if s[i]!=s[j]:
break
temp = s[i]
while i<=j and s[i]==temp:
i+=1
while j>=i and s[j]==t... | class Solution:
def minimum_length(self, s: str) -> int:
if len(s) == 1:
return 1
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
break
temp = s[i]
while i <= j and s[i] == temp:
i += 1
wh... |
"""
Created by akiselev on 2019-07-18
In this challenge, the task is to debug the existing code to successfully execute all provided test files.
Consider that vowels in the alphabet are a, e, i, o, u and y.
Function score_words takes a list of lowercase words as an argument and returns a score as follows:
The s... | """
Created by akiselev on 2019-07-18
In this challenge, the task is to debug the existing code to successfully execute all provided test files.
Consider that vowels in the alphabet are a, e, i, o, u and y.
Function score_words takes a list of lowercase words as an argument and returns a score as follows:
The s... |
# -*- coding: utf-8 -*-
"""The modules manager."""
class ModulesManager(object):
"""The modules manager."""
_module_classes = {}
@classmethod
def GetModuleObjects(cls, module_filter_expression=None):
excludes, includes = cls.SplitExpression(cls, expression = module_filter_expression)
... | """The modules manager."""
class Modulesmanager(object):
"""The modules manager."""
_module_classes = {}
@classmethod
def get_module_objects(cls, module_filter_expression=None):
(excludes, includes) = cls.SplitExpression(cls, expression=module_filter_expression)
module_objects = {}
... |
# set declaration
myfruits = {"Apple", "Banana", "Grapes", "Litchi", "Mango"}
mynums = {1, 2, 3, 4, 5}
# Set printing before removing
print("Before remove() method...")
print("fruits: ", myfruits)
print("numbers: ", mynums)
# Removing the elements from the sets
elerem = myfruits.remove('Apple')
elerem = myfruits.remo... | myfruits = {'Apple', 'Banana', 'Grapes', 'Litchi', 'Mango'}
mynums = {1, 2, 3, 4, 5}
print('Before remove() method...')
print('fruits: ', myfruits)
print('numbers: ', mynums)
elerem = myfruits.remove('Apple')
elerem = myfruits.remove('Litchi')
elerem = myfruits.remove('Mango')
elerem = mynums.remove(1)
elerem = mynums.... |
# CPU: 0.05 s
amounts = list(map(int, input().split()))
ratios = list(map(int, input().split()))
n = min(amounts[x] / ratios[x] for x in range(3))
for amount, ratio in zip(amounts, ratios):
print(amount - ratio * n, end=" ")
| amounts = list(map(int, input().split()))
ratios = list(map(int, input().split()))
n = min((amounts[x] / ratios[x] for x in range(3)))
for (amount, ratio) in zip(amounts, ratios):
print(amount - ratio * n, end=' ') |
COUNTRIES = [
"US",
"IL",
"IN",
"UA",
"CA",
"AR",
"SG",
"TW",
"GB",
"AT",
"BE",
"BG",
"HR",
"CY",
"CZ",
"DK",
"EE",
"FI",
"FR",
"DE",
"GR",
"HU",
"IE",
"IT",
"LK",
"LV",
"LT",
"LU",
"MT",
"NL",
"P... | countries = ['US', 'IL', 'IN', 'UA', 'CA', 'AR', 'SG', 'TW', 'GB', 'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LK', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'NZ', 'AU', 'BF', 'BO', 'BR', 'BZ', 'CI', 'CL', 'CO', 'DO', 'EC', 'GE', 'GH', 'GY', '... |
x = 1
y = 10
# Checks if one value is equal to another
if x == 1:
print("x is equal to 1")
# Checks if one value is NOT equal to another
if y != 1:
print("y is not equal to 1")
# Checks if one value is less than another
if x < y:
print("x is less than y")
# Checks if one value is greater ... | x = 1
y = 10
if x == 1:
print('x is equal to 1')
if y != 1:
print('y is not equal to 1')
if x < y:
print('x is less than y')
if y > x:
print('y is greater than x')
if x >= 1:
print('x is greater than or equal to 1')
if x == 1 and y == 10:
print('Both values returned true')
if x < 45 or y < 5:
... |
# general configuration
LOCAL_OTP_PORT = 8088 # port for OTP to use, HTTPS will be served on +1
TEMP_DIRECTORY = "mara-ptm-temp"
PROGRESS_WATCHER_INTERVAL = 5 * 60 * 1000 # milliseconds
JVM_PARAMETERS = "-Xmx8G" # 6-8GB of RAM is good for bigger graphs
# itinerary filter parameters
CAR_KMH = 50
CAR_TRAVEL_FACTOR = ... | local_otp_port = 8088
temp_directory = 'mara-ptm-temp'
progress_watcher_interval = 5 * 60 * 1000
jvm_parameters = '-Xmx8G'
car_kmh = 50
car_travel_factor = 1.4
allowed_transit_modes = ['WALK', 'BUS', 'TRAM', 'SUBWAY', 'RAIL']
max_walk_distance = 1000
otp_parameters_template = '&'.join(['fromPlace=1:{origin}', 'toPlace=... |
class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
if not dict:
return False
n = len(s)
res = [False] * n
for i in xrange(0, n):
if s[:i+1] in dict:
res[i] = True
... | class Solution:
def word_break(self, s, dict):
if not dict:
return False
n = len(s)
res = [False] * n
for i in xrange(0, n):
if s[:i + 1] in dict:
res[i] = True
if not True in res:
return False
i = 0
while i... |
diccionario= {91: 95}
a=91
if a==91:
a=diccionario.get(91)
print(a) | diccionario = {91: 95}
a = 91
if a == 91:
a = diccionario.get(91)
print(a) |
arquivo = open('linguagens.txt', 'r')
num = int(input("Numero de linguagens: "))
count=0
for linha in arquivo:
if count<num:
print(linha.rstrip('\n'))
count += 1
else:
break
arquivo.close() | arquivo = open('linguagens.txt', 'r')
num = int(input('Numero de linguagens: '))
count = 0
for linha in arquivo:
if count < num:
print(linha.rstrip('\n'))
count += 1
else:
break
arquivo.close() |
#!/usr/bin/env python3
# coding:utf-8
class Solution:
def StrToInt(self, s):
if s == '':
return 0
string = s.strip()
num = 0
start = 0
symbol = 1
if string[0] == '+':
start += 1
elif string[0] == '-':
start += 1
... | class Solution:
def str_to_int(self, s):
if s == '':
return 0
string = s.strip()
num = 0
start = 0
symbol = 1
if string[0] == '+':
start += 1
elif string[0] == '-':
start += 1
symbol = -1
for i in range(... |
def roman(num):
"""
Function to convert an integer to roman numeral.
:type num: int
:rtype: str
"""
if type(num) is not int:
raise TypeError("Invalid input.")
if num <= 0:
raise ValueError("Roman numbers can only be positive. " +
"Please enter a po... | def roman(num):
"""
Function to convert an integer to roman numeral.
:type num: int
:rtype: str
"""
if type(num) is not int:
raise type_error('Invalid input.')
if num <= 0:
raise value_error('Roman numbers can only be positive. ' + 'Please enter a positive integer.')
val... |
fit2_lm = sm.ols(formula="y ~ age + np.power(age, 2) + np.power(age, 3)",data=diab).fit()
poly_predictions = fit2_lm.get_prediction(predict_df).summary_frame()
poly_predictions.head()
| fit2_lm = sm.ols(formula='y ~ age + np.power(age, 2) + np.power(age, 3)', data=diab).fit()
poly_predictions = fit2_lm.get_prediction(predict_df).summary_frame()
poly_predictions.head() |
class Solution:
# def countAndSay(self, n):
# """
# :type n: int
# :rtype: str
# """
# s = '1'
# for _ in range(n - 1):
# s = ''.join(str(len(list(group))) + digit for digit, group in itertools.groupby(s))
# return s
def countAndSay(self, ... | class Solution:
def count_and_say(self, n):
res = '1'
for i in range(1, n):
res = self.helper(res)
return res
def helper(self, s):
if s == '':
return s
count = 1
say = s[0]
res = ''
for i in range(1, len(s)):
i... |
"""
Given a square matrix, write a function that rotates the matrix 90 degrees clockwise.
For example:
1 2 3 7 4 1
4 5 6 ---> 8 5 6
7 8 9 9 6 3
1 2 3 4 13 9 5 1
5 6 7 8 ---> 14 10 6 2
9 10 11 12 15 11 7 3
13 14 15 16 16 12 8 4
"""
def rotate_square_arr... | """
Given a square matrix, write a function that rotates the matrix 90 degrees clockwise.
For example:
1 2 3 7 4 1
4 5 6 ---> 8 5 6
7 8 9 9 6 3
1 2 3 4 13 9 5 1
5 6 7 8 ---> 14 10 6 2
9 10 11 12 15 11 7 3
13 14 15 16 16 12 8 4
"""
def rotate_square_arr... |
"""
The rotor class replicates the physical rotor in an Enigma.
"""
class Rotor:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
amountOfRotations = 0
def __init__(self, permutation, rotation):
"""
:param permutation: string, mono-alphabetic permutation of the alphabet in string form with corres... | """
The rotor class replicates the physical rotor in an Enigma.
"""
class Rotor:
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
amount_of_rotations = 0
def __init__(self, permutation, rotation):
"""
:param permutation: string, mono-alphabetic permutation of the alphabet in string form with corres... |
scores = [("Rodney Dangerfield", -1), ("Marlon Brando", 1), ("You", 100)] # list of tuples
for person in scores:
name = person[0]
score = person[1]
print("Hello {}. Your score is {}.".format(name, score))
origPrice = float(input('Enter the original price: $'))
discount = float(input('Enter discount perce... | scores = [('Rodney Dangerfield', -1), ('Marlon Brando', 1), ('You', 100)]
for person in scores:
name = person[0]
score = person[1]
print('Hello {}. Your score is {}.'.format(name, score))
orig_price = float(input('Enter the original price: $'))
discount = float(input('Enter discount percentage: '))
new_pric... |
def find_loop(root):
S = root
F = root
# set up first meeting
while True:
# if there is no loop, we will detect it
if S is None or F is None:
return None
# advance slow and fast pointers
S = S.next_node
F = F.next_node.next_node
if S is F:
... | def find_loop(root):
s = root
f = root
while True:
if S is None or F is None:
return None
s = S.next_node
f = F.next_node.next_node
if S is F:
break
s = root
while True:
s = S.next_node
f = F.next_node
if S is F:
... |
'''
Assume that two variables, varA and varB, are assigned values, either numbers or strings.
Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages:
"string involved" if either varA or varB are strings
"bigger" if varA is larger than varB
"equal" if varA is equ... | """
Assume that two variables, varA and varB, are assigned values, either numbers or strings.
Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages:
"string involved" if either varA or varB are strings
"bigger" if varA is larger than varB
"equal" if varA is equ... |
def __create_snap_entry(marker, entry_no, l):
# use parse_roll() to create search entry
node = []
x = []
for i in range(len(l)-1):
if len(l) == 2 and abs(l[i] - l[i+1]) == 2:
# if only two balls on the row
x += [[l[i], 1]]
elif abs(l[i] - l[i+1]) > 1:
... | def __create_snap_entry(marker, entry_no, l):
node = []
x = []
for i in range(len(l) - 1):
if len(l) == 2 and abs(l[i] - l[i + 1]) == 2:
x += [[l[i], 1]]
elif abs(l[i] - l[i + 1]) > 1:
x += [[l[i], 1]]
x += [[l[i + 1], -1]]
for item in x:
node.... |
""" Exceptions for EventBus. """
class EventDoesntExist(Exception):
""" Raised when trying remove an event that doesn't exist. """
pass
| """ Exceptions for EventBus. """
class Eventdoesntexist(Exception):
""" Raised when trying remove an event that doesn't exist. """
pass |
ls = list()
for _ in range(5):
ls.append(input())
res = list()
for i in range(len(ls)):
if 'FBI' in ls[i]:
res.append(str(i + 1))
if len(res) == 0:
print('HE GOT AWAY!')
else:
print(' '.join(res))
| ls = list()
for _ in range(5):
ls.append(input())
res = list()
for i in range(len(ls)):
if 'FBI' in ls[i]:
res.append(str(i + 1))
if len(res) == 0:
print('HE GOT AWAY!')
else:
print(' '.join(res)) |
matriz = [[], [], []]
for c in range(0, 3):
linha0 = matriz[0].append(int(input(f'Digite um valor para [0, {c}]: ')))
for c in range(0, 3):
linha1 = matriz[1].append(int(input(f'Digite um valor para [1, {c}]: ')))
for c in range(0, 3):
linha2 = matriz[2]. append(int(input(f'Digite um valor para [2, {c}]: ')... | matriz = [[], [], []]
for c in range(0, 3):
linha0 = matriz[0].append(int(input(f'Digite um valor para [0, {c}]: ')))
for c in range(0, 3):
linha1 = matriz[1].append(int(input(f'Digite um valor para [1, {c}]: ')))
for c in range(0, 3):
linha2 = matriz[2].append(int(input(f'Digite um valor para [2, {c}]: '))... |
class NCSBase:
def train(self, X, y):
pass
def scores(self, X, y, cp):
pass
def score(self, x, labels):
pass
class NCSBaseRegressor:
def train(self, X, y):
pass
def coeffs(self, X, y, cp):
pass
def coeffs_n(self, x):
pass
| class Ncsbase:
def train(self, X, y):
pass
def scores(self, X, y, cp):
pass
def score(self, x, labels):
pass
class Ncsbaseregressor:
def train(self, X, y):
pass
def coeffs(self, X, y, cp):
pass
def coeffs_n(self, x):
pass |
# Conditionals
# Allows for decision making based on the values of our variables
def main():
x = 1000
y = 10
if (x < y):
st = " x is less than y"
elif (x == y):
st = " x is the same as y"
else:
st = "x is greater than y"
print(st)
print("\nAlternatively:...")
... | def main():
x = 1000
y = 10
if x < y:
st = ' x is less than y'
elif x == y:
st = ' x is the same as y'
else:
st = 'x is greater than y'
print(st)
print('\nAlternatively:...')
statement = 'x is less than y' if x < y else 'x is greater than or the same as'
print... |
#!/usr/bin/env python
#
# Class implementing a serial (console) user interface for the Manchester Baby (SSEM)
#
#------------------------------------------------------------------------------
#
# Class construction.
#
#----------------------------------------------------------------------------... | class Consoleuserinterface:
"""This object will implement a console user interface for the Manchester Baby (SSEM)."""
def __init__(self):
pass
def update_display_tube(self, storeLines):
"""Update the display tube with the current contents od the store lines.
@param: storeL... |
a,b=map(str,input().split())
z=[]
x,c="",""
if a[0].islower():
x=x+a[0].upper()
if b[0].islower():
c=c+b[0].upper()
for i in range(1,len(a)):
if a[i].isupper() or a[i].islower():
x=x+a[i].lower()
for i in range(1,len(b)):
if b[i].isupper() or b[i].islower():
c=c+b[i].lower(... | (a, b) = map(str, input().split())
z = []
(x, c) = ('', '')
if a[0].islower():
x = x + a[0].upper()
if b[0].islower():
c = c + b[0].upper()
for i in range(1, len(a)):
if a[i].isupper() or a[i].islower():
x = x + a[i].lower()
for i in range(1, len(b)):
if b[i].isupper() or b[i].islower():
... |
#tutorials 3: Execute the below instructions in the interpreter
#execute the below command
"Hello World!"
print("Hello World!")
#execute using single quote
'Hello World!'
print('Hello World!')
#use \' to escape single quote
'can\'t'
print('can\'t')
#or use double quotes
"can't"
print("can't")
#more examples 1-... | """Hello World!"""
print('Hello World!')
'Hello World!'
print('Hello World!')
"can't"
print("can't")
"can't"
print("can't")
print('" I won\'t," she said.')
a = 'First Line. \n Second Line'
print(a)
print('\n-->string concatenation example without using +')
print('Python')
print('\n-->string concatenation: concatenating... |
k = int(input("k: "))
array = [10,2,3,6,18]
fulfilled = False
i = 0
while i < len(array):
if k-array[i] in array:
fulfilled = True
i += 1
if fulfilled == True:
print("True")
else:
print("False") | k = int(input('k: '))
array = [10, 2, 3, 6, 18]
fulfilled = False
i = 0
while i < len(array):
if k - array[i] in array:
fulfilled = True
i += 1
if fulfilled == True:
print('True')
else:
print('False') |
# https://www.codewars.com/kata/570ac43a1618ef634000087f/train/python
'''
Instructions:
Nova polynomial add
This kata is from a series on polynomial handling. ( #1 #2 #3 #4 )
Consider a polynomial in a list where each element in the list element corresponds to a factor. The factor order is the position in the list. ... | """
Instructions:
Nova polynomial add
This kata is from a series on polynomial handling. ( #1 #2 #3 #4 )
Consider a polynomial in a list where each element in the list element corresponds to a factor. The factor order is the position in the list. The first element is the zero order factor (the constant).
p = [a0, a1... |
# https://leetcode.com/problems/simplify-path/
class Solution:
def simplifyPath(self, path: str) -> str:
directories = path.split('/')
directory_stack = list()
for directory in directories:
if not directory == '' and not directory == '.':
if not directory == '..'... | class Solution:
def simplify_path(self, path: str) -> str:
directories = path.split('/')
directory_stack = list()
for directory in directories:
if not directory == '' and (not directory == '.'):
if not directory == '..':
directory_stack.append... |
#-------------------------------------------------------------------------------
# Name: misc_python
# Purpose: misc python utilities
#
# Author: matthewl9
#
# Version: 1.0
#
# Contains: write to file, quicksort, import_list
#
# Created: 21/02/2018
# Copyright: (c) matthewl9 2018
# Licence:... | def write(filepath, list1):
filepath = str(filepath)
file = open(filepath, 'w')
for count in range(len(list1)):
file.write(list1[count])
if count < len(list1) - 1:
file.write('\n')
file.close
def partition(data):
pivot = data[0]
(less, equal, greater) = ([], [], [])
... |
NONE = 0
HALT = 1 << 0
FAULT = 1 << 1
BREAK = 1 << 2
def VMStateStr(_VMState):
if _VMState == NONE:
return "NONE"
state = []
if _VMState & HALT:
state.append("HALT")
if _VMState & FAULT:
state.append("FAULT")
if _VMState & BREAK:
state.append("BREAK")
return ... | none = 0
halt = 1 << 0
fault = 1 << 1
break = 1 << 2
def vm_state_str(_VMState):
if _VMState == NONE:
return 'NONE'
state = []
if _VMState & HALT:
state.append('HALT')
if _VMState & FAULT:
state.append('FAULT')
if _VMState & BREAK:
state.append('BREAK')
return ',... |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return linear_search_iterative(array, i... | def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_iterative(array, item)
def linear_search_iterative(array, item):
for (index, value) in enumerate(array):
if item == value:
return index
return None
def li... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
# {
# 'target_name': 'byte_reader',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'conten... | {'targets': []} |
#!/usr/bin/env python3
'''
lib/subl/constants.py
Constants for use in sublime apis, including plugin-specific settings.
'''
'''
Settings file name.
This name is passed to sublime when loading the settings.
''' # pylint: disable=pointless-string-statement
SUBLIME_SETTINGS_FILENAME = 'sublime-ycmd.sublime-setting... | """
lib/subl/constants.py
Constants for use in sublime apis, including plugin-specific settings.
"""
'\nSettings file name.\n\nThis name is passed to sublime when loading the settings.\n'
sublime_settings_filename = 'sublime-ycmd.sublime-settings'
'\nSettings keys.\n\nThe "watch" key is used to register an on-change e... |
class Method:
BEGIN = 'calling.begin'
ANSWER = 'calling.answer'
END = 'calling.end'
CONNECT = 'calling.connect'
DISCONNECT = 'calling.disconnect'
PLAY = 'calling.play'
RECORD = 'calling.record'
RECEIVE_FAX = 'calling.receive_fax'
SEND_FAX = 'calling.send_fax'
SEND_DIGITS = 'calling.send_digits'
TA... | class Method:
begin = 'calling.begin'
answer = 'calling.answer'
end = 'calling.end'
connect = 'calling.connect'
disconnect = 'calling.disconnect'
play = 'calling.play'
record = 'calling.record'
receive_fax = 'calling.receive_fax'
send_fax = 'calling.send_fax'
send_digits = 'calli... |
SCHEMA = """\
CREATE TABLE gene (
id INTEGER PRIMARY KEY,
name TEXT,
start_pos INTEGER,
end_pos INTEGER,
strand INTEGER,
translation TEXT,
scaffold TEXT,
organism TEXT
);\
"""
QUERY = """\
SELECT
id,
name,
star... | schema = 'CREATE TABLE gene (\n id INTEGER PRIMARY KEY,\n name TEXT,\n start_pos INTEGER,\n end_pos INTEGER,\n strand INTEGER,\n translation TEXT,\n scaffold TEXT,\n organism TEXT\n);'
query = 'SELECT\n id,\n name,\n start... |
construction = ['Owner Authorization',
'Bidding & Contract Documents',
'Plans',
'Spedifications',
'Addenda',
'Submittals',
'Shop Drawings',
'Bonds',
'Insurance Certificates',
'Design Clarifications',
'Baseline Schedule',
'Schedule Revisions',
'Permits',
'Meeting Minutes',
'Payment Requests',
'Correspondence',
'Progres... | construction = ['Owner Authorization', 'Bidding & Contract Documents', 'Plans', 'Spedifications', 'Addenda', 'Submittals', 'Shop Drawings', 'Bonds', 'Insurance Certificates', 'Design Clarifications', 'Baseline Schedule', 'Schedule Revisions', 'Permits', 'Meeting Minutes', 'Payment Requests', 'Correspondence', 'Progress... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.