content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
combs = set()
for a in xrange(2,101):
for b in xrange(2,101):
combs.add(a**b)
print(len(combs)) # 9183 | combs = set()
for a in xrange(2, 101):
for b in xrange(2, 101):
combs.add(a ** b)
print(len(combs)) |
# ------------------------------
# 417. Pacific Atlantic Water Flow
#
# Description:
# Given an m x n matrix of non-negative integers representing the height of each unit cell in a
# continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic
# ocean" touches the right and bottom ed... | class Solution:
def pacific_atlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix or not matrix[0]:
return
res = []
n = len(matrix)
m = len(matrix[0])
pacific = [[False for _ in range(m)] for _ in range(n)]
atlantic = [[False for _ in ... |
class McostGrid():
default_value = 1
def __init__(self):
self.grid = []
self.terrain_types = []
self.unit_types = []
@property
def row_headers(self):
return self.terrain_types
@property
def column_headers(self):
return self.unit_types
def set(self,... | class Mcostgrid:
default_value = 1
def __init__(self):
self.grid = []
self.terrain_types = []
self.unit_types = []
@property
def row_headers(self):
return self.terrain_types
@property
def column_headers(self):
return self.unit_types
def set(self, c... |
def sort(arr, exp1):
n = len(arr)
output = [0] * (n)
count = [0] * (10)
for i in range(0, n):
index = (arr[i]/exp1)
count[int((index)%10)] += 1
for i in range(1,10):
count[i] += count[i-1]
i = n-1
while i>=0:
index = (arr[i]/exp1)
output[ count[ int((index)%10) ] - 1] = arr[i]
count[... | def sort(arr, exp1):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(0, n):
index = arr[i] / exp1
count[int(index % 10)] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] / exp1
output[count[int(i... |
'''
import flask as f # give name to flask mode]ule as f
print(f.__version__) # see version
import sys
print(sys.path)
import f33var
print(f33var.n)
'''
| """
import flask as f # give name to flask mode]ule as f
print(f.__version__) # see version
import sys
print(sys.path)
import f33var
print(f33var.n)
""" |
# Remove Duplicates from Sorted List
# https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list/
#
# Given a sorted linked list, delete all duplicates such that each element appear only once.
#
# For example,
# Given 1->1->2, return 1->2.
# Given 1->1->2->3->3, return 1->2->3.
#
# # # # # # # # # # # # ... | class Solution:
def delete_duplicates(self, A):
if A is None or A.next is None:
return A
(prev, tmp) = (A, A.next)
while tmp:
if prev.val == tmp.val:
prev.next = tmp.next
tmp = prev.next
else:
prev = tmp
... |
if __name__ == "__main__":
with open("12_04_01.txt", "r") as f:
rng = f.readline().split("-")
pwds = []
for pwd in range(int(rng[0]), int(rng[1])):
lpwd = [char for char in str(pwd)]
for num in lpwd:
num = int(num)
flag = 1
... | if __name__ == '__main__':
with open('12_04_01.txt', 'r') as f:
rng = f.readline().split('-')
pwds = []
for pwd in range(int(rng[0]), int(rng[1])):
lpwd = [char for char in str(pwd)]
for num in lpwd:
num = int(num)
flag = 1
for ... |
"""
OpenID utils
some copied from http://github.com/openid/python-openid/examples/djopenid
ben@adida.net
"""
| """
OpenID utils
some copied from http://github.com/openid/python-openid/examples/djopenid
ben@adida.net
""" |
'''
Joe Walter
difficulty: 5%
run time: 0:00
answer: 9110846700
***
048 Self Powers
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
'''
def solve(n, num_digits = 10):
mod = 10**num_digits
sum = 0
for k in range(1, n+1):
sum += pow(k, k, mod)
return sum % mod
assert solve(10... | """
Joe Walter
difficulty: 5%
run time: 0:00
answer: 9110846700
***
048 Self Powers
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
"""
def solve(n, num_digits=10):
mod = 10 ** num_digits
sum = 0
for k in range(1, n + 1):
sum += pow(k, k, mod)
return sum % ... |
# Number of occurrences of 2 as a digit in numbers from 0 to n
# Count the number of 2s as digit in all numbers from 0 to n.
# Examples :
# Input : 22
# Output : 6
# Explanation: Total 2s that appear as digit
# from 0 to 22 are (2, 12, 20,
# 21, 22);
# Input : 100
# Output : 20
# Explanat... | def occurance_of_twos(n):
num = 0
two_count = 0
while num <= n:
two_count += list(str(num)).count('2')
num += 1
return twoCount
print(occurance_of_twos(22))
print(occurance_of_twos(100)) |
"""
All configuration is here.
"""
## globals: FIXME: load from conf
MAPBOX_ACCESS_TOKEN = "pk.eyJ1IjoiamFja3AiLCJhIjoidGpzN0lXVSJ9.7YK6eRwUNFwd3ODZff6JvA"
N_BINS = 10
SCALE = 100
# _palette = sns.light_palette((5, 90, 55), N_BINS, input="husl")
# DEFAULT_COLORSCALE = _palette.as_hex()
DEFAULT_COLORSCALE = [
'#e8f6f8... | """
All configuration is here.
"""
mapbox_access_token = 'pk.eyJ1IjoiamFja3AiLCJhIjoidGpzN0lXVSJ9.7YK6eRwUNFwd3ODZff6JvA'
n_bins = 10
scale = 100
default_colorscale = ['#e8f6f8', '#fce5e7', '#f9cdd2', '#f7b4bb', '#f49ca6', '#f1848f', '#ef6c7a', '#ec5363', '#e93b4e', '#e72338']
default_opacity = 0.8
value_to_mapbox_styl... |
#!/usr/bin/python3
"""
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make
two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the
sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, bo... | """
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make
two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the
sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equa... |
emojis = [{"id": 1, "emoji": "emoji1", "active": "y", "type": "Free", "type_num": 1},
{"id": 2, "emoji": "emoji2", "active": "y", "type": "Free", "type_num": 1},
{"id": 3, "emoji": "emoji3", "active": "y", "type": "Free", "type_num": 1},
{"id": 4, "emoji": "emoji4", "active": "y", "typ... | emojis = [{'id': 1, 'emoji': 'emoji1', 'active': 'y', 'type': 'Free', 'type_num': 1}, {'id': 2, 'emoji': 'emoji2', 'active': 'y', 'type': 'Free', 'type_num': 1}, {'id': 3, 'emoji': 'emoji3', 'active': 'y', 'type': 'Free', 'type_num': 1}, {'id': 4, 'emoji': 'emoji4', 'active': 'y', 'type': 'Free', 'type_num': 1}, {'id':... |
#-----------------------------------------------------------------------------
# Runtime: 56ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def permuteUnique(self, nums: [int]) -> [[int]]:
if len(nums) == 1:
return [ nu... | class Solution:
def permute_unique(self, nums: [int]) -> [[int]]:
if len(nums) == 1:
return [nums]
nums.sort()
visited = [False] * len(nums)
result = []
temp_result = []
def dfs(temp_result: [int]):
if len(nums) == len(temp_result):
... |
#1. Create a greeting for your program.
#2. Ask the user for the city that they grew up in.
#3. Ask the user for the name of a pet.
#4. Combine the name of their city and pet and show them their band name.
#5. Make sure the input cursor shows on a new line, see the example at:
# https://band-name-generator-end.ap... | print('Welcome to Band Name Generator')
city = input("What's name of the city you grew up in?\n")
pet = input("What is the name of your pet?(Let's have a pet's name if not a pet otherwise)\n")
print('Seems like ' + pet + ' ' + city + ' will be a good band name for you') |
"""
This script takes a sequence and reverses it, such that it can be inserted back into the genome as an artificial
reversal of a sequence.
"""
seq = """TTATGTGTTTTGGGGGCGATCGTGAGGCAAAGAAAACCCGGCGCTGAGGCCGGGTTATTCTTGTTCTCTG
GTCAAATTATATAGTTGGAAAACAAGGATGCATATATGAATGAACGATGCAGAGGCAATGCCGATGGCGA
TAGTGGGTATCATGTAGCCGCTT... | """
This script takes a sequence and reverses it, such that it can be inserted back into the genome as an artificial
reversal of a sequence.
"""
seq = 'TTATGTGTTTTGGGGGCGATCGTGAGGCAAAGAAAACCCGGCGCTGAGGCCGGGTTATTCTTGTTCTCTG\nGTCAAATTATATAGTTGGAAAACAAGGATGCATATATGAATGAACGATGCAGAGGCAATGCCGATGGCGA\nTAGTGGGTATCATGTAGCCGCTTA... |
mysql = {
'host': 'localhost',
'user': 'student',
'password': 'student',
'database': 'BeerDB'
}
| mysql = {'host': 'localhost', 'user': 'student', 'password': 'student', 'database': 'BeerDB'} |
# Adesh Gautam
def merge(arr, l, m, r):
L = arr[:m]
R = arr[m:]
n1 = len(L)
n2 = len(R)
i, j, k = 0, 0, 0
while i < n1 and j < n2 :
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
whi... | def merge(arr, l, m, r):
l = arr[:m]
r = arr[m:]
n1 = len(L)
n2 = len(R)
(i, j, k) = (0, 0, 0)
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k]... |
# python is a General Purpose High level Programming Language
# Dictionaries
''' Dictionaries are unordered changeable (muteable) indexed collections
in Python Dictionaries are Declared with {} and key value pairs
'''
thisDict = {
'Name':'Shinji Ikari',
'Father':'Gendo Ikari',
'Mother':'Yui Ikari',
... | """ Dictionaries are unordered changeable (muteable) indexed collections
in Python Dictionaries are Declared with {} and key value pairs
"""
this_dict = {'Name': 'Shinji Ikari', 'Father': 'Gendo Ikari', 'Mother': 'Yui Ikari', 'Guardian': 'Misato Kasturagi'}
print(thisDict)
thisDict['Father'] = 'Ikari Gendo'
print(... |
#!/usr/bin/env python
# encoding: utf-8
FILE = 'File'
ASSIGNMENT = 'Assignment'
DOWNLOAD_URL_EXTENSION = "?forcedownload=1"
| file = 'File'
assignment = 'Assignment'
download_url_extension = '?forcedownload=1' |
class Solution(object):
def numTilings(self, N):
H = [[0, 0] for _ in xrange(N+1)]
H[0][0] = 1
H[1][0] = 1
for i in xrange(2, N+1):
H[i][0] = (H[i-1][0] + H[i-2][0] + H[i-1][1]*2) % 1000000007
H[i][1] = (H[i-2][0] + H[i-1][1]) % 1000000007
... | class Solution(object):
def num_tilings(self, N):
h = [[0, 0] for _ in xrange(N + 1)]
H[0][0] = 1
H[1][0] = 1
for i in xrange(2, N + 1):
H[i][0] = (H[i - 1][0] + H[i - 2][0] + H[i - 1][1] * 2) % 1000000007
H[i][1] = (H[i - 2][0] + H[i - 1][1]) % 1000000007
... |
#dic.py
stu = {"203-2012-045":"John", "203-2012-037":"Peter"}
stu["202-2011-121"] = "Susan"
print(stu["202-2011-121"])
del stu["202-2011-121"]
for key in stu:
print(key+" : "+str(stu[key]))
for value in stu.values():
print(value)
for item in stu.items():
print(item)
print("203-2012-037" in stu)
print(tuple(stu.ke... | stu = {'203-2012-045': 'John', '203-2012-037': 'Peter'}
stu['202-2011-121'] = 'Susan'
print(stu['202-2011-121'])
del stu['202-2011-121']
for key in stu:
print(key + ' : ' + str(stu[key]))
for value in stu.values():
print(value)
for item in stu.items():
print(item)
print('203-2012-037' in stu)
print(tuple(st... |
class AttrDict(object):
def __init__(self, initializer=None):
self._data=dict()
self._initializer = initializer
self._is_initialized = False if initializer is not None else True
def _initialize(self):
if self._initializer:
self._initializer(self)
def get(self, ... | class Attrdict(object):
def __init__(self, initializer=None):
self._data = dict()
self._initializer = initializer
self._is_initialized = False if initializer is not None else True
def _initialize(self):
if self._initializer:
self._initializer(self)
def get(self... |
# integers
print(format(10, '+'))
print(format(15, 'b'))
print(format(15, 'x'))
print(format(15, 'X'))
# float
print(format(.2, '%'))
print(format(10.5, 'e'))
print(format(10.5, 'e'))
print(format(10.5345678, 'f'))
print(format(10.5, 'F'))
class Data:
id = 0
def __init__(self, i):
self.id = i
... | print(format(10, '+'))
print(format(15, 'b'))
print(format(15, 'x'))
print(format(15, 'X'))
print(format(0.2, '%'))
print(format(10.5, 'e'))
print(format(10.5, 'e'))
print(format(10.5345678, 'f'))
print(format(10.5, 'F'))
class Data:
id = 0
def __init__(self, i):
self.id = i
def __format__(self, ... |
class Man:
def __init__(self, name):
self.name = name
def hello(self):
print(self.name)
m = Man("Ken")
m.hello()
| class Man:
def __init__(self, name):
self.name = name
def hello(self):
print(self.name)
m = man('Ken')
m.hello() |
@frappe.whitelist(allow_guest=True)
def holdOrder(data):
try:
doc = data
if isinstance(doc, string_types):
doc = json.loads(doc)
if doc.get('hold_Id'):
cart = frappe.get_doc('Shopping Cart', doc.get('hold_Id'))
else:
cart = frappe.new_doc('Shopping Cart')
cart.cart_type = 'Pos Cart'
car... | @frappe.whitelist(allow_guest=True)
def hold_order(data):
try:
doc = data
if isinstance(doc, string_types):
doc = json.loads(doc)
if doc.get('hold_Id'):
cart = frappe.get_doc('Shopping Cart', doc.get('hold_Id'))
else:
cart = frappe.new_doc('Shoppin... |
class Solution:
def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
v = [i for i in nums1]
v.sort()
gap = float('-inf')
for ind, (i, j) in enumerate(zip(nums1, nums2)):
k = bisect.bisect_right(v, j)
if k < len(nums1):
gap =... | class Solution:
def min_absolute_sum_diff(self, nums1: List[int], nums2: List[int]) -> int:
v = [i for i in nums1]
v.sort()
gap = float('-inf')
for (ind, (i, j)) in enumerate(zip(nums1, nums2)):
k = bisect.bisect_right(v, j)
if k < len(nums1):
... |
# Discord OAuth connection token environment variable
DISCORD_OAUTH_TOKEN = "TOKEN"
# Prefix used for the Bot commands
COMMAND_PREFIX = "p!ka "
# Logging configuration file environment variable
LOGGING_CONFIG_JSON = "LOGGING_CONFIG_JSON"
class SqliteDB:
"""SQLite database tables"""
# Database environment va... | discord_oauth_token = 'TOKEN'
command_prefix = 'p!ka '
logging_config_json = 'LOGGING_CONFIG_JSON'
class Sqlitedb:
"""SQLite database tables"""
database_config_path_env_var = 'DATABASE_CONFIG_PATH'
database_storage_path = 'SQLITE_DATA_PATH'
database_name = 'pokemon.db'
user_table = 'users'
poke... |
"""
https://www.codewars.com/kata/563b662a59afc2b5120000c6
Given p0: initial population,
percent: the amount of growth each year (%)
aug: the number of new inhabitants per year that come to live in the town
p: the target population
Return the number of years it will take to reach the target population.
Examples:
nb_... | """
https://www.codewars.com/kata/563b662a59afc2b5120000c6
Given p0: initial population,
percent: the amount of growth each year (%)
aug: the number of new inhabitants per year that come to live in the town
p: the target population
Return the number of years it will take to reach the target population.
Examples:
nb_... |
def look():
for i in range (1,101):
if i%3==0:
print("Fizz")
elif i%5==0:
print("Buzz")
elif i%3==0 and i//5==0:
print("FizzBuzz")
else:
print(i)
look() | def look():
for i in range(1, 101):
if i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
elif i % 3 == 0 and i // 5 == 0:
print('FizzBuzz')
else:
print(i)
look() |
#!/usr/bin/env python3
N = 53
eps = 1.0
for i in range(N):
eps = eps /2
onepeps = 1.0 + eps
print('eps = ', eps, ' , one + eps = ', onepeps)
| n = 53
eps = 1.0
for i in range(N):
eps = eps / 2
onepeps = 1.0 + eps
print('eps = ', eps, ' , one + eps = ', onepeps) |
{'stack': {'backgrounds': [{'components': [{'label': 'Make Visible',
'name': 'Command4',
'position': (480, 16),
'size': (89, 25),
'type': 'VBBut... | {'stack': {'backgrounds': [{'components': [{'label': 'Make Visible', 'name': 'Command4', 'position': (480, 16), 'size': (89, 25), 'type': 'VBButton'}, {'label': 'Move ', 'name': 'Command5', 'position': (576, 16), 'size': (89, 25), 'type': 'VBButton'}, {'label': 'Size ', 'name': 'Command6', 'position': (672, 16), 'size'... |
class ReduceNumberToZero:
@classmethod
def number_of_steps(cls, num: int) -> int:
"""
@name 1342. Number of Steps to Reduce a Number to Zero
@ref Leetcode, 1342.
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
@brief Given an integ... | class Reducenumbertozero:
@classmethod
def number_of_steps(cls, num: int) -> int:
"""
@name 1342. Number of Steps to Reduce a Number to Zero
@ref Leetcode, 1342.
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
@brief Given an integer n... |
def messages_sent(message_container, start_date, end_date, message_type=None):
"""
Return number of messages sent between start and end date contained
by message container (chat/member).
"""
messages_sent = 0
for message in message_container.messages:
if (start_date <= message.timestamp.... | def messages_sent(message_container, start_date, end_date, message_type=None):
"""
Return number of messages sent between start and end date contained
by message container (chat/member).
"""
messages_sent = 0
for message in message_container.messages:
if start_date <= message.timestamp.d... |
def bit_add(bit, i, x):
i += 1
n = len(bit)
while i <= n:
bit[i - 1] += x
i += i & -i
def bit_sum(bit, i):
result = 0
i += 1
while i > 0:
result += bit[i - 1]
i -= i & -i
return result
def bit_query(bit, start, stop):
if start == 0:
return bit_... | def bit_add(bit, i, x):
i += 1
n = len(bit)
while i <= n:
bit[i - 1] += x
i += i & -i
def bit_sum(bit, i):
result = 0
i += 1
while i > 0:
result += bit[i - 1]
i -= i & -i
return result
def bit_query(bit, start, stop):
if start == 0:
return bit_su... |
#!phthon 2
ip = raw_input("please type ip :")
# print "{:<12} {:<12} {:<12} {:<12}".format(*ip.split('.'))
ip_addr = ip.split(".")
ip_addr[3]='0'
print (ip_addr[0],ip_addr[1],ip_addr[2],ip_addr[3])
print (bin(int(ip_addr[0])),bin(int(ip_addr[1])),bin(int(ip_addr[2])),bin(int(ip_addr[3])))
| ip = raw_input('please type ip :')
ip_addr = ip.split('.')
ip_addr[3] = '0'
print(ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3])
print(bin(int(ip_addr[0])), bin(int(ip_addr[1])), bin(int(ip_addr[2])), bin(int(ip_addr[3]))) |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
class Connection(object):
"""The connection object pairs a backend with an individual
identity (phone number, nickname, email, etc) so application
authors need not concern themselves with backends."""
def __init__(self, backend, identit... | class Connection(object):
"""The connection object pairs a backend with an individual
identity (phone number, nickname, email, etc) so application
authors need not concern themselves with backends."""
def __init__(self, backend, identity):
self.backend = backend
self.ide... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Assignment 1 Day8
def getInput(calculate_arg_fun):
def Fibonacci(n):
if n<=0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==1:
return 0
# Second Fibonacci number is 1
elif n==2:
... | def get_input(calculate_arg_fun):
def fibonacci(n):
if n <= 0:
print('Incorrect input')
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
return calculate_arg_fun(a)
return Fibonac... |
# encoding: utf-8
"""Constants for pynetgear."""
# ---------------------
# DEFAULTS
# ---------------------
DEFAULT_HOST = "routerlogin.net"
DEFAULT_USER = "admin"
DEFAULT_PORT = 5000
ALL_PORTS = [(5555, True), (443, True), (5000, False), (80, False)]
BLOCK = "Block"
ALLOW = "Allow"
UNKNOWN_DEVICE_DECODED = "<unknow... | """Constants for pynetgear."""
default_host = 'routerlogin.net'
default_user = 'admin'
default_port = 5000
all_ports = [(5555, True), (443, True), (5000, False), (80, False)]
block = 'Block'
allow = 'Allow'
unknown_device_decoded = '<unknown>'
unknown_device_encoded = '<unknown>'
session_id = 'A7D88AE69687E58D9A0... |
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
if(hour == 12):
hour = 0
angle_h = hour * 30.0 + minutes / 2.0
angle_m = minutes * 6.0
ans = abs(angle_h - angle_m)
return ans if 360.0 - ans > ans else 360.0 - ans
| class Solution:
def angle_clock(self, hour: int, minutes: int) -> float:
if hour == 12:
hour = 0
angle_h = hour * 30.0 + minutes / 2.0
angle_m = minutes * 6.0
ans = abs(angle_h - angle_m)
return ans if 360.0 - ans > ans else 360.0 - ans |
graph = [
[],
[2, 6],
[1],
[4, 5, 6],
[3],
[3],
[1, 3]
]
def dfs1(v, visited, graph):
stack = [v]
while stack:
node = stack.pop()
visited[node] = True
print(node)
for nd in graph[node]:
if not visited[nd]:
stack.append(nd)... | graph = [[], [2, 6], [1], [4, 5, 6], [3], [3], [1, 3]]
def dfs1(v, visited, graph):
stack = [v]
while stack:
node = stack.pop()
visited[node] = True
print(node)
for nd in graph[node]:
if not visited[nd]:
stack.append(nd)
def dfs2(v, visited, graph):
... |
class Calculator:
def __init__(self, a: int, b: int) -> None:
self.a = a
self.b = b
def suma(self) -> int:
return self.a+self.b
def resta(self) -> int:
return self.a-self.b
def multi(self) -> int:
return self.a*self.b
def divi(self) -> int:... | class Calculator:
def __init__(self, a: int, b: int) -> None:
self.a = a
self.b = b
def suma(self) -> int:
return self.a + self.b
def resta(self) -> int:
return self.a - self.b
def multi(self) -> int:
return self.a * self.b
def divi(self) -> int:
... |
#Linear Search
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
n = int(input("Enter number: "))
arr = list(map(int, input().split()))
target = int(input("Enter target: "))
print(linear_search(arr, target))
| def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
n = int(input('Enter number: '))
arr = list(map(int, input().split()))
target = int(input('Enter target: '))
print(linear_search(arr, target)) |
# FLAKE8: NOQA
c = get_config()
c.TerminalIPythonApp.display_banner = True
c.InteractiveShellApp.log_level = 20
c.InteractiveShellApp.extensions = [
# 'myextension'
]
c.InteractiveShellApp.exec_lines = [
# '%load_ext pyflyby',
# 'import json',
# 'import requests',
# 'import pandas as pd',
]
c.Inte... | c = get_config()
c.TerminalIPythonApp.display_banner = True
c.InteractiveShellApp.log_level = 20
c.InteractiveShellApp.extensions = []
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_files = []
c.InteractiveShell.autoindent = True
c.InteractiveShell.colors = 'LightBG'
c.InteractiveShell.confirm_exit = ... |
# Selection structure
# conditional operators: if, else,elif
name = "Pedro"
if name:
print("The variable is not empty")
number1 = 20
number2 = 30
if number1 != number2:
print("Number 1 is lower than number 2")
else:
print("Number 2 is bigger than number 1")
color = "blue"
if color == "green":
pr... | name = 'Pedro'
if name:
print('The variable is not empty')
number1 = 20
number2 = 30
if number1 != number2:
print('Number 1 is lower than number 2')
else:
print('Number 2 is bigger than number 1')
color = 'blue'
if color == 'green':
print('Go ahead')
elif color == 'red':
print('Stop')
elif color == ... |
class TestModel_E2E_CNN:
def test_basic(self):
pass
# TODO
| class Testmodel_E2E_Cnn:
def test_basic(self):
pass |
# -*- coding: utf-8 -*-
def execute_rule(**kwargs):
sql = kwargs.get("sql")
bind_num = kwargs.get("or_num")
if sql.count(" or ") > bind_num:
return True
return False
| def execute_rule(**kwargs):
sql = kwargs.get('sql')
bind_num = kwargs.get('or_num')
if sql.count(' or ') > bind_num:
return True
return False |
def gen_mp4(src='pipe:0', dest='pipe:1'):
return [
'ffmpeg',
'-y',
'-i', src,
'-crf', '25',
'-preset', 'faster',
'-f', 'mp4',
'-movflags', 'frag_keyframe+empty_moov',
dest
]
def gen_mp3(src='pipe:0', dest='pipe:1', empty=False):
cmd = [
... | def gen_mp4(src='pipe:0', dest='pipe:1'):
return ['ffmpeg', '-y', '-i', src, '-crf', '25', '-preset', 'faster', '-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov', dest]
def gen_mp3(src='pipe:0', dest='pipe:1', empty=False):
cmd = ['ffmpeg', '-y', '-i', src, '-codec:a', 'libmp3lame', '-qscale:a', '2', dest]
... |
pink = 0xDEADBF
yellow = 0xFDDF86
blue = 0x6F90F5
red = 0xe74c3c
dark_red = 0x992d22
green = 0x1fb600
gold = 0xd4af3a
| pink = 14593471
yellow = 16637830
blue = 7311605
red = 15158332
dark_red = 10038562
green = 2078208
gold = 13938490 |
# -*- coding: utf-8 -*-
"""
Unit test package for execution_trace.
"""
| """
Unit test package for execution_trace.
""" |
# Use this file to maintain resume data
# ======================================================
# ============= NAME AND CONTACT =======================
contact_info = {
'name':'Some Guy',
'street':'123 Fake St',
'city': 'Springfield',
'state':'OR',
'zip': '99700',
'phone':'555-555-5555',
'email':'som... | contact_info = {'name': 'Some Guy', 'street': '123 Fake St', 'city': 'Springfield', 'state': 'OR', 'zip': '99700', 'phone': '555-555-5555', 'email': 'someguy@somewebsite.example.com', 'title': 'All Around Great Guy'}
links = [{'url': 'http://www.google.com', 'label': 'Link'}]
about = 'Some Guy has over 20 years of expe... |
class Enum(object):
class __metaclass__(type):
def __getitem__(self, key):
return "Constants.{0}".format([item for item in self.__dict__ if key == self.__dict__[item]][0])
def get_name(self, key):
return "Constants.{0}".format([item for item in self.__dict__ if key == self.__... | class Enum(object):
class __Metaclass__(type):
def __getitem__(self, key):
return 'Constants.{0}'.format([item for item in self.__dict__ if key == self.__dict__[item]][0])
def get_name(self, key):
return 'Constants.{0}'.format([item for item in self.__dict__ if key == self... |
#create
dictionary1 = {1:"a", 2:"b", 3:"c"}
#access
print(dictionary1[1])
#updating
dictionary1[1]="hello"
print(dictionary1)
#delete
del dictionary1[1]
dictionary1.clear() # to clear it but keep the variable
print(dictionary1.keys())
print(dictionary1.values())
| dictionary1 = {1: 'a', 2: 'b', 3: 'c'}
print(dictionary1[1])
dictionary1[1] = 'hello'
print(dictionary1)
del dictionary1[1]
dictionary1.clear()
print(dictionary1.keys())
print(dictionary1.values()) |
# Adapted, with minor modifications, from stackoverflow:
# https://stackoverflow.com/questions/6752374/cube-root-modulo-p-how-do-i-do-this
# did not test fully, but it works for the NTTRU parameters we're using
def tonelli3(a,p,many=False):
def solution(p,root):
g=p-2
while pow(g,(p-1)//3,p)==1: ... | def tonelli3(a, p, many=False):
def solution(p, root):
g = p - 2
while pow(g, (p - 1) // 3, p) == 1:
g -= 1
g = pow(g, (p - 1) // 3, p)
return sorted([root % p, root * g % p, root * g ** 2 % p])
a = a % p
if p in [2, 3] or a == 0:
return a
if p % 3 ==... |
"""Descriptor utilities.
Utilities to support special Python descriptors [1,2], in particular the use of
a useful pattern for properties we call 'one time properties'. These are
object attributes which are declared as properties, but become regular
attributes once they've been read the first time. They can thus be e... | """Descriptor utilities.
Utilities to support special Python descriptors [1,2], in particular the use of
a useful pattern for properties we call 'one time properties'. These are
object attributes which are declared as properties, but become regular
attributes once they've been read the first time. They can thus be e... |
def common_end(L1: list, L2: list)-> bool:
"""Returns True if they have the same first element or the same last element
or if the first and last elements of both lists are the same. Otherwise,
the function returns False .
Example:
common_end(test_list1,test_list2)
Faluse
... | def common_end(L1: list, L2: list) -> bool:
"""Returns True if they have the same first element or the same last element
or if the first and last elements of both lists are the same. Otherwise,
the function returns False .
Example:
common_end(test_list1,test_list2)
Faluse
""... |
def localSant(numOfSiblings, numOfSweets) -> str:
try:
if numOfSweets == 0:
return 'no sweets left'
if numOfSweets % numOfSiblings == 0:
return 'give away'
else:
return 'eat them yourself'
except ZeroDivisionError:
return 'eat them yourself'
if __name__ == '__main__':
print(... | def local_sant(numOfSiblings, numOfSweets) -> str:
try:
if numOfSweets == 0:
return 'no sweets left'
if numOfSweets % numOfSiblings == 0:
return 'give away'
else:
return 'eat them yourself'
except ZeroDivisionError:
return 'eat them yourself'
i... |
def part1(s):
i = 0
while i < len(s) - 1:
react = abs(ord(s[i]) - ord(s[i+1])) == 32
if react:
if i == len(s) - 1:
s = s[:i]
else:
s = s[:i] + s[i+2:]
i = max(0, i-1)
else:
i += 1
return len(s)
def ... | def part1(s):
i = 0
while i < len(s) - 1:
react = abs(ord(s[i]) - ord(s[i + 1])) == 32
if react:
if i == len(s) - 1:
s = s[:i]
else:
s = s[:i] + s[i + 2:]
i = max(0, i - 1)
else:
i += 1
return len(s)
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | class Commandtree(object):
""" a command tree """
def __init__(self, data, children=None):
self.data = data
if not children:
self.children = []
else:
self.children = children
def get_child(self, child_name, kids):
""" returns the object with the name... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 17:05:23 2018
@author: user
"""
| """
Created on Sun Sep 30 17:05:23 2018
@author: user
""" |
'''Common constants.'''
NUCLIOTIDES = ('A', 'C', 'G', 'T')
# vcf data columns
CHROM = 'CHROM'
POS = 'POS'
ID = 'ID'
REF = 'REF'
ALT = 'ALT'
QUAL = 'QUAL'
FILTER = 'FILTER'
INFO = 'INFO'
FORMAT = 'FORMAT'
MANDATORY_FIELDS = (CHROM, POS, ID, REF, ALT, QUAL, FILTER)
# Info-section keys
NUMBER = 'Number'
TYPE = 'Type'
... | """Common constants."""
nucliotides = ('A', 'C', 'G', 'T')
chrom = 'CHROM'
pos = 'POS'
id = 'ID'
ref = 'REF'
alt = 'ALT'
qual = 'QUAL'
filter = 'FILTER'
info = 'INFO'
format = 'FORMAT'
mandatory_fields = (CHROM, POS, ID, REF, ALT, QUAL, FILTER)
number = 'Number'
type = 'Type'
description = 'Description'
mandatory_field... |
# Link: https://leetcode.com/problems/clone-graph/
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGrap... | class Solution:
def clone_graph(self, node):
if not node:
return None
q = []
m = {}
head = undirected_graph_node(node.label)
q.append(node)
m[node] = head
while len(q):
curr = q.pop()
for neighbor in curr.neighbors:
... |
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load(":dot_case.bzl", "dot_case")
def _dot_case_test_impl(ctx):
env = unittest.begin(ctx)
tt = [
["", ""],
["test", "test"],
["test string", "test.string"],
["Test String", "test.string"],
["dot.case", "dot.c... | load('@bazel_skylib//lib:unittest.bzl', 'asserts', 'unittest')
load(':dot_case.bzl', 'dot_case')
def _dot_case_test_impl(ctx):
env = unittest.begin(ctx)
tt = [['', ''], ['test', 'test'], ['test string', 'test.string'], ['Test String', 'test.string'], ['dot.case', 'dot.case'], ['path/case', 'path.case'], ['Test... |
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository", "new_git_repository")
_BBCP_BUILD = """
package(default_visibility = ["//visibility:public"])
# TODO(sustrik): make this hermetic
genrule(
name = "bbcp_binary",
srcs = glob(["**"]),
outs = ["bbcp"],
cmd = "pushd $$(dirname $(locatio... | load('@bazel_tools//tools/build_defs/repo:git.bzl', 'git_repository', 'new_git_repository')
_bbcp_build = '\npackage(default_visibility = ["//visibility:public"])\n\n# TODO(sustrik): make this hermetic\ngenrule(\n name = "bbcp_binary",\n srcs = glob(["**"]),\n outs = ["bbcp"],\n cmd = "pushd $$(dirname $(lo... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Education, obj[6]: Occupation, obj[7]: Bar, obj[8]: Coffeehouse, obj[9]: Restaurant20to50, obj[10]: Direction_same, obj[11]: Distance
# {"feature": "Bar", "instances": 34, "metric_value": 0.9975, "depth": 1}
... | def find_decision(obj):
if obj[7] <= 2.0:
if obj[2] > 1:
if obj[11] <= 2:
if obj[5] <= 3:
if obj[4] > 0:
if obj[10] <= 0:
if obj[8] <= 2.0:
if obj[9] <= 1.0:
... |
def bin_to_oct(binary):
decimal = int(binary, 2)
return oct(decimal)
def oct_to_bin(octal):
decimal = int(octal, 8)
return bin(decimal)
if __name__ == "__main__":
print(bin_to_oct("111"))
print(oct_to_bin("7")) | def bin_to_oct(binary):
decimal = int(binary, 2)
return oct(decimal)
def oct_to_bin(octal):
decimal = int(octal, 8)
return bin(decimal)
if __name__ == '__main__':
print(bin_to_oct('111'))
print(oct_to_bin('7')) |
'''
Function for insertion sort
Time Complexity : O(N)
Space Complexity : O(N)
Auxilary Space : O(1)
'''
def insertionSort(ar):
for i in range(1,len(ar)):
j = i - 1
elem = ar[i]
while(j >= 0 and ar[j] > elem):
ar[j + 1] = ar[j]
j -= 1
a... | """
Function for insertion sort
Time Complexity : O(N)
Space Complexity : O(N)
Auxilary Space : O(1)
"""
def insertion_sort(ar):
for i in range(1, len(ar)):
j = i - 1
elem = ar[i]
while j >= 0 and ar[j] > elem:
ar[j + 1] = ar[j]
j -= 1
ar[j + ... |
assert 1 < 2
assert 1 < 2 < 3
assert 5 == 5 == 5
assert (5 == 5) == True
assert 5 == 5 != 4 == 4 > 3 > 2 < 3 <= 3 != 0 == 0
assert not 1 > 2
assert not 5 == 5 == True
assert not 5 == 5 != 5 == 5
assert not 1 < 2 < 3 > 4
assert not 1 < 2 > 3 < 4
assert not 1 > 2 < 3 < 4
| assert 1 < 2
assert 1 < 2 < 3
assert 5 == 5 == 5
assert (5 == 5) == True
assert 5 == 5 != 4 == 4 > 3 > 2 < 3 <= 3 != 0 == 0
assert not 1 > 2
assert not 5 == 5 == True
assert not 5 == 5 != 5 == 5
assert not 1 < 2 < 3 > 4
assert not 1 < 2 > 3 < 4
assert not 1 > 2 < 3 < 4 |
def find_salary_threshold(target_payroll, current_salaries):
# custom algorithm, not from the book
# first i take avg salary based on payroll and total number of current_salaries in current_salaries list
# residue is the remainder left after comparing salary with avg_target for any salary that's more than avg_tar... | def find_salary_threshold(target_payroll, current_salaries):
avg_target = target_payroll // len(current_salaries)
residue = 0
i = 0
while i < len(current_salaries):
if current_salaries[i] < avg_target:
residue += avg_target - current_salaries[i]
i += 1
else:
... |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Tabea Spahn <tabea.spahn@e-mundo.de>
# This program is published under a GPLv2 license
# scapy.contrib.status = skip
"""
Package of contrib automotive xcp specific modules
that have to be loaded explicitly.
""... | """
Package of contrib automotive xcp specific modules
that have to be loaded explicitly.
""" |
#-----------------------------------------------------------------------------
#
# Copyright (c) 2005 by Enthought, Inc.
# All rights reserved.
#
#-----------------------------------------------------------------------------
""" Two-dimensionsal plotting application toolkit.
Part of the Chaco project of the Entho... | """ Two-dimensionsal plotting application toolkit.
Part of the Chaco project of the Enthought Tool Suite.
""" |
class OrderedMap(dict):
def __init__(self,*args,**kwargs):
super().__init__(*args, **kwargs)
def __iter__(self):
return iter(sorted(super().__iter__()))
class OrderedSet(set):
def __init__(self,lst=[]):
super().__init__(lst)
def __iter__(self):
... | class Orderedmap(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __iter__(self):
return iter(sorted(super().__iter__()))
class Orderedset(set):
def __init__(self, lst=[]):
super().__init__(lst)
def __iter__(self):
return iter(sorted(... |
class Solution:
def luckyNumbers(self, mat):
def solve(i, m):
for row in mat:
if row[i] > m: return False
return True
ans = []
for row in mat:
idx, mn = [], 10 ** 6
for i, ele in enumerate(row):
if ele < mn:
... | class Solution:
def lucky_numbers(self, mat):
def solve(i, m):
for row in mat:
if row[i] > m:
return False
return True
ans = []
for row in mat:
(idx, mn) = ([], 10 ** 6)
for (i, ele) in enumerate(row):
... |
__author__ = 'marble_xu'
DEBUG = False
DEBUG_START_X = 110
DEBUG_START_Y = 534
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 800
SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)
ORIGINAL_CAPTION = 'Super Mario Bros.'
# COLORS
# R G B
GRAY = (100, 100, 100)
NAVYBLUE = ( 60, 60, 100)
WHITE = ... | __author__ = 'marble_xu'
debug = False
debug_start_x = 110
debug_start_y = 534
screen_height = 600
screen_width = 800
screen_size = (SCREEN_WIDTH, SCREEN_HEIGHT)
original_caption = 'Super Mario Bros.'
gray = (100, 100, 100)
navyblue = (60, 60, 100)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
forest_gr... |
def mergesort(array):
if len(array) <= 1:
return array
if len(array) % 2 == 0:
midpoint = (len(array) // 2)
else:
midpoint = (len(array)+1) // 2
left = mergesort(array[:midpoint])
right = mergesort(array[midpoint:])
# Merge our two halves and return
return merge(le... | def mergesort(array):
if len(array) <= 1:
return array
if len(array) % 2 == 0:
midpoint = len(array) // 2
else:
midpoint = (len(array) + 1) // 2
left = mergesort(array[:midpoint])
right = mergesort(array[midpoint:])
return merge(left, right)
def merge(left, right):
m... |
# Find the set of all integers a, b, c, d that satisfy the following conditions:
# 0 <= a^3 + b^3 + c^3 + d^3 <= N
# a^3 + b^3 = c^ + d3
# 0 <= a, b, c, d <= N
def find_satisfy_sets(N):
a = 0
d = dict()
m = N // 2
while pow(a, 3) <= m:
for b in range(a):
t = pow(a, 3) + pow(b, 3)
... | def find_satisfy_sets(N):
a = 0
d = dict()
m = N // 2
while pow(a, 3) <= m:
for b in range(a):
t = pow(a, 3) + pow(b, 3)
if t > m:
break
if t in d:
for cd in d[t]:
print(a, b, cd[0], cd[1])
d[... |
expected_output = {
"slot": {
"P6": {
"sensor": {
"Temp: FC PWM1": {"state": "Fan Speed 45%", "reading": "25 Celsius"}
}
},
"P7": {
"sensor": {
"Temp: FC PWM1": {"state": "Fan Speed 45%", "reading": "25 Celsius"}
... | expected_output = {'slot': {'P6': {'sensor': {'Temp: FC PWM1': {'state': 'Fan Speed 45%', 'reading': '25 Celsius'}}}, 'P7': {'sensor': {'Temp: FC PWM1': {'state': 'Fan Speed 45%', 'reading': '25 Celsius'}}}}} |
def square_dict(num):
return {n: n * n for n in range(1, int(num) + 1)}
# py.test exercise_10_27_16.py --cov=exercise_10_27_16.py --cov-report=html
def test_square_dict():
assert square_dict(3) == {1: 1, 2: 4, 3: 9}
assert square_dict(0) == {}
assert square_dict(-1) == {}
if __name__ == '__main__':
... | def square_dict(num):
return {n: n * n for n in range(1, int(num) + 1)}
def test_square_dict():
assert square_dict(3) == {1: 1, 2: 4, 3: 9}
assert square_dict(0) == {}
assert square_dict(-1) == {}
if __name__ == '__main__':
print(square_dict(input('Number: '))) |
n: int; i: int; somaPares: int; contPares: int
mediaPares: float
n = int(input("Quantos elementos vai ter o vetor? "))
vet: [int] = [0 for x in range(n)]
for i in range(0, n):
vet[i] = int(input("Digite um numero: "))
somaPares = 0
contPares = 0
for i in range(0, n):
if vet[i] % 2 == 0:
somaPares =... | n: int
i: int
soma_pares: int
cont_pares: int
media_pares: float
n = int(input('Quantos elementos vai ter o vetor? '))
vet: [int] = [0 for x in range(n)]
for i in range(0, n):
vet[i] = int(input('Digite um numero: '))
soma_pares = 0
cont_pares = 0
for i in range(0, n):
if vet[i] % 2 == 0:
soma_pares = s... |
# create simple dictionary
person_one = {
'name': 'tazri',
'age' : 17
}
# direct method
person_two = person_one;
print("person_one : ",person_one);
print("person_two : ",person_two);
# changing value in person two and see what happen
person_two['name'] = 'focasa';
print("\n\nAfter change name in person two ... | person_one = {'name': 'tazri', 'age': 17}
person_two = person_one
print('person_one : ', person_one)
print('person_two : ', person_two)
person_two['name'] = 'focasa'
print('\n\nAfter change name in person two : ')
print('person_one : ', person_one)
person_one['name'] = 'tazri'
copy_person = person_one.copy()
copy_perso... |
"""Create symlink to specific submodule path."""
def _submodule_repository(repository_ctx):
# Remove the need to try and get a path to 'WORKSPACE.bazel'
# once we start using a bazel version that includes the following commit:
# https://github.com/bazelbuild/bazel/commit/8edf6abec40c848a5df93647f948e31f324... | """Create symlink to specific submodule path."""
def _submodule_repository(repository_ctx):
workspace_root = repository_ctx.path(label('//:WORKSPACE.bazel')).dirname
for segment in repository_ctx.attr.path.split('/'):
workspace_root = workspace_root.get_child(segment)
repository_ctx.symlink(workspa... |
vHora = float(input("informe o valor da sua hora"))
qtdHoras = int(input("informe a quantidade de horas trabalhadas por sua pessoa"))
salario = vHora*qtdHoras
print(salario)
ir = salario*0.11
print(ir)
inss = salario*0.08
print(inss)
sindicato = salario*0.05
print(sindicato)
sLiquido = salario-ir-inss-sindicato
print(s... | v_hora = float(input('informe o valor da sua hora'))
qtd_horas = int(input('informe a quantidade de horas trabalhadas por sua pessoa'))
salario = vHora * qtdHoras
print(salario)
ir = salario * 0.11
print(ir)
inss = salario * 0.08
print(inss)
sindicato = salario * 0.05
print(sindicato)
s_liquido = salario - ir - inss - ... |
BASE_ATTR_TMPL = '_attr_{name}'
BASE_ATTR_GET_TMPL = '_attr__get_{name}'
BASE_ATTR_SET_TMPL = '_attr__set_{name}'
def mixin(cls):
return cls
| base_attr_tmpl = '_attr_{name}'
base_attr_get_tmpl = '_attr__get_{name}'
base_attr_set_tmpl = '_attr__set_{name}'
def mixin(cls):
return cls |
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse,... | def find_decision(obj):
if obj[5] > 1:
if obj[15] > 0.0:
if obj[18] > 0.0:
if obj[12] <= 7:
if obj[8] <= 6:
if obj[14] > 0.0:
if obj[19] <= 0:
if obj[17] > 2.0:
... |
def support_map_vectorized1(linked,num_indirect_equal_direct=3):
# columns
# 'team_j', 'team_i_name', 'team_i_score', 'team_i_H_A_N',
# 'team_j_i_score', 'team_j_i_H_A_N', 'game_i_j', 'team_k_name',
# 'team_k_score', 'team_k_H_A_N', 'team_j_k_score', 'team_j_k_H_A_N',
# 'game_k_j'
linked["direc... | def support_map_vectorized1(linked, num_indirect_equal_direct=3):
linked['direct'] = linked['team_i_name'] == linked['team_k_name']
for_index1 = linked[['team_i_name', 'team_k_name']].copy()
for_index1.loc[linked['direct']] = linked.loc[linked['direct'], ['team_i_name', 'team_j_name']]
for_index1.column... |
# Algorith of Attraction
# @author unobatbayar
# Basic information used: Physical, Status, Character, Chemistry
# Let's just give points for each trait, however, minus points if not her preference
points = 0 # will give points depending on traits below
questions = ["He has a symmetrical face:",
"He has ... | points = 0
questions = ['He has a symmetrical face:', 'He has a good smell:', 'He is handsome:', 'He is well dressed or looking good:', 'He has clear skin, bright eyes, fit body:', 'He is powerful (financial, physical, Informational or etc):', 'He is ambitious, motivated:', 'He has a great job or holds a reputable posi... |
#!/usr/bin/env python
"""
This file defines custom exceptions for bayesloop.
"""
class ConfigurationError(Exception):
"""
Raised if some part of the configuration of a study instance is not consistent, e.g. non-existent parameter names
are set to be optimized or the shape of a custom prior distribution do... | """
This file defines custom exceptions for bayesloop.
"""
class Configurationerror(Exception):
"""
Raised if some part of the configuration of a study instance is not consistent, e.g. non-existent parameter names
are set to be optimized or the shape of a custom prior distribution does not fit the grid siz... |
class Solution:
def maxDiff(self, num: int) -> int:
num = str(num)
d = [int(c) for c in num]
d = list(set(d))
res = []
for x in d:
for y in range(0, 10):
p = str(num)
p = p.replace(str(x), str(y))
if p[0] != '0' and ... | class Solution:
def max_diff(self, num: int) -> int:
num = str(num)
d = [int(c) for c in num]
d = list(set(d))
res = []
for x in d:
for y in range(0, 10):
p = str(num)
p = p.replace(str(x), str(y))
if p[0] != '0' an... |
# Exercise 006: Double, Triple, Square Root
"""Create an algorithm that reads a number and displays its double, triple and square root."""
# First, we ask the user for an input
num = float(input("Enter a number: "))
# So we multiply by two and by three to get double and triple
double_num = num * 2
triple_num = num *... | """Create an algorithm that reads a number and displays its double, triple and square root."""
num = float(input('Enter a number: '))
double_num = num * 2
triple_num = num * 3
sqrt_num = num ** 0.5
print(f"Given the value {num}, it's double is {double_num}")
print(f"It's triple is {triple_num} and the square root is {s... |
"""
Linear Motion.
Changing a variable to create a moving line. When the line moves off the edge
of the window, the variable is set to 0, which places the line back at the
bottom of the screen.
"""
a = None
def setup():
size(640, 360)
stroke(255)
a = height / 2
def draw():
background(51)
line(... | """
Linear Motion.
Changing a variable to create a moving line. When the line moves off the edge
of the window, the variable is set to 0, which places the line back at the
bottom of the screen.
"""
a = None
def setup():
size(640, 360)
stroke(255)
a = height / 2
def draw():
background(51)
line(0, ... |
"""
'W0104': ('Statement seems to have no effect',
'Used when a statement doesn\'t have (or at least seems to) \
any effect.'),
'W0105': ('String statement has no effect',
'Used when a string is used as a statement (which of course \
has no effect). This i... | """
'W0104': ('Statement seems to have no effect',
'Used when a statement doesn't have (or at least seems to) any effect.'),
'W0105': ('String statement has no effect',
'Used when a string is used as a statement (which of course has no effect). This is a p... |
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""Math.
Running time: O(k) where k is the area of the board.
"""
def count(i, j, m, n):
s = 0
for i in range(max(0, r-1), min(r+2, len(board))):
for j in range(max(0, c-1),... | class Solution:
def game_of_life(self, board: List[List[int]]) -> None:
"""Math.
Running time: O(k) where k is the area of the board.
"""
def count(i, j, m, n):
s = 0
for i in range(max(0, r - 1), min(r + 2, len(board))):
for j in range(max(... |
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print(phonebook)
phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781}
for name, number in p... | phonebook = {}
phonebook['John'] = 938477566
phonebook['Jack'] = 938377264
phonebook['Jill'] = 947662781
print(phonebook)
phonebook = {'John': 938477566, 'Jack': 938377264, 'Jill': 947662781}
print(phonebook)
phonebook = {'John': 938477566, 'Jack': 938377264, 'Jill': 947662781}
for (name, number) in phonebook.items():
... |
INTRAHEALTH_DOMAINS = ('ipm-senegal', 'testing-ipm-senegal', 'ct-apr')
OPERATEUR_XMLNSES = (
'http://openrosa.org/formdesigner/7330597b92db84b1a33c7596bb7b1813502879be',
'http://openrosa.org/formdesigner/EF8B5DB8-4FB2-4CFB-B0A2-CDD26ADDAE3D'
)
COMMANDE_XMLNSES = (
'http://openrosa.org/formdesigner/9ED6673... | intrahealth_domains = ('ipm-senegal', 'testing-ipm-senegal', 'ct-apr')
operateur_xmlnses = ('http://openrosa.org/formdesigner/7330597b92db84b1a33c7596bb7b1813502879be', 'http://openrosa.org/formdesigner/EF8B5DB8-4FB2-4CFB-B0A2-CDD26ADDAE3D')
commande_xmlnses = ('http://openrosa.org/formdesigner/9ED66735-752D-4C69-B9C8-... |
# This method computes the name (and IDs) of the features by recursion
def addNames(curName, curd, targetd, lasti, curID,options,names,ids,N):
if curd<targetd:
for i in range(lasti,N):
addNames(curName + (' * ' if len(curName)>0 else '') + options[i], curd + 1, targetd, i + 1, curID + [i], optio... | def add_names(curName, curd, targetd, lasti, curID, options, names, ids, N):
if curd < targetd:
for i in range(lasti, N):
add_names(curName + (' * ' if len(curName) > 0 else '') + options[i], curd + 1, targetd, i + 1, curID + [i], options, names, ids, N)
elif curd == targetd:
names.a... |
"""
Queries of lock queries
"""
def gql_locks(fragment):
"""
Return the GraphQL locks query
"""
return f'''
query($where: LockWhere!, $first: PageSize!, $skip: Int!) {{
data: locks(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
'''
GQL_LOCKS_COUNT = '''
query($where: LockWher... | """
Queries of lock queries
"""
def gql_locks(fragment):
"""
Return the GraphQL locks query
"""
return f'\nquery($where: LockWhere!, $first: PageSize!, $skip: Int!) {{\n data: locks(where: $where, first: $first, skip: $skip) {{\n {fragment}\n }}\n}}\n'
gql_locks_count = '\nquery($where: LockWhere!... |
class Full(Exception):
pass
class Empty(Exception):
pass
class Queue(object):
def __init__(self, maxSize = 0):
self._list = []
self._maxQueued = maxSize
def push(self, i):
if self._maxQueued and len(self._list) >= self._maxQueued:
raise Full
else:
... | class Full(Exception):
pass
class Empty(Exception):
pass
class Queue(object):
def __init__(self, maxSize=0):
self._list = []
self._maxQueued = maxSize
def push(self, i):
if self._maxQueued and len(self._list) >= self._maxQueued:
raise Full
else:
... |
def validate_coordinates(row, col):
return 0 <= row < matrix_size and 0 <= col < matrix_size
matrix_size = int(input())
matrix = [[int(num) for num in input().split()] for _ in range(matrix_size)]
line = input()
while not line == "END":
command, row, col, value = line.split()
row = int(row)
col = int... | def validate_coordinates(row, col):
return 0 <= row < matrix_size and 0 <= col < matrix_size
matrix_size = int(input())
matrix = [[int(num) for num in input().split()] for _ in range(matrix_size)]
line = input()
while not line == 'END':
(command, row, col, value) = line.split()
row = int(row)
col = int(... |
def animated_player_mgt(game_mgr):
def fn_get_action(board):
# fn_display(board_pieces)
valid_moves = game_mgr.fn_get_valid_moves(board, 1)
if valid_moves is None:
return None
for i in range(len(valid_moves)):
if valid_moves[i]:
print("[", int... | def animated_player_mgt(game_mgr):
def fn_get_action(board):
valid_moves = game_mgr.fn_get_valid_moves(board, 1)
if valid_moves is None:
return None
for i in range(len(valid_moves)):
if valid_moves[i]:
print('[', int(i / game_mgr.fn_get_board_size()),... |
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
ans = 0
for i in range(len(columnTitle)):
temp = pow(26,len(columnTitle)-1-i)*(ord(columnTitle[i])-ord('A')+1)
ans+=temp
return ans | class Solution:
def title_to_number(self, columnTitle: str) -> int:
ans = 0
for i in range(len(columnTitle)):
temp = pow(26, len(columnTitle) - 1 - i) * (ord(columnTitle[i]) - ord('A') + 1)
ans += temp
return ans |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.