content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
__all__ = (
'readonly_admin',
'singleton'
)
| __all__ = ('readonly_admin', 'singleton') |
integer = [
['lld', 'long long', 9223372036854775807, -9223372036854775808],
['ld', 'long', 9223372036854775807, -9223372036854775808],
['lu', 'unsigned long', 18446744073709551615, 0],
['d', 'signed', 2147483647, -2147483648],
['u', 'unsigned', 4294967295, 0],
['hd', 'short', 32767, -32768],
... | integer = [['lld', 'long long', 9223372036854775807, -9223372036854775808], ['ld', 'long', 9223372036854775807, -9223372036854775808], ['lu', 'unsigned long', 18446744073709551615, 0], ['d', 'signed', 2147483647, -2147483648], ['u', 'unsigned', 4294967295, 0], ['hd', 'short', 32767, -32768], ['hu', 'unsigned short', 65... |
#!/usr/bin/env python
#
# Create filter taps to use for interpolation filter in
# clock recovery algorithm. These taps are copied from
# GNU Radio at gnuradio/filter/interpolator_taps.h.
#
# This file includes them in natural order and I want
# them stored in reversed order such that they can be
# used directly.
#
fil... | filters = [[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [-0.0001547, 0.000853777, -0.00276968, 0.00789295, 0.998534, -0.00541054, 0.00124642, -0.000198993], [-0.000309412, 0.00170888, -0.00555134, 0.015884, 0.996891, -0.0107209, 0.00247942, -0.000396391], [-0.000464053, 0.00256486, -0.00834364, 0.0239714, 0.995074, -0.015... |
class Node:
def __init__(self, val: int):
self.val = val
self.prev = None
self.next = None
class DoublyLinkedList:
def takeinput(self) -> Node:
inputlist = [int(x) for x in input().split()]
head = None
temp = None
for curr in inputlist:
if c... | class Node:
def __init__(self, val: int):
self.val = val
self.prev = None
self.next = None
class Doublylinkedlist:
def takeinput(self) -> Node:
inputlist = [int(x) for x in input().split()]
head = None
temp = None
for curr in inputlist:
if c... |
class Combo():
def combine(self,n, k):
A = list(range(1,n + 1))
res = self.comb(A, k)
return res
def comb(self, A, n):
if n == 0:
return [[]]
l = []
for i in range(0, len(A)):
m = A[i]
remLst = A[i + 1:]
for p in se... | class Combo:
def combine(self, n, k):
a = list(range(1, n + 1))
res = self.comb(A, k)
return res
def comb(self, A, n):
if n == 0:
return [[]]
l = []
for i in range(0, len(A)):
m = A[i]
rem_lst = A[i + 1:]
for p in ... |
f = open('./day4.py')
for chunk in iter(lambda :f.read(10),''):
print(chunk)
| f = open('./day4.py')
for chunk in iter(lambda : f.read(10), ''):
print(chunk) |
class WebsiteBaseError(Exception):
pass
class TreeTraversal(WebsiteBaseError):
def __init__(self, tree, request, segment, req=None):
super().__init__()
self.tree, self.request, self.segment, self.req = tree, request, segment, req
def __str__(self) -> str:
return f"{self.tree} > {s... | class Websitebaseerror(Exception):
pass
class Treetraversal(WebsiteBaseError):
def __init__(self, tree, request, segment, req=None):
super().__init__()
(self.tree, self.request, self.segment, self.req) = (tree, request, segment, req)
def __str__(self) -> str:
return f"{self.tree} ... |
linelist = [line for line in open('Day 02.input').readlines()]
hor = 0
dep = 0
for line in linelist:
mov, amount = line.split(' ')
if mov == 'forward':
hor += int(amount)
else:
dep += int(amount) * (-1 if mov == 'up' else 1)
print(hor * dep)
| linelist = [line for line in open('Day 02.input').readlines()]
hor = 0
dep = 0
for line in linelist:
(mov, amount) = line.split(' ')
if mov == 'forward':
hor += int(amount)
else:
dep += int(amount) * (-1 if mov == 'up' else 1)
print(hor * dep) |
def convert_sample_to_shot_wow(sample, with_knowledge=True):
prefix = "Dialogue:\n"
assert len(sample["dialogue"]) == len(sample["meta"])
for turn, meta in zip(sample["dialogue"],sample["meta"]):
prefix += f"User: {turn[0]}" +"\n"
if with_knowledge:
if len(meta)>0:
... | def convert_sample_to_shot_wow(sample, with_knowledge=True):
prefix = 'Dialogue:\n'
assert len(sample['dialogue']) == len(sample['meta'])
for (turn, meta) in zip(sample['dialogue'], sample['meta']):
prefix += f'User: {turn[0]}' + '\n'
if with_knowledge:
if len(meta) > 0:
... |
# Test cases that are expected to fail, e.g. unimplemented features or bug-fixes.
# Remove from list when fixed.
xfail = {
"namespace_keywords", # 70
"googletypes_struct", # 9
"googletypes_value", # 9
"import_capitalized_package",
"example", # This is the example in the readme. Not a test.
}
se... | xfail = {'namespace_keywords', 'googletypes_struct', 'googletypes_value', 'import_capitalized_package', 'example'}
services = {'googletypes_response', 'googletypes_response_embedded', 'service', 'service_separate_packages', 'import_service_input_message', 'googletypes_service_returns_empty', 'googletypes_service_return... |
class Settings:
BOT_KEY = ""
HOST_NAME = "127.0.0.1"
USER_NAME = "root"
USER_PASS = "Andrey171200"
SQL_NAME = "moneysaver"
| class Settings:
bot_key = ''
host_name = '127.0.0.1'
user_name = 'root'
user_pass = 'Andrey171200'
sql_name = 'moneysaver' |
{
"targets": [
{
"target_name": "binding",
"sources": [
"native\\winhttpBindings.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"libraries": [
"WinHTTP.lib",
"-DelayLoad:node.exe"
],
"msbuild_settings": {
"ClCompile"... | {'targets': [{'target_name': 'binding', 'sources': ['native\\winhttpBindings.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'libraries': ['WinHTTP.lib', '-DelayLoad:node.exe'], 'msbuild_settings': {'ClCompile': {'RuntimeLibrary': 'MultiThreaded'}}}]} |
def open_file():
while True:
file_name = input("Enter input file: ")
try:
measles = open(file_name, "r")
break
except:
print("File unable to open. Invalid name or file doesn't exist!")
continue # name it re-prompts for a write name
return ... | def open_file():
while True:
file_name = input('Enter input file: ')
try:
measles = open(file_name, 'r')
break
except:
print("File unable to open. Invalid name or file doesn't exist!")
continue
return measles
def process_file(measles):
... |
def get_obj1():
obj = \
{
"sha": "d25341478381063d1c76e81b3a52e0592a7c997f",
"commit": {
"author": {
"name": "Stephen Dolan",
"email": "mu@netsoc.tcd.ie",
"date": "2013-06-22T16:30:59Z"
},
"committer": {
"name": "Stephen Dolan",
... | def get_obj1():
obj = {'sha': 'd25341478381063d1c76e81b3a52e0592a7c997f', 'commit': {'author': {'name': 'Stephen Dolan', 'email': 'mu@netsoc.tcd.ie', 'date': '2013-06-22T16:30:59Z'}, 'committer': {'name': 'Stephen Dolan', 'email': 'mu@netsoc.tcd.ie', 'date': '2013-06-22T16:30:59Z'}, 'message': 'Merge pull request #... |
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache = 'localhost',
instrument = 'ErWIN',
experiment = 'Exp',
datasinks = ['conssink', 'dmnsink'],
notifiers = [],
)
modules = ['nicos.commands.standard']
devices = dict(
ErWIN = device('nicos.devices.instrument.Instrument',
... | description = 'system setup'
group = 'lowlevel'
sysconfig = dict(cache='localhost', instrument='ErWIN', experiment='Exp', datasinks=['conssink', 'dmnsink'], notifiers=[])
modules = ['nicos.commands.standard']
devices = dict(ErWIN=device('nicos.devices.instrument.Instrument', description='ErWIN instrument', instrument='... |
num1 = input()
num2 = input()
num3 = input()
print(int(num1) + int(num2) + int(num3))
| num1 = input()
num2 = input()
num3 = input()
print(int(num1) + int(num2) + int(num3)) |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
linked_list = ''
while temp:
linked_list += str(temp.data) + " -> "
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
linked_list = ''
while temp:
linked_list += str(temp.data) + ' -> '
... |
def bubblesort(L):
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L)-1):
if L[i]>L[i+1]:
L[i], L[i+1] = L[i+1], L[i]
keepgoing = True
| def bubblesort(L):
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L) - 1):
if L[i] > L[i + 1]:
(L[i], L[i + 1]) = (L[i + 1], L[i])
keepgoing = True |
# Hydro settings
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en-us'
APPLICATION_NAME = 'HYDRO'
SECRET_KEY = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&022shmi1jcgihb*'
# SESSION_TIMEOUT is used in validate_session_active decorator to see if the
# session is active.
SECOND = 1
MINUTE = SECOND * 60
SECONDS_IN_DAY = SECOND*86400
... | time_zone = 'UTC'
language_code = 'en-us'
application_name = 'HYDRO'
secret_key = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&022shmi1jcgihb*'
second = 1
minute = SECOND * 60
seconds_in_day = SECOND * 86400
mysql_cache_db = 'cache'
mysql_stats_db = 'stats'
mysql_cache_table = 'hydro_cache_table'
cache_in_memory_key_expire ... |
def load_external_repo():
native.local_repository(
name = "ext_repo",
path = "test/external_repo/repo",
)
| def load_external_repo():
native.local_repository(name='ext_repo', path='test/external_repo/repo') |
'''
Created on May 26, 2012
@author: Charlie
'''
class MainModule01(object):
def __init__(self):
pass | """
Created on May 26, 2012
@author: Charlie
"""
class Mainmodule01(object):
def __init__(self):
pass |
#
# PySNMP MIB module GENERIC-3COM-VLAN-MIB-1-0-7 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENERIC-3COM-VLAN-MIB-1-0-7
# Produced by pysmi-0.3.4 at Wed May 1 11:09:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) ... |
# PROBLEM
#
# Assume s is a string of lower case characters.
#
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your
# program should print:
#
# 'Longest substring in alphabetical order is: beggh'
#
# In case of ti... | s = 'azcbobobegghakl'
if len(s) > 1:
substring = s[0]
length = 1
bestsubstring = substring
bestlength = length
for num in range(len(s) - 1):
if s[num] <= s[num + 1]:
substring = substring + s[num + 1]
length += 1
if length > bestlength:
bes... |
mandatory = \
{
'article' : ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'],
'book' : ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'],
'booklet' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'conference' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'],
'inbook' : ['... | mandatory = {'article': ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'], 'book': ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'], 'booklet': ['ENTRYTYPE', 'ID', 'title', 'year'], 'conference': ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'], 'inbook': ['ENTRYTYPE', 'ID', '... |
class ParkingLot:
def __init__(self, username, latitude, longitude, totalSpace, costHour):
self.username = username
self.latitude = latitude
self.longitude = longitude
self.totalSpace = totalSpace
self.availableSpace = totalSpace
self.costHour = costHour
def getS... | class Parkinglot:
def __init__(self, username, latitude, longitude, totalSpace, costHour):
self.username = username
self.latitude = latitude
self.longitude = longitude
self.totalSpace = totalSpace
self.availableSpace = totalSpace
self.costHour = costHour
def get... |
lst1=list()
lst1.append('K')
lst1.append('A')
lst2=['U', 'S', 'H', 'I', 'K']
print(lst1+lst2)
print(lst2[0] +lst2[1]+lst1[1])
for i in lst1+lst2:
print(i)
| lst1 = list()
lst1.append('K')
lst1.append('A')
lst2 = ['U', 'S', 'H', 'I', 'K']
print(lst1 + lst2)
print(lst2[0] + lst2[1] + lst1[1])
for i in lst1 + lst2:
print(i) |
class Photo(object):
def __init__(self, photo_id: int, orientation: str, number_of_tags: int, tags: set):
self.id = photo_id
self.orientation = orientation
self.number_of_tags = number_of_tags
self.tags = tags
self.is_vertical = orientation == 'V'
self.is_horizontal =... | class Photo(object):
def __init__(self, photo_id: int, orientation: str, number_of_tags: int, tags: set):
self.id = photo_id
self.orientation = orientation
self.number_of_tags = number_of_tags
self.tags = tags
self.is_vertical = orientation == 'V'
self.is_horizontal ... |
# addition will takes place after multiplication and addition
num1 = 1 + 4 * 3 / 2;
# same as 5 * 3 /2
num2 = (1 + 4) * 3 / 2;
# same as 1+12/2
num3 = 1 + (4 * 3) / 2;
print("python follow precedence rules");
# this should produce 7.5
print(num1);
print(num2);
print(num3); | num1 = 1 + 4 * 3 / 2
num2 = (1 + 4) * 3 / 2
num3 = 1 + 4 * 3 / 2
print('python follow precedence rules')
print(num1)
print(num2)
print(num3) |
class Fruit:
def __init__(self,name,parents):
self.name = name
self.parents = parents
self.children = []
self.family = []
self.siblings = []
self.node = None ## Link to node object in graph
def find_children(self,basket): # basket is a list of Fruit objects
for fruit in basket:
if ... | class Fruit:
def __init__(self, name, parents):
self.name = name
self.parents = parents
self.children = []
self.family = []
self.siblings = []
self.node = None
def find_children(self, basket):
for fruit in basket:
if fruit.name is not self.na... |
file = open("text.txt", "r")
file2 = open("text2.txt", "w")
for data in file:
file2.write(data)
file.close()
file2.close()
| file = open('text.txt', 'r')
file2 = open('text2.txt', 'w')
for data in file:
file2.write(data)
file.close()
file2.close() |
animals = ['cat', 'dog', 'pig']
for animal in animals :
print (animal + 'would make a great pet.')
print ('All of those animals would makea great pet')
| animals = ['cat', 'dog', 'pig']
for animal in animals:
print(animal + 'would make a great pet.')
print('All of those animals would makea great pet') |
genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
num_files = 100
with open(f'INPUT_FULL', 'w') as f:
for genre in genres:
for i in range(num_files):
for j in range(6):
f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav /... | genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
num_files = 100
with open(f'INPUT_FULL', 'w') as f:
for genre in genres:
for i in range(num_files):
for j in range(6):
f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav\t... |
# Copyright 2020 University of Adelaide
#
# 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 ... | def check_inst(inst, mask, match):
return inst & mask == match
def cycles_push(inst):
if check_inst(inst, 65024, 46080):
return 1 + bin(inst & 255).count('1')
return -1
def cycles_pop(inst):
if check_inst(inst, 65024, 48128):
return 1 + bin(inst & 255).count('1')
return -1
def cyc... |
d = {'key1': 1, 'key2': 2, 'key3': 3}
for k in d:
print(k)
# key1
# key2
# key3
for k in d.keys():
print(k)
# key1
# key2
# key3
keys = d.keys()
print(keys)
print(type(keys))
# dict_keys(['key1', 'key2', 'key3'])
# <class 'dict_keys'>
k_list = list(d.keys())
print(k_list)
print(type(k_list))
# ['key1', 'key... | d = {'key1': 1, 'key2': 2, 'key3': 3}
for k in d:
print(k)
for k in d.keys():
print(k)
keys = d.keys()
print(keys)
print(type(keys))
k_list = list(d.keys())
print(k_list)
print(type(k_list))
for v in d.values():
print(v)
values = d.values()
print(values)
print(type(values))
v_list = list(d.values())
print(v... |
# Testing out some stuff with async and await
async def hello(name):
print ("hello" + name)
return "hello" + name
# We can use the await statement in coroutines to call
# coroutines as normal functions; i.e. what it implies is that
# if we runt return await func(*args) in a courtoune
# is like running r... | async def hello(name):
print('hello' + name)
return 'hello' + name
async def await_hello(func, *args):
return await func(*args)
def run(coro, *args):
try:
g = coro(*args)
g.send(None)
except StopIteration as e:
return e.value
print(run(await_hello, hello, 'wut')) |
number = int(input())
raiz = number/2
for i in range(1,20):
raiz = ((raiz ** 2) + number) / (2 * raiz)
print(raiz) | number = int(input())
raiz = number / 2
for i in range(1, 20):
raiz = (raiz ** 2 + number) / (2 * raiz)
print(raiz) |
class Item:
def __init__(self,weight,value) -> None:
self.weight=weight
self.value=value
self.ratio=value/weight
def knapsackMethod(items,capacity):
items.sort(key=lambda x: x.ratio,reverse=True)
usedCapacity=0
totalValue=0
for i in items:
if usedCapacity+i.weight<=c... | class Item:
def __init__(self, weight, value) -> None:
self.weight = weight
self.value = value
self.ratio = value / weight
def knapsack_method(items, capacity):
items.sort(key=lambda x: x.ratio, reverse=True)
used_capacity = 0
total_value = 0
for i in items:
if used... |
#LeetCode problem 54: Spiral Matrix
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if(len(matrix)==0 or len(matrix[0])==0):
return []
res=[]
rb=0
re=len(matrix)
cb=0
ce=len(matrix[0])
while(re>rb and ce>cb):
... | class Solution:
def spiral_order(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
res = []
rb = 0
re = len(matrix)
cb = 0
ce = len(matrix[0])
while re > rb and ce > cb:
for j in range(c... |
def isPower(n):
'''
Determine if the given number is a power of some non-negative integer.
'''
if n == 1:
return True
sqrt = math.sqrt(n)
for a in range(int(sqrt)+1):
for b in range(2, int(sqrt)+1):
if a ** b == n:
return True
return False | def is_power(n):
"""
Determine if the given number is a power of some non-negative integer.
"""
if n == 1:
return True
sqrt = math.sqrt(n)
for a in range(int(sqrt) + 1):
for b in range(2, int(sqrt) + 1):
if a ** b == n:
return True
return False |
# Add your own choices here!
fruit = ["apples", "oranges", "pears", "grapes", "blueberries"]
lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"]
situations = {"fruit":fruit, "lunch":lunch}
| fruit = ['apples', 'oranges', 'pears', 'grapes', 'blueberries']
lunch = ['pho', 'timmies', 'thai', 'burgers', 'buffet!', 'indian', 'montanas']
situations = {'fruit': fruit, 'lunch': lunch} |
__author__ = 'Brian Nguyen'
def greeting(msg):
print("We would like to say: " + msg) | __author__ = 'Brian Nguyen'
def greeting(msg):
print('We would like to say: ' + msg) |
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
k = 1
max_len, i = 0, 0
for j in range(len(nums)):
if nums[j] == 0:
k -= 1
if k < 0:
if nums[i] == 0:
k += 1
i += 1
max_... | class Solution:
def longest_subarray(self, nums: List[int]) -> int:
k = 1
(max_len, i) = (0, 0)
for j in range(len(nums)):
if nums[j] == 0:
k -= 1
if k < 0:
if nums[i] == 0:
k += 1
i += 1
... |
ROOT_WK_API_URL = "https://api.wanikani.com/v2/"
RESOURCES_WITHOUT_IDS = ["user", "collection", "report"]
SUBJECT_ENDPOINT = "subjects"
SINGLE_SUBJECT_ENPOINT = r"subjects/\d+"
ASSIGNMENT_ENDPOINT = "assignments"
REVIEW_STATS_ENDPOINT = "review_statistics"
STUDY_MATERIALS_ENDPOINT = "study_materials"
REVIEWS_ENDPOINT ... | root_wk_api_url = 'https://api.wanikani.com/v2/'
resources_without_ids = ['user', 'collection', 'report']
subject_endpoint = 'subjects'
single_subject_enpoint = 'subjects/\\d+'
assignment_endpoint = 'assignments'
review_stats_endpoint = 'review_statistics'
study_materials_endpoint = 'study_materials'
reviews_endpoint =... |
MAX_N = 10000 + 1
isprime = [True] * (MAX_N)
isprime[0] = False
isprime[1] = False
for i in range(2, MAX_N):
if not isprime[i]:
continue
for j in range(i+i, MAX_N, i):
isprime[j] = False
T = int(input())
for _ in range(T):
n = int(input())
for i in range(n//2, 1, -1):
if isprim... | max_n = 10000 + 1
isprime = [True] * MAX_N
isprime[0] = False
isprime[1] = False
for i in range(2, MAX_N):
if not isprime[i]:
continue
for j in range(i + i, MAX_N, i):
isprime[j] = False
t = int(input())
for _ in range(T):
n = int(input())
for i in range(n // 2, 1, -1):
if isprim... |
#
# PySNMP MIB module DOCS-LOADBALANCING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-LOADBALANCING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:53:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, constraints_union, single_value_constraint) ... |
class Solution:
def minCut(self, s: str) -> int:
dp=self.isPal(s)
return self.bfs(s,dp)
def isPal(self,s):
dp=[[False for i in s] for i in s]
for i in range(len(s)):
dp[i][i]=True
if i+1<len(s):
dp[i][i+1]=True if s[i]==s[i+1] else False
... | class Solution:
def min_cut(self, s: str) -> int:
dp = self.isPal(s)
return self.bfs(s, dp)
def is_pal(self, s):
dp = [[False for i in s] for i in s]
for i in range(len(s)):
dp[i][i] = True
if i + 1 < len(s):
dp[i][i + 1] = True if s[i] =... |
def main(j, args, params, tags, tasklet):
params.merge(args)
doc = params.doc
tags = params.tags
out = ""
cmdstr = params.macrostr.split(":", 1)[1].replace("}}", "").strip()
md5 = j.base.byteprocessor.hashMd5(cmdstr)
j.system.fs.createDir(j.system.fs.joinPaths(j.core.portal.active.filesro... | def main(j, args, params, tags, tasklet):
params.merge(args)
doc = params.doc
tags = params.tags
out = ''
cmdstr = params.macrostr.split(':', 1)[1].replace('}}', '').strip()
md5 = j.base.byteprocessor.hashMd5(cmdstr)
j.system.fs.createDir(j.system.fs.joinPaths(j.core.portal.active.filesroot,... |
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
for i in range(0, len(haystack) - len(needle) + 1):
print(haystack[i : i + len(needle)], needle)
if haystack[i : i + len(needle)] == needle:
return i
... | class Solution:
def str_str(self, haystack: str, needle: str) -> int:
if needle == '':
return 0
for i in range(0, len(haystack) - len(needle) + 1):
print(haystack[i:i + len(needle)], needle)
if haystack[i:i + len(needle)] == needle:
return i
... |
n = int(input())
m = int(input())
r = m
for i in range(n):
a, b = map(int, input().split())
m += a
m -= b
if m < 0:
print(0)
exit()
r = max(r, m)
print(r)
| n = int(input())
m = int(input())
r = m
for i in range(n):
(a, b) = map(int, input().split())
m += a
m -= b
if m < 0:
print(0)
exit()
r = max(r, m)
print(r) |
name = " alberT"
one = name.rsplit()
print("one:", one)
two = name.index('al', 0)
print("two:", two)
three = name.index('T', -1)
print("three:", three)
four = name.replace('l', 'p')
print("four:", four)
five = name.split('l')
print("five:", five)
six = name.upper()
print("six:", six)
seven = name.lower()
print("... | name = ' alberT'
one = name.rsplit()
print('one:', one)
two = name.index('al', 0)
print('two:', two)
three = name.index('T', -1)
print('three:', three)
four = name.replace('l', 'p')
print('four:', four)
five = name.split('l')
print('five:', five)
six = name.upper()
print('six:', six)
seven = name.lower()
print('seven:'... |
n = int(input())
s = [[0] * 10 for _ in range(n + 1)]
s[1] = [0] + [1] * 9
mod = 1000 ** 3
for i in range(2, n + 1):
for j in range(0, 9 + 1):
if j >= 1:
s[i][j] += s[i - 1][j - 1]
if j <= 8:
s[i][j] += s[i - 1][j + 1]
print(sum(s[n]) % mod) | n = int(input())
s = [[0] * 10 for _ in range(n + 1)]
s[1] = [0] + [1] * 9
mod = 1000 ** 3
for i in range(2, n + 1):
for j in range(0, 9 + 1):
if j >= 1:
s[i][j] += s[i - 1][j - 1]
if j <= 8:
s[i][j] += s[i - 1][j + 1]
print(sum(s[n]) % mod) |
__title__ = "FisherExactTest"
__version__ = "1.0.1"
__author__ = "Ae-Mc"
__author_email__ = "ae_mc@mail.ru"
__description__ = "Two tailed Fisher's exact test wrote in pure Python"
__url__ = "https://github.com/Ae-Mc/Fisher"
__classifiers__ = [
"Programming Language :: Python :: 3 :: Only",
"Programming Language... | __title__ = 'FisherExactTest'
__version__ = '1.0.1'
__author__ = 'Ae-Mc'
__author_email__ = 'ae_mc@mail.ru'
__description__ = "Two tailed Fisher's exact test wrote in pure Python"
__url__ = 'https://github.com/Ae-Mc/Fisher'
__classifiers__ = ['Programming Language :: Python :: 3 :: Only', 'Programming Language :: Pytho... |
# -*- coding: utf-8 -*-
class Solution:
def sortSentence(self, s: str) -> str:
tokens = s.split()
result = [None] * len(tokens)
for token in tokens:
word, index = token[:-1], int(token[-1])
result[index - 1] = word
return ' '.join(result)
if __name__ == '... | class Solution:
def sort_sentence(self, s: str) -> str:
tokens = s.split()
result = [None] * len(tokens)
for token in tokens:
(word, index) = (token[:-1], int(token[-1]))
result[index - 1] = word
return ' '.join(result)
if __name__ == '__main__':
solution... |
def _compile(words):
if not len(words):
return None, ''
num = None
if words[0].isdigit():
num = int(words[0])
words = words[1:]
return num, ' '.join(words)
def _split_out_colons(terms):
newterms = []
for term in terms:
if ':' in term:
subterms = term... | def _compile(words):
if not len(words):
return (None, '')
num = None
if words[0].isdigit():
num = int(words[0])
words = words[1:]
return (num, ' '.join(words))
def _split_out_colons(terms):
newterms = []
for term in terms:
if ':' in term:
subterms = t... |
class BankAccount:
def __init__(self, checking = None, savings = None):
self._checking = checking
self._savings = savings
def get_checking(self):
return self._checking
def set_checking(self, new_checking):
self._checking = new_checking
def get_savings(self):
return self._savings
def s... | class Bankaccount:
def __init__(self, checking=None, savings=None):
self._checking = checking
self._savings = savings
def get_checking(self):
return self._checking
def set_checking(self, new_checking):
self._checking = new_checking
def get_savings(self):
retur... |
# abba
# foo bar bar foo
text1 = list(input())
text2 = input().split()
# text1 = set(text1)
print(text1)
print(text2)
for i in range(len(text1)):
if text1[i] == "a":
text1[i] = 1
else:
text1[i] = 0
for i in range(len(text2)):
if text2[i] == "foo":
text2[i] = 1
else:
te... | text1 = list(input())
text2 = input().split()
print(text1)
print(text2)
for i in range(len(text1)):
if text1[i] == 'a':
text1[i] = 1
else:
text1[i] = 0
for i in range(len(text2)):
if text2[i] == 'foo':
text2[i] = 1
else:
text2[i] = 0
print(text1)
print(text2)
if text1 == ... |
#!/usr/bin/env python3
'''
The MIT License (MIT)
Copyright (c) 2014 Mark Haines
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without... | """
The MIT License (MIT)
Copyright (c) 2014 Mark Haines
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
... |
class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
n = len(A)
g = local = 0
for i in range(1, n):
if A[i] < A[i-1]:
local += 1
if A[i] < i:
diff = i - A[i]
... | class Solution:
def is_ideal_permutation(self, A: List[int]) -> bool:
n = len(A)
g = local = 0
for i in range(1, n):
if A[i] < A[i - 1]:
local += 1
if A[i] < i:
diff = i - A[i]
g += diff * (diff + 1) // 2
return... |
xval = 0
xvalue1 = 1
xvalue2 = 2
print(xvalue1 + xvalue2)
| xval = 0
xvalue1 = 1
xvalue2 = 2
print(xvalue1 + xvalue2) |
class Order():
def __init__(self, exchCode, sym_, _sym, orderType, price, side, qty, stopPrice=''):
self.odid = None
self.status = None
self.tempOdid = None
self.sym_ = sym_
self._sym = _sym
self.symbol = sym_ + _sym
self.exchCode = exchCode.upper()
se... | class Order:
def __init__(self, exchCode, sym_, _sym, orderType, price, side, qty, stopPrice=''):
self.odid = None
self.status = None
self.tempOdid = None
self.sym_ = sym_
self._sym = _sym
self.symbol = sym_ + _sym
self.exchCode = exchCode.upper()
sel... |
def add_native_methods(clazz):
def initProto____():
raise NotImplementedError()
def socketCreate__boolean__(a0, a1):
raise NotImplementedError()
def socketConnect__java_net_InetAddress__int__int__(a0, a1, a2, a3):
raise NotImplementedError()
def socketBind__java_net_InetAddres... | def add_native_methods(clazz):
def init_proto____():
raise not_implemented_error()
def socket_create__boolean__(a0, a1):
raise not_implemented_error()
def socket_connect__java_net__inet_address__int__int__(a0, a1, a2, a3):
raise not_implemented_error()
def socket_bind__java_n... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/viki/catkin_ws/src/beginner_tutorials/msg/Num.msg"
services_str = "/home/viki/catkin_ws/src/beginner_tutorials/srv/ResetCount.srv;/home/viki/catkin_ws/src/beginner_tutorials/srv/AddTwoInts.srv"
pkg_name = "beginner_tutorials"
dependencies_str = ... | messages_str = '/home/viki/catkin_ws/src/beginner_tutorials/msg/Num.msg'
services_str = '/home/viki/catkin_ws/src/beginner_tutorials/srv/ResetCount.srv;/home/viki/catkin_ws/src/beginner_tutorials/srv/AddTwoInts.srv'
pkg_name = 'beginner_tutorials'
dependencies_str = 'std_msgs'
langs = 'gencpp;genlisp;genpy'
dep_include... |
x=int(input("no 1 "))
y=int(input("no 2 "))
def pow(x,y):
if y!=0:
return(x*pow(x,y-1))
else:
return 1
print(pow(x,y))
| x = int(input('no 1 '))
y = int(input('no 2 '))
def pow(x, y):
if y != 0:
return x * pow(x, y - 1)
else:
return 1
print(pow(x, y)) |
#!/usr/bin/python
hamming_threshold = [50, 60]
pattern_scale = [4.0, 6.0, 8.0, 10.0]
fp_runscript = open("/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_validation.sh", 'w')
fp_runscript.write("#!/bin/bash\n\n")
cnt = 0
for i in range(len(hamming_threshold)):
for j in range(len(pattern_scale)):
cn... | hamming_threshold = [50, 60]
pattern_scale = [4.0, 6.0, 8.0, 10.0]
fp_runscript = open('/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_validation.sh', 'w')
fp_runscript.write('#!/bin/bash\n\n')
cnt = 0
for i in range(len(hamming_threshold)):
for j in range(len(pattern_scale)):
cnt += 1
filepa... |
#!/usr/bin/env python
colors = ['white', 'black']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for size in sizes
for color in colors ]
print(tshirts)
tshirts = [(color, size) for color in colors
for size in sizes ]
print(tshirts)
| colors = ['white', 'black']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for size in sizes for color in colors]
print(tshirts)
tshirts = [(color, size) for color in colors for size in sizes]
print(tshirts) |
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
max = -9999999
max2 = -9999999
for i in arr:
if(i>max):
max2=max
max=i
elif i>max2 and max>i:
max2=i
print(max2) | if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
max = -9999999
max2 = -9999999
for i in arr:
if i > max:
max2 = max
max = i
elif i > max2 and max > i:
max2 = i
print(max2) |
class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use peek to look at the top of the stack
d... | class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
def peek(self):
return self.stack[-1] |
class KataResult:
def __init__(self, revenue, ipa, cost_of_kata, net_income, cost_of_goods, kata_penalty):
self.revenue = revenue
self.ipa = ipa
self.cost_of_kata = cost_of_kata
self.net_income = net_income
self.cost_of_goods = cost_of_goods
self.kata_penalty = kata... | class Kataresult:
def __init__(self, revenue, ipa, cost_of_kata, net_income, cost_of_goods, kata_penalty):
self.revenue = revenue
self.ipa = ipa
self.cost_of_kata = cost_of_kata
self.net_income = net_income
self.cost_of_goods = cost_of_goods
self.kata_penalty = kata_... |
su = 0
a = [3,5,6,2,7,1]
print(sum(a))
x, y = input("Enter a two value: ").split()
x = int(x)
y = int(y)
su = a[y] + sum(a[:y])
print(su) | su = 0
a = [3, 5, 6, 2, 7, 1]
print(sum(a))
(x, y) = input('Enter a two value: ').split()
x = int(x)
y = int(y)
su = a[y] + sum(a[:y])
print(su) |
def test_topic_regexp_matching(dequeuer):
msg = {'company_name': 'test_company'}
actions_1 = tuple(dequeuer.get_actions_for_topic('object__created', msg))
actions_2 = tuple(dequeuer.get_actions_for_topic('object__deleted', msg))
actions_3 = tuple(dequeuer.get_actions_for_topic('otherthing__created', msg... | def test_topic_regexp_matching(dequeuer):
msg = {'company_name': 'test_company'}
actions_1 = tuple(dequeuer.get_actions_for_topic('object__created', msg))
actions_2 = tuple(dequeuer.get_actions_for_topic('object__deleted', msg))
actions_3 = tuple(dequeuer.get_actions_for_topic('otherthing__created', msg... |
# -*- coding: utf-8 -*-
VERSION = (1, 0, 4)
__version__ = "1.0.4"
__authors__ = ["Stefan Foulis <stefan.foulis@gmail.com>", ]
| version = (1, 0, 4)
__version__ = '1.0.4'
__authors__ = ['Stefan Foulis <stefan.foulis@gmail.com>'] |
'''
This is the exceptions module:
'''
'''
Exception of when user do not have the access to certain pages.
'''
class CannotAccessPageException(Exception):
pass
'''
Exception of the first password and the second password does not match during registration.
'''
class PasswordsNotMatchingException(Exception):
p... | """
This is the exceptions module:
"""
'\nException of when user do not have the access to certain pages.\n'
class Cannotaccesspageexception(Exception):
pass
'\nException of the first password and the second password does not match during registration.\n'
class Passwordsnotmatchingexception(Exception):
pass
'... |
# Copyright 2016-2022 The FEAGI 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 applic... | def utf_detection_logic(detection_list):
highest_ranked_item = '-'
second_highest_ranked_item = '-'
for item in detection_list:
if highest_ranked_item == '-':
highest_ranked_item = item
elif detection_list[item]['rank'] > detection_list[highest_ranked_item]['rank']:
s... |
def is_triangle(func):
def wrapped(sides):
if any(i <= 0 for i in sides):
return False
sum_ = sum(sides)
if any(sides[i] > sum_ - sides[i] for i in range(3)):
return False
return func(sides)
return wrapped
@is_triangle
def is_equilateral(sides):
retu... | def is_triangle(func):
def wrapped(sides):
if any((i <= 0 for i in sides)):
return False
sum_ = sum(sides)
if any((sides[i] > sum_ - sides[i] for i in range(3))):
return False
return func(sides)
return wrapped
@is_triangle
def is_equilateral(sides):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
BOT_NAME = 'book'
SPIDER_MODULES = ['book.spiders']
NEWSPIDER_MODULE = 'book.spiders'
IMAGES_STORE = '../storage/book/'
COOKIES_ENABLED = True
COOKIE_DEBUG = True
LOG_LEVEL = 'INFO'
# LOG_LEVEL = 'DEBUG'
CONCURRENT_REQUESTS = 100
CONCURRENT_REQUESTS_PER_DOMAIN = 1000
U... | bot_name = 'book'
spider_modules = ['book.spiders']
newspider_module = 'book.spiders'
images_store = '../storage/book/'
cookies_enabled = True
cookie_debug = True
log_level = 'INFO'
concurrent_requests = 100
concurrent_requests_per_domain = 1000
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHT... |
AP = "AP"
BP = "BP"
ARRIVE = "ARRIVE"
NEUROMODULATORS = "NEUROMODULATORS"
TARGET = "TARGET"
OBSERVE = "OBSERVE"
SET_FREQUENCY = "SET_FREQUENCY"
DEACTIVATE = "DEACTIVATE"
ENCODE_INFORMATION = "ENCODE_INFORMATION"
| ap = 'AP'
bp = 'BP'
arrive = 'ARRIVE'
neuromodulators = 'NEUROMODULATORS'
target = 'TARGET'
observe = 'OBSERVE'
set_frequency = 'SET_FREQUENCY'
deactivate = 'DEACTIVATE'
encode_information = 'ENCODE_INFORMATION' |
#! /usr/bin/python3
print("HELLO PYTHON")
| print('HELLO PYTHON') |
try:
with open('proxies.txt', 'r') as file:
proxy = [ line.rstrip() for line in file.readlines()]
except FileNotFoundError:
raise Exception('Proxies.txt not found.') | try:
with open('proxies.txt', 'r') as file:
proxy = [line.rstrip() for line in file.readlines()]
except FileNotFoundError:
raise exception('Proxies.txt not found.') |
text = input()
punc_remove = [",", ".", "!", "?"]
for i in punc_remove:
text = text.replace(i, "")
print(text.lower()) | text = input()
punc_remove = [',', '.', '!', '?']
for i in punc_remove:
text = text.replace(i, '')
print(text.lower()) |
'''
Student: Dan Grecoe
Assignment: Homework 1
Submission of the first homework assignment. The assignment
was to create a python file with 2 functions
multiply - Takes two parameters x and y and returns the product
of the values provided.
noop - Takes 0 parameters and returns... | """
Student: Dan Grecoe
Assignment: Homework 1
Submission of the first homework assignment. The assignment
was to create a python file with 2 functions
multiply - Takes two parameters x and y and returns the product
of the values provided.
noop - Takes 0 parameters and returns... |
# `name` is the name of the package as used for `pip install package`
name = "package-name"
# `path` is the name of the package for `import package`
path = name.lower().replace("-", "_").replace(" ", "_")
version = "0.1.0"
author = "Author Name"
author_email = ""
description = "" # summary
license = "MIT"
| name = 'package-name'
path = name.lower().replace('-', '_').replace(' ', '_')
version = '0.1.0'
author = 'Author Name'
author_email = ''
description = ''
license = 'MIT' |
__title__ = 'cisco_support'
__description__ = 'Cisco Support APIs'
__version__ = '0.1.0'
__author__ = 'Dennis Roth'
__license__ = 'MIT'
| __title__ = 'cisco_support'
__description__ = 'Cisco Support APIs'
__version__ = '0.1.0'
__author__ = 'Dennis Roth'
__license__ = 'MIT' |
elements = [int(x) for x in input().split(', ')]
even_numbers = [x for x in elements if x % 2 == 0]
odd_numbers = [x for x in elements if x % 2 != 0]
positive = [x for x in elements if x >= 0]
negative = [x for x in elements if x < 0]
print(f"Positive: {', '.join(str(x) for x in positive)}")
print(f"Negative: {', '.j... | elements = [int(x) for x in input().split(', ')]
even_numbers = [x for x in elements if x % 2 == 0]
odd_numbers = [x for x in elements if x % 2 != 0]
positive = [x for x in elements if x >= 0]
negative = [x for x in elements if x < 0]
print(f"Positive: {', '.join((str(x) for x in positive))}")
print(f"Negative: {', '.j... |
vals = {
"yes" : 0,
"residential" : 1,
"service" : 2,
"unclassified" : 3,
"stream" : 4,
"track" : 5,
"water" : 6,
"footway" : 7,
"tertiary" : 8,
"private" : 9,
"tree" : 10,
"path" : 11,
"forest" : 12,
"secondary" : 13,
"house" : 14,
"no" : 15,
"asphalt" : 16,
"wood" : 17,
"grass" : 18,
"paved" : 19,
"primary" : 20,
"un... | vals = {'yes': 0, 'residential': 1, 'service': 2, 'unclassified': 3, 'stream': 4, 'track': 5, 'water': 6, 'footway': 7, 'tertiary': 8, 'private': 9, 'tree': 10, 'path': 11, 'forest': 12, 'secondary': 13, 'house': 14, 'no': 15, 'asphalt': 16, 'wood': 17, 'grass': 18, 'paved': 19, 'primary': 20, 'unpaved': 21, 'bus_stop'... |
def write_file(filess, T):
f = open(filess, "w")
for o in T:
f.write("[\n")
for l in o:
f.write(str(l)+"\n")
f.write("]\n")
f.close()
def save_hidden_weight(nb_hidden, hiddenw):
for i in range(nb_hidden):
write_file("save/base_nn_hid_" + str(i+1) + "w.nn", hiddenw[i])
def load_hiddenw(filess, hi... | def write_file(filess, T):
f = open(filess, 'w')
for o in T:
f.write('[\n')
for l in o:
f.write(str(l) + '\n')
f.write(']\n')
f.close()
def save_hidden_weight(nb_hidden, hiddenw):
for i in range(nb_hidden):
write_file('save/base_nn_hid_' + str(i + 1) + 'w.nn'... |
class Config(object):
embedding_size = 300
n_layers = 1
hidden_size = 128
drop_prob = 0.2 | class Config(object):
embedding_size = 300
n_layers = 1
hidden_size = 128
drop_prob = 0.2 |
sm.setSpeakerID(1013000)
sm.sendNext("Ugh. This isn't going to work. I need something else. No plants. No meat. What, you have no idea? But you're the master, and you're older than me, too. You must know what'd be good for me!")
sm.setPlayerAsSpeaker()
sm.sendSay("#bBut I don't. It's not like age has anything to do wi... | sm.setSpeakerID(1013000)
sm.sendNext("Ugh. This isn't going to work. I need something else. No plants. No meat. What, you have no idea? But you're the master, and you're older than me, too. You must know what'd be good for me!")
sm.setPlayerAsSpeaker()
sm.sendSay("#bBut I don't. It's not like age has anything to do wit... |
class Solution:
def chooseandswap (self, A):
opt = 'a'
fir = A[0]
arr = [0]*26
for s in A :
arr[ord(s)-97] += 1
i = 0
while i < len(A) :
if opt > 'z' :
break
while opt < fir :
if o... | class Solution:
def chooseandswap(self, A):
opt = 'a'
fir = A[0]
arr = [0] * 26
for s in A:
arr[ord(s) - 97] += 1
i = 0
while i < len(A):
if opt > 'z':
break
while opt < fir:
if opt in A:
... |
class AccountManager(object):
def __init__(self, balance = 0):
self.balance = balance
def getBalance(self):
return self.balance
def withdraw(self, value):
if self.balance >= value:
self.balance = self.balance - value
print('Successful Withdrawal.')
... | class Accountmanager(object):
def __init__(self, balance=0):
self.balance = balance
def get_balance(self):
return self.balance
def withdraw(self, value):
if self.balance >= value:
self.balance = self.balance - value
print('Successful Withdrawal.')
e... |
# Exercicio 01 Tuplas
x = int(input('Digite o primeiro numero: '))
y = int(input('Digite o segundo numero: '))
cont = 1
soma = x
while cont < y:
soma = soma + x
cont = cont + 1
print('O resultado eh: {}' .format(soma))
| x = int(input('Digite o primeiro numero: '))
y = int(input('Digite o segundo numero: '))
cont = 1
soma = x
while cont < y:
soma = soma + x
cont = cont + 1
print('O resultado eh: {}'.format(soma)) |
'''
To have a error free way of accessing and updating private variables, we create specific methods for this.
Those methods which are meant to set a value to a private variable are called setter methods and methods
meant to access private variable values are called getter methods.
The below code is an example of g... | """
To have a error free way of accessing and updating private variables, we create specific methods for this.
Those methods which are meant to set a value to a private variable are called setter methods and methods
meant to access private variable values are called getter methods.
The below code is an example of g... |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
# this is a dynamic programming solution fot this
matrix = [[False for x in range(len(p) + 1)] for x in range(len(s) + 1)]
matrix[0][0] = True
for i in range(1, len(matrix[0])):
if p[i - 1] == "*":
... | class Solution:
def is_match(self, s: str, p: str) -> bool:
matrix = [[False for x in range(len(p) + 1)] for x in range(len(s) + 1)]
matrix[0][0] = True
for i in range(1, len(matrix[0])):
if p[i - 1] == '*':
matrix[0][i] = matrix[0][i - 1]
for i in range(... |
# https://open.kattis.com/problems/luhnchecksum
for _ in range(int(input())):
count = 0
for i, d in enumerate(reversed(input())):
if i % 2 == 0:
count += int(d)
continue
x = 2 * int(d)
if x < 10:
count += x
else:
x = str(x)
... | for _ in range(int(input())):
count = 0
for (i, d) in enumerate(reversed(input())):
if i % 2 == 0:
count += int(d)
continue
x = 2 * int(d)
if x < 10:
count += x
else:
x = str(x)
count += int(x[0]) + int(x[1])
print('... |
inputFile = "3-input"
outputFile = "3-output"
dir = {'L': [-1,0],'R': [1,0],'U': [0,1],'D': [0,-1]}
def readFile():
file = open(inputFile, "r")
A,B = file.readlines()
A,B = [line.split(",") for line in [A,B]]
file.close()
return A,B
def writeFile(a, b):
file = open(outputFile, "w+")
fil... | input_file = '3-input'
output_file = '3-output'
dir = {'L': [-1, 0], 'R': [1, 0], 'U': [0, 1], 'D': [0, -1]}
def read_file():
file = open(inputFile, 'r')
(a, b) = file.readlines()
(a, b) = [line.split(',') for line in [A, B]]
file.close()
return (A, B)
def write_file(a, b):
file = open(outputF... |
name = 'Urban Dictionary Therapy'
__all__ = ['UDTherapy',
'helper']
| name = 'Urban Dictionary Therapy'
__all__ = ['UDTherapy', 'helper'] |
class SimulateMode:
@staticmethod
def start_simulation(device, guide=None):
return
| class Simulatemode:
@staticmethod
def start_simulation(device, guide=None):
return |
# Uses python3
n = int(input())
if n == 1:
print(1)
print(1)
quit()
W = n
prizes = []
for i in range(1, n):
if W>2*i:
prizes.append(i)
W -= i
else:
prizes.append(W)
break
print(len(prizes))
print(' '.join([str(i) for i in prizes])) | n = int(input())
if n == 1:
print(1)
print(1)
quit()
w = n
prizes = []
for i in range(1, n):
if W > 2 * i:
prizes.append(i)
w -= i
else:
prizes.append(W)
break
print(len(prizes))
print(' '.join([str(i) for i in prizes])) |
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your first pizza!")
if 'mush... | requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print('Adding mushrooms.')
if 'pepperoni' in requested_toppings:
print('Adding pepperoni.')
if 'extra cheese' in requested_toppings:
print('Adding extra cheese.')
print('\nFinished making your first pizza!')
if 'mushroo... |
# -*- coding: utf-8 -*-
MNIST_DATASET_PATH = 'raw_data/mnist.pkl.gz'
TEST_FOLDER = 'test/'
TRAIN_FOLDER = 'train/'
MODEL_FILE_PATH = 'model/recognizer.pickle'
LABEL_ENCODER_FILE_PATH = 'model/label_encoder.pickle'
# Manual
DEMO_HELP_MSG = '\n' + \
'Input parameter is incorrect\n' + \
'Display ... | mnist_dataset_path = 'raw_data/mnist.pkl.gz'
test_folder = 'test/'
train_folder = 'train/'
model_file_path = 'model/recognizer.pickle'
label_encoder_file_path = 'model/label_encoder.pickle'
demo_help_msg = '\n' + 'Input parameter is incorrect\n' + "Display help: 'python demo.py -h'"
trainer_help_msg = '\n' + 'Input par... |
#! /usr/bin/env python
def cut_the_sticks(a):
cuts = []
while len(a) > 0:
cutter = a.pop()
if cutter == 0:
continue
for i in range(len(a)):
a[i] -= cutter
cuts.append(len(a) + 1)
return cuts
if __name__ == '__main__':
_ = input()
value = map... | def cut_the_sticks(a):
cuts = []
while len(a) > 0:
cutter = a.pop()
if cutter == 0:
continue
for i in range(len(a)):
a[i] -= cutter
cuts.append(len(a) + 1)
return cuts
if __name__ == '__main__':
_ = input()
value = map(int, input().split(' '))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.