content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not postorder:
return
root = TreeNode(postorder[-1])
rootpos = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:rootpos], postorder[:rootpos])
root.right ... | class Solution:
def build_tree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not postorder:
return
root = tree_node(postorder[-1])
rootpos = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:rootpos], postorder[:rootpos])
root.rig... |
class Node:
def __init__(self, data=None, next=None):
self.__data = data
self.__next = next
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def next(self):
return self.__next
@next.se... | class Node:
def __init__(self, data=None, next=None):
self.__data = data
self.__next = next
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def next(self):
return self.__next
@next.s... |
def y():
raise TypeError
def x():
y()
try:
x()
except TypeError:
print("x")
| def y():
raise TypeError
def x():
y()
try:
x()
except TypeError:
print('x') |
# nominal reactor positions
data = dict([
('YJ1', [52.5]),
('YJ2', [52.5]),
('YJ3', [52.5]),
('YJ4', [52.5]),
('YJ5', [52.5]),
('YJ6', [52.5]),
('TS1', [52.5]),
('TS2', [52.5]),
('TS3', [52.5]),
('TS4', [52.5]),
('DYB', [215.0]),
('HZ', [265.0]),
])
| data = dict([('YJ1', [52.5]), ('YJ2', [52.5]), ('YJ3', [52.5]), ('YJ4', [52.5]), ('YJ5', [52.5]), ('YJ6', [52.5]), ('TS1', [52.5]), ('TS2', [52.5]), ('TS3', [52.5]), ('TS4', [52.5]), ('DYB', [215.0]), ('HZ', [265.0])]) |
class Summary:
def __init__(self, total_income, net_income, income_tax, employees_ni,
employers_ni):
self._total_income = total_income
self._net_income = net_income
self._income_tax = income_tax
self._employees_ni = employees_ni
self._employers_ni = employers... | class Summary:
def __init__(self, total_income, net_income, income_tax, employees_ni, employers_ni):
self._total_income = total_income
self._net_income = net_income
self._income_tax = income_tax
self._employees_ni = employees_ni
self._employers_ni = employers_ni
@proper... |
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
def isChar(c):
return True if ord('z')>=ord(c)>=ord('a') or ord('Z')>=ord(c)>=ord('A') else False
right = len(s)-1
left = 0
charArray = [c for c in s]
while left<righ... | class Solution:
def reverse_only_letters(self, s: str) -> str:
def is_char(c):
return True if ord('z') >= ord(c) >= ord('a') or ord('Z') >= ord(c) >= ord('A') else False
right = len(s) - 1
left = 0
char_array = [c for c in s]
while left < right:
prin... |
def fp(i,n) :
i /= 100
return (1+i)**n
def pf(i,n) :
i /= 100
return 1/((1+i)**n)
def fa(i,n) :
i /= 100
return (((1+i)**n)-1)/i
def af(i,n) :
i /= 100
return i/(((1+i)**n)-1)
def pa(i,n) :
i /= 100
return (((1+i)**n)-1)/(i*((1+i)**n))
def ap(i,n) :
i /= 100
return (i*((1+i)**n))/(((1+i)**n... | def fp(i, n):
i /= 100
return (1 + i) ** n
def pf(i, n):
i /= 100
return 1 / (1 + i) ** n
def fa(i, n):
i /= 100
return ((1 + i) ** n - 1) / i
def af(i, n):
i /= 100
return i / ((1 + i) ** n - 1)
def pa(i, n):
i /= 100
return ((1 + i) ** n - 1) / (i * (1 + i) ** n)
def ap(i,... |
"""utility functions to read in and parse a file efficiently
"""
def gen_file_line(text):
with open(text) as fp:
for line in fp:
yield line | """utility functions to read in and parse a file efficiently
"""
def gen_file_line(text):
with open(text) as fp:
for line in fp:
yield line |
# Copyright (c) 2018 Turysaz <turysaz@posteo.org>
class IoCContainer():
def __init__(self):
self.__constructors = {} # {"service_key" : service_ctor}
self.__dependencies = {} # {"service_key" : ["dep_key_1", "dep_key_2", ..]} constructor parameters
self.__quantity = {} # {"service_... | class Ioccontainer:
def __init__(self):
self.__constructors = {}
self.__dependencies = {}
self.__quantity = {}
self.__singletons = {}
def register_on_demand(self, service_name_string, service, *dependencies):
self.__register_internal(service_name_string, service, 'multi... |
# def isIPv4Address(inputString):
# return len([num for num in inputString.split(".") if num != "" and 0 <= int(num) < 255]) == 4
# def isIPv4Address(inputString):
# return len([int(num) for num in inputString.split(".") if num != "" and not num.islower() and 0 <= int(num) <= 255]) == 4
# def isIPv4Addr... | def is_i_pv4_address(inputString):
if inputString.count('.') != 3:
return False
return len([int(num) for num in inputString.split('.') if num != '' and (not num.islower()) and (0 <= int(num) <= 255) and (len(num) == len(str(int(num))))]) == 4
print(is_i_pv4_address('0..1.0.0')) |
def validTime(time):
tokens = time.split(":")
hours, mins = tokens[0], tokens[1]
if int(hours) < 0 or int(hours) > 23:
return False
if int(mins) < 0 or int(mins) > 59:
return False
return True
| def valid_time(time):
tokens = time.split(':')
(hours, mins) = (tokens[0], tokens[1])
if int(hours) < 0 or int(hours) > 23:
return False
if int(mins) < 0 or int(mins) > 59:
return False
return True |
#
# PySNMP MIB module AT-IGMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-IGMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:30:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (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) ... |
#!/usr/bin/env python
#
# Copyright (c) 2018 10X Genomics, Inc. All rights reserved.
#
MULTI_REFS_PREFIX = 'multi'
# Constants for metasamples
GENE_EXPRESSION_LIBRARY_TYPE = 'Gene Expression'
VDJ_LIBRARY_TYPE = 'VDJ'
ATACSEQ_LIBRARY_TYPE = 'Peaks'
ATACSEQ_LIBRARY_DERIVED_TYPE = 'Motifs'
DEFAULT_LIBRARY_TYPE = GENE_EX... | multi_refs_prefix = 'multi'
gene_expression_library_type = 'Gene Expression'
vdj_library_type = 'VDJ'
atacseq_library_type = 'Peaks'
atacseq_library_derived_type = 'Motifs'
default_library_type = GENE_EXPRESSION_LIBRARY_TYPE |
def noOfwords(strs):
l = strs.split(' ')
return len(l)
string = input()
count = noOfwords(string)
print(count)
| def no_ofwords(strs):
l = strs.split(' ')
return len(l)
string = input()
count = no_ofwords(string)
print(count) |
def modular_exp(b, e, mod):
if e == 0:
return 1
res = modular_exp(b, e//2, mod)
res = (res * res ) % mod
if e%2 == 1:
res = (res * b) % mod
return res
| def modular_exp(b, e, mod):
if e == 0:
return 1
res = modular_exp(b, e // 2, mod)
res = res * res % mod
if e % 2 == 1:
res = res * b % mod
return res |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for Skia.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmi... | """Top-level presubmit script for Skia.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
def __check_change_has_eol(input_api, output_api, source_file_filter=None):
"""Checks that files end with atleast one
(LF)."""
eof_... |
#!C:\Python27\python.exe
# EASY-INSTALL-SCRIPT: 'docutils==0.12','rst2odt_prepstyles.py'
__requires__ = 'docutils==0.12'
__import__('pkg_resources').run_script('docutils==0.12', 'rst2odt_prepstyles.py')
| __requires__ = 'docutils==0.12'
__import__('pkg_resources').run_script('docutils==0.12', 'rst2odt_prepstyles.py') |
"""
FIT1008 Prac 6 Task 1
Loh Hao Bin 25461257, Tan Wen Jie 25839063
@purpose: Knight in Chess
File: The columns
Rank: The rows
@created 20140831
@modified 20140903
"""
class Tour:
def __init__(self,y,x):
self.board = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
... | """
FIT1008 Prac 6 Task 1
Loh Hao Bin 25461257, Tan Wen Jie 25839063
@purpose: Knight in Chess
File: The columns
Rank: The rows
@created 20140831
@modified 20140903
"""
class Tour:
def __init__(self, y, x):
self.board = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0,... |
"""
union operation
"""
def union(set1: list, set2: list) -> list:
result = []
for s1 in set1:
for s2 in set2:
if s1 == s2:
result.append(s1)
return result
if __name__ == "__main__":
cases = [
{"s1": [1, 2, 3], "s2": [3, 4, 5], "ans": [3]},
{"s1"... | """
union operation
"""
def union(set1: list, set2: list) -> list:
result = []
for s1 in set1:
for s2 in set2:
if s1 == s2:
result.append(s1)
return result
if __name__ == '__main__':
cases = [{'s1': [1, 2, 3], 's2': [3, 4, 5], 'ans': [3]}, {'s1': [1], 's2': [3], 'ans... |
"""Module focussing on the `format` command.
Contains the task and helpers to format the codebase given a specific formatter.
"""
# import pathlib
#
#
# def bob_format(options, cwd):
# folders = ['src', 'include']
# filetypes = ['*.c', '*.h', '*.cpp', '*.hpp']
#
# files = []
# for f in folders:
# ... | """Module focussing on the `format` command.
Contains the task and helpers to format the codebase given a specific formatter.
""" |
template = """
module rom32x4 (
input [4:0] addr,
input clk,
output [4:0] data);
wire [7:0] rdata;
wire [15:0] RDATA;
wire RCLK;
wire [10:0] RADDR;
SB_RAM40_4KNR #( // negative edge readclock so we can apply and addres on the positive edge and guarantee data is available on the next posedge
.WRITE_MODE(... | template = "\nmodule rom32x4 (\n\tinput [4:0] addr, \n\tinput clk,\n\toutput [4:0] data);\n\n wire [7:0] rdata;\n\twire [15:0] RDATA;\n\twire RCLK;\n\twire [10:0] RADDR;\n\n\tSB_RAM40_4KNR #( // negative edge readclock so we can apply and addres on the positive edge and guarantee data is available on the next posedg... |
#!/usr/bin/env python3
def raw_limit_ranges(callback_values):
data = {
'__meta': {
'chart': 'cisco-sso/raw',
'version': '0.1.0'
},
'resources': [{
'apiVersion': 'v1',
'kind': 'LimitRange',
'metadata': {
'name': 'l... | def raw_limit_ranges(callback_values):
data = {'__meta': {'chart': 'cisco-sso/raw', 'version': '0.1.0'}, 'resources': [{'apiVersion': 'v1', 'kind': 'LimitRange', 'metadata': {'name': 'limits'}, 'spec': {'limits': [{'default': {'cpu': '100m', 'memory': '256Mi'}, 'defaultRequest': {'cpu': '100m', 'memory': '256Mi'}, ... |
#definir variables y otros
print("Ejemplo 01-Area de un triangulo")
#Datos de entrada - Ingresados mediante dispositivos de entrada
b=int(input("Ingrese Base:"))
h=int(input("Ingrese altura"))
#proceso de calculo de Area
area=(b*h)/2
#Datos de salida
print("El area del triangulo es:", area) | print('Ejemplo 01-Area de un triangulo')
b = int(input('Ingrese Base:'))
h = int(input('Ingrese altura'))
area = b * h / 2
print('El area del triangulo es:', area) |
def handle_request(response):
if response.error:
print("Error:", response.error)
else:
print('called')
print(response.body)
| def handle_request(response):
if response.error:
print('Error:', response.error)
else:
print('called')
print(response.body) |
# CPP Program of Prim's algorithm for MST
inf = 65000
# To add an edge
def addEdge(adj, u, v, wt):
adj[u].append([v, wt])
adj[v].append([u, wt])
def primMST(adj, V):
# Create a priority queue to store vertices that
# are being preinMST.
pq = []
src = 0 # Taking vertex 0 as source
#... | inf = 65000
def add_edge(adj, u, v, wt):
adj[u].append([v, wt])
adj[v].append([u, wt])
def prim_mst(adj, V):
pq = []
src = 0
key = [inf for i in range(V)]
parent = [-1 for i in range(V)]
in_mst = [False for i in range(V)]
pq.append([0, src])
key[src] = 0
while len(pq) != 0:
... |
n,m,k = map(int,input().split())
d = list(map(int,input().split()))
m = list(map(int,input().split()))
ans = []
check = 10**18
for i in range(len(d)):
frog=d[i]
c=0
for j in range(len(m)):
if m[j]%frog==0:
c+=1
if c<check:
ans.clear()
ans.append(i+1)
check=c
... | (n, m, k) = map(int, input().split())
d = list(map(int, input().split()))
m = list(map(int, input().split()))
ans = []
check = 10 ** 18
for i in range(len(d)):
frog = d[i]
c = 0
for j in range(len(m)):
if m[j] % frog == 0:
c += 1
if c < check:
ans.clear()
ans.append(i... |
# Variables
age = 20 # declaring int variable
temperature = 89.8 # declaring float variable
name = 'John' # declaring str variable, Note: we use single quotes to store the text.
model = "SD902" # declaring str variable
print(model)
model = 8890 # n... | age = 20
temperature = 89.8
name = 'John'
model = 'SD902'
print(model)
model = 8890
print(model)
msg = str('Big Brother is in town')
msg = str('Case sensitive variable')
print(f'msg = {msg}')
print(f'Msg = {Msg}') |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2014
@author: Marat Khayrullin <xmm.dev@gmail.com>
'''
API_VERSION_V0 = 0
API_VERSION = API_VERSION_V0
bp_name = 'api_v0'
api_v0_prefix = '{prefix}/v{version}'.format(
prefix='/api', # current_app.config['URL_PREFIX'],
version=API_VERSION_V0
)
| """
Copyright (c) 2014
@author: Marat Khayrullin <xmm.dev@gmail.com>
"""
api_version_v0 = 0
api_version = API_VERSION_V0
bp_name = 'api_v0'
api_v0_prefix = '{prefix}/v{version}'.format(prefix='/api', version=API_VERSION_V0) |
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
def float_dec2bin(n):
neg = False
if n < 0:
n = -n
neg = True
hx = float(n).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])
return (('1' if neg else '0') + bn.strip('0') + hx[p... | hex2bin = dict(('{:x} {:04b}'.format(x, x).split() for x in range(16)))
def float_dec2bin(n):
neg = False
if n < 0:
n = -n
neg = True
hx = float(n).hex()
p = hx.index('p')
bn = ''.join((hex2bin.get(char, char) for char in hx[2:p]))
return ('1' if neg else '0') + bn.strip('0') + ... |
# basicpackage/foo.py
a = 10
class Foo(object):
pass
print("inside 'basicpackage/foo.py' with a variable in it")
| a = 10
class Foo(object):
pass
print("inside 'basicpackage/foo.py' with a variable in it") |
famous_people = []
with open("/Users/coco/Documents/GitHub/python-side-projects/wikipedia-crawler/year1902-2020.txt",'r') as foo:
for line in foo.readlines():
if '``' in line:
famous_people.append(line)
with open("famous_people.txt", "a") as f:
for person in famous_people:
f.wr... | famous_people = []
with open('/Users/coco/Documents/GitHub/python-side-projects/wikipedia-crawler/year1902-2020.txt', 'r') as foo:
for line in foo.readlines():
if '``' in line:
famous_people.append(line)
with open('famous_people.txt', 'a') as f:
for person in famous_people:
f.write(p... |
class no_deps(object):
pass
class one_dep(object):
def __init__(self, dependency):
self.dependency = dependency
class two_deps(object):
def __init__(self, first_dep, second_dep):
self.first_dep = first_dep
self.second_dep = second_dep
| class No_Deps(object):
pass
class One_Dep(object):
def __init__(self, dependency):
self.dependency = dependency
class Two_Deps(object):
def __init__(self, first_dep, second_dep):
self.first_dep = first_dep
self.second_dep = second_dep |
#
# PySNMP MIB module HP-ICF-ARP-PROTECT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-ARP-PROTECT
# Produced by pysmi-0.3.4 at Mon Apr 29 19:20:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
pkgname = "libuninameslist"
pkgver = "20211114"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf", "automake", "libtool"]
pkgdesc = "Library of Unicode names and annotation data"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-3-Clause"
url = "https://github.com/fontforge/libuninameslist"
... | pkgname = 'libuninameslist'
pkgver = '20211114'
pkgrel = 0
build_style = 'gnu_configure'
hostmakedepends = ['pkgconf', 'automake', 'libtool']
pkgdesc = 'Library of Unicode names and annotation data'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'BSD-3-Clause'
url = 'https://github.com/fontforge/libuninameslist'
... |
POSTGRESQL = 'PostgreSQL'
MYSQL = 'MySQL'
DEV = 'Development'
STAGE = 'Staging'
TEST = 'Testing'
PROD = 'Production' | postgresql = 'PostgreSQL'
mysql = 'MySQL'
dev = 'Development'
stage = 'Staging'
test = 'Testing'
prod = 'Production' |
# 10001st prime
# The nth prime number
def isPrime(n):
for i in range(2, int(math.sqrt(n))+1):
if n%i == 0:
return False
return True
def nthPrime(n):
num = 2
nums = []
while len(nums) < n:
if isPrime(num) == True:
nums.append(num)
num += 1
return nums[-1]
| def is_prime(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def nth_prime(n):
num = 2
nums = []
while len(nums) < n:
if is_prime(num) == True:
nums.append(num)
num += 1
return nums[-1] |
class IntervalNum:
def __init__(self,a,b):
if a > b:
a,b = b,a
self.a = a
self.b = b
def __str__(self):
return f"[{self.a};{self.b}]"
def __add__(self,other):
return IntervalNum(self.a+other.a, self.b+other.b)
def __sub__(self,other):
re... | class Intervalnum:
def __init__(self, a, b):
if a > b:
(a, b) = (b, a)
self.a = a
self.b = b
def __str__(self):
return f'[{self.a};{self.b}]'
def __add__(self, other):
return interval_num(self.a + other.a, self.b + other.b)
def __sub__(self, other)... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'cv.sqlite', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOS... | databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'cv.sqlite', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': ''}}
middleware_classes = ('django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.AuthenticationM... |
vehicles = {
'dream': 'Honda 250T',
'er5': 'Kawasaki ER5',
'can-am': 'Bombardier Can-Am 250',
'virago': 'Yamaha XV250',
'tenere': 'Yamaha XT650',
'jimny': 'Suzuki Jimny 1.5',
'fiesta': 'Ford Fiesta Ghia 1.4',
'roadster': 'Triumph Street Triple'
}
vehicles["starfighter"] = "Lockhead F-10... | vehicles = {'dream': 'Honda 250T', 'er5': 'Kawasaki ER5', 'can-am': 'Bombardier Can-Am 250', 'virago': 'Yamaha XV250', 'tenere': 'Yamaha XT650', 'jimny': 'Suzuki Jimny 1.5', 'fiesta': 'Ford Fiesta Ghia 1.4', 'roadster': 'Triumph Street Triple'}
vehicles['starfighter'] = 'Lockhead F-104'
vehicles['learjet'] = 'Bombardie... |
class DpiChangedEventArgs(RoutedEventArgs):
# no doc
NewDpi=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: NewDpi(self: DpiChangedEventArgs) -> DpiScale
"""
OldDpi=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: OldDpi(self: DpiChangedEventAr... | class Dpichangedeventargs(RoutedEventArgs):
new_dpi = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Get: NewDpi(self: DpiChangedEventArgs) -> DpiScale\n\n\n\n'
old_dpi = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Get: OldDpi(self: DpiChangedEven... |
#!/usr/bin/env python
def start():
print("Hello, world.")
if __name__ == '__main__':
start()
| def start():
print('Hello, world.')
if __name__ == '__main__':
start() |
numbers = [3, 6, 2, 8, 4, 10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max) | numbers = [3, 6, 2, 8, 4, 10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max) |
class StateMachineException(Exception):
def __init__(self, message_format, **kwargs):
if kwargs:
self.message = message_format.format(**kwargs)
else:
self.message = message_format
self.__dict__.update(**kwargs)
def __str__(self):
return self.message
cla... | class Statemachineexception(Exception):
def __init__(self, message_format, **kwargs):
if kwargs:
self.message = message_format.format(**kwargs)
else:
self.message = message_format
self.__dict__.update(**kwargs)
def __str__(self):
return self.message
cla... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class DataSet:
def __init__(self,
src_channels_url: str,
injection_file_name: str,
out_file_name: str,
out_file_encoding: str,
out_file_first_line: str,
out_file_format... | class Dataset:
def __init__(self, src_channels_url: str, injection_file_name: str, out_file_name: str, out_file_encoding: str, out_file_first_line: str, out_file_format: str, filter_file_name: str, clean_filter: bool) -> None:
self._src_channels_url: str = src_channels_url
self._injection_file_name... |
sys_word = {}
for x in range(0,325):
sys_word[x] = 0
file = open("UAD-0015.txt", "r+")
words = file.read().split()
file.close()
for word in words:
sys_word[int(word)] += 1
for x in range(0,325):
sys_word[x] = sys_word[x]/int(325)
file_ = open("a_1.txt", "w")
for x in range(0,325):
if x is 324:
... | sys_word = {}
for x in range(0, 325):
sys_word[x] = 0
file = open('UAD-0015.txt', 'r+')
words = file.read().split()
file.close()
for word in words:
sys_word[int(word)] += 1
for x in range(0, 325):
sys_word[x] = sys_word[x] / int(325)
file_ = open('a_1.txt', 'w')
for x in range(0, 325):
if x is 324:
... |
#Soumya Pal
#Assignment 2 part 4
info = {
"name": "Shomo Pal",
"favorite_color": "Blue",
"favorite_number": 10,
"favorite_movies": ["Inception","The Shashank Redemption","One Piece (Anime not movie)"],
"favorite_songs" : [{'artist': 'Metallica', 'title': 'Nothing Else Matters'},
{'artist':... | info = {'name': 'Shomo Pal', 'favorite_color': 'Blue', 'favorite_number': 10, 'favorite_movies': ['Inception', 'The Shashank Redemption', 'One Piece (Anime not movie)'], 'favorite_songs': [{'artist': 'Metallica', 'title': 'Nothing Else Matters'}, {'artist': 'Nirvana', 'title': 'Come as you are'}]}
print(info['name'])
p... |
class Solution:
# @param {integer[][]} grid
# @return {integer}
def minPathSum(self, grid):
n = len(grid);
m = len(grid[0]);
p = [([0] * m) for i in range(n)]
p[0][0] = grid[0][0];
for k in range (1, n):
p[k][0] = p[k-1][0]+grid[k][0];
for... | class Solution:
def min_path_sum(self, grid):
n = len(grid)
m = len(grid[0])
p = [[0] * m for i in range(n)]
p[0][0] = grid[0][0]
for k in range(1, n):
p[k][0] = p[k - 1][0] + grid[k][0]
for k in range(1, m):
p[0][k] = p[0][k - 1] + grid[0][k]... |
# Cidades: Crie um dicionario chamado cities. Use os nomes de tres cidades como chaves em seu dicionario. Crie um dicionario com informacoes sobre cada cidade e inclua o pais em que a cidade esta localizada, a populacao aproximada e um fato sobre essa cidade. As chaves do dicionario de cada cidade devem ser algo como c... | cities = {'maputo': {'coutry': 'mozambique', 'population': '12.488.246', 'fact': 'corupt coutry'}, 'sao paulo': {'coutry': 'brazil', 'population': '145.264.218', 'fact': 'beautiful people'}, 'lisbon': {'coutry': 'portugal', 'population': '10.264.254', 'fact': 'racist'}}
for (key, value) in cities.items():
print(f'{... |
""" Problem - 239. Sliding Window Maximum
Problem statement -
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return ... | """ Problem - 239. Sliding Window Maximum
Problem statement -
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return ... |
#!/usr/bin/env python
"""Pseudocode for the OPTICS algorithm."""
def optics(objects, epsilon, min_points):
"""
Clustering.
Parameters
----------
objects : set
epsilon : float
min_points : int
"""
assert min_points >= 1
# TODO
| """Pseudocode for the OPTICS algorithm."""
def optics(objects, epsilon, min_points):
"""
Clustering.
Parameters
----------
objects : set
epsilon : float
min_points : int
"""
assert min_points >= 1 |
feedback_poly = {
2: [1],
3: [2],
4: [3],
5: [3],
6: [5],
7: [6],
8: [6, 5, 4],
9: [5],
10: [7],
11: [9],
12: [11, 10, 4],
13: [12, 11, 8],
14: [13, 12, 2],
15: [14],
16: [14, 13, 11],
17: [14],
18: [11],
19: [18, 17, 14],
20: [17],
21: [19... | feedback_poly = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [6, 5, 4], 9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8], 14: [13, 12, 2], 15: [14], 16: [14, 13, 11], 17: [14], 18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21], 23: [18], 24: [23, 22, 17]}
def one_hot_encode(n):
coeffs = []
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
res = []
if root i... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binary_tree_paths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
res = []
if root is None:
return res
... |
# Generated by h2py from /usr/include/sys/event.h
EVFILT_READ = (-1)
EVFILT_WRITE = (-2)
EVFILT_AIO = (-3)
EVFILT_VNODE = (-4)
EVFILT_PROC = (-5)
EVFILT_SIGNAL = (-6)
EVFILT_SYSCOUNT = 6
EV_ADD = 0x0001
EV_DELETE = 0x0002
EV_ENABLE = 0x0004
EV_DISABLE = 0x0008
EV_ONESHOT = 0x0010
EV_CLEAR = 0x0020
EV_SYSFLAGS = 0xF000
... | evfilt_read = -1
evfilt_write = -2
evfilt_aio = -3
evfilt_vnode = -4
evfilt_proc = -5
evfilt_signal = -6
evfilt_syscount = 6
ev_add = 1
ev_delete = 2
ev_enable = 4
ev_disable = 8
ev_oneshot = 16
ev_clear = 32
ev_sysflags = 61440
ev_flag1 = 8192
ev_eof = 32768
ev_error = 16384
note_delete = 1
note_write = 2
note_extend ... |
a = 1
b = 2
c = 3
print(a)
print(b)
print(c)
| a = 1
b = 2
c = 3
print(a)
print(b)
print(c) |
default_prefix = "DWB"
known_chains = {
"BEX": {
"chain_id": "38f14b346eb697ba04ae0f5adcfaa0a437ed3711197704aa256a14cb9b4a8f26",
"prefix": "DWB",
"dpay_symbol": "BEX",
"bbd_symbol": "BBD",
"vests_symbol": "VESTS",
},
"BET": {
"chain_id":
"9afbce9f... | default_prefix = 'DWB'
known_chains = {'BEX': {'chain_id': '38f14b346eb697ba04ae0f5adcfaa0a437ed3711197704aa256a14cb9b4a8f26', 'prefix': 'DWB', 'dpay_symbol': 'BEX', 'bbd_symbol': 'BBD', 'vests_symbol': 'VESTS'}, 'BET': {'chain_id': '9afbce9f2416520733bacb370315d32b6b2c43d6097576df1c1222859d91eecc', 'prefix': 'DWT', 'd... |
# RemoveDuplicatesfromSortedArray.py
# weird accepted answer that doesn't actually remove anything.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if (len(nums)==0):
return 0
i=0
j=0
while j < len(nums):
# print(nums, i , j)
... | class Solution:
def remove_duplicates(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
i = 0
j = 0
while j < len(nums):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
j += 1
return i + 1 |
# Values obtained from running against the Fuss & Navarro 2009 reference implementation
vals = [(0.3325402105490861,
0.18224585277734096,
2.0210322268188046,
0.37178992456396914,
0.7513994191503139,
1.6883221884854474,
1.0,
0.082198565245068272),
(-0.13074510229340497,
0.44696631528174735,
2.4890334... | vals = [(0.3325402105490861, 0.18224585277734096, 2.0210322268188046, 0.37178992456396914, 0.7513994191503139, 1.6883221884854474, 1.0, 0.08219856524506827), (-0.13074510229340497, 0.44696631528174735, 2.4890334572448456, 0.3816245478330931, 0.9498762676625047, 1.0790903665954314, 0.1, 0.4159172228850658), (0.605601086... |
"""
Given a sorted array arr, two integers k and x, find the k closest elements
to x in the array. The result should also be sorted in ascending order.
If there is a tie, the smaller elements are always preferred.
Example:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Cons... | """
Given a sorted array arr, two integers k and x, find the k closest elements
to x in the array. The result should also be sorted in ascending order.
If there is a tie, the smaller elements are always preferred.
Example:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Cons... |
class HourRange():
def __init__(self, start: int, end: int):
if start == end:
raise ValueError("Start and end may not be equal.")
if start < 0 or 23 < start:
raise ValueError("Invalid start value: " + str(start))
if end < 0 or 23 < end:
raise ValueError("I... | class Hourrange:
def __init__(self, start: int, end: int):
if start == end:
raise value_error('Start and end may not be equal.')
if start < 0 or 23 < start:
raise value_error('Invalid start value: ' + str(start))
if end < 0 or 23 < end:
raise value_error(... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self, root:TreeNode, sum:int, cur_sum:int):
if not root.left and not root.right:
if cur_sum + root.val == sum:
return True
else:... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self, root: TreeNode, sum: int, cur_sum: int):
if not root.left and (not root.right):
if cur_sum + root.val == sum:
return True
... |
def moeda(p = 0, moeda = 'R$'):
return (f'{moeda}{p:.2f}'.replace('.',','))
def metade(p = 0, formato=False):
res = p/2
return res if formato is False else moeda(res)
def dobro(p = 0, formato=False):
res = p*2
return res if formato is False else moeda(res)
def aumentar(p = 0, taxa = 0, formato... | def moeda(p=0, moeda='R$'):
return f'{moeda}{p:.2f}'.replace('.', ',')
def metade(p=0, formato=False):
res = p / 2
return res if formato is False else moeda(res)
def dobro(p=0, formato=False):
res = p * 2
return res if formato is False else moeda(res)
def aumentar(p=0, taxa=0, formato=False):
... |
class BookReader:
country = 'South Korea'
print(BookReader.country )
BookReader.country = 'USA'
print(BookReader.country )
| class Bookreader:
country = 'South Korea'
print(BookReader.country)
BookReader.country = 'USA'
print(BookReader.country) |
"""
File used to test the scraping ability of the regular
expressions.
"""
# Setting up our fake functions and objects.
_ = lambda x: x
f = lambda x: x
class C(object):
pass
obj = C()
obj.blah = lambda x: x
# A single letter function that we don't want
f("_key")
# Simple function call.
_("_key")
# The chained ... | """
File used to test the scraping ability of the regular
expressions.
"""
_ = lambda x: x
f = lambda x: x
class C(object):
pass
obj = c()
obj.blah = lambda x: x
f('_key')
_('_key')
_('_key').f()
_('_key').f('hello', 1337)
_('_key').f(obj.blah(), {'dog': 'cat'})
_('_key').f('dogs', 'cats', {'living': 'together'}) |
def patxi():
tip = raw_input("Don't forget to use your new company WC as soon as possible, It's important....")
kk = """ @@X
@@@@@'
... | def patxi():
tip = raw_input("Don't forget to use your new company WC as soon as possible, It's important....")
kk = " @@X \n @@@@@' \n ... |
# DESCRIPTION
# Given a string containing only three types of characters: '(', ')' and '*',
# write a function to check whether this string is valid.
# We define the validity of a string by these rules:
# Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# Any right parenthesis ')' must ... | class Solution:
def check_valid_string(self, s: str) -> bool:
"""
Time: O(N), where N is the length of the string
Space: O(1), constant space no aux space used
"""
cmin = 0
cmax = 0
for i in s:
if i == '(':
cmax += 1
... |
lines = open('dayfivedata.txt').read().split('\n')
ids = []
for line in lines:
top = 0; bottom = 127
for _ in range(7):
if 'F' in line[_]:
bottom = (top+bottom)//2
else:
top = (top+bottom)//2 + 1
left = 0; right = 7
for _ in range(7, 10):
if 'L' in line[_]... | lines = open('dayfivedata.txt').read().split('\n')
ids = []
for line in lines:
top = 0
bottom = 127
for _ in range(7):
if 'F' in line[_]:
bottom = (top + bottom) // 2
else:
top = (top + bottom) // 2 + 1
left = 0
right = 7
for _ in range(7, 10):
if ... |
"""feedshepherd
All your (fairly simple) feed needs
"""
| """feedshepherd
All your (fairly simple) feed needs
""" |
def plot_confusion_matrix(cm, class_names):
"""
Returns a matplotlib figure containing the plotted confusion matrix.
Args:
cm (array, shape = [n, n]): a confusion matrix of integer classes
class_names (array, shape = [n]): String names of the integer classes
"""
figure = plt.figure(figsize=(8, 8))
... | def plot_confusion_matrix(cm, class_names):
"""
Returns a matplotlib figure containing the plotted confusion matrix.
Args:
cm (array, shape = [n, n]): a confusion matrix of integer classes
class_names (array, shape = [n]): String names of the integer classes
"""
figure = plt.figure(figsize=(8, 8)... |
n=int(input())
ans=[]
used=[False for i in range(n)]
d=[i+1 for i in range(n)]
a=list(map(int,input().split()))
p=0
f=False
while True:
for i in range(n-1):
if f:
i=n-2-i
if a[i]>i+1 and a[i+1]<i+2 and not used[i]:
ans.append(i+1)
used[i]=True
a[i],a[i... | n = int(input())
ans = []
used = [False for i in range(n)]
d = [i + 1 for i in range(n)]
a = list(map(int, input().split()))
p = 0
f = False
while True:
for i in range(n - 1):
if f:
i = n - 2 - i
if a[i] > i + 1 and a[i + 1] < i + 2 and (not used[i]):
ans.append(i + 1)
... |
# position, name, age, level, salary
se1 = ["Software Engineer", "Max", 20, "Junior", 5000]
se2 = ["Software Engineer", "Lisa", 25, "Senior", 7000]
# class
class SoftwareEngineer:
# class attributes
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary):
# instance attributes
... | se1 = ['Software Engineer', 'Max', 20, 'Junior', 5000]
se2 = ['Software Engineer', 'Lisa', 25, 'Senior', 7000]
class Softwareengineer:
alias = 'Keyboard Magician'
def __init__(self, name, age, level, salary):
self.name = name
self.age = age
self.level = level
self.salary = sala... |
##
# \breif Copula function rotation helpers
#
# These helpers must be implemented outside of
# copula_base since we need access to them in all
# our child copula classes as decorators.
#
# Rotate the data before fitting copula
#
# Always rotate data to original orientation after
# evaluation of copula functions
def r... | def rotate_pdf(input_pdf):
def rotated_fn(self, *args, **kwargs):
if args[2] == 0:
return input_pdf(self, *args, **kwargs)
if args[2] == 1:
return input_pdf(self, *args, **kwargs)
if args[2] == 2:
return input_pdf(self, *args, **kwargs)
if args[2]... |
class Usuario:
def __init__(self):
self.usuario=""
self.ingresos=0
def intro(self):
self.usuario=input("Ingrese el nombre del usuario:")
self.ingresos=float(input("Cantidad ingresos anual:"))
def visualizar(self):
print("Nombre:",self.usuario)
... | class Usuario:
def __init__(self):
self.usuario = ''
self.ingresos = 0
def intro(self):
self.usuario = input('Ingrese el nombre del usuario:')
self.ingresos = float(input('Cantidad ingresos anual:'))
def visualizar(self):
print('Nombre:', self.usuario)
prin... |
a=3
b=6
a,b=b,a
print('After Swapping values of A and B are',a,b)
| a = 3
b = 6
(a, b) = (b, a)
print('After Swapping values of A and B are', a, b) |
def pow(base,exponent):
"""
Given a base b and an exponent e, this function returns b^e
"""
return base**exponent | def pow(base, exponent):
"""
Given a base b and an exponent e, this function returns b^e
"""
return base ** exponent |
class LayerManager:
""" """
def __init__(self, canvas):
self.canvas = canvas
self.current_layer = 0
self.layers = []
def set_layer(self, cid):
self.current_layer = self.canvas.find_withtag('caption-'+str(cid))[0]
print(self.current_layer)
def raise_layer(self... | class Layermanager:
""" """
def __init__(self, canvas):
self.canvas = canvas
self.current_layer = 0
self.layers = []
def set_layer(self, cid):
self.current_layer = self.canvas.find_withtag('caption-' + str(cid))[0]
print(self.current_layer)
def raise_layer(self... |
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
lines = len(matrix)
lists = len(matrix[0])
mat = [[0] * lists for _ in range(lines)]
for i in range(lists):
mat[0][i] = int(matrix[0][i])
for i in ... | class Solution:
def maximal_square(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
lines = len(matrix)
lists = len(matrix[0])
mat = [[0] * lists for _ in range(lines)]
for i in range(lists):
mat[0][i] = int(matrix[0][i])
for i i... |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
d = {}
for num in nums:
if num not in d:
d[num] = 1
else:
d[num] = d[num] + 1
for k,v in d.items():
if v == 1:
return k
| class Solution:
def single_number(self, nums: List[int]) -> int:
d = {}
for num in nums:
if num not in d:
d[num] = 1
else:
d[num] = d[num] + 1
for (k, v) in d.items():
if v == 1:
return k |
# https://leetcode.com/problems/find-the-difference/
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
s = sorted(s)
t = sorted(t)
count = 0
for i in range(len(s)):
if s[i] != t[i] :
count = 1
print(t[i])
... | class Solution:
def find_the_difference(self, s: str, t: str) -> str:
s = sorted(s)
t = sorted(t)
count = 0
for i in range(len(s)):
if s[i] != t[i]:
count = 1
print(t[i])
return t[i]
if count == 0:
retur... |
for i in range(1,5):
for j in range(1,5):
print(j,end=" ")
print( )
| for i in range(1, 5):
for j in range(1, 5):
print(j, end=' ')
print() |
def round_off(ls2): # Function for the algorithm to obtain the desired output
final_grade = []
for value in ls2: # iterating in the list to read every student's marks
reminder = value % 5 # calculating remainder
if value < 38:
final_grade.append(value)
elif reminder >= 3: ... | def round_off(ls2):
final_grade = []
for value in ls2:
reminder = value % 5
if value < 38:
final_grade.append(value)
elif reminder >= 3:
value += 5 - reminder
final_grade.append(value)
else:
final_grade.append(value)
return fina... |
"""
Code used for the 'Singly linked list' class.
"""
class Node:
"Represents a single linked node."
def __init__(self, data, next = None):
self.data = data
self.next = None
def __str__(self):
"String representation of the node data."
return str(self.data)
def __repr_... | """
Code used for the 'Singly linked list' class.
"""
class Node:
"""Represents a single linked node."""
def __init__(self, data, next=None):
self.data = data
self.next = None
def __str__(self):
"""String representation of the node data."""
return str(self.data)
def _... |
n,m = map(int,input().split())
rows = [input() for _ in range(n)]
k = int(input())
for row in sorted(rows, key=lambda row: int(row.split()[k])):
print(row)
| (n, m) = map(int, input().split())
rows = [input() for _ in range(n)]
k = int(input())
for row in sorted(rows, key=lambda row: int(row.split()[k])):
print(row) |
def func_header(funcname):
print('\t.global %s' % funcname)
print('\t.type %s, %%function' % funcname)
print('%s:' % funcname)
def push_stack(reg):
print('\tstr %s, [sp, -0x10]!' % reg)
def pop_stack(reg):
print('\tldr %s, [sp], 0x10' % reg)
def store_stack(value, offset):
print('\tmov... | def func_header(funcname):
print('\t.global %s' % funcname)
print('\t.type %s, %%function' % funcname)
print('%s:' % funcname)
def push_stack(reg):
print('\tstr %s, [sp, -0x10]!' % reg)
def pop_stack(reg):
print('\tldr %s, [sp], 0x10' % reg)
def store_stack(value, offset):
print('\tmov ... |
(10 and 2)[::-5]
(10 and 2)[5]
(10 and 2)(5)
(10 and 2).foo
-(10 and 2)
+(10 and 2)
~(10 and 2)
5 ** (10 and 2)
(10 and 2) ** 5
5 * (10 and 2)
(10 and 2) * 5
5 / (10 and 2)
(10 and 2) / 5
5 // (10 and 2)
(10 and 2) // 5
5 + (10 and 2)
(10 and 2) + 5
(10 and 2) - 5
5 - (10 and 2)
5 >> (10 and 2)
(10 and 2) << 5
... | (10 and 2)[::-5]
(10 and 2)[5]
(10 and 2)(5)
(10 and 2).foo
-(10 and 2)
+(10 and 2)
~(10 and 2)
5 ** (10 and 2)
(10 and 2) ** 5
5 * (10 and 2)
(10 and 2) * 5
5 / (10 and 2)
(10 and 2) / 5
5 // (10 and 2)
(10 and 2) // 5
5 + (10 and 2)
(10 and 2) + 5
(10 and 2) - 5
5 - (10 and 2)
5 >> (10 and 2)
(10 and 2) << 5
5 & (10 ... |
inputA = 277
inputB = 349
score = 0
queueA = []
queueB = []
i = 0
while len(queueA) < (5*(10**6)):
inputA = (inputA*16807)%2147483647
if inputA%4 == 0: queueA.append(inputA)
while len(queueB) < (5*(10**6)):
inputB = (inputB*48271)%2147483647
if inputB%8 == 0: queueB.append(inputB)
for i in range(0,(5*(10**6... | input_a = 277
input_b = 349
score = 0
queue_a = []
queue_b = []
i = 0
while len(queueA) < 5 * 10 ** 6:
input_a = inputA * 16807 % 2147483647
if inputA % 4 == 0:
queueA.append(inputA)
while len(queueB) < 5 * 10 ** 6:
input_b = inputB * 48271 % 2147483647
if inputB % 8 == 0:
queueB.append(... |
# Created by MechAviv
# [Magic Library Checker] | [1032220]
# Ellinia : Magic Library
if "1" not in sm.getQuestEx(25566, "c3"):
sm.setQuestEx(25566, "c3", "1")
sm.chatScript("You search the Magic Library.") | if '1' not in sm.getQuestEx(25566, 'c3'):
sm.setQuestEx(25566, 'c3', '1')
sm.chatScript('You search the Magic Library.') |
"""
Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
"""
x = int(input("Enter a number : "))
if x%2==1:
print("The number is an even number")
else:
print("The number is an odd number")
| """
Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
"""
x = int(input('Enter a number : '))
if x % 2 == 1:
print('The number is an even number')
else:
print('The number is an odd number') |
class Comparable:
def __init__(self, value):
self.value = value
def __eq__(self, other):
other_value = other.value if isinstance(other, Comparable) else other
return self.value == other_value
def __ne__(self, other):
other_value = other.value if isinstance(other, Comparabl... | class Comparable:
def __init__(self, value):
self.value = value
def __eq__(self, other):
other_value = other.value if isinstance(other, Comparable) else other
return self.value == other_value
def __ne__(self, other):
other_value = other.value if isinstance(other, Comparabl... |
def DecodeToFile(osufile, newfilename, SVLines: list):
with open(newfilename, "w+") as f:
old = open(osufile, "r")
old = old.readlines()
old_TotimingPoints = old[:old.index("[TimingPoints]\n") + 1]
old_afterTimingPoints = old[old.index("[TimingPoints]\n") + 1:]
all_file = old... | def decode_to_file(osufile, newfilename, SVLines: list):
with open(newfilename, 'w+') as f:
old = open(osufile, 'r')
old = old.readlines()
old__totiming_points = old[:old.index('[TimingPoints]\n') + 1]
old_after_timing_points = old[old.index('[TimingPoints]\n') + 1:]
all_file... |
#Program for a Function that takes a list of words and returns the length of the longest one.
def longest_word(list): #define a function which takes list as a parameter
longest=0
for words in list: #l... | def longest_word(list):
longest = 0
for words in list:
if len(words) > longest:
longest = len(words)
lword = words
return lword
w = ['Entertainment', 'entire', 'Elephant', 'inconsequential']
print('Longest word is', longest_word(w), 'with', len(longest_word(w)), 'letters.') |
def print_a_string():
my_string = "hello world"
print(my_string)
def print_a_number():
my_number = 9
print(my_number)
# my logic starts here
if __name__ == "__main__":
print_a_string()
print_a_number()
print("all done...bye-bye") | def print_a_string():
my_string = 'hello world'
print(my_string)
def print_a_number():
my_number = 9
print(my_number)
if __name__ == '__main__':
print_a_string()
print_a_number()
print('all done...bye-bye') |
def hms2dec(h,m,s):
return 15*(h + (m/60) + (s/3600))
def dms2dec(d,m,s):
if d>=0:
return (d + (m/60) + (s/3600))
return (d - (m/60) - (s/3600))
if __name__ == '__main__':
print(hms2dec(23, 12, 6))
print(dms2dec(22, 57, 18))
print(dms2dec(-66, 5, 5.1)) | def hms2dec(h, m, s):
return 15 * (h + m / 60 + s / 3600)
def dms2dec(d, m, s):
if d >= 0:
return d + m / 60 + s / 3600
return d - m / 60 - s / 3600
if __name__ == '__main__':
print(hms2dec(23, 12, 6))
print(dms2dec(22, 57, 18))
print(dms2dec(-66, 5, 5.1)) |
class PossumException(Exception):
"""Base Possum Exception"""
class PipenvPathNotFound(PossumException):
"""Pipenv could not be located"""
class SAMTemplateError(PossumException):
"""There was an error reading the template file"""
| class Possumexception(Exception):
"""Base Possum Exception"""
class Pipenvpathnotfound(PossumException):
"""Pipenv could not be located"""
class Samtemplateerror(PossumException):
"""There was an error reading the template file""" |
no_list = [22,68,90,78,90,88]
def average(x):
#complete the function's body to return the average
length=len(no_list)
return sum(no_list)/length
print(average(no_list))
| no_list = [22, 68, 90, 78, 90, 88]
def average(x):
length = len(no_list)
return sum(no_list) / length
print(average(no_list)) |
__lname__ = "yass"
__uname__ = "YASS"
__acronym__ = "Yet Another Subdomainer Software"
__version__ = "0.8.0"
__author__ = "Francesco Marano (@mrnfrancesco)"
__author_email__ = "francesco.mrn24@gmail.com"
__source_url__ = "https://github.com/mrnfrancesco/yass"
| __lname__ = 'yass'
__uname__ = 'YASS'
__acronym__ = 'Yet Another Subdomainer Software'
__version__ = '0.8.0'
__author__ = 'Francesco Marano (@mrnfrancesco)'
__author_email__ = 'francesco.mrn24@gmail.com'
__source_url__ = 'https://github.com/mrnfrancesco/yass' |
end = 1000
total = 0
for x in range(1,end):
if x % 15 == 0:
total = total + x
print(x)
elif x % 5 == 0:
total = total + x
print(x)
elif x % 3 == 0:
total = total + x
print(x)
print(f"total = {total}") | end = 1000
total = 0
for x in range(1, end):
if x % 15 == 0:
total = total + x
print(x)
elif x % 5 == 0:
total = total + x
print(x)
elif x % 3 == 0:
total = total + x
print(x)
print(f'total = {total}') |
# Section 3-16
# Question: How do we find the sum of the digits of a positive integer using recursion?
# Step 1: The recursive case
# Add the current digit to a total
# Step 2: The Base Condition
# If there are no more digits, return the total
# Step 3: The unintended cases
# If the input is not a positive integer... | test = 349587
expected = 3 + 4 + 9 + 5 + 8 + 7
def sum_digits(number):
assert number >= 0 and int(number) == number, 'Input must be a nonnegative integer.'
return 0 if number == 0 else number % 10 + sum_digits(int(number / 10))
outcome = sum_digits(test)
print('Expected: ', expected)
print('Outcome: ', outcome... |
# -*- coding: utf-8 -*-
"""This module contains two variables which will store all defined nodes models and instances
"""
model_store = {}
node_store = {}
| """This module contains two variables which will store all defined nodes models and instances
"""
model_store = {}
node_store = {} |
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l) / 2;
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
... | def binary_search(arr, l, r, x):
while l <= r:
mid = l + (r - l) / 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return -1 |
# Segment tree
class SegmentTree:
def __init__(self, data):
size = len(data)
t = 1
while t < size:
t <<= 1
offset = t - 1
index = [0] * (t * 2 - 1)
index[offset:offset + size] = range(size)
for i in range(offset - 1, -1, -1):
x = index[... | class Segmenttree:
def __init__(self, data):
size = len(data)
t = 1
while t < size:
t <<= 1
offset = t - 1
index = [0] * (t * 2 - 1)
index[offset:offset + size] = range(size)
for i in range(offset - 1, -1, -1):
x = index[i * 2 + 1]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.