content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
numbers = [int(el) for el in input().split()]
average = sum(numbers) / (len(numbers))
top_5_list = []
current_max = 0
for num in range(5):
current_max = max(numbers)
if current_max > average:
top_5_list.append(current_max)
numbers.remove(current_max)
list(top_5_list)
if top_5_list:
print(*... | numbers = [int(el) for el in input().split()]
average = sum(numbers) / len(numbers)
top_5_list = []
current_max = 0
for num in range(5):
current_max = max(numbers)
if current_max > average:
top_5_list.append(current_max)
numbers.remove(current_max)
list(top_5_list)
if top_5_list:
print(*top_... |
class Solution:
def uniquePathsIII(self, grid) -> int:
start=list()
paths=set()
row=len(grid)
col=len(grid[0])
for r in range(row):
for c in range(col):
if grid[r][c]==1:
start.append(r)
start.append(c)
... | class Solution:
def unique_paths_iii(self, grid) -> int:
start = list()
paths = set()
row = len(grid)
col = len(grid[0])
for r in range(row):
for c in range(col):
if grid[r][c] == 1:
start.append(r)
start.ap... |
def print_multiples(n, high):
for i in range(1, high+1):
print(n * i, end=" ")
print()
def print_mult_table(high):
for i in range(1, high+1):
print_multiples(i, i)
print_mult_table(7)
| def print_multiples(n, high):
for i in range(1, high + 1):
print(n * i, end=' ')
print()
def print_mult_table(high):
for i in range(1, high + 1):
print_multiples(i, i)
print_mult_table(7) |
# -*- coding: utf-8 -*-
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
| thislist = ['banana', 'Orange', 'Kiwi', 'cherry']
thislist.sort(key=str.lower)
print(thislist) |
"""
None
"""
class Solution:
def wordsAbbreviation(self, dict: List[str]) -> List[str]:
def shorten(word, idx):
return word if idx > len(word) - 3 else \
word[:idx] + str(len(word)-1-idx) + word[-1]
res = [shorten(word, 1) for word in dict]
p... | """
None
"""
class Solution:
def words_abbreviation(self, dict: List[str]) -> List[str]:
def shorten(word, idx):
return word if idx > len(word) - 3 else word[:idx] + str(len(word) - 1 - idx) + word[-1]
res = [shorten(word, 1) for word in dict]
pre = {word: 1 for word in dict}... |
#!/usr/bin/python3.6
# This should be introduced in the interactive python shell. Where the arguments to print should just be passed to the shell.
# We should keep it to the 4 basic arithmetic functions at first since most kids don't get introduced to other functions until later.
print(2 + 2)
print(3 - 2)
print(2 ... | print(2 + 2)
print(3 - 2)
print(2 * 3)
print(8 / 5)
x = 10
print(x)
y = 5
print(x * y)
print(x - y) |
"""
Data acquisition boards
=======================
.. todo:: Data acquisition board drivers.
Provides:
.. autosummary::
:toctree:
daqmx
"""
| """
Data acquisition boards
=======================
.. todo:: Data acquisition board drivers.
Provides:
.. autosummary::
:toctree:
daqmx
""" |
#
# PySNMP MIB module Wellfleet-SWSMDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-SWSMDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:41:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
#!/usr/bin/env python
class Edge:
"""Edge class, to contain a directed edge of a tree or directed graph.
attributes parent and child: index of parent and child node in the graph.
"""
def __init__ (self, parent, child, length=None):
"""create a new Edge object, linking nodes
with indice... | class Edge:
"""Edge class, to contain a directed edge of a tree or directed graph.
attributes parent and child: index of parent and child node in the graph.
"""
def __init__(self, parent, child, length=None):
"""create a new Edge object, linking nodes
with indices parent and child."""
... |
class Session(list):
"""Abstract Session class"""
def to_strings(self, user_id, session_id):
"""represent session as list of strings (one per event)"""
user_id, session_id = str(user_id), str(session_id)
session_type = self.get_type()
strings = []
for event, product in s... | class Session(list):
"""Abstract Session class"""
def to_strings(self, user_id, session_id):
"""represent session as list of strings (one per event)"""
(user_id, session_id) = (str(user_id), str(session_id))
session_type = self.get_type()
strings = []
for (event, product... |
DEVICE_NOT_KNOWN = "Device name not known"
NEED_TO_SPECIFY_DEVICE_NAME = "You need to specify device name : ?device_name=..."
INVALID_HOUR = "Provided time is invalid"
DEVICE_SCHEDULE_OK = "Device schedule was setup"
NEED_TO_SPECIFY_JOB_ID = "You need to specidy Job id you want to get removed"
DELETE_SCHEDULE_OK =... | device_not_known = 'Device name not known'
need_to_specify_device_name = 'You need to specify device name : ?device_name=...'
invalid_hour = 'Provided time is invalid'
device_schedule_ok = 'Device schedule was setup'
need_to_specify_job_id = 'You need to specidy Job id you want to get removed'
delete_schedule_ok = 'Sch... |
'''
name = input()
if name != 'Anton':
print(f'I am not Anton, i am {name}')
else:
print(f'I am {name}')
'''
n = 10
while n > 0:
n = n - 1
print(n)
| """
name = input()
if name != 'Anton':
print(f'I am not Anton, i am {name}')
else:
print(f'I am {name}')
"""
n = 10
while n > 0:
n = n - 1
print(n) |
# Pattern Matching (Python)
# string is already given to you. Please don't edit this string.
stringData = "qwe sdf dsld dssdfsqwe sdlcsd fdslkcsdsdk sdvnsdnvs dsvd d d dddqwelkmvl sdlksf qwelkmdsldm dsfkmsdf ds lknvnv dsdfdfnoiewqwek sdjnsdf djndsjnnqwnewefsjdc kqwj fsdfjsldnlsqwelkwnekennlksnq dlkneknqwn wqenln qlwn... | string_data = 'qwe sdf dsld dssdfsqwe sdlcsd fdslkcsdsdk sdvnsdnvs dsvd d d dddqwelkmvl sdlksf qwelkmdsldm dsfkmsdf ds lknvnv dsdfdfnoiewqwek sdjnsdf djndsjnnqwnewefsjdc kqwj fsdfjsldnlsqwelkwnekennlksnq dlkneknqwn wqenln qlwn qlwknr wkernwen dkfndks ewqsdkslf efwekwkewqwen mdfsdfsdfskdnlknqwenknfsd lsklksna kasndasndq... |
""" Parameters of the FLAT data sets, as documented for Kinect2 camera in the FLAT code"""
resolution = [424, 512]
fov_real = [58.5, 46.6]
fov_synth = [42.13, 42.13]
# frequencies of the first and last 3 measurements, the middle measurements are not sinusoidal
frequencies = [40, 1e2 / 3.3, 1e2 / 1.7]
frequencies_2 =... | """ Parameters of the FLAT data sets, as documented for Kinect2 camera in the FLAT code"""
resolution = [424, 512]
fov_real = [58.5, 46.6]
fov_synth = [42.13, 42.13]
frequencies = [40, 100.0 / 3.3, 100.0 / 1.7]
frequencies_2 = [80.1675385, 16.05444453, 120.44403642]
phase_offsets = [240, 120, 0]
phase_offsets_2 = [[150... |
FUNC_ORDER = [
"do_fetch",
"do_unpack",
"do_patch",
"do_configure",
"do_compile",
"do_install",
"do_populate_sysroot",
"do_build",
"do_package"
]
KNOWN_FUNCS = [
"do_addto_recipe_sysroot",
"do_allpackagedata",
"do_ar_configured",
"do_ar_original",
"do_ar_patched"... | func_order = ['do_fetch', 'do_unpack', 'do_patch', 'do_configure', 'do_compile', 'do_install', 'do_populate_sysroot', 'do_build', 'do_package']
known_funcs = ['do_addto_recipe_sysroot', 'do_allpackagedata', 'do_ar_configured', 'do_ar_original', 'do_ar_patched', 'do_ar_recipe', 'do_assemble_fitimage', 'do_assemble_fitim... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class MyLinkedList(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
def get(self, index):
cur = self.getnthnode(index)
if ... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Mylinkedlist(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
def get(self, index):
cur = self.getnthnode(index)
if... |
def test(name, input0, input1, output0, input0_data, input1_data, output_data):
model = Model().Operation("REVERSE_EX", input0, input1).To(output0)
example = Example({
input0: input0_data,
input1: input1_data,
output0: output_data,
}, model=model, name=name)
test(
name="1d",
input0=Inpu... | def test(name, input0, input1, output0, input0_data, input1_data, output_data):
model = model().Operation('REVERSE_EX', input0, input1).To(output0)
example = example({input0: input0_data, input1: input1_data, output0: output_data}, model=model, name=name)
test(name='1d', input0=input('input0', 'TENSOR_FLOAT32',... |
def get_gender(gender = 'Unknown'):
if gender is 'm':
gender="male"
elif gender is 'f':
gender='female'
print("Gender is ", gender)
get_gender('m')
get_gender('f')
get_gender()
def sentence(name = 'Aousnik', gender = 'male', category = 'general'):
print(name, gender, catego... | def get_gender(gender='Unknown'):
if gender is 'm':
gender = 'male'
elif gender is 'f':
gender = 'female'
print('Gender is ', gender)
get_gender('m')
get_gender('f')
get_gender()
def sentence(name='Aousnik', gender='male', category='general'):
print(name, gender, category)
sentence('abc... |
list = [1,2,3,4]
test_list = list1
test_list.reverse()
print(list)
| list = [1, 2, 3, 4]
test_list = list1
test_list.reverse()
print(list) |
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
if not costs: return 0
lower_row = costs[-1]
for i in range(len(costs)-2, -1, -1):
curr_row = costs[i]
curr_row[0] += min(lower_row[1], lower_row[2])
curr_row[1] += min(lower_row[0], lower_r... | class Solution:
def min_cost(self, costs: List[List[int]]) -> int:
if not costs:
return 0
lower_row = costs[-1]
for i in range(len(costs) - 2, -1, -1):
curr_row = costs[i]
curr_row[0] += min(lower_row[1], lower_row[2])
curr_row[1] += min(lower... |
__author__ = 'harsh'
class Iterable(object):
def __init__(self,values):
self.values = values
self.location = 0
def __iter__(self):
return self
def next(self):
if self.location == len(self.values):
raise StopIteration
value = self.values[self.location]... | __author__ = 'harsh'
class Iterable(object):
def __init__(self, values):
self.values = values
self.location = 0
def __iter__(self):
return self
def next(self):
if self.location == len(self.values):
raise StopIteration
value = self.values[self.location]... |
"""Base class for SHADHO task managers.
Classes
-------
Manager
Base class for task managers.
"""
class Manager():
"""Base class for task managers.
Notes
-----
To implement a new local or distributed manager, create an __init__
method and override all
"""
def __init__(self):
... | """Base class for SHADHO task managers.
Classes
-------
Manager
Base class for task managers.
"""
class Manager:
"""Base class for task managers.
Notes
-----
To implement a new local or distributed manager, create an __init__
method and override all
"""
def __init__(self):
p... |
#
# PySNMP MIB module Nortel-Magellan-Passport-FrameRelayDteMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-FrameRelayDteMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:17:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user da... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint) ... |
"""
This module holds all the sql statements for List_Tags
"""
#------------------------------------------------------
# Select all the tags assigned to a list
#
# 2 parms:
# - list_id
# - user_id
#------------------------------------------------------
SELECT_ALL = '''
SELECT *
FROM View_Tags vt
WHE... | """
This module holds all the sql statements for List_Tags
"""
select_all = '\n SELECT * \n FROM View_Tags vt\n WHERE EXISTS \n (\n SELECT 1 \n FROM List_Tags lt\n WHERE lt.list_id = %s \n AND lt.tag_id = vt.id\n AND Owns_List(%s, lt.list_id)\n )\n \n ... |
query_issues = """
{
repository(name: "{placeholder_nome_repo}", owner: "{placeholder_owner_repo}") {
issues(filterBy: {labels: ["BUG", "bug", "Bug", "Type: Bug", "Type: BUG", "Type: bug", "type: Bug",
"type: BUG", "type: bug", "browser bug", "Error", "ERROR", "error", "Failure", "FAILURE", "failure... | query_issues = '\n{\n repository(name: "{placeholder_nome_repo}", owner: "{placeholder_owner_repo}") {\n issues(filterBy: {labels: ["BUG", "bug", "Bug", "Type: Bug", "Type: BUG", "Type: bug", "type: Bug",\n "type: BUG", "type: bug", "browser bug", "Error", "ERROR", "error", "Failure", "FAILURE", "failu... |
numbers = [1,21,4234,423432,42345,324]
largest = numbers[0]
for x in numbers:
if largest < x:
largest = x
print(f'The largest value is : {largest}')
| numbers = [1, 21, 4234, 423432, 42345, 324]
largest = numbers[0]
for x in numbers:
if largest < x:
largest = x
print(f'The largest value is : {largest}') |
# -*- coding: utf-8 -*-
class Solution:
def matrixReshape(self, nums, r, c):
original_r, original_c = len(nums), len(nums[0])
if r * c != original_r * original_c:
return nums
tmp = [nums[i][j] for i in range(original_r) for j in range(original_c)]
result = []
... | class Solution:
def matrix_reshape(self, nums, r, c):
(original_r, original_c) = (len(nums), len(nums[0]))
if r * c != original_r * original_c:
return nums
tmp = [nums[i][j] for i in range(original_r) for j in range(original_c)]
result = []
for i in range(r):
... |
#food = "Python's favorite food is perl"
#say = "\"Python is very easy.\" he says"
#print(say)
#multiline = """
# Test1
# Test2
#"""
#print(multiline)
a = "Test"
b = "123"
print(a+b)
| a = 'Test'
b = '123'
print(a + b) |
def clientFunction(args, files):
print('client function call with args ' +
str(args) + ' and files ' + str(files))
return args
if __name__ == "__main__":
clientFunction()
| def client_function(args, files):
print('client function call with args ' + str(args) + ' and files ' + str(files))
return args
if __name__ == '__main__':
client_function() |
# Instructions
print('''This short program computes the circumference of a circle
from a provided raduis. Provide the radius as a floating
point value.\n''')
# Prompt user for circumference
radius = input('Enter a radius: ')
# Assume correct type
circ = 2 * 3.14159 * float(radius);
# Provide output
print(f'The circ... | print('This short program computes the circumference of a circle\nfrom a provided raduis. Provide the radius as a floating\npoint value.\n')
radius = input('Enter a radius: ')
circ = 2 * 3.14159 * float(radius)
print(f'The circumference of a circle with radius {radius} is {circ}') |
class Place:
destination=""
iata_code = ""
attractions_list =[]
hotels_list = []
weather = []
flights = []
restaurants_list = []
def __init__(self, iata_code):
self.iata_code = iata_code
| class Place:
destination = ''
iata_code = ''
attractions_list = []
hotels_list = []
weather = []
flights = []
restaurants_list = []
def __init__(self, iata_code):
self.iata_code = iata_code |
# tutorial 38 revison of chapter 2
a=int(input("enter first number : "))
b=int(input("enter second number : "))
total=a+b
print("total is " + str(total)) | a = int(input('enter first number : '))
b = int(input('enter second number : '))
total = a + b
print('total is ' + str(total)) |
class Request(object):
""" Represents a request of a product. """
def __init__(self):
self.backend_object = None
self.amount = None
self.name = None
self.due = None
self.impossible = False
self.due = None
def set(self, name, amount, obj):
self.name ... | class Request(object):
""" Represents a request of a product. """
def __init__(self):
self.backend_object = None
self.amount = None
self.name = None
self.due = None
self.impossible = False
self.due = None
def set(self, name, amount, obj):
self.name =... |
__title__ = 'icd10-cm-ng'
__description__ = ('ICD-10 codes for diseases, signs and symptoms, abnormal findings, '
'complaints, social circumstances, and external causes of injury or disease')
__url__ = 'https://github.com/AberystwythSystemsBiology/icd10-cm-ng'
__version__ = '0.0.5'
__author__ = 'Keir... | __title__ = 'icd10-cm-ng'
__description__ = 'ICD-10 codes for diseases, signs and symptoms, abnormal findings, complaints, social circumstances, and external causes of injury or disease'
__url__ = 'https://github.com/AberystwythSystemsBiology/icd10-cm-ng'
__version__ = '0.0.5'
__author__ = 'Keiron OShea'
__author_email... |
def layout_instructors(instructors) -> str:
result = ''
for instructor in instructors[:-1]:
result += '{}; '.format(instructor)
else:
result += '{}'.format(instructors[-1])
return result
def layout_enr(enr) -> str:
return enr.split('/')[0] if '/' in enr else enr
| def layout_instructors(instructors) -> str:
result = ''
for instructor in instructors[:-1]:
result += '{}; '.format(instructor)
else:
result += '{}'.format(instructors[-1])
return result
def layout_enr(enr) -> str:
return enr.split('/')[0] if '/' in enr else enr |
# Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
# If the last word does not exist, return 0.
# Note: A word is defined as a character sequence consists of non-space characters only.
# Example:
# Input: "Hello World"
# Output: 5
... | class Solution(object):
def length_of_last_word(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.rstrip().split(' ')[-1]) |
def time_diff(time_vals):
time1 = time_vals
time2 = time_vals.shift(1)
delta = time1 - time2
return delta | def time_diff(time_vals):
time1 = time_vals
time2 = time_vals.shift(1)
delta = time1 - time2
return delta |
"""
CherryPy Config server settings module.
"""
__author__ = 'Jovan Brakus <jovan@brakus.rs>'
__contact__ = 'jovan@brakus.rs'
__date__ = '31 May 2012'
CONFIG_FILENAME = "config_server.ini"
WEBSERVER_HOST = '0.0.0.0'
WEBSERVER_PORT = 8080
USERS = {'cherrypy': '57ed5d98cce71967d508cb785aa76d2c23894347'} # SHA... | """
CherryPy Config server settings module.
"""
__author__ = 'Jovan Brakus <jovan@brakus.rs>'
__contact__ = 'jovan@brakus.rs'
__date__ = '31 May 2012'
config_filename = 'config_server.ini'
webserver_host = '0.0.0.0'
webserver_port = 8080
users = {'cherrypy': '57ed5d98cce71967d508cb785aa76d2c23894347'}
log_dir = 'logs'
... |
nome = input('Qual seu nome? ')
idade = input('Digite sua idade: ')
peso = input('Digite seu peso: ')
print(nome, idade, peso)
| nome = input('Qual seu nome? ')
idade = input('Digite sua idade: ')
peso = input('Digite seu peso: ')
print(nome, idade, peso) |
def main():
"""Main program
"""
digits = []
while True:
new_dig = input("Enter a digit. Enter E to exit.\n")
if new_dig == "E":
break
digits.append(new_dig)
print(sorted(digits))
if __name__ == "__main__":
main()
| def main():
"""Main program
"""
digits = []
while True:
new_dig = input('Enter a digit. Enter E to exit.\n')
if new_dig == 'E':
break
digits.append(new_dig)
print(sorted(digits))
if __name__ == '__main__':
main() |
expected_output = {
"test_genie_1": {
"color": 0,
"name": "test_genie_1",
"status": {
"admin": "down",
"operational": {
"since": "05-18 03:50:08.958",
"state": "down",
"time_for_state": "00:00:01",
},
... | expected_output = {'test_genie_1': {'color': 0, 'name': 'test_genie_1', 'status': {'admin': 'down', 'operational': {'since': '05-18 03:50:08.958', 'state': 'down', 'time_for_state': '00:00:01'}}}, 'test_genie_2': {'attributes': {'binding_sid': {257: {'allocation_mode': 'dynamic', 'state': 'programmed'}}}, 'candidate_pa... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(X, Y, D):
# write your code in Python 3.6
total_distance = Y - X
rounded_number_of_jumps = total_distance // D
division_rest = total_distance % D
return rounded_number_of_jumps if division_rest ... | def solution(X, Y, D):
total_distance = Y - X
rounded_number_of_jumps = total_distance // D
division_rest = total_distance % D
return rounded_number_of_jumps if division_rest == 0 else rounded_number_of_jumps + 1 |
def minimum_swaps(ratings: list) -> int:
# get the rating compliment value. That is, lower value is higher rating
complmnt = [len(ratings)-val+1 for val in ratings]
len_arr = len(complmnt)
idx = 0
swap_counter = 0
while idx < len_arr:
if complmnt[idx] != (idx+1):
# swap the values ... | def minimum_swaps(ratings: list) -> int:
complmnt = [len(ratings) - val + 1 for val in ratings]
len_arr = len(complmnt)
idx = 0
swap_counter = 0
while idx < len_arr:
if complmnt[idx] != idx + 1:
(complmnt[complmnt[idx] - 1], complmnt[idx]) = (complmnt[idx], complmnt[complmnt[idx]... |
def getPointsInOrder(box,flag):
'''
returns in top-left, top-right, bottom-left, bottom-right order
'''
ret = []
if flag==0:
ret = [box[1],box[2],box[0],box[3]]
else:
ret = [box[2],box[3],box[1],box[0]]
return ret | def get_points_in_order(box, flag):
"""
returns in top-left, top-right, bottom-left, bottom-right order
"""
ret = []
if flag == 0:
ret = [box[1], box[2], box[0], box[3]]
else:
ret = [box[2], box[3], box[1], box[0]]
return ret |
# Bus communication
SJ_DefaultBaud = 115200
SJ_DefaultPortIn = 5000
# General
SJ_Timeout = 100 #in ms
SJ_CommandStart = "#"
SJ_CommandEnd = "\r"
#actions
SJ_ActionLED = "LED"
SJ_BlinkLED = "BLK"
SJ_BlinkLEDSTOP = "NBLK"
SJ_FetchTemperature = "ATMP"
#response
SJ_Temperature = "RTMP"
# LED colors
NAVIO_LED_Blac... | sj__default_baud = 115200
sj__default_port_in = 5000
sj__timeout = 100
sj__command_start = '#'
sj__command_end = '\r'
sj__action_led = 'LED'
sj__blink_led = 'BLK'
sj__blink_ledstop = 'NBLK'
sj__fetch_temperature = 'ATMP'
sj__temperature = 'RTMP'
navio_led__black = '0'
navio_led__red = '1'
navio_led__green = '2'
navio_l... |
starts_with_B = {
'B&':'Banned',
'B2B':'Business-to-business',
'B2C':'Business-to-consumer',
'B2W':'Back to work',
'B8':'Bait',
('B/F','BF'):'Boyfriend',
('B/G','BG'):'Background',
... | starts_with_b = {'B&': 'Banned', 'B2B': 'Business-to-business', 'B2C': 'Business-to-consumer', 'B2W': 'Back to work', 'B8': 'Bait', ('B/F', 'BF'): 'Boyfriend', ('B/G', 'BG'): 'Background', 'B4': 'Before', 'B4N': 'Bye for now', 'BAE': 'Babe', 'BAFO': 'Best and final offer', 'BAO': 'Be aware of', 'BAU': 'Business as usua... |
# coding: utf-8
n = int(input())
x = [int(i) for i in input().split()]
while True:
tmp = min(x)
for i in range(n):
if x[i]%tmp == 0:
x[i] = tmp
else:
x[i] %= tmp
if sum(x) == tmp*n:
break
print(sum(x))
| n = int(input())
x = [int(i) for i in input().split()]
while True:
tmp = min(x)
for i in range(n):
if x[i] % tmp == 0:
x[i] = tmp
else:
x[i] %= tmp
if sum(x) == tmp * n:
break
print(sum(x)) |
string = str(input("Enter numbers for polynom divided by whitespaces: "))
polynums = string.split(" ")
sum = 0
i = 0
while i<len(polynums):
sum += (1 / int(polynums[i]))
i +=1
print("Answer is ", sum)
| string = str(input('Enter numbers for polynom divided by whitespaces: '))
polynums = string.split(' ')
sum = 0
i = 0
while i < len(polynums):
sum += 1 / int(polynums[i])
i += 1
print('Answer is ', sum) |
# o(n) time
# o(n) space
def find_best_schedule(appointments):
n = len(appointments)
dp = [0] * (n + 1)
dp[-2] = appointments[-1]
max_so_far = -float("inf")
for i in reversed(range(n - 1)):
choices = []
# choice 1, take the ith element, then skip i+1, and take i+2.
choice... | def find_best_schedule(appointments):
n = len(appointments)
dp = [0] * (n + 1)
dp[-2] = appointments[-1]
max_so_far = -float('inf')
for i in reversed(range(n - 1)):
choices = []
choices.append((appointments[i] + dp[i + 2], i + 2))
choices.append((dp[i + 1], i + 1))
dp... |
# import sys
# sys.setrecursionlimit(1000)
# print(sys.getrecursionlimit())
def factorial(n):
"""Calculate n factorial
n int > 0
returns n!
"""
if n == 1:
return 1
return n * factorial(n - 1)
n = int(input('Input a integer to get the factorial value: '))
print(f'{n} factorial = {factor... | def factorial(n):
"""Calculate n factorial
n int > 0
returns n!
"""
if n == 1:
return 1
return n * factorial(n - 1)
n = int(input('Input a integer to get the factorial value: '))
print(f'{n} factorial = {factorial(n)}') |
enc = map(int,raw_input("Paste the cipher.txt here \n").split(','))
for a in range(26):
a += ord('a')
for b in range(26):
b += ord('a')
for c in range(26):
c += ord('a')
dec = [x for x in enc]
f = 0
for i in range(len(dec)):
if i %3... | enc = map(int, raw_input('Paste the cipher.txt here \n').split(','))
for a in range(26):
a += ord('a')
for b in range(26):
b += ord('a')
for c in range(26):
c += ord('a')
dec = [x for x in enc]
f = 0
for i in range(len(dec)):
if i %... |
# creating an empty hash table from 5 items
hash_table = [[] for _ in range(5)]
print(hash_table)
# insterting keys and values to it
def insert(hash_table, key, value):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, ... | hash_table = [[] for _ in range(5)]
print(hash_table)
def insert(hash_table, key, value):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for (i, kv) in enumerate(bucket):
(k, v) = kv
if key == k:
key_exists = True
break
... |
# -*- coding: utf-8 -*-
even = 0
odd = 0
positive = 0
negative = 0
for i in range(5):
A = float(input())
if (A % 2) == 0:
even +=1
elif (A%2) != 0 and A != 0:
odd+=1
if A > 0:
positive +=1
elif A < 0:
negative +=1
print("%i valor(es) par(es)"%even)
print("%i valor(es... | even = 0
odd = 0
positive = 0
negative = 0
for i in range(5):
a = float(input())
if A % 2 == 0:
even += 1
elif A % 2 != 0 and A != 0:
odd += 1
if A > 0:
positive += 1
elif A < 0:
negative += 1
print('%i valor(es) par(es)' % even)
print('%i valor(es) impar(es)' % odd)
... |
x = input()
y = input()
z = input()
if x == 'vertebrado':
if y == 'ave':
if z == 'carnivoro':
print('aguia')
elif z == 'onivoro':
print('pomba')
elif y == 'mamifero':
if z == 'onivoro':
print('homem')
elif z == 'herbivoro':
print('v... | x = input()
y = input()
z = input()
if x == 'vertebrado':
if y == 'ave':
if z == 'carnivoro':
print('aguia')
elif z == 'onivoro':
print('pomba')
elif y == 'mamifero':
if z == 'onivoro':
print('homem')
elif z == 'herbivoro':
print('v... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | class Modelbase(object):
"""`ModelBase` is the base class of the `parl.Model` in different frameworks.
This base class mainly do the following things:
1. Implements APIs to manage model_id of the `parl.Model`;
2. Defines common APIs that `parl.Model` should implement in different frameworks.
... |
def test_head_request_():
pass
def test_status_smaller_100():
pass
def test_not_modified_304():
pass
def test_no_content_204():
pass
def test_reset_content_205():
pass
| def test_head_request_():
pass
def test_status_smaller_100():
pass
def test_not_modified_304():
pass
def test_no_content_204():
pass
def test_reset_content_205():
pass |
# Prison Break
#
# Find the largest area created in the cell after removing horz and vert rods
# Solution: Find the longest seq of rods removed from horz * longest seq of rods removed from vert
# Time O(n+m) Space O(1)
def find_max_gap(size, rods):
# track curr gap, max gap, and prev rod removed
prev = -1
... | def find_max_gap(size, rods):
prev = -1
curr = 1
max_gap = curr
for i in rods:
if i - 1 == prev:
curr += 1
max_gap = max(max_gap, curr)
else:
curr = 2
max_gap = max(max_gap, curr)
prev = i
return max_gap
def max_area(n, m, rows... |
# import time
# a = time.localtime()
# print(a)
file = open("test", "r")
# file_lines = file.readlines()
# for line in file:
# print(line)
#
# for line in file_lines:
# print(line)
while True:
data = file.read(5)
print(data)
if not data:
break
| file = open('test', 'r')
while True:
data = file.read(5)
print(data)
if not data:
break |
# -*- coding: utf-8 -*-
SMILLY_ITEMS = ["Duplicate Code", "Long Methods", "Ugly Variable Names"]
BACKSTAGE_PASSES = ["Backstage passes for Re:Factor" ,"Backstage passes for HAXX"]
GOOD_WINE = "Good Wine"
LEGENDARY_ITEM = "B-DAWG Keychain"
class GildedRose(object):
def __init__(self, items):
self.items = i... | smilly_items = ['Duplicate Code', 'Long Methods', 'Ugly Variable Names']
backstage_passes = ['Backstage passes for Re:Factor', 'Backstage passes for HAXX']
good_wine = 'Good Wine'
legendary_item = 'B-DAWG Keychain'
class Gildedrose(object):
def __init__(self, items):
self.items = items
def increment(... |
def spp():
a = [1, 2, 3, 4]
val = 3
print(a.index(val))
if __name__ == '__main__':
spp() | def spp():
a = [1, 2, 3, 4]
val = 3
print(a.index(val))
if __name__ == '__main__':
spp() |
# You are given with an array of numbers,
# Your task is to print the difference of indices of largest and smallest number.
# All number are unique.
N = int(input(""))
array = list(map(int, input().split(" ")[:N]))
maxIndex = 0
minIndex = 0
max = array[0]
min = array[0]
for i in range(1, len(array)):
if(array[i] ... | n = int(input(''))
array = list(map(int, input().split(' ')[:N]))
max_index = 0
min_index = 0
max = array[0]
min = array[0]
for i in range(1, len(array)):
if array[i] > max:
max = array[i]
max_index = i
if array[i] < min:
min = array[i]
min_index = i
print(maxIndex - minIndex) |
class ObjectAlreadyInCollection(Exception):
pass
class CollectionIsLocked(Exception):
pass
| class Objectalreadyincollection(Exception):
pass
class Collectionislocked(Exception):
pass |
# SUPPLY
class Supply:
vid = 0
v_bulk = 0
v_proc = 0
i_inst = 0
proc_max_i = 0
proc_min_i = 0
proc_max_v = 0
proc_min_v = 0
rpdn = 0
rll = 0
def __init__(self, rpdn, rll, vcc_max, vcc_min, imax, imin):
self.rpdn = rpdn
self.rll = rll
self.proc_max_i = imax
self.proc_min_i = im... | class Supply:
vid = 0
v_bulk = 0
v_proc = 0
i_inst = 0
proc_max_i = 0
proc_min_i = 0
proc_max_v = 0
proc_min_v = 0
rpdn = 0
rll = 0
def __init__(self, rpdn, rll, vcc_max, vcc_min, imax, imin):
self.rpdn = rpdn
self.rll = rll
self.proc_max_i = imax
... |
def intersection(lst1, lst2):
"""
>>> intersection([1, 2, 3], [2, 4, 6])
[2]
>>> intersection([1, 2, 3], [4, 5, 6])
[]
>>> intersection([2, 3, 2, 4], [2, 2, 4])
[2, 4]
"""
in_both = []
for item1 in lst1:
for item2 in lst2:
if item1 == item2 and item2 not in i... | def intersection(lst1, lst2):
"""
>>> intersection([1, 2, 3], [2, 4, 6])
[2]
>>> intersection([1, 2, 3], [4, 5, 6])
[]
>>> intersection([2, 3, 2, 4], [2, 2, 4])
[2, 4]
"""
in_both = []
for item1 in lst1:
for item2 in lst2:
if item1 == item2 and item2 not in in... |
# The list is generated using https://w.wiki/aaD
# Picking the top 50 ones only because it covers 97% of cases
ASTRONOMICAL_OBJECTS = [
'Q523', 'Q318', 'Q1931185', 'Q1457376', 'Q2247863', 'Q3863', 'Q83373',
'Q2154519', 'Q726242', 'Q1153690', 'Q204107', 'Q71963409', 'Q67206691',
'Q1151284', 'Q67206701', 'Q66... | astronomical_objects = ['Q523', 'Q318', 'Q1931185', 'Q1457376', 'Q2247863', 'Q3863', 'Q83373', 'Q2154519', 'Q726242', 'Q1153690', 'Q204107', 'Q71963409', 'Q67206691', 'Q1151284', 'Q67206701', 'Q66619666', 'Q72802727', 'Q2168098', 'Q6243', 'Q72802508', 'Q11282', 'Q72803170', 'Q1332364', 'Q72802977', 'Q6999', 'Q1491746',... |
class InvalidToken(Exception):
"""An Exception Raised When an Invalid Token was Supplied."""
def __init__(self):
super(InvalidToken, self).__init__("An Invalid Bearer Token was Supplied to Weverse.")
class PageNotFound(Exception):
r"""
An Exception Raised When a link was not found.
Parame... | class Invalidtoken(Exception):
"""An Exception Raised When an Invalid Token was Supplied."""
def __init__(self):
super(InvalidToken, self).__init__('An Invalid Bearer Token was Supplied to Weverse.')
class Pagenotfound(Exception):
"""
An Exception Raised When a link was not found.
Paramet... |
# Shunting algorithm
# Jose Retamal
# Graph theory project GMIT 2019
# This algorithm is base on:
# http://www.oxfordmathcenter.com/drupal7/node/628
# https://web.microsoftstream.com/video/cfc9f4a2-d34f-4cde-afba-063797493a90
class Converter:
"""
Methods for converting string.
toPofix() implement, ... | class Converter:
"""
Methods for converting string.
toPofix() implement, method that convert a infix string into a
postfix string.
"""
def to_pofix(self, infix):
"""
Convert infix string to postfix string.
:param infix: infix string to convert
:return: p... |
class Solution:
def helper(self, n: int):
if n == 0:
return (0, 1)
else:
a, b = self.helper(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
... | class Solution:
def helper(self, n: int):
if n == 0:
return (0, 1)
else:
(a, b) = self.helper(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
... |
'''
Kattis - blackout
We start by blocking off 1 row, then we are left with a 4x6 grid, notice that both lengths are even! So what we can do
is to mirror the moves of the opponent on both axes and then we will definitely win!s
Time: O(1), Space: O(1)'''
num_tc = int(input())
for _ in range(num_tc):
print("5 1 5 6"... | """
Kattis - blackout
We start by blocking off 1 row, then we are left with a 4x6 grid, notice that both lengths are even! So what we can do
is to mirror the moves of the opponent on both axes and then we will definitely win!s
Time: O(1), Space: O(1)"""
num_tc = int(input())
for _ in range(num_tc):
print('5 1 5 6'... |
def hero_to_zeroa(n:int, k:int)->int:
step = 0
while(n>0):
step += n%k
n = (n//k) * k
if n == 0:
break
step += 1
n //= k
return step
numtest = int(input().strip())
for _ in range(numtest):
line = input().strip().split()
... | def hero_to_zeroa(n: int, k: int) -> int:
step = 0
while n > 0:
step += n % k
n = n // k * k
if n == 0:
break
step += 1
n //= k
return step
numtest = int(input().strip())
for _ in range(numtest):
line = input().strip().split()
print(hero_to_zeroa(i... |
num = int(input("Enter a number:\n"))
if num % 5 == 0:
print(f"{num} is a multiple of 5.")
else:
print(f"{num} is not a multiple of 5.")
| num = int(input('Enter a number:\n'))
if num % 5 == 0:
print(f'{num} is a multiple of 5.')
else:
print(f'{num} is not a multiple of 5.') |
# Fibonacci Pyramid
a = 1
b = 2
s = a + b
m = 1
n = int(input('Enser no. of rows'))
d = n - 1
for i in range(0, n):
for j in range(0, d):
print(" ", end = ' ')
for k in range(0, m):
print(a, " ", end = ' ')
s = a + b
a = b
b = s
print()
d -= 1
m += 1 | a = 1
b = 2
s = a + b
m = 1
n = int(input('Enser no. of rows'))
d = n - 1
for i in range(0, n):
for j in range(0, d):
print(' ', end=' ')
for k in range(0, m):
print(a, ' ', end=' ')
s = a + b
a = b
b = s
print()
d -= 1
m += 1 |
def not_string (n):
for i in range (1,n):
print(i,end='')
return n
n = int(input())
print(not_string(n)) | def not_string(n):
for i in range(1, n):
print(i, end='')
return n
n = int(input())
print(not_string(n)) |
def hi():
print ('Hello world!')
print(hi())
| def hi():
print('Hello world!')
print(hi()) |
# Flipping bits
# You will be given a list of 32-bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset).
def flipping(a):
ans = ~a & 0xffffffff
return ans
n = int(raw... | def flipping(a):
ans = ~a & 4294967295
return ans
n = int(raw_input())
for i in range(n):
a = int(raw_input())
ans = flipping(a)
print(ans) |
TITLE = "PyKi"
PRIVATE = True
FILE_SIZE_MAX_MB = 16
SECRET_KEY= "a unique and long key"
CONTENT_DIR = "C:\\Users\\ongew\\Desktop\\Transfer\\CSC 440\\Projects\\PyKi\\content"
UPLOAD_DIR = "C:\\Users\\ongew\\Desktop\\Transfer\\CSC 440\\Projects\\PyKi\\wiki\\web\\static\\upload"
CONNECTION_STRING = "DRIVER={SQLite3 ODBC D... | title = 'PyKi'
private = True
file_size_max_mb = 16
secret_key = 'a unique and long key'
content_dir = 'C:\\Users\\ongew\\Desktop\\Transfer\\CSC 440\\Projects\\PyKi\\content'
upload_dir = 'C:\\Users\\ongew\\Desktop\\Transfer\\CSC 440\\Projects\\PyKi\\wiki\\web\\static\\upload'
connection_string = 'DRIVER={SQLite3 ODBC ... |
LogLevels = {
"Fatal": 0,
"Error": 1,
"Warning": 2,
"Notice": 3,
"Info": 4,
"Debug": 5,
"Trace": 6
}
class Logger:
def __init__(self, log_level):
self.log_level = log_level
def log(self, level, message):
if int(self.log_level) >= int(level):
print(messa... | log_levels = {'Fatal': 0, 'Error': 1, 'Warning': 2, 'Notice': 3, 'Info': 4, 'Debug': 5, 'Trace': 6}
class Logger:
def __init__(self, log_level):
self.log_level = log_level
def log(self, level, message):
if int(self.log_level) >= int(level):
print(message)
def log_info(self, m... |
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
answer = []
res = []
[res.append(i) for i in nums1 if i not in res and i not in nums2]
answer.append(res[:])
res = []
[res.append(i) for i in nums2 if i not in res and i n... | class Solution:
def find_difference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
answer = []
res = []
[res.append(i) for i in nums1 if i not in res and i not in nums2]
answer.append(res[:])
res = []
[res.append(i) for i in nums2 if i not in res and i... |
def insertionSort(array):
# loop through unsorted elements, considering first element sorted
for i in range(1, len(array)):
# select first unsorted element
elementToSort = array[i]
# initialize position as the previous position
position = i - 1
# loop through last sorted... | def insertion_sort(array):
for i in range(1, len(array)):
element_to_sort = array[i]
position = i - 1
for j in range(i - 1, -1, -1):
if array[j] > elementToSort:
array[j + 1] = array[j]
position = j
else:
position = j + ... |
class LoadData():
"""
Loads data from a trace input file into an array of shape (N, 2), where N represents the Total Memory Requests and 2 represents cache input.
"""
def __init__(self, filename):
#assuming N x 2.
self.filename = filename
self.memory = []
def to_bin(self, add... | class Loaddata:
"""
Loads data from a trace input file into an array of shape (N, 2), where N represents the Total Memory Requests and 2 represents cache input.
"""
def __init__(self, filename):
self.filename = filename
self.memory = []
def to_bin(self, address):
""" Conver... |
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minim... | """
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minim... |
def aliquot_sum(n: int) -> int:
return sum([factor for factor in range(1, n//2+1) if n % factor == 0])
def classify(number: int) -> str:
""" A perfect number equals the sum of its positive divisors.
:param number: int a positive integer
:return: str the classification of the input integer
"""
... | def aliquot_sum(n: int) -> int:
return sum([factor for factor in range(1, n // 2 + 1) if n % factor == 0])
def classify(number: int) -> str:
""" A perfect number equals the sum of its positive divisors.
:param number: int a positive integer
:return: str the classification of the input integer
"""
... |
@app.route("/transaction", methods=['GET','POST'])
def transactions():
Create_Transaction_Form = CreateTransactionForm(request.form)
user_id = session['user_id']
if request.method == 'POST':
first_name = Create_Transaction_Form.first_name.data
last_name = Create_Transaction_Form.last_name.da... | @app.route('/transaction', methods=['GET', 'POST'])
def transactions():
create__transaction__form = create_transaction_form(request.form)
user_id = session['user_id']
if request.method == 'POST':
first_name = Create_Transaction_Form.first_name.data
last_name = Create_Transaction_Form.last_na... |
#
# PySNMP MIB module Nortel-Magellan-Passport-ModAtmQosMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-ModAtmQosMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:18:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
#... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
'''
In place quickSort The quickSort Method
Time Complexity : Best,Avg - O(NlogN) , Worst - O(N^2)
Space Complexity : O(N)
Auxilary Space : O(logN) for the stack frames
'''
def quickSort(a,start,end):
if(start >= end): return a
else:
pivot = a[end]
swapIndex = start
for i in... | """
In place quickSort The quickSort Method
Time Complexity : Best,Avg - O(NlogN) , Worst - O(N^2)
Space Complexity : O(N)
Auxilary Space : O(logN) for the stack frames
"""
def quick_sort(a, start, end):
if start >= end:
return a
else:
pivot = a[end]
swap_index = start
fo... |
def f(lst):
lst.reverse()
lst.append(42)
return lst
L = [1, 2, 3]
counter = 2
while counter > 0:
len(f(f((f(L))))) # breakpoint
counter -= 1
| def f(lst):
lst.reverse()
lst.append(42)
return lst
l = [1, 2, 3]
counter = 2
while counter > 0:
len(f(f(f(L))))
counter -= 1 |
def createCalendar(month):
ac = ''
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for i in days:
ac = ac + i + ' '
print(f'\n {month}\n')
print(ac)
createCalendar('March') | def create_calendar(month):
ac = ''
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for i in days:
ac = ac + i + ' '
print(f'\n {month}\n')
print(ac)
create_calendar('March') |
"""
Given a nested list of lexemes that have been parsed from a boolean expression, factor everything
out into a list-of-lists of conjunctions (AND combinations).
For example, given an expression like "(a or b and c) and (e or f)"
It is first parsed into [['a', 'or', 'b', 'and', 'c'], 'and', ['e', 'or', 'f']]
Then it ... | """
Given a nested list of lexemes that have been parsed from a boolean expression, factor everything
out into a list-of-lists of conjunctions (AND combinations).
For example, given an expression like "(a or b and c) and (e or f)"
It is first parsed into [['a', 'or', 'b', 'and', 'c'], 'and', ['e', 'or', 'f']]
Then it ... |
def load_loss_function(loss_class, *args, **kwargs):
loss_function = loss_class(*args, **kwargs)
return loss_function
| def load_loss_function(loss_class, *args, **kwargs):
loss_function = loss_class(*args, **kwargs)
return loss_function |
#!/usr/bin/env python2.7
#-*- coding: utf-8 -*-
QTUM_PREFIX = "/home/danx/std_workspace/qtum-package/"
QTUM_BIN = QTUM_PREFIX + "bin/"
CMD_QTUMD = QTUM_BIN + "qtumd"
CMD_QTUMCLI = QTUM_BIN + "qtum-cli"
########################################
QTUM_NODES = {
'node1': {
'NODEX__QTUM_DATAD... | qtum_prefix = '/home/danx/std_workspace/qtum-package/'
qtum_bin = QTUM_PREFIX + 'bin/'
cmd_qtumd = QTUM_BIN + 'qtumd'
cmd_qtumcli = QTUM_BIN + 'qtum-cli'
qtum_nodes = {'node1': {'NODEX__QTUM_DATADIR': '/home/danx/std_workspace/qtum-data/node1/', 'NODEX__PORT': 13888, 'NODEX__RCPPORT': 13889, 'NODEX__QTUM_RPC': 'http://... |
# Write a function called get_info that receives a name, an age, and a town and returns a string in the format:
# "This is {name} from {town} and he is {age} years old". Use dictionary unpacking when testing your function. Submit only the function in the judge system.
def get_info(**kwargs):
return f"This is {kw... | def get_info(**kwargs):
return f"This is {kwargs.get('name')} from {kwargs.get('town')} and he is {kwargs.get('age')} years old" |
#encoding:utf-8
subreddit = 'learntodraw'
t_channel = '@Learntodrawx'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'learntodraw'
t_channel = '@Learntodrawx'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
s = ""
for i in range(1, 1000):
s += str(i)
x = int(input())
print(s[x-1]) | s = ''
for i in range(1, 1000):
s += str(i)
x = int(input())
print(s[x - 1]) |
"""
DatabaseSetingsModule
----------------------
This is a Module which has Class for Database and database Settings
"""
class Database(object):
"""Database Class which is responsile for connecting to databse """
def __init__(self, connection_string):
"""
This is connection string o connect... | """
DatabaseSetingsModule
----------------------
This is a Module which has Class for Database and database Settings
"""
class Database(object):
"""Database Class which is responsile for connecting to databse """
def __init__(self, connection_string):
"""
This is connection string o connect t... |
# Copyright 2016 Recorded Future, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | """Data models to manipulate responses from the API."""
class Dotaccessdict(dict):
"""Creates a dict/object hybrid.
Instances of DotAccessDict behaves like dicts and objects
at the same time. Ex d['example'] = 1 and d.example = 1 are
equivalent.
Ex:
# example = DotAccessDict()
# example.k... |
def splitter(string):
split = string.split(' ')
return split
print(splitter('this is a very messy string')) | def splitter(string):
split = string.split(' ')
return split
print(splitter('this is a very messy string')) |
S = [int(x) for x in input()]
N = len(S)
if S[0] == 0 or S[-1] == 1 or any(S[i] != S[-i - 2] for i in range(N - 1)):
print(-1)
quit()
edge = [(1, 2)]
root, now = 2, 3
for i in range(1, N // 2 + 1):
edge.append((root, now))
if S[i] == 1:
root = now
now += 1
while now <= N:
edge.append((r... | s = [int(x) for x in input()]
n = len(S)
if S[0] == 0 or S[-1] == 1 or any((S[i] != S[-i - 2] for i in range(N - 1))):
print(-1)
quit()
edge = [(1, 2)]
(root, now) = (2, 3)
for i in range(1, N // 2 + 1):
edge.append((root, now))
if S[i] == 1:
root = now
now += 1
while now <= N:
edge.appe... |
MANO_CONF_ROOT_DIR = './'
# Attetion: pretrained detnet and iknet are only trained for left model! use left hand
DETECTION_MODEL_PATH = MANO_CONF_ROOT_DIR+'model/detnet/detnet.ckpt'
IK_MODEL_PATH = MANO_CONF_ROOT_DIR+'model/iknet/iknet.ckpt'
# Convert 'HAND_MESH_MODEL_PATH' to 'HAND_MESH_MODEL_PATH_JSON' with 'prepar... | mano_conf_root_dir = './'
detection_model_path = MANO_CONF_ROOT_DIR + 'model/detnet/detnet.ckpt'
ik_model_path = MANO_CONF_ROOT_DIR + 'model/iknet/iknet.ckpt'
hand_mesh_model_left_path_json = MANO_CONF_ROOT_DIR + 'model/hand_mesh/mano_hand_mesh_left.json'
hand_mesh_model_right_path_json = MANO_CONF_ROOT_DIR + 'model/ha... |
# PyAlgoTrade
#
# Copyright 2012 Gabriel Martin Becedillas Ruiz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | """
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <gabriel.becedillas@gmail.com>
"""
def get_change_percentage(actual, prev):
if actual is None or prev is None or prev == 0:
raise exception('Invalid values')
diff = actual - prev
ret = diff / float(abs(prev))
return ret
def lt(v1, v2):
i... |
# MEDIUM
# sliding window size: [Start,i]
# increment start if window size - most frequent char > k
# time O(N) Space O(1)
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
count = [0]* 26
result,gmax,start = 0,0,0
for i in range(len(s)):
count[ord(s... | class Solution:
def character_replacement(self, s: str, k: int) -> int:
count = [0] * 26
(result, gmax, start) = (0, 0, 0)
for i in range(len(s)):
count[ord(s[i]) - ord('A')] += 1
gmax = max(gmax, count[ord(s[i]) - ord('A')])
while i - start + 1 - gmax > ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.