content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Normal Lambda Expression
lambda_Func = lambda x, y : x + y
print("Normal Lambda : ",lambda_Func(x = 15, y =20))
# Argumental Lambda Expression
lambda_Args = lambda *args : sum(args)
print("Args Lambda : ",lambda_Args(10,20,30,40,50))
# Key Value Argumental Lambda Expression
lambda_KeyArgs = lambda **args : sum(ar... | lambda__func = lambda x, y: x + y
print('Normal Lambda : ', lambda__func(x=15, y=20))
lambda__args = lambda *args: sum(args)
print('Args Lambda : ', lambda__args(10, 20, 30, 40, 50))
lambda__key_args = lambda **args: sum(args.values())
print('Key Value Args Lambda : ', lambda__key_args(one=1, three=3, five=5, seven=7)) |
def heapify(arr):
n = len(arr)
for i in reversed(range(n//2)):
shift_down(arr, n, i)
def shift_down(arr, n, k):
while 2 * k + 1 < n:
j = 2 * k + 1
if j + 1 < n and arr[j + 1] < arr[j]:
j += 1
if arr[k] <= arr[j]:
break
arr[k], arr[j] = arr[j]... | def heapify(arr):
n = len(arr)
for i in reversed(range(n // 2)):
shift_down(arr, n, i)
def shift_down(arr, n, k):
while 2 * k + 1 < n:
j = 2 * k + 1
if j + 1 < n and arr[j + 1] < arr[j]:
j += 1
if arr[k] <= arr[j]:
break
(arr[k], arr[j]) = (ar... |
# -*- coding: utf-8 -*-
class LossModelBertottiError(Exception):
"""Raised when there is a Loss error"""
pass
| class Lossmodelbertottierror(Exception):
"""Raised when there is a Loss error"""
pass |
number_of_chicken_menu = int(input())
number_of_fish_menu = int(input())
number_of_vege_menu = int(input())
chicken_menu = 10.35
fish_menu = 12.40
vege_menu = 8.15
total_chicken = chicken_menu * number_of_chicken_menu
total_fish = fish_menu * number_of_fish_menu
total_vege = vege_menu * number_of_vege_menu
sum_of_al... | number_of_chicken_menu = int(input())
number_of_fish_menu = int(input())
number_of_vege_menu = int(input())
chicken_menu = 10.35
fish_menu = 12.4
vege_menu = 8.15
total_chicken = chicken_menu * number_of_chicken_menu
total_fish = fish_menu * number_of_fish_menu
total_vege = vege_menu * number_of_vege_menu
sum_of_all = ... |
def brick_sort(arr):
n = len(arr)
is_sorted = 0
while is_sorted == 0:
is_sorted = 1
for i in range(1, n-1, 2):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
is_sorted = 0
for i in range(0, n-1, 2):
if arr[i] > arr... | def brick_sort(arr):
n = len(arr)
is_sorted = 0
while is_sorted == 0:
is_sorted = 1
for i in range(1, n - 1, 2):
if arr[i] > arr[i + 1]:
(arr[i], arr[i + 1]) = (arr[i + 1], arr[i])
is_sorted = 0
for i in range(0, n - 1, 2):
if a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class WeightedQuickUnion(object):
def __init__(self, data=None):
self.id = data
self.weight = [1] * len(data)
self.count = len(data)
def count(self):
return self.count
def find(self, val):
n = val
while self.i... | class Weightedquickunion(object):
def __init__(self, data=None):
self.id = data
self.weight = [1] * len(data)
self.count = len(data)
def count(self):
return self.count
def find(self, val):
n = val
while self.id[n] != n:
self.id[n] = self.id[self... |
# Exercise 1.4.
# Observe that our model of evaluation allows for combinations whose operators are compound expressions.
# Use this observation to describe the behavior of the following procedure:
# (define (a-plus-abs-b a b)
# ((if (> b 0) + -) a b))
def a_plus_abs_b (a, b):
if b > 0:
return a + b
el... | def a_plus_abs_b(a, b):
if b > 0:
return a + b
elif b <= 0:
return a - b
print(a_plus_abs_b(a, b)) |
class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
lis = [s.split(",") for s in transactions]
l = len(transactions)
ans = []
for i in range(0, l):
if int(lis[i][2]) > 1000:
ans.append(transactions[i])
conti... | class Solution:
def invalid_transactions(self, transactions: List[str]) -> List[str]:
lis = [s.split(',') for s in transactions]
l = len(transactions)
ans = []
for i in range(0, l):
if int(lis[i][2]) > 1000:
ans.append(transactions[i])
con... |
def getLockdownFirewallConfigCommand(root):
for command in root.iter('command'):
if 'name' in command.attrib and \
'/usr/bin/firewall-config' in command.attrib['name']:
return command.attrib['name']
return ''
def getEbtablesTablesInUse(root):
tables = []
for rule in roo... | def get_lockdown_firewall_config_command(root):
for command in root.iter('command'):
if 'name' in command.attrib and '/usr/bin/firewall-config' in command.attrib['name']:
return command.attrib['name']
return ''
def get_ebtables_tables_in_use(root):
tables = []
for rule in root.iter(... |
x = ' \033[34mDESAFIO 07\033[m '
print('{:=^22}'.format(x))
n1 = float(input('Informe a primeira nota: '))
n2 = float(input('Informe a segunda nota: '))
media = (n1+n2) /2
print('A sua media e \033[36m{:.1f}\033[m'.format(media)) | x = ' \x1b[34mDESAFIO 07\x1b[m '
print('{:=^22}'.format(x))
n1 = float(input('Informe a primeira nota: '))
n2 = float(input('Informe a segunda nota: '))
media = (n1 + n2) / 2
print('A sua media e \x1b[36m{:.1f}\x1b[m'.format(media)) |
p=float(input('qual o preco do produto?'))
des=p*5/100
pf=p-des
print('o preco final com desconto de 5% fica ', pf)
| p = float(input('qual o preco do produto?'))
des = p * 5 / 100
pf = p - des
print('o preco final com desconto de 5% fica ', pf) |
class Node:
def __init__(self, element):
self.item = element
self.next_link = None
class CircularLinkedList:
def __init__(self):
self.head = Node(None)
self.tail = Node(None)
self.head.next_link = self.tail
self.tail.next_link = self.head
def is_empty(self)... | class Node:
def __init__(self, element):
self.item = element
self.next_link = None
class Circularlinkedlist:
def __init__(self):
self.head = node(None)
self.tail = node(None)
self.head.next_link = self.tail
self.tail.next_link = self.head
def is_empty(self... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class HashTable():
def __init__(self, size):
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[has... | class Hashtable:
def __init__(self, size):
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] is None:
self.slots[hashvalue] =... |
#%%
def test(s,seq):
if s == '' or seq == []:
return s == '' and seq == [] # if both are empty, True. If only one, False.
r = rules[seq[0]]
if '"' in r:
if s[0] in r:
return test(s[1:], seq[1:]) # strip first character
else:
return False # wrong first cha... | def test(s, seq):
if s == '' or seq == []:
return s == '' and seq == []
r = rules[seq[0]]
if '"' in r:
if s[0] in r:
return test(s[1:], seq[1:])
else:
return False
else:
return any((test(s, t + seq[1:]) for t in r))
def parse_rule(s):
(n, e) =... |
def magic_index(array, seed = 0):
if len(array) == 0: return None
middle = len(array) // 2
if array[middle] == middle + seed: return middle + seed
if middle == 0: return None
if array[middle] > middle:
return magic_index(array[:middle], seed)
return magic_index(array[(middle + 1):], mid... | def magic_index(array, seed=0):
if len(array) == 0:
return None
middle = len(array) // 2
if array[middle] == middle + seed:
return middle + seed
if middle == 0:
return None
if array[middle] > middle:
return magic_index(array[:middle], seed)
return magic_index(arra... |
class Message(object):
__slots__ = ['opcode', 'position',
'is_event']
| class Message(object):
__slots__ = ['opcode', 'position', 'is_event'] |
def range2region(s):
if ';' in s:
parts = s.split(';')
return range2region(parts[0]) + range2region(parts[1])
parts = s.split('-')
parts = [int(x) for x in parts]
return range(parts[0], parts[1]+1)
| def range2region(s):
if ';' in s:
parts = s.split(';')
return range2region(parts[0]) + range2region(parts[1])
parts = s.split('-')
parts = [int(x) for x in parts]
return range(parts[0], parts[1] + 1) |
# Get your keys from https://apps.twitter.com/
consumer_key = '*****'
consumer_secret = '*****'
access_token = '*****'
access_token_secret = '*****'
| consumer_key = '*****'
consumer_secret = '*****'
access_token = '*****'
access_token_secret = '*****' |
def find_pythagorean_triplet_sum(sum):
c = 1
while(c < sum):
c += 1
b = 1
while(b < c):
a = 1
while(a < b):
if (check_pythagorean_triplet(a, b, c) and (a + b + c) == sum):
return [a, b, c]
a += 1
b +=... | def find_pythagorean_triplet_sum(sum):
c = 1
while c < sum:
c += 1
b = 1
while b < c:
a = 1
while a < b:
if check_pythagorean_triplet(a, b, c) and a + b + c == sum:
return [a, b, c]
a += 1
b += 1
def... |
#!/bin/python3
# Copyright 2020 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | """Generates testcases for grid.torusGet"""
grid = ['++#+++++', '#++#++++', '#+###+++', '######++', '++#####+', '+++###++', '++++#+++', '+++++++#']
cases = []
for x in range(-1, 9):
for y in range(-1, 9):
cases.append('\t\t{{\n\t\t\tx: {},\n\t\t\ty: {},\n\t\t\texpected: state.{},\n\t\t}},'.format(x, y, 'Ali... |
"""
BioThings Explorer.
.. moduleauthor:: Jiwen Xin <kevinxin@scripps.edu>
""" | """
BioThings Explorer.
.. moduleauthor:: Jiwen Xin <kevinxin@scripps.edu>
""" |
#!/usr/bin/python3
def format_number(str):
w = ""
for ch in str:
if (ch>='0' and ch<='9') or (ch>='A' and ch<='Z') or (ch >='a' and ch <= 'z') or (ch == ' '):
w+=ch
if w.startswith("91"):
w = w[2:]
return "'"+w+"'"
def format_msg(msg):
w=""
msg = msg.lower()
fo... | def format_number(str):
w = ''
for ch in str:
if ch >= '0' and ch <= '9' or (ch >= 'A' and ch <= 'Z') or (ch >= 'a' and ch <= 'z') or (ch == ' '):
w += ch
if w.startswith('91'):
w = w[2:]
return "'" + w + "'"
def format_msg(msg):
w = ''
msg = msg.lower()
for ch i... |
def nti_triangle(n):
return n*(n+1)//2
def dodaj_triangle(sez, n):
return sez + [nti_triangle(n)]
def nta_penta(n):
return n*(3*n - 1)//2
def dodaj_pento(sez, n):
return sez + [nta_penta(n)]
def nta_hexa(n):
return n*(2*n - 1)
def dodaj_hexo(sez, n):
return sez + [nta_hexa(n)]
triangli = [1]
t ... | def nti_triangle(n):
return n * (n + 1) // 2
def dodaj_triangle(sez, n):
return sez + [nti_triangle(n)]
def nta_penta(n):
return n * (3 * n - 1) // 2
def dodaj_pento(sez, n):
return sez + [nta_penta(n)]
def nta_hexa(n):
return n * (2 * n - 1)
def dodaj_hexo(sez, n):
return sez + [nta_hexa(n... |
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack, res = [], 0
for i, c in enumerate(s):
if c == '(':
stack.append(i)
else:
if stack and s[stack[-1]] == '(':
... | class Solution:
def longest_valid_parentheses(self, s):
"""
:type s: str
:rtype: int
"""
(stack, res) = ([], 0)
for (i, c) in enumerate(s):
if c == '(':
stack.append(i)
elif stack and s[stack[-1]] == '(':
stack.... |
# 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
class Solution:
def counting(self, node) -> int:
if not node:
return 0
else:
return self.c... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def counting(self, node) -> int:
if not node:
return 0
else:
return self.counting(node.left) + self.counting(nod... |
"""
N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring,
a switch also changes the state of all the bulbs to the right of current bulb. Given an initial state of all bulbs,
find the minimum number of switches you have to press to turn on all the bulbs. You can ... | """
N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring,
a switch also changes the state of all the bulbs to the right of current bulb. Given an initial state of all bulbs,
find the minimum number of switches you have to press to turn on all the bulbs. You can ... |
ABBREVIATIONS = {
'ALLPURP': 'All Purpose',
'AL': 'Aluminum',
'&': 'And',
'APPL': 'Apple',
'APPLS': 'Apples',
'APPLSAUC': 'Applesauce',
'APPROX': 'Approximately',
'ARM&BLD': 'Arm and Blade',
'ART': 'Artificial',
'VIT C': 'Vitamin C',
'ASPRT': 'Aspartame',
'ASPRT-S... | abbreviations = {'ALLPURP': 'All Purpose', 'AL': 'Aluminum', '&': 'And', 'APPL': 'Apple', 'APPLS': 'Apples', 'APPLSAUC': 'Applesauce', 'APPROX': 'Approximately', 'ARM&BLD': 'Arm and Blade', 'ART': 'Artificial', 'VIT C': 'Vitamin C', 'ASPRT': 'Aspartame', 'ASPRT-SWTND': 'Aspartame-sweetened', 'BABYFD': 'Babyfood... |
"""
FIT1008 Prac 5 Task 2
@purpose binary.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140823
@created 20140822
"""
def binary():
"""
@purpose This function accepts a positive integer,
and outputs the binary representation of the integer.
@parameter: None
@complexity:
... | """
FIT1008 Prac 5 Task 2
@purpose binary.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140823
@created 20140822
"""
def binary():
"""
@purpose This function accepts a positive integer,
and outputs the binary representation of the integer.
@parameter: None
@complexity:
... |
URL = {
"WS_LATEST_BLOCK": "wss://ws.blockchain.info/inv",
"LATEST_BLOCK": "https://blockchain.info/latestblock",
"RAW_BLOCK": "https://blockchain.info/rawblock/",
}
NEW_BLOCK_WAITING_TIME = 10.0
NUMBER_OF_BLOCKS_ON_A_PAGE = 5
NEED_FIELDS_OF_TRANSACTION = (
"block_index",
"hash",
"... | url = {'WS_LATEST_BLOCK': 'wss://ws.blockchain.info/inv', 'LATEST_BLOCK': 'https://blockchain.info/latestblock', 'RAW_BLOCK': 'https://blockchain.info/rawblock/'}
new_block_waiting_time = 10.0
number_of_blocks_on_a_page = 5
need_fields_of_transaction = ('block_index', 'hash', 'inputs', 'out', 'time', 'tx_index')
need_f... |
class ProtobufException(Exception):
SYMBOL = 0
NOT_FOUND = 1
@property
def sym(self):
return self._sym
@property
def code(self):
return self._code
def __init__(self, code, sym=None):
self._code = code
self._sym = sym
if code == ProtobufException.SYM... | class Protobufexception(Exception):
symbol = 0
not_found = 1
@property
def sym(self):
return self._sym
@property
def code(self):
return self._code
def __init__(self, code, sym=None):
self._code = code
self._sym = sym
if code == ProtobufException.SYM... |
ies = []
ies.append({ "iei" : "", "value" : "Paging identity", "type" : "Paging identity", "reference" : "9.9.3.25A", "presence" : "M", "format" : "V", "length" : "1"})
ies.append({ "iei" : "60", "value" : "CLI", "type" : "CLI", "reference" : "9.9.3.38", "presence" : "O", "format" : "TLV", "length" : "3-14"})
ies.appen... | ies = []
ies.append({'iei': '', 'value': 'Paging identity', 'type': 'Paging identity', 'reference': '9.9.3.25A', 'presence': 'M', 'format': 'V', 'length': '1'})
ies.append({'iei': '60', 'value': 'CLI', 'type': 'CLI', 'reference': '9.9.3.38', 'presence': 'O', 'format': 'TLV', 'length': '3-14'})
ies.append({'iei': '61', ... |
def recovery_factor_drygas_waterdrive(swi, Bgi, sgr, Bga):
"recovery factor of dry gas reservoir with waterdrive"
# gas FVF at abandonment pressure (RB/scf)
# sgr: residual gas saturation
rf = (((1 - swi) / Bgi) - (sgr / Bga)) / ((1 - swi) / Bgi)
return(rf)
def recovery_factor_drygas_volumetric(Bgi, Bga):
... | def recovery_factor_drygas_waterdrive(swi, Bgi, sgr, Bga):
"""recovery factor of dry gas reservoir with waterdrive"""
rf = ((1 - swi) / Bgi - sgr / Bga) / ((1 - swi) / Bgi)
return rf
def recovery_factor_drygas_volumetric(Bgi, Bga):
"""recovery factor of dry gas reservoir with NO waterdrive"""
rf = ... |
# Input = [1, 1, 2, 2, 3, 4, 4] : ordered list
# Output = [1, 2, 3, 4]
def remove_dups(l):
if not l or len(l) == 0:
return
f = None
i = 0
while i < len(l):
if l[i] == f:
del l[i]
else:
f = l[i]
i += 1
| def remove_dups(l):
if not l or len(l) == 0:
return
f = None
i = 0
while i < len(l):
if l[i] == f:
del l[i]
else:
f = l[i]
i += 1 |
#!/usr/bin/python3
def simple_delete(a_dictionary, key=""):
if key is not '' and key in a_dictionary:
a_dictionary.pop(key)
return a_dictionary
| def simple_delete(a_dictionary, key=''):
if key is not '' and key in a_dictionary:
a_dictionary.pop(key)
return a_dictionary |
"""
This module provides functions for processing station relative river
level data to identify high flood risk locations
"""
def stations_level_over_threshold(stations, tol):
"""
Returns a list of tuples, where each tuple holds
(i) a station (object) at which the latest relative water level is over tol and
(ii)... | """
This module provides functions for processing station relative river
level data to identify high flood risk locations
"""
def stations_level_over_threshold(stations, tol):
"""
Returns a list of tuples, where each tuple holds
(i) a station (object) at which the latest relative water level is over tol and
(i... |
def merge(a, aux, lo:int, mid: int, hi:int):
#TODO: can we get rid of this?
for i in range(lo, hi+1):
aux[i] = a[i]
i = lo
j = mid+1
for k in range(lo, hi+1):
#if exhausted first half
if i > mid:
a[k] = aux[j]
j += 1
#else if exhausted second... | def merge(a, aux, lo: int, mid: int, hi: int):
for i in range(lo, hi + 1):
aux[i] = a[i]
i = lo
j = mid + 1
for k in range(lo, hi + 1):
if i > mid:
a[k] = aux[j]
j += 1
elif j > hi:
a[k] = aux[i]
i += 1
elif aux[j] < aux[i]:... |
#!/usr/bin/python3
delimeter = " : "
class MonitorMessage:
def __init__(self):
self._target_directory = ""
self._target_file = ""
self._additional_information = ""
self._event_type = 0
def __repr__(self):
return self.__combine_message()
def __str__(self):
r... | delimeter = ' : '
class Monitormessage:
def __init__(self):
self._target_directory = ''
self._target_file = ''
self._additional_information = ''
self._event_type = 0
def __repr__(self):
return self.__combine_message()
def __str__(self):
return self.__combi... |
#!/usr/bin/env python2.7
# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | def get_github_repo(lang):
return {'go': 'git@github.com:grpc/grpc-go.git', 'java': 'git@github.com:grpc/grpc-java.git'}.get(lang, 'git@github.com:grpc/grpc.git')
lang_runtime_matrix = {'go': ['go1.7', 'go1.8'], 'java': ['java_oracle8']}
lang_release_matrix = {'go': ['v1.0.1-GA', 'v1.3.0'], 'java': ['v1.0.3', 'v1.1... |
def prod_esc_min(V, W):
producto = 0
Vm = sorted(V)[::-1]
WM = sorted(W)
for i in range(len(Vm)):
producto += Vm[i] * WM[i]
return(producto)
def main():
entrada = open("input.txt","r")
salida = open("output.txt","w")
T = int(entrada.readline())
x = 0
for i in range(T):... | def prod_esc_min(V, W):
producto = 0
vm = sorted(V)[::-1]
wm = sorted(W)
for i in range(len(Vm)):
producto += Vm[i] * WM[i]
return producto
def main():
entrada = open('input.txt', 'r')
salida = open('output.txt', 'w')
t = int(entrada.readline())
x = 0
for i in range(T):
... |
a = int(input())
b = int(input())
m = int(input())
powered_value = a ** b
print(powered_value)
print(powered_value % m)
| a = int(input())
b = int(input())
m = int(input())
powered_value = a ** b
print(powered_value)
print(powered_value % m) |
# This question was asked by Zillow.
# You are given a 2-d matrix where each cell represents number of coins in that cell. Assuming we start at matrix[0][0], and can only move right or down, find the maximum number of coins you can collect by the bottom right corner.
# For example, in this matrix
# 0 3 1 1
# 2 1 0 4
# ... | def max_coins(coins):
m = len(coins)
n = len(coins[0])
reward = [[0] * n for i in range(m)]
reward[0][0] = coins[0][0]
for i in range(1, m):
reward[i][0] = reward[i - 1][0] + coins[i][0]
for i in range(1, n):
reward[0][i] = reward[0][i - 1] + coins[0][i]
for i in range(1, m):... |
def func(k, n):
ret = 0
for i in range(1, len(str(n)) + 1):
ret += int(n[-i]) * (k ** (i - 1))
return ret
k = int(input())
a, b = input().split()
print(func(k, a) * func(k, b))
| def func(k, n):
ret = 0
for i in range(1, len(str(n)) + 1):
ret += int(n[-i]) * k ** (i - 1)
return ret
k = int(input())
(a, b) = input().split()
print(func(k, a) * func(k, b)) |
def lambda_handler(event, context):
"""
:param event:
:param context:
:return:
"""
print(event)
print("*"*20)
print(context)
return
| def lambda_handler(event, context):
"""
:param event:
:param context:
:return:
"""
print(event)
print('*' * 20)
print(context)
return |
a, b, c, d = map(int, input().split())
if b/a == d/c:
print("DRAW")
elif b/a > d/c:
print("TAKAHASHI")
else:
print("AOKI")
| (a, b, c, d) = map(int, input().split())
if b / a == d / c:
print('DRAW')
elif b / a > d / c:
print('TAKAHASHI')
else:
print('AOKI') |
N = int(input())
sub_populations = []
for x in range(N):
input_ = input().split()
if len(input_) == 1:
sub_populations.append([])
else:
sub_populations.append(input_[1:])
for i in range(0, len(sub_populations)-1):
cow1 = set(sub_populations[i])
for j in range(i+1, len... | n = int(input())
sub_populations = []
for x in range(N):
input_ = input().split()
if len(input_) == 1:
sub_populations.append([])
else:
sub_populations.append(input_[1:])
for i in range(0, len(sub_populations) - 1):
cow1 = set(sub_populations[i])
for j in range(i + 1, len(sub_populat... |
#!/usr/bin/env python
#
# Copyright 2014 - 2018 The BCE Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the license.txt file.
#
ABBREVIATION_DATABASE = {
"CHES": "C8H17NO3S",
"Val": "C5H11NO2",
"BOP": "C12H22F6N6OP2",
"CPD": "C5H6"... | abbreviation_database = {'CHES': 'C8H17NO3S', 'Val': 'C5H11NO2', 'BOP': 'C12H22F6N6OP2', 'CPD': 'C5H6', 'DABCO': 'C6H12N2', 'MTBE': 'C5H12O', 'BuLi': 'C4H9Li', 'Trp': 'C11H12N2O2', 'TBTU': 'C11H16N5OBF4', 'Cys': 'C3H7NO2S', 'DCM': 'CH2Cl2', 'DMPU': 'C6H12N2O', 'Bn': 'C7H7', 'TEMPO': 'C9H18NO', 'DCC': 'C13H22N2', 'Bu': ... |
def main():
pass
if __name__ == '__main__.py':
main()
| def main():
pass
if __name__ == '__main__.py':
main() |
if exists("OK-1.png"):
click("OK-1.png")
else:
exit(1)
exit(0)
| if exists('OK-1.png'):
click('OK-1.png')
else:
exit(1)
exit(0) |
n = int(input(""))
problem_matrix = []
for i in range(0,n):
problem_line = list(int(x) for x in input("").split(" "))
problem_matrix.append(problem_line)
output = 0
for l in problem_matrix:
if l.count(1) >= 2:
output += 1
print(output) | n = int(input(''))
problem_matrix = []
for i in range(0, n):
problem_line = list((int(x) for x in input('').split(' ')))
problem_matrix.append(problem_line)
output = 0
for l in problem_matrix:
if l.count(1) >= 2:
output += 1
print(output) |
'''
Ordinary Differential Equation (ODE) Solvers.
Copyright (c) Maurice H.T. Ling <mauriceling@acm.org>
Date created: 20th December 2014
'''
def boundary_checker(y, boundary, type):
'''
Private function - called by ODE solvers to perform boundary checking
of variable values and reset them to specific va... | """
Ordinary Differential Equation (ODE) Solvers.
Copyright (c) Maurice H.T. Ling <mauriceling@acm.org>
Date created: 20th December 2014
"""
def boundary_checker(y, boundary, type):
"""
Private function - called by ODE solvers to perform boundary checking
of variable values and reset them to specific va... |
def update_ema_variables(model, ema_model, alpha=0.999, global_step=-1):
# Use the true average until the exponential average is more correct
alpha = min(1 - 1 / (global_step + 1), alpha)
for ema_param, param in zip(ema_model.parameters(), model.parameters()):
ema_param.data.mul_(alpha).add_(1 - a... | def update_ema_variables(model, ema_model, alpha=0.999, global_step=-1):
alpha = min(1 - 1 / (global_step + 1), alpha)
for (ema_param, param) in zip(ema_model.parameters(), model.parameters()):
ema_param.data.mul_(alpha).add_(1 - alpha, param.data) |
class Store(object):
"""Serves as a container for the data about a single web store"""
def __init__(self, data):
if not data:
raise Exception("None argument")
self.name = data[0]
self.url = data[1]
# Prices
self.keyword_container = data[2]
self.keywo... | class Store(object):
"""Serves as a container for the data about a single web store"""
def __init__(self, data):
if not data:
raise exception('None argument')
self.name = data[0]
self.url = data[1]
self.keyword_container = data[2]
self.keyword_attribute = dat... |
class Token:
def __init__(self, number):
if number == 0:
self.color = 'G'
self.number = 0
else:
if number >= 1 and number <= 10:
self.color = 'B' if number % 2 == 0 else 'R'
self.number = number
elif number >= 11 and num... | class Token:
def __init__(self, number):
if number == 0:
self.color = 'G'
self.number = 0
elif number >= 1 and number <= 10:
self.color = 'B' if number % 2 == 0 else 'R'
self.number = number
elif number >= 11 and number <= 18:
self... |
def get_data():
userin = input("Please enter 1 for a list, 2 for a frequency table or 3 for a stem and leaf. >>> ")
if userin == "1":
return [float(x) for x in input("Enter simple list separated by spaces >>> ").split(" ") if x]
elif userin == "2":
print("You should enter each row of the fre... | def get_data():
userin = input('Please enter 1 for a list, 2 for a frequency table or 3 for a stem and leaf. >>> ')
if userin == '1':
return [float(x) for x in input('Enter simple list separated by spaces >>> ').split(' ') if x]
elif userin == '2':
print('You should enter each row of the fre... |
# The following example shows the populations for some animals
# over the years.
df = pd.DataFrame({
'pig': [20, 18, 489, 675, 1776],
'horse': [4, 25, 281, 600, 1900]
}, index=[1990, 1997, 2003, 2009, 2014])
lines = df.plot.line()
| df = pd.DataFrame({'pig': [20, 18, 489, 675, 1776], 'horse': [4, 25, 281, 600, 1900]}, index=[1990, 1997, 2003, 2009, 2014])
lines = df.plot.line() |
# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
inline = """
<map>
<name>adc_mux</name>
<doc>valid mux values for DUT's two banks of INA219 off PCA9540
ADCs</doc>
<params none="0" b... | inline = '\n <map>\n <name>adc_mux</name>\n <doc>valid mux values for DUT\'s two banks of INA219 off PCA9540\n ADCs</doc>\n <params none="0" bank0="4" bank1="5"></params>\n </map>\n <control>\n <name>adc_mux</name>\n <doc>4 to 1 mux to steer remote i2c i2c_mux:rem to two sets of\n 16 INA219 ADCs... |
ACCOUNT_SID = '' # put your Twilio Account sid here
AUTH_TOKEN = '' # put your Twilio Auth token here
TWILIO_ALLOTED_NUMBER = '' # put your Twilio alloted number here
# Header if necessary otherwise Govt. API thinks request is coming from bot , not from actual browser and block your request.
HEADER = {
'user-age... | account_sid = ''
auth_token = ''
twilio_alloted_number = ''
header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'}
your_phone_no = '' |
"""Load dependencies needed to compile the protobuf library as a 3rd-party consumer."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
PROTOBUF_MAVEN_ARTIFACTS = [
"com.google.code.findbugs:jsr305:3.0.2",
"com.google.code.gson:gson:2.8.6",
"com.google.errorprone:error_prone_annotatio... | """Load dependencies needed to compile the protobuf library as a 3rd-party consumer."""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
protobuf_maven_artifacts = ['com.google.code.findbugs:jsr305:3.0.2', 'com.google.code.gson:gson:2.8.6', 'com.google.errorprone:error_prone_annotations:2.3.2', 'com... |
# -*- coding: utf-8 -*-
class Foo(object):
pass
class Bar(Foo):
pass
class Baz(Bar):
pass
class Qux(Foo):
pass
| class Foo(object):
pass
class Bar(Foo):
pass
class Baz(Bar):
pass
class Qux(Foo):
pass |
"""
A collection of similarity measures between
items
"""
class EdgeSimilarityMeasure(object):
def compute_similarity(self, a, b):
"""
Computes the similarity between two tags.
:param a: the starting item
:param b: the target item
"""
qid_a = int(a.id[1:])
... | """
A collection of similarity measures between
items
"""
class Edgesimilaritymeasure(object):
def compute_similarity(self, a, b):
"""
Computes the similarity between two tags.
:param a: the starting item
:param b: the target item
"""
qid_a = int(a.id[1:])
... |
#!/usr/bin/env python
# coding: utf-8
# # *section 3: Strings*
#
# ### writer : Faranak Alikhah 1954128
# ### 14.Merge the Tools! :
#
# In[ ]:
def merge_the_tools(string, k):
# your code goes here
sequ=[]
counter=0
delta=len(string)//k
for i in range(delta):
sequ.append(string[counter... | def merge_the_tools(string, k):
sequ = []
counter = 0
delta = len(string) // k
for i in range(delta):
sequ.append(string[counter:counter + k])
counter = counter + k
for j in sequ:
print(''.join(list(dict.fromkeys(list(j)).keys()))) |
# OpenWeatherMap API Key
weather_api_key = "86e091696d04e4636555f97b1ff31889"
# Google API Key
g_key = "YOUR KEY HERE!"
| weather_api_key = '86e091696d04e4636555f97b1ff31889'
g_key = 'YOUR KEY HERE!' |
def unzip(L):
return [l[0] for l in L],[l[1] for l in L]
def busqueda_binaria(L, x):
primero = 0
ultimo = len(L)
while primero+1 < ultimo:
medio = (ultimo + primero)//2
if x < L[medio]:
ultimo = medio
else:
primero = medio
return L[primero] == x
if _... | def unzip(L):
return ([l[0] for l in L], [l[1] for l in L])
def busqueda_binaria(L, x):
primero = 0
ultimo = len(L)
while primero + 1 < ultimo:
medio = (ultimo + primero) // 2
if x < L[medio]:
ultimo = medio
else:
primero = medio
return L[primero] == ... |
#Just a quick experiment with default arguments in python.
##########################################################
def default(x = 5, y = 5):
print(x)
print(y)
# Should print 5\n5
default()
#Prints 0\n5
default(0)
# Prints 0\n0
default(0, 0)
| def default(x=5, y=5):
print(x)
print(y)
default()
default(0)
default(0, 0) |
# MIT License
#
# Copyright (c) 2016 Anders Steen Christensen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mo... | nuclear_charge = {'H': 1, 'He': 2, 'Li': 3, 'Be': 4, 'B': 5, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Ne': 10, 'Na': 11, 'Mg': 12, 'Al': 13, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17, 'Ar': 18, 'K': 19, 'Ca': 20, 'Sc': 21, 'Ti': 22, 'V': 23, 'Cr': 24, 'Mn': 25, 'Fe': 26, 'Co': 27, 'Ni': 28, 'Cu': 29, 'Zn': 30, 'Ga': 31, 'Ge': 32, '... |
class MyStack():
def __init__(self):
self.v_stack = []
self.m_stack = []
def push(self, number: int):
self.v_stack.append(number)
if len(self.m_stack) == 0:
self.m_stack.append(number)
else:
if self.m_stack[-1] > number:
self.m_sta... | class Mystack:
def __init__(self):
self.v_stack = []
self.m_stack = []
def push(self, number: int):
self.v_stack.append(number)
if len(self.m_stack) == 0:
self.m_stack.append(number)
elif self.m_stack[-1] > number:
self.m_stack.append(number)
... |
'''
https://leetcode.com/problems/combination-sum/
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from can... | """
https://leetcode.com/problems/combination-sum/
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from can... |
# https://projecteuler.net/problem=7
# 10001st prime
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10001st prime number?
def is_prime(n):
# if n in primes:
# return True
f = 2
while f < n:
if n % f == 0 and ... | def is_prime(n):
f = 2
while f < n:
if n % f == 0 and f != n:
return False
f += 1
return True
prime_count = 1
stop_number = 10001
val = 3
end_num = 0
while prime_count != stop_number:
if is_prime(val):
prime_count += 1
end_num = val
val += 2
print(end_num) |
class Field:
name: str
value: str
inline: bool
def __init__(self, name, value, inline=False):
self.name = name
self.value = value
self.inline = inline
self._validate(name)
self._validate(value)
def to_dict(self):
return self.__dict__
def _valid... | class Field:
name: str
value: str
inline: bool
def __init__(self, name, value, inline=False):
self.name = name
self.value = value
self.inline = inline
self._validate(name)
self._validate(value)
def to_dict(self):
return self.__dict__
def _valida... |
num=int(input())
def LoadingBar(value=0):
barLength=value//10; bar=""
for k in range(1,11):
if k<=barLength:
bar+="%"
else:
bar+="."
if barLength<10:
return f"{barLength*10}% [{bar}]\nStill loading..."
else:
return f"{barLength*10}% Comp... | num = int(input())
def loading_bar(value=0):
bar_length = value // 10
bar = ''
for k in range(1, 11):
if k <= barLength:
bar += '%'
else:
bar += '.'
if barLength < 10:
return f'{barLength * 10}% [{bar}]\nStill loading...'
else:
return f'{barLe... |
# Colecoes: set e dictionary
# SET
# utiliza {},
# nao contabiliza itens repetidos
# lista nao ordenada
# LISTA utiliza []
frutas = {"maca", "laranja", "abacaxi"}
frutas.add("pera")
print(frutas)
frutas.remove("maca")
print(frutas)
frutas.pop() #como a lista nao eh ordenada ele nao remove o ultimo, mas sim um valor... | frutas = {'maca', 'laranja', 'abacaxi'}
frutas.add('pera')
print(frutas)
frutas.remove('maca')
print(frutas)
frutas.pop()
print(frutas)
set1 = {'maca', 'laranja', 'abacaxi'}
set2 = {0, 3, 50, -74}
set3 = {True, False, False, False}
set4 = {'Hugo', 33, True}
print(set4)
print(len(set4)) |
#
# PySNMP MIB module DKSF-253-6-X-A-X (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DKSF-253-6-X-A-X
# Produced by pysmi-0.3.4 at Mon Apr 29 18:32:23 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_union, constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint) ... |
ENTER = """
<Press Enter to continue>"""
def print_messages(*messages):
"""Print a bunch of messages."""
for m in messages:
raw_input(m + ENTER)
WELCOME = '''
*******************************************************************************
><><><><><><><><><><><><><><><>PICKETT<><><><><><><><><><><><><><><><... | enter = '\n\n<Press Enter to continue>'
def print_messages(*messages):
"""Print a bunch of messages."""
for m in messages:
raw_input(m + ENTER)
welcome = '\n*******************************************************************************\n><><><><><><><><><><><><><><><>PICKETT<><><><><><><><><><><><><><... |
def gcd( a, b ):
if (b == 0):
return a
else:
return gcd(b, a % b)
n = int(input())
a = list(map(int, input().split()))
ans = a[0]
for i in range(1, n):
ans = gcd(ans, a[i])
print(ans)
| def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
n = int(input())
a = list(map(int, input().split()))
ans = a[0]
for i in range(1, n):
ans = gcd(ans, a[i])
print(ans) |
class CandidateSet(object):
def __init__(self):
self.candidates_history = {}
self.candidates = []
self.costs = 0
self.iteration = 0
self.verbose = True
def removeAlreadyExistingGridPoints(self, grid, intersections):
gs = grid.getStorage()
return [gp for... | class Candidateset(object):
def __init__(self):
self.candidates_history = {}
self.candidates = []
self.costs = 0
self.iteration = 0
self.verbose = True
def remove_already_existing_grid_points(self, grid, intersections):
gs = grid.getStorage()
return [gp ... |
class Participant:
def __init__(self):
self.name = ""
self.isStillIn = True
self.hasCheckedIn = False
def setFromLine(self, lineString):
# format of participants.txt line:
# name hasCheckedIn isStillIn
# e.g.:
# foobarbazblarg True True
words = li... | class Participant:
def __init__(self):
self.name = ''
self.isStillIn = True
self.hasCheckedIn = False
def set_from_line(self, lineString):
words = lineString.split()
self.name = words[0]
self.hasCheckedIn = words[1] == 'True'
self.isStillIn = words[2] ==... |
class DGNImportOptions(BaseImportOptions,IDisposable):
"""
The import options used to import DGN format files.
DGNImportOptions(option: DGNImportOptions)
DGNImportOptions()
"""
def Dispose(self):
""" Dispose(self: BaseImportOptions,A_0: bool) """
pass
def ReleaseUnmanagedResources(self,*args):... | class Dgnimportoptions(BaseImportOptions, IDisposable):
"""
The import options used to import DGN format files.
DGNImportOptions(option: DGNImportOptions)
DGNImportOptions()
"""
def dispose(self):
""" Dispose(self: BaseImportOptions,A_0: bool) """
pass
def release_unmanaged_resour... |
def datastructure():
name = input('What\'s your name? ')
password = input('Digit your password: ')
password_length = len(password)
hidden_password = '*' * password_length
print(
f'{name}, your password {hidden_password} is {password_length} letters long'
) | def datastructure():
name = input("What's your name? ")
password = input('Digit your password: ')
password_length = len(password)
hidden_password = '*' * password_length
print(f'{name}, your password {hidden_password} is {password_length} letters long') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
File: factorial.py
Author: tdoly
Description: http://en.wikipedia.org/wiki/Factorial
'''
def factorial(num):
if num < 0:
raise "the input number is error"
elif num == 0:
return 1
else:
return reduce((lambda x, y: x*y), [i for i in ... | """
File: factorial.py
Author: tdoly
Description: http://en.wikipedia.org/wiki/Factorial
"""
def factorial(num):
if num < 0:
raise 'the input number is error'
elif num == 0:
return 1
else:
return reduce(lambda x, y: x * y, [i for i in range(num + 1) if i > 0]) |
def field_keys(field):
return [
'count',
field + '_delta_avg',
field + '_delta_avg_abs',
field + '_delta_std_dev',
]
def map_keys(field):
return [
field + '_delta_avg_ad',
field + '_delta_abs_avg_ad',
field + '_delta_std_dev_ad'
]
| def field_keys(field):
return ['count', field + '_delta_avg', field + '_delta_avg_abs', field + '_delta_std_dev']
def map_keys(field):
return [field + '_delta_avg_ad', field + '_delta_abs_avg_ad', field + '_delta_std_dev_ad'] |
test = {
"name": "q1",
"points": 1,
"hidden": True,
"suites": [
{
"cases": [
{
"code": r"""
>>> sample_population(new_tests).num_rows
348
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> sample_population(Table().with_columns("", np.arange(523)... | test = {'name': 'q1', 'points': 1, 'hidden': True, 'suites': [{'cases': [{'code': '\n\t\t\t\t\t>>> sample_population(new_tests).num_rows\n\t\t\t\t\t348\n\t\t\t\t\t', 'hidden': False, 'locked': False}, {'code': '\n\t\t\t\t\t>>> sample_population(Table().with_columns("", np.arange(523))).num_rows\n\t\t\t\t\t523\n\t\t\t\t... |
coins = [1, 2, 5, 10, 20, 50, 100, 200]
def coin_sums(wanted_pence):
return _coin_sums(wanted_pence, coins, {})
def _coin_sums(wanted_pence, available_coins, computation_cache):
if wanted_pence == 0:
return 1
if not available_coins:
return 0
if (wanted_pence, len(available_coins)) in... | coins = [1, 2, 5, 10, 20, 50, 100, 200]
def coin_sums(wanted_pence):
return _coin_sums(wanted_pence, coins, {})
def _coin_sums(wanted_pence, available_coins, computation_cache):
if wanted_pence == 0:
return 1
if not available_coins:
return 0
if (wanted_pence, len(available_coins)) in c... |
# coding=utf-8
"""
basepkg: tests module.
Meant for use with py.test.
Organize tests into files, each named xxx_test.py
Read more here: http://pytest.org/
Copyright 2014, Stefan Braun
Licensed under MIT
""" | """
basepkg: tests module.
Meant for use with py.test.
Organize tests into files, each named xxx_test.py
Read more here: http://pytest.org/
Copyright 2014, Stefan Braun
Licensed under MIT
""" |
class Solution:
def sortString(self, s: str) -> str:
charFrequencyMap, result, length = [0] * 26, [], len(s)
for c in s:
charFrequencyMap[ord(c) - ord('a')] += 1
while len(result) != length:
for index in range(26):
if charFrequencyMap[index] > 0:
... | class Solution:
def sort_string(self, s: str) -> str:
(char_frequency_map, result, length) = ([0] * 26, [], len(s))
for c in s:
charFrequencyMap[ord(c) - ord('a')] += 1
while len(result) != length:
for index in range(26):
if charFrequencyMap[index] > ... |
class Error(Exception):
def __init__(self, message='', stderr=None):
super().__init__(message)
self.stderr = stderr
| class Error(Exception):
def __init__(self, message='', stderr=None):
super().__init__(message)
self.stderr = stderr |
PERnc_testValuesAndGrads = [
[[-0.00400827, -0.00400437, -0.0], 0.011, 0.010007, 0.0131],
[[-0.00400827, -0.00400437, 0.0], 0.011, 0.010007, 0.1031],
[[-0.00400827, -0.00400437, 2.04542e-39], 0.011, 0.010007, 0.5031],
[[-0.00400827, -0.00400436, 1.53851e-9], 0.011, 0.010007, 1.0031],
[[-0.00137552, ... | pe_rnc_test_values_and_grads = [[[-0.00400827, -0.00400437, -0.0], 0.011, 0.010007, 0.0131], [[-0.00400827, -0.00400437, 0.0], 0.011, 0.010007, 0.1031], [[-0.00400827, -0.00400437, 2.04542e-39], 0.011, 0.010007, 0.5031], [[-0.00400827, -0.00400436, 1.53851e-09], 0.011, 0.010007, 1.0031], [[-0.00137552, 0.0271467, 0.013... |
def trans_string(a):
return int(a)
print(trans_string('6')) | def trans_string(a):
return int(a)
print(trans_string('6')) |
#
# Example file for variables
#
# Declare a variable and initialize it
f = "0"
# print(f)
# # re-declaring the variable works
#f = "abc"
# print(f)
# # ERROR: variables of different types cannot be combined
#print("String words" + str(564))
# Global vs. local variables in functions
def someFunction():
globa... | f = '0'
def some_function():
global f
f = 'def'
print(f)
some_function()
print(f)
del f
print(f) |
"""Store networking information for all node files to share"""
CLIENT_RECV_PORT = 5005
CLIENT_SEND_PORT = 5006
# Buffer size for socket
BUFFER_SIZE = 1048576
# IP to be used for local system
LOCAL_IP = '127.0.0.1'
# Time (in sec) after which it's assumed that a communicating node has crashed
CRASH_ASSUMPTION_TIME =... | """Store networking information for all node files to share"""
client_recv_port = 5005
client_send_port = 5006
buffer_size = 1048576
local_ip = '127.0.0.1'
crash_assumption_time = 10 |
_base_ = './qdtrack-frcnn_r50_fpn_12e_bdd100k.py'
# model settings
model = dict(
type='QuasiDenseMaskRCNN',
pretrained='torchvision://resnet50',
roi_head=dict(
type='QuasiDenseSegRoIHead',
mask_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAli... | _base_ = './qdtrack-frcnn_r50_fpn_12e_bdd100k.py'
model = dict(type='QuasiDenseMaskRCNN', pretrained='torchvision://resnet50', roi_head=dict(type='QuasiDenseSegRoIHead', mask_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_stride... |
"""
You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i]
represent the speed and efficiency of the ith engineer respectively.
Choose at most k different engineers out of the n engineers to form a team wit... | """
You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i]
represent the speed and efficiency of the ith engineer respectively.
Choose at most k different engineers out of the n engineers to form a team wit... |
# Stub unicodedata module. Covers only the Latin-1 range.
# Copyright (c) 2005 Nokia Corporation
#
# 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/LICEN... | _latin1_categories = {u'\x00': 'Cc', u'\x83': 'Cc', u'\x04': 'Cc', u'\x87': 'Cc', u'\x08': 'Cc', u'\x8b': 'Cc', u'\x0c': 'Cc', u'\x8f': 'Cc', u'\x10': 'Cc', u'\x93': 'Cc', u'\x14': 'Cc', u'\x97': 'Cc', u'\x18': 'Cc', u'\x9b': 'Cc', u'\x1c': 'Cc', u'\x9f': 'Cc', u' ': 'Zs', u'£': 'Sc', u'$': 'Sc', u'§': 'So', u'(': 'Ps'... |
__author__ = 'michaelokuboyejo'
class JusibeException(Exception):
"""
There was an ambiguous exception that occurred while attempting to fetch
your machine's public IP address from the Jusibe service.
"""
pass
class ServiceException(JusibeException):
"""
The request failed because the Ju... | __author__ = 'michaelokuboyejo'
class Jusibeexception(Exception):
"""
There was an ambiguous exception that occurred while attempting to fetch
your machine's public IP address from the Jusibe service.
"""
pass
class Serviceexception(JusibeException):
"""
The request failed because the Jusi... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(N):
# write your code in Python 3.6
biny = bin(N)[2:]
# print(N)
# print(biny)
stringy = list(str(biny))
# print(stringy)
max_count = 0
temp_count = 0
flip_occured = False
... | def solution(N):
biny = bin(N)[2:]
stringy = list(str(biny))
max_count = 0
temp_count = 0
flip_occured = False
for i in range(0, len(stringy), 1):
while i < len(stringy) and stringy[i] == '0':
temp_count += 1
i += 1
if i < len(stringy) and stringy[i] == '1... |
def revrot(s, n, res=""):
if not s or n < 1 or n > len(s):
return ""
while len(s) >= n:
group = s[:n]
if sum([int(d)**3 for d in group]) % 2 == 0:
res += group[::-1]
else:
res += group[1:] + group[0]
s = s[n:]
return res
| def revrot(s, n, res=''):
if not s or n < 1 or n > len(s):
return ''
while len(s) >= n:
group = s[:n]
if sum([int(d) ** 3 for d in group]) % 2 == 0:
res += group[::-1]
else:
res += group[1:] + group[0]
s = s[n:]
return res |
class Users:
"""
A class to store user log in details.
"""
user_list = [] # Blank user list to store user details
def __init__(self, username, password):
"""
Defining the init method (constructor) that will be used to create new user instances
"""
self.username = us... | class Users:
"""
A class to store user log in details.
"""
user_list = []
def __init__(self, username, password):
"""
Defining the init method (constructor) that will be used to create new user instances
"""
self.username = username
self.password = password
... |
# Print largest old number, taking 10 input numbers
# num_inputs = []
# n = 10
# largest = None
# while n > 0:
# try:
# num_inputs.append(int(input("Enter a number: ")))
# except:
# print("NaN")
# continue
# n -= 1
# for num in num_inputs:
# if largest == None or num > largest:
# if nu... | n = 10
largest = None
while n > 0:
try:
num = int(input('Enter a number: '))
if largest == None or num > largest:
if num % 2 != 0:
largest = num
except:
print('NaN')
continue
n -= 1
if largest is None:
print('No odd numbers.')
else:
print(f... |
#Fibonacijev niz
def fibonaci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonaci(n-1) + fibonaci(n-2)
rezultat = fibonaci(0)
print("fibonaci(0) = ", rezultat)
rezultat = fibonaci(1)
print("fibonaci(1) = ", rezultat)
# <- fibonaci(2-1) + fibonaci(2-2)
# <- 1 + 0
re... | def fibonaci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonaci(n - 1) + fibonaci(n - 2)
rezultat = fibonaci(0)
print('fibonaci(0) = ', rezultat)
rezultat = fibonaci(1)
print('fibonaci(1) = ', rezultat)
rezultat = fibonaci(2)
print('fibonaci(2) = ', rezultat)
rezulta... |
x = int(input())
a = []
for i in range(x):
a.append(int(input()))
for i in range(x):
m = a[i]//2
for j in range(2,m+1):
if(a[i]%j==0):
print("not prime")
break
else:
print("prime")
| x = int(input())
a = []
for i in range(x):
a.append(int(input()))
for i in range(x):
m = a[i] // 2
for j in range(2, m + 1):
if a[i] % j == 0:
print('not prime')
break
else:
print('prime') |
def dfs(L, crt, remain):
if remain == 0:
L.append(crt[:])
else:
for i in range(1, 4):
crt.append(i)
if(remain - i >= 0):
dfs(L, crt, remain - i)
crt.pop()
N,K = map(int ,input().split())
L = []
crt = []
dfs(L, crt, N)
if K > len(L):
print... | def dfs(L, crt, remain):
if remain == 0:
L.append(crt[:])
else:
for i in range(1, 4):
crt.append(i)
if remain - i >= 0:
dfs(L, crt, remain - i)
crt.pop()
(n, k) = map(int, input().split())
l = []
crt = []
dfs(L, crt, N)
if K > len(L):
print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.