content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
Created on May 4 - 2019
---Based on the 2-stage stochastic program structure
---Assumption: RHS is random
---read stoc file (.sto)
---save the distributoin of the random variables and return the
---random variables
@author: Siavash Tabrizian - stabrizian@smu.edu
"""
class readstoc:
def __init__(self, name):
self.name = name + ".sto"
self.rv = list()
self.dist = list()
self.cumul_dist = list()
self.rvnum = 0
## Read the stoc file
def readfile(self):
with open(self.name, "r") as f:
data = f.readlines()
count = 0
cumul = 0
for line in data:
words = line.split()
#print words
if len(words) > 2:
if words[0] != "RHS":
print("ERROR: Randomness is not on the RHS")
else:
#store the name of the random variables
if words[1] not in self.rv:
cumul = 0
self.rv.append(words[1])
tmp = list()
tmp.append({float(words[2]):float(words[3])})
self.dist.append(tmp)
tmp = list()
tmp.append({float(words[2]):float(words[3])})
self.cumul_dist.append(tmp)
count += 1
else:
cumul += float(words[3])
tmp = list()
tmp.append({float(words[2]):float(words[3])})
rvidx = self.rv.index(words[1])
self.dist[rvidx].append(tmp)
tmp = list()
tmp.append({float(words[2]):cumul})
self.cumul_dist[rvidx].append(tmp)
#count contains the number of rvs
self.rvnum = count
| """
Created on May 4 - 2019
---Based on the 2-stage stochastic program structure
---Assumption: RHS is random
---read stoc file (.sto)
---save the distributoin of the random variables and return the
---random variables
@author: Siavash Tabrizian - stabrizian@smu.edu
"""
class Readstoc:
def __init__(self, name):
self.name = name + '.sto'
self.rv = list()
self.dist = list()
self.cumul_dist = list()
self.rvnum = 0
def readfile(self):
with open(self.name, 'r') as f:
data = f.readlines()
count = 0
cumul = 0
for line in data:
words = line.split()
if len(words) > 2:
if words[0] != 'RHS':
print('ERROR: Randomness is not on the RHS')
elif words[1] not in self.rv:
cumul = 0
self.rv.append(words[1])
tmp = list()
tmp.append({float(words[2]): float(words[3])})
self.dist.append(tmp)
tmp = list()
tmp.append({float(words[2]): float(words[3])})
self.cumul_dist.append(tmp)
count += 1
else:
cumul += float(words[3])
tmp = list()
tmp.append({float(words[2]): float(words[3])})
rvidx = self.rv.index(words[1])
self.dist[rvidx].append(tmp)
tmp = list()
tmp.append({float(words[2]): cumul})
self.cumul_dist[rvidx].append(tmp)
self.rvnum = count |
#********************************************************************
# Filename: FibonacciSearch.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the fibonacci search algorithm.
#*********************************************************************
def fibonacci_search(arr, val):
fib_N_2 = 0
fib_N_1 = 1
fibNext = fib_N_1 + fib_N_2
length = len(arr)
if length == 0:
return 0
while fibNext < len(arr):
fib_N_2 = fib_N_1
fib_N_1 = fibNext
fibNext = fib_N_1 + fib_N_2
index = -1
while fibNext > 1:
i = min(index + fib_N_2, (length - 1))
if arr[i] < val:
fibNext = fib_N_1
fib_N_1 = fib_N_2
fib_N_2 = fibNext - fib_N_1
index = i
elif arr[i] > val:
fibNext = fib_N_2
fib_N_1 = fib_N_1 - fib_N_2
fib_N_2 = fibNext - fib_N_1
else:
return i
if (fib_N_1 and index < length - 1) and (arr[index + 1] == val):
return index + 1
return -1
if __name__ == "__main__":
collection = [1, 6, 7, 0, 0, 0]
print("List numbers: %s\n" % repr(collection))
target_input = input("Enter a single number to be found in the list:\n")
target = int(target_input)
result = fibonacci_search(collection, target)
if result > 0:
print("%s found at positions: %s" % (target, result))
else:
print("Number not found in list")
| def fibonacci_search(arr, val):
fib_n_2 = 0
fib_n_1 = 1
fib_next = fib_N_1 + fib_N_2
length = len(arr)
if length == 0:
return 0
while fibNext < len(arr):
fib_n_2 = fib_N_1
fib_n_1 = fibNext
fib_next = fib_N_1 + fib_N_2
index = -1
while fibNext > 1:
i = min(index + fib_N_2, length - 1)
if arr[i] < val:
fib_next = fib_N_1
fib_n_1 = fib_N_2
fib_n_2 = fibNext - fib_N_1
index = i
elif arr[i] > val:
fib_next = fib_N_2
fib_n_1 = fib_N_1 - fib_N_2
fib_n_2 = fibNext - fib_N_1
else:
return i
if (fib_N_1 and index < length - 1) and arr[index + 1] == val:
return index + 1
return -1
if __name__ == '__main__':
collection = [1, 6, 7, 0, 0, 0]
print('List numbers: %s\n' % repr(collection))
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
result = fibonacci_search(collection, target)
if result > 0:
print('%s found at positions: %s' % (target, result))
else:
print('Number not found in list') |
class HostAssignedStorageVolumes(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_assigned_volumes(idx_name)
class HostAssignedStorageVolumesColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts()
| class Hostassignedstoragevolumes(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_assigned_volumes(idx_name)
class Hostassignedstoragevolumescolumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts() |
class Input:
"""
Input prototype
"""
def __init__(self, mod_opts=None):
self.name = ""
self.pretty_name = ""
self.help = ""
self.image_large = ""
self.image_small = ""
self.opts = mod_opts
if mod_opts:
if 'name' in mod_opts:
self.name = mod_opts['name']
self.parse_options()
def List(self):
pass
def parse_options(self):
if self.opts:
# If this module has defined module options
if self.module_options:
self.module_options.parse_dict(self.opts) | class Input:
"""
Input prototype
"""
def __init__(self, mod_opts=None):
self.name = ''
self.pretty_name = ''
self.help = ''
self.image_large = ''
self.image_small = ''
self.opts = mod_opts
if mod_opts:
if 'name' in mod_opts:
self.name = mod_opts['name']
self.parse_options()
def list(self):
pass
def parse_options(self):
if self.opts:
if self.module_options:
self.module_options.parse_dict(self.opts) |
def checkBingo(c):
for x in range(5):
if c[(x * 5) + 0] == c[(x * 5) + 1] == c[(x * 5) + 2] == c[(x * 5) + 3] == c[(x * 5) + 4] == True:
return True
if c[x + 0] == c[x + 5] == c[x + 10] == c[x + 15] == c[x + 20] == True:
return True
return False
def part2(path):
p_input = []
with open(path) as input:
for l in input:
p_input.append(l)
drawing = [int(x) for x in p_input[0].split(",")]
p_input = p_input[2:]
card = 0
cards = [[]]
ticked = [[]]
for l in p_input:
if l == "\n":
card += 1
cards.append([])
ticked.append([])
else:
# print(l[0:2])
cards[card].append(int(l[0:2]))
ticked[card].append(False)
# print(l[3:5])
cards[card].append(int(l[3:5]))
ticked[card].append(False)
# print(l[6:8])
cards[card].append(int(l[6:8]))
ticked[card].append(False)
# print(l[9:11])
cards[card].append(int(l[9:11]))
ticked[card].append(False)
# print(l[12:15])
cards[card].append(int(l[12:15]))
ticked[card].append(False)
cards_won = 0
won_cards = set()
for n in drawing:
for i, x in enumerate(cards):
for j, y in enumerate(x):
if y == n:
ticked[i][j] = True
for i in range(len(cards)):
if i not in won_cards and checkBingo(ticked[i]):
# print(i)
cards_won += 1
won_cards.add(i)
if cards_won == len(cards):
sum_unmarked = 0
for x in range(25):
if not ticked[i][x]:
sum_unmarked += cards[i][x]
# print(n)
return sum_unmarked * n | def check_bingo(c):
for x in range(5):
if c[x * 5 + 0] == c[x * 5 + 1] == c[x * 5 + 2] == c[x * 5 + 3] == c[x * 5 + 4] == True:
return True
if c[x + 0] == c[x + 5] == c[x + 10] == c[x + 15] == c[x + 20] == True:
return True
return False
def part2(path):
p_input = []
with open(path) as input:
for l in input:
p_input.append(l)
drawing = [int(x) for x in p_input[0].split(',')]
p_input = p_input[2:]
card = 0
cards = [[]]
ticked = [[]]
for l in p_input:
if l == '\n':
card += 1
cards.append([])
ticked.append([])
else:
cards[card].append(int(l[0:2]))
ticked[card].append(False)
cards[card].append(int(l[3:5]))
ticked[card].append(False)
cards[card].append(int(l[6:8]))
ticked[card].append(False)
cards[card].append(int(l[9:11]))
ticked[card].append(False)
cards[card].append(int(l[12:15]))
ticked[card].append(False)
cards_won = 0
won_cards = set()
for n in drawing:
for (i, x) in enumerate(cards):
for (j, y) in enumerate(x):
if y == n:
ticked[i][j] = True
for i in range(len(cards)):
if i not in won_cards and check_bingo(ticked[i]):
cards_won += 1
won_cards.add(i)
if cards_won == len(cards):
sum_unmarked = 0
for x in range(25):
if not ticked[i][x]:
sum_unmarked += cards[i][x]
return sum_unmarked * n |
# 207-course-schedule.py
#
# Copyright (C) 2019 Sang-Kil Park <likejazz@gmail.com>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# Make skeleton vertex graph.
graph = {k[1]: [] for k in prerequisites}
for pr in prerequisites:
graph[pr[1]].append(pr[0])
visited = set() # Visited vertex set for permanent storage
traced = set() # Traced vertex set for temporary storage.
def visit(vertex):
if vertex in visited:
return False
traced.add(vertex)
visited.add(vertex)
if vertex in graph:
for neighbour in graph[vertex]:
if neighbour in traced or visit(neighbour):
return True # cyclic!
traced.remove(vertex)
return False
for v in graph:
if visit(v):
return False
return True
| class Solution:
def can_finish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = {k[1]: [] for k in prerequisites}
for pr in prerequisites:
graph[pr[1]].append(pr[0])
visited = set()
traced = set()
def visit(vertex):
if vertex in visited:
return False
traced.add(vertex)
visited.add(vertex)
if vertex in graph:
for neighbour in graph[vertex]:
if neighbour in traced or visit(neighbour):
return True
traced.remove(vertex)
return False
for v in graph:
if visit(v):
return False
return True |
def main():
n = int(input("Enter a number: "))
for i in range(3, n + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime: print(f"{i} ", end="")
print()
if __name__ == '__main__':
main()
| def main():
n = int(input('Enter a number: '))
for i in range(3, n + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime:
print(f'{i} ', end='')
print()
if __name__ == '__main__':
main() |
class Registry(object):
def __init__(self, name):
super(Registry, self).__init__()
self._name = name
self._module_dict = dict()
@property
def name(self):
return self._name
@property
def module_dict(self):
return self._module_dict
def __len__(self):
return len(self.module_dict)
def get(self, key):
return self._module_dict[key]
def register_module(self, module=None):
if module is None:
raise TypeError('fail to register None in Registry {}'.format(self.name))
module_name = module.__name__
if module_name in self._module_dict:
raise KeyError('{} is already registry in Registry {}'.format(module_name, self.name))
self._module_dict[module_name] = module
return module
DATASETS = Registry('dataset')
BACKBONES = Registry('backbone')
NETS = Registry('nets')
| class Registry(object):
def __init__(self, name):
super(Registry, self).__init__()
self._name = name
self._module_dict = dict()
@property
def name(self):
return self._name
@property
def module_dict(self):
return self._module_dict
def __len__(self):
return len(self.module_dict)
def get(self, key):
return self._module_dict[key]
def register_module(self, module=None):
if module is None:
raise type_error('fail to register None in Registry {}'.format(self.name))
module_name = module.__name__
if module_name in self._module_dict:
raise key_error('{} is already registry in Registry {}'.format(module_name, self.name))
self._module_dict[module_name] = module
return module
datasets = registry('dataset')
backbones = registry('backbone')
nets = registry('nets') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
Instrucciones
1. Ordenar la siguiente lista de valores por medio de ciclos y/o validaciones
arreglo = [54,26,93,17,77,31,44,55,20]
Resultado
arreglo = [54,26,93,17,77,31,44,55,20]
arreglo = [17, 20, 26, 31, 44, 54, 55, 77, 93]
"""
a = [54,26,93,17,77,31,44,55,20]
def bubbleSort(a):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)
| """
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
Instrucciones
1. Ordenar la siguiente lista de valores por medio de ciclos y/o validaciones
arreglo = [54,26,93,17,77,31,44,55,20]
Resultado
arreglo = [54,26,93,17,77,31,44,55,20]
arreglo = [17, 20, 26, 31, 44, 54, 55, 77, 93]
"""
a = [54, 26, 93, 17, 77, 31, 44, 55, 20]
def bubble_sort(a):
for passnum in range(len(alist) - 1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i + 1]:
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubble_sort(alist)
print(alist) |
'''
293. Flip Game
=========
You are playing the following Flip Game with your friend: Given a string that
contains only these two characters: + and -, you and your friend take turns to
flip two consecutive "++" into "--". The game ends when a person can no longer
make a move and therefore the other person will be the winner.
Write a function to compute all possible states of the string after one valid
move.
For example, given s = "++++", after one move, it may become one of the
following states:
[
"--++",
"+--+",
"++--"
]
If there is no valid move, return an empty list [].
'''
class Solution(object):
# https://github.com/shiyanhui/Algorithm/blob/master/LeetCode/Python/293%20Flip%20Game.py
def generatePossibleNextMoves(self, s):
res = []
for i in range(len(s)-1):
if s[i] == s[i+1] == '+':
res.append(s[:i] + '--' + s[i+2:])
return res
s = Solution()
print(s.generatePossibleNextMoves('++++'))
| """
293. Flip Game
=========
You are playing the following Flip Game with your friend: Given a string that
contains only these two characters: + and -, you and your friend take turns to
flip two consecutive "++" into "--". The game ends when a person can no longer
make a move and therefore the other person will be the winner.
Write a function to compute all possible states of the string after one valid
move.
For example, given s = "++++", after one move, it may become one of the
following states:
[
"--++",
"+--+",
"++--"
]
If there is no valid move, return an empty list [].
"""
class Solution(object):
def generate_possible_next_moves(self, s):
res = []
for i in range(len(s) - 1):
if s[i] == s[i + 1] == '+':
res.append(s[:i] + '--' + s[i + 2:])
return res
s = solution()
print(s.generatePossibleNextMoves('++++')) |
test_patterns = '''
Given source text and a list of pattens,
look for matches for each patterns within the
text and print them to stdout'''
# Look for each pattern in the text and print the results.
| test_patterns = '\nGiven source text and a list of pattens,\nlook for matches for each patterns within the\ntext and print them to stdout' |
# Source : https://leetcode.com/problems/range-sum-of-bst/
# Author : foxfromworld
# Date : 27/04/2021
# Second attempt (recursive)
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
self.retV = 0
def sub_rangeSumBST(root):
if root:
if low <= root.val <= high:
self.retV += root.val
if low < root.val:
sub_rangeSumBST(root.left)
if root.val < high:
sub_rangeSumBST(root.right)
sub_rangeSumBST(root)
return self.retV
# Date : 26/04/2021
# First attempt (iterative)
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
returnV = 0
stack = [root]
while stack:
current = stack.pop()
if current:
if low <= current.val <= high:
returnV += current.val
if low < current.val:
stack.append(current.left)
if current.val < high:
stack.append(current.right)
return returnV
| class Solution:
def range_sum_bst(self, root: TreeNode, low: int, high: int) -> int:
self.retV = 0
def sub_range_sum_bst(root):
if root:
if low <= root.val <= high:
self.retV += root.val
if low < root.val:
sub_range_sum_bst(root.left)
if root.val < high:
sub_range_sum_bst(root.right)
sub_range_sum_bst(root)
return self.retV
class Solution:
def range_sum_bst(self, root: TreeNode, low: int, high: int) -> int:
return_v = 0
stack = [root]
while stack:
current = stack.pop()
if current:
if low <= current.val <= high:
return_v += current.val
if low < current.val:
stack.append(current.left)
if current.val < high:
stack.append(current.right)
return returnV |
class IntegerString:
def __init__(self) -> None:
self.digits = bytearray([0])
self._length = 0
def __init__(self, digits: bytearray) -> None:
self.digits = digits
self._length = len(self.digits)
@property
def length(self):
return self._length
def add(self):
my_digits = []
other_digits = []
class SquareTenTree:
def __init__(self):
pass
def get_level_length(self, level: int) -> int:
if 0 == level:
return 10
return 10 ** (2 ** (level - 1))
def is_ten_factor(self, num: int) -> bool:
return num % 10 == 0
def find_level(self, num:int) -> int:
level_num = 0
while num >= 10:
num = num // 10
level_num += 1
return level_num
def find_partitions(self, l, r, dest, subset_count=-1, level=0, num_levels=0):
num_levels += 1
level_finished_flag = 0
while l <= r:
k = 1
size = 10
while (r % size == 0) and (r - size + 1) >= l:
k += 1
size = 10 ** (2 ** (k - 1))
k -= 1
if r == dest:
level = k
if k == 0:
size = 1
else:
size = 10 ** (2 ** (k - 1))
r -= size
print(r)
if k == level:
subset_count += 1
else:
level_finished_flag = 1
break
if l > r:
if level_finished_flag == 1:
num_levels += 1
subset_count += 1
print(num_levels)
print(k, " ", 1)
print(level, " ", subset_count)
else:
subset_count += 1
print(num_levels)
print(k, " ", subset_count)
return
if level_finished_flag == 1:
if subset_count >= 0:
subset_count += 1
self.find_partitions(l, r, dest, 0, k, num_levels)
print(level, " ", subset_count)
else:
self.find_partitions(l, r, dest, 0, k, num_levels-1)
if __name__ == '__main__':
st = SquareTenTree()
l = int(input())
r = int(input())
dest = r
st.find_partitions(l, r, dest)
| class Integerstring:
def __init__(self) -> None:
self.digits = bytearray([0])
self._length = 0
def __init__(self, digits: bytearray) -> None:
self.digits = digits
self._length = len(self.digits)
@property
def length(self):
return self._length
def add(self):
my_digits = []
other_digits = []
class Squaretentree:
def __init__(self):
pass
def get_level_length(self, level: int) -> int:
if 0 == level:
return 10
return 10 ** 2 ** (level - 1)
def is_ten_factor(self, num: int) -> bool:
return num % 10 == 0
def find_level(self, num: int) -> int:
level_num = 0
while num >= 10:
num = num // 10
level_num += 1
return level_num
def find_partitions(self, l, r, dest, subset_count=-1, level=0, num_levels=0):
num_levels += 1
level_finished_flag = 0
while l <= r:
k = 1
size = 10
while r % size == 0 and r - size + 1 >= l:
k += 1
size = 10 ** 2 ** (k - 1)
k -= 1
if r == dest:
level = k
if k == 0:
size = 1
else:
size = 10 ** 2 ** (k - 1)
r -= size
print(r)
if k == level:
subset_count += 1
else:
level_finished_flag = 1
break
if l > r:
if level_finished_flag == 1:
num_levels += 1
subset_count += 1
print(num_levels)
print(k, ' ', 1)
print(level, ' ', subset_count)
else:
subset_count += 1
print(num_levels)
print(k, ' ', subset_count)
return
if level_finished_flag == 1:
if subset_count >= 0:
subset_count += 1
self.find_partitions(l, r, dest, 0, k, num_levels)
print(level, ' ', subset_count)
else:
self.find_partitions(l, r, dest, 0, k, num_levels - 1)
if __name__ == '__main__':
st = square_ten_tree()
l = int(input())
r = int(input())
dest = r
st.find_partitions(l, r, dest) |
# format the date in January 1, 2022 form
def format_date(date):
return date.strftime('%B %d, %Y')
# format plural word
def format_plural(total, word):
if total != 1:
return word + 's'
return word
| def format_date(date):
return date.strftime('%B %d, %Y')
def format_plural(total, word):
if total != 1:
return word + 's'
return word |
# Transliteration rules for Chakma ASCII to Chakma
Description = u'Chakma ASCII to Unicode conversion'
TRANS_LIT_RULES = CCP_UNICODE_TRANSLITERATE = u"""
$letter = [\u11103-\u11126];
$evowel = \u1112C;
$virama = \u11133;
\u0000 > \u0020 ; # null
\u000D > \u000D ; # Carriage return
\u0020 > \u0020 ; # space
\u0021 > \0u0021 ; # !
#\u0023 > \u11142 ; # # PROBLEM
#\u0024 > \u11141 ; # $ PROBLEM
\u0025 > \u0025 ; # %
\u0026 > \u11100 ; # &
# \u002a > \u11133 \u11123 ; # *
# \u002e > \u1063 \u103a ; # .
\u0030 > \u11136 ; # 0
\u0031 > \u11137 ; # 1
\u0032 > \u11138 ; # 2
\u0033 > \u11139 ; # 3
\u0034 > \u1113a ; # 4
\u0035 > \u1113b ; # 5
\u0036 > \u1113c ; # 6
\u0037 > \u1113d ; # 7
\u0038 > \u1113e ; # 8
\u0039 > \u1113f ; # 9
\u0040 > \u11104 ; # @
\u0041 > \u11106 ; # A
\u0042 > \u11133\u11123 ; # B
\u0043 > \u1110d ; # C
\u0044 > \u11119 ; # D
\u0045 > \u11129 ; # E
\u0046 > \u11103 ; # F
\u0047 > \u103d ; # G
\u0048 > \u11133\u11126 ; # H
\u0049 > \u1112d ; # I
\u004a > \u1110f ; # J
\u004b > \u11108 ; # K
\u004c > \u111126\u11133\u11123 ; # L
\u004d > \u11134 ; # M
\u004e > \u11115 ; #N
\u004f > \u11127\u11132 ; # O
\u0050 > \u11104 ; #P
\u0051 > \u11112 ; #Q
\u0052 > \u11133\u11122 ; # R
\u0053 > \u11105 ; # S
\u0054 > \u11117 ; #T
\u0055 > \u1112b ; # U
\u0056 > \u1110b ; # V
\u0057 > \u11131 ; #W
\u0058 > \u11114 ; # X
\u0059 > \u11110 ; #Y
\u005a > \u11133\u11120 ; # Z
\u005e > \u11133\u1111a ; # ^
\u005f > \u11134 ; # _
\u0060 > \u11101 ; # `
\u0061 > \u1112c ; #a
\u0062 > \u1111d ; # b
\u0063 > \u1110c ; # c
\u0064 > \u11118 ; # d
\u0065 > \u11128 ; # e
\u0066 > \u1111c ; # f
\u0067 > \u11109 ; # g
\u0068 > \u11126 ; # h
\u0069 > \u11127 ; # i
\u006a > \u1110e ; # j
\u006b > \u11107 ; # k
\u006c > \u11123 ; # l
\u006d > \u1111f ; # m
\u006e > \u1111a ; # n
\u006f > \u1112e ; # o
\u0070 > \u1111b ; # p
\u0071 > \u11111 ; # q
\u0072 > \u11122 ; # r
\u0073 > \u11125 ; # s
\u0074 > \u11116 ; # t
\u0075 > \u1112a ; # u
\u0076 > \u1111e ; # v
\u0077 > \u11124 ; # w
\u0078 > \u11113 ; # x
\u0079 > \u11120 ; # y
\u007a > \u11121 ; # z
\u007c > \u11133\u11103 ; # |
##### STAGE (2): POST REORDERING RULES FOR UNICODE RENDERING
::Null;
$evowel ($letter) > $1 $evowel ;
##### STAGE (3): Move evowel over virama.
::Null;
$evowel $virama ($letter) > $virama $1 $evowel ;
"""
| description = u'Chakma ASCII to Unicode conversion'
trans_lit_rules = ccp_unicode_transliterate = u'\n\n $letter = [α3-α6];\n $evowel = αC;\n $virama = α3;\n\n \x00 > ; # null\n \r > \r ; # Carriage return\n > ; # space\n ! > \x00u0021 ; # !\n ## > α2 ; # # PROBLEM\n #$ > α1 ; # $ PROBLEM\n % > % ; # %\n & > α0 ; # &\n # * > α3 α3 ; # *\n # . > α£ αΊ ; # .\n 0 > α6 ; # 0\n 1 > α7 ; # 1\n 2 > α8 ; # 2\n 3 > α9 ; # 3\n 4 > αa ; # 4\n 5 > αb ; # 5\n 6 > αc ; # 6\n 7 > αd ; # 7\n 8 > αe ; # 8\n 9 > αf ; # 9\n @ > α4 ; # @\n A > α6 ; # A\n B > α3α3 ; # B\n C > αd ; # C\n D > α9 ; # D\n E > α9 ; # E\n F > α3 ; # F\n G > α½ ; # G\n H > α3α6 ; # H\n I > αd ; # I\n J > αf ; # J\n K > α8 ; # K\n L > α26α3α3 ; # L\n M > α4 ; # M\n N > α5 ; #N\n O > α7α2 ; # O\n P > α4 ; #P\n Q > α2 ; #Q\n R > α3α2 ; # R\n S > α5 ; # S\n T > α7 ; #T\n U > αb ; # U\n V > αb ; # V\n W > α1 ; #W\n X > α4 ; # X\n Y > α0 ; #Y\n Z > α3α0 ; # Z\n ^ > α3αa ; # ^\n _ > α4 ; # _\n ` > α1 ; # `\n a > αc ; #a\n b > αd ; # b\n c > αc ; # c\n d > α8 ; # d\n e > α8 ; # e\n f > αc ; # f\n g > α9 ; # g\n h > α6 ; # h\n i > α7 ; # i\n j > αe ; # j\n k > α7 ; # k\n l > α3 ; # l\n m > αf ; # m\n n > αa ; # n\n o > αe ; # o\n p > αb ; # p\n q > α1 ; # q\n r > α2 ; # r\n s > α5 ; # s\n t > α6 ; # t\n u > αa ; # u\n v > αe ; # v\n w > α4 ; # w\n x > α3 ; # x\n y > α0 ; # y\n z > α1 ; # z\n | > α3α3 ; # |\n\n##### STAGE (2): POST REORDERING RULES FOR UNICODE RENDERING\n::Null;\n\n $evowel ($letter) > $1 $evowel ;\n\n##### STAGE (3): Move evowel over virama.\n::Null;\n\n $evowel $virama ($letter) > $virama $1 $evowel ;\n' |
# -*- coding: utf-8 -*-
class Visitor:
def visit(self, manager):
self.begin_visit(manager)
manager.visit(self)
return self.end_visit(manager)
def begin_visit(self, manager):
pass
def end_visit(self, manager):
pass
def begin_chapter(self, chapter):
pass
def end_chapter(self, chapter):
pass
def begin_section(self, section, chapter):
pass
def end_section(self, section, chapter):
pass
def visit_talk(self, talk, section, chapter):
pass
| class Visitor:
def visit(self, manager):
self.begin_visit(manager)
manager.visit(self)
return self.end_visit(manager)
def begin_visit(self, manager):
pass
def end_visit(self, manager):
pass
def begin_chapter(self, chapter):
pass
def end_chapter(self, chapter):
pass
def begin_section(self, section, chapter):
pass
def end_section(self, section, chapter):
pass
def visit_talk(self, talk, section, chapter):
pass |
# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
output=[]
stack=[(root,0)]
prev_depth=0
while(stack):
node, depth = stack.pop(0)
if depth!=prev_depth:
output.append(prev_node.val)
if node.left:
stack.append((node.left, depth+1))
if node.right:
stack.append((node.right, depth+1))
prev_depth=depth
prev_node=node
output.append(prev_node.val)
return output
| class Solution:
def right_side_view(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
output = []
stack = [(root, 0)]
prev_depth = 0
while stack:
(node, depth) = stack.pop(0)
if depth != prev_depth:
output.append(prev_node.val)
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
prev_depth = depth
prev_node = node
output.append(prev_node.val)
return output |
_base_ = ["./common_base.py", "./renderer_base.py"]
# -----------------------------------------------------------------------------
# base model cfg for self6d-v2
# -----------------------------------------------------------------------------
refiner_cfg_path = "configs/_base_/self6dpp_refiner_base.py"
MODEL = dict(
DEVICE="cuda",
WEIGHTS="",
REFINER_WEIGHTS="",
PIXEL_MEAN=[0, 0, 0], # to [0,1]
PIXEL_STD=[255.0, 255.0, 255.0],
SELF_TRAIN=False, # whether to do self-supervised training
FREEZE_BN=False, # use frozen_bn for self-supervised training
WITH_REFINER=False, # whether to use refiner
# -----------
LOAD_DETS_TRAIN=False, # NOTE: load detections for self-train
LOAD_DETS_TRAIN_WITH_POSE=False, # load detections with pose_refine as pseudo pose
PSEUDO_POSE_TYPE="pose_refine", # pose_est | pose_refine | pose_init (online inferred by teacher)
LOAD_DETS_TEST=False,
BBOX_CROP_REAL=False, # whether to use bbox_128, for cropped lm
BBOX_CROP_SYN=False,
# -----------
# Model Exponential Moving Average https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
# NOTE: momentum-based mean teacher
EMA=dict(
ENABLED=False,
INIT_CFG=dict(decay=0.999, updates=0), # epoch-based
UPDATE_FREQ=10, # update the mean teacher every n epochs
),
POSE_NET=dict(
NAME="GDRN", # used module file name
# NOTE: for self-supervised training phase, use offline labels should be more accurate
XYZ_ONLINE=False, # rendering xyz online
XYZ_BP=True, # calculate xyz from depth by backprojection
NUM_CLASSES=13,
USE_MTL=False, # uncertainty multi-task weighting, TODO: implement for self loss
INPUT_RES=256,
OUTPUT_RES=64,
## backbone
BACKBONE=dict(
FREEZE=False,
PRETRAINED="timm",
INIT_CFG=dict(
type="timm/resnet34",
pretrained=True,
in_chans=3,
features_only=True,
out_indices=(4,),
),
),
NECK=dict(
ENABLED=False,
FREEZE=False,
LR_MULT=1.0,
INIT_CFG=dict(
type="FPN",
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs=4,
),
),
## geo head: Mask, XYZ, Region
GEO_HEAD=dict(
FREEZE=False,
LR_MULT=1.0,
INIT_CFG=dict(
type="TopDownMaskXyzRegionHead",
in_dim=512, # this is num out channels of backbone conv feature
up_types=("deconv", "bilinear", "bilinear"), # stride 32 to 4
deconv_kernel_size=3,
num_conv_per_block=2,
feat_dim=256,
feat_kernel_size=3,
norm="GN",
num_gn_groups=32,
act="GELU", # relu | lrelu | silu (swish) | gelu | mish
out_kernel_size=1,
out_layer_shared=True,
),
XYZ_BIN=64, # for classification xyz, the last one is bg
XYZ_CLASS_AWARE=False,
MASK_CLASS_AWARE=False,
REGION_CLASS_AWARE=False,
MASK_THR_TEST=0.5,
# for region classification, 0 is bg, [1, num_regions]
# num_regions <= 1: no region classification
NUM_REGIONS=64,
),
## for direct regression
PNP_NET=dict(
FREEZE=False,
TRAIN_R_ONLY=False, # only train fc_r (only valid when FREEZE=False)
LR_MULT=1.0,
# ConvPnPNet | SimplePointPnPNet | PointPnPNet | ResPointPnPNet
INIT_CFG=dict(
type="ConvPnPNet",
norm="GN",
act="relu",
num_gn_groups=32,
drop_prob=0.0, # 0.25
denormalize_by_extent=True,
),
WITH_2D_COORD=False, # using 2D XY coords
COORD_2D_TYPE="abs", # rel | abs
REGION_ATTENTION=False, # region attention
MASK_ATTENTION="none", # none | concat | mul
ROT_TYPE="ego_rot6d", # {allo/ego}_{quat/rot6d/log_quat/lie_vec}
TRANS_TYPE="centroid_z", # trans | centroid_z (SITE) | centroid_z_abs
Z_TYPE="REL", # REL | ABS | LOG | NEG_LOG (only valid for centroid_z)
),
LOSS_CFG=dict(
# xyz loss ----------------------------
XYZ_LOSS_TYPE="L1", # L1 | CE_coor
XYZ_LOSS_MASK_GT="visib", # trunc | visib | obj
XYZ_LW=1.0,
# full mask loss ---------------------------
FULL_MASK_LOSS_TYPE="BCE", # L1 | BCE | CE
FULL_MASK_LW=0.0,
# mask loss ---------------------------
MASK_LOSS_TYPE="L1", # L1 | BCE | CE | RW_BCE | dice
MASK_LOSS_GT="trunc", # trunc | visib | gt
MASK_LW=1.0,
# region loss -------------------------
REGION_LOSS_TYPE="CE", # CE
REGION_LOSS_MASK_GT="visib", # trunc | visib | obj
REGION_LW=1.0,
# point matching loss -----------------
NUM_PM_POINTS=3000,
PM_LOSS_TYPE="L1", # L1 | Smooth_L1
PM_SMOOTH_L1_BETA=1.0,
PM_LOSS_SYM=False, # use symmetric PM loss
PM_NORM_BY_EXTENT=False, # 10. / extent.max(1, keepdim=True)[0]
# if False, the trans loss is in point matching loss
PM_R_ONLY=True, # only do R loss in PM
PM_DISENTANGLE_T=False, # disentangle R/T
PM_DISENTANGLE_Z=False, # disentangle R/xy/z
PM_T_USE_POINTS=True,
PM_LW=1.0,
# rot loss ----------------------------
ROT_LOSS_TYPE="angular", # angular | L2
ROT_LW=0.0,
# centroid loss -----------------------
CENTROID_LOSS_TYPE="L1",
CENTROID_LW=1.0,
# z loss ------------------------------
Z_LOSS_TYPE="L1",
Z_LW=1.0,
# trans loss --------------------------
TRANS_LOSS_TYPE="L1",
TRANS_LOSS_DISENTANGLE=True,
TRANS_LW=0.0,
# bind term loss: R^T@t ---------------
BIND_LOSS_TYPE="L1",
BIND_LW=0.0,
),
SELF_LOSS_CFG=dict(
# LAB space loss ------------------
LAB_NO_L=True,
LAB_LW=0.0,
# MS-SSIM loss --------------------
MS_SSIM_LW=0.0,
# perceptual loss -----------------
# PERCEPT_CFG=
PERCEPT_LW=0.0,
# mask loss (init, ren) -----------------------
MASK_WEIGHT_TYPE="edge_lower", # none | edge_lower | edge_higher
MASK_INIT_REN_LOSS_TYPE="RW_BCE", # L1 | RW_BCE (re-weighted BCE) | dice
MASK_INIT_REN_LW=1.0,
# depth-based geometric loss ------
GEOM_LOSS_TYPE="chamfer", # L1, chamfer
GEOM_LW=0.0, # 100
CHAMFER_CENTER_LW=0.0,
CHAMFER_DIST_THR=0.5,
# refiner-based loss --------------
REFINE_LW=0.0,
# xyz loss (init, ren)
XYZ_INIT_REN_LOSS_TYPE="L1", # L1 | CE_coor (for cls)
XYZ_INIT_REN_LW=0.0,
# xyz loss (init, pred)
XYZ_INIT_PRED_LOSS_TYPE="L1", # L1 | smoothL1
XYZ_INIT_PRED_LW=0.0,
# region loss
REGION_INIT_PRED_LW=0.0,
# losses between init and pred ==========================
# mask loss (init, pred) -----------------------
MASK_TYPE="vis", # vis | full
MASK_INIT_PRED_LOSS_TYPE="RW_BCE", # L1 | RW_BCE (re-weighted BCE)
MASK_INIT_PRED_LW=0.0,
MASK_INIT_PRED_TYPE=("vis",), # ("vis","full",)
# point matching loss using pseudo pose ---------------------------
SELF_PM_CFG=dict(
loss_type="L1",
beta=1.0,
reduction="mean",
loss_weight=0.0, # NOTE: >0 to enable this loss
norm_by_extent=False,
symmetric=True,
disentangle_t=True,
disentangle_z=True,
t_loss_use_points=True,
r_only=False,
),
),
),
# some d2 keys but not used
KEYPOINT_ON=False,
LOAD_PROPOSALS=False,
)
TRAIN = dict(PRINT_FREQ=20, DEBUG_SINGLE_IM=False)
TEST = dict(
EVAL_PERIOD=0,
VIS=False,
TEST_BBOX_TYPE="est", # gt | est
USE_PNP=False, # use pnp or direct prediction
SAVE_RESULTS_ONLY=False, # turn this on to only save the predicted results
# ransac_pnp | net_iter_pnp (learned pnp init + iter pnp) | net_ransac_pnp (net init + ransac pnp)
# net_ransac_pnp_rot (net_init + ransanc pnp --> net t + pnp R)
PNP_TYPE="ransac_pnp",
PRECISE_BN=dict(ENABLED=False, NUM_ITER=200),
)
| _base_ = ['./common_base.py', './renderer_base.py']
refiner_cfg_path = 'configs/_base_/self6dpp_refiner_base.py'
model = dict(DEVICE='cuda', WEIGHTS='', REFINER_WEIGHTS='', PIXEL_MEAN=[0, 0, 0], PIXEL_STD=[255.0, 255.0, 255.0], SELF_TRAIN=False, FREEZE_BN=False, WITH_REFINER=False, LOAD_DETS_TRAIN=False, LOAD_DETS_TRAIN_WITH_POSE=False, PSEUDO_POSE_TYPE='pose_refine', LOAD_DETS_TEST=False, BBOX_CROP_REAL=False, BBOX_CROP_SYN=False, EMA=dict(ENABLED=False, INIT_CFG=dict(decay=0.999, updates=0), UPDATE_FREQ=10), POSE_NET=dict(NAME='GDRN', XYZ_ONLINE=False, XYZ_BP=True, NUM_CLASSES=13, USE_MTL=False, INPUT_RES=256, OUTPUT_RES=64, BACKBONE=dict(FREEZE=False, PRETRAINED='timm', INIT_CFG=dict(type='timm/resnet34', pretrained=True, in_chans=3, features_only=True, out_indices=(4,))), NECK=dict(ENABLED=False, FREEZE=False, LR_MULT=1.0, INIT_CFG=dict(type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=4)), GEO_HEAD=dict(FREEZE=False, LR_MULT=1.0, INIT_CFG=dict(type='TopDownMaskXyzRegionHead', in_dim=512, up_types=('deconv', 'bilinear', 'bilinear'), deconv_kernel_size=3, num_conv_per_block=2, feat_dim=256, feat_kernel_size=3, norm='GN', num_gn_groups=32, act='GELU', out_kernel_size=1, out_layer_shared=True), XYZ_BIN=64, XYZ_CLASS_AWARE=False, MASK_CLASS_AWARE=False, REGION_CLASS_AWARE=False, MASK_THR_TEST=0.5, NUM_REGIONS=64), PNP_NET=dict(FREEZE=False, TRAIN_R_ONLY=False, LR_MULT=1.0, INIT_CFG=dict(type='ConvPnPNet', norm='GN', act='relu', num_gn_groups=32, drop_prob=0.0, denormalize_by_extent=True), WITH_2D_COORD=False, COORD_2D_TYPE='abs', REGION_ATTENTION=False, MASK_ATTENTION='none', ROT_TYPE='ego_rot6d', TRANS_TYPE='centroid_z', Z_TYPE='REL'), LOSS_CFG=dict(XYZ_LOSS_TYPE='L1', XYZ_LOSS_MASK_GT='visib', XYZ_LW=1.0, FULL_MASK_LOSS_TYPE='BCE', FULL_MASK_LW=0.0, MASK_LOSS_TYPE='L1', MASK_LOSS_GT='trunc', MASK_LW=1.0, REGION_LOSS_TYPE='CE', REGION_LOSS_MASK_GT='visib', REGION_LW=1.0, NUM_PM_POINTS=3000, PM_LOSS_TYPE='L1', PM_SMOOTH_L1_BETA=1.0, PM_LOSS_SYM=False, PM_NORM_BY_EXTENT=False, PM_R_ONLY=True, PM_DISENTANGLE_T=False, PM_DISENTANGLE_Z=False, PM_T_USE_POINTS=True, PM_LW=1.0, ROT_LOSS_TYPE='angular', ROT_LW=0.0, CENTROID_LOSS_TYPE='L1', CENTROID_LW=1.0, Z_LOSS_TYPE='L1', Z_LW=1.0, TRANS_LOSS_TYPE='L1', TRANS_LOSS_DISENTANGLE=True, TRANS_LW=0.0, BIND_LOSS_TYPE='L1', BIND_LW=0.0), SELF_LOSS_CFG=dict(LAB_NO_L=True, LAB_LW=0.0, MS_SSIM_LW=0.0, PERCEPT_LW=0.0, MASK_WEIGHT_TYPE='edge_lower', MASK_INIT_REN_LOSS_TYPE='RW_BCE', MASK_INIT_REN_LW=1.0, GEOM_LOSS_TYPE='chamfer', GEOM_LW=0.0, CHAMFER_CENTER_LW=0.0, CHAMFER_DIST_THR=0.5, REFINE_LW=0.0, XYZ_INIT_REN_LOSS_TYPE='L1', XYZ_INIT_REN_LW=0.0, XYZ_INIT_PRED_LOSS_TYPE='L1', XYZ_INIT_PRED_LW=0.0, REGION_INIT_PRED_LW=0.0, MASK_TYPE='vis', MASK_INIT_PRED_LOSS_TYPE='RW_BCE', MASK_INIT_PRED_LW=0.0, MASK_INIT_PRED_TYPE=('vis',), SELF_PM_CFG=dict(loss_type='L1', beta=1.0, reduction='mean', loss_weight=0.0, norm_by_extent=False, symmetric=True, disentangle_t=True, disentangle_z=True, t_loss_use_points=True, r_only=False))), KEYPOINT_ON=False, LOAD_PROPOSALS=False)
train = dict(PRINT_FREQ=20, DEBUG_SINGLE_IM=False)
test = dict(EVAL_PERIOD=0, VIS=False, TEST_BBOX_TYPE='est', USE_PNP=False, SAVE_RESULTS_ONLY=False, PNP_TYPE='ransac_pnp', PRECISE_BN=dict(ENABLED=False, NUM_ITER=200)) |
#
# PySNMP MIB module RADLAN-SOCKET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-SOCKET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:49:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
rnd, = mibBuilder.importSymbols("RADLAN-MIB", "rnd")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, NotificationType, TimeTicks, ObjectIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, ModuleIdentity, Gauge32, Counter64, Unsigned32, IpAddress, iso, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "NotificationType", "TimeTicks", "ObjectIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "ModuleIdentity", "Gauge32", "Counter64", "Unsigned32", "IpAddress", "iso", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
rlSocket = ModuleIdentity((1, 3, 6, 1, 4, 1, 89, 85))
rlSocket.setRevisions(('2007-01-02 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: rlSocket.setRevisionsDescriptions(('Initial revision.',))
if mibBuilder.loadTexts: rlSocket.setLastUpdated('200701020000Z')
if mibBuilder.loadTexts: rlSocket.setOrganization('Radlan - a MARVELL company. Marvell Semiconductor, Inc.')
if mibBuilder.loadTexts: rlSocket.setContactInfo('www.marvell.com')
if mibBuilder.loadTexts: rlSocket.setDescription('This private MIB module defines socket private MIBs.')
rlSocketMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 89, 85, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketMibVersion.setStatus('current')
if mibBuilder.loadTexts: rlSocketMibVersion.setDescription("MIB's version, the current version is 1.")
rlSocketTable = MibTable((1, 3, 6, 1, 4, 1, 89, 85, 2), )
if mibBuilder.loadTexts: rlSocketTable.setStatus('current')
if mibBuilder.loadTexts: rlSocketTable.setDescription('The (conceptual) table listing the sockets which are currently open in the system.')
rlSocketEntry = MibTableRow((1, 3, 6, 1, 4, 1, 89, 85, 2, 1), ).setIndexNames((0, "RADLAN-SOCKET-MIB", "rlSocketId"))
if mibBuilder.loadTexts: rlSocketEntry.setStatus('current')
if mibBuilder.loadTexts: rlSocketEntry.setDescription('An entry (conceptual row) in the SocketTable.')
rlSocketId = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketId.setStatus('current')
if mibBuilder.loadTexts: rlSocketId.setDescription('The value of the id of the socket. ')
rlSocketType = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("stream", 1), ("dgram", 2), ("raw", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketType.setStatus('current')
if mibBuilder.loadTexts: rlSocketType.setDescription('Specifies the type of the socket. ')
rlSocketState = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("connected", 1), ("notConnected", 2), ("recvClosed", 3), ("sendClosed", 4), ("closed", 5), ("peerClosed", 6), ("sendRecvClosed", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketState.setStatus('current')
if mibBuilder.loadTexts: rlSocketState.setDescription('Specifies the state in which the socket is in. ')
rlSocketBlockMode = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("blocking", 1), ("nonBlocking", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketBlockMode.setStatus('current')
if mibBuilder.loadTexts: rlSocketBlockMode.setDescription('Specifies the blocking mode of the socket. ')
rlSocketUpTime = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 5), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketUpTime.setStatus('current')
if mibBuilder.loadTexts: rlSocketUpTime.setDescription('The time elapsed since this socket was created.')
mibBuilder.exportSymbols("RADLAN-SOCKET-MIB", rlSocketUpTime=rlSocketUpTime, rlSocketTable=rlSocketTable, PYSNMP_MODULE_ID=rlSocket, rlSocketId=rlSocketId, rlSocketType=rlSocketType, rlSocket=rlSocket, rlSocketState=rlSocketState, rlSocketEntry=rlSocketEntry, rlSocketBlockMode=rlSocketBlockMode, rlSocketMibVersion=rlSocketMibVersion)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueRangeConstraint', 'SingleValueConstraint')
(rnd,) = mibBuilder.importSymbols('RADLAN-MIB', 'rnd')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(integer32, notification_type, time_ticks, object_identity, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, module_identity, gauge32, counter64, unsigned32, ip_address, iso, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'NotificationType', 'TimeTicks', 'ObjectIdentity', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'ModuleIdentity', 'Gauge32', 'Counter64', 'Unsigned32', 'IpAddress', 'iso', 'Counter32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
rl_socket = module_identity((1, 3, 6, 1, 4, 1, 89, 85))
rlSocket.setRevisions(('2007-01-02 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
rlSocket.setRevisionsDescriptions(('Initial revision.',))
if mibBuilder.loadTexts:
rlSocket.setLastUpdated('200701020000Z')
if mibBuilder.loadTexts:
rlSocket.setOrganization('Radlan - a MARVELL company. Marvell Semiconductor, Inc.')
if mibBuilder.loadTexts:
rlSocket.setContactInfo('www.marvell.com')
if mibBuilder.loadTexts:
rlSocket.setDescription('This private MIB module defines socket private MIBs.')
rl_socket_mib_version = mib_scalar((1, 3, 6, 1, 4, 1, 89, 85, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketMibVersion.setStatus('current')
if mibBuilder.loadTexts:
rlSocketMibVersion.setDescription("MIB's version, the current version is 1.")
rl_socket_table = mib_table((1, 3, 6, 1, 4, 1, 89, 85, 2))
if mibBuilder.loadTexts:
rlSocketTable.setStatus('current')
if mibBuilder.loadTexts:
rlSocketTable.setDescription('The (conceptual) table listing the sockets which are currently open in the system.')
rl_socket_entry = mib_table_row((1, 3, 6, 1, 4, 1, 89, 85, 2, 1)).setIndexNames((0, 'RADLAN-SOCKET-MIB', 'rlSocketId'))
if mibBuilder.loadTexts:
rlSocketEntry.setStatus('current')
if mibBuilder.loadTexts:
rlSocketEntry.setDescription('An entry (conceptual row) in the SocketTable.')
rl_socket_id = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketId.setStatus('current')
if mibBuilder.loadTexts:
rlSocketId.setDescription('The value of the id of the socket. ')
rl_socket_type = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('stream', 1), ('dgram', 2), ('raw', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketType.setStatus('current')
if mibBuilder.loadTexts:
rlSocketType.setDescription('Specifies the type of the socket. ')
rl_socket_state = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('connected', 1), ('notConnected', 2), ('recvClosed', 3), ('sendClosed', 4), ('closed', 5), ('peerClosed', 6), ('sendRecvClosed', 7)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketState.setStatus('current')
if mibBuilder.loadTexts:
rlSocketState.setDescription('Specifies the state in which the socket is in. ')
rl_socket_block_mode = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('blocking', 1), ('nonBlocking', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketBlockMode.setStatus('current')
if mibBuilder.loadTexts:
rlSocketBlockMode.setDescription('Specifies the blocking mode of the socket. ')
rl_socket_up_time = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 5), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketUpTime.setStatus('current')
if mibBuilder.loadTexts:
rlSocketUpTime.setDescription('The time elapsed since this socket was created.')
mibBuilder.exportSymbols('RADLAN-SOCKET-MIB', rlSocketUpTime=rlSocketUpTime, rlSocketTable=rlSocketTable, PYSNMP_MODULE_ID=rlSocket, rlSocketId=rlSocketId, rlSocketType=rlSocketType, rlSocket=rlSocket, rlSocketState=rlSocketState, rlSocketEntry=rlSocketEntry, rlSocketBlockMode=rlSocketBlockMode, rlSocketMibVersion=rlSocketMibVersion) |
RATING_DATE = 'rating_date'
ANALYSTS_MIN_MEAN_SUCCESS_RATE = 'ANALYSTS_MIN_MEAN_SUCCESS_RATE'
DAYS_SINCE_ANALYSTS_ALERT = 'DAYS_SINCE_ANALYSTS_ALERT'
QUESTIONABLE_SOURCES = []
EMISSIONS = 'emissions'
| rating_date = 'rating_date'
analysts_min_mean_success_rate = 'ANALYSTS_MIN_MEAN_SUCCESS_RATE'
days_since_analysts_alert = 'DAYS_SINCE_ANALYSTS_ALERT'
questionable_sources = []
emissions = 'emissions' |
# Source and destination file names.
test_source = "cyrillic.txt"
test_destination = "xetex-cyrillic.tex"
# Keyword parameters passed to publish_file.
writer_name = "xetex"
# Settings
settings_overrides['language_code'] = 'ru'
# use "smartquotes" transition:
settings_overrides['smart_quotes'] = True
| test_source = 'cyrillic.txt'
test_destination = 'xetex-cyrillic.tex'
writer_name = 'xetex'
settings_overrides['language_code'] = 'ru'
settings_overrides['smart_quotes'] = True |
# Leetcode 101. Symmetric Tree
#
# Link: https://leetcode.com/problems/symmetric-tree/
# Difficulty: Easy
# Complexity:
# O(N) time | where N represent the number of nodes in the tree
# O(N) space | where N represent the number of nodes in the tree
# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
def isMirror(root1, root2):
if not root1 and not root2:
return True
if root1 and root2:
if root1.val == root2.val:
return (isMirror(root1.left, root2.right) and isMirror(root1.right, root2.left))
return False
return isMirror(root, root)
| class Solution:
def is_symmetric(self, root: Optional[TreeNode]) -> bool:
def is_mirror(root1, root2):
if not root1 and (not root2):
return True
if root1 and root2:
if root1.val == root2.val:
return is_mirror(root1.left, root2.right) and is_mirror(root1.right, root2.left)
return False
return is_mirror(root, root) |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-07-09 19:40:06
# Description:
class Solution:
def isValid(self, s: str) -> bool:
n = len(s)
if n == 0:
return True
if n % 2 != 0:
return False
while '()' in s or '{}' in s or '[]' in s:
s = s.replace('{}','').replace('()','').replace('[]','')
if s == '':
return True
else:
return False
if __name__ == "__main__":
pass
| class Solution:
def is_valid(self, s: str) -> bool:
n = len(s)
if n == 0:
return True
if n % 2 != 0:
return False
while '()' in s or '{}' in s or '[]' in s:
s = s.replace('{}', '').replace('()', '').replace('[]', '')
if s == '':
return True
else:
return False
if __name__ == '__main__':
pass |
'''
Numerical validations.
All functions are boolean.
'''
def is_int(string: str) -> bool:
'''
Returns True if the string argument represents a valid integer.
'''
try:
int(string)
except ValueError:
return False
else:
return True
def is_float(string: str) -> bool:
'''
Returns True if the string parameter represents a valid float number.
'''
try:
float(string)
except ValueError:
return False
else:
return True
| """
Numerical validations.
All functions are boolean.
"""
def is_int(string: str) -> bool:
"""
Returns True if the string argument represents a valid integer.
"""
try:
int(string)
except ValueError:
return False
else:
return True
def is_float(string: str) -> bool:
"""
Returns True if the string parameter represents a valid float number.
"""
try:
float(string)
except ValueError:
return False
else:
return True |
def method1(ll: list) -> int:
inversionCount = 0
for i in range(len(ll) - 1):
for j in range(i + 1, len(ll)):
if ll[i] > ll[j]:
inversionCount = inversionCount + 1
return inversionCount
if __name__ == "__main__":
"""
from timeit import timeit
ll = [1, 9, 6, 4, 5]
print(timeit(lambda: method1(ll), number=10000)) # 0.017585102999873925
"""
| def method1(ll: list) -> int:
inversion_count = 0
for i in range(len(ll) - 1):
for j in range(i + 1, len(ll)):
if ll[i] > ll[j]:
inversion_count = inversionCount + 1
return inversionCount
if __name__ == '__main__':
'\n from timeit import timeit\n ll = [1, 9, 6, 4, 5]\n print(timeit(lambda: method1(ll), number=10000)) # 0.017585102999873925\n ' |
"""
Exceptions raised in the sublp package.
"""
__all__ = [
'SublpException',
'ProjectNotFoundError',
'ProjectsDirectoryNotFoundError',
'UnmatchedInputString'
]
class SublpException(Exception):
"""Root exception type for sublp module."""
pass
class ProjectNotFoundError(SublpException, IOError):
"""
Raised by sublp when a project file can not be found.
"""
pass
class ProjectsDirectoryNotFoundError(SublpException, IOError):
"""
Raised by sublp functions when a project directory can not be found.
"""
pass
class NoProjectFilesFoundError(SublpException):
"""
Raised by sublp functions when attempting to open a projects file
(based on a directory which should contain one or more projects files)
but no projects files were found.
"""
class UnmatchedInputString(SublpException, ValueError):
"""
Rasied when input string cannot be successfully matched against
any of the cases known by the dispatcher.
"""
pass
| """
Exceptions raised in the sublp package.
"""
__all__ = ['SublpException', 'ProjectNotFoundError', 'ProjectsDirectoryNotFoundError', 'UnmatchedInputString']
class Sublpexception(Exception):
"""Root exception type for sublp module."""
pass
class Projectnotfounderror(SublpException, IOError):
"""
Raised by sublp when a project file can not be found.
"""
pass
class Projectsdirectorynotfounderror(SublpException, IOError):
"""
Raised by sublp functions when a project directory can not be found.
"""
pass
class Noprojectfilesfounderror(SublpException):
"""
Raised by sublp functions when attempting to open a projects file
(based on a directory which should contain one or more projects files)
but no projects files were found.
"""
class Unmatchedinputstring(SublpException, ValueError):
"""
Rasied when input string cannot be successfully matched against
any of the cases known by the dispatcher.
"""
pass |
class DumbCRC32(object):
def __init__(self):
self._remainder = 0xffffffff
self._reversed_polynomial = 0xedb88320
self._final_xor = 0xffffffff
def update(self, data):
bit_count = len(data) * 8
for bit_n in range(bit_count):
bit_in = data[bit_n >> 3] & (1 << (bit_n & 7))
self._remainder ^= 1 if bit_in != 0 else 0
bit_out = (self._remainder & 1)
self._remainder >>= 1;
if bit_out != 0:
self._remainder ^= self._reversed_polynomial;
def digest(self):
return self._remainder ^ self._final_xor
def hexdigest(self):
return '%08x' % self.digest()
| class Dumbcrc32(object):
def __init__(self):
self._remainder = 4294967295
self._reversed_polynomial = 3988292384
self._final_xor = 4294967295
def update(self, data):
bit_count = len(data) * 8
for bit_n in range(bit_count):
bit_in = data[bit_n >> 3] & 1 << (bit_n & 7)
self._remainder ^= 1 if bit_in != 0 else 0
bit_out = self._remainder & 1
self._remainder >>= 1
if bit_out != 0:
self._remainder ^= self._reversed_polynomial
def digest(self):
return self._remainder ^ self._final_xor
def hexdigest(self):
return '%08x' % self.digest() |
"""
@Author Jay Lee
Credits to joeld at stackoverflow for the examples and also the link to the
blender build script for the bcolors class
link: https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
"""
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def colored_str_builder(color):
"""
Function to building colored string
:param color: The color that we want to display.
:return:
"""
def colored_str(*input_str, sep=" ", start=None, end=None):
"""
:param input_str: The input string. Simi
:param sep: The separator for each of the inputs passed
:param start: The starting index of the string. If not specified, equals to 0.
:param end: The ending index of the colored portion. If not specified, equals to
length of the string.
:return: Colored version of the string
"""
concat_str = sep.join(input_str)
if end is None and start is None:
return color + concat_str + bcolors.ENDC
elif start is None:
start = 0
elif end is None:
end = len(concat_str)
return concat_str[:start] + color + concat_str[start:end] + bcolors.ENDC
return colored_str
# Maybe this might not be a good idea when working with large strings
warning_str = colored_str_builder(bcolors.WARNING)
info_str = colored_str_builder(bcolors.OKBLUE)
fail_str = colored_str_builder(bcolors.FAIL)
ok_str = colored_str_builder(bcolors.OKGREEN)
bold_str = colored_str_builder(bcolors.BOLD)
if __name__ == "__main__":
print(warning_str("this is a warning", " this is a test"))
print(bold_str("this is a warning", start=2))
| """
@Author Jay Lee
Credits to joeld at stackoverflow for the examples and also the link to the
blender build script for the bcolors class
link: https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
"""
class Bcolors:
header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
def colored_str_builder(color):
"""
Function to building colored string
:param color: The color that we want to display.
:return:
"""
def colored_str(*input_str, sep=' ', start=None, end=None):
"""
:param input_str: The input string. Simi
:param sep: The separator for each of the inputs passed
:param start: The starting index of the string. If not specified, equals to 0.
:param end: The ending index of the colored portion. If not specified, equals to
length of the string.
:return: Colored version of the string
"""
concat_str = sep.join(input_str)
if end is None and start is None:
return color + concat_str + bcolors.ENDC
elif start is None:
start = 0
elif end is None:
end = len(concat_str)
return concat_str[:start] + color + concat_str[start:end] + bcolors.ENDC
return colored_str
warning_str = colored_str_builder(bcolors.WARNING)
info_str = colored_str_builder(bcolors.OKBLUE)
fail_str = colored_str_builder(bcolors.FAIL)
ok_str = colored_str_builder(bcolors.OKGREEN)
bold_str = colored_str_builder(bcolors.BOLD)
if __name__ == '__main__':
print(warning_str('this is a warning', ' this is a test'))
print(bold_str('this is a warning', start=2)) |
# Leetcode 36. Valid Sudoku
#
# Link: https://leetcode.com/problems/valid-sudoku/
# Difficulty: Medium
# Complexity:
# O(9^2) time
# O(9^2) space
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
width, height = len(board[0]), len(board)
rows = collections.defaultdict(set)
cols = collections.defaultdict(set)
boxs = collections.defaultdict(set)
for row in range(height):
for col in range(width):
if board[row][col] == '.':
continue
if (board[row][col] in rows[row] or
board[row][col] in cols[col] or
board[row][col] in boxs[(col // 3, row // 3)]):
return False
rows[row].add(board[row][col])
cols[col].add(board[row][col])
boxs[(col // 3, row // 3)].add(board[row][col])
return True
| class Solution:
def is_valid_sudoku(self, board: List[List[str]]) -> bool:
(width, height) = (len(board[0]), len(board))
rows = collections.defaultdict(set)
cols = collections.defaultdict(set)
boxs = collections.defaultdict(set)
for row in range(height):
for col in range(width):
if board[row][col] == '.':
continue
if board[row][col] in rows[row] or board[row][col] in cols[col] or board[row][col] in boxs[col // 3, row // 3]:
return False
rows[row].add(board[row][col])
cols[col].add(board[row][col])
boxs[col // 3, row // 3].add(board[row][col])
return True |
filename="data2.txt"
file=open(filename, "r")
rs=file.read()
fs=rs.split(",")
il=[]
for i in fs:
il.append(int(i))
i=0
while i<len(il):
moved=False
if il[i]==1:
il[il[i+3]]=il[il[i+1]]+il[il[i+2]]
moved=True
elif il[i]==2:
il[il[i+3]]=il[il[i+1]]*il[il[i+2]]
moved=True
elif il[i]==99:
break
if moved==True:
i+=4
else:
i+=1
print(il) | filename = 'data2.txt'
file = open(filename, 'r')
rs = file.read()
fs = rs.split(',')
il = []
for i in fs:
il.append(int(i))
i = 0
while i < len(il):
moved = False
if il[i] == 1:
il[il[i + 3]] = il[il[i + 1]] + il[il[i + 2]]
moved = True
elif il[i] == 2:
il[il[i + 3]] = il[il[i + 1]] * il[il[i + 2]]
moved = True
elif il[i] == 99:
break
if moved == True:
i += 4
else:
i += 1
print(il) |
class Post:
def __init__(self, index, title, subtitle, body):
self.id = index
self.title = title
self.subtitle = subtitle
self.body = body | class Post:
def __init__(self, index, title, subtitle, body):
self.id = index
self.title = title
self.subtitle = subtitle
self.body = body |
# Rwapple -
#Lesson 1: saying hello
# Chapter one of the book.
Print ('Hello, World!')
| print('Hello, World!') |
# Write your solution here
word = input("Please type in a word: ")
char = input("Please type in a character: ")
index = word.find(char)
if (char in word and index < len(word)-2):
print(word[index:index+3]) | word = input('Please type in a word: ')
char = input('Please type in a character: ')
index = word.find(char)
if char in word and index < len(word) - 2:
print(word[index:index + 3]) |
def multi_bracket_validation(str):
open_brackets = tuple('({[')
close_brackets = tuple(')}]')
map = dict(zip(open_brackets, close_brackets))
queue = []
for i in str:
if i in open_brackets:
queue.append(map[i])
elif i in close_brackets:
if not queue or i != queue.pop():
return "False"
if not queue:
return "True"
else:
return "False"
string = ""
print(string, "-", multi_bracket_validation(string)) | def multi_bracket_validation(str):
open_brackets = tuple('({[')
close_brackets = tuple(')}]')
map = dict(zip(open_brackets, close_brackets))
queue = []
for i in str:
if i in open_brackets:
queue.append(map[i])
elif i in close_brackets:
if not queue or i != queue.pop():
return 'False'
if not queue:
return 'True'
else:
return 'False'
string = ''
print(string, '-', multi_bracket_validation(string)) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_simulation_1.py
# Create Date: 2015-03-02 23:19:56
# Usage: AC_simulation_1.py
# Descripton:
class Solution:
# @return an integer
def romanToInt(self, s):
val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
ret = 0
for i in range(len(s)):
if i > 0 and val[s[i]] > val[s[i - 1]]:
ret += val[s[i]] - 2 * val[s[i - 1]]
else:
ret += val[s[i]]
return ret
| class Solution:
def roman_to_int(self, s):
val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
ret = 0
for i in range(len(s)):
if i > 0 and val[s[i]] > val[s[i - 1]]:
ret += val[s[i]] - 2 * val[s[i - 1]]
else:
ret += val[s[i]]
return ret |
"""A python implementation of the PageRank algorithm.
Requirements:
------------
None
Usage:
------------
python3 page_rank.py
NB: this code was developed and tested with python 3.7
Disclaimer: this code is intended for teaching purposes only.
"""
def page_rank(G, d=0.85, tolerance=0.01, max_iterations=50):
"""Returns the PageRank of the nodes in the graph.
:param dict G: the graph
:param float d: the damping factor
:param flat tol: tolerance to determine algorithm convergence
:param int max_iter: max number of iterations
"""
N = len(G)
pr = dict.fromkeys(G, 1.0)
print("======= Initialization")
print(pr)
outgoing_degree = {k: len(v) for k, v in G.items()}
# main loop
for it in range(max_iterations):
print("======= Iteration", it)
old_pr = dict(pr)
pr = dict.fromkeys(old_pr.keys(), 0)
for node in G:
for neighbor in G[node]:
pr[neighbor] += d * old_pr[node] / outgoing_degree[node]
pr[node] += (1 - d)
print(pr)
# check convergence
mean_diff_to_prev_pr = sum([abs(pr[n] - old_pr[n]) for n in G])/N
if mean_diff_to_prev_pr < tolerance:
return pr
raise Exception(
f'PageRank failed after max iteration = {max_iterations}'
f' (err={mean_diff_to_prev_pr} > tol = {tolerance})'
)
if __name__ == '__main__':
G = {
'A': {'B': 1, 'D': 1},
'B': {'A': 1},
'C': {'B': 1},
'D': {'B': 1},
}
print("="*20, "Start", "="*20)
pr = page_rank(G)
print("="*15, "Result", "="*15)
print(pr)
print("="*20, " End ", "="*20)
| """A python implementation of the PageRank algorithm.
Requirements:
------------
None
Usage:
------------
python3 page_rank.py
NB: this code was developed and tested with python 3.7
Disclaimer: this code is intended for teaching purposes only.
"""
def page_rank(G, d=0.85, tolerance=0.01, max_iterations=50):
"""Returns the PageRank of the nodes in the graph.
:param dict G: the graph
:param float d: the damping factor
:param flat tol: tolerance to determine algorithm convergence
:param int max_iter: max number of iterations
"""
n = len(G)
pr = dict.fromkeys(G, 1.0)
print('======= Initialization')
print(pr)
outgoing_degree = {k: len(v) for (k, v) in G.items()}
for it in range(max_iterations):
print('======= Iteration', it)
old_pr = dict(pr)
pr = dict.fromkeys(old_pr.keys(), 0)
for node in G:
for neighbor in G[node]:
pr[neighbor] += d * old_pr[node] / outgoing_degree[node]
pr[node] += 1 - d
print(pr)
mean_diff_to_prev_pr = sum([abs(pr[n] - old_pr[n]) for n in G]) / N
if mean_diff_to_prev_pr < tolerance:
return pr
raise exception(f'PageRank failed after max iteration = {max_iterations} (err={mean_diff_to_prev_pr} > tol = {tolerance})')
if __name__ == '__main__':
g = {'A': {'B': 1, 'D': 1}, 'B': {'A': 1}, 'C': {'B': 1}, 'D': {'B': 1}}
print('=' * 20, 'Start', '=' * 20)
pr = page_rank(G)
print('=' * 15, 'Result', '=' * 15)
print(pr)
print('=' * 20, ' End ', '=' * 20) |
__version__ = "0.7.1"
def version():
return __version__
| __version__ = '0.7.1'
def version():
return __version__ |
lista = [1, 3, 5, 7]
lista_animal = ['cachorro', 'gato', 'elefante']
print(lista)
print(type(lista))
print(lista_animal[1]) | lista = [1, 3, 5, 7]
lista_animal = ['cachorro', 'gato', 'elefante']
print(lista)
print(type(lista))
print(lista_animal[1]) |
class Credentials:
"""
Class that generates new instances of credentials.
"""
def __init__(self,username,password):
self.username = username
self.password = password
| class Credentials:
"""
Class that generates new instances of credentials.
"""
def __init__(self, username, password):
self.username = username
self.password = password |
# The version number is stored here here so that:
# 1) we don't load dependencies by storing it in the actual project
# 2) we can import it in setup.py for the same reason as 1)
# 3) we can import it into all other modules
__version__ = '0.0.1'
| __version__ = '0.0.1' |
class Solution:
def isConvex(self, points):
def direction(a, b, c): return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
d, n = 0, len(points)
for i in range(n):
a = direction(points[i], points[(i + 1) % n], points[(i + 2) % n])
if not d: d = a
elif a * d < 0: return False
return True | class Solution:
def is_convex(self, points):
def direction(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
(d, n) = (0, len(points))
for i in range(n):
a = direction(points[i], points[(i + 1) % n], points[(i + 2) % n])
if not d:
d = a
elif a * d < 0:
return False
return True |
"""
[2017-05-29] Challenge #317 [Easy] Collatz Tag System
https://www.reddit.com/r/dailyprogrammer/comments/6e08v6/20170529_challenge_317_easy_collatz_tag_system/
# Description
Implement the [Collatz Conjecture tag system described
here](https://en.wikipedia.org/wiki/Tag_system#Example:_Computation_of_Collatz_sequences)
# Input Description
A string of n *a*'s
# Output Description
Print the string at each step. The last line should be "*a*" (assuming the Collatz conjecture)
# Challenge Input
aaa
aaaaa
# Challenge Output
aaa
abc
cbc
caaa
aaaaa
aaabc
abcbc
cbcbc
cbcaaa
caaaaaa
aaaaaaaa
aaaaaabc
aaaabcbc
aabcbcbc
bcbcbcbc
bcbcbca
bcbcaa
bcaaa
aaaa
aabc
bcbc
bca
aa
bc
a
aaaaaaa
aaaaabc
aaabcbc
abcbcbc
cbcbcbc
cbcbcaaa
cbcaaaaaa
caaaaaaaaa
aaaaaaaaaaa
aaaaaaaaabc
aaaaaaabcbc
aaaaabcbcbc
aaabcbcbcbc
abcbcbcbcbc
cbcbcbcbcbc
cbcbcbcbcaaa
cbcbcbcaaaaaa
cbcbcaaaaaaaaa
cbcaaaaaaaaaaaa
caaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaabc
aaaaaaaaaaaaabcbc
aaaaaaaaaaabcbcbc
aaaaaaaaabcbcbcbc
aaaaaaabcbcbcbcbc
aaaaabcbcbcbcbcbc
aaabcbcbcbcbcbcbc
abcbcbcbcbcbcbcbc
cbcbcbcbcbcbcbcbc
cbcbcbcbcbcbcbcaaa
cbcbcbcbcbcbcaaaaaa
cbcbcbcbcbcaaaaaaaaa
cbcbcbcbcaaaaaaaaaaaa
cbcbcbcaaaaaaaaaaaaaaa
cbcbcaaaaaaaaaaaaaaaaaa
cbcaaaaaaaaaaaaaaaaaaaaa
caaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaabc
aaaaaaaaaaaaaaaaaaaaaabcbc
aaaaaaaaaaaaaaaaaaaabcbcbc
aaaaaaaaaaaaaaaaaabcbcbcbc
aaaaaaaaaaaaaaaabcbcbcbcbc
aaaaaaaaaaaaaabcbcbcbcbcbc
aaaaaaaaaaaabcbcbcbcbcbcbc
aaaaaaaaaabcbcbcbcbcbcbcbc
aaaaaaaabcbcbcbcbcbcbcbcbc
aaaaaabcbcbcbcbcbcbcbcbcbc
aaaabcbcbcbcbcbcbcbcbcbcbc
aabcbcbcbcbcbcbcbcbcbcbcbc
bcbcbcbcbcbcbcbcbcbcbcbcbc
bcbcbcbcbcbcbcbcbcbcbcbca
bcbcbcbcbcbcbcbcbcbcbcaa
bcbcbcbcbcbcbcbcbcbcaaa
bcbcbcbcbcbcbcbcbcaaaa
bcbcbcbcbcbcbcbcaaaaa
bcbcbcbcbcbcbcaaaaaa
bcbcbcbcbcbcaaaaaaa
bcbcbcbcbcaaaaaaaa
bcbcbcbcaaaaaaaaa
bcbcbcaaaaaaaaaa
bcbcaaaaaaaaaaa
bcaaaaaaaaaaaa
aaaaaaaaaaaaa
aaaaaaaaaaabc
aaaaaaaaabcbc
aaaaaaabcbcbc
aaaaabcbcbcbc
aaabcbcbcbcbc
abcbcbcbcbcbc
cbcbcbcbcbcbc
cbcbcbcbcbcaaa
cbcbcbcbcaaaaaa
cbcbcbcaaaaaaaaa
cbcbcaaaaaaaaaaaa
cbcaaaaaaaaaaaaaaa
caaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaabc
aaaaaaaaaaaaaaaabcbc
aaaaaaaaaaaaaabcbcbc
aaaaaaaaaaaabcbcbcbc
aaaaaaaaaabcbcbcbcbc
aaaaaaaabcbcbcbcbcbc
aaaaaabcbcbcbcbcbcbc
aaaabcbcbcbcbcbcbcbc
aabcbcbcbcbcbcbcbcbc
bcbcbcbcbcbcbcbcbcbc
bcbcbcbcbcbcbcbcbca
bcbcbcbcbcbcbcbcaa
bcbcbcbcbcbcbcaaa
bcbcbcbcbcbcaaaa
bcbcbcbcbcaaaaa
bcbcbcbcaaaaaa
bcbcbcaaaaaaa
bcbcaaaaaaaa
bcaaaaaaaaa
aaaaaaaaaa
aaaaaaaabc
aaaaaabcbc
aaaabcbcbc
aabcbcbcbc
bcbcbcbcbc
bcbcbcbca
bcbcbcaa
bcbcaaa
bcaaaa
aaaaa
aaabc
abcbc
cbcbc
cbcaaa
caaaaaa
aaaaaaaa
aaaaaabc
aaaabcbc
aabcbcbc
bcbcbcbc
bcbcbca
bcbcaa
bcaaa
aaaa
aabc
bcbc
bca
aa
bc
a
# Notes/Hints
The [Collatz Conjecture](https://en.wikipedia.org/wiki/3x_%2B_1_problem)
If you're not familiar with tag systems, you can read the [Wikipedia article on them
here](https://en.wikipedia.org/wiki/Tag_system)
# Bonus
Implement the same tag system as a cyclic tag system using the [schema described
here](https://en.wikipedia.org/wiki/Tag_system#Emulation_of_tag_systems_by_cyclic_tag_systems)
# Bonus Input
100100100
# Bonus Output
00100100010001
0100100010001
100100010001
00100010001
0100010001
100010001
00010001010001
0010001010001
010001010001
10001010001
0001010001
001010001
01010001
1010001
010001100100100
10001100100100
0001100100100
001100100100
01100100100
1100100100
100100100100100100
00100100100100100
0100100100100100
100100100100100
00100100100100010001
0100100100100010001
100100100100010001
00100100100010001
0100100100010001
100100100010001
00100100010001010001
0100100010001010001
100100010001010001
00100010001010001
0100010001010001
100010001010001
00010001010001010001
0010001010001010001
010001010001010001
10001010001010001
0001010001010001
001010001010001
01010001010001
1010001010001
010001010001100100100
10001010001100100100
0001010001100100100
001010001100100100
01010001100100100
1010001100100100
010001100100100100100100
10001100100100100100100
0001100100100100100100
001100100100100100100
01100100100100100100
1100100100100100100
100100100100100100100100100
00100100100100100100100100
0100100100100100100100100
100100100100100100100100
00100100100100100100100010001
0100100100100100100100010001
100100100100100100100010001
00100100100100100100010001
0100100100100100100010001
100100100100100100010001
00100100100100100010001010001
0100100100100100010001010001
100100100100100010001010001
00100100100100010001010001
0100100100100010001010001
100100100100010001010001
00100100100010001010001010001
0100100100010001010001010001
100100100010001010001010001
00100100010001010001010001
0100100010001010001010001
100100010001010001010001
00100010001010001010001010001
0100010001010001010001010001
100010001010001010001010001
00010001010001010001010001
0010001010001010001010001
010001010001010001010001
10001010001010001010001
0001010001010001010001100
001010001010001010001100
01010001010001010001100
1010001010001010001100
010001010001010001100
10001010001010001100
0001010001010001100100
001010001010001100100
01010001010001100100
1010001010001100100
010001010001100100
10001010001100100
0001010001100100100
001010001100100100
01010001100100100
1010001100100100
010001100100100
10001100100100
0001100100100100
001100100100100
01100100100100
1100100100100
100100100100
00100100100010001
0100100100010001
100100100010001
00100100010001
0100100010001
100100010001
00100010001010001
0100010001010001
100010001010001
00010001010001
0010001010001
010001010001
10001010001
0001010001100
001010001100
01010001100
1010001100
010001100
10001100
0001100100
001100100
01100100
1100100
100100
00100010001
0100010001
100010001
00010001
0010001
010001
10001
0001100
001100
01100
1100
100
# Credit
This challenge was proposed by /u/thebutterflydefect, many thanks. If you have a challenge idea, please share it in
/r/dailyprogrammer_ideas and there's a good chance we'll use it.
"""
def main():
pass
if __name__ == "__main__":
main()
| """
[2017-05-29] Challenge #317 [Easy] Collatz Tag System
https://www.reddit.com/r/dailyprogrammer/comments/6e08v6/20170529_challenge_317_easy_collatz_tag_system/
# Description
Implement the [Collatz Conjecture tag system described
here](https://en.wikipedia.org/wiki/Tag_system#Example:_Computation_of_Collatz_sequences)
# Input Description
A string of n *a*'s
# Output Description
Print the string at each step. The last line should be "*a*" (assuming the Collatz conjecture)
# Challenge Input
aaa
aaaaa
# Challenge Output
aaa
abc
cbc
caaa
aaaaa
aaabc
abcbc
cbcbc
cbcaaa
caaaaaa
aaaaaaaa
aaaaaabc
aaaabcbc
aabcbcbc
bcbcbcbc
bcbcbca
bcbcaa
bcaaa
aaaa
aabc
bcbc
bca
aa
bc
a
aaaaaaa
aaaaabc
aaabcbc
abcbcbc
cbcbcbc
cbcbcaaa
cbcaaaaaa
caaaaaaaaa
aaaaaaaaaaa
aaaaaaaaabc
aaaaaaabcbc
aaaaabcbcbc
aaabcbcbcbc
abcbcbcbcbc
cbcbcbcbcbc
cbcbcbcbcaaa
cbcbcbcaaaaaa
cbcbcaaaaaaaaa
cbcaaaaaaaaaaaa
caaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaabc
aaaaaaaaaaaaabcbc
aaaaaaaaaaabcbcbc
aaaaaaaaabcbcbcbc
aaaaaaabcbcbcbcbc
aaaaabcbcbcbcbcbc
aaabcbcbcbcbcbcbc
abcbcbcbcbcbcbcbc
cbcbcbcbcbcbcbcbc
cbcbcbcbcbcbcbcaaa
cbcbcbcbcbcbcaaaaaa
cbcbcbcbcbcaaaaaaaaa
cbcbcbcbcaaaaaaaaaaaa
cbcbcbcaaaaaaaaaaaaaaa
cbcbcaaaaaaaaaaaaaaaaaa
cbcaaaaaaaaaaaaaaaaaaaaa
caaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaabc
aaaaaaaaaaaaaaaaaaaaaabcbc
aaaaaaaaaaaaaaaaaaaabcbcbc
aaaaaaaaaaaaaaaaaabcbcbcbc
aaaaaaaaaaaaaaaabcbcbcbcbc
aaaaaaaaaaaaaabcbcbcbcbcbc
aaaaaaaaaaaabcbcbcbcbcbcbc
aaaaaaaaaabcbcbcbcbcbcbcbc
aaaaaaaabcbcbcbcbcbcbcbcbc
aaaaaabcbcbcbcbcbcbcbcbcbc
aaaabcbcbcbcbcbcbcbcbcbcbc
aabcbcbcbcbcbcbcbcbcbcbcbc
bcbcbcbcbcbcbcbcbcbcbcbcbc
bcbcbcbcbcbcbcbcbcbcbcbca
bcbcbcbcbcbcbcbcbcbcbcaa
bcbcbcbcbcbcbcbcbcbcaaa
bcbcbcbcbcbcbcbcbcaaaa
bcbcbcbcbcbcbcbcaaaaa
bcbcbcbcbcbcbcaaaaaa
bcbcbcbcbcbcaaaaaaa
bcbcbcbcbcaaaaaaaa
bcbcbcbcaaaaaaaaa
bcbcbcaaaaaaaaaa
bcbcaaaaaaaaaaa
bcaaaaaaaaaaaa
aaaaaaaaaaaaa
aaaaaaaaaaabc
aaaaaaaaabcbc
aaaaaaabcbcbc
aaaaabcbcbcbc
aaabcbcbcbcbc
abcbcbcbcbcbc
cbcbcbcbcbcbc
cbcbcbcbcbcaaa
cbcbcbcbcaaaaaa
cbcbcbcaaaaaaaaa
cbcbcaaaaaaaaaaaa
cbcaaaaaaaaaaaaaaa
caaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaabc
aaaaaaaaaaaaaaaabcbc
aaaaaaaaaaaaaabcbcbc
aaaaaaaaaaaabcbcbcbc
aaaaaaaaaabcbcbcbcbc
aaaaaaaabcbcbcbcbcbc
aaaaaabcbcbcbcbcbcbc
aaaabcbcbcbcbcbcbcbc
aabcbcbcbcbcbcbcbcbc
bcbcbcbcbcbcbcbcbcbc
bcbcbcbcbcbcbcbcbca
bcbcbcbcbcbcbcbcaa
bcbcbcbcbcbcbcaaa
bcbcbcbcbcbcaaaa
bcbcbcbcbcaaaaa
bcbcbcbcaaaaaa
bcbcbcaaaaaaa
bcbcaaaaaaaa
bcaaaaaaaaa
aaaaaaaaaa
aaaaaaaabc
aaaaaabcbc
aaaabcbcbc
aabcbcbcbc
bcbcbcbcbc
bcbcbcbca
bcbcbcaa
bcbcaaa
bcaaaa
aaaaa
aaabc
abcbc
cbcbc
cbcaaa
caaaaaa
aaaaaaaa
aaaaaabc
aaaabcbc
aabcbcbc
bcbcbcbc
bcbcbca
bcbcaa
bcaaa
aaaa
aabc
bcbc
bca
aa
bc
a
# Notes/Hints
The [Collatz Conjecture](https://en.wikipedia.org/wiki/3x_%2B_1_problem)
If you're not familiar with tag systems, you can read the [Wikipedia article on them
here](https://en.wikipedia.org/wiki/Tag_system)
# Bonus
Implement the same tag system as a cyclic tag system using the [schema described
here](https://en.wikipedia.org/wiki/Tag_system#Emulation_of_tag_systems_by_cyclic_tag_systems)
# Bonus Input
100100100
# Bonus Output
00100100010001
0100100010001
100100010001
00100010001
0100010001
100010001
00010001010001
0010001010001
010001010001
10001010001
0001010001
001010001
01010001
1010001
010001100100100
10001100100100
0001100100100
001100100100
01100100100
1100100100
100100100100100100
00100100100100100
0100100100100100
100100100100100
00100100100100010001
0100100100100010001
100100100100010001
00100100100010001
0100100100010001
100100100010001
00100100010001010001
0100100010001010001
100100010001010001
00100010001010001
0100010001010001
100010001010001
00010001010001010001
0010001010001010001
010001010001010001
10001010001010001
0001010001010001
001010001010001
01010001010001
1010001010001
010001010001100100100
10001010001100100100
0001010001100100100
001010001100100100
01010001100100100
1010001100100100
010001100100100100100100
10001100100100100100100
0001100100100100100100
001100100100100100100
01100100100100100100
1100100100100100100
100100100100100100100100100
00100100100100100100100100
0100100100100100100100100
100100100100100100100100
00100100100100100100100010001
0100100100100100100100010001
100100100100100100100010001
00100100100100100100010001
0100100100100100100010001
100100100100100100010001
00100100100100100010001010001
0100100100100100010001010001
100100100100100010001010001
00100100100100010001010001
0100100100100010001010001
100100100100010001010001
00100100100010001010001010001
0100100100010001010001010001
100100100010001010001010001
00100100010001010001010001
0100100010001010001010001
100100010001010001010001
00100010001010001010001010001
0100010001010001010001010001
100010001010001010001010001
00010001010001010001010001
0010001010001010001010001
010001010001010001010001
10001010001010001010001
0001010001010001010001100
001010001010001010001100
01010001010001010001100
1010001010001010001100
010001010001010001100
10001010001010001100
0001010001010001100100
001010001010001100100
01010001010001100100
1010001010001100100
010001010001100100
10001010001100100
0001010001100100100
001010001100100100
01010001100100100
1010001100100100
010001100100100
10001100100100
0001100100100100
001100100100100
01100100100100
1100100100100
100100100100
00100100100010001
0100100100010001
100100100010001
00100100010001
0100100010001
100100010001
00100010001010001
0100010001010001
100010001010001
00010001010001
0010001010001
010001010001
10001010001
0001010001100
001010001100
01010001100
1010001100
010001100
10001100
0001100100
001100100
01100100
1100100
100100
00100010001
0100010001
100010001
00010001
0010001
010001
10001
0001100
001100
01100
1100
100
# Credit
This challenge was proposed by /u/thebutterflydefect, many thanks. If you have a challenge idea, please share it in
/r/dailyprogrammer_ideas and there's a good chance we'll use it.
"""
def main():
pass
if __name__ == '__main__':
main() |
#! -*- coding: utf-8 -*-
SIGBITS = 5
RSHIFT = 8 - SIGBITS
MAX_ITERATION = 1000
FRACT_BY_POPULATIONS = 0.75
| sigbits = 5
rshift = 8 - SIGBITS
max_iteration = 1000
fract_by_populations = 0.75 |
def in_radius(signal, lag=6):
n = len(signal) - 6
r = []
for m in range(n):
a = sqrt((signal[m] - signal[m + 2]) ** 2 + (signal[m + 1] - signal[m + 3]) ** 2)
b = sqrt((signal[m] - signal[m + 4]) ** 2 + (signal[m + 1] - signal[m + 5]) ** 2)
c = sqrt((signal[m + 2] - signal[m + 4]) ** 2 + (signal[m + 3] - signal[m + 5]) ** 2)
if a + b + c == 0:
r = 0
else:
s = (a + b + c) / 2
area = (s * (s - a) * (s - b) * (s - c))
area = sqrt(area)
r.append((2 * area) / (a + b + c))
return r[::lag]
| def in_radius(signal, lag=6):
n = len(signal) - 6
r = []
for m in range(n):
a = sqrt((signal[m] - signal[m + 2]) ** 2 + (signal[m + 1] - signal[m + 3]) ** 2)
b = sqrt((signal[m] - signal[m + 4]) ** 2 + (signal[m + 1] - signal[m + 5]) ** 2)
c = sqrt((signal[m + 2] - signal[m + 4]) ** 2 + (signal[m + 3] - signal[m + 5]) ** 2)
if a + b + c == 0:
r = 0
else:
s = (a + b + c) / 2
area = s * (s - a) * (s - b) * (s - c)
area = sqrt(area)
r.append(2 * area / (a + b + c))
return r[::lag] |
# Determine the sign of number
n = float(input("Enter a number: "))
if n > 0:
print("Positive.")
elif n < 0:
print("Negative.")
else:
print("STRAIGHT AWAY ZERROOO.")
| n = float(input('Enter a number: '))
if n > 0:
print('Positive.')
elif n < 0:
print('Negative.')
else:
print('STRAIGHT AWAY ZERROOO.') |
def simpleFun(dim, device):
"""
Args:
dim: integer
device: "cpu" or "cuda"
Returns:
Nothing.
"""
x = torch.rand(dim, dim).to(device)
y = torch.rand_like(x).to(device)
z = 2*torch.ones(dim, dim).to(device)
x = x * y
x = x @ z
del x
del y
del z
## TODO: Implement the function above and uncomment the following lines to test your code
timeFun(f=simpleFun, dim=dim, iterations=iterations)
timeFun(f=simpleFun, dim=dim, iterations=iterations, device=DEVICE) | def simple_fun(dim, device):
"""
Args:
dim: integer
device: "cpu" or "cuda"
Returns:
Nothing.
"""
x = torch.rand(dim, dim).to(device)
y = torch.rand_like(x).to(device)
z = 2 * torch.ones(dim, dim).to(device)
x = x * y
x = x @ z
del x
del y
del z
time_fun(f=simpleFun, dim=dim, iterations=iterations)
time_fun(f=simpleFun, dim=dim, iterations=iterations, device=DEVICE) |
# https://codeforces.com/problemset/problem/520/A
n = int(input())
s = sorted(set(list(input().upper())))
flag = 0
if len(s) == 26:
for i in range(len(s)):
if chr(65 + i) != s[i]:
flag = 1
break
print("YES") if flag == 0 else print("NO")
else:
print("NO") | n = int(input())
s = sorted(set(list(input().upper())))
flag = 0
if len(s) == 26:
for i in range(len(s)):
if chr(65 + i) != s[i]:
flag = 1
break
print('YES') if flag == 0 else print('NO')
else:
print('NO') |
{
'targets':[
{
'target_name': 'native_module',
'sources': [
'src/native_module.cc',
'src/native.cc'
],
'conditions': [
['OS=="linux"', {
'cflags_cc': [ '-std=c++0x' ]
}]
]
}
]
}
| {'targets': [{'target_name': 'native_module', 'sources': ['src/native_module.cc', 'src/native.cc'], 'conditions': [['OS=="linux"', {'cflags_cc': ['-std=c++0x']}]]}]} |
level = 3
name = 'Pacet'
capital = 'Cikitu'
area = 91.94
| level = 3
name = 'Pacet'
capital = 'Cikitu'
area = 91.94 |
# Function to calculate the mask of a number.
def split(n):
b = []
# Iterating the number by digits.
while n > 0:
# If the digit is lucky digit it is appended to the list.
if n % 10 == 4 or n % 10 == 7:
b.append(n % 10)
n //= 10
# Return the mask.
return b
# Input the two input values.
x, y = [int(x) for x in input().split()]
# Calculate the mask of 'y'.
a = split(y)
# Iterate for value greater than 'x'.
for i in range(x + 1, 1000000):
# If mask equals output the integer and break the loop.
if split(i) == a:
print(i)
break | def split(n):
b = []
while n > 0:
if n % 10 == 4 or n % 10 == 7:
b.append(n % 10)
n //= 10
return b
(x, y) = [int(x) for x in input().split()]
a = split(y)
for i in range(x + 1, 1000000):
if split(i) == a:
print(i)
break |
class Hunk(object):
""" Parsed hunk data container (hunk starts with @@ -R +R @@) """
def __init__(self):
self.startsrc = None #: line count starts with 1
self.linessrc = None
self.starttgt = None
self.linestgt = None
self.invalid = False
self.desc = ''
self.text = []
| class Hunk(object):
""" Parsed hunk data container (hunk starts with @@ -R +R @@) """
def __init__(self):
self.startsrc = None
self.linessrc = None
self.starttgt = None
self.linestgt = None
self.invalid = False
self.desc = ''
self.text = [] |
class Player:
""" Behavior to have a paddle controlled by the player """
def __init__(self, upKey, downKey):
""" Initialize the Player """
self.upKey = upKey
self.downKey = downKey
def start(self):
""" Connect the player input """
self.inputHandler.register(self.upKey, self.movement["Up"].startOrStop(startWhen=lambda event: event.pressed))
self.inputHandler.register(self.downKey, self.movement["Down"].startOrStop(startWhen=lambda event: event.pressed))
@property
def inputHandler(self):
""" Return the input handler """
return self.entity.scene.app.inputHandler
@property
def movement(self):
""" Return the connected movement """
return self.entity.movement | class Player:
""" Behavior to have a paddle controlled by the player """
def __init__(self, upKey, downKey):
""" Initialize the Player """
self.upKey = upKey
self.downKey = downKey
def start(self):
""" Connect the player input """
self.inputHandler.register(self.upKey, self.movement['Up'].startOrStop(startWhen=lambda event: event.pressed))
self.inputHandler.register(self.downKey, self.movement['Down'].startOrStop(startWhen=lambda event: event.pressed))
@property
def input_handler(self):
""" Return the input handler """
return self.entity.scene.app.inputHandler
@property
def movement(self):
""" Return the connected movement """
return self.entity.movement |
## Model parameters
model_hidden_size = 256
model_embedding_size = 256
model_num_layers = 3
## Training parameters
learning_rate_init = 1e-4
#speakers_per_batch = 64
speakers_per_batch = 128
utterances_per_speaker = 10
| model_hidden_size = 256
model_embedding_size = 256
model_num_layers = 3
learning_rate_init = 0.0001
speakers_per_batch = 128
utterances_per_speaker = 10 |
fyrst_number = int(input())
second_number = int(input())
third_number = int(input())
if fyrst_number > second_number and fyrst_number > third_number:
print(fyrst_number)
elif second_number > fyrst_number and second_number > third_number:
print(second_number)
else:
print(third_number)
| fyrst_number = int(input())
second_number = int(input())
third_number = int(input())
if fyrst_number > second_number and fyrst_number > third_number:
print(fyrst_number)
elif second_number > fyrst_number and second_number > third_number:
print(second_number)
else:
print(third_number) |
class OGCSensor:
""" This class represents the SENSOR entity of the OCG Sensor Things model.
For more info: http://developers.sensorup.com/docs/#sensors_post
"""
def __init__(self, name: str, description: str, metadata, encoding: str = "application/pdf"):
self._id = None # the id is assigned by the OGC Server
self._name = name
self._description = description
self._encoding = encoding
self._metadata = metadata
def set_id(self, sensor_id: int):
self._id = sensor_id
def get_id(self) -> int:
return self._id
def get_name(self) -> str:
return self._name
def get_rest_payload(self) -> dict:
return {
"name": self._name,
"description": self._description,
"encodingType": self._encoding,
"metadata": self._metadata
}
def __str__(self):
to_return = self.get_rest_payload()
if self._id:
to_return["@iot.id"] = self._id
return str(to_return)
| class Ogcsensor:
""" This class represents the SENSOR entity of the OCG Sensor Things model.
For more info: http://developers.sensorup.com/docs/#sensors_post
"""
def __init__(self, name: str, description: str, metadata, encoding: str='application/pdf'):
self._id = None
self._name = name
self._description = description
self._encoding = encoding
self._metadata = metadata
def set_id(self, sensor_id: int):
self._id = sensor_id
def get_id(self) -> int:
return self._id
def get_name(self) -> str:
return self._name
def get_rest_payload(self) -> dict:
return {'name': self._name, 'description': self._description, 'encodingType': self._encoding, 'metadata': self._metadata}
def __str__(self):
to_return = self.get_rest_payload()
if self._id:
to_return['@iot.id'] = self._id
return str(to_return) |
s1 = input().upper()
s2 = input().upper()
def sol(s1, s2):
i = 0
while i < len(s1):
if ord(s1[i]) < ord(s2[i]):
return -1
elif ord(s1[i]) > ord(s2[i]):
return 1
i += 1
return 0
print(sol(s1, s2)) | s1 = input().upper()
s2 = input().upper()
def sol(s1, s2):
i = 0
while i < len(s1):
if ord(s1[i]) < ord(s2[i]):
return -1
elif ord(s1[i]) > ord(s2[i]):
return 1
i += 1
return 0
print(sol(s1, s2)) |
lexy_copts = select({
"@bazel_tools//src/conditions:windows": ["/std:c++latest"],
"@bazel_tools//src/conditions:windows_msvc": ["/std:c++latest"],
"//conditions:default": ["-std=c++20"],
})
| lexy_copts = select({'@bazel_tools//src/conditions:windows': ['/std:c++latest'], '@bazel_tools//src/conditions:windows_msvc': ['/std:c++latest'], '//conditions:default': ['-std=c++20']}) |
class URLInfo:
def __init__(self, domain, subject):
self.domain = domain
self.subject = subject
def __str__(self):
result = ""
result += f"domain: {self.domain}\n"
result += f"subject: {self.subject}\n"
return result
| class Urlinfo:
def __init__(self, domain, subject):
self.domain = domain
self.subject = subject
def __str__(self):
result = ''
result += f'domain: {self.domain}\n'
result += f'subject: {self.subject}\n'
return result |
def insertion_sorting(input_array):
for i in range(len(input_array)):
value, position = input_array[i], i
while position > 0 and input_array[position-1] > value:
input_array[position] = input_array[position - 1]
position = position - 1
input_array[position] = value
return input_array
if __name__ == '__main__':
user_input = int(input("Enter number of elements in your array: "))
input_array = list(map(int, input("\nEnter the array elements separated by spaces: ").strip().split()))[:user_input]
sorted_array = insertion_sorting(input_array)
print('Here is your sorted array: ' + ','.join(str(number) for number in sorted_array))
| def insertion_sorting(input_array):
for i in range(len(input_array)):
(value, position) = (input_array[i], i)
while position > 0 and input_array[position - 1] > value:
input_array[position] = input_array[position - 1]
position = position - 1
input_array[position] = value
return input_array
if __name__ == '__main__':
user_input = int(input('Enter number of elements in your array: '))
input_array = list(map(int, input('\nEnter the array elements separated by spaces: ').strip().split()))[:user_input]
sorted_array = insertion_sorting(input_array)
print('Here is your sorted array: ' + ','.join((str(number) for number in sorted_array))) |
A=[3,5,7]
B=[1,8]
C=[]
counter=0
while len(A)>0 and len(B)>0:
if A[0] <= B[0]:
C[counter]=A[0]
A=A[1:]
counter=counter+1
else:
C[counter]=B[0]
B=B[1:]
counter=counter+1
print(C)
| a = [3, 5, 7]
b = [1, 8]
c = []
counter = 0
while len(A) > 0 and len(B) > 0:
if A[0] <= B[0]:
C[counter] = A[0]
a = A[1:]
counter = counter + 1
else:
C[counter] = B[0]
b = B[1:]
counter = counter + 1
print(C) |
"""Source module to create ``Assumption`` space from.
This module is a source module to create ``Assumption`` space and its
sub spaces from.
The formulas of the cells in the ``Assumption`` space are created from the
functions defined in this module.
The ``Assumption`` space is the base space of the assumption spaces
for individual policies, which are derived from and belong to
the ``Assumption`` space as its dynamic child spaces.
The assumption spaces for individual policies are parametrized by ``PolicyID``.
For example, to get the assumption space of the policy whose ID is 171::
>> asmp = model.Assumption(171)
The cells in an assumption space for each individual policy retrieve
input data, calculate and hold values of assumptions specific to that policy,
so various spaces in :mod:`Input<simplelife.build_input>` must be accessible
from the ``Assumption`` space.
.. rubric:: Project Templates
This module is included in the following project templates.
* :mod:`simplelife`
* :mod:`nestedlife`
.. rubric:: Referred Spaces
The ``Assumption`` space and its sub spaces depend of the following spaces.
See references sections below for aliases to those spaces and their members
that are referenced in the ``Assumption`` spaces.
* :mod:`Policy<simplelife.policy>` its sub spaces
* ``LifeTable`` in :mod:`Input<simplelife.build_input>`
* ``MortalityTables`` in :mod:`Input<simplelife.build_input>`
* ``Assumption`` in :mod:`Input<simplelife.build_input>`
.. rubric:: Space Parameters
Attributes:
PolicyID: Policy ID
.. rubric:: References in Base
Attributes:
asmp_tbl: ``AssumptionTables`` space in :mod:`Input<simplelife.build_input>` space
asmp: ``Assumption`` space in :mod:`Input<simplelife.build_input>` space
MortalityTables: ``MortalityTables`` space in :mod:`Input<simplelife.build_input>` space
.. rubric:: References in Sub
Attributes:
pol: Alias to :mod:`Policy[PolicyID]<simplelife.policy>`
prod: Alias to :attr:`Policy[PolicyID].Product<simplelife.policy.Product>`
polt: Alias to :attr:`Policy[PolicyID].PolicyType<simplelife.policy.PolicyType>`
gen: Alias to :attr:`Policy[PolicyID].Gen<simplelife.policy.Gen>`
"""
policy_attrs = []
# #--- Mortality ---
def MortTable():
"""Mortality Table"""
result = asmp.BaseMort.match(prod, polt, gen).value
if result is not None:
return MortalityTables(result).MortalityTable
else:
raise ValueError('MortTable not found')
def LastAge():
"""Age at which mortality becomes 1"""
x = 0
while True:
if BaseMortRate(x) == 1:
return x
x += 1
def BaseMortRate(x):
"""Bae mortality rate"""
return MortTable()(pol.Sex, x)
def MortFactor(y):
"""Mortality factor"""
table = asmp.MortFactor.match(prod, polt, gen).value
if table is None:
raise ValueError('MortFactor not found')
result = asmp_tbl.cells[table](y)
if result is None:
return MortFactor(y-1)
else:
return result
# --- Surrender Rates ---
def SurrRate(y):
"""Surrender Rate"""
table = asmp.Surrender.match(prod, polt, gen).value
if table is None:
raise ValueError('Surrender not found')
result = asmp_tbl.cells[table](y)
if result is None:
return SurrRate(y-1)
else:
return result
# --- Commissions ---
def CommInitPrem():
"""Initial commission per premium"""
result = asmp.CommInitPrem.match(prod, polt, gen).value
if result is not None:
return result
else:
raise ValueError('CommInitPrem not found')
def CommRenPrem():
"""Renewal commission per premium"""
result = asmp.CommRenPrem.match(prod, polt, gen).value
if result is not None:
return result
else:
raise ValueError('CommRenPrem not found')
def CommRenTerm():
"""Renewal commission term"""
result = asmp.CommRenTerm.match(prod, polt, gen).value
if result is not None:
return result
else:
raise ValueError('CommRenTerm not found')
# # --- Expenses ---
def ExpsAcqSA():
"""Acquisition expense per sum assured"""
return asmp.ExpsAcqSA.match(prod, polt, gen).value
def ExpsAcqAnnPrem():
"""Acquisition expense per annualized premium"""
return asmp.ExpsAcqAnnPrem.match(prod, polt, gen).value
def ExpsAcqPol():
"""Acquisition expense per policy"""
return asmp.ExpsAcqPol.match(prod, polt, gen).value
def ExpsMaintSA():
"""Maintenance expense per sum assured"""
return asmp.ExpsMaintSA.match(prod, polt, gen).value
def ExpsMaintAnnPrem():
"""Maintenance expense per annualized premium"""
return asmp.ExpsMaintPrem.match(prod, polt, gen).value
def ExpsMaintPol():
"""Maintenance expense per policy"""
return asmp.ExpsMaintPol.match(prod, polt, gen).value
def CnsmpTax():
"""Consumption tax rate"""
return asmp.CnsmpTax()
def InflRate():
"""Inflation rate"""
return asmp.InflRate()
| """Source module to create ``Assumption`` space from.
This module is a source module to create ``Assumption`` space and its
sub spaces from.
The formulas of the cells in the ``Assumption`` space are created from the
functions defined in this module.
The ``Assumption`` space is the base space of the assumption spaces
for individual policies, which are derived from and belong to
the ``Assumption`` space as its dynamic child spaces.
The assumption spaces for individual policies are parametrized by ``PolicyID``.
For example, to get the assumption space of the policy whose ID is 171::
>> asmp = model.Assumption(171)
The cells in an assumption space for each individual policy retrieve
input data, calculate and hold values of assumptions specific to that policy,
so various spaces in :mod:`Input<simplelife.build_input>` must be accessible
from the ``Assumption`` space.
.. rubric:: Project Templates
This module is included in the following project templates.
* :mod:`simplelife`
* :mod:`nestedlife`
.. rubric:: Referred Spaces
The ``Assumption`` space and its sub spaces depend of the following spaces.
See references sections below for aliases to those spaces and their members
that are referenced in the ``Assumption`` spaces.
* :mod:`Policy<simplelife.policy>` its sub spaces
* ``LifeTable`` in :mod:`Input<simplelife.build_input>`
* ``MortalityTables`` in :mod:`Input<simplelife.build_input>`
* ``Assumption`` in :mod:`Input<simplelife.build_input>`
.. rubric:: Space Parameters
Attributes:
PolicyID: Policy ID
.. rubric:: References in Base
Attributes:
asmp_tbl: ``AssumptionTables`` space in :mod:`Input<simplelife.build_input>` space
asmp: ``Assumption`` space in :mod:`Input<simplelife.build_input>` space
MortalityTables: ``MortalityTables`` space in :mod:`Input<simplelife.build_input>` space
.. rubric:: References in Sub
Attributes:
pol: Alias to :mod:`Policy[PolicyID]<simplelife.policy>`
prod: Alias to :attr:`Policy[PolicyID].Product<simplelife.policy.Product>`
polt: Alias to :attr:`Policy[PolicyID].PolicyType<simplelife.policy.PolicyType>`
gen: Alias to :attr:`Policy[PolicyID].Gen<simplelife.policy.Gen>`
"""
policy_attrs = []
def mort_table():
"""Mortality Table"""
result = asmp.BaseMort.match(prod, polt, gen).value
if result is not None:
return mortality_tables(result).MortalityTable
else:
raise value_error('MortTable not found')
def last_age():
"""Age at which mortality becomes 1"""
x = 0
while True:
if base_mort_rate(x) == 1:
return x
x += 1
def base_mort_rate(x):
"""Bae mortality rate"""
return mort_table()(pol.Sex, x)
def mort_factor(y):
"""Mortality factor"""
table = asmp.MortFactor.match(prod, polt, gen).value
if table is None:
raise value_error('MortFactor not found')
result = asmp_tbl.cells[table](y)
if result is None:
return mort_factor(y - 1)
else:
return result
def surr_rate(y):
"""Surrender Rate"""
table = asmp.Surrender.match(prod, polt, gen).value
if table is None:
raise value_error('Surrender not found')
result = asmp_tbl.cells[table](y)
if result is None:
return surr_rate(y - 1)
else:
return result
def comm_init_prem():
"""Initial commission per premium"""
result = asmp.CommInitPrem.match(prod, polt, gen).value
if result is not None:
return result
else:
raise value_error('CommInitPrem not found')
def comm_ren_prem():
"""Renewal commission per premium"""
result = asmp.CommRenPrem.match(prod, polt, gen).value
if result is not None:
return result
else:
raise value_error('CommRenPrem not found')
def comm_ren_term():
"""Renewal commission term"""
result = asmp.CommRenTerm.match(prod, polt, gen).value
if result is not None:
return result
else:
raise value_error('CommRenTerm not found')
def exps_acq_sa():
"""Acquisition expense per sum assured"""
return asmp.ExpsAcqSA.match(prod, polt, gen).value
def exps_acq_ann_prem():
"""Acquisition expense per annualized premium"""
return asmp.ExpsAcqAnnPrem.match(prod, polt, gen).value
def exps_acq_pol():
"""Acquisition expense per policy"""
return asmp.ExpsAcqPol.match(prod, polt, gen).value
def exps_maint_sa():
"""Maintenance expense per sum assured"""
return asmp.ExpsMaintSA.match(prod, polt, gen).value
def exps_maint_ann_prem():
"""Maintenance expense per annualized premium"""
return asmp.ExpsMaintPrem.match(prod, polt, gen).value
def exps_maint_pol():
"""Maintenance expense per policy"""
return asmp.ExpsMaintPol.match(prod, polt, gen).value
def cnsmp_tax():
"""Consumption tax rate"""
return asmp.CnsmpTax()
def infl_rate():
"""Inflation rate"""
return asmp.InflRate() |
name = str(input('digite seu name: ')).upper()
if name == 'LUZIA':
print(f'{name} good night')
else:
print(f'hello {name}')
| name = str(input('digite seu name: ')).upper()
if name == 'LUZIA':
print(f'{name} good night')
else:
print(f'hello {name}') |
"""
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
"""
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
N = len(s)
if N == 0 or s[0] == '0':
return 0
dp = [0 for i in range(N+1)]
dp[0] = 1
dp[1] = 1
for i in range(2, N+1):
if s[i-1] == '0' and s[i-2] not in ['1', '2']:
return 0
if s[i-1] != '0':
dp[i] += dp[i-1]
if 10 <= int(s[i-2: i]) <= 26:
dp[i] += dp[i-2]
return dp[N]
# Note:
# 1. State: dp[i] means from char 0 to char i-1 how many decode ways
# 2. Init: dp[0] = 1; dp[1] = 1
# 3. Function:
# dp[i] = if s[i-1] == 0 and s[i-2] not in ['1', '2'] : return 0
# if s[i-1] != 0 : += dp[i-1]
# if 10 <= int(s[i-2:i]) <= 26 : += dp[i-2]
# 4. Result: dp[N]
# i. dp size is len(s)+1
# ii. 10 <= x <= 26
# iii. use if += instead of if dp = xx else dp = xx
# Another idea
def numDecodings_2(self, s):
if s == '' or s[0] == '0': return 0
dp = [1, 1]
length = len(s)
for i in xrange(2, length + 1):
if 10 <= int(s[i-2:i]) <= 26 and '1' <= s[i-1] <= '9':
dp.append(dp[i-1] + dp[i-2])
elif 10 <= int(s[i-2:i]) <= 26: # s[i-1] == '0'
dp.append(dp[i-2])
elif '1' <= s[i-1] <= '9':
dp.append(dp[i-1])
else: # s[i] == '0'
return 0
return dp[length]
| """
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
"""
class Solution:
def num_decodings(self, s):
n = len(s)
if N == 0 or s[0] == '0':
return 0
dp = [0 for i in range(N + 1)]
dp[0] = 1
dp[1] = 1
for i in range(2, N + 1):
if s[i - 1] == '0' and s[i - 2] not in ['1', '2']:
return 0
if s[i - 1] != '0':
dp[i] += dp[i - 1]
if 10 <= int(s[i - 2:i]) <= 26:
dp[i] += dp[i - 2]
return dp[N]
def num_decodings_2(self, s):
if s == '' or s[0] == '0':
return 0
dp = [1, 1]
length = len(s)
for i in xrange(2, length + 1):
if 10 <= int(s[i - 2:i]) <= 26 and '1' <= s[i - 1] <= '9':
dp.append(dp[i - 1] + dp[i - 2])
elif 10 <= int(s[i - 2:i]) <= 26:
dp.append(dp[i - 2])
elif '1' <= s[i - 1] <= '9':
dp.append(dp[i - 1])
else:
return 0
return dp[length] |
# All participants who ranked A-th or higher get a T-shirt.
# Additionally, from the participants who ranked between
# (A+1)-th and B-th (inclusive), C participants chosen uniformly at random get a T-shirt.
A, B, C, X = map(int, input().split())
if(X <= A):
print(1.000000000000)
elif(X > A and X <= B):
print(C/(B-A))
else:
print(0.000000000000) | (a, b, c, x) = map(int, input().split())
if X <= A:
print(1.0)
elif X > A and X <= B:
print(C / (B - A))
else:
print(0.0) |
cifar10_config = {
'num_clients': 100,
'model_name': 'Cifar10Net', # Model type
'round': 1000,
'save_period': 200,
'weight_decay': 1e-3,
'batch_size': 50,
'test_batch_size': 256, # no this param in official code
'lr_decay_per_round': 1,
'epochs': 5,
'lr': 0.1,
'print_freq': 5,
'alpha_coef': 1e-2,
'max_norm': 10,
'sample_ratio': 1,
'partition': 'iid',
'dataset': 'cifar10',
}
debug_config = {
'num_clients': 30,
'model_name': 'Cifar10Net', # Model type
'round': 5,
'save_period': 2,
'weight_decay': 1e-3,
'batch_size': 50,
'test_batch_size': 50,
'act_prob': 1,
'lr_decay_per_round': 1,
'epochs': 5,
'lr': 0.1,
'print_freq': 1,
'alpha_coef': 1e-2,
'max_norm': 10,
'sample_ratio': 1,
'partition': 'iid',
'dataset': 'cifar10'
}
# usage: local_params_file_pattern.format(cid=cid)
local_grad_vector_file_pattern = "client_{cid:03d}_local_grad_vector.pt" # accumulated model gradient
clnt_params_file_pattern = "client_{cid:03d}_clnt_params.pt" # latest model param
local_grad_vector_list_file_pattern = "client_rank_{rank:02d}_local_grad_vector_list.pt" # accumulated model gradient for clients in one client process
clnt_params_list_file_pattern = "client_rank_{rank:02d}_clnt_params_list.pt" # latest model param for clients in one client process
| cifar10_config = {'num_clients': 100, 'model_name': 'Cifar10Net', 'round': 1000, 'save_period': 200, 'weight_decay': 0.001, 'batch_size': 50, 'test_batch_size': 256, 'lr_decay_per_round': 1, 'epochs': 5, 'lr': 0.1, 'print_freq': 5, 'alpha_coef': 0.01, 'max_norm': 10, 'sample_ratio': 1, 'partition': 'iid', 'dataset': 'cifar10'}
debug_config = {'num_clients': 30, 'model_name': 'Cifar10Net', 'round': 5, 'save_period': 2, 'weight_decay': 0.001, 'batch_size': 50, 'test_batch_size': 50, 'act_prob': 1, 'lr_decay_per_round': 1, 'epochs': 5, 'lr': 0.1, 'print_freq': 1, 'alpha_coef': 0.01, 'max_norm': 10, 'sample_ratio': 1, 'partition': 'iid', 'dataset': 'cifar10'}
local_grad_vector_file_pattern = 'client_{cid:03d}_local_grad_vector.pt'
clnt_params_file_pattern = 'client_{cid:03d}_clnt_params.pt'
local_grad_vector_list_file_pattern = 'client_rank_{rank:02d}_local_grad_vector_list.pt'
clnt_params_list_file_pattern = 'client_rank_{rank:02d}_clnt_params_list.pt' |
class ConnectedClientsList(list):
"""A response class representing the clients connected
to the router at this time (or that have been recently connected).
"""
pass
class ConnectedClientsListItem(object):
"""A client entry in the :class:`ConnectedClientsList`."""
LEASE_TIME_PERMANENT = 'Permanent'
def __init__(self):
self._client_name = None
self._mac_address = None
self._ip_address = None
self._lease_time = None
def set_client_name(self, value):
self._client_name = value
@property
def client_name(self):
return self._client_name
def set_mac(self, value):
self._mac_address = value
@property
def mac(self):
return self._mac_address
def set_ip(self, value):
self._ip_address = value
@property
def ip(self):
return self._ip_address
def set_lease_time(self, value):
self._lease_time = value
@property
def lease_time(self):
return self._lease_time
@property
def is_permanent_lease(self):
return (self._lease_time == self.__class__.LEASE_TIME_PERMANENT)
def __repr__(self):
return '<%s: %s; %s>' % (self.__class__, self._client_name, self._ip_address)
| class Connectedclientslist(list):
"""A response class representing the clients connected
to the router at this time (or that have been recently connected).
"""
pass
class Connectedclientslistitem(object):
"""A client entry in the :class:`ConnectedClientsList`."""
lease_time_permanent = 'Permanent'
def __init__(self):
self._client_name = None
self._mac_address = None
self._ip_address = None
self._lease_time = None
def set_client_name(self, value):
self._client_name = value
@property
def client_name(self):
return self._client_name
def set_mac(self, value):
self._mac_address = value
@property
def mac(self):
return self._mac_address
def set_ip(self, value):
self._ip_address = value
@property
def ip(self):
return self._ip_address
def set_lease_time(self, value):
self._lease_time = value
@property
def lease_time(self):
return self._lease_time
@property
def is_permanent_lease(self):
return self._lease_time == self.__class__.LEASE_TIME_PERMANENT
def __repr__(self):
return '<%s: %s; %s>' % (self.__class__, self._client_name, self._ip_address) |
# Problem: Set Matrix Zeros
# Difficulty: Medium
# Category: Array
# Leetcode 73: https://leetcode.com/problems/set-matrix-zeroes/description/
# Description:
"""
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
"""
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
col0 = 1
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
if matrix[i][0] == 0:
col0 = 0
for j in range(1, cols):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
for i in range(rows - 1, -1, -1):
for j in range(cols - 1, 0, -1):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if col0 == 0:
matrix[i][0] = 0
obj = Solution()
t1 = [[0], [1]]
obj.setZeroes(t1)
| """
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
"""
class Solution(object):
def set_zeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
col0 = 1
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
if matrix[i][0] == 0:
col0 = 0
for j in range(1, cols):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
for i in range(rows - 1, -1, -1):
for j in range(cols - 1, 0, -1):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if col0 == 0:
matrix[i][0] = 0
obj = solution()
t1 = [[0], [1]]
obj.setZeroes(t1) |
def insertion_sort(a, n):
"""
insertion sort algorithm
# outer loop from left to right start from 1
# inner loop from right to left end to right counter eq 0
start outer loop:
1. compare 2 elements
2. and swap
3. and decrement right counter
# let l be left_cnf
# let r be right_cnt
"""
for l in range(1, n):
r = l
while a[r-1] > a[r] and r > 0:
a[r], a[r - 1] = a[r-1], a[r]
r -= 1
return a
def reversed_insertion_sort(a, n):
for i in range(1, n):
idx = i
while a[idx] > a[idx - 1] and idx > 0:
# swap
a[idx], a[idx - 1] = a[idx - 1], a[idx]
idx -= 1
return a
print(insertion_sort([101, 45, 9, 17, 2, 3, 1], 7))
print(insertion_sort([1, 2, 3, 4, 5, 6, 9], 7))
print(reversed_insertion_sort([101, 45, 9, 17, 2, 3, 1], 7))
| def insertion_sort(a, n):
"""
insertion sort algorithm
# outer loop from left to right start from 1
# inner loop from right to left end to right counter eq 0
start outer loop:
1. compare 2 elements
2. and swap
3. and decrement right counter
# let l be left_cnf
# let r be right_cnt
"""
for l in range(1, n):
r = l
while a[r - 1] > a[r] and r > 0:
(a[r], a[r - 1]) = (a[r - 1], a[r])
r -= 1
return a
def reversed_insertion_sort(a, n):
for i in range(1, n):
idx = i
while a[idx] > a[idx - 1] and idx > 0:
(a[idx], a[idx - 1]) = (a[idx - 1], a[idx])
idx -= 1
return a
print(insertion_sort([101, 45, 9, 17, 2, 3, 1], 7))
print(insertion_sort([1, 2, 3, 4, 5, 6, 9], 7))
print(reversed_insertion_sort([101, 45, 9, 17, 2, 3, 1], 7)) |
# OpenWeatherMap API Key
weather_api_key = "9cfaeb3dbd4832137f0fb5f0e12ca0f4"
# Google API Key
g_key = "AIzaSyBwiWBdcMksrxnWzcOvCM1cjxhqV8017_A"
| weather_api_key = '9cfaeb3dbd4832137f0fb5f0e12ca0f4'
g_key = 'AIzaSyBwiWBdcMksrxnWzcOvCM1cjxhqV8017_A' |
input = """
zwanzig(A) :- A=5*4.
fuenf(A) :- 20=A*4.
eins(A) :- 3=2+A.
"""
output = """
zwanzig(A) :- A=5*4.
fuenf(A) :- 20=A*4.
eins(A) :- 3=2+A.
"""
| input = '\nzwanzig(A) :- A=5*4.\nfuenf(A) :- 20=A*4.\n\neins(A) :- 3=2+A.\n'
output = '\nzwanzig(A) :- A=5*4.\nfuenf(A) :- 20=A*4.\n\neins(A) :- 3=2+A.\n' |
"""A module for the ProjectListing class."""
class ProjectListing:
"""A class to respresent a projects listing."""
def __init__(self, response):
self.response = response
def can_access_project(self, project: str):
"""Check if the provided project ID is in the response."""
return any(int(project) == item["id"] for item in self.response.json())
def get_projects(self):
"""Return the list of projects."""
return self.response.json()
def print_all(self):
"""Print all projects."""
for item in self.get_projects():
print(f'-> Project {item["id"]:>3}, named "{item["name"]}"')
def __repr__(self):
return f"ProjectListing({self.response!r})"
| """A module for the ProjectListing class."""
class Projectlisting:
"""A class to respresent a projects listing."""
def __init__(self, response):
self.response = response
def can_access_project(self, project: str):
"""Check if the provided project ID is in the response."""
return any((int(project) == item['id'] for item in self.response.json()))
def get_projects(self):
"""Return the list of projects."""
return self.response.json()
def print_all(self):
"""Print all projects."""
for item in self.get_projects():
print(f'''-> Project {item['id']:>3}, named "{item['name']}"''')
def __repr__(self):
return f'ProjectListing({self.response!r})' |
class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
unittest = Square(88)
print(unittest.area())
unittest2 = Shape()
print((unittest2.area())) | class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
unittest = square(88)
print(unittest.area())
unittest2 = shape()
print(unittest2.area()) |
# TESTS FOR COLOURABLE
# graph with no vertices
g0 = Graph(0)
print(str(colourable(g0)) + "... should be TRUE")
# graph with one vertice (no edge)
g1 = Graph(1)
g1.matrix[0][0] = True
print(str(colourable(g1)) + "... should be FALSE")
# graph with one vertice (and edge)
g2 = Graph(1)
print(str(colourable(g2)) + "... should be TRUE")
# two vertices
g3 = Graph(2)
print(str(colourable(g3)) + "... should be TRUE")
g4 = Graph(2)
g4.matrix[0][0] = True
print(str(colourable(g4)) + "... should be FALSE")
g5 = Graph(2)
g5.matrix[0][1] = True
g5.matrix[1][0] = True
print(str(colourable(g5)) + "... should be TRUE")
g6 = Graph(2)
g6.matrix[1][1] = True
print(str(colourable(g6)) + "... should be FALSE")
# three vertices
g7 = Graph(3)
print(str(colourable(g7)) + "... should be TRUE")
g8 = Graph(3)
g8.matrix[0][1] = True
g8.matrix[1][0] = True
print(str(colourable(g8)) + "... should be TRUE")
g9 = Graph(3)
g9.matrix[0][1] = True
g9.matrix[1][0] = True
g9.matrix[2][2] = True
print(str(colourable(g9)) + "... should be FALSE")
g10 = Graph(3)
g10.matrix[0][1] = True
g10.matrix[1][0] = True
g10.matrix[0][2] = True
g10.matrix[2][0] = True
print(str(colourable(g10)) + "... should be TRUE")
g11 = Graph(3)
g11.matrix[0][1] = True
g11.matrix[1][0] = True
g11.matrix[0][2] = True
g11.matrix[2][0] = True
g11.matrix[2][2] = True
print(str(colourable(g11)) + "... should be FALSE")
g12 = Graph(3)
g12.matrix[0][1] = True
g12.matrix[1][0] = True
g12.matrix[0][2] = True
g12.matrix[2][0] = True
g12.matrix[2][1] = True
g12.matrix[1][2] = True
print(str(colourable(g12)) + "... should be FALSE")
g13 = Graph(3)
g13.matrix[0][2] = True
g13.matrix[1][2] = True
g13.matrix[2][0] = True
g13.matrix[2][1] = True
print(str(colourable(g13)) + "... should be TRUE")
g14 = Graph(4)
g14.matrix[0][1] = True
g14.matrix[0][2] = True
g14.matrix[1][3] = True
g14.matrix[2][3] = True
g14.matrix[1][0] = True
g14.matrix[2][0] = True
g14.matrix[3][1] = True
g14.matrix[3][2] = True
print(str(colourable(g14)) + "... should be TRUE")
#same graph as 14, but no backwards edges
g15 = Graph(4)
g15.matrix[0][1] = True
g15.matrix[0][2] = True
g15.matrix[1][3] = True
g15.matrix[2][3] = True
print(str(colourable(g15)) + "... should be TRUE")
g16 = Graph(6)
g16.matrix[0][1] = True
g16.matrix[0][2] = True
g16.matrix[1][3] = True
g16.matrix[2][3] = True
g16.matrix[1][0] = True
g16.matrix[2][0] = True
g16.matrix[3][1] = True
g16.matrix[3][2] = True
g16.matrix[4][5] = True
g16.matrix[5][4] = True
print(str(colourable(g16)) + "... should be TRUE")
g17 = Graph(4)
g17.matrix[0][1] = True
g17.matrix[1][0] = True
g17.matrix[1][3] = True
g17.matrix[3][1] = True
g17.matrix[2][3] = True
g17.matrix[3][2] = True
print(str(colourable(g17)) + "... should be TRUE")
g18 = Graph(5)
g18.matrix[4][3] = True
g18.matrix[4][1] = True
g18.matrix[1][0] = True
g18.matrix[0][2] = True
g18.matrix[2][4] = True
g18.matrix[4][2] = True
g18.matrix[2][0] = True
g18.matrix[0][1] = True
g18.matrix[1][4] = True
g18.matrix[3][4] = True
print(str(colourable(g18)) + "... should be TRUE")
g20 = Graph(4)
g20.matrix[3][0] = True
g20.matrix[0][1] = True
g20.matrix[0][2] = True
g20.matrix[0][3] = True
g20.matrix[1][0] = True
g20.matrix[2][0] = True
print(str(colourable(g20)) + "... should be TRUE")
# TEST FOR DEPENDENCY
g1 = Graph(0)
print(str(compute_dependencies(g1)) + " ... should be []")
g2 = Graph(1)
g2.matrix[0][0] = True
print(str(compute_dependencies(g2)) + " ... should be None")
g3 = Graph(3)
g3.matrix[0][1] = True
g3.matrix[2][0] = True
g3.matrix[2][1] = True
print(str(compute_dependencies(g3)) + " ... [2, 0, 1]")
g4 = Graph(3)
g4.matrix[1][2] = True
print(str(compute_dependencies(g4)) + " ... [0, 1, 2], [1, 0, 2], [1, 2, 0]")
g5 = Graph(4)
g5.matrix[0][1] = True
g5.matrix[2][3] = True
print(str(compute_dependencies(g5)) + " ... [2, 3, 0, 1], [0, 2, 1, 3]")
g6 = Graph(3)
g6.matrix[0][1] = True
g6.matrix[1][2] = True
g6.matrix[2][0] = True
print(str(compute_dependencies(g6)) + " ... None")
| g0 = graph(0)
print(str(colourable(g0)) + '... should be TRUE')
g1 = graph(1)
g1.matrix[0][0] = True
print(str(colourable(g1)) + '... should be FALSE')
g2 = graph(1)
print(str(colourable(g2)) + '... should be TRUE')
g3 = graph(2)
print(str(colourable(g3)) + '... should be TRUE')
g4 = graph(2)
g4.matrix[0][0] = True
print(str(colourable(g4)) + '... should be FALSE')
g5 = graph(2)
g5.matrix[0][1] = True
g5.matrix[1][0] = True
print(str(colourable(g5)) + '... should be TRUE')
g6 = graph(2)
g6.matrix[1][1] = True
print(str(colourable(g6)) + '... should be FALSE')
g7 = graph(3)
print(str(colourable(g7)) + '... should be TRUE')
g8 = graph(3)
g8.matrix[0][1] = True
g8.matrix[1][0] = True
print(str(colourable(g8)) + '... should be TRUE')
g9 = graph(3)
g9.matrix[0][1] = True
g9.matrix[1][0] = True
g9.matrix[2][2] = True
print(str(colourable(g9)) + '... should be FALSE')
g10 = graph(3)
g10.matrix[0][1] = True
g10.matrix[1][0] = True
g10.matrix[0][2] = True
g10.matrix[2][0] = True
print(str(colourable(g10)) + '... should be TRUE')
g11 = graph(3)
g11.matrix[0][1] = True
g11.matrix[1][0] = True
g11.matrix[0][2] = True
g11.matrix[2][0] = True
g11.matrix[2][2] = True
print(str(colourable(g11)) + '... should be FALSE')
g12 = graph(3)
g12.matrix[0][1] = True
g12.matrix[1][0] = True
g12.matrix[0][2] = True
g12.matrix[2][0] = True
g12.matrix[2][1] = True
g12.matrix[1][2] = True
print(str(colourable(g12)) + '... should be FALSE')
g13 = graph(3)
g13.matrix[0][2] = True
g13.matrix[1][2] = True
g13.matrix[2][0] = True
g13.matrix[2][1] = True
print(str(colourable(g13)) + '... should be TRUE')
g14 = graph(4)
g14.matrix[0][1] = True
g14.matrix[0][2] = True
g14.matrix[1][3] = True
g14.matrix[2][3] = True
g14.matrix[1][0] = True
g14.matrix[2][0] = True
g14.matrix[3][1] = True
g14.matrix[3][2] = True
print(str(colourable(g14)) + '... should be TRUE')
g15 = graph(4)
g15.matrix[0][1] = True
g15.matrix[0][2] = True
g15.matrix[1][3] = True
g15.matrix[2][3] = True
print(str(colourable(g15)) + '... should be TRUE')
g16 = graph(6)
g16.matrix[0][1] = True
g16.matrix[0][2] = True
g16.matrix[1][3] = True
g16.matrix[2][3] = True
g16.matrix[1][0] = True
g16.matrix[2][0] = True
g16.matrix[3][1] = True
g16.matrix[3][2] = True
g16.matrix[4][5] = True
g16.matrix[5][4] = True
print(str(colourable(g16)) + '... should be TRUE')
g17 = graph(4)
g17.matrix[0][1] = True
g17.matrix[1][0] = True
g17.matrix[1][3] = True
g17.matrix[3][1] = True
g17.matrix[2][3] = True
g17.matrix[3][2] = True
print(str(colourable(g17)) + '... should be TRUE')
g18 = graph(5)
g18.matrix[4][3] = True
g18.matrix[4][1] = True
g18.matrix[1][0] = True
g18.matrix[0][2] = True
g18.matrix[2][4] = True
g18.matrix[4][2] = True
g18.matrix[2][0] = True
g18.matrix[0][1] = True
g18.matrix[1][4] = True
g18.matrix[3][4] = True
print(str(colourable(g18)) + '... should be TRUE')
g20 = graph(4)
g20.matrix[3][0] = True
g20.matrix[0][1] = True
g20.matrix[0][2] = True
g20.matrix[0][3] = True
g20.matrix[1][0] = True
g20.matrix[2][0] = True
print(str(colourable(g20)) + '... should be TRUE')
g1 = graph(0)
print(str(compute_dependencies(g1)) + ' ... should be []')
g2 = graph(1)
g2.matrix[0][0] = True
print(str(compute_dependencies(g2)) + ' ... should be None')
g3 = graph(3)
g3.matrix[0][1] = True
g3.matrix[2][0] = True
g3.matrix[2][1] = True
print(str(compute_dependencies(g3)) + ' ... [2, 0, 1]')
g4 = graph(3)
g4.matrix[1][2] = True
print(str(compute_dependencies(g4)) + ' ... [0, 1, 2], [1, 0, 2], [1, 2, 0]')
g5 = graph(4)
g5.matrix[0][1] = True
g5.matrix[2][3] = True
print(str(compute_dependencies(g5)) + ' ... [2, 3, 0, 1], [0, 2, 1, 3]')
g6 = graph(3)
g6.matrix[0][1] = True
g6.matrix[1][2] = True
g6.matrix[2][0] = True
print(str(compute_dependencies(g6)) + ' ... None') |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ret = set()
for i, v in enumerate(nums):
j, k = i + 1, len(nums) - 1
while j < k:
if nums[j] + nums[k] == -v:
ret.add((v, nums[j], nums[k]))
if nums[j] + nums[k] > -v:
k -= 1
else:
j += 1
return list(map(lambda x: list(x), ret))
| class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ret = set()
for (i, v) in enumerate(nums):
(j, k) = (i + 1, len(nums) - 1)
while j < k:
if nums[j] + nums[k] == -v:
ret.add((v, nums[j], nums[k]))
if nums[j] + nums[k] > -v:
k -= 1
else:
j += 1
return list(map(lambda x: list(x), ret)) |
'''
(C) Copyright 2021 Steven;
@author: Steven kangweibaby@163.com
@date: 2021-06-30
'''
| """
(C) Copyright 2021 Steven;
@author: Steven kangweibaby@163.com
@date: 2021-06-30
""" |
with open('day13/input.txt', 'r') as file:
timestamp = int(file.readline())
data = str(file.readline()).split(',')
data_1 = [int(x) for x in data if x != 'x']
res = sorted([(x - timestamp % x, x) for x in data_1], key=lambda x: x[0])
data_2 = [(int(x), data.index(x)) for x in data if x != 'x']
superbus_time = data_2[0][0]
final_time = 0
for bus, remainder in data_2[1:]:
while (final_time + remainder) % bus != 0:
final_time += superbus_time
superbus_time *= bus
print(f"Result 1: {res[0][0] * res[0][1]}\nResult 2: {final_time}")
| with open('day13/input.txt', 'r') as file:
timestamp = int(file.readline())
data = str(file.readline()).split(',')
data_1 = [int(x) for x in data if x != 'x']
res = sorted([(x - timestamp % x, x) for x in data_1], key=lambda x: x[0])
data_2 = [(int(x), data.index(x)) for x in data if x != 'x']
superbus_time = data_2[0][0]
final_time = 0
for (bus, remainder) in data_2[1:]:
while (final_time + remainder) % bus != 0:
final_time += superbus_time
superbus_time *= bus
print(f'Result 1: {res[0][0] * res[0][1]}\nResult 2: {final_time}') |
#O(n) Space and time Complexity
# Maintain a frequency map as {prefix_Sum:frequency of this prefix sum}
# While looping the array:
#0. hash_map[current_prefix_sum] += 1
#1. If (current_prefix_sum - k) exists in the map, it means there is a subarray found hence increment the counter.
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
D={}
D[0]=1
s=0
c=0
for i in range(len(nums)):
s=s+nums[i]
if s-k in D:
c += D[s-k]
if s in D:
D[s] += 1
else:
D[s]=1
return c
| class Solution:
def subarray_sum(self, nums: List[int], k: int) -> int:
d = {}
D[0] = 1
s = 0
c = 0
for i in range(len(nums)):
s = s + nums[i]
if s - k in D:
c += D[s - k]
if s in D:
D[s] += 1
else:
D[s] = 1
return c |
# Here's a challenge for you to help you practice
# See if you can fix the code below
# print the message
# There was a single quote inside the string!
# Use double quotes to enclose the string
print("Why won't this line of code print")
# print the message
# There was a mistake in the function name
print('This line fails too!')
# print the message
# Need to add the () around the string
print ("I think I know how to fix this one")
# print the name entered by the user
# You need to store the value returned by the input statement
# in a variable
name = input('Please tell me your name: ')
print(name)
| print("Why won't this line of code print")
print('This line fails too!')
print('I think I know how to fix this one')
name = input('Please tell me your name: ')
print(name) |
POST_ACTIONS = [
'oauth.getAccessToken',
'oauth.getRequestToken',
'oauth.verify',
'comment.digg',
'comment.bury',
'shorturl.create',
'story.bury',
'story.digg',
]
| post_actions = ['oauth.getAccessToken', 'oauth.getRequestToken', 'oauth.verify', 'comment.digg', 'comment.bury', 'shorturl.create', 'story.bury', 'story.digg'] |
N = input()
before = ""
count = 1
for s in N:
if before == -1:
before = s
else:
if before == s:
count += 1
if count >= 3:
print("Yes")
exit()
else:
before = s
count = 1
print("No")
| n = input()
before = ''
count = 1
for s in N:
if before == -1:
before = s
elif before == s:
count += 1
if count >= 3:
print('Yes')
exit()
else:
before = s
count = 1
print('No') |
class Optimizer:
pass
class RandomRestartOptimizer(Optimizer):
def __init__(self, N=10):
self.N=N | class Optimizer:
pass
class Randomrestartoptimizer(Optimizer):
def __init__(self, N=10):
self.N = N |
class Solution(object):
def license_key_formatiing(self, S, K):
"""
You are given a license key represented as a string S which consists only alphanumeric character and dashes.
The string is separated into N+1 groups by N dashes.
:type S: str
:type K: int
:rtype: str
"""
S = S.replace("-", "").upper()[::-1]
return '-'.join(S[i:i+K] for i in range(0, len(S), K))[::-1] | class Solution(object):
def license_key_formatiing(self, S, K):
"""
You are given a license key represented as a string S which consists only alphanumeric character and dashes.
The string is separated into N+1 groups by N dashes.
:type S: str
:type K: int
:rtype: str
"""
s = S.replace('-', '').upper()[::-1]
return '-'.join((S[i:i + K] for i in range(0, len(S), K)))[::-1] |
class Piece(object):
BLACK = 'X'
WHITE = 'O'
def __init__(self, position, state):
self.x = position[0]
self.y = position[1]
self.state = state
@property
def other_side(self):
"""The opposite side of this piece.
Returns:
str: Whatever the other side of piece current is.
"""
if self.state == self.BLACK:
return self.WHITE
return self.BLACK
| class Piece(object):
black = 'X'
white = 'O'
def __init__(self, position, state):
self.x = position[0]
self.y = position[1]
self.state = state
@property
def other_side(self):
"""The opposite side of this piece.
Returns:
str: Whatever the other side of piece current is.
"""
if self.state == self.BLACK:
return self.WHITE
return self.BLACK |
AUTH_USER_MODEL = 'users.User'
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
DJOSER = {
'HIDE_USERS': False,
'LOGIN_FIELD': 'email',
'SERIALIZERS': {
'user_create': 'users.api.serializers.UserCreateSerializer',
'user': 'users.api.serializers.UserSerializer',
'current_user': 'users.api.serializers.UserSerializer',
},
'PERMISSIONS': {
'user_list': ['rest_framework.permissions.AllowAny'],
'user': ['rest_framework.permissions.IsAuthenticated'],
},
}
| auth_user_model = 'users.User'
auth_password_validators = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}]
djoser = {'HIDE_USERS': False, 'LOGIN_FIELD': 'email', 'SERIALIZERS': {'user_create': 'users.api.serializers.UserCreateSerializer', 'user': 'users.api.serializers.UserSerializer', 'current_user': 'users.api.serializers.UserSerializer'}, 'PERMISSIONS': {'user_list': ['rest_framework.permissions.AllowAny'], 'user': ['rest_framework.permissions.IsAuthenticated']}} |
class AlgorithmConfigurationProvider:
def __init__(self, chromosome_config, left_range_number, right_range_number, population_number,
epochs_number, selection_amount, elite_amount, selection_method, is_maximization):
self.__chromosome_config = chromosome_config
self.__left_range_number = left_range_number
self.__right_range_number = right_range_number
self.__variables_number = 2
self.__population_number = population_number
self.__epochs_number = epochs_number
self.__selection_amount = selection_amount
self.__elite_amount = elite_amount
self.__selection_method = selection_method
self.__is_maximization = is_maximization
@property
def left_range_number(self):
return self.__left_range_number
@property
def right_range_number(self):
return self.__right_range_number
@property
def population_number(self):
return self.__population_number
@property
def epochs_number(self):
return self.__epochs_number
@property
def variables_number(self):
return self.__variables_number
@property
def is_maximization(self):
return self.__is_maximization
@property
def chromosome_config(self):
return self.__chromosome_config
@property
def selection_method(self):
return self.__selection_method
@property
def selection_amount(self):
return self.__selection_amount
@property
def elite_amount(self):
return self.__elite_amount
| class Algorithmconfigurationprovider:
def __init__(self, chromosome_config, left_range_number, right_range_number, population_number, epochs_number, selection_amount, elite_amount, selection_method, is_maximization):
self.__chromosome_config = chromosome_config
self.__left_range_number = left_range_number
self.__right_range_number = right_range_number
self.__variables_number = 2
self.__population_number = population_number
self.__epochs_number = epochs_number
self.__selection_amount = selection_amount
self.__elite_amount = elite_amount
self.__selection_method = selection_method
self.__is_maximization = is_maximization
@property
def left_range_number(self):
return self.__left_range_number
@property
def right_range_number(self):
return self.__right_range_number
@property
def population_number(self):
return self.__population_number
@property
def epochs_number(self):
return self.__epochs_number
@property
def variables_number(self):
return self.__variables_number
@property
def is_maximization(self):
return self.__is_maximization
@property
def chromosome_config(self):
return self.__chromosome_config
@property
def selection_method(self):
return self.__selection_method
@property
def selection_amount(self):
return self.__selection_amount
@property
def elite_amount(self):
return self.__elite_amount |
def get_ids_and_classes(tag):
attrs = tag.attrs
if 'id' in attrs:
ids = attrs['id']
if isinstance(ids, list):
for subitem in ids:
yield subitem
else:
yield ids
if 'class' in attrs:
classes = attrs['class']
if isinstance(classes, list):
for subitem in classes:
yield subitem
else:
yield classes
| def get_ids_and_classes(tag):
attrs = tag.attrs
if 'id' in attrs:
ids = attrs['id']
if isinstance(ids, list):
for subitem in ids:
yield subitem
else:
yield ids
if 'class' in attrs:
classes = attrs['class']
if isinstance(classes, list):
for subitem in classes:
yield subitem
else:
yield classes |
def testHasMasterPrimary(nodeSet, up):
masterPrimaryCount = 0
for node in nodeSet:
masterPrimaryCount += int(node.monitor.hasMasterPrimary)
assert masterPrimaryCount == 1
| def test_has_master_primary(nodeSet, up):
master_primary_count = 0
for node in nodeSet:
master_primary_count += int(node.monitor.hasMasterPrimary)
assert masterPrimaryCount == 1 |
"""
Kata Sort deck of cards - Use a sort function to put cards in order
#1 Best Practices: zebulan, Unnamed, acaccia, j_codez, Mr.Child, iamchingel (plus 8 more warriors)
def sort_cards(cards):
return sorted(cards, key="A23456789TJQK".index)
."""
def sort_cards(cards):
"""Sort a deck of cards."""
a_bucket = []
t_bucket = []
j_bucket = []
q_bucket = []
k_bucket = []
num_bucket = []
for item in cards:
if item == 'A':
a_bucket.append(item)
elif item == 'T':
t_bucket.append(item)
elif item == 'J':
j_bucket.append(item)
elif item == 'Q':
q_bucket.append(item)
elif item == 'K':
k_bucket.append(item)
else:
num_bucket.append(item)
return a_bucket + sorted(num_bucket) + t_bucket + j_bucket + q_bucket + k_bucket
| """
Kata Sort deck of cards - Use a sort function to put cards in order
#1 Best Practices: zebulan, Unnamed, acaccia, j_codez, Mr.Child, iamchingel (plus 8 more warriors)
def sort_cards(cards):
return sorted(cards, key="A23456789TJQK".index)
."""
def sort_cards(cards):
"""Sort a deck of cards."""
a_bucket = []
t_bucket = []
j_bucket = []
q_bucket = []
k_bucket = []
num_bucket = []
for item in cards:
if item == 'A':
a_bucket.append(item)
elif item == 'T':
t_bucket.append(item)
elif item == 'J':
j_bucket.append(item)
elif item == 'Q':
q_bucket.append(item)
elif item == 'K':
k_bucket.append(item)
else:
num_bucket.append(item)
return a_bucket + sorted(num_bucket) + t_bucket + j_bucket + q_bucket + k_bucket |
###################################
# File Name : dir_normal_func.py
###################################
#!/usr/bin/python3
def normal_func():
pass
if __name__ == "__main__":
p = dir(normal_func())
print ("=== attribute ===")
print (p)
| def normal_func():
pass
if __name__ == '__main__':
p = dir(normal_func())
print('=== attribute ===')
print(p) |
# -*- coding: mbcs -*-
"""
=========================================
PyQus 0.1.0
Author: Pedro Jorge De Los Santos
E-mail: delossantosmfq@gmail.com
https://github.com/JorgeDeLosSantos/pyqus
=========================================
"""
| """
=========================================
PyQus 0.1.0
Author: Pedro Jorge De Los Santos
E-mail: delossantosmfq@gmail.com
https://github.com/JorgeDeLosSantos/pyqus
=========================================
""" |
dividendo=int(input("Dividendo: "))
divisor=int(input("Divisor: "))
if dividendo>0 and divisor>0:
cociente=0
residuo=dividendo
while (residuo>=divisor):
residuo-=divisor
cociente+=1
print(residuo)
print(cociente)
| dividendo = int(input('Dividendo: '))
divisor = int(input('Divisor: '))
if dividendo > 0 and divisor > 0:
cociente = 0
residuo = dividendo
while residuo >= divisor:
residuo -= divisor
cociente += 1
print(residuo)
print(cociente) |
"""
adam_objects.py
"""
class AdamObject(object):
def __init__(self):
self._uuid = None
self._runnable_state = None
self._children = None
def set_uuid(self, uuid):
self._uuid = uuid
def set_runnable_state(self, runnable_state):
self._runnable_state = runnable_state
def set_children(self, children):
self._children = children
def get_uuid(self):
return self._uuid
def get_runnable_state(self):
return self._runnable_state
def get_children(self):
return self._children
class AdamObjectRunnableState(object):
def __init__(self, response):
self._uuid = response['uuid']
self._calc_state = response['calculationState']
self._error = response.get('error')
def get_uuid(self):
return self._uuid
def get_calc_state(self):
return self._calc_state
def get_error(self):
return self._error
class AdamObjects(object):
"""Module for managing AdamObjects.
"""
def __init__(self, rest, obj_type):
self._rest = rest
self._type = obj_type
def __repr__(self):
return "AdamObjects module"
def _insert(self, data):
code, response = self._rest.post(
'/adam_object/single/' + self._type, data)
if code != 200:
raise RuntimeError(
"Server status code: %s; Response: %s" % (code, response))
return response['uuid']
def get_runnable_state(self, uuid):
code, response = self._rest.get(
'/adam_object/runnable_state/single/' + self._type + '/' + uuid)
if code == 404:
return None
elif code != 200:
raise RuntimeError(
"Server status code: %s; Response: %s" % (code, response))
return AdamObjectRunnableState(response)
def get_runnable_states(self, project_uuid):
code, response = self._rest.get(
'/adam_object/runnable_state/by_project/' + self._type + '/' + project_uuid)
if code == 404:
return []
elif code != 200:
raise RuntimeError(
"Server status code: %s; Response: %s" % (code, response))
return [AdamObjectRunnableState(r) for r in response['items']]
def _get_json(self, uuid):
code, response = self._rest.get(
'/adam_object/single/' + self._type + '/' + uuid)
if code == 404:
return None
elif code != 200:
raise RuntimeError(
"Server status code: %s; Response: %s" % (code, response))
return response
def _get_in_project_json(self, project_uuid):
code, response = self._rest.get(
'/adam_object/by_project/' + self._type + '/' + project_uuid)
if code == 404:
return []
elif code != 200:
raise RuntimeError(
"Server status code: %s; Response: %s" % (code, response))
return response['items']
def _get_children_json(self, uuid):
code, response = self._rest.get(
'/adam_object/by_parent/' + self._type + '/' + uuid)
if code == 404:
return []
elif code != 200:
raise RuntimeError(
"Server status code: %s; Response: %s" % (code, response))
if response is None:
return []
child_json_list = []
for child_type, child_uuid in zip(response['childTypes'], response['childUuids']):
print('Fetching ' + child_uuid + ' of type ' + child_type)
retriever = AdamObjects(self._rest, child_type)
child_json_list.append([retriever._get_json(child_uuid),
retriever.get_runnable_state(child_uuid),
child_type])
return child_json_list
def delete(self, uuid):
code, _ = self._rest.delete(
'/adam_object/single/' + self._type + '/' + uuid)
if code != 204:
raise RuntimeError("Server status code: %s" % (code))
| """
adam_objects.py
"""
class Adamobject(object):
def __init__(self):
self._uuid = None
self._runnable_state = None
self._children = None
def set_uuid(self, uuid):
self._uuid = uuid
def set_runnable_state(self, runnable_state):
self._runnable_state = runnable_state
def set_children(self, children):
self._children = children
def get_uuid(self):
return self._uuid
def get_runnable_state(self):
return self._runnable_state
def get_children(self):
return self._children
class Adamobjectrunnablestate(object):
def __init__(self, response):
self._uuid = response['uuid']
self._calc_state = response['calculationState']
self._error = response.get('error')
def get_uuid(self):
return self._uuid
def get_calc_state(self):
return self._calc_state
def get_error(self):
return self._error
class Adamobjects(object):
"""Module for managing AdamObjects.
"""
def __init__(self, rest, obj_type):
self._rest = rest
self._type = obj_type
def __repr__(self):
return 'AdamObjects module'
def _insert(self, data):
(code, response) = self._rest.post('/adam_object/single/' + self._type, data)
if code != 200:
raise runtime_error('Server status code: %s; Response: %s' % (code, response))
return response['uuid']
def get_runnable_state(self, uuid):
(code, response) = self._rest.get('/adam_object/runnable_state/single/' + self._type + '/' + uuid)
if code == 404:
return None
elif code != 200:
raise runtime_error('Server status code: %s; Response: %s' % (code, response))
return adam_object_runnable_state(response)
def get_runnable_states(self, project_uuid):
(code, response) = self._rest.get('/adam_object/runnable_state/by_project/' + self._type + '/' + project_uuid)
if code == 404:
return []
elif code != 200:
raise runtime_error('Server status code: %s; Response: %s' % (code, response))
return [adam_object_runnable_state(r) for r in response['items']]
def _get_json(self, uuid):
(code, response) = self._rest.get('/adam_object/single/' + self._type + '/' + uuid)
if code == 404:
return None
elif code != 200:
raise runtime_error('Server status code: %s; Response: %s' % (code, response))
return response
def _get_in_project_json(self, project_uuid):
(code, response) = self._rest.get('/adam_object/by_project/' + self._type + '/' + project_uuid)
if code == 404:
return []
elif code != 200:
raise runtime_error('Server status code: %s; Response: %s' % (code, response))
return response['items']
def _get_children_json(self, uuid):
(code, response) = self._rest.get('/adam_object/by_parent/' + self._type + '/' + uuid)
if code == 404:
return []
elif code != 200:
raise runtime_error('Server status code: %s; Response: %s' % (code, response))
if response is None:
return []
child_json_list = []
for (child_type, child_uuid) in zip(response['childTypes'], response['childUuids']):
print('Fetching ' + child_uuid + ' of type ' + child_type)
retriever = adam_objects(self._rest, child_type)
child_json_list.append([retriever._get_json(child_uuid), retriever.get_runnable_state(child_uuid), child_type])
return child_json_list
def delete(self, uuid):
(code, _) = self._rest.delete('/adam_object/single/' + self._type + '/' + uuid)
if code != 204:
raise runtime_error('Server status code: %s' % code) |
# Sudoku Solver :https://leetcode.com/problems/sudoku-solver/
# Write a program to solve a Sudoku puzzle by filling the empty cells.
# A sudoku solution must satisfy all of the following rules:
# Each of the digits 1-9 must occur exactly once in each row.
# Each of the digits 1-9 must occur exactly once in each column.
# Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
# The '.' character indicates empty cells.
# So this problem seems rather complicated. However when we apply a backtracking dfs solution
# this problem becomes easier to write. Basically we will continue trying every possible remaining option
# From the set of values 1-9 left after considering following sets: Row, Col and Square if we run out of options
# remove the last value and continue trying until we have reached the last square
class Solution:
def solveSudoku(self, board) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# For any backtracking problem we need a few steps
# Check if you can place an element as they can't be in any set
def canAddVal(value, r, c):
return value not in row[r] and value not in col[c] and value not in sqr[sqrIndex(r, c)]
# Add an element
def addToBoard(value, r, c):
row[r].add(value)
col[c].add(value)
sqr[sqrIndex(r, c)].add(value)
board[r][c] = str(value)
# Remove an element
def remFromBoard(value, r, c):
row[r].remove(value)
col[c].remove(value)
sqr[sqrIndex(r, c)].remove(value)
board[r][c] = '.'
# Move forward
def nextLocation(r, c):
if r == N-1 and c == N-1:
self.isSolved = True
return
else:
if c == N - 1:
backtrack(r + 1)
else:
backtrack(r, c + 1)
def backtrack(r=0, c=0):
if board[r][c] != '.':
# If the number already exists keep moving
nextLocation(r, c)
else:
# iterate over all values 1-9 and try adding them
for val in range(1, 10):
if canAddVal(val, r, c):
addToBoard(val, r, c)
nextLocation(r, c)
# Now that we have added if we end up solving
# we need return the result
if self.isSolved:
return
remFromBoard(val, r, c)
# Set up box lengths
n = 3
N = n * n
# There are 9 rows 9 col and 9 squares which influence which
# nums can be chosen
row = [set() for _ in range(N)]
col = [set() for _ in range(N)]
sqr = [set() for _ in range(N)]
# This formula comes from the fact squares in sudoku work like this:
# 0 1 2
# 3 4 5
# 6 7 8
def sqrIndex(r, c): return (r // 3 * 3) + (c // 3)
self.isSolved = False
for i in range(N):
for j in range(N):
# Add all existing numbers to our sets
if board[i][j] != '.':
addToBoard(int(board[i][j]), i, j)
backtrack()
return board
# So the above works the problem is for backtracking the time complexity is o(1) However
# in the worst case you have to run 9! possible combinations minus whatever combinations
# are removed from numbers already on the board.
# As for the space complexity it is also o(1) as we have 3 sets of 9 and then the 9 by 9 board
# Score Card
# Did I need hints? N
# Did you finish within 30 min? 30
# Was the solution optimal? This is optimal
# Were there any bugs? No
# 5 4 5 5 = 4.75
| class Solution:
def solve_sudoku(self, board) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def can_add_val(value, r, c):
return value not in row[r] and value not in col[c] and (value not in sqr[sqr_index(r, c)])
def add_to_board(value, r, c):
row[r].add(value)
col[c].add(value)
sqr[sqr_index(r, c)].add(value)
board[r][c] = str(value)
def rem_from_board(value, r, c):
row[r].remove(value)
col[c].remove(value)
sqr[sqr_index(r, c)].remove(value)
board[r][c] = '.'
def next_location(r, c):
if r == N - 1 and c == N - 1:
self.isSolved = True
return
elif c == N - 1:
backtrack(r + 1)
else:
backtrack(r, c + 1)
def backtrack(r=0, c=0):
if board[r][c] != '.':
next_location(r, c)
else:
for val in range(1, 10):
if can_add_val(val, r, c):
add_to_board(val, r, c)
next_location(r, c)
if self.isSolved:
return
rem_from_board(val, r, c)
n = 3
n = n * n
row = [set() for _ in range(N)]
col = [set() for _ in range(N)]
sqr = [set() for _ in range(N)]
def sqr_index(r, c):
return r // 3 * 3 + c // 3
self.isSolved = False
for i in range(N):
for j in range(N):
if board[i][j] != '.':
add_to_board(int(board[i][j]), i, j)
backtrack()
return board |
class FunctionMetadata:
def __init__(self):
self._constantReturnValue = ()
def setConstantReturnValue(self, value):
self._constantReturnValue = (value,)
def hasConstantReturnValue(self):
return self._constantReturnValue
def getConstantReturnValue(self):
return self._constantReturnValue[0] if self._constantReturnValue else None
| class Functionmetadata:
def __init__(self):
self._constantReturnValue = ()
def set_constant_return_value(self, value):
self._constantReturnValue = (value,)
def has_constant_return_value(self):
return self._constantReturnValue
def get_constant_return_value(self):
return self._constantReturnValue[0] if self._constantReturnValue else None |
# https://www.codewars.com/kata/578553c3a1b8d5c40300037c/train/python
# Given an array of ones and zeroes, convert the equivalent binary value
# to an integer.
# Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
# Examples:
# Testing: [0, 0, 0, 1] ==> 1
# Testing: [0, 0, 1, 0] ==> 2
# Testing: [0, 1, 0, 1] ==> 5
# Testing: [1, 0, 0, 1] ==> 9
# Testing: [0, 0, 1, 0] ==> 2
# Testing: [0, 1, 1, 0] ==> 6
# Testing: [1, 1, 1, 1] ==> 15
# Testing: [1, 0, 1, 1] ==> 11
# However, the arrays can have varying lengths, not just limited to 4.
def binary_array_to_number(arr):
total = 0
i = 1
for num in arr[::-1]:
total += i * num
i *= 2
return total
# Alternative:
# def binary_array_to_number(arr):
# return int("".join(
# map(str, arr)
# ), 2)
# def binary_array_to_number(arr):
# s = 0
# for digit in arr:
# s = s * 2 + digit
# return s
| def binary_array_to_number(arr):
total = 0
i = 1
for num in arr[::-1]:
total += i * num
i *= 2
return total |
class Solution:
def rob(self, nums: List[int]) -> int:
def rob(l: int, r: int) -> int:
dp1 = 0
dp2 = 0
for i in range(l, r + 1):
temp = dp1
dp1 = max(dp1, dp2 + nums[i])
dp2 = temp
return dp1
if not nums:
return 0
if len(nums) < 2:
return nums[0]
return max(rob(0, len(nums) - 2), rob(1, len(nums) - 1))
| class Solution:
def rob(self, nums: List[int]) -> int:
def rob(l: int, r: int) -> int:
dp1 = 0
dp2 = 0
for i in range(l, r + 1):
temp = dp1
dp1 = max(dp1, dp2 + nums[i])
dp2 = temp
return dp1
if not nums:
return 0
if len(nums) < 2:
return nums[0]
return max(rob(0, len(nums) - 2), rob(1, len(nums) - 1)) |
array = ['a', 'b', 'c']
def decorator(func):
def newValueOf(pos):
if pos >= len(array):
print("Oops! Array index is out of range")
return
func(pos)
return newValueOf
@decorator
def valueOf(index):
print(array[index])
valueOf(10)
| array = ['a', 'b', 'c']
def decorator(func):
def new_value_of(pos):
if pos >= len(array):
print('Oops! Array index is out of range')
return
func(pos)
return newValueOf
@decorator
def value_of(index):
print(array[index])
value_of(10) |
numero = 5
fracao = 6.1
online = True
texto = "Armando"
| numero = 5
fracao = 6.1
online = True
texto = 'Armando' |
maior = 0
pos = 0
for i in range(1, 11):
val = int(input())
if val > maior:
maior = val
pos = i
print('{}\n{}'.format(maior, pos))
| maior = 0
pos = 0
for i in range(1, 11):
val = int(input())
if val > maior:
maior = val
pos = i
print('{}\n{}'.format(maior, pos)) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 14 09:42:46 2019
@author: ASUS
"""
class Solution:
def uniqueMorseRepresentations(self, words: list) -> int:
self.M = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
for k in range(len(words)):
words[k] = self.convert(words[k])
return len(set(words))
def convert(self, word):
# word = list(word)
# length = len(word)
# for letter in word:
# word.append(self.M[ord(letter) - ord('a')])
# word.reverse()
# for _ in range(length):
# word.pop()
# word.reverse()
# return ''.join(word)
word = list(word)
for k in range(len(word)):
word[k] = self.M[ord(word[k]) - ord('a')]
return ''.join(word)
solu = Solution()
words = ["gin", "zen", "gig", "msg"]
print(solu.uniqueMorseRepresentations(words)) | """
Created on Sun Jul 14 09:42:46 2019
@author: ASUS
"""
class Solution:
def unique_morse_representations(self, words: list) -> int:
self.M = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..']
for k in range(len(words)):
words[k] = self.convert(words[k])
return len(set(words))
def convert(self, word):
word = list(word)
for k in range(len(word)):
word[k] = self.M[ord(word[k]) - ord('a')]
return ''.join(word)
solu = solution()
words = ['gin', 'zen', 'gig', 'msg']
print(solu.uniqueMorseRepresentations(words)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.