content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# https://www.codechef.com/INCC2018/problems/PRISTG/
a=str(input().strip())
b=str(input().strip())
c=0
for i in range(0,len(a)):
for j in range(i+1,len(a)+1):
#print(a[i:j])
if(a[i:j] in b):
c+=1
print(c)
| a = str(input().strip())
b = str(input().strip())
c = 0
for i in range(0, len(a)):
for j in range(i + 1, len(a) + 1):
if a[i:j] in b:
c += 1
print(c) |
alist = input('Numbers: ')
if alist == '':
print('No numbers have been given.')
else:
blist = alist.split(', ')
s = 0
i = 0
while i < len(blist):
if blist[i].isdigit():
s += int(blist[i])
else :
print('No numbers have been given.')
exit()
i += 1
print('The total sum of the given numbers is {}.'.f... | alist = input('Numbers: ')
if alist == '':
print('No numbers have been given.')
else:
blist = alist.split(', ')
s = 0
i = 0
while i < len(blist):
if blist[i].isdigit():
s += int(blist[i])
else:
print('No numbers have been given.')
exit()
i ... |
def getleast(seq):
if seq[0] > seq[1]:
return seq[1]
else:
return seq[0]
def getRotating(seq):
length = len(seq)
if length == 1:
# Recursion end gate
return seq[0]
elif length == 2:
# Recursion end gate
return getleast(seq)
eli... | def getleast(seq):
if seq[0] > seq[1]:
return seq[1]
else:
return seq[0]
def get_rotating(seq):
length = len(seq)
if length == 1:
return seq[0]
elif length == 2:
return getleast(seq)
elif seq[0] < (seq[1] and seq[length - 1]):
return seq[0]
elif seq[l... |
# Python - 2.7.6
Test.assert_equals(am_i_wilson(0), False)
Test.assert_equals(am_i_wilson(1), False)
Test.assert_equals(am_i_wilson(5), True)
Test.assert_equals(am_i_wilson(8), False)
Test.assert_equals(am_i_wilson(9), False)
| Test.assert_equals(am_i_wilson(0), False)
Test.assert_equals(am_i_wilson(1), False)
Test.assert_equals(am_i_wilson(5), True)
Test.assert_equals(am_i_wilson(8), False)
Test.assert_equals(am_i_wilson(9), False) |
#
# PySNMP MIB module NOTIFICATION-LOG-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/NOTIFICATION-LOG-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:22:51 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 1... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) ... |
pkgname = "xvidcore"
pkgver = "1.3.7"
pkgrel = 0
build_wrksrc = "build/generic"
build_style = "gnu_configure"
make_cmd = "gmake"
make_dir = "."
hostmakedepends = ["gmake", "nasm"]
pkgdesc = "ISO MPEG-4 compliant video codec"
maintainer = "q66 <q66@chimera-linux.org>"
license = "GPL-2.0-or-later"
url = "https://www.xvid... | pkgname = 'xvidcore'
pkgver = '1.3.7'
pkgrel = 0
build_wrksrc = 'build/generic'
build_style = 'gnu_configure'
make_cmd = 'gmake'
make_dir = '.'
hostmakedepends = ['gmake', 'nasm']
pkgdesc = 'ISO MPEG-4 compliant video codec'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'GPL-2.0-or-later'
url = 'https://www.xvid... |
# Virtual Memory Module
class VirtualMemory:
def __init__(self):
self.memory = {}
# Key: 32-bit address
# Value: Any C variable/Python object
self.counter = 1
# NOTE: self.counter is an integer, is not possible to use as a key for self.memory
def checkCounter(self):
# Check if self.cou... | class Virtualmemory:
def __init__(self):
self.memory = {}
self.counter = 1
def check_counter(self):
if bin(self.counter) in self.memory.keys():
self.counter = 0
while True:
self.counter += 1
if bin(self.counter) not in self.memory... |
__________________________________________________________________________________________________
class Solution(object):
def maxNumberOfApples(self, A):
A.sort()
space = 5000
ans = 0
for x in A:
if space >= x:
space -= x
ans += 1
... | __________________________________________________________________________________________________
class Solution(object):
def max_number_of_apples(self, A):
A.sort()
space = 5000
ans = 0
for x in A:
if space >= x:
space -= x
ans += 1
... |
print("Please enter a number", end =" ")
number= int(input())
count= 1
while count<=10 :
print (number,'x',count,'=', number*count)
count+=1
| print('Please enter a number', end=' ')
number = int(input())
count = 1
while count <= 10:
print(number, 'x', count, '=', number * count)
count += 1 |
# Example: Iterate over all applications to find specific name
apps = api.list_applications(size=20)
app_name = ""
while app_name != "MyAppName":
my_app = next(apps)
app_name = my_app["name"]
print(my_app)
## { 'autoAnswer': True,
## 'callbackHttpMethod': 'get',
## 'id': 'a-asdf',
## 'incomingCal... | apps = api.list_applications(size=20)
app_name = ''
while app_name != 'MyAppName':
my_app = next(apps)
app_name = my_app['name']
print(my_app) |
# Print the following pattern for the given N number of rows.
# Pattern for N = 3
# A
# BC
# CDE
# Input format :
# Integer N (Total no. of rows)
# Output format :
# Pattern in N lines
n = int(input())
i = 1
start_chr = chr(ord("A") + i - 1)
while i <= n:
j = 1
while j <= i:
x = ord(chr(ord("A")... | n = int(input())
i = 1
start_chr = chr(ord('A') + i - 1)
while i <= n:
j = 1
while j <= i:
x = ord(chr(ord('A') + i - 1))
chra = chr(x + j - 1)
print(chra, end='')
x += 1
j += 1
print()
i += 1 |
def inputs():
n = int(input())
len_values = []
values = []
for i in range(n):
value = list(map(int, input().split()))
len_values.append(value[0])
values.append(value[1:])
return values, len_values
def solve(values, len_values):
minimum = len_values.index(min(len... | def inputs():
n = int(input())
len_values = []
values = []
for i in range(n):
value = list(map(int, input().split()))
len_values.append(value[0])
values.append(value[1:])
return (values, len_values)
def solve(values, len_values):
minimum = len_values.index(min(len_values... |
# https://en.wikipedia.org/wiki/Collatz_conjecture
# Code based on lecture by Dr Ian McLoughlin
# Week 3 exercise - program which applies Collatz to an integer chosen by the user.
# Student: Cormac Holleran, GMIT - Module: 52167
#input is taken from the user and stored as n.
n = int(input('Please enter and integer:'))... | n = int(input('Please enter and integer:'))
while n != 1:
if n % 2 == 0:
n = n / 2
print(n)
elif n % 2 > 0:
n = n * 3 + 1
print(n) |
def check(attempt, context):
if attempt.answer == flags[attempt.participant.id % len(flags)]:
return Checked(True)
if attempt.answer in flags:
return CheckedPlagiarist(False, flags.index(attempt.answer))
return Checked(False)
flags = ['LKL{U5E_STR1NG5_UT1LITY_jwUOzL5ymvjO}', 'LKL... | def check(attempt, context):
if attempt.answer == flags[attempt.participant.id % len(flags)]:
return checked(True)
if attempt.answer in flags:
return checked_plagiarist(False, flags.index(attempt.answer))
return checked(False)
flags = ['LKL{U5E_STR1NG5_UT1LITY_jwUOzL5ymvjO}', 'LKL{U5E_STR1NG... |
'''
I am Easy
This is an easy problem.
All you need to do is to print the first 10 multiples of the number given in input.
Input:
An integer N, whose first 10 multiples need to be printed.
Output:
First 10 multiples of number given in input
'''
n= int(input())
for i in range(1,11):
print(n*i)
| """
I am Easy
This is an easy problem.
All you need to do is to print the first 10 multiples of the number given in input.
Input:
An integer N, whose first 10 multiples need to be printed.
Output:
First 10 multiples of number given in input
"""
n = int(input())
for i in range(1, 11):
print(n * i) |
with open("input.txt", "r") as f:
x = 0
y = 0
lines = f.readlines()
for line in lines :
tmp = line.split(" ")
if "forward" in tmp[0]:
x += int(tmp[1])
elif "down" in tmp[0]:
y += int(tmp[1])
else:
y -= int(tmp[1])
print("x = ", x)
... | with open('input.txt', 'r') as f:
x = 0
y = 0
lines = f.readlines()
for line in lines:
tmp = line.split(' ')
if 'forward' in tmp[0]:
x += int(tmp[1])
elif 'down' in tmp[0]:
y += int(tmp[1])
else:
y -= int(tmp[1])
print('x = ', x)
... |
class ChromeException(Exception):
pass
class ChromeValueError(ValueError, ChromeException):
pass
class ChromeRuntimeError(RuntimeError, ChromeException):
pass
class ChromeTypeError(TypeError, ChromeException):
pass
class TabConnectionError(ChromeRuntimeError):
pass
| class Chromeexception(Exception):
pass
class Chromevalueerror(ValueError, ChromeException):
pass
class Chromeruntimeerror(RuntimeError, ChromeException):
pass
class Chrometypeerror(TypeError, ChromeException):
pass
class Tabconnectionerror(ChromeRuntimeError):
pass |
#
# PySNMP MIB module EXTREME-MPLS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-MPLS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:54:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint, constraints_union) ... |
'''Strategy model.
'''
'''
Copyright (c) 2017, WinQuant Information and Technology Co. Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above cop... | """Strategy model.
"""
'\nCopyright (c) 2017, WinQuant Information and Technology Co. Ltd.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above ... |
# Author: Melissa Perez
# Date: --/--/--
# Description:
def next_prime(prime):
next = prime + 1
while not is_prime(next):
next += 1
return next
def is_prime(prime):
for i in range(2, prime - 1):
if prime % i == 0:
return False
return True
if __name__ == "__main__"... | def next_prime(prime):
next = prime + 1
while not is_prime(next):
next += 1
return next
def is_prime(prime):
for i in range(2, prime - 1):
if prime % i == 0:
return False
return True
if __name__ == '__main__':
print(next_prime(19)) |
def solution(xs):
maxNeg = -9999999
count = 0
countNeg = 0
res = str(int(1))
if len(xs) > 50 or len(xs) < 1 or max(xs) > 1000 or min(xs) < -1000:
raise ValueError('invalid inputs')
if len(xs) == 1:
return str(xs[0])
for v in xs:
if v == 0:
continue
... | def solution(xs):
max_neg = -9999999
count = 0
count_neg = 0
res = str(int(1))
if len(xs) > 50 or len(xs) < 1 or max(xs) > 1000 or (min(xs) < -1000):
raise value_error('invalid inputs')
if len(xs) == 1:
return str(xs[0])
for v in xs:
if v == 0:
continue
... |
my_dict = dict()
def my_cache(fun):
def wrap(*args, **kwargs):
key = args[0]
if key not in my_dict:
my_dict[key] = fun(*args, **kwargs)
return my_dict[key]
return wrap
@my_cache
def fib_self_cache(n):
if n < 2:
return n
return fib_self_cache(n - 1) + fib_... | my_dict = dict()
def my_cache(fun):
def wrap(*args, **kwargs):
key = args[0]
if key not in my_dict:
my_dict[key] = fun(*args, **kwargs)
return my_dict[key]
return wrap
@my_cache
def fib_self_cache(n):
if n < 2:
return n
return fib_self_cache(n - 1) + fib_se... |
#LANGUAGE: Python 3.8.5
#ENV: VS Code
#AUTHOR: Kashyap Shah
#github https://github.com/kashyap-shah
print ("Hello World")
print ("Kashyap Shah was here to Say Hello World!") | print('Hello World')
print('Kashyap Shah was here to Say Hello World!') |
############################################################################
## MagicQ MACROS Constants
## July 22, 2016
## Austin Tyler
##
## Reference: MagicQ Manual - Chapter 31. ChamSys Remote Protocol Commands
## http://chamsys.co.uk
#################################################################... | macro_1 = 22
macro_2 = 23 |
#
# Copyright (c) 2012 OpenStack LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | def arg(*args, **kwargs):
def _decorator(func):
func.__dict__.setdefault('arguments', []).insert(0, (args, kwargs))
return func
return _decorator |
class parzyste:
def __init__(self, liczby):
self.liczby=liczby
self.ind=-2
def __iter__(self):
return self
def __next__(self):
if self.ind>=len(self.liczby):
raise StopIteration
self.ind=self.ind+2
return self.liczby[self.ind]
... | class Parzyste:
def __init__(self, liczby):
self.liczby = liczby
self.ind = -2
def __iter__(self):
return self
def __next__(self):
if self.ind >= len(self.liczby):
raise StopIteration
self.ind = self.ind + 2
return self.liczby[self.ind]
tabelka ... |
name = 'Leandro Tk'
print(len(name))
print(name.lower())
print(name.upper())
print(str(10))
| name = 'Leandro Tk'
print(len(name))
print(name.lower())
print(name.upper())
print(str(10)) |
# import pytest
class TestObjectName:
def test___str__(self): # synced
assert True
def test___eq__(self): # synced
assert True
def test___hash__(self): # synced
assert True
class TestTableName:
pass
class TestViewName:
pass
class TestSchemaName:
def test___st... | class Testobjectname:
def test___str__(self):
assert True
def test___eq__(self):
assert True
def test___hash__(self):
assert True
class Testtablename:
pass
class Testviewname:
pass
class Testschemaname:
def test___str__(self):
assert True
def test___eq... |
try:
value = 45 / 0
except ZeroDivisionError:
print("oops")
else:
print("No oops")
try:
value = 45 / 0
except ZeroDivisionError:
print("oops")
except FileNotFoundError:
print("ooooopps")
finally:
print("after all the oops")
class NameErrorException(Exception):
# def __init__(self, va... | try:
value = 45 / 0
except ZeroDivisionError:
print('oops')
else:
print('No oops')
try:
value = 45 / 0
except ZeroDivisionError:
print('oops')
except FileNotFoundError:
print('ooooopps')
finally:
print('after all the oops')
class Nameerrorexception(Exception):
pass
def print_name(name... |
arrSayan=[]
for i in range(1,1000):
if (i%3 == 0 or i%5 == 0):
arrSayan.append(i)
print(sum(arrSayan))
| arr_sayan = []
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
arrSayan.append(i)
print(sum(arrSayan)) |
# module name is filename
def summation(a,b):
return a + b
def division(a,b):
return a / b
def subtraction(a,b):
return a - b
| def summation(a, b):
return a + b
def division(a, b):
return a / b
def subtraction(a, b):
return a - b |
class Predicate:
def __init__(self, fn, desc, onFail = None):
self.fn = fn
self.desc = desc
self.onFail = onFail
def __call__(self, *args, **kw):
rtn = self.fn(*args, **kw)
if rtn is False and self.onFail:
rtn = self.onFail(*args, **kw)
return rtn
def __repr__(self):
return self.desc
def oneof(*m... | class Predicate:
def __init__(self, fn, desc, onFail=None):
self.fn = fn
self.desc = desc
self.onFail = onFail
def __call__(self, *args, **kw):
rtn = self.fn(*args, **kw)
if rtn is False and self.onFail:
rtn = self.onFail(*args, **kw)
return rtn
... |
def add_sort(l, value):
if not l:
l.append(value)
else:
i = 0
tam = len(l)
while i < tam:
if value < l[i]:
l.insert(i, value)
return
i += 1
l.append(value)
def add_des(l, value):
l.append(value)
def insert_va... | def add_sort(l, value):
if not l:
l.append(value)
else:
i = 0
tam = len(l)
while i < tam:
if value < l[i]:
l.insert(i, value)
return
i += 1
l.append(value)
def add_des(l, value):
l.append(value)
def insert_valu... |
expected_output = {
'node': {
1: {
'pod': 1,
'current_firmware': 'apic-4.2(4o)',
'status': 'success',
'upgrade_progress_percentage': 100
},
101: {
'pod': 1,
'current_firmware': 'un... | expected_output = {'node': {1: {'pod': 1, 'current_firmware': 'apic-4.2(4o)', 'status': 'success', 'upgrade_progress_percentage': 100}, 101: {'pod': 1, 'current_firmware': 'unknown', 'target_firmware': 'unknown', 'status': 'node unreachable'}, 102: {'pod': 1, 'current_firmware': 'n9000-14.2(4q)', 'status': 'not schedul... |
# https://leetcode.com/problems/flood-fill/
def reachable_neighbors(
sr: int, sc: int, row_cnt: int, col_cnt: int) -> list[tuple[int, int]]:
result = list()
candidates = [(sr - 1, sc), (sr + 1, sc), (sr, sc - 1), (sr, sc + 1)]
for candidate in candidates:
candidate_row, candidate_col = cand... | def reachable_neighbors(sr: int, sc: int, row_cnt: int, col_cnt: int) -> list[tuple[int, int]]:
result = list()
candidates = [(sr - 1, sc), (sr + 1, sc), (sr, sc - 1), (sr, sc + 1)]
for candidate in candidates:
(candidate_row, candidate_col) = candidate
if 0 <= candidate_row < row_cnt and 0 ... |
# Create dummy secrey key so we can use sessions
SECRET_KEY = '1234567890'
# Flask-Security config
SECURITY_URL_PREFIX = "/admin"
SECURITY_PASSWORD_HASH = "pbkdf2_sha256"
SECURITY_PASSWORD_SALT = "ATGUOHAELKiubahiughaerGOJAEGj"
SECURITY_USER_IDENTITY_ATTRIBUTES = ["name"]
# Flask-Security URLs, overridden because th... | secret_key = '1234567890'
security_url_prefix = '/admin'
security_password_hash = 'pbkdf2_sha256'
security_password_salt = 'ATGUOHAELKiubahiughaerGOJAEGj'
security_user_identity_attributes = ['name']
security_login_url = '/login/'
security_logout_url = '/logout/'
security_register_url = '/register/'
security_post_login... |
my_list = ['Joe', 2, 'Ted', 4.98, 14, 'Sam', 'void *', '42', 'float', 'pointers', 5006]
for x in my_list:
print(x)
| my_list = ['Joe', 2, 'Ted', 4.98, 14, 'Sam', 'void *', '42', 'float', 'pointers', 5006]
for x in my_list:
print(x) |
def info(msg):
print(f'[Info] {msg}')
def warn(msg):
print(f'[Warning] {msg}')
def err(msg):
print(f'[Error] {msg}')
def crit(msg):
print(f'[CRITICAL ERROR] {msg}')
| def info(msg):
print(f'[Info] {msg}')
def warn(msg):
print(f'[Warning] {msg}')
def err(msg):
print(f'[Error] {msg}')
def crit(msg):
print(f'[CRITICAL ERROR] {msg}') |
'''input
3
abc
cde
5
1
a
z
2
4
expr
expr
4
'''
# -*- coding: utf-8 -*-
# AtCoder Grand Contest
# Problem A
if __name__ == '__main__':
n = int(input())
s = input()
t = input()
# See:
# https://www.youtube.com/watch?v=VX8cGy7kNTE
for l in range(n, 2 * n + 1):
s_end = s[-(2 * n - l)... | """input
3
abc
cde
5
1
a
z
2
4
expr
expr
4
"""
if __name__ == '__main__':
n = int(input())
s = input()
t = input()
for l in range(n, 2 * n + 1):
s_end = s[-(2 * n - l):]
t_start = t[:2 * n - l]
if s_end == t_start:
print(len(s) + len(t) - len(s_end))
ex... |
class QueryException(Exception):
pass
class NoMatchFound(QueryException):
pass
class MultipleMatchesFound(QueryException):
pass
class InvalidKeyException(QueryException):
pass
| class Queryexception(Exception):
pass
class Nomatchfound(QueryException):
pass
class Multiplematchesfound(QueryException):
pass
class Invalidkeyexception(QueryException):
pass |
# -*- coding: utf-8 -*-
# Scrapy settings for amazon_moviles project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'eacopenlistbot'
SPIDER_MODULES = ['eacopenl... | bot_name = 'eacopenlistbot'
spider_modules = ['eacopenlistbot.spiders']
newspider_module = 'eacopenlistbot.spiders'
cookies_enabled = False
user_agent = 'eacopenlistbot (http://www.eacopenlist.org)'
download_delay = 2.25
log_file = 'log/crawlers.log'
log_level = 'INFO'
item_pipelines = {'eacopenlistbot.pipelines.EaCOpe... |
class PubInfo():
def __init__(self, item_id, mac_address, nlri, label, next_hop, encapsulations):
self.item_id = item_id
self.mac_address = mac_address
self.nlri = nlri
self.next_hop = next_hop
self.label = label
self.encapsulations = encapsulations
class Event(obje... | class Pubinfo:
def __init__(self, item_id, mac_address, nlri, label, next_hop, encapsulations):
self.item_id = item_id
self.mac_address = mac_address
self.nlri = nlri
self.next_hop = next_hop
self.label = label
self.encapsulations = encapsulations
class Event(object... |
mattermost_hook_url = "https://example.com/hooks/XZY"
threema_api_secret = "XXXXXXXXXXXXXXXX"
threema_id = "*XXXXXXX"
threema_private_key = "private:XXXXX"
threema_public_key = "public:XXXXX"
icon_url = "https://raw.githubusercontent.com/lgrahl/threema-msgapi-sdk-python/master/examples/res/threema.jpg"
threema_se... | mattermost_hook_url = 'https://example.com/hooks/XZY'
threema_api_secret = 'XXXXXXXXXXXXXXXX'
threema_id = '*XXXXXXX'
threema_private_key = 'private:XXXXX'
threema_public_key = 'public:XXXXX'
icon_url = 'https://raw.githubusercontent.com/lgrahl/threema-msgapi-sdk-python/master/examples/res/threema.jpg'
threema_servers ... |
#!/usr/bin/env python3
# Where to find explanation: https://www.geeksforgeeks.org/reverse-a-linked-list/
# Iterative approach:
# 1. Initialize three pointers prev as NULL, curr as head and next as NULL.
# 2. Iterate through the linked list. In loop, do following.
# 3. Before changing next of current, store next node
... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
if head.next is None or head is None:
return head
rest = solution().reverseList(head.next)
head.next.ne... |
#Parameter dictionary
Parameter1S = ['products','uom','op stock','production','dispatch/Sales','internal consumption','closing stock','mkg offer']
Parameter2 = ['today','to month','to date']
| parameter1_s = ['products', 'uom', 'op stock', 'production', 'dispatch/Sales', 'internal consumption', 'closing stock', 'mkg offer']
parameter2 = ['today', 'to month', 'to date'] |
# Define a function with an arbitrary number of arguments
def sort_types(*args):
nums, strings, bools = [], [], []
for arg in args:
# Check if 'arg' is a number, add it to 'nums'-list
if isinstance(arg, (int, float)):
nums.append(arg)
# Check if 'arg' is a number, add it to '... | def sort_types(*args):
(nums, strings, bools) = ([], [], [])
for arg in args:
if isinstance(arg, (int, float)):
nums.append(arg)
if isinstance(arg, bool):
bools.append(arg)
elif isinstance(arg, str):
strings.append(arg)
return (nums, strings, bools... |
def sum(numbers: list)->int:
if len(numbers) == 0:
return 0
elif len(numbers) == 1:
return numbers[0]
else:
return numbers[0] + sum(numbers[1:])
print(sum([]))
print(sum([1]))
print(sum([1, 2])) | def sum(numbers: list) -> int:
if len(numbers) == 0:
return 0
elif len(numbers) == 1:
return numbers[0]
else:
return numbers[0] + sum(numbers[1:])
print(sum([]))
print(sum([1]))
print(sum([1, 2])) |
#
# PySNMP MIB module ALCATEL-IND1-TIMETRA-OAM-TEST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-TIMETRA-OAM-TEST-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:04:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... | (tmnx_sr_notify_prefix, timetra_srmib_modules, tmnx_sr_confs, tmnx_sr_objs) = mibBuilder.importSymbols('ALCATEL-IND1-TIMETRA-GLOBAL-MIB', 'tmnxSRNotifyPrefix', 'timetraSRMIBModules', 'tmnxSRConfs', 'tmnxSRObjs')
(t_profile,) = mibBuilder.importSymbols('ALCATEL-IND1-TIMETRA-QOS-MIB', 'TProfile')
(sdp_bind_vc_type, sdp_i... |
expected_output = {
"global_static_table": {
"10.169.197.93": {
"ip_address": "10.169.197.93",
"mac_address": "fa16.3eff.b7ad",
"encap_type": "ARPA",
"age": "-",
"protocol": "Internet",
}
},
"interfaces": {
"GigabitEthernet2... | expected_output = {'global_static_table': {'10.169.197.93': {'ip_address': '10.169.197.93', 'mac_address': 'fa16.3eff.b7ad', 'encap_type': 'ARPA', 'age': '-', 'protocol': 'Internet'}}, 'interfaces': {'GigabitEthernet2': {'ipv4': {'neighbors': {'10.169.197.94': {'ip': '10.169.197.94', 'link_layer_address': 'fa16.3eff.aa... |
arquivo = open("dados.txt", "r")
print("Iterando sobre o arquivo")
for linha in arquivo:
print(repr(linha))
arquivo.close()
| arquivo = open('dados.txt', 'r')
print('Iterando sobre o arquivo')
for linha in arquivo:
print(repr(linha))
arquivo.close() |
n = input()
a = set(map(int,input().strip().split()))
m = input()
b = set(map(int,input().strip().split()))
c = list(a^b)
c = sorted(c)
for i in c:
print(i) | n = input()
a = set(map(int, input().strip().split()))
m = input()
b = set(map(int, input().strip().split()))
c = list(a ^ b)
c = sorted(c)
for i in c:
print(i) |
def pattern_search(text, pattern):
# Remove pass and write your logic here
count = 0
l = []
l = text.split()
for each in l:
if pattern in each:
count += 1
return count
# Use different values for text and pattern and test your program
text = "MESMERIZING MESSAGE"
pattern = "... | def pattern_search(text, pattern):
count = 0
l = []
l = text.split()
for each in l:
if pattern in each:
count += 1
return count
text = 'MESMERIZING MESSAGE'
pattern = 'MES'
result = pattern_search(text, pattern)
print('The given text:', text)
print('Pattern:', pattern)
print('No.... |
#https://www.hackerrank.com/challenges/manasa-and-stones
t = int(input().strip())
for i in range(t):
n = int(input())
a = int(input())
b = int(input())
if(a!=b):
c = a if a<b else b
d = b if c==a else a
ans=[]
for j in range(n):
temp = (n-1-j)*c + j... | t = int(input().strip())
for i in range(t):
n = int(input())
a = int(input())
b = int(input())
if a != b:
c = a if a < b else b
d = b if c == a else a
ans = []
for j in range(n):
temp = (n - 1 - j) * c + j * d
ans.append(temp)
for i in ans:... |
# The base error class for all <tt>Whois</tt> error classes.
class Error(StandardError):
pass
# Raised when the connection to the WHOIS server fails.
class ConnectionError(Error):
pass
# Generic class for server errors.
class ServerError(Error):
pass
# Raised when we know about a specific f... | class Error(StandardError):
pass
class Connectionerror(Error):
pass
class Servererror(Error):
pass
class Servernotimplemented(ServerError):
pass
class Servernotsupported(ServerError):
pass
class Allocationunknown(ServerError):
pass
class Interfacenotsupported(ServerError):
pass
class ... |
'''
AND - if both operands are TRUE, then condition becomes TRUE
'''
a = 10
b = 5
if a < 20 and b < 10:
print("The logical operand is TRUE")
else:
print("The result is FALSE")
'''
OR - if any of the operands are TRUE, then the condition becomes TRUE
NOT - reverses the actual logical state of the given variabl... | """
AND - if both operands are TRUE, then condition becomes TRUE
"""
a = 10
b = 5
if a < 20 and b < 10:
print('The logical operand is TRUE')
else:
print('The result is FALSE')
'\nOR - if any of the operands are TRUE, then the condition becomes TRUE\nNOT - reverses the actual logical state of the given variable\... |
PARDON = "Pardon?\n"
FIRST_TAKING = "(first taking %s %s)\n"
CANT_SEE_A = "I can't see a %s here!\n"
UNDERSTAND_AS_FAR = "I only understand as far as you wanting to %s something.\n"
NOT_A_VERB = "That's not a verb I recognise.\n"
FIRST_TAKING_OFF = "(first taking the %s off)\n"
DROPPED = "Dropped.\n"
TOO_DARK = "It is... | pardon = 'Pardon?\n'
first_taking = '(first taking %s %s)\n'
cant_see_a = "I can't see a %s here!\n"
understand_as_far = 'I only understand as far as you wanting to %s something.\n'
not_a_verb = "That's not a verb I recognise.\n"
first_taking_off = '(first taking the %s off)\n'
dropped = 'Dropped.\n'
too_dark = 'It is ... |
def translate_charset(text, chrA, chrB, terminator):
if isinstance(text, str):
text = bytes(text, 'ascii')
res = []
for i in text:
if i == terminator:
break
if i not in chrA:
continue
res.append(chrB[chrA.index(i)])
return bytes(res)
CHARSET_A... | def translate_charset(text, chrA, chrB, terminator):
if isinstance(text, str):
text = bytes(text, 'ascii')
res = []
for i in text:
if i == terminator:
break
if i not in chrA:
continue
res.append(chrB[chrA.index(i)])
return bytes(res)
charset_ascii ... |
class SpellingResult:
numCorrect = 0
numTotal = 0
def __init__(self):
self.numCorrect = 0
self.numTotal = 0
def __init__(self, correct, total):
self.numCorrect = correct
self.numTotal = total
def getAccuracy(self):
if self.numTotal == 0:
return 0.0
else:
return float(s... | class Spellingresult:
num_correct = 0
num_total = 0
def __init__(self):
self.numCorrect = 0
self.numTotal = 0
def __init__(self, correct, total):
self.numCorrect = correct
self.numTotal = total
def get_accuracy(self):
if self.numTotal == 0:
retu... |
# create campaign
class DtlCampaignCreateModel:
def __init__(self, company_id, template_id): # required fields
self.company_id = company_id
self.template_id = template_id
self.OnReplyAction = None
self.ScheduledMailLimit = None
def get_json_object(self):
return {
... | class Dtlcampaigncreatemodel:
def __init__(self, company_id, template_id):
self.company_id = company_id
self.template_id = template_id
self.OnReplyAction = None
self.ScheduledMailLimit = None
def get_json_object(self):
return {'companyId': self.company_id, 'templateId':... |
fire_info = input().split("#")
water_amount = int(input())
effort = 0
fire_put_out = []
for i in fire_info:
fire_type_and_range = i.split(" = ")
fire_type = fire_type_and_range[0]
fire_range = int(fire_type_and_range[1])
if fire_type == "High" and 81 <= fire_range <= 125:
if water_amount >= ... | fire_info = input().split('#')
water_amount = int(input())
effort = 0
fire_put_out = []
for i in fire_info:
fire_type_and_range = i.split(' = ')
fire_type = fire_type_and_range[0]
fire_range = int(fire_type_and_range[1])
if fire_type == 'High' and 81 <= fire_range <= 125:
if water_amount >= fire... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def solve(r,k):
x = TreeNode(k)
ans = r
if(not r):
return x
while(r and (r.left or r.right) ):
... | def solve(r, k):
x = tree_node(k)
ans = r
if not r:
return x
while r and (r.left or r.right):
if r.val < k:
if r.right:
r = r.right
else:
r.right = x
return ans
elif r.left:
r = r.left
els... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.logo... | response.logo = a(b(COMPANY_NAME), xml('™ '), _class='brand', _href='http://www.web2py.com/')
response.title = COMPANY_NAME
response.subtitle = ''
response.meta.author = 'Your Name <you@example.com>'
response.meta.description = 'a cool new app'
response.meta.keywords = 'web2py, python, framework'
response.me... |
#
# 1446. Consecutive Characters
#
# Q: https://leetcode.com/problems/consecutive-characters/
# A: https://leetcode.com/problems/consecutive-characters/discuss/639815/Kt-Js-Py3-Cpp-Best-Same
#
# last
class Solution:
def maxPower(self, s: str, last = '0', same = 1, best = 1) -> int:
for c in s:
... | class Solution:
def max_power(self, s: str, last='0', same=1, best=1) -> int:
for c in s:
if last == c:
same += 1
best = max(best, same)
else:
last = c
same = 1
return best
class Solution:
def max_power(se... |
class GlobalVars:
def __init__(self):
self.default_qp_values = dict(exam_name='Exam Name', course_code='0001', qp_code='12345', program='B.E',
max_marks=100, date='12122017', semester=3, duration=90, num_parts=1,
qp_data='')
... | class Globalvars:
def __init__(self):
self.default_qp_values = dict(exam_name='Exam Name', course_code='0001', qp_code='12345', program='B.E', max_marks=100, date='12122017', semester=3, duration=90, num_parts=1, qp_data='')
self.default_qpd_values = dict() |
build_deps = [
"@maven//:org_slf4j_slf4j_api",
"@maven//:org_apache_logging_log4j_log4j_api",
"@maven//:org_jboss_logging_jboss_logging",
]
test_deps = [
"@maven//:junit_junit",
"@maven//:org_mockito_mockito_all",
]
jmh_deps = [
"@jmh_m2//:org_openjdk_jmh_jmh_core",
"@jmh_m2//:net_sf_jopt_... | build_deps = ['@maven//:org_slf4j_slf4j_api', '@maven//:org_apache_logging_log4j_log4j_api', '@maven//:org_jboss_logging_jboss_logging']
test_deps = ['@maven//:junit_junit', '@maven//:org_mockito_mockito_all']
jmh_deps = ['@jmh_m2//:org_openjdk_jmh_jmh_core', '@jmh_m2//:net_sf_jopt_simple_jopt_simple', '@jmh_m2//:org_a... |
NATIONALITIES=(
('Afghan', 'Afghan'),
('Albanian', 'Albanian'),
('Algerian', 'Algerian'),
('American', 'American'),
('Andorran', 'Andorran'),
('Angolan', 'Angolan'),
('Antiguans', 'Antiguans'),
('Argentinean', 'Argentinean'),
('Armenian', 'Armenian'),
('Australian', 'Australian')... | nationalities = (('Afghan', 'Afghan'), ('Albanian', 'Albanian'), ('Algerian', 'Algerian'), ('American', 'American'), ('Andorran', 'Andorran'), ('Angolan', 'Angolan'), ('Antiguans', 'Antiguans'), ('Argentinean', 'Argentinean'), ('Armenian', 'Armenian'), ('Australian', 'Australian'), ('Austrian', 'Austrian'), ('Azerbaija... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
debug = 1
#kan qing ti yi
#"Multiples of 3 and 5"
#solution(10), 23
def debug_print(flag, out):
if debug:
print("temp" + str(flag) + ":" + str(out))
def sum_ap(num_max,num_diff):
num_max=(num_max-1)//num_diff*num_diff
if num_max :
n=(num_max-n... | debug = 1
def debug_print(flag, out):
if debug:
print('temp' + str(flag) + ':' + str(out))
def sum_ap(num_max, num_diff):
num_max = (num_max - 1) // num_diff * num_diff
if num_max:
n = (num_max - num_diff) // num_diff + 1
return (num_diff + num_max) * n // 2
else:
retur... |
class Solution:
def isValid(self, s: str) -> bool:
closing_parentheses = []
# loop through str
for char in s:
# if character is either (, [, {
if char in '(, [, {':
# add ) ] } to list
if char == '(':
closing_parenth... | class Solution:
def is_valid(self, s: str) -> bool:
closing_parentheses = []
for char in s:
if char in '(, [, {':
if char == '(':
closing_parentheses.append(')')
if char == '[':
closing_parentheses.append(']')
... |
class PFFRCResponseStatus:
success = "success"
error = "error"
class PFFRCResponseCode:
# SUCCESS Codes
success = 2200
# ERROR Codes
error = 5100
validation_error = 5101
class PFFRCHTTPCode:
# SUCCESS Codes
OK = 200
| class Pffrcresponsestatus:
success = 'success'
error = 'error'
class Pffrcresponsecode:
success = 2200
error = 5100
validation_error = 5101
class Pffrchttpcode:
ok = 200 |
word = input("hello world")
word = word.strip()
len_last_word = len(word) - word.rindex(" ") - 1
print(len_last_word)
data_test = input()
m = int(data_test.split(" ")[0])
n = int(data_test.split(" ")[1])
# count = 0
count = 1
n_to_2 = int((n - 1) / 2)
count = count + n_to_2
for i in range(3, m + 1):
count = count + n... | word = input('hello world')
word = word.strip()
len_last_word = len(word) - word.rindex(' ') - 1
print(len_last_word)
data_test = input()
m = int(data_test.split(' ')[0])
n = int(data_test.split(' ')[1])
count = 1
n_to_2 = int((n - 1) / 2)
count = count + n_to_2
for i in range(3, m + 1):
count = count + n - i
print... |
'''
Created on Apr 30, 2012
@author: h87966
'''
class BlogDataStore():
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
def save(self, blog_entry):
pass
def delete(self, id):
pass
def fetch(self, id):
... | """
Created on Apr 30, 2012
@author: h87966
"""
class Blogdatastore:
"""
classdocs
"""
def __init__(self):
"""
Constructor
"""
def save(self, blog_entry):
pass
def delete(self, id):
pass
def fetch(self, id):
pass
def fetch_all(self):... |
peso=[]
for i in range(5):
peso.append(float(input("Digite seu peso: ")))
print("Maior peso: ", max(peso))
print("Menor peso: ", min(peso)) | peso = []
for i in range(5):
peso.append(float(input('Digite seu peso: ')))
print('Maior peso: ', max(peso))
print('Menor peso: ', min(peso)) |
'''
Given the head of a singly linked list, return true if it is a palindrome.
'''
#TC O(N) and Space O(1)
# Find the end of the first half.
# Reverse the second half.
# Determine whether or not there is a palindrome.
# Restore the list.
# Return the result.
# Definition for singly-linked list.
# class ListNode(obj... | """
Given the head of a singly linked list, return true if it is a palindrome.
"""
class Solution(object):
def end_of_first_half(self, head):
(fast_ptr, slow_ptr) = (head, head)
while fast_ptr.next and fast_ptr.next.next:
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.ne... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
count=0
input_file = "easter_03.input"
input = []
_A = []
_B = []
_C = []
_x=0
#Mise au propre de l'input
for line in open(input_file):
values = line.rstrip('\n').split()
_A.append(int(values[0]))
_B.append(int(values[1]))
_C.append(int(values[2]))
_x+=1
if (_x... | count = 0
input_file = 'easter_03.input'
input = []
_a = []
_b = []
_c = []
_x = 0
for line in open(input_file):
values = line.rstrip('\n').split()
_A.append(int(values[0]))
_B.append(int(values[1]))
_C.append(int(values[2]))
_x += 1
if _x % 3 == 0:
input.append(_A)
input.append(... |
def words_to_sentiment(sentence):
# Given a string representing a sentence, we want to split it into clean tokens with the clean_text function
# Then we apply the vec_to_sentiment function to each token (if present in the vocabulary) to get a sentiment value
# We return the average sentiment value
retur... | def words_to_sentiment(sentence):
return np.mean(vec_to_sentiment(np.array([wordVectors[w] for w in clean_text(sentence) if w in wordVectors.vocab]))) |
# https://leetcode.com/problems/word-ladder/
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList or not beginWord or not endWord or not wordList:
return 0
l = len(beginWord)
d = d... | class Solution:
def ladder_length(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList or not beginWord or (not endWord) or (not wordList):
return 0
l = len(beginWord)
d = defaultdict(list)
for word in wordList:
for i in... |
n = 1
avrg = 0
for i in input().split(","):
avrg += (int(i) - avrg)/n
n += 1
print(int(round(avrg))) | n = 1
avrg = 0
for i in input().split(','):
avrg += (int(i) - avrg) / n
n += 1
print(int(round(avrg))) |
def main():
N, v = map(int, input().split())
s = list(map(int, input().split()))
output = 0
for i in s:
if i == v:
output += 1
print(output)
if __name__=='__main__':
main() | def main():
(n, v) = map(int, input().split())
s = list(map(int, input().split()))
output = 0
for i in s:
if i == v:
output += 1
print(output)
if __name__ == '__main__':
main() |
class ConfigSpecialField:
def __init__(self, parent, field_name, field_type, field_required):
assert field_type == "String"
self.parent = parent
self.field_name = field_name
self.field_type = field_type
self.field_required = field_required
def __str__(self):
retu... | class Configspecialfield:
def __init__(self, parent, field_name, field_type, field_required):
assert field_type == 'String'
self.parent = parent
self.field_name = field_name
self.field_type = field_type
self.field_required = field_required
def __str__(self):
ret... |
def C_R_T(b, n):
sum = 0
N = 1
for items in n:
N *= items
for y, x in zip(b, n):
p = N // x
sum += y * p * Mul_Inv(p, x)
return sum % N
def Mul_Inv(i, j):
i = i % j;
for x in range(1, j) :
if ((i * x) % j == 1) :
return x
return 1
def gcd(a, b):
if a == b:
... | def c_r_t(b, n):
sum = 0
n = 1
for items in n:
n *= items
for (y, x) in zip(b, n):
p = N // x
sum += y * p * mul__inv(p, x)
return sum % N
def mul__inv(i, j):
i = i % j
for x in range(1, j):
if i * x % j == 1:
return x
return 1
def gcd(a, b):... |
{
"cidLRPadding": {
W3Const.w3ElementType: W3Const.w3TypeClass,
W3Const.w3PropCSS: {
"padding-left": "5px",
"padding-right": "5px"
}
},
"cidLeftBorder": {
W3Const.w3ElementType: W3Const.w3TypeClass,
W3Const.w3PropCSS: {
"border-lef... | {'cidLRPadding': {W3Const.w3ElementType: W3Const.w3TypeClass, W3Const.w3PropCSS: {'padding-left': '5px', 'padding-right': '5px'}}, 'cidLeftBorder': {W3Const.w3ElementType: W3Const.w3TypeClass, W3Const.w3PropCSS: {'border-left': '1px solid', 'padding-left': '5px', 'float': 'left'}}, 'cidRightLabel': {W3Const.w3ElementTy... |
while True:
vl = input().split(" ")
x1,y1,x2,y2 = vl
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
if (x1 + y1 + x2 + y2) == 0:
break
if (x1==x2) and (y1==y2):
print("%d" %0)
continue
if (x1==x2) or (y1==y2):
print("%d" %1)
co... | while True:
vl = input().split(' ')
(x1, y1, x2, y2) = vl
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
if x1 + y1 + x2 + y2 == 0:
break
if x1 == x2 and y1 == y2:
print('%d' % 0)
continue
if x1 == x2 or y1 == y2:
print('%d' % 1)
continue
... |
class Session(object):
def __init__(self, client, id):
self.client = client
self.id = id
self.history = [client.get_root_node()]
self.pos = 0
def __repr__(self):
return '{} @{}'.format(self.id, self.client)
@property
def status(self):
return self.clien... | class Session(object):
def __init__(self, client, id):
self.client = client
self.id = id
self.history = [client.get_root_node()]
self.pos = 0
def __repr__(self):
return '{} @{}'.format(self.id, self.client)
@property
def status(self):
return self.client... |
def decode_bits(bits):
bits=bits.strip("0")
low=len(bits)
count=0
zero=0
count2=0
for i in bits:
if i=="1":
count+=1
zero=max(zero, count2)
count2=0
elif i=="0":
if count: low=min(count, low)
count=0
count2+=... | def decode_bits(bits):
bits = bits.strip('0')
low = len(bits)
count = 0
zero = 0
count2 = 0
for i in bits:
if i == '1':
count += 1
zero = max(zero, count2)
count2 = 0
elif i == '0':
if count:
low = min(count, low)
... |
# O(N * 2^M)
class Solution:
def smallestSufficientTeam(self, req_skills, people):
m, n = len(req_skills), len(people)
mapping = {v: i for i, v in enumerate(req_skills)}
# convert each person's skills into bitmask
skill_masks = [0] * n
for i, p in enumerate(people):
... | class Solution:
def smallest_sufficient_team(self, req_skills, people):
(m, n) = (len(req_skills), len(people))
mapping = {v: i for (i, v) in enumerate(req_skills)}
skill_masks = [0] * n
for (i, p) in enumerate(people):
for skill in p:
if skill in mapping... |
# Python 3 program to sort
# an array according to given
# indexes
# Function to reorder
# elements of arr[] according
# to index[]
def reorder(arr,index, n):
temp = [0] * n;
# arr[i] should be
# present at index[i] index
for i in range(0,n):
temp[index[i]] = arr[i]
... | def reorder(arr, index, n):
temp = [0] * n
for i in range(0, n):
temp[index[i]] = arr[i]
for i in range(0, n):
arr[i] = temp[i]
index[i] = i
arr = [50, 40, 70, 60, 90]
index = [3, 0, 4, 1, 2]
n = len(arr)
reorder(arr, index, n)
print('Reordered array is:')
for i in range(0, n):
p... |
'''Configuration file - copy to settings.py and fill in your own settings.'''
SERVER_PORT = 5000
DATABASE = '/home/twenty/var/sqlite/causeway.db'
DATA_DIR = '/home/twenty/var/storage'
# Price in satoshis for 1MB storage and 50MB transfer
PRICE = 1000
| """Configuration file - copy to settings.py and fill in your own settings."""
server_port = 5000
database = '/home/twenty/var/sqlite/causeway.db'
data_dir = '/home/twenty/var/storage'
price = 1000 |
__author__ = "Dusan (Ph4r05) Klinec"
__copyright__ = "Copyright (C) 2014 Dusan (ph4r05) Klinec"
__license__ = "Apache License, Version 2.0"
__version__ = "1.0"
class Visitor(object):
def __init__(self, verbose=False):
self.verbose = verbose
def __getattr__(self, name):
if not name.startswith(... | __author__ = 'Dusan (Ph4r05) Klinec'
__copyright__ = 'Copyright (C) 2014 Dusan (ph4r05) Klinec'
__license__ = 'Apache License, Version 2.0'
__version__ = '1.0'
class Visitor(object):
def __init__(self, verbose=False):
self.verbose = verbose
def __getattr__(self, name):
if not name.startswith(... |
with open("day_05/day_05.txt") as f:
data = f.read().splitlines()
def binary_search(line, start, end, lo, hi, char1, char2,):
target = 0
for char in line[start:end]:
if char in char1:
hi -= (hi - lo) // 2 + 1
target = lo
elif char in char2:
lo += (hi - lo... | with open('day_05/day_05.txt') as f:
data = f.read().splitlines()
def binary_search(line, start, end, lo, hi, char1, char2):
target = 0
for char in line[start:end]:
if char in char1:
hi -= (hi - lo) // 2 + 1
target = lo
elif char in char2:
lo += (hi - lo)... |
# HackerLand University has the following grading policy:
# Every student receives a in the inclusive range from 0 to 100.
# Any grade less than 40 is a failing grade.
# Sam is a professor at the university and likes to round each
# student's grade according to these rules:
# If the difference between the grade an... | def next_multiple(number):
max_multiple = True
start = 1
while max_multiple:
if start * 5 > number:
max_multiple = False
else:
start += 1
return start
def solve(grades):
new_grades = []
for i in range(len(grades)):
if grades[i] >= 38:
... |
n=int(input())
l=[]
for i in range(n):
l.append(input().split())
m=int(input());c=0;d=0;e=0
for i in range(n):
if l[i][1] == 'children':
c+=1
elif l[i][1] == 'men':
d+=1
elif l[i][1] == 'women':
e+=1
t = max(c,e,d)
print(t,m-t,0)
| n = int(input())
l = []
for i in range(n):
l.append(input().split())
m = int(input())
c = 0
d = 0
e = 0
for i in range(n):
if l[i][1] == 'children':
c += 1
elif l[i][1] == 'men':
d += 1
elif l[i][1] == 'women':
e += 1
t = max(c, e, d)
print(t, m - t, 0) |
class b(int):
__hash__ = None
a = b()
b = 3
b.__hash__ = None
hash(b)
| class B(int):
__hash__ = None
a = b()
b = 3
b.__hash__ = None
hash(b) |
class Solution:
def myAtoi(self, s):
s = s.lstrip()
l = list("0123456789")
if s:
res = 0
count = 0
flag = 1
for i in s:
if(count == 0 and i in ["+", "-"]):
if(i == "+"):
flag = 1
... | class Solution:
def my_atoi(self, s):
s = s.lstrip()
l = list('0123456789')
if s:
res = 0
count = 0
flag = 1
for i in s:
if count == 0 and i in ['+', '-']:
if i == '+':
flag = 1
... |
class Solution:
def findMin(self, nums: List[int]) -> int:
def find(nums, i, j):
if i == j - 1 or i == j:
return min(nums[i], nums[j])
if nums[i] < nums[j]:
return nums[i]
mid = (i + j) // 2
if nums[mid] < nums[mid - ... | class Solution:
def find_min(self, nums: List[int]) -> int:
def find(nums, i, j):
if i == j - 1 or i == j:
return min(nums[i], nums[j])
if nums[i] < nums[j]:
return nums[i]
mid = (i + j) // 2
if nums[mid] < nums[mid - 1] and n... |
COLOURS = [
0, 0, 0, 0, 0, 42, 0, 42, 0, 0, 42, 42, 42, 0, 0, 42,
0, 42, 42, 21, 0, 42, 42, 42, 21, 21, 21, 21, 21, 63, 21, 63,
21, 21, 63, 63, 63, 21, 21, 63, 21, 63, 63, 63, 21, 63, 63, 63,
59, 59, 59, 55, 55, 55, 52, 52, 52, 48, 48, 48, 45, 45, 45, 42,
42, 42, 38, 38, 38, 35, 35, 35, 31, 31, 31, 28... | colours = [0, 0, 0, 0, 0, 42, 0, 42, 0, 0, 42, 42, 42, 0, 0, 42, 0, 42, 42, 21, 0, 42, 42, 42, 21, 21, 21, 21, 21, 63, 21, 63, 21, 21, 63, 63, 63, 21, 21, 63, 21, 63, 63, 63, 21, 63, 63, 63, 59, 59, 59, 55, 55, 55, 52, 52, 52, 48, 48, 48, 45, 45, 45, 42, 42, 42, 38, 38, 38, 35, 35, 35, 31, 31, 31, 28, 28, 28, 25, 25, 2... |
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
possible=int(num)
except:
print ("Invalid input")
if smallest is None:
smallest = possible
elif possible < smallest:
smallest = possible
elif la... | largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num == 'done':
break
try:
possible = int(num)
except:
print('Invalid input')
if smallest is None:
smallest = possible
elif possible < smallest:
smallest = possible
elif large... |
class Bounds:
def __init__(self):
self.upper = 1
self.lower = 0
Bounds = Bounds()
| class Bounds:
def __init__(self):
self.upper = 1
self.lower = 0
bounds = bounds() |
#Set spam equal to 1 using modulo on line 3!
spam = 3 % 2
print(spam) | spam = 3 % 2
print(spam) |
cluster_settings_requests = {
"change_auto_create_index": {
"summary": "Set the auto create index flag",
"description": "Set the auto create index flag to true",
"value": {
"persistent": {
"action": {
"auto_create_index": "true"
... | cluster_settings_requests = {'change_auto_create_index': {'summary': 'Set the auto create index flag', 'description': 'Set the auto create index flag to true', 'value': {'persistent': {'action': {'auto_create_index': 'true'}}}}, 'change_cluster_metadata': {'summary': 'Change Cluster Metadata', 'description': 'Change Cl... |
'''
Given matrix of rivers (1's) and lands(0's) return array of all river lengths.
e.g. for matrix:
[
[1, 0, 0, 1, 0],
[1, 0, 1, 0, 0],
[0, 0, 1, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 1, 1, 0]
]
answer would be: [1,2,2,2,5]
'''
# O(w*h) time | O(w*h) space
def riverSizes(area):
n = len(area)
if n == 0:
... | """
Given matrix of rivers (1's) and lands(0's) return array of all river lengths.
e.g. for matrix:
[
[1, 0, 0, 1, 0],
[1, 0, 1, 0, 0],
[0, 0, 1, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 1, 1, 0]
]
answer would be: [1,2,2,2,5]
"""
def river_sizes(area):
n = len(area)
if n == 0:
return []
m = len(ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.