content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Copyright (C) 2019-2021 Data Ductus AB
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
... | class Bytesview:
_bytes: bytes = None
_pre = None
_start: int = 0
_end: int = 0
_eof: bool = False
def __init__(self, b, n=None, start=None, pre=None, closed=False):
self._bytes = b
self._pre = pre
self._start = 0 if start is None else start
if n is not None:
... |
# Find the sum pair who is divisible by a certain integer in an arry
# You modulo from the start and compute the complement and
# store the modulo that way when u see a complement that matches
# the modulo hashmap you add to the counter
# O(n)
# O(k)
def divisibleSumPairs(n, k, arr):
hMap = dict()
counter =... | def divisible_sum_pairs(n, k, arr):
h_map = dict()
counter = 0
for item in arr:
modu = item % k
comp = k - modu
if comp in hMap.keys():
counter += hMap[comp]
if modu in hMap.keys():
hMap[modu] += 1
else:
hMap.setdefault(modu, 1)
... |
s = input()
k = int(input())
subst = list(s)
for i in range(2, k + 1):
for j in range(len(s) - i + 1):
subst.append(s[j:j + i])
subst = sorted(list(set(subst)))
print(subst[k - 1]) | s = input()
k = int(input())
subst = list(s)
for i in range(2, k + 1):
for j in range(len(s) - i + 1):
subst.append(s[j:j + i])
subst = sorted(list(set(subst)))
print(subst[k - 1]) |
#
# PySNMP MIB module ASCEND-MIBMGW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBMGW-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:27:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration')
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constra... |
# This object is for creating a daily report, indicating the progress of the
# currently running Time Lapse. The file structure is plain text with some
# slight formatting.
# Every section/seperator will be represented by '-' characters on both sides
# of the given text.
# Every alert will be represented similarly to t... | class Report:
file_name = 'daily_report.txt'
file = open(fileName, 'w')
line_length = 80
def section_header(self, header: str):
length = len(header) + 2
number_of_indicators = (self.line_length - length) // 2
separator = '-' * number_of_indicators
line = '{0} {1} {0}'.fo... |
# python_version >= '3.5'
#: Okay
async def test():
good = 1
#: N806
async def f():
async with expr as ASYNC_VAR:
pass
| async def test():
good = 1
async def f():
async with expr as async_var:
pass |
# birth_year=input("please enter your bith year: ")
curr=2021
# age=curr-int(birth_year)
# print("you are "+ str(age)+" years old)")
# f_name=input("enter your name: ")
# l_name=input("enter your last name: ")
# print(f"hello {l_name} {f_name} you are {age} years old)")
# user_data=input(" Enter Ur name , last na... | curr = 2021 |
# -*- coding: utf-8 -*-
class HostsNotFound(OSError):
pass
class InvalidFormat(ValueError):
pass
| class Hostsnotfound(OSError):
pass
class Invalidformat(ValueError):
pass |
def printall(*args, **kwargs):
# Handle the args values
print('args:')
for arg in args:
print(arg)
print('-' * 20)
# Handle the key value pairs in kwargs
print('kwargs:')
for arg in kwargs.values():
print(arg)
printall(1, 2, 3, a="John", b="Hunt")
| def printall(*args, **kwargs):
print('args:')
for arg in args:
print(arg)
print('-' * 20)
print('kwargs:')
for arg in kwargs.values():
print(arg)
printall(1, 2, 3, a='John', b='Hunt') |
P,K=map(int,input().split())
L=[i for i in range(K)]
k=[]
L[0]=-1
L[1]=-1
for i in range(K):
if L[i] == i:
k.append(i)
for j in range(i+i,K,i):
L[j]=-1
for i in k:
if P%i == 0:
print("BAD",i)
break
else:
print("GOOD")
| (p, k) = map(int, input().split())
l = [i for i in range(K)]
k = []
L[0] = -1
L[1] = -1
for i in range(K):
if L[i] == i:
k.append(i)
for j in range(i + i, K, i):
L[j] = -1
for i in k:
if P % i == 0:
print('BAD', i)
break
else:
print('GOOD') |
# Photon/energy
g_eV_per_Hartree = 27.211396641308
g_omega_IR = 0.0569614*g_eV_per_Hartree
# Plot parameters
g_linewidth = 2
g_fontsize = 20
g_colors_list = ['royalblue', 'crimson', 'lawngreen', 'violet', 'orange', 'black', 'deepskyblue', 'pink', 'lightseagreen']
g_linestyles = ["solid",
"dotted",
... | g_e_v_per__hartree = 27.211396641308
g_omega_ir = 0.0569614 * g_eV_per_Hartree
g_linewidth = 2
g_fontsize = 20
g_colors_list = ['royalblue', 'crimson', 'lawngreen', 'violet', 'orange', 'black', 'deepskyblue', 'pink', 'lightseagreen']
g_linestyles = ['solid', 'dotted', 'dashdot', 'dashed', (0, (3, 1, 1, 1, 1, 1))] |
# work dir
root_workdir = 'workdir'
# seed
seed = 0
# 1. logging
logger = dict(
handlers=(
dict(type='StreamHandler', level='INFO'),
# dict(type='FileHandler', level='INFO'),
),
)
# 2. data
test_cfg = dict(
scales=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],
bias=[0.5, 0.25, 0.0, -0.25, -0.5, -... | root_workdir = 'workdir'
seed = 0
logger = dict(handlers=(dict(type='StreamHandler', level='INFO'),))
test_cfg = dict(scales=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75], bias=[0.5, 0.25, 0.0, -0.25, -0.5, -0.75], flip=True)
img_norm_cfg = dict(mean=(123.675, 116.28, 103.53), std=(58.395, 57.12, 57.375))
ignore_label = 255
datase... |
#!/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Reverses a user provided string. #
# Program Author : Happi ... | def get_user_data(input_mess: str):
is_valid = False
user_data = ''
while is_valid is not True:
try:
user_data = input(input_mess)
if len(user_data) == 0:
raise value_error('Please provide some data')
is_valid = True
except ValueError as ve... |
# from OME
def get_headers_csv(file_dir):
f = open(file_dir)
header_str = ""
for line in f.readlines():
header_str = line
break
header = []
start_q = False
start_idx = 0
print("header_string: "+header_str)
for idx, ch in enumerate(header_str):
if ch == '"' and ... | def get_headers_csv(file_dir):
f = open(file_dir)
header_str = ''
for line in f.readlines():
header_str = line
break
header = []
start_q = False
start_idx = 0
print('header_string: ' + header_str)
for (idx, ch) in enumerate(header_str):
if ch == '"' and start_q ==... |
class Dafsm(object):
# Constructor
def __init__(self, name):
self.name = name
def trigger(self, fname, cntx):
raise NotImplementedError()
def call(self, fname, cntx):
raise NotImplementedError()
def queuecall(self, cntx):
raise NotImplementedError()
def switc... | class Dafsm(object):
def __init__(self, name):
self.name = name
def trigger(self, fname, cntx):
raise not_implemented_error()
def call(self, fname, cntx):
raise not_implemented_error()
def queuecall(self, cntx):
raise not_implemented_error()
def switch(self, cntx... |
RED = "0;31"
GREEN = "0;32"
YELLOW = "0;33"
BLUE = "0;34"
GRAY = "0;37"
def _ansicolorize(text, color_code):
return "\033[{}m{}\033[0m".format(color_code, text)
def color_print(text, color_code):
if color_code:
print(_ansicolorize(text, color_code))
else:
print(text)
| red = '0;31'
green = '0;32'
yellow = '0;33'
blue = '0;34'
gray = '0;37'
def _ansicolorize(text, color_code):
return '\x1b[{}m{}\x1b[0m'.format(color_code, text)
def color_print(text, color_code):
if color_code:
print(_ansicolorize(text, color_code))
else:
print(text) |
expected_output = {
"version": {
"version_short": "03.04",
"platform": "Catalyst 4500 L3 Switch",
"version": "03.04.06.SG",
"image_id": "cat4500e-UNIVERSALK9-M",
"os": "IOS-XE",
"image_type": "production image",
"compiled_date": "Mon 04-May-15 02:44",
... | expected_output = {'version': {'version_short': '03.04', 'platform': 'Catalyst 4500 L3 Switch', 'version': '03.04.06.SG', 'image_id': 'cat4500e-UNIVERSALK9-M', 'os': 'IOS-XE', 'image_type': 'production image', 'compiled_date': 'Mon 04-May-15 02:44', 'compiled_by': 'prod_rel_team', 'rom': '15.0(1r)SG10', 'hostname': 'sa... |
class Executions(object):
def __init__(self):
self.executions = []
def append(self, execution):
self.executions.append(execution)
def shares_traded(self):
return sum([abs(item.qty) for item in self.executions])
def __len__(self):
return len(self.executions)
| class Executions(object):
def __init__(self):
self.executions = []
def append(self, execution):
self.executions.append(execution)
def shares_traded(self):
return sum([abs(item.qty) for item in self.executions])
def __len__(self):
return len(self.executions) |
# Copyright (c) 2018, Red Hat, Inc.
# 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 requir... | name = 'ember-csi.io'
reverse_name = 'io.ember-csi'
endpoint = '[::]:50051'
mode = 'all'
persistence_cfg = {'storage': 'crd', 'namespace': 'default'}
root_helper = 'sudo'
state_path = '/var/lib/ember-csi'
vol_binds_dir = '$state_path/vols'
locks_dir = '$state_path/locks'
request_multipath = False
workers = 30
enable_pr... |
# Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7... | largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num == 'done':
break
else:
try:
n = int(num)
if largest is None:
largest = n
elif largest < n:
largest = n
if smallest is None:
... |
def bogota_to_mio(bogota_id):
lookup = {
0: 0, # ... background
1: 1, # articulated-truck - articulated-truck
2: 2, # bicycle
3: 3, # bus
4: 4, # car
5: 5, # motorcycle
6: 4, # suv-car
7: 4, # taxi-car
8: 8, # person/pedest... | def bogota_to_mio(bogota_id):
lookup = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 4, 7: 4, 8: 8, 9: 9, 10: 10, 11: 11}
return lookup[bogota_id] |
# Input: x = 123
# Output: 321
# Input: x = -123
# Output: -321
class Solution:
def reverse(self, x: int) -> int:
string = str(abs(x))
reversed = int(string[::-1])
if reversed > 2147483647:
return 0
elif x > 0:
return reversed
return -1 * reversed... | class Solution:
def reverse(self, x: int) -> int:
string = str(abs(x))
reversed = int(string[::-1])
if reversed > 2147483647:
return 0
elif x > 0:
return reversed
return -1 * reversed |
primes = []
def is_prime(number):
for i in primes:
if number % i == 0:
return False
return True
def get_prime(target):
i = 1
while(len(primes)< target):
i += 1
if is_prime(i):
primes.append(i)
return primes[-1]
print(get_prime(10001))
| primes = []
def is_prime(number):
for i in primes:
if number % i == 0:
return False
return True
def get_prime(target):
i = 1
while len(primes) < target:
i += 1
if is_prime(i):
primes.append(i)
return primes[-1]
print(get_prime(10001)) |
num=int(input("Enter a number to be reversed: "))
print("The number in reversed order is: ")
for i in range(len(str(num))):
m=num%10
print(m,end='')
num//=10 | num = int(input('Enter a number to be reversed: '))
print('The number in reversed order is: ')
for i in range(len(str(num))):
m = num % 10
print(m, end='')
num //= 10 |
#
# @lc app=leetcode id=320 lang=python3
#
# [320] Generalized Abbreviation
#
# @lc code=start
class Solution:
def generateAbbreviations(self, word: str):
if not word:
return [""]
ans = ['']
for i in range(len(word)):
temp = []
for item in ans:
... | class Solution:
def generate_abbreviations(self, word: str):
if not word:
return ['']
ans = ['']
for i in range(len(word)):
temp = []
for item in ans:
temp.append(item + word[i])
if not item:
temp.append... |
class Tile:
def __init__(self, x, y, tile_type):
self.x = x
self.y = y
self.tile_type = tile_type
| class Tile:
def __init__(self, x, y, tile_type):
self.x = x
self.y = y
self.tile_type = tile_type |
# Define the rotors
# Each value represents the amount that must be added
# to get the output value when feeding input into that index.
# Index values must be adjusted to account for rotation.
rotors = [[1, 2, 4, 7, 1, 9, 2, 0, 1, 3],
[0, 2, 3, 9, 2, 4, 5, 7, 0, 8],
[5, 8, 9, 4, 9, 3, 4, 5, 6, 7],
... | rotors = [[1, 2, 4, 7, 1, 9, 2, 0, 1, 3], [0, 2, 3, 9, 2, 4, 5, 7, 0, 8], [5, 8, 9, 4, 9, 3, 4, 5, 6, 7], [1, 5, 3, 9, 5, 5, 1, 7, 5, 9]]
inverse_rotors = [[3, 9, 7, 8, 1, 9, 6, 0, 8, 9], [0, 5, 1, 8, 3, 7, 8, 2, 0, 6], [6, 1, 5, 1, 4, 5, 3, 6, 7, 2], [5, 9, 1, 5, 3, 7, 5, 9, 1, 5]]
reflector = [3, 5, 6, 7, 1, 9, 5, 2,... |
class stack(object):
def __init__(self):
self.stk = [] #initializing an array as a stack
def is_empty(self):
return self.stk == []
def push(self, item):
self.stk.append(data)
def pop(self):
if self.is_empty():
print("the stack is empty")
... | class Stack(object):
def __init__(self):
self.stk = []
def is_empty(self):
return self.stk == []
def push(self, item):
self.stk.append(data)
def pop(self):
if self.is_empty():
print('the stack is empty')
else:
self.stk.pop()
def si... |
n=int(input())
coin=[]
for i in range(n):
a,b=map(int,input().split())
coin.append([min(a,b),max(a,b)])
print(len(list(map(list,set(map(tuple,coin)))))) | n = int(input())
coin = []
for i in range(n):
(a, b) = map(int, input().split())
coin.append([min(a, b), max(a, b)])
print(len(list(map(list, set(map(tuple, coin)))))) |
class Node():
def __init__(self, val, children: list['Node'] = []) -> None:
self.val = val
self.children = children
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
four = Node(4)
five = Node(5)
six = Node(6)
seven = Node(7)
two = Node(2, [four, five])... | class Node:
def __init__(self, val, children: list['Node']=[]) -> None:
self.val = val
self.children = children
four = node(4)
five = node(5)
six = node(6)
seven = node(7)
two = node(2, [four, five])
three = node(3, [six, seven])
one = node(1, [two, three])
basic_tree = one |
# -*- coding: utf-8 -*-
description = 'sps devices'
group = 'lowlevel'
tangohost = 'phys.spheres.frm2'
profibus_base = 'tango://%s:10000/spheres/profibus/sps_' % tangohost
profinet_base = 'tango://%s:10000/spheres/profinet/back_' % tangohost
analogs = dict(
rpower = dict(desc='reactor power', unit='MW', low=Fal... | description = 'sps devices'
group = 'lowlevel'
tangohost = 'phys.spheres.frm2'
profibus_base = 'tango://%s:10000/spheres/profibus/sps_' % tangohost
profinet_base = 'tango://%s:10000/spheres/profinet/back_' % tangohost
analogs = dict(rpower=dict(desc='reactor power', unit='MW', low=False), chop_vib1=dict(desc='chopper p... |
# This is the solution for Sorting > NumberOfDiscIntersections
#
# This is marked as RESPECTABLE difficulty
class Disc():
def __init__(self, low_x, high_x):
self.low_x = low_x
self.high_x = high_x
def index_less_than(sortedDiscList, i, start, last):
mid = start + (last - start) // 2
if las... | class Disc:
def __init__(self, low_x, high_x):
self.low_x = low_x
self.high_x = high_x
def index_less_than(sortedDiscList, i, start, last):
mid = start + (last - start) // 2
if last <= start and sortedDiscList[mid].low_x > i:
return mid - 1
elif last <= start:
return mi... |
def main():
print(summation(100)-multiplication(100))
def summation(n):
res = 0
for i in range(1, n+1):
res += i
return res*res
def multiplication(n):
res = 0
for i in range(1, n+1):
res += i * i
return res
| def main():
print(summation(100) - multiplication(100))
def summation(n):
res = 0
for i in range(1, n + 1):
res += i
return res * res
def multiplication(n):
res = 0
for i in range(1, n + 1):
res += i * i
return res |
N = int(input())
towers = 0
last = 0
sequence = [int(x) for x in input().split()]
for x in sequence:
if (x > last):
towers += 1
last = x
print(towers)
| n = int(input())
towers = 0
last = 0
sequence = [int(x) for x in input().split()]
for x in sequence:
if x > last:
towers += 1
last = x
print(towers) |
# Available constants:
# They are to assign a type to a field with a value null.
# NULL_BOOLEAN, NULL_CHAR, NULL_BYTE, NULL_SHORT, NULL_INTEGER, NULL_LONG
# NULL_FLOATNULL_DOUBLE, NULL_DATE, NULL_DATETIME, NULL_TIME, NULL_DECIMAL
# NULL_BYTE_ARRAY, NULL_STRING, NULL_LIST, NULL_MAP
#
# Available Objects:
#
# ... | for record in records:
try:
output.write(record)
except Exception as e:
error.write(record, str(e)) |
# LCM 33
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
if n == 0:
return -1
if n == 1:
return 0 if nums[0] == target else -1
# apply modified binary search
low = 0
high = n-1
while low <= high:
... | class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
if n == 0:
return -1
if n == 1:
return 0 if nums[0] == target else -1
low = 0
high = n - 1
while low <= high:
mid = (low + high) // 2
... |
# -*- coding: utf-8 -*-
__name__ = 'google_streetview'
__author__ = 'Richard Wen'
__email__ = 'rrwen.dev@gmail.com'
__version__ = '1.2.9'
__license__ = 'MIT'
__description__ = 'A command line tool and module for Google Street View Image API.'
__long_description_content_type__='text/markdown'
__keywords__ = [
... | __name__ = 'google_streetview'
__author__ = 'Richard Wen'
__email__ = 'rrwen.dev@gmail.com'
__version__ = '1.2.9'
__license__ = 'MIT'
__description__ = 'A command line tool and module for Google Street View Image API.'
__long_description_content_type__ = 'text/markdown'
__keywords__ = ['google', 'api', 'street', 'view'... |
def print_sequence(n):
for i in range(1, n+1):
print(i, end="")
if __name__ == '__main__':
n = int(input("Enter number :"))
print_sequence(n)
| def print_sequence(n):
for i in range(1, n + 1):
print(i, end='')
if __name__ == '__main__':
n = int(input('Enter number :'))
print_sequence(n) |
class Hello(object):
@staticmethod
def hello_w() -> str:
return f"hello"
| class Hello(object):
@staticmethod
def hello_w() -> str:
return f'hello' |
class NodoCola:
def __init__(self):
self.__numero = 0
self.__siguiente = None
def getNumero(self):
return self.__numero
def setNumero(self, numero):
self.__numero = numero
def getSiguiente(self):
return self.__siguiente
def setSiguiente(self, siguiente):
... | class Nodocola:
def __init__(self):
self.__numero = 0
self.__siguiente = None
def get_numero(self):
return self.__numero
def set_numero(self, numero):
self.__numero = numero
def get_siguiente(self):
return self.__siguiente
def set_siguiente(self, siguient... |
# Copyright (c) 2016 Cloudbase Solutions Srl
#
# 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 ... | migration_status_running = 'RUNNING'
migration_status_completed = 'COMPLETED'
migration_status_error = 'ERROR'
task_status_pending = 'PENDING'
task_status_running = 'RUNNING'
task_status_completed = 'COMPLETED'
task_status_error = 'ERROR'
task_status_canceled = 'CANCELED'
task_type_export_instance = 'EXPORT_INSTANCE'
t... |
node = S(input, "application/json")
oldValue = node.prop("order")
jsonObject = {
"name": "test",
"comment": "42!"
}
node.prop("order", jsonObject)
newValue = node.prop("order") | node = s(input, 'application/json')
old_value = node.prop('order')
json_object = {'name': 'test', 'comment': '42!'}
node.prop('order', jsonObject)
new_value = node.prop('order') |
class Button:
def __init__(self, fn):
self.fn = fn
def click(self):
self.fn()
def test(string):
print(string)
fn = lambda: test('Pesho')
button_1 = Button(fn)
button_1.click()
button_1.click()
button_2 = Button(lambda: test('Toto'))
button_2.click()
| class Button:
def __init__(self, fn):
self.fn = fn
def click(self):
self.fn()
def test(string):
print(string)
fn = lambda : test('Pesho')
button_1 = button(fn)
button_1.click()
button_1.click()
button_2 = button(lambda : test('Toto'))
button_2.click() |
# Contributed by @Hinal-Srivastava
#Get Inputs from User
def get_input():
a = int(input("Enter 1st number: "))
b = int(input("Enter 2nd number: "))
return a, b
#Error Message for IndexOutOfBoundException
def error():
print("Invalid Entry")
#Addition
def add():
x, y = get_input()
return x + y
... | def get_input():
a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
return (a, b)
def error():
print('Invalid Entry')
def add():
(x, y) = get_input()
return x + y
def subtract():
(x, y) = get_input()
return x - y
def multiply():
(x, y) = get_input()
ret... |
# -*- coding: utf-8 -*-
n = int(input())
for _ in range(n):
A, B = input().split()
if A[len(A)-len(B):] == B:
print('encaixa')
else:
print('nao encaixa')
| n = int(input())
for _ in range(n):
(a, b) = input().split()
if A[len(A) - len(B):] == B:
print('encaixa')
else:
print('nao encaixa') |
class TemplateFileType:
def __init__(self):
pass
StandardPage = 0
WikiPage = 1
FormPage = 2
| class Templatefiletype:
def __init__(self):
pass
standard_page = 0
wiki_page = 1
form_page = 2 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Advent of Code 2018, Day 00 - Part 0
# https://github.com/vesche
#
def main():
with open("day00_input.txt") as f:
data = f.read()
if __name__ == "__main__":
main()
| def main():
with open('day00_input.txt') as f:
data = f.read()
if __name__ == '__main__':
main() |
#!/usr/local/bin/python
# Code Fights Range Bit Count (Core) Problem
def rangeBitCount(a, b):
return (''.join([bin(n) for n in range(a, b + 1)])).count('1')
def main():
tests = [
[2, 7, 11],
[0, 1, 1],
[1, 10, 17],
[8, 9, 3],
[9, 10, 4]
]
for t in tests:
... | def range_bit_count(a, b):
return ''.join([bin(n) for n in range(a, b + 1)]).count('1')
def main():
tests = [[2, 7, 11], [0, 1, 1], [1, 10, 17], [8, 9, 3], [9, 10, 4]]
for t in tests:
res = range_bit_count(t[0], t[1])
if t[2] == res:
print('PASSED: rangeBitCount({}, {}) returned... |
# -*- coding: utf-8 -*-
# Copyright 2019 Carsten Blank
#
# 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 la... | result = {'experiment': {'qobj': {'qobj_id': '2019-06-07T08:24:07.836571-exp-sim-regular', 'config': {'shots': 8192, 'memory_slots': 2, 'max_credits': 315, 'memory': False, 'n_qubits': 5}, 'experiments': [{'instructions': [{'name': 'u2', 'params': [0.0, 3.141592653589793], 'texparams': ['0', '\\pi'], 'qubits': [0], 'me... |
# Time: O(n) | Space: O(d) is depth
def productSum(array, multiplier = 1):
sum = 0
for element in array:
if type(element) is list:
sum += productSum(element, multiplier + 1)
else:
sum += element
return sum * multiplier | def product_sum(array, multiplier=1):
sum = 0
for element in array:
if type(element) is list:
sum += product_sum(element, multiplier + 1)
else:
sum += element
return sum * multiplier |
input()
string = input()
result = string[0]
lastChar = string[0]
for i in range(len(string)):
if string[i] != lastChar:
result += string[i]
lastChar = string[i]
print(len(string) - len(result)) | input()
string = input()
result = string[0]
last_char = string[0]
for i in range(len(string)):
if string[i] != lastChar:
result += string[i]
last_char = string[i]
print(len(string) - len(result)) |
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda letter: letter.replace("X", ""), garbled)
print(message)
| garbled = 'IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX'
message = filter(lambda letter: letter.replace('X', ''), garbled)
print(message) |
N = int(input('Digite um numero:'))
a = N - 1
s = N + 1
#print('analisando o valor {} , seu antecessor e {} e o sucessor e {} '.format(N, a, s))
print(f'Analisando o valor {N} , seu antecessor e {a} e o sucessor e {s}')
| n = int(input('Digite um numero:'))
a = N - 1
s = N + 1
print(f'Analisando o valor {N} , seu antecessor e {a} e o sucessor e {s}') |
__version__ = '0.0.8'
__title__ = 'repovisor'
__summary__ = 'A tool for managing many repositories and creating daily reports'
__uri__ = 'https://github.com/gjcooper/repovisor'
__license__ = 'BSD'
__author__ = 'Gavin Cooper'
__email__ = 'gjcooper@gmail.com'
| __version__ = '0.0.8'
__title__ = 'repovisor'
__summary__ = 'A tool for managing many repositories and creating daily reports'
__uri__ = 'https://github.com/gjcooper/repovisor'
__license__ = 'BSD'
__author__ = 'Gavin Cooper'
__email__ = 'gjcooper@gmail.com' |
# This is the main code for the problem! Driver code should be same as present on HackerRank!
def isPalindrome(s):
for idx in range(len(s)//2):
if s[idx] != s[len(s)-idx-1]:
return False
return True
def palindromeIndex(s):
for idx in range((len(s)+1)//2):
if s[idx] != s[len(s)... | def is_palindrome(s):
for idx in range(len(s) // 2):
if s[idx] != s[len(s) - idx - 1]:
return False
return True
def palindrome_index(s):
for idx in range((len(s) + 1) // 2):
if s[idx] != s[len(s) - idx - 1]:
if is_palindrome(s[:idx] + s[idx + 1:]):
re... |
name = 'rextest'
version = '1.3'
def commands():
env.REXTEST_ROOT = '{root}'
env.REXTEST_VERSION = this.version
env.REXTEST_MAJOR_VERSION = this.version.major
# prepend to non-existent var
env.REXTEST_DIRS.prepend('{root}/data')
alias('rextest', 'foobar')
# Copyright 2013-2016 Allan Johns.
#
... | name = 'rextest'
version = '1.3'
def commands():
env.REXTEST_ROOT = '{root}'
env.REXTEST_VERSION = this.version
env.REXTEST_MAJOR_VERSION = this.version.major
env.REXTEST_DIRS.prepend('{root}/data')
alias('rextest', 'foobar') |
# site_no -- Site identification number
# station_nm -- Site name
# site_tp_cd -- Site type
# lat_va -- DMS latitude
# long_va -- DMS longitude
# dec_lat_va -- Decimal latitude
# dec_long_va -- Decimal longitude
# coord_meth_cd -- Latitude-longitude method
# coord_... | streamflow_attributes = ['site_no', 'station_nm', 'site_tp_cd', 'dec_lat_va', 'dec_long_va', 'coord_meth_cd', 'coord_acy_cd', 'coord_datum_cd', 'dec_coord_datum_cd', 'district_cd', 'state_cd', 'county_cd', 'country_cd', 'land_net_ds', 'map_nm', 'map_scale_fc', 'alt_va', 'alt_meth_cd', 'alt_acy_va', 'alt_datum_cd', 'huc... |
# /*
# * Copyright (C) 2019 Atos Spain SA. All rights reserved.
# *
# * This file is part of pCEP.
# *
# * pCEP is free software: you can redistribute it and/or modify it under the
# * terms of the Apache License, Version 2.0 (the License);
# *
# * http://www.apache.org/licenses/LICENSE-2.0
# *
# * The softw... | class Bcolors:
header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m' |
a = 1
done = False
list = [3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19]
while not done:
if a % 10 == 0:
for i in list:
if a % i == 0:
if i == 19:
done = True
print(a)
else:
break
a += 1
| a = 1
done = False
list = [3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19]
while not done:
if a % 10 == 0:
for i in list:
if a % i == 0:
if i == 19:
done = True
print(a)
else:
break
a += 1 |
free = True
node_id = '762'
node_password = '656531'
local_path = ''
code_done = False
| free = True
node_id = '762'
node_password = '656531'
local_path = ''
code_done = False |
class BfsSearchNode:
def __init__(self, position, moves, parent = None, warpHistory = None):
self.parent = parent
self.position = position
self.moves = moves
self.warpHistory = warpHistory or []
def getMinimumSteps(maze, multilevel = False):
startingPoint, endingPoint, warpPoint... | class Bfssearchnode:
def __init__(self, position, moves, parent=None, warpHistory=None):
self.parent = parent
self.position = position
self.moves = moves
self.warpHistory = warpHistory or []
def get_minimum_steps(maze, multilevel=False):
(starting_point, ending_point, warp_poin... |
print('Welcome to the Average Calculator App.')
# get user input
name = input('\nWhat is your name? : ').title().strip()
count = int(input('How many grades would you like to enter? : '))
# get user's grades
grades = []
for i in range(1, count + 1):
grades.append(int(input('Enter grade : ')))
# sort grades and pri... | print('Welcome to the Average Calculator App.')
name = input('\nWhat is your name? : ').title().strip()
count = int(input('How many grades would you like to enter? : '))
grades = []
for i in range(1, count + 1):
grades.append(int(input('Enter grade : ')))
grades.sort(reverse=True)
print('\nGrades highest to lowest:... |
lf=[]
for i in range(2):
l=[int(i) for i in input().strip().split()]
lf.append(l)
print(lf)
for i in lf:
print(i)
| lf = []
for i in range(2):
l = [int(i) for i in input().strip().split()]
lf.append(l)
print(lf)
for i in lf:
print(i) |
class Item():
def __init__(self,value):
self.value = value
self.nxt = None
self.prev = None
def get_nxt(self):
return self.nxt
def get_prev(self):
return self.prev
def get_val(self):
return self.value
def set_nxt(self,nxt_):
self.nxt = nxt_
def set_prev(self,prev_):
self.prev = pre... | class Item:
def __init__(self, value):
self.value = value
self.nxt = None
self.prev = None
def get_nxt(self):
return self.nxt
def get_prev(self):
return self.prev
def get_val(self):
return self.value
def set_nxt(self, nxt_):
self.nxt = nxt... |
class Base:
WINDOW_W = 700
WINDOW_H = 550
GAME_WH = 500
SIZE = 5
FPS = 60
DEBUG = False
COLORS = {
'0': (205, 193, 180),
'2': (238, 228, 218),
'4': (237, 224, 200),
'8': (242, 177, 121),
'16': (245, 149, 99),
'32': (246, 124, 95),
'64'... | class Base:
window_w = 700
window_h = 550
game_wh = 500
size = 5
fps = 60
debug = False
colors = {'0': (205, 193, 180), '2': (238, 228, 218), '4': (237, 224, 200), '8': (242, 177, 121), '16': (245, 149, 99), '32': (246, 124, 95), '64': (246, 94, 59), '128': (237, 207, 114), '256': (237, 204,... |
def is_alt(s):
return helper(s, 0, 1) if s[0] in "aeiou" else helper(s, 1, 0)
def helper(s, n, m):
for i in range(n, len(s), 2):
if s[i] not in "aeiou":
return False
for i in range(m, len(s), 2):
if s[i] in "aeiou":
return False
return True | def is_alt(s):
return helper(s, 0, 1) if s[0] in 'aeiou' else helper(s, 1, 0)
def helper(s, n, m):
for i in range(n, len(s), 2):
if s[i] not in 'aeiou':
return False
for i in range(m, len(s), 2):
if s[i] in 'aeiou':
return False
return True |
print('___')
answers = []
for i in range(2, 10000000):
s = 0
for k in str(i):
s += int(k) ** 5
if i == s:
answers.append(i)
print(answers, sum(answers))
| print('___')
answers = []
for i in range(2, 10000000):
s = 0
for k in str(i):
s += int(k) ** 5
if i == s:
answers.append(i)
print(answers, sum(answers)) |
# your credentials.py should look as follows
USER_TOKEN = 'your facebook user token'
email_address = 'email address to send out menus'
email_password = 'email password'
admin_email = 'admin email to sent error messages'
slack_webhook = 'slack webhook to post to slack'
| user_token = 'your facebook user token'
email_address = 'email address to send out menus'
email_password = 'email password'
admin_email = 'admin email to sent error messages'
slack_webhook = 'slack webhook to post to slack' |
nome = input('Digite o seu nome: ')
print(nome.upper())
print(nome.lower())
nome = nome.split()
primeironome = nome[0]
nome = ''.join(nome)
print('Seu nome tem {} letras'.format(len(nome)))
print('O seu primeiro nome ({}) tem {} letras'.format(primeironome, len(primeironome))) | nome = input('Digite o seu nome: ')
print(nome.upper())
print(nome.lower())
nome = nome.split()
primeironome = nome[0]
nome = ''.join(nome)
print('Seu nome tem {} letras'.format(len(nome)))
print('O seu primeiro nome ({}) tem {} letras'.format(primeironome, len(primeironome))) |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A, B, K):
# write your code in Python 3.6
if K == 0:
print('terrible mistake, someone is trying to divide by 0')
return 0
result = 0
biggyfound = smallyfound = False
upperbonus = ... | def solution(A, B, K):
if K == 0:
print('terrible mistake, someone is trying to divide by 0')
return 0
result = 0
biggyfound = smallyfound = False
upperbonus = lowerbonus = 0
if A % K == 0:
lowerbonus += 1
smally = A
smallyfound = True
if B % K == 0:
... |
#
# PySNMP MIB module TPT-HIGH-AVAIL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-HIGH-AVAIL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:18:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
class Silly:
def __setattr__(self, attr, value):
if attr == "silly" and value == 7:
raise AttributeError("you shall not set 7 for silly")
super().__setattr__(attr, value)
def __getattribute__(self, attr):
if attr == "silly":
return "Just Try and Change Me!"
... | class Silly:
def __setattr__(self, attr, value):
if attr == 'silly' and value == 7:
raise attribute_error('you shall not set 7 for silly')
super().__setattr__(attr, value)
def __getattribute__(self, attr):
if attr == 'silly':
return 'Just Try and Change Me!'
... |
def leiaint(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[31mERRO: Por favor, digite um numero inteiro valido.\033[m ')
continue
except (KeyboardInterrupt):
print('\033[31mUsuario preferiu nao digitar es... | def leiaint(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\x1b[31mERRO: Por favor, digite um numero inteiro valido.\x1b[m ')
continue
except KeyboardInterrupt:
print('\x1b[31mUsuario preferiu nao digitar esse... |
#!/bin/python3
def n2l(n):
return chr((n%26)+65)
def l2n(l):
return (ord(l.upper())-65) % 26
def l2n2ls(l,s=0):
if l.isalpha():
if l.isupper():
return n2l(l2n(l) + s)
else:
return (n2l(l2n(l) + s)).lower()
else:
return l
if __name__ == '__main__':
... | def n2l(n):
return chr(n % 26 + 65)
def l2n(l):
return (ord(l.upper()) - 65) % 26
def l2n2ls(l, s=0):
if l.isalpha():
if l.isupper():
return n2l(l2n(l) + s)
else:
return n2l(l2n(l) + s).lower()
else:
return l
if __name__ == '__main__':
print('A: ', n... |
class CustomException(Exception):
def __init__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args [1])
class DeprecatedException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)... | class Customexception(Exception):
def __init__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args[1])
class Deprecatedexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwar... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
class Matcher:
def __init__(self, routes):
self._routes = routes
def match_request(self, request):
for route in self._routes:
match_dict = {}
rest = request.path
value = True
for typ, data in route.segments:
if typ == 'exact':
... | class Matcher:
def __init__(self, routes):
self._routes = routes
def match_request(self, request):
for route in self._routes:
match_dict = {}
rest = request.path
value = True
for (typ, data) in route.segments:
if typ == 'exact':
... |
# Specs
SPECS_STORAGE_PATH = 'specs/'
SPECS_FILE_NAME = 'specs.txt'
PHONE_LIST = 'phone_list.txt'
GSM_ARENA_BASE_URL = "https://www.gsmarena.com/"
# Reviews
REVIEW_STORAGE_PATH = 'reviews/'
REVIEWS_FILE_NAME = 'reviews.txt'
AMAZON_BASE_URL = 'https://www.amazon.com/'
AMAZON_REVIEW_URL_1 = '/ref=cm_cr_arp_d_paging_btm?i... | specs_storage_path = 'specs/'
specs_file_name = 'specs.txt'
phone_list = 'phone_list.txt'
gsm_arena_base_url = 'https://www.gsmarena.com/'
review_storage_path = 'reviews/'
reviews_file_name = 'reviews.txt'
amazon_base_url = 'https://www.amazon.com/'
amazon_review_url_1 = '/ref=cm_cr_arp_d_paging_btm?ie=UTF8&reviewerTyp... |
{
"targets": [
{
"target_name": "roaring",
"default_configuration": "Release",
"cflags_cc": ["-O3", "-std=c++14"],
"sources": [
"src/cpp/v8utils/v8utils.cpp",
"src/cpp/RoaringBitmap32.cpp"
],
"conditions"... | {'targets': [{'target_name': 'roaring', 'default_configuration': 'Release', 'cflags_cc': ['-O3', '-std=c++14'], 'sources': ['src/cpp/v8utils/v8utils.cpp', 'src/cpp/RoaringBitmap32.cpp'], 'conditions': [["OS=='win'", {'configurations': {'Release': {'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': ['/std:c++la... |
# based on: https://github.com/tigertv/secretpy/blob/master/secretpy/ciphers/columnar_transposition.py
class cipher_columnar_transposition:
def __dec(self, alphabet, key, text):
chars = [alphabets.get_index_in_alphabet(char, alphabet)
for char in key]
keyorder = sorted(enumerate(ch... | class Cipher_Columnar_Transposition:
def __dec(self, alphabet, key, text):
chars = [alphabets.get_index_in_alphabet(char, alphabet) for char in key]
keyorder = sorted(enumerate(chars), key=lambda x: x[1])
ret = u''
rows = int(len(text) / len(key))
cols = [0] * len(key)
... |
# Copyright (c) 2009 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.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'../../build/common.gypi',
'../../build/version.gypi',
],
'targets': [
{
... | {'variables': {'chromium_code': 1}, 'includes': ['../../build/common.gypi', '../../build/version.gypi'], 'targets': [{'target_name': 'installer', 'type': 'none', 'dependencies': ['../../converter/converter.gyp:o3dConverter', '../../breakpad/breakpad.gyp:reporter', '../../documentation/documentation.gyp:*', '../../plugi... |
# Title: Construct Binary Tree from Preorder and Inorder Traversal
# Runtime: 68 ms
# Memory: 18.1 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Time Complexity: O(n)
# Space Complexity: O(n)
class... | class Solution:
def get_mapping(self, inorder: List[int]) -> dict:
mapping = {}
for index in range(len(inorder)):
num = inorder[index]
mapping[num] = index
return mapping
def build_tree_recursive(self, preorder: List[int], mapping: dict, left: int, right: int) -... |
class Config:
# AWS Information
ACCESS_KEY = ""
SECRET_KEY = ""
INSTANCE_ID = ""
EC2_REGION = ""
# SSH Key Path
SSH_KEY_FILE_NAME = ""
# Login Password
SERVER_PASSWORD = "1"
| class Config:
access_key = ''
secret_key = ''
instance_id = ''
ec2_region = ''
ssh_key_file_name = ''
server_password = '1' |
Patk = 15
Pdef = 12
Php = 25
Pgold = 250
choices = [ ' a) Fight like a champion.',
' b) Run like a coward.',
' c) Analyze the situation first.',
' d) Attempt to heal.'
]
wit_access_token = 'GIKG4P7FJTE44GV3U6YPUJGCRY7AYPDH'
| patk = 15
pdef = 12
php = 25
pgold = 250
choices = [' a) Fight like a champion.', ' b) Run like a coward.', ' c) Analyze the situation first.', ' d) Attempt to heal.']
wit_access_token = 'GIKG4P7FJTE44GV3U6YPUJGCRY7AYPDH' |
largest = None
smallest = None
def Maximum(largest, num):
if largest is None:
largest = num
elif largest < num:
largest = num
return largest
def Minimum(smallest, num):
if smallest is None:
smallest = num
elif smallest > num:
smallest = num
re... | largest = None
smallest = None
def maximum(largest, num):
if largest is None:
largest = num
elif largest < num:
largest = num
return largest
def minimum(smallest, num):
if smallest is None:
smallest = num
elif smallest > num:
smallest = num
return smallest
while... |
print('''
A string is said to be palindrome if it reads
the same backward as forward. For e.g. "AKA" string
is a palindrome because if we try to read it from
backward, it is same as forward. One of the approach
to check this is iterate through the string till
middle of string and compare a character from bac... | print('\nA string is said to be palindrome if it reads \nthe same backward as forward. For e.g. "AKA" string \nis a palindrome because if we try to read it from \nbackward, it is same as forward. One of the approach \nto check this is iterate through the string till \nmiddle of string and compare a character from back ... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"format_cookie_str": "01_Advanced_Request.ipynb",
"get_children": "01_Advanced_Request.ipynb",
"get_class": "01_Advanced_Request.ipynb",
"get_all_class": "01_Advanced_Request.ipynb"... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'format_cookie_str': '01_Advanced_Request.ipynb', 'get_children': '01_Advanced_Request.ipynb', 'get_class': '01_Advanced_Request.ipynb', 'get_all_class': '01_Advanced_Request.ipynb', 'get_class_count': '01_Advanced_Request.ipynb', 'is_content_list':... |
# -*- coding: utf-8 -*-
questoes = int(input())
respostas = input()
gabarito = input()
acertos = 0
for i in range(questoes):
if respostas[i] == gabarito[i]:
acertos += 1
print(acertos)
| questoes = int(input())
respostas = input()
gabarito = input()
acertos = 0
for i in range(questoes):
if respostas[i] == gabarito[i]:
acertos += 1
print(acertos) |
#!/usr/bin/python
# Author: Wayne Keenan
# email: wayne@thebubbleworks.com
# Twitter: https://twitter.com/wkeenan
HCIPY_HCI_CMD_STRUCT_HEADER = "<BHB"
HCIPY_HCI_FILTER_STRUCT = "<LLLH"
# HCI ioctl Commands:
HCIDEVUP = 0x400448c9 # 201
HCIDEVDOWN = 0x400448ca # 202
HCIGETDEVINFO = -2147202861 #0x800448d3L # ... | hcipy_hci_cmd_struct_header = '<BHB'
hcipy_hci_filter_struct = '<LLLH'
hcidevup = 1074022601
hcidevdown = 1074022602
hcigetdevinfo = -2147202861
hci_success = 0
hci_oe_user_ended_connection = 19
le_public_address = 0
le_random_address = 1
scan_type_passive = 0
scan_type_active = 1
scan_filter_duplicates = 1
scan_disabl... |
#Adapted from https://github.com/FakeNewsChallenge/fnc-1/blob/master/scorer.py
#Original credit - @bgalbraith
LABELS = ['agree', 'disagree', 'discuss', 'unrelated']
LABELS_RELATED = ['unrelated','related']
RELATED = LABELS[0:3]
def score_submission(gold_labels, test_labels):
score = 0.0
cm = [[0, 0, 0, 0],
... | labels = ['agree', 'disagree', 'discuss', 'unrelated']
labels_related = ['unrelated', 'related']
related = LABELS[0:3]
def score_submission(gold_labels, test_labels):
score = 0.0
cm = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
for (i, (g, t)) in enumerate(zip(gold_labels, test_labels)):
... |
#CODE:
def create_stack():
stack = []
return stack
def peek(stack):
if len(stack) == 0:
return "Underflow"
else:
return stack[-1]
def isEmpty(stack):
if len(stack) == 0:
return True
else:
return False
def push(stack):
element=int(input("Enter the element:"))
#int should be used if we want to a... | def create_stack():
stack = []
return stack
def peek(stack):
if len(stack) == 0:
return 'Underflow'
else:
return stack[-1]
def is_empty(stack):
if len(stack) == 0:
return True
else:
return False
def push(stack):
element = int(input('Enter the element:'))
... |
#GCD
a = int(input("Enter a: "))
b = int(input('Enter b: '))
gcd = 1 #initial gcd
k = 2 #possible gcd
while k <= a and k <= b:
if a%k == 0 and b%k == 0:
gcd = k
k += 1
print(gcd) | a = int(input('Enter a: '))
b = int(input('Enter b: '))
gcd = 1
k = 2
while k <= a and k <= b:
if a % k == 0 and b % k == 0:
gcd = k
k += 1
print(gcd) |
ABCDE = list(map(int, input().split()))
t = []
for i in range(3):
for j in range(i + 1, 4):
for k in range(j + 1, 5):
t.append(ABCDE[i] + ABCDE[j] + ABCDE[k])
t.sort()
print(t[-3])
| abcde = list(map(int, input().split()))
t = []
for i in range(3):
for j in range(i + 1, 4):
for k in range(j + 1, 5):
t.append(ABCDE[i] + ABCDE[j] + ABCDE[k])
t.sort()
print(t[-3]) |
class CredentialsError(Exception):
pass
class InvalidSetup(Exception):
pass | class Credentialserror(Exception):
pass
class Invalidsetup(Exception):
pass |
number_of_test_cases = int(input())
for i in range(number_of_test_cases):
number_of_candies = int(input())
one_gram_candies_number = 0
two_grams_candies_number = 0
for weight in map(int, input().split()):
if weight == 1:
one_gram_candies_number += 1
else:
two_g... | number_of_test_cases = int(input())
for i in range(number_of_test_cases):
number_of_candies = int(input())
one_gram_candies_number = 0
two_grams_candies_number = 0
for weight in map(int, input().split()):
if weight == 1:
one_gram_candies_number += 1
else:
two_gram... |
# Project Euler Problem 3
###############################
# Find the largest prime factor
# of the number 600851475143
###############################
#checks if a natural number n is prime
#returns boolean
def prime_check(n):
assert type(n) is int, "Non int passed"
assert n > 0, "No negative values allowed, o... | def prime_check(n):
assert type(n) is int, 'Non int passed'
assert n > 0, 'No negative values allowed, or zero'
if n == 1:
return False
i = 2
while i * i < n + 1:
if n != i and n % i == 0:
return False
i += 1
return True
def generate_primes(n):
assert typ... |
#!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: johnjim0816@gmail.com
Date: 2020-08-09 08:40:38
LastEditor: John
LastEditTime: 2020-08-10 10:38:59
Discription:
Environment:
'''
# Source : https://leetcode.com/problems/as-far-from-land-as-possible/
# Author : JohnJim0816
# Date : 2020-08-09
###########... | """
Author: John
Email: johnjim0816@gmail.com
Date: 2020-08-09 08:40:38
LastEditor: John
LastEditTime: 2020-08-10 10:38:59
Discription:
Environment:
"""
class Solution:
def max_distance(self, grid: List[List[int]]) -> int:
(m, n) = (len(grid), len(grid[0]))
steps = -1
island_pos = [(i, j... |
# Given an array of integers arr, return true if and only if it is a valid mountain array.
# More info: https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3251/
class Solution:
def is_mountain_array(self, arr: list([int])) -> bool:
if len(arr) < 3:
retur... | class Solution:
def is_mountain_array(self, arr: list([int])) -> bool:
if len(arr) < 3:
return False
going_down = False
going_up = arr[0] < arr[1]
if not going_up:
return False
prev_val = -1
for elem in arr:
if elem > prev_val and ... |
#
# PySNMP MIB module A3COM-SWITCHING-SYSTEMS-ROUTEPOLICY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-SWITCHING-SYSTEMS-ROUTEPOLICY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:53:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection, constraints_union) ... |
#This function prints the initial menu
def print_program_menu():
print("\n")
print("Welcome to the probability & statistics calculator. Please, choose an option:")
print("1. Descripive Statistics")
#print("2. ")
#print("3. ")
#print("4. ")
#print("5. ")
print("6. Exit")
#Checks if optio... | def print_program_menu():
print('\n')
print('Welcome to the probability & statistics calculator. Please, choose an option:')
print('1. Descripive Statistics')
print('6. Exit')
def identify_option(option):
if option.isdigit():
numeric_option = int(option)
if numeric_option >= 1 and n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.