content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
a = int(input())
f = int(input())
if a == f:
print('YES')
elif a != 1 and f != 1:
print('YES')
else:
print('NO') | a = int(input())
f = int(input())
if a == f:
print('YES')
elif a != 1 and f != 1:
print('YES')
else:
print('NO') |
# _*_ coding: utf-8 _*_
"""
Created by Alimazing on 2018/6/24.
"""
__author__ = 'Alimazing'
APP_ID = 'wx5511fgf81259cd7339b'
APP_SECRET = '266db3182ae98421940d292e0ce021182c'
LOGIN_URL = 'https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code' | """
Created by Alimazing on 2018/6/24.
"""
__author__ = 'Alimazing'
app_id = 'wx5511fgf81259cd7339b'
app_secret = '266db3182ae98421940d292e0ce021182c'
login_url = 'https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code' |
extn2tag = { '.c' : 'c', \
'.cpp' : 'cpp', '.cpp_' : 'cpp', '.cpp1' : 'cpp', '.cpp2' : 'cpp', '.cppclean' : 'cpp', '.cpp_NvidiaAPI_sample' : 'cpp', '.cpp-s8inyu' : 'cpp', '.cpp-woains' : 'cpp', \
'.cs' : 'csharp', '.csharp' : 'csharp', \
'.m' : 'objc', \
'.java' : 'java', \
'.s... | extn2tag = {'.c': 'c', '.cpp': 'cpp', '.cpp_': 'cpp', '.cpp1': 'cpp', '.cpp2': 'cpp', '.cppclean': 'cpp', '.cpp_NvidiaAPI_sample': 'cpp', '.cpp-s8inyu': 'cpp', '.cpp-woains': 'cpp', '.cs': 'csharp', '.csharp': 'csharp', '.m': 'objc', '.java': 'java', '.scala': 'scala', '.scla': 'scala', '.go': 'go', '.javascript': 'jav... |
#! /usr/bin/env python
def count_routes(n, a):
count = 1
for i in range(len(a)):
count *= a[i]
return count
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
print(count_routes(n, a) % 1234567)
| def count_routes(n, a):
count = 1
for i in range(len(a)):
count *= a[i]
return count
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
print(count_routes(n, a) % 1234567) |
#!/usr/bin/env python3
r"""
Botorch Errors.
"""
class BotorchError(Exception):
r"""Base botorch exception."""
pass
class CandidateGenerationError(BotorchError):
r"""Exception raised during generating candidates."""
pass
class UnsupportedError(BotorchError):
r"""Currently unsupported feature... | """
Botorch Errors.
"""
class Botorcherror(Exception):
"""Base botorch exception."""
pass
class Candidategenerationerror(BotorchError):
"""Exception raised during generating candidates."""
pass
class Unsupportederror(BotorchError):
"""Currently unsupported feature."""
pass |
print('\033[32m =\033[m'*50)
print('BUILD AN PYTHON SCRIPT THAT READ AN NAME AND SHOW AN MENSAGE OF GRETTINS ACORD WITH TYPED VALUE'.title())
print('\033[32m =\033[m'*50)
name = str(input('\033[4m Welcome Little Locust please type your name :\033[m \n'))
print(' Hello \033[4;34m{}!\033[m nice to meet you '.format(name)... | print('\x1b[32m =\x1b[m' * 50)
print('BUILD AN PYTHON SCRIPT THAT READ AN NAME AND SHOW AN MENSAGE OF GRETTINS ACORD WITH TYPED VALUE'.title())
print('\x1b[32m =\x1b[m' * 50)
name = str(input('\x1b[4m Welcome Little Locust please type your name :\x1b[m \n'))
print(' Hello \x1b[4;34m{}!\x1b[m nice to meet you '.format(n... |
# Time: O(n)
# Space: O(1)
# dp
class Solution(object):
def countTexts(self, pressedKeys):
"""
:type pressedKeys: str
:rtype: int
"""
MOD = 10**9+7
dp = [1]*5
for i in xrange(1, len(pressedKeys)+1):
dp[i%5] = 0
for j in reversed(xrang... | class Solution(object):
def count_texts(self, pressedKeys):
"""
:type pressedKeys: str
:rtype: int
"""
mod = 10 ** 9 + 7
dp = [1] * 5
for i in xrange(1, len(pressedKeys) + 1):
dp[i % 5] = 0
for j in reversed(xrange(max(i - (4 if presse... |
def for_p():
""" Pattern of Small Alphabet: 'p' using for loop """
for i in range(9):
for j in range(4):
if i in (1,4) and j!=3 or j==0 or j==3 and i in(2,3):
print('*',end=' ')
else:
... | def for_p():
""" Pattern of Small Alphabet: 'p' using for loop """
for i in range(9):
for j in range(4):
if i in (1, 4) and j != 3 or j == 0 or (j == 3 and i in (2, 3)):
print('*', end=' ')
else:
print(' ', end=' ')
print()
def while_p():
... |
# coding:utf-8
class SSError(Exception):
pass
| class Sserror(Exception):
pass |
# x = int(input("How many candies you want:"))
# av = 5
# i = 1
# while i <= x:
# if i > av:
# print("We are out of stock")
# break
# print("Candy")
# i = i+1
# print("Bye")
# for i in range(1,101):
# if i %3 == 0 and i%5==0:# skip the values whick=h are divisible by 3 and(both) ... | x = int(input('How many candies do you want?'))
av = 3
i = 1
while i <= x:
if i > av:
break
print('candy')
i = i + 1
print('Bye') |
def parse_field(field):
name, valid = field.split(':')
valid = [tuple(map(int, r)) for r in
(r.split('-') for r in valid.split(' or '))]
return name, valid
def read_ticket(_ticket):
return list(map(int, _ticket.split(',')))
with open("input.txt") as f:
fields, ticket, nearby = f.rea... | def parse_field(field):
(name, valid) = field.split(':')
valid = [tuple(map(int, r)) for r in (r.split('-') for r in valid.split(' or '))]
return (name, valid)
def read_ticket(_ticket):
return list(map(int, _ticket.split(',')))
with open('input.txt') as f:
(fields, ticket, nearby) = f.read().split(... |
# do not create a map in this way
names = ['Jack', 'John', 'Joe', 'Mary']
m = {}
for name in names:
m[name] = len(name)
# create a map in this way, using a map comprehension
names = ['Jack', 'John', 'Joe', 'Mary']
m = {name: len(name) for name in names}
| names = ['Jack', 'John', 'Joe', 'Mary']
m = {}
for name in names:
m[name] = len(name)
names = ['Jack', 'John', 'Joe', 'Mary']
m = {name: len(name) for name in names} |
# code/load_original_interkey_speeds.py
# Left: Right:
# 1 2 3 4 25 28 13 14 15 16 31
# 5 6 7 8 26 29 17 18 19 20 32
# 9 10 11 12 27 30 21 22 23 24
Time24x24 = np.array([
[196,225,204,164,266,258,231,166,357,325,263,186,169,176,178,186,156,156,158,163,171,175,177,189],
[225,181,1... | time24x24 = np.array([[196, 225, 204, 164, 266, 258, 231, 166, 357, 325, 263, 186, 169, 176, 178, 186, 156, 156, 158, 163, 171, 175, 177, 189], [225, 181, 182, 147, 239, 245, 196, 150, 289, 296, 229, 167, 162, 169, 170, 178, 148, 148, 150, 155, 163, 167, 169, 182], [204, 182, 170, 149, 196, 194, 232, 155, 237, 214, 263... |
class Solution(object):
def bitwiseComplement(self, num):
"""
:type N: int
:rtype: int
"""
return (1 << len(bin(num)) >> 2) - num - 1
| class Solution(object):
def bitwise_complement(self, num):
"""
:type N: int
:rtype: int
"""
return (1 << len(bin(num)) >> 2) - num - 1 |
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
maxlen = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = int(matrix[i][j])
if matrix[i][j] and i and j:
matrix[i][j] = min(matrix[i... | class Solution:
def maximal_square(self, matrix: List[List[str]]) -> int:
maxlen = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = int(matrix[i][j])
if matrix[i][j] and i and j:
matrix[i][j] = min(matrix[i... |
class InvalidListOfWordsException(Exception):
print("Invalid list of words exception raised")
class InvalidWordException(Exception):
print("InvalidWordException raised")
class GameWonException(Exception):
print("You won the game! Congrats!")
class GameLostException(Exception):
print("You lost the ... | class Invalidlistofwordsexception(Exception):
print('Invalid list of words exception raised')
class Invalidwordexception(Exception):
print('InvalidWordException raised')
class Gamewonexception(Exception):
print('You won the game! Congrats!')
class Gamelostexception(Exception):
print('You lost the gam... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0.20107669 0.29543058 -0.16135565 -0.26139101 0.21345801]]\n",
"[ 0.20107669 0.29543058 -0.16135565 -0.26139101 0.21345801]... | {'cells': [{'cell_type': 'code', 'execution_count': 24, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['[[ 0.20107669 0.29543058 -0.16135565 -0.26139101 0.21345801]]\n', '[ 0.20107669 0.29543058 -0.16135565 -0.26139101 0.21345801]\n']}, {'ename': 'ValueError', 'evalue': 'operands c... |
def power_level(x, y, grid_sn):
rack_id = x + 10
result = rack_id * y + grid_sn
result *= rack_id
return (result % 1000 // 100) - 5
def create_grid(grid_sn):
return [[power_level(x, y, grid_sn) for y in range(301)]
for x in range(301)]
def best(grid_sn, sq):
grid = create_grid(gr... | def power_level(x, y, grid_sn):
rack_id = x + 10
result = rack_id * y + grid_sn
result *= rack_id
return result % 1000 // 100 - 5
def create_grid(grid_sn):
return [[power_level(x, y, grid_sn) for y in range(301)] for x in range(301)]
def best(grid_sn, sq):
grid = create_grid(grid_sn)
def ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 00:39:06 2018
@author: Mohammed
"""
#Problem Statement
"""
An isogram is a word that has no repeating letters, consecutive or
non-consecutive. Implement a function that determines whether a string
that contains only letters is an isogram. Assume the empty string is ... | """
Created on Wed Aug 15 00:39:06 2018
@author: Mohammed
"""
'\nAn isogram is a word that has no repeating letters, consecutive or \nnon-consecutive. Implement a function that determines whether a string \nthat contains only letters is an isogram. Assume the empty string is an \nisogram. Ignore letter case.\n\nis_iso... |
class queue_array():
def __init__(self, length = 10):
self.array = [None]*length
self.index = 0
def __str__(self):
output = ""
for i in range(len(self.array)):
if (self.array[i]):
output += str(self.array[i]) + " -> "
output += " End "
... | class Queue_Array:
def __init__(self, length=10):
self.array = [None] * length
self.index = 0
def __str__(self):
output = ''
for i in range(len(self.array)):
if self.array[i]:
output += str(self.array[i]) + ' -> '
output += ' End '
re... |
# put lua51 include path before macports in case lua 5.2 is installed
CPPPATH = ['__PREFIX__/include/lua-5.1', '__PREFIX__/include']
CPPDEFINES = []
LIBPATH = ['__PREFIX__/lib']
CCFLAGS = ['-fsigned-char']
LINKFLAGS = ['$__RPATH']
CC = ['__CC__']
CXX = ['__CXX__']
MINGWCPPPATH = []
MINGWLIBPATH = []
| cpppath = ['__PREFIX__/include/lua-5.1', '__PREFIX__/include']
cppdefines = []
libpath = ['__PREFIX__/lib']
ccflags = ['-fsigned-char']
linkflags = ['$__RPATH']
cc = ['__CC__']
cxx = ['__CXX__']
mingwcpppath = []
mingwlibpath = [] |
sjzips = [
'95101',
'95102',
'95106',
'95108',
'95109',
'95110',
'95111',
'95112',
'95113',
'95114',
'95115',
'95116',
'95117',
'95118',
'95119',
'95120',
'95121',
'95122',
'95123',
'95124',
'95125',
'95126',
'95127',
'95128... | sjzips = ['95101', '95102', '95106', '95108', '95109', '95110', '95111', '95112', '95113', '95114', '95115', '95116', '95117', '95118', '95119', '95120', '95121', '95122', '95123', '95124', '95125', '95126', '95127', '95128', '95129', '95130', '95131', '95132', '95133', '95134', '95135', '95136', '95137', '95138', '951... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 29 20:46:11 2021
@author: thibaut
function karatsuba to multiply 2 integers
"""
def karatsuba(num1, num2):
#if it's one-digit numbers just multiply
if len(str(num1))==1 and len(str(num2))==1:
return num1*num2
# write the numbers in this form:10^(... | """
Created on Thu Jul 29 20:46:11 2021
@author: thibaut
function karatsuba to multiply 2 integers
"""
def karatsuba(num1, num2):
if len(str(num1)) == 1 and len(str(num2)) == 1:
return num1 * num2
num1_lenght = len(str(num1))
num2_lenght = len(str(num2))
n = max(num1_lenght, num2_lenght)
... |
#!/usr/bin/env python
# This python script checks the sfincsOutput.h5 file for an example to
# see if the results are close to expected values. This script may be
# run directly, and it is also called when "make test" is run from the
# main SFINCS directory.
execfile('../testsCommon.py')
desiredTolerance = 0.001
... | execfile('../testsCommon.py')
desired_tolerance = 0.001
num_failures = 0
species = 0
num_failures += should_be('FSABFlow', species, 0.009193502564773663, desiredTolerance)
num_failures += should_be('particleFlux', species, -1.078924587797651e-06, desiredTolerance)
num_failures += should_be('heatFlux', species, -2.33732... |
n = int(input())
if n >= 404:
print("MSU")
elif n >= 322:
print("MPI")
elif n >= 239:
print("MIT")
else:
print(":(")
| n = int(input())
if n >= 404:
print('MSU')
elif n >= 322:
print('MPI')
elif n >= 239:
print('MIT')
else:
print(':(') |
def z_algorithm(S: str):
ret = [0] * len(S)
ret[0] = len(S)
i, j = 1, 0
while i < len(S):
while i + j < len(S) and S[j] == S[i + j]:
j += 1
ret[i] = j
if j == 0:
i += 1
continue
k = 1
while i + k < len(S) and k + ret[k] < j:
... | def z_algorithm(S: str):
ret = [0] * len(S)
ret[0] = len(S)
(i, j) = (1, 0)
while i < len(S):
while i + j < len(S) and S[j] == S[i + j]:
j += 1
ret[i] = j
if j == 0:
i += 1
continue
k = 1
while i + k < len(S) and k + ret[k] < j:... |
# ---------- PROBLEM : SECRET STRING ----------
# Receive a uppercase string and then hide its meaning by turning it into a string of unicode
# Then translate it from unicode back into its original meaning
# Enter a string to hide in uppercase
# Secret Message : 34567890
# Original Message : HIDE
# Input string to be... | orig_message = input('Enter a string in uppercase :')
secret_message = ''
for char in orig_message:
if char.isalpha():
secret_message += str(ord(char) - 23)
elif char.isspace():
secret_message += str(ord(char))
print('Secret message: ', secret_message)
norm_string = ''
for i in range(0, len(secr... |
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0) #S-BLOCK
RED = ( 255, 0, 0) # Z-BLOCK
BLUE = (0,0,255) # J-BLOCK
ORANGE = (255, 127, 0) # L-BLOCK
YELLOW = (255,255,0) # O-BLOCK
PURPLE = (128, 0 , 128) # T-BLOCK
TURQUOISE = (64, 224, 208) # I-BLOCK
x = 50 # The direction of our Blocks, LEFT... | black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
orange = (255, 127, 0)
yellow = (255, 255, 0)
purple = (128, 0, 128)
turquoise = (64, 224, 208)
x = 50
y = 50
height = 60
width = 40
vel = 5
level = [i for i in range(100)]
level_speed = [i for i in range(10)] |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 09:45:06 2022
@author: craig
"""
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
name = name1 + name2
name_lower = name.lower()
name_count_t = name_lower.count("t")
name_count_r = n... | """
Created on Tue Mar 15 09:45:06 2022
@author: craig
"""
print('Welcome to the Love Calculator!')
name1 = input('What is your name? \n')
name2 = input('What is their name? \n')
name = name1 + name2
name_lower = name.lower()
name_count_t = name_lower.count('t')
name_count_r = name_lower.count('r')
name_count_u = name... |
N = int(input())
mod = 10 ** 9 + 7
dp = [[[[0] * 4 for _ in range(4)] for _ in range(4)] for _ in range(N + 1)]
dp[0][3][3][3] = 1
for i in range(N):
for j in range(4):
for k in range(4):
for m in range(4):
if dp[i][j][k][m] == 0:
continue
... | n = int(input())
mod = 10 ** 9 + 7
dp = [[[[0] * 4 for _ in range(4)] for _ in range(4)] for _ in range(N + 1)]
dp[0][3][3][3] = 1
for i in range(N):
for j in range(4):
for k in range(4):
for m in range(4):
if dp[i][j][k][m] == 0:
continue
for ... |
load(
"@bazel_gazelle//internal:go_repository.bzl",
_go_repository = "go_repository",
)
load(
"@bazel_gazelle//internal:go_repository_cache.bzl",
"go_repository_cache",
)
load(
"@bazel_gazelle//internal:go_repository_tools.bzl",
"go_repository_tools",
)
load(
"@bazel_gazelle//internal:go... | load('@bazel_gazelle//internal:go_repository.bzl', _go_repository='go_repository')
load('@bazel_gazelle//internal:go_repository_cache.bzl', 'go_repository_cache')
load('@bazel_gazelle//internal:go_repository_tools.bzl', 'go_repository_tools')
load('@bazel_gazelle//internal:go_repository_config.bzl', 'go_repository_conf... |
# source unclear
# modified to add policy
funder_names = [
{
"name": "Wellcome Trust",
"alternate_names": "Wellcome Trust",
"works_count": 13550,
"id": 100004440,
"policy": "plan-s",
"country": "United Kingdom",
"country_iso": "GB"
},
# {
# "n... | funder_names = [{'name': 'Wellcome Trust', 'alternate_names': 'Wellcome Trust', 'works_count': 13550, 'id': 100004440, 'policy': 'plan-s', 'country': 'United Kingdom', 'country_iso': 'GB'}, {'name': 'Nederlandse Organisatie voor Wetenschappelijk Onderzoek', 'alternate_names': 'Dutch National Scientific Foundation|Dutch... |
"""
Codemonk link: https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/practice-problems/algorithm/the-final-fight-6/
Fatal Eagle has had it enough with Arjit aka Mr. XYZ who's been trying to destroy the city from the first go. He cannot
tolerate all this nuisance anymore. He's... tired of it... | """
Codemonk link: https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/practice-problems/algorithm/the-final-fight-6/
Fatal Eagle has had it enough with Arjit aka Mr. XYZ who's been trying to destroy the city from the first go. He cannot
tolerate all this nuisance anymore. He's... tired of it... |
#!/usr/bin/env python3
class TaskList():
"""Task list for Jenkins."""
tasks = []
__lock__ = False
def is_locked(self):
"""Check if list is locked."""
return self.__lock__
def lock(self):
"""Lock TaskList."""
self.__lock__ = True
def unlock(self):
"""... | class Tasklist:
"""Task list for Jenkins."""
tasks = []
__lock__ = False
def is_locked(self):
"""Check if list is locked."""
return self.__lock__
def lock(self):
"""Lock TaskList."""
self.__lock__ = True
def unlock(self):
"""Unlock TaskList."""
... |
'''10. Write a Python program to reverse the digits of a given number and add it to the original,
If the sum is not a palindrome repeat this procedure.
Note: A palindrome is a word, number, or other sequence of characters which reads the same
backward as forward, such as madam or racecar.'''
def reverseInteger(x):
... | """10. Write a Python program to reverse the digits of a given number and add it to the original,
If the sum is not a palindrome repeat this procedure.
Note: A palindrome is a word, number, or other sequence of characters which reads the same
backward as forward, such as madam or racecar."""
def reverse_integer(x):
... |
prefixes = {
8: "ampersand_angleBracket_currency_accent_tilde_mathPower_@_scriptIndicator_dagger_prefix",
16: "asterisk_roundBracket_basicMathSign_ditto_dash_prefix",
24: "genderSign_doubleQuotation_IP_accent_paragraphSection_degree_boldIndicator_ligaturedIndicator_prefix",
32: "capital_singleQuotation_... | prefixes = {8: 'ampersand_angleBracket_currency_accent_tilde_mathPower_@_scriptIndicator_dagger_prefix', 16: 'asterisk_roundBracket_basicMathSign_ditto_dash_prefix', 24: 'genderSign_doubleQuotation_IP_accent_paragraphSection_degree_boldIndicator_ligaturedIndicator_prefix', 32: 'capital_singleQuotation_prefix', 40: 'squ... |
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
l = len(cost)
if l == 2:
return min(cost)
res = [0] * (l)
for i in range(2, l):
res[i] = min(cost[i-1] + res[i-1], res[i-2] + cost[i-2])
return... | class Solution:
def min_cost_climbing_stairs(self, cost: List[int]) -> int:
l = len(cost)
if l == 2:
return min(cost)
res = [0] * l
for i in range(2, l):
res[i] = min(cost[i - 1] + res[i - 1], res[i - 2] + cost[i - 2])
return min(res[l - 1] + cost[l -... |
def get_max(lst):
return max(lst)
def get_min(lst):
return min(lst)
def get_avg(lst):
return sum(lst)/len(lst)
| def get_max(lst):
return max(lst)
def get_min(lst):
return min(lst)
def get_avg(lst):
return sum(lst) / len(lst) |
# -*- coding: utf-8 -*-
linha = int(input())
coluna = int(input())
if linha == coluna: corCasaInferiorDireito = 1
elif linha % 2 == 0:
if coluna % 2 != 0: corCasaInferiorDireito = 0
else: corCasaInferiorDireito = 1
elif linha % 2 != 0:
if coluna % 2 != 0: corCasaInferiorDireito = 1
else: corCasaInferior... | linha = int(input())
coluna = int(input())
if linha == coluna:
cor_casa_inferior_direito = 1
elif linha % 2 == 0:
if coluna % 2 != 0:
cor_casa_inferior_direito = 0
else:
cor_casa_inferior_direito = 1
elif linha % 2 != 0:
if coluna % 2 != 0:
cor_casa_inferior_direito = 1
else:... |
# read file
file = open('data.txt')
data = file.read()
file.close()
# write file
out = open('data2.txt', 'w')
out.write(data)
out.close()
| file = open('data.txt')
data = file.read()
file.close()
out = open('data2.txt', 'w')
out.write(data)
out.close() |
# -*- coding: utf-8 -*-
"""
We prefer to address the txt file containing data as the format [src des]
"""
def readFile(path):
f = open(path,'r')
array_list = []
for line in f:
src, des = map(int,line.split())
if len(array_list)-1 < src:
array_list.append([])
array_list[s... | """
We prefer to address the txt file containing data as the format [src des]
"""
def read_file(path):
f = open(path, 'r')
array_list = []
for line in f:
(src, des) = map(int, line.split())
if len(array_list) - 1 < src:
array_list.append([])
array_list[src].append(des)
... |
#
# PySNMP MIB module BDCOM-MEMORY-POOL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BDCOM-MEMORY-POOL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:19:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
"""
File: anagram.py
Name: Amber Chang
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for eac... | """
File: anagram.py
Name: Amber Chang
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for eac... |
a = int(input())
x = ""
c = 0
b = False
for i in range(a):
x += input()
for char in x:
if char == "{":
c += 1
elif char == "}":
c -= 1
if c < 0:
b = True
break
if c != 0 or b:
print("N")
else:
print("S")
| a = int(input())
x = ''
c = 0
b = False
for i in range(a):
x += input()
for char in x:
if char == '{':
c += 1
elif char == '}':
c -= 1
if c < 0:
b = True
break
if c != 0 or b:
print('N')
else:
print('S') |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
... | class Solution(object):
def add_two_numbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
head = list_node(0)
curr = head
while l1 or l2:
v1 = l1.val if l1 else 0
v2 = l2.val if... |
""" Introduction to Binary Tree """
class Node:
def __init__(self, data):
self.right=None
self.left=None
self.key=data
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(4)
| """ Introduction to Binary Tree """
class Node:
def __init__(self, data):
self.right = None
self.left = None
self.key = data
root = node(1)
root.left = node(2)
root.right = node(3)
root.left.left = node(4) |
"""
Parameter conversion table
*CONVERSION_TABLE* gives the old model name and a dictionary of old parameter
names for each parameter in sasmodels. This is used by :mod:`convert` to
determine the equivalent parameter set when comparing a sasmodels model to
the models defined in previous versions of SasView and sasmod... | """
Parameter conversion table
*CONVERSION_TABLE* gives the old model name and a dictionary of old parameter
names for each parameter in sasmodels. This is used by :mod:`convert` to
determine the equivalent parameter set when comparing a sasmodels model to
the models defined in previous versions of SasView and sasmod... |
class Contact:
def __init__(self, name, midname, last_name, nick, title, comp_name, address, home, email,
date, birth_month, birth_year):
self.name = name
self.midname = midname
self.last_name = last_name
self.nick = nick
self.title = title
... | class Contact:
def __init__(self, name, midname, last_name, nick, title, comp_name, address, home, email, date, birth_month, birth_year):
self.name = name
self.midname = midname
self.last_name = last_name
self.nick = nick
self.title = title
self.comp_name = comp_name... |
def hex_to_rgb(hex_code):
hex_code = hex_code.lstrip('#')
return tuple(int(hex_code[i:i + 2], 16) for i in (0, 2, 4))
def rgb_to_float(red, green, blue):
return tuple(x / 255.0 for x in (red, green, blue))
def hex_to_float(hex_code):
rgb = hex_to_rgb(hex_code)
return rgb_to_float(*rgb)
class C... | def hex_to_rgb(hex_code):
hex_code = hex_code.lstrip('#')
return tuple((int(hex_code[i:i + 2], 16) for i in (0, 2, 4)))
def rgb_to_float(red, green, blue):
return tuple((x / 255.0 for x in (red, green, blue)))
def hex_to_float(hex_code):
rgb = hex_to_rgb(hex_code)
return rgb_to_float(*rgb)
class ... |
def isPrime(num):
for k in range(2, num // 2):
if (num % k == 0):
return False
return True
numSets = int(input())
for _ in range(numSets):
num = int(input())
print("%d " % num, end='')
if (isPrime(num)):
print("0")
else:
i = num - 1
while True:... | def is_prime(num):
for k in range(2, num // 2):
if num % k == 0:
return False
return True
num_sets = int(input())
for _ in range(numSets):
num = int(input())
print('%d ' % num, end='')
if is_prime(num):
print('0')
else:
i = num - 1
while True:
... |
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__ (self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = f'{first.lower()}.{last.lower()}@company.com' #first + '.' + last + '@company.com'
Employee.num_of_emps += 1
... | class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = f'{first.lower()}.{last.lower()}@company.com'
Employee.num_of_emps += 1
def fullname(self):
return f... |
"""
_get_offspring and associated functions
"""
def get_complete_gen(tree):
"""
Given a tree, return a list of lists indexed by node number.
Each list entry is a set of points that can be added
as an offspring node to that node
"""
return map(_get_new_points(tree), range(len(tree)))
def _get... | """
_get_offspring and associated functions
"""
def get_complete_gen(tree):
"""
Given a tree, return a list of lists indexed by node number.
Each list entry is a set of points that can be added
as an offspring node to that node
"""
return map(_get_new_points(tree), range(len(tree)))
def _get_n... |
"""
Module with Clock which helps countdown time
"""
class Clock:
"""
Countdown time and perform an action after time is over
"""
def __init__(self, when_end=None, start_time=0):
"""
Pass start_time here if it is const
:param when_end: Action that will be performed after the ... | """
Module with Clock which helps countdown time
"""
class Clock:
"""
Countdown time and perform an action after time is over
"""
def __init__(self, when_end=None, start_time=0):
"""
Pass start_time here if it is const
:param when_end: Action that will be performed after the t... |
# 1 test case failed
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
n... | def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i = i + 6
return True
n = int(input())
arr = list(map(int, input()... |
sol = [0,1]
disBS = False
def disG(n: int):
print( "Sequence number " + str(n) + " is " + str(get(n)) )
def disS(n: int):
print( str(n) + " is sequence " + str(search(n)) )
def solT():
print( "Solution Table: \n" + "\t" + str(sol) )
def get(n: int) -> int:
if(len(sol) - 1 >= n):
# Then we have the soluti... | sol = [0, 1]
dis_bs = False
def dis_g(n: int):
print('Sequence number ' + str(n) + ' is ' + str(get(n)))
def dis_s(n: int):
print(str(n) + ' is sequence ' + str(search(n)))
def sol_t():
print('Solution Table: \n' + '\t' + str(sol))
def get(n: int) -> int:
if len(sol) - 1 >= n:
return sol[n]
... |
cities = [
'Asuncion',
'Ciudad del Este',
'San Lorenzo',
'Capiata',
'Lambare',
'Fernando de la Mora',
'Limpio',
'Nemby',
'Pedro Juan Caballero',
'Encarnacion',
'Mariano Roque Alonso',
'Itaugua',
'Villa Elisa',
'Villa Hayes',
'San Antonio',
'Caaguazu',
... | cities = ['Asuncion', 'Ciudad del Este', 'San Lorenzo', 'Capiata', 'Lambare', 'Fernando de la Mora', 'Limpio', 'Nemby', 'Pedro Juan Caballero', 'Encarnacion', 'Mariano Roque Alonso', 'Itaugua', 'Villa Elisa', 'Villa Hayes', 'San Antonio', 'Caaguazu', 'Presidente Franco', 'Coronel Oviedo', 'Concepcion', 'Villarrica', 'P... |
#input
# 17
# 15 4 3 3 16 4 14 2 2 10 11 2 6 18 17 10 4 8 11 3 19 9 4 13 6 6 14 3 3 14 19 16 17 3
# 13 5 13 14 6 4 5 6 9 3 4 17 6 10 8 8 9 16 10 3 2 15 15 4 16 10 4 13 7 5 11 19 8 5
# 13 7 17 17 14 19 19 12 6 10 19 12 17 15 2 19 15 15 14 17 11 5 19 5 11 5 15 10 11 18
# 4 6 2 2 19 2 2 12 6 10 11 17 8 6 17 7 2 13 2 18 5 ... | def choose_best_path(isle, max_candies):
rec(isle[1:], isle[0], max_candies)
def rec(isle, score, max_candies):
if len(isle) <= 1:
max_candies.append(score)
return
if len(isle) >= 2:
score1 = score + isle[1]
rec(isle[2:], score1, max_candies)
if len(isle) >= 3:
s... |
class Counter:
instance = None
def __init__(self):
self.same_as_original = 0
self.dict = {}
@staticmethod
def get():
if Counter.instance is None:
Counter.instance = Counter()
return Counter.instance
| class Counter:
instance = None
def __init__(self):
self.same_as_original = 0
self.dict = {}
@staticmethod
def get():
if Counter.instance is None:
Counter.instance = counter()
return Counter.instance |
class CILNode:
pass
class CILProgram(CILNode):
def __init__(self, dottypes, dotdata, dotcode):
self.dottypes = dottypes
self.dotdata = dotdata
self.dotcode = dotcode
class CILType(CILNode):
def __init__(self, name, attributes, methods):
self.name = name
self.attri... | class Cilnode:
pass
class Cilprogram(CILNode):
def __init__(self, dottypes, dotdata, dotcode):
self.dottypes = dottypes
self.dotdata = dotdata
self.dotcode = dotcode
class Ciltype(CILNode):
def __init__(self, name, attributes, methods):
self.name = name
self.attri... |
titles = ['Creature if Habit','Crewel Fate']
plots = ['A num turns into a monster', 'A haunted yarn shop']
movies = dict( zip(titles, plots) )
# expected output:
'''
{'Creature if Habit': 'A num turns into a monster', 'Crewel Fate': 'A haunted yarn shop'}
'''
print( movies) | titles = ['Creature if Habit', 'Crewel Fate']
plots = ['A num turns into a monster', 'A haunted yarn shop']
movies = dict(zip(titles, plots))
"\n{'Creature if Habit': 'A num turns into a monster', 'Crewel Fate': 'A haunted yarn shop'}\n"
print(movies) |
## Predicting using a regression model
# Generate predictions with the model using those inputs
predictions = model.predict(new_inputs.reshape(-1,1))
# Visualize the inputs and predicted values
plt.scatter(new_inputs, predictions, color='r', s=3)
plt.xlabel('inputs')
plt.ylabel('predictions')
plt.show() | predictions = model.predict(new_inputs.reshape(-1, 1))
plt.scatter(new_inputs, predictions, color='r', s=3)
plt.xlabel('inputs')
plt.ylabel('predictions')
plt.show() |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def _deleteDuplicates(self,head,a,pointer):
if head.next is None:
return 0
else:
if head.val == head.next.val:
a = head.val
... | def _delete_duplicates(self, head, a, pointer):
if head.next is None:
return 0
elif head.val == head.next.val:
a = head.val
return self._deleteDuplicates(head.next, a, pointer)
elif a == head.val:
return self._deleteDuplicates(head.next, a, pointer)
else:
pointer.... |
class AudioModel():
classes_: []
classifier: None
def __init__(self, settings, classifier):
self.settings = {}
self.settings['version'] = settings['version']
self.settings['RATE'] = settings['RATE']
self.settings['CHANNELS'] = settings['CHANNELS']
self.settings['... | class Audiomodel:
classes_: []
classifier: None
def __init__(self, settings, classifier):
self.settings = {}
self.settings['version'] = settings['version']
self.settings['RATE'] = settings['RATE']
self.settings['CHANNELS'] = settings['CHANNELS']
self.settings['RECORD... |
class Czlowiek:
iloscOczu = 2
def __init__(self,imie,wiek):
self.imie = imie
self.wiek = wiek
And = Czlowiek("Andrzej", 22)
Ann = Czlowiek("Anna", 17)
print(And.iloscOczu)
print(Ann.wiek)
#-------------------------------
def dodawanie(x,y):
return x+y
dod = lambda x,y: ... | class Czlowiek:
ilosc_oczu = 2
def __init__(self, imie, wiek):
self.imie = imie
self.wiek = wiek
and = czlowiek('Andrzej', 22)
ann = czlowiek('Anna', 17)
print(And.iloscOczu)
print(Ann.wiek)
def dodawanie(x, y):
return x + y
dod = lambda x, y: x + y |
class RangeMethod:
RANGE_MAX = 0
RANGE_3SIGMA = 1
RANGE_MAX_TENPERCENT = 2
RANGE_SWEEP = 3
class QuantizeMethod:
# quantize methods
FIX_NONE = 0
FIX_AUTO = 1
FIX_FIXED = 2
| class Rangemethod:
range_max = 0
range_3_sigma = 1
range_max_tenpercent = 2
range_sweep = 3
class Quantizemethod:
fix_none = 0
fix_auto = 1
fix_fixed = 2 |
def compose(*fns):
"""
Returns a function that evaluates it all
"""
def comp(*args, **kwargs):
v = fns[0](*args, **kwargs)
for fn in fns[1:]:
v = fn(v)
return v
return comp
| def compose(*fns):
"""
Returns a function that evaluates it all
"""
def comp(*args, **kwargs):
v = fns[0](*args, **kwargs)
for fn in fns[1:]:
v = fn(v)
return v
return comp |
class Logger:
def __init__(self, name: str):
self.name: str = name
def console_log(self, message: str):
print('<{0}> {1}'.format(self.name, message))
| class Logger:
def __init__(self, name: str):
self.name: str = name
def console_log(self, message: str):
print('<{0}> {1}'.format(self.name, message)) |
#
# PySNMP MIB module SEI-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SEI-SMI
# Produced by pysmi-0.3.4 at Wed May 1 15:01:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) ... |
def solution(n):
answer = 0
for i in range(1, n+1):
if n % i == 0: answer += i
return answer | def solution(n):
answer = 0
for i in range(1, n + 1):
if n % i == 0:
answer += i
return answer |
"""
Lecture 17: Approximation Algorithms
Vertex Cover
------------
This program contains two approximation algorithms
for solving the vertex cover problem for an undirected
graphs G(V, E).
A vertex cover is a subset V' of V such that
forall (u, v) in E, either u or v is in V'.
The goal is to find the smallest set V' w... | """
Lecture 17: Approximation Algorithms
Vertex Cover
------------
This program contains two approximation algorithms
for solving the vertex cover problem for an undirected
graphs G(V, E).
A vertex cover is a subset V' of V such that
forall (u, v) in E, either u or v is in V'.
The goal is to find the smallest set V' w... |
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
max_heap = []
for n in stones :
heappush(max_heap,-n)
while max_heap :
sto1 = -heappop(max_heap)
if not max_heap :
return sto1
sto2 = -heappop(max_hea... | class Solution:
def last_stone_weight(self, stones: List[int]) -> int:
max_heap = []
for n in stones:
heappush(max_heap, -n)
while max_heap:
sto1 = -heappop(max_heap)
if not max_heap:
return sto1
sto2 = -heappop(max_heap)
... |
class Spam:
def __init__(self):
self.spam = 'spam, spam, spam'
def set_eggs(eggs):
self.eggs = eggs
def __str__(self):
return '%s and %s' % (self.spam, self.eggs) # Maybe uninitialized attribute 'eggs'
#Fixed version
class Spam:
def __init__(self):
self.spam = 'spam... | class Spam:
def __init__(self):
self.spam = 'spam, spam, spam'
def set_eggs(eggs):
self.eggs = eggs
def __str__(self):
return '%s and %s' % (self.spam, self.eggs)
class Spam:
def __init__(self):
self.spam = 'spam, spam, spam'
self.eggs = None
def set_egg... |
# https://edabit.com/challenge/yfooETHj3sHoHTJsv
# Create a function that returns True when num1 is equal to num2; otherwise return False.
def same_thing(int1: int, int2: int) -> bool:
try:
if int1 == int2:
return True
elif int1 != int2:
return False
except ValueErr... | def same_thing(int1: int, int2: int) -> bool:
try:
if int1 == int2:
return True
elif int1 != int2:
return False
except ValueError as err:
print(f'Error: {err}')
print(same_thing(4, 4))
print(same_thing(5, 9)) |
# a metric cross reference:
# <haproxy metric>: (<collectd type instance>, <collectd type>)
METRIC_XREF = {
# metrics from the "show info" command
'Nbproc': ('num_processes', 'gauge'),
'Process_num': ('process_num', 'gauge'),
'Pid': ('pid', 'gauge'),
'Uptime_sec': ('uptime_seconds', 'gauge'),
... | metric_xref = {'Nbproc': ('num_processes', 'gauge'), 'Process_num': ('process_num', 'gauge'), 'Pid': ('pid', 'gauge'), 'Uptime_sec': ('uptime_seconds', 'gauge'), 'Memmax_MB': ('max_memory_mb', 'gauge'), 'Maxsock': ('max_sockets', 'gauge'), 'Maxconn': ('max_connections', 'gauge'), 'Hard_maxconn': ('hard_max_connections'... |
class Tree:
def __init__(self, content):
self.content = content
self.children = []
def add_child(self, tree):
if not isinstance(tree, Tree):
tree = self.__class__(tree)
self.children.append(tree)
return self
def add_children(self, *trees):
for tr... | class Tree:
def __init__(self, content):
self.content = content
self.children = []
def add_child(self, tree):
if not isinstance(tree, Tree):
tree = self.__class__(tree)
self.children.append(tree)
return self
def add_children(self, *trees):
for t... |
CLUSTER_NODE_LABEL = 'Cluster'
CLUSTER_RELATION_TYPE = 'CLUSTER'
CLUSTER_REVERSE_RELATION_TYPE = 'CLUSTER_OF'
CLUSTER_NAME_PROP_KEY = 'name'
| cluster_node_label = 'Cluster'
cluster_relation_type = 'CLUSTER'
cluster_reverse_relation_type = 'CLUSTER_OF'
cluster_name_prop_key = 'name' |
'''
Created on 23. nov. 2015
@author: kga
'''
MYSQL = "mysql"
POSTGRESSQL = "postgressql"
SQLITE = "sqlite"
ORACLE = "oracle"
| """
Created on 23. nov. 2015
@author: kga
"""
mysql = 'mysql'
postgressql = 'postgressql'
sqlite = 'sqlite'
oracle = 'oracle' |
#!/usr/bin/python
CLUSTER_NAME = 'gcp-integration-test-cluster'
LOGNAME_LENGTH = 16
LOGGING_PREFIX = 'GCP_INTEGRATION_TEST_'
DEFAULT_TIMEOUT = 30 # seconds
ROOT_ENDPOINT = '/'
ROOT_EXPECTED_OUTPUT = 'Hello World!'
STANDARD_LOGGING_ENDPOINT = '/logging_standard'
CUSTOM_LOGGING_ENDPOINT = '/logging_custom'
MONITOR... | cluster_name = 'gcp-integration-test-cluster'
logname_length = 16
logging_prefix = 'GCP_INTEGRATION_TEST_'
default_timeout = 30
root_endpoint = '/'
root_expected_output = 'Hello World!'
standard_logging_endpoint = '/logging_standard'
custom_logging_endpoint = '/logging_custom'
monitoring_endpoint = '/monitoring'
except... |
class Team:
def __init__(
self,
name: str,
team_id: str,
wins: int,
losses: int,
line_scores: list,
):
self.name = name
self.team_id = team_id
self.wins = wins
self.losses = losses
self.line_scores = line_scores
def __s... | class Team:
def __init__(self, name: str, team_id: str, wins: int, losses: int, line_scores: list):
self.name = name
self.team_id = team_id
self.wins = wins
self.losses = losses
self.line_scores = line_scores
def __str__(self):
s = 'Team(name={}, team_id={}, win... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What ... | """
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a... |
x = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 3.6, 4.8, 7.2, 9.6, 14.4, 19.2]
with open("../test.txt") as f:
l = f.readlines()
for i in range(len(l)):
l[i] = l[i].split()
print(f'{x[i]:.1f} & 3 & {l[i][0]} & {l[i][1]} & {l[i][2]} ' + r'\\')
| x = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 3.6, 4.8, 7.2, 9.6, 14.4, 19.2]
with open('../test.txt') as f:
l = f.readlines()
for i in range(len(l)):
l[i] = l[i].split()
print(f'{x[i]:.1f} & 3 & {l[i][0]} & {l[i][1]} & {l[i][2]} ' + '\\\\') |
def bubble_sort(arr):
length = len(arr)
while True:
swapped = False
for i in range(1, length):
if arr[i - 1] > arr[i]:
arr[i - 1], arr[i] = arr[i], arr[i - 1]
swapped = True
if not swapped:
break
else:
pass
... | def bubble_sort(arr):
length = len(arr)
while True:
swapped = False
for i in range(1, length):
if arr[i - 1] > arr[i]:
(arr[i - 1], arr[i]) = (arr[i], arr[i - 1])
swapped = True
if not swapped:
break
else:
pass
... |
#
# PySNMP MIB module HH3C-OBJP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-OBJP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:28:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, value_size_constraint, constraints_union, single_value_constraint) ... |
# Given an integer array nums, return true if any value appears at least twice in the array, and return false if
# every element is distinct.
#
# Example 1:
# Input: nums = [1, 2, 3, 1]
# Output: true
#
# Example 2:
# Input: nums = [1, 2, 3, 4]
# Output: false
#
# Example 3:
# Input: nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, ... | class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
hashset = set()
for num in nums:
if num in hashset:
return True
hashset.add(num)
return False |
"""Reads initial conditions from a file and outputs to a dictionary."""
class fileInput(object):
"""Loads data then outputs an initial parameters dictionary."""
def updateDict(initParams, filename=None):
"""Update and return the initial parameter dictionary from a file."""
labelToParam_MD = i... | """Reads initial conditions from a file and outputs to a dictionary."""
class Fileinput(object):
"""Loads data then outputs an initial parameters dictionary."""
def update_dict(initParams, filename=None):
"""Update and return the initial parameter dictionary from a file."""
label_to_param_md =... |
list=[1,2,3,2,1,4,56,8,7]
newlist=[]
for i in range(0,len(list)):
if(list[i] in newlist):
continue
newlist.append(list[i])
print("old list: \t\t",list)
print("unique elements :",newlist)
| list = [1, 2, 3, 2, 1, 4, 56, 8, 7]
newlist = []
for i in range(0, len(list)):
if list[i] in newlist:
continue
newlist.append(list[i])
print('old list: \t\t', list)
print('unique elements :', newlist) |
p, d, m, s = map(int, input().split())
count = 0
total = 0
while p >= m and total <= s:
total += p
p -= d
count += 1
if p - d < m:
while total <= s:
total += m
count += 1
print(count-1)
| (p, d, m, s) = map(int, input().split())
count = 0
total = 0
while p >= m and total <= s:
total += p
p -= d
count += 1
if p - d < m:
while total <= s:
total += m
count += 1
print(count - 1) |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
cf-configuration-exporter
"""
__program__ = "cf-configuration-exporter"
__version__ = "0.0.13"
__author__ = "Claudio Benfatto"
__year__ = "2017"
__email__ = "<claudio.benfatto@springer.com>"
__license__ = "MIT"
| """
cf-configuration-exporter
"""
__program__ = 'cf-configuration-exporter'
__version__ = '0.0.13'
__author__ = 'Claudio Benfatto'
__year__ = '2017'
__email__ = '<claudio.benfatto@springer.com>'
__license__ = 'MIT' |
'''
Created on 1.12.2016
@author: Darren
''''''
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
click to show clarifica... | """
Created on 1.12.2016
@author: Darren
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
click to show clarification.
Clarification:
... |
#!/usr/bin/env python -tt
#
# Copyright (c) 2007 Red Hat, Inc.
# Copyright (c) 2011 Intel, Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; version 2 of the License
#
# This program is dis... | class Wicerror(Exception):
pass |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p1 = None
p2 = head
while p2 is not None:
temp1 = p1
te... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
p1 = None
p2 = head
while p2 is not None:
temp1 = p1
temp2 = p2
p1 = temp2
... |
"""
Implementing some of the LinkedList functions
In this file I try to practice on how to play with Linkedlists and thsi makes me more Familiar with
Linkedlists
"""
class Node:
def __init__(self,data=None,next=None):
self.data = data
self.next =next
class LinkedList:
def __init__ (self):
... | """
Implementing some of the LinkedList functions
In this file I try to practice on how to play with Linkedlists and thsi makes me more Familiar with
Linkedlists
"""
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class Linkedlist:
def __init__(self):... |
"""
Jamie Thayer -- Project Week 8
"""
""" Problem 1a and 1b """
def diff_first_last(L, *opArg):
"""
(list) -> boolean
Precondition: len(L) >= 2
Returns True if the first item of the list is different from the last; else returns False.
>>> diff_first_last([3, 4, 2, 8, 3])
False
>>> diff... | """
Jamie Thayer -- Project Week 8
"""
' Problem 1a and 1b '
def diff_first_last(L, *opArg):
"""
(list) -> boolean
Precondition: len(L) >= 2
Returns True if the first item of the list is different from the last; else returns False.
>>> diff_first_last([3, 4, 2, 8, 3])
False
>>> diff_firs... |
# -*- coding: utf-8 -*-
"""
A toolkit for python dict type
"""
class DictToolkit(object):
@staticmethod
def merge_dict(original: dict, updates: dict):
if original is None and updates is None:
return None
if original is None:
return updates
if updates is None:
... | """
A toolkit for python dict type
"""
class Dicttoolkit(object):
@staticmethod
def merge_dict(original: dict, updates: dict):
if original is None and updates is None:
return None
if original is None:
return updates
if updates is None:
return origina... |
DATA_MEAN = 168.3172158554484
DATA_STD = 340.21625683608994
OUTPUT_CHANNELS = 1
DATA_PATH = "/home/matthew/Documents/unet_model/6375_images/"
WEIGHTS = "/home/matthew/Documents/unet_model/dsc_after_bce_old.hdf5"
| data_mean = 168.3172158554484
data_std = 340.21625683608994
output_channels = 1
data_path = '/home/matthew/Documents/unet_model/6375_images/'
weights = '/home/matthew/Documents/unet_model/dsc_after_bce_old.hdf5' |
'''
lab4 dict and tuple
'''
#3.1
my_dict = {
'name' : 'Athena',
'id':123
}
print(my_dict)
#3.2
print(my_dict.values())
print(my_dict.keys())
#3.3
my_dict['id']=321 #changing the value
print(my_dict)
#3.4
my_dict.pop('name',None)
print(my_dict)
#3.5
my_tweet = {
"tweet_id":1138,
"coordinates":(-75,... | """
lab4 dict and tuple
"""
my_dict = {'name': 'Athena', 'id': 123}
print(my_dict)
print(my_dict.values())
print(my_dict.keys())
my_dict['id'] = 321
print(my_dict)
my_dict.pop('name', None)
print(my_dict)
my_tweet = {'tweet_id': 1138, 'coordinates': (-75, 40), 'visited_countries': ['GR', 'HK', 'MY']}
print(my_tweet)
pr... |
#
# PySNMP MIB module MICOMFLTR (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MICOMFLTR
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
"""
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it
returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that
reads n characters from the fil... | """
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it
returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that
reads n characters from the fil... |
def delta(x):
if x==0:
y=1;
else:
y=0;
return(y) | def delta(x):
if x == 0:
y = 1
else:
y = 0
return y |
a=97
b= 98
while(a>=97 and a <=1003):
if(a%2==0):
print("{:.0f}".format(c))
a= a+1
c= (a+b)*226.5 | a = 97
b = 98
while a >= 97 and a <= 1003:
if a % 2 == 0:
print('{:.0f}'.format(c))
a = a + 1
c = (a + b) * 226.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.