content
stringlengths 7
1.05M
|
|---|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 12 17:16:30 2021
@author: Marchiano
Sudoku solver using backtraking algorithm
Steps followed:
1) Find empty position on grid
2) Check if value on specified grid position is admissible
3) If valid, solve recursively the puzzle by repeating steps 1 and 2 for the entire grid.
Otherwise, reset position that was just filled to initial unfilled state.
"""
# find empty element in grid (represented by 0) and return position
# if no empty element is found, return None
def find_empty(grid):
gridDim = 9
for row in range(gridDim):
for col in range(gridDim):
if grid[row][col] == 0:
return (row, col)
return None
# check if number of interest is valid in given position
# num: number of interest (1 to 9)
# pos: position of number of interest as tuple (row, col)
# grid: sudoku grid
def is_valid(num, pos, grid):
gridDim = 9
boxDim = 3
row_num = pos[0] # row the number of interest is in
col_num = pos[1] # column the number of interest is in
# check if num already exists in specified row and return False (for not valid) if it exists
for col in range(gridDim):
if grid[row_num][col] == num:
return False
# check if num already exists in specified column and return False (for not valid) if it exists
for row in range(gridDim):
if grid[row][col_num] == num:
return False
# check if num already exists in its box and return False (for not valid) if it exists
row_box = row_num // boxDim
col_box = col_num // boxDim
for row in range(row_box * boxDim, row_box * boxDim + boxDim):
for col in range(col_box * boxDim, col_box * boxDim + boxDim):
if grid[row][col] == num:
return False
# check if num already exists in its 3x3 box and return False (for not valid) if it exists
# Check box
# box_x = pos[1] // 3
# box_y = pos[0] // 3
# for row in range(box_y*3, box_y*3 + 3):
# for col in range(box_x * 3, box_x*3 + 3):
# if grid[row][col] == num:
# return False
return True
# solve Sudoku puzzle given grid and return solution if it exists
def sudoku_solver(grid):
gridDim = 9
start = 1 # number Sudoku puzzle starts at
empty_pos = find_empty(grid)
# base case
if bool(empty_pos):
row, col = empty_pos
else:
return True # return True if no empty positions exist and thus, solution exists
for n in range(start, gridDim + 1):
if is_valid(n, (row, col), grid):
grid[row][col] = n
if sudoku_solver(grid): # recursive solver call
return True
grid[row][col] = 0 # reset the board
return False
# print sudoku solution if it exists
# otherwise, print statement that no solution found
def print_solution(grid):
if sudoku_solver(grid):
gridDim = 9
for row in range(gridDim):
for col in range(gridDim):
print(grid[row][col], end=' ')
print('') # print nothing to start on new line since default end in print is '\n'
else:
print("No solution found")
# =============================DRIVER CODE========================================
grid = [[0, 0, 3, 0, 0, 0, 0, 0, 9],
[0, 0, 0, 0, 7, 0, 0, 0, 0],
[2, 0, 0, 5, 8, 0, 3, 0, 0],
[0, 8, 0, 1, 5, 0, 0, 0, 4],
[0, 0, 0, 0, 0, 7, 5, 0, 0],
[1, 0, 0, 0, 0, 9, 0, 0, 0],
[0, 4, 0, 0, 0, 0, 0, 6, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[8, 0, 0, 2, 3, 0, 9, 0, 0]]
print_solution(grid)
|
# game model
# - holds global game properties
class Game():
def __init__(self, config):
self.config = config
self.pygame = config.pygame
self.screen = self.pygame.display.set_mode(
(
self.config.SCREEN_PX_WIDTH,
self.config.SCREEN_PX_HEIGHT
)
)
self.clock = self.pygame.time.Clock()
self.running = True
self.restart = True
self.updated = []
def initialize(self):
self.running = True
self.restart = True
def get_running(self):
return self.running
def set_running(self, val):
self.running = val
def get_restart(self):
return self.restart
def set_restart(self, val):
self.restart = val
def init_display(self):
self.pygame.display.update()
|
lexicon_dataset = {
'direction': 'north south east west down up left right back',
'verb': 'go stop kill eat',
'stop': 'the in of from at it',
'noun': 'door bear princess cabinet'
}
def scan(sentence):
result = []
words = sentence.split(' ')
for word in words:
if word.isnumeric():
word = int(word)
tuple = (find_word_type(str(word)), word)
result.append(tuple)
return result
def find_word_type(word):
if word.isnumeric():
return 'number'
for type in lexicon_dataset.keys():
if word in lexicon_dataset[type]:
return type
return 'error'
|
EN_US_CHARSET = (
"`1234567890-=\\"
"qwertyuiop[]"
"asdfghjkl;'"
"zxcvbnm,./"
"~!@#$%^&*()_+|"
"QWERTYUIOP{}"
"ASDFGHJKL:\""
"ZXCVBNM<>?"
" \n"
)
UK_UA_CHARSET = (
"'1234567890-=ґ"
"йцукенгшщзхї"
"фівапролджє"
"ячсмитьбю."
"ʼ!\"№;%:?*()_+Ґ"
"ЙЦУКЕНГШЩЗХЇ"
"ФІВАПРОЛДЖЄ"
"ЯЧСМИТЬБЮ,"
" \n"
)
RU_RU_CHARSET = (
"ё1234567890-=\\"
"йцукенгшщзхъ"
"фывапролджэ"
"ячсмитьбю."
"Ё!\"№;%:?*()_+/"
"ЙЦУКЕНГШЩЗХЪ"
"ФЫВАПРОЛДЖЭ"
"ЯЧСМИТЬБЮ,"
" \n"
)
|
#
# PHASE: unused deps checker
#
# DOCUMENT THIS
#
load(
"@io_bazel_rules_scala//scala/private:rule_impls.bzl",
"get_unused_dependency_checker_mode",
)
def phase_unused_deps_checker(ctx, p):
return get_unused_dependency_checker_mode(ctx)
|
# MÉDIA ESCOLAR
n1 = float(input('Primeira nota: _ '))
n2 = float(input('Segunda nota: _ '))
m = (n1 + n2) / 2
if m < 5:
print('Infelizmente você foi REPROVADO, pois sua média é {:.1f}' .format(m))
elif m >= 5 and m < 7: #elif 5 <= m < 7: _também funcionaria!! mlk
print('Sua média é {} e você está de RECUPERAÇÃO' .format(m))
else:
print('Você foi APROVADO com média {}! Parabéns!' .format(m))
# same as above
# mas com outra lógica de teste
# um pouco mais inteligente, no caso
# mandei bem! rsrsrs
if m > 7:
print('Você foi APROVADO com média {}! Parabéns!'.format(m))
elif m >=5:
print('Sua média é {} e você está de RECUPERAÇÃO'.format(m))
else:
print('Infelizmente você foi REPROVADO, pois sua média é {:.1f}'.format(m))
|
def merge_sorted_arr(left, right):
i = 0
j = 0
new_arr = []
while j < len(right) and i < len(left):
if left[i] < right[j]:
new_arr.append(left[i])
i += 1
elif right[j] <= left[i]:
new_arr.append(right[j])
j += 1
while i < len(left):
new_arr.append(left[i])
i += 1
while j < len(right):
new_arr.append(right[j])
j += 1
return new_arr
def merge_sort(arr):
if len(arr) <= 2:
return arr
pivot = len(arr) // 2
left = merge_sort(arr[:pivot])
right = merge_sort(arr[pivot:])
return merge_sorted_arr(left, right)
if __name__ == "__main__":
assert merge_sorted_arr([1, 3, 5], [2, 4, 12]) == [1, 2, 3, 4, 5, 12]
assert merge_sort([1, 3, 4, 5, 0, 2, 19, 6, 29]) == sorted([1, 3, 4, 5, 0, 2, 19, 6, 29])
|
"""
Security = chave
5ecur1ty = senha
"""
"""hexadecimal:
1= 1
2=2
3=3
até 9=9
10 = A
11 = B
12 = C
13 = D
14 = E
15 = F
"""
chave = input("Digite a base da sua senha: ")
senha = ""
for letra in chave:
if letra in "Aa": senha = senha + "1"
elif letra in "Bb": senha = senha + "@"
elif letra in "Cc": senha = senha + "2"
elif letra in "Dd": senha = senha + "3"
elif letra in "Ee": senha = senha + "4"
elif letra in "Ff": senha = senha + "5"
elif letra in "Rr": senha = senha + "#"
elif letra in "Ss": senha = senha + "%"
elif letra in "Mn": senha = senha + "$"
else: senha = senha + letra
print(senha)
|
{
"targets": [
{
"target_name" : "libtracer",
"type" : "static_library",
"sources" : [
"./libtracer/basic.observer.cpp",
"./libtracer/simple.tracer/simple.tracer.cpp",
"./libtracer/annotated.tracer/TrackingExecutor.cpp",
"./libtracer/annotated.tracer/BitMap.cpp",
"./libtracer/annotated.tracer/annotated.tracer.cpp"
],
"include_dirs": [
"./include",
"./river.format/include",
"<!(echo $RIVER_SDK_DIR)/include/"
],
"conditions": [
["OS==\"linux\"", {
"cflags": [
"-g",
"-m32",
"-std=c++11",
"-D__cdecl=''",
"-D__stdcall=''"
]
}
]
]
}
]
}
|
pet1 = {'name': 'mr.bubbles', "type":'dog', "owner" : 'joe'}
pet2 = {'name': 'spot', "type":'cat', "owner" : 'bob'}
pet3 = {'name': 'chester', "type":'horse', "owner" : 'chloe'}
pets = [pet1, pet2, pet3]
for pet in pets:
print(pet['name'], pet['type'], pet['owner'])
|
'''
Author: ZHAO Zinan
Created: 10. March 2019
1005. Maximize Sum Of Array After K Negations
'''
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A.sort()
for index, a in enumerate(A):
if a <= 0:
if K > 0:
A[index] = -a
K -= 1
if K == 0 or a == 0:
return sum(A)
else:
break
A.sort(reverse = True)
K = K%2
while(K):
A[-K] = -A[-K]
K -= 1
return sum(A)
|
def main():
N, M = map(int, input().split())
a = list(map(int, input().split()))
A = a[-1]
def is_ok(mid):
last = a[0]
count = 1
for i in range(1,N):
if a[i] - last >= mid:
count += 1
last = a[i]
if count >= M:
res = True
else:
res = False
return res
def bisect(ng, ok):
while (abs(ok - ng) > 1):
mid = (ok + ng) // 2
if is_ok(mid):
ok = mid
else:
ng = mid
return ok
ans = bisect(A, 0)
print(ans)
if __name__=='__main__':
main()
|
class AddOperation:
def soma(self, number1, number2):
return number1 + number2
|
GOOGLE_SHEET_URL = (
"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/{table_name}"
)
LOGGING_DICT = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {"standard": {"format": "%(message)s"}},
"handlers": {
"file": {
"level": "INFO",
"class": "logging.handlers.RotatingFileHandler",
"filename": "app.log",
"maxBytes": 1024 * 1024 * 5,
"backupCount": 5,
"formatter": "standard",
},
"console": {
"level": "INFO",
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
"formatter": "standard",
},
},
"loggers": {},
"root": {"handlers": ["file"], "level": "INFO"},
}
|
N = int(input())
A = [int(x) for x in input().split()]
for i in range(N):
for j in range(i, N):
A[i], A[j] = A[j], A[i]
if sorted(A) == A:
print("YES")
quit()
A[i], A[j] = A[j], A[i]
print("NO")
|
"""Top-level package for pycorrel."""
__author__ = """Maxime Godin"""
__email__ = 'maxime.godin@polytechnique.org'
__version__ = '0.1.1'
|
def add_time(start, duration, start_day = ""):
new_time = ""
#24h_hours = 0
# If a user added a starting day, correct the input to be lower
if start_day:
start_day = start_day.lower()
if start_day == 'monday':
start_day_num = 0
elif start_day == 'tuesday':
start_day_num = 1
elif start_day == 'wednesday':
start_day_num = 2
elif start_day == 'thursday':
start_day_num = 3
elif start_day == 'friday':
start_day_num = 4
elif start_day == 'saturday':
start_day_num = 5
elif start_day == 'sunday':
start_day_num = 6
else:
start_day_num = -1
#segmenting out the starting time into hours, mins and the AM or PM
AM_PM = start.split()[1].upper()
start_hours = (start.split()[0]).split(':')[0]
start_mins = (start.split()[0]).split(':')[1]
duration_hours = duration.split(':')[0]
duration_mins = duration.split(':')[1]
mins_24h = int(start_mins) + int(duration_mins)
# Total any multiples of 60 in the mins section over to hours, add 12 hours if we start in the PM (to convert to the 24h time) and add the duration hours
hours_24h = int(start_hours) + (12 * (1 if AM_PM == 'PM' else 0)) + (mins_24h//60) + int(duration_hours)
#print("hours" + str(hours_24h))
#after adding the excess mins to the hours, make the mins equal to only the leftover mins
mins_24h = mins_24h%60
#print("mins" + str(mins_24h))
#make a days count for the "days later" section
days_24h = hours_24h//24
#print("mins" + str(days_24h))
#make the hours 24h equal to the remaining hours after removing the number of days
hours_24h = hours_24h%24
#convert the 24h back into 12h display
AM_PM_12h = ("PM" if hours_24h >= 12 else "AM")
hours_12h = ((hours_24h - 12) if AM_PM_12h == "PM" else hours_24h)
#account for edge case of midnight
if hours_12h == 0:
hours_12h += 12
mins_12h = mins_24h
#construct time part of new_time
new_time = str(hours_12h) + ":" + str(mins_12h).rjust(2,"0") + " " + AM_PM_12h
#add the days past to the day it currently is and remove the multiples of 7 from the total to get the remaining value and thus what day it currently is. convert to string.
if start_day_num >= 0:
end_day_num_12h = ((start_day_num + days_24h)%7)
if end_day_num_12h == 0:
new_time += ", " + "Monday"
elif end_day_num_12h == 1:
new_time += ", " + "Tuesday"
elif end_day_num_12h == 2:
new_time += ", " + "wednesday"
elif end_day_num_12h == 3:
new_time += ", " + "Thursday"
elif end_day_num_12h == 4:
new_time += ", " + "Friday"
elif end_day_num_12h == 5:
new_time += ", " + "Saturday"
elif end_day_num_12h == 6:
new_time += ", " + "Sunday"
#append next day/days later information
if days_24h == 1:
new_time += " (next day)"
elif days_24h > 1:
new_time += " (" + str(days_24h) + " days later)"
return new_time
|
n1 = 36
n2 = 14
m = max(n1, n2)
lcm = n1 * n2
rng = range(m, n1*n2+1)
for i in rng:
if i % n1 == 0 and i % n2 == 0:
print("The lcm is " + str(i))
break
|
test_text="Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz Zhzh Chch Shsh Yoyo Yaya "
replace_table=[
["by","бай"],
["By","Бай"],
["The","Дзе"],
["the","дзе"],
["t'h","дз"],
["T'h","Дз"],
["too","ту"],
["Too","Ту"],
["to","ту"],
["To","Ту"],
["ss","с"],
["cc","кс"],
["Wh","У"],
["pp","п"],
["tt","т"],
["tion","шен"],
["ph","ф"],
["Ph","Ф"],
["q","ку"],
["Q","Ку"],
["zh","ж"],
["Zh","Ж"],
["sh","ш"],
["Sh","Ш"],
["ch","ч"],
["Ch","Ч"],
["you","ю"],
["You","Ю"],
["yo","ю"],
["Yo","Ю"],
["iu","ю"],
["iu","Ю"],
["I ","Я "],
["I'm","Я'м"],
["ya","я"],
["Ya","Я"],
["a","а"],["b","б"],["c","с"],["d","д"],["e","е"],["f","ф"],["g","г"],["h","х"],["i","и"],["j","ж"],["k","к"],["l","л"],["m","м"],["n","н"],["o","о"],["p","п"],["r","р"],["s","с"],["t","т"],["u","у"],["v","в"],["w","у"],["x","с"],["y","й"],["z","з"],["A","А"],["B","Б"],["C","С"],["D","Д"],["E","Е"],["F","Ф"],["G","Г"],["H","Х"],["I","И"],["J","Ж"],["K","К"],["L","Л"],["M","М"],["N","Н"],["O","О"],["P","П"],["R","Р"],["S","С"],["T","Т"],["U","У"],["V","В"],["W","У"],["X","С"],["Y","Й"],["Z","З"],
["''",""],
['"',""],
[" ",""]
]
def main():
cyrillic=input()
for group in replace_table:
cyrillic=cyrillic.replace(group[0],group[1])
print(cyrillic)
if __name__=="__main__":
while True:
main()
|
def add_bias(v):
"""
Inclui bias no vetor de entrada
:param v: vetor de entrada
:return: matriz do vetor de entrada com bias
"""
v_bias = []
if dataset == "Books_attend_grade":
v_bias = [[1] + x for x in v]
else:
for i in v:
v_bias.append([1, i])
return v_bias
def add_bias_quadratic(v):
"""
Inclui bias + quadratico no vetor de entrada
:param v: vetor de entrada
:return: matriz do vetor de entrada com bias e x^2
"""
v_bias = []
for item in v:
if not isinstance(item, list):
v_bias.append([1, item, item ** 2])
else:
quadratic = item.copy()
for col in range(len(item)):
quadratic.append(item[col] ** 2)
v_bias.append([1] + quadratic)
return v_bias
def matrix_transpose(m):
"""
Retorna a matriz transposta
:param m: matriz a ser transposta
:return: resultado da matriz de entrada transposta
"""
if not isinstance(m[0], list):
m = [m]
rows = len(m)
cols = len(m[0])
mt = matrix_empty(cols, rows)
for i in range(rows):
for j in range(cols):
mt[j][i] = m[i][j]
return mt
def matrix_empty(rows, cols):
"""
Cria uma matriz vazia
:param rows: número de linhas da matriz
:param cols: número de colunas da matriz
:return: matriz preenchida com 0.0
"""
M = []
while len(M) < rows:
M.append([])
while len(M[-1]) < cols:
M[-1].append(0.0)
return M
def vector_empty(rows):
"""
Cria um vetor vazio
:param rows: número de linhas do vetor
:return: vetor preenchido com 0.0
"""
M = []
while len(M) < rows:
M.append(0.0)
return M
def matrix_multiply(a, b):
"""
Retorna o produto da multiplicação da matriz a com b
:param a: primeira matriz
:param b: segunda matriz
:return: matriz resultante
"""
rows_a = len(a)
cols_a = len(a[0])
rows_b = len(b)
cols_b = len(b[0])
if cols_a != rows_b:
raise ArithmeticError('O número de colunas da matriz a deve ser igual ao número de linhas da matriz b.')
result_matrix = matrix_empty(rows_a, cols_b)
for i in range(rows_a):
for j in range(cols_b):
total = 0
for ii in range(cols_a):
total += a[i][ii] * b[ii][j]
result_matrix[i][j] = total
return result_matrix
def matrix_vector_multiply(matrix, vector):
"""
Retorna o produto da multiplicação da matriz com o vetor
:param matrix: matriz
:param vector: vetor
:return: vetor resultante
"""
rows_matrix = len(matrix)
cols_matrix = len(matrix[0])
if cols_matrix != len(vector):
raise ArithmeticError('O número de colunas da matriz deve ser igual ao número de linhas do vetor.')
output = vector_empty(rows_matrix)
for i in range(rows_matrix):
for j in range(cols_matrix):
output[i] += matrix[i][j] * vector[j]
return output
def matrix_minor(m, i, j):
return [row[:j] + row[j + 1:] for row in (m[:i] + m[i + 1:])]
def matrix_determinant(m):
# caso especial para matriz 2x2
if len(m) == 2:
return m[0][0] * m[1][1] - m[0][1] * m[1][0]
determinant = 0
for c in range(len(m)):
determinant += ((-1) ** c) * m[0][c] * matrix_determinant(matrix_minor(m, 0, c))
return determinant
def matrix_inverse(m):
determinant = matrix_determinant(m)
# caso especial para matriz 2x2
if len(m) == 2:
return [[m[1][1] / determinant, -1 * m[0][1] / determinant],
[-1 * m[1][0] / determinant, m[0][0] / determinant]]
# calcular matriz de cofatores
cofactors = []
for r in range(len(m)):
cofactorRow = []
for c in range(len(m)):
minor = matrix_minor(m, r, c)
cofactorRow.append(((-1) ** (r + c)) * matrix_determinant(minor))
cofactors.append(cofactorRow)
cofactors = matrix_transpose(cofactors)
for r in range(len(cofactors)):
for c in range(len(cofactors)):
cofactors[r][c] = cofactors[r][c] / determinant
return cofactors
def weigthing(weight_list, x_list):
"""
Retorna vetor com x * pesos
:param weight_list: pesos
:param x_list: x
:return: vetor resultante
"""
rows_x = len(x_list)
for i in range(rows_x):
if isinstance(x_list[0], list):
for j in range(len(x_list[i])):
x_list[i][j] = x_list[i][j] * weight_list[i]
else:
x_list[i] = x_list[i] * weight_list[i]
return x_list
def calculate_beta(x_bias):
"""
Retorna o vetor com beta calculado
:param x_bias: x já com bias
:return: vetor resultante
"""
x_bias_t = matrix_transpose(x_bias)
Xt_X = matrix_multiply(x_bias_t, x_bias)
Xt_Y = matrix_vector_multiply(x_bias_t, y_input)
Xt_X_i = matrix_inverse(Xt_X)
beta = matrix_vector_multiply(Xt_X_i, Xt_Y)
return beta
def regression(input_regression):
"""
Retorna a estimativa da regressão
:param input_regression: entrada que precisa ser estimada
:return: estimativa resultante
"""
x_bias = add_bias(x_input)
beta = calculate_beta(x_bias)
regression_result = matrix_vector_multiply(input_regression, beta)
return regression_result
def regression_quadratic(input_regression):
"""
Retorna a estimativa da regressão quadratica
:param input_regression: entrada que precisa ser estimada
:return: estimativa resultante
"""
x_bias = add_bias_quadratic(x_input)
beta = calculate_beta(x_bias)
regression_result = matrix_vector_multiply(input_regression, beta)
return regression_result
def regression_weighted(input_regression):
"""
Retorna a estimativa da regressão quadratica
:param input_regression: entrada que precisa ser estimada
:return: estimativa resultante
"""
x_bias = add_bias(x_input)
beta = calculate_beta(x_bias)
weight_vector = weight(x_bias, y_input, beta)
x_bias_weighted = weigthing(weight_vector, x_input)
x_bias_weighted = add_bias(x_bias_weighted)
x_bias_t = matrix_transpose(x_bias_weighted)
Xt_X = matrix_multiply(x_bias_t, x_bias_weighted)
y_weighted = weigthing(weight_vector, y_input)
Xt_Y = matrix_vector_multiply(x_bias_t, y_weighted)
Xt_X_i = matrix_inverse(Xt_X)
beta = matrix_vector_multiply(Xt_X_i, Xt_Y)
regression_result = matrix_vector_multiply(input_regression, beta)
return regression_result
def weight(x, y, beta):
"""
Retorna o cálculo dos pesos
:param x: entradas
:param y: saídas
:param beta: beta calculado
:return: vetor com pesos calculados
"""
weight = []
x_beta = matrix_vector_multiply(x, beta)
size = len(x_beta)
for i in range(size):
w = 1 / (y[i] - x_beta[i])
weight.append(abs(w))
return weight
def load_file(filename):
f = open("data/" + filename + ".txt")
lines = f.readlines()
for line in lines:
if filename == "Books_attend_grade":
x0, x1, y = line.split(";")
x_input.append([float(x0), float(x1)])
y_input.append(float(y))
else:
line = line.strip("\n")
x, y = line.split(";")
x_input.append(float(x))
y_input.append(float(y))
# teste com height_shoesize
x_input = []
y_input = []
dataset = "height_shoesize"
load_file(dataset)
height_shoesize_estimation = regression([[1, 70]])
height_shoesize_estimation_quadratic = regression_quadratic([[1, 70, 70 ** 2]])
height_shoesize_estimation_robust = regression_weighted([[1, 70]])
print("height_shoesize_estimation: ", height_shoesize_estimation)
print("height_shoesize_estimation_quadratic: ", height_shoesize_estimation_quadratic)
print("height_shoesize_estimation_robust: ", height_shoesize_estimation_robust)
print("******************************")
# teste com US_Census
x_input = []
y_input = []
dataset = "US_Census"
load_file(dataset)
us_census_estimation = regression([[1, 2010]])
us_census_estimation_quadratic = regression_quadratic([[1, 2010, 2010 ** 2]])
us_census_estimation_robust = regression_weighted([[1, 2010]])
print("us_census_estimation: ", us_census_estimation)
print("us_census_estimation_quadratic: ", us_census_estimation_quadratic)
print("us_census_estimation_robust: ", us_census_estimation_robust)
print("******************************")
# teste com alpswater
x_input = []
y_input = []
dataset = "alpswater"
load_file(dataset)
alpswater_estimation = regression([[1, 31.06]])
alpswater_estimation_quadratic = regression_quadratic([[1, 31.06, 31.06 ** 2]])
alpswater_estimation_robust = regression_weighted([[1, 31.06]])
print("alpswater_estimation: ", alpswater_estimation)
print("alpswater_estimation_quadratic: ", alpswater_estimation_quadratic)
print("alpswater_estimation_robust: ", alpswater_estimation_robust)
print("******************************")
# teste com Books_attend_grade
x_input = []
y_input = []
dataset = "Books_attend_grade"
load_file(dataset)
books_attend_grade_estimation = regression([[1, 2, 15]])
books_attend_grade_estimation_quadratic = regression_quadratic([[1, 2, 15, 2 ** 2, 15 ** 2]])
books_attend_grade_estimation_robust = regression_weighted([[1, 2, 15]])
print("books_attend_grade_estimation: ", books_attend_grade_estimation)
print("books_attend_grade_estimation_quadratic: ", books_attend_grade_estimation_quadratic)
print("books_attend_grade_estimation_robust: ", books_attend_grade_estimation_robust)
print("******************************")
|
# take linear julia list of lists and convert to julia array format
execfile('../pyprgs/in_out_line.py')
execfile('../pyprgs/in_out_csv.py')
dat1 = lin.reader("../poets/results_poets/cross_validation/EC1.dat")
dat2 = lin.reader("../poets/results_poets/cross_validation/EC2.dat")
dat3 = lin.reader("../poets/results_poets/cross_validation/EC3.dat")
dat4 = lin.reader("../poets/results_poets/cross_validation/EC4.dat")
dat5 = lin.reader("../poets/results_poets/cross_validation/EC5.dat")
dat6 = lin.reader("../poets/results_poets/cross_validation/EC6.dat")
dat7 = lin.reader("../poets/results_poets/cross_validation/EC7.dat")
dat8 = lin.reader("../poets/results_poets/cross_validation/EC8.dat")
dat9 = lin.reader("../poets/results_poets/cross_validation/EC9.dat")
dat10 = lin.reader("../poets/results_poets/cross_validation/EC10.dat")
dat11 = lin.reader("../poets/results_poets/cross_validation/EC11.dat")
# map X1 (size e.g. 772) to x1 within x2 from X2 (size 11)
def julia_listlist_to_array(dat):
dat_new = [[],[],[],[],[],[],[],[],[],[],[]] # number of objectives (x2space)
counter = 0
for LINE in dat:
if LINE.count('[') == 1:
counter = 0
dat_new[counter].append(LINE.replace('[','').replace(']',''))
counter = counter + 1
outlines = []
for LIST in dat_new:
outlines.append('\t'.join(LIST))
return outlines
outlines = julia_listlist_to_array(dat1)
lin.writer("../poets/results_poets/cross_validation/EC1_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat2)
lin.writer("../poets/results_poets/cross_validation/EC2_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat3)
lin.writer("../poets/results_poets/cross_validation/EC3_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat4)
lin.writer("../poets/results_poets/cross_validation/EC4_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat5)
lin.writer("../poets/results_poets/cross_validation/EC5_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat6)
lin.writer("../poets/results_poets/cross_validation/EC6_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat7)
lin.writer("../poets/results_poets/cross_validation/EC7_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat8)
lin.writer("../poets/results_poets/cross_validation/EC8_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat9)
lin.writer("../poets/results_poets/cross_validation/EC9_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat10)
lin.writer("../poets/results_poets/cross_validation/EC10_jl_array.dat",outlines)
outlines = julia_listlist_to_array(dat11)
lin.writer("../poets/results_poets/cross_validation/EC11_jl_array.dat",outlines)
# need to reformat random as well
datr = lin.reader("../poets/results_poets/random_set/EC.dat")
outlines = julia_listlist_to_array(datr)
lin.writer("../poets/results_poets/random_set/EC_jl_array.dat",outlines)
datrf = lin.reader("../poets/results_poets/random_set/EC_full.dat")
outlines = julia_listlist_to_array(datrf)
lin.writer("../poets/results_poets/random_set/EC_full_jl_array.dat",outlines)
#for line in dat:
# dat_new.append([float(string.replace('[' ,'').replace(']','')) for string in line])
#datx = lin.reader("../poets/results_poets/cross_validation/fold_pop_obj_1/EC.dat")
|
#!/usr/bin/env python3
#coding: utf-8
### 1st line allows to execute this script by typing only its name in terminal, with no need to precede it with the python command
### 2nd line declaring source code charset should be not necessary but for exemple pydoc request it
__doc__ = "3D obj file loader"#information describing the purpose of this module
__status__ = "Development"#should be one of 'Prototype' 'Development' 'Production' 'Deprecated' 'Release'
__version__ = "2.0.0"# version number,date or about last modification made compared to the previous version
__license__ = "public domain"# ref to an official existing License
__date__ = "2010"#started creation date / year month day
__author__ = "N-zo syslog@laposte.net"#the creator origin of this prog,
__maintainer__ = "Nzo"#person who curently makes improvements, replacing the author
__credits__ = []#passed mainteners and any other helpers
__contact__ = "syslog@laposte.net"# current contact adress for more info about this file
def load_obj_file(filepath):
"""read 3D obj file and return data"""
#obj_file_list=[]
objet={}
vertex_list=[]
vertice_list=[]
normal_list=[]
surface_mat={}
group=''
data_file=open(filepath,'r')
for line in data_file.readlines() :
if line.startswith('#'):
continue
data=string.split(line)
if not len(data)==0 :
signal=data[0]
if signal=='v' :
vertice_list.append( map(float, values[1:4]) )
elif signal=='vt' :
vertex_list.append( map(float, values[1:3]) )
elif signal=='vn':
normal_list.append( map(float, values[1:4]) )
elif values[0] == 's':
# smoothing-group not currently supported
pass
elif signal=='f' :
a=map(int,string.split(data[1],'/'))
b=map(int,string.split(data[2],'/'))
c=map(int,string.split(data[3],'/'))
face=(tuple(a),tuple(b),tuple(c))
face_list.append(face)
elif signal in ('usemtl', 'usemat') :
material_name=data[1]
if not surface_mat.has_key(material_name) :
new_face_list=[]
surface_mat[material_name]=new_face_list
face_list=surface_mat[material_name]
elif signal=='mtllib' :
mat_lib=data[1]
elif signal=='g' :
group=data[1]
elif signal=='o' :
name=data[1]
else :
warning("signal inconu: "+signal)
data_file.close()
objet={
"name":name,
"group":group,
"mat_lib":mat_lib,
"vertex_list":vertex_list,
"vertice_list":vertice_list,
"normal_list":normal_list,
"surface_mat":surface_mat
}
return objet
|
# Quick Sort
# Randomize Pivot to avoid worst case, currently pivot is last element
def quickSort(A, si, ei):
if si < ei:
pi = partition(A, si, ei)
quickSort(A, si, pi-1)
quickSort(A, pi+1, ei)
# Partition
# Utility function for partitioning the array(used in quick sort)
def partition(A, si, ei):
x = A[ei] # x is pivot, last element
i = (si-1)
for j in range(si, ei):
if A[j] <= x:
i += 1
A[i], A[j] = A[j], A[i]
A[i+1], A[ei] = A[ei], A[i+1]
return i+1
#'Alternate Implementation'
# Warning --> As this function returns the array itself, assign it to some
# variable while calling. Example--> sorted_arr=quicksort(arr)
# Quick sort
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) / 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
|
# -*- coding:utf-8 -*-
"""
@file name: __init__.py.py
Created on 2019/5/14
@author: kyy_b
@desc:
"""
if __name__ == "__main__":
pass
|
class Proxy():
proxies = [] # Will contain proxies [ip, port]
#### adding proxy information so as not to get blocked so fast
def getProxyList(self):
# Retrieve latest proxies
url = 'https://www.sslproxies.org/'
header = {'User-Agent': str(ua.random)}
response = requests.get(url, headers=header)
soup = BeautifulSoup(response.text, 'lxml')
proxies_table = soup.find(id='proxylisttable')
try:
# Save proxies in the array
for row in proxies_table.tbody.find_all('tr'):
self.proxies.append({
'ip': row.find_all('td')[0].string,
'port': row.find_all('td')[1].string
})
except:
print("error in getting proxy from ssl proxies")
return proxies
def getProxyList2(self,proxies):
# Retrieve latest proxies
try:
url = 'http://list.proxylistplus.com/SSL-List-1'
header = {'User-Agent': str(ua.random)}
response = requests.get(url, headers=header)
soup = BeautifulSoup(response.text, 'lxml')
proxies_table = soup.find("table", {"class": "bg"})
#print(proxies_table)
# Save proxies in the array
for row in proxies_table.find_all("tr", {"class": "cells"}):
google = row.find_all('td')[5].string
if google == "yes":
#print(row.find_all('td')[1].string)
self.proxies.append({
'ip': row.find_all('td')[1].string,
'port': row.find_all('td')[2].string
})
except:
print("broken")
# Choose a random proxy
try:
url = 'http://list.proxylistplus.com/SSL-List-2'
header = {'User-Agent': str(ua.random)}
response = requests.get(url, headers=header)
soup = BeautifulSoup(response.text, 'lxml')
proxies_table = soup.find("table", {"class": "bg"})
# print(proxies_table)
# Save proxies in the array
for row in proxies_table.find_all("tr", {"class": "cells"}):
google = row.find_all('td')[5].string
if google == "yes":
#print(row.find_all('td')[1].string)
self.proxies.append({
'ip': row.find_all('td')[1].string,
'port': row.find_all('td')[2].string
})
except:
print("broken")
return proxies
def getProxy(self):
proxies = self.getProxyList()
proxies = self.getProxyList2(proxies)
proxy = random.choice(proxies)
return proxy
#### end proxy info added by ML
|
input = """
mysum(X) :- #sum{P: c(P)} = X, dom(X).
mycount(X) :- #count{P: c(P)} = X, dom(X).
dom(0). dom(1).
c(X) | d(X) :- dom(X).
:- not c(0).
:- not c(1).
"""
output = """
mysum(X) :- #sum{P: c(P)} = X, dom(X).
mycount(X) :- #count{P: c(P)} = X, dom(X).
dom(0). dom(1).
c(X) | d(X) :- dom(X).
:- not c(0).
:- not c(1).
"""
|
file = open("nomes.txt", "r")
lines = file.readlines()
title = lines[0]
names = title.strip().split(",")
print(names)
for i in lines[1:]:
aux = i.strip().split(",")
print('{}{:>5}{:>8}'.format(aux[0], aux[1], aux[2]))
|
x = 50
def funk():
global x
print("x je ", x)
x = 2
print("Promjena globalne vrijednost promjeljive x na ", x)
funk()
print("Vrijednost promjeljive x sada je ", x)
|
# https://leetcode.com/contest/weekly-contest-132/problems/maximum-difference-between-node-and-ancestor/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.max = 0
self.min = 10000
def maxAncestorDiff(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.findMaxDiff(root ,10000 ,0)
def iq_test(self,numbers):
# your code here
even = []
odd = []
numbers = list(numbers.split(" "))
for i in range(0,len(numbers)):
if numbers[i] % 2 == 0:
even.append((i + 1, numbers[i]))
else:
odd.append((i + 1, numbers[i]))
if len(even) == 1:
return even[0][0]
else:
return odd[0][0]
def findMaxDiff(self ,root ,mn ,mx):
if not root:
return mx -mn
mx = max(mx ,root.val)
mn = min(mn ,root.val)
print(mx ,mn)
a = self.findMaxDiff(root.left ,mn ,mx)
b = self.findMaxDiff(root.right ,mn ,mx)
print(a ,b ,max(a ,b))
return max(a ,b)
# def findMaxDiff(self,root):
# if not root:
# return 10000
# if not root.left and not root.right:
# return root.val
# val = min(self.findMaxDiff(root.left),self.findMaxDiff(root.right))
# print(val)
# diff = abs(root.val-val)
# self.max = max(self.max, diff)
# print(self.max)
# return min(root.val,val)
|
def main():
lista = []
while True:
a = int(input(f'Digite o primeiro número: '))
if a == 0:
break
lista.append(a)
print(lista)
lista_a = comprimento(lista)
print(lista_a)
lista_b = inverter(lista)
print(lista_b)
lista_c = minimo(lista)
print(lista_c)
lista_d = maxino(lista)
print(lista_d)
lista_e = soma(lista)
print(lista_e)
def comprimento(lista):
cont = 0
for compri in lista:
cont += 1
return cont
def inverter(lista):
lista_b = lista[::-1]
return lista_b
def minimo(lista):
menor = lista[0]
for a in lista:
if a < menor:
menor = a
return menor
def maxino(lista):
maior = lista[0]
for a in lista:
if a > maior:
maior = a
return maior
def soma(lista):
s = 0
for elementos in lista:
s += elementos
return s
if __name__ == '__main__':
main()
|
"""
project_month01/game_2048_core.py
2048 游戏核心算法
"""
# 1. 定义零元素后移函数
# [2,0,0,2] --> [2,2,0,0]
# [2,0,4,2] --> [2,4,2,0]
# 14:10
list_merge =[2,16,0,4]
def zero_to_end():
# 思想:从后向前,如果是零元素,删除后末尾追加零.
for i in range(len(list_merge) - 1, -1, -1):
if list_merge[i] == 0:
del list_merge[i]
list_merge.append(0)
# 测试...
# zero_to_end()
# print(list_merge)
#2. 定义合并相同元素的函数
# [2,2,0,0] --> [4,0,0,0]
# [2,0,0,2] --> [4,0,0,0]
# [2,0,2,2] --> [4,2,0,0]
# [0,2,2,4] --> [4,4,0,0]
# [2,2,2,2] --> [4,4,0,0]
# 14:32
def merge():
zero_to_end()
for i in range(len(list_merge)-1):#0 1 2
# 如果相邻 还 相同
if list_merge[i] == list_merge[i+1]:
list_merge[i] *=2
del list_merge[i+1]
list_merge.append(0)
# merge()
# print(list_merge)
# 3. 向左移动
map = [
[2,0,0,2],
[2,2,0,4],
[0,4,0,4],
[2,2,2,0],
]
def move_left():
global list_merge
for line in map:
list_merge = line
merge()
# move_left()
# print(map)
# 4. 向右移动
def move_right():
global list_merge
for line in map:
# 切片会产生新列表
list_merge = line[::-1]
# 合并操作的就是新列表
merge()
# 将新列表中的数据赋值给map中的行
line[::-1] = list_merge
# move_right()
# print(map)
# 5. 向上移动
def move_up():
square_matrix_transpose()
move_left()
square_matrix_transpose()
# 6. 向下移动
def move_down():
square_matrix_transpose()
move_right()
square_matrix_transpose()
def square_matrix_transpose():
"""
矩阵转置
"""
for c in range(1, len(map)):
for r in range(c, len(map)):
map[r][c - 1], map[c - 1][r] = map[c - 1][r], map[r][c - 1]
# move_down()
# print(map)
|
# 列表 list
L1 = []
L2 = [1, 2, 3, 4]
L3 = ['1', 2, '3', 'hello']
L4 = [L1, L2, L3]
L4[2][3] = 'world'
# 通过迭代创建list
L5 = list(range(1, 11))
print(L4)
print(L5)
# 可加
print(L2 + L3)
# 可乘
print(L2 * 2)
|
# Each new term in the Fibonacci sequence is generated by adding
# the previous two terms. By starting with 1 and 2, the first 10
# terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values
# do not exceed four million, find the sum of the even-valued terms.
def fib_sum(limit):
return fib_calc(limit,0,1,0)
def fib_calc(limit, a, b, accum):
if b > limit:
return accum
else:
if b % 2 == 0:
accum += b
return fib_calc(limit, b, (a+b), accum)
if __name__ == "__main__":
print(fib_sum(4000000))
|
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Gregorian'},
{'abbr': 1, 'code': 1, 'title': '360-day'},
{'abbr': 2, 'code': 2, 'title': '365-day'},
{'abbr': 3, 'code': 3, 'title': 'Proleptic Gregorian'},
{'abbr': None, 'code': 255, 'title': 'Missing'})
|
#
# PySNMP MIB module ZXR10-VSWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZXR10-VSWITCH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:42:32 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)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion")
EntryStatus, = mibBuilder.importSymbols("RMON-MIB", "EntryStatus")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, ObjectIdentity, Unsigned32, iso, MibIdentifier, IpAddress, NotificationType, Integer32, TimeTicks, Counter32, Gauge32, Bits, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "ObjectIdentity", "Unsigned32", "iso", "MibIdentifier", "IpAddress", "NotificationType", "Integer32", "TimeTicks", "Counter32", "Gauge32", "Bits", "enterprises")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
zte = MibIdentifier((1, 3, 6, 1, 4, 1, 3902))
zxr10 = MibIdentifier((1, 3, 6, 1, 4, 1, 3902, 3))
zxr10protocol = MibIdentifier((1, 3, 6, 1, 4, 1, 3902, 3, 101))
zxr10vswitch = ModuleIdentity((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4))
if mibBuilder.loadTexts: zxr10vswitch.setLastUpdated('0408031136Z')
if mibBuilder.loadTexts: zxr10vswitch.setOrganization('ZXR10 ROS OAM group')
class DisplayString(OctetString):
pass
class VsiwtchTransMode(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2))
namedValues = NamedValues(("ip", 0), ("vlan", 1), ("mix", 2))
class VsiwtchVlanDirection(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1))
namedValues = NamedValues(("intoout", 0), ("both", 1))
zxr10vswitchIfTable = MibTable((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1), )
if mibBuilder.loadTexts: zxr10vswitchIfTable.setStatus('current')
zxr10vswitchIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1), ).setIndexNames((0, "ZXR10-VSWITCH-MIB", "zxr10vsiwtchIfIndex"))
if mibBuilder.loadTexts: zxr10vswitchIfEntry.setStatus('current')
zxr10vsiwtchIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vsiwtchIfIndex.setStatus('current')
zxr10vswitchIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfType.setStatus('current')
zxr10vswitchIfTransType = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 3), VsiwtchTransMode()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfTransType.setStatus('current')
zxr10vswitchIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfStatus.setStatus('current')
zxr10vswitchIfAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 5), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfAddr.setStatus('current')
zxr10vswitchIfDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zxr10vswitchIfDesc.setStatus('current')
zxr10vswitchIfTableLastchange = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 2), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfTableLastchange.setStatus('current')
zxr10vswitchVlanTable = MibTable((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3), )
if mibBuilder.loadTexts: zxr10vswitchVlanTable.setStatus('current')
zxr10vsiwtchVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1), ).setIndexNames((0, "ZXR10-VSWITCH-MIB", "zxr10vswitchVlanIngressIfIndex"), (0, "ZXR10-VSWITCH-MIB", "zxr10vswitchVlanIngressExtVlanid"))
if mibBuilder.loadTexts: zxr10vsiwtchVlanEntry.setStatus('current')
zxr10vswitchVlanIngressExtVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanIngressExtVlanid.setStatus('current')
zxr10vswitchVlanIngressIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanIngressIfIndex.setStatus('current')
zxr10vswitchVlanIngressIntVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanIngressIntVlanid.setStatus('current')
zxr10vswitchVlanEgressExtVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanEgressExtVlanid.setStatus('current')
zxr10vswitchVlanEgressIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanEgressIfIndex.setStatus('current')
zxr10vswitchVlanEgressIntVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanEgressIntVlanid.setStatus('current')
zxr10vswitchVlanVlanidRange = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 7), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanVlanidRange.setStatus('current')
zxr10vswitchVlandDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 8), VsiwtchVlanDirection()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlandDirection.setStatus('current')
zxr10vswitchVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 9), EntryStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanRowStatus.setStatus('current')
zxr10vswitchVlanDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 10), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanDesc.setStatus('current')
zxr10vswitchVlanTableLastchange = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanTableLastchange.setStatus('current')
mibBuilder.exportSymbols("ZXR10-VSWITCH-MIB", zxr10vswitchVlanTable=zxr10vswitchVlanTable, zxr10vswitchVlandDirection=zxr10vswitchVlandDirection, VsiwtchTransMode=VsiwtchTransMode, zxr10vsiwtchIfIndex=zxr10vsiwtchIfIndex, zxr10vswitchIfTableLastchange=zxr10vswitchIfTableLastchange, zxr10vswitchVlanEgressExtVlanid=zxr10vswitchVlanEgressExtVlanid, zxr10vswitchIfStatus=zxr10vswitchIfStatus, zxr10vswitchIfDesc=zxr10vswitchIfDesc, DisplayString=DisplayString, zxr10vswitchIfTransType=zxr10vswitchIfTransType, zte=zte, zxr10vswitchVlanEgressIntVlanid=zxr10vswitchVlanEgressIntVlanid, zxr10vswitch=zxr10vswitch, zxr10vswitchVlanIngressIntVlanid=zxr10vswitchVlanIngressIntVlanid, zxr10vswitchVlanDesc=zxr10vswitchVlanDesc, zxr10vswitchVlanTableLastchange=zxr10vswitchVlanTableLastchange, zxr10vswitchVlanRowStatus=zxr10vswitchVlanRowStatus, zxr10vswitchVlanVlanidRange=zxr10vswitchVlanVlanidRange, VsiwtchVlanDirection=VsiwtchVlanDirection, zxr10protocol=zxr10protocol, zxr10vswitchVlanEgressIfIndex=zxr10vswitchVlanEgressIfIndex, zxr10vswitchIfType=zxr10vswitchIfType, zxr10vswitchIfEntry=zxr10vswitchIfEntry, zxr10vswitchIfAddr=zxr10vswitchIfAddr, zxr10vswitchIfTable=zxr10vswitchIfTable, zxr10=zxr10, PYSNMP_MODULE_ID=zxr10vswitch, zxr10vswitchVlanIngressExtVlanid=zxr10vswitchVlanIngressExtVlanid, zxr10vswitchVlanIngressIfIndex=zxr10vswitchVlanIngressIfIndex, zxr10vsiwtchVlanEntry=zxr10vsiwtchVlanEntry)
|
del_items(0x80122A40)
SetType(0x80122A40, "struct Creds CreditsTitle[6]")
del_items(0x80122BE8)
SetType(0x80122BE8, "struct Creds CreditsSubTitle[28]")
del_items(0x80123084)
SetType(0x80123084, "struct Creds CreditsText[35]")
del_items(0x8012319C)
SetType(0x8012319C, "int CreditsTable[224]")
del_items(0x801243BC)
SetType(0x801243BC, "struct DIRENTRY card_dir[16][2]")
del_items(0x801248BC)
SetType(0x801248BC, "struct file_header card_header[16][2]")
del_items(0x801242E0)
SetType(0x801242E0, "struct sjis sjis_table[37]")
del_items(0x801297BC)
SetType(0x801297BC, "unsigned char save_buffer[106496]")
del_items(0x80129724)
SetType(0x80129724, "struct FeTable McLoadGameMenu")
del_items(0x80129704)
SetType(0x80129704, "char *CharFileList[5]")
del_items(0x80129718)
SetType(0x80129718, "char *Classes[3]")
del_items(0x80129740)
SetType(0x80129740, "struct FeTable McLoadCharMenu")
del_items(0x8012975C)
SetType(0x8012975C, "struct FeTable McLoadCard1Menu")
del_items(0x80129778)
SetType(0x80129778, "struct FeTable McLoadCard2Menu")
|
# -*- coding: utf-8 -*-
class RegisterException(Exception):
"""Exception raised on a registration error."""
|
has_high_income = True
has_good_credit = True
has_criminal_record = False
if has_high_income and has_good_credit:
print("Eligible for loan")
if has_high_income or has_good_credit:
print("Eligible for consultation")
if has_good_credit and not has_criminal_record:
print("Eligible for credit card")
|
#1
def print_factors(n):
#2
for i in range(1, n+1):
#3
if n % i == 0:
print(i)
#4
number = int(input("Enter a number : "))
#5
print("The factors for {} are : ".format(number))
print_factors(number)
|
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# Viikkotehtävä 6, videovuokraamon käyttöliittymän kontrolleri
# date: 9.11.2016
# authot: Toni Pikkarainen
# -------------------------------------------------------------------------
@auth.requires_login()
def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if you need a simple wiki simply replace the two lines below with:
return auth.wiki()
"""
#response.flash = T("Hello World")
#return dict(message=T('Welcome to web2py!'))
redirect(URL('vuokraukset'))
# Lisää uuden vuokrauksen
@auth.requires_login()
def uusivuokraus():
response.title = "Lisää uusi vuokraus"
if request.get_vars['id'] != None:
vuokraus = db.vuokraus( request.get_vars['id'] )
form = SQLFORM(db.vuokraus, vuokraus, showid=False)
form.add_button('Delete', URL('poistavuokraus',vars=dict(id=request.get_vars['id'])))
else:
form = SQLFORM(db.vuokraus)
if form.process().accepted:
response.flash = 'Vuokraus on lisätty/muokattu'
elif form.errors:
response.flash = 'Lomakkeen tiedoissa on virheitä'
else:
response.flash = 'Täytä lomake lisätäksesi uuden vuokrauksen(/muokataksesi vuokrausta)'
return dict(lomake=form)
# Lisää uuden elokuvan
@auth.requires_login()
def uusielokuva():
response.title = "Lisää uusi elokuva"
elokuvat = db().select(db.elokuva.ALL)
if request.get_vars['id'] != None:
elokuva = db.elokuva( request.get_vars['id'] )
form = SQLFORM(db.elokuva, elokuva, showid=False)
form.add_button('Delete', URL('poistaelokuva',vars=dict(id=request.get_vars['id'])))
else:
form = SQLFORM(db.elokuva)
if form.process().accepted:
response.flash = 'Elokuva on lisätty/muokattu'
elif form.errors:
response.flash = 'Lomakkeen tiedoissa on virheitä'
else:
response.flash = 'Täytä lomake lisätäksesi uuden elokuvan (/muokataksesi elokuvaa)'
return dict(lomake=form,elokuvat=elokuvat)
# Lisää uuden jäsenen
@auth.requires_login()
def uusijasen():
response.title = "Lisää uusi jäsen"
if request.get_vars['id'] != None:
jasen = db.jasen( request.get_vars['id'] )
form = SQLFORM(db.jasen, jasen, showid=False)
form.add_button('Delete', URL('poistajasen',vars=dict(id=request.get_vars['id'])))
else:
form = SQLFORM(db.jasen)
if form.process().accepted:
response.flash = 'Jäsen on lisätty/muokattu'
elif form.errors:
response.flash = 'Lomakkeen tiedoissa on virheitä'
else:
response.flash = 'Täytä lomake lisätäksesi uuden jäsenen (/muokataksesi jäsentä)'
return dict(lomake=form)
# Poistaa elokuvan, jos voi.
@auth.requires_login()
def poistaelokuva():
eid = request.get_vars['id']
if not db(db.vuokraus.elokuvaid == eid).select(db.vuokraus):
db(db.elokuva.id == eid).delete()
response.flash = 'Elokuva on poistettu'
redirect(URL('uusielokuva'))
response.flash = 'Poisto ei onnistunut'
redirect(URL('uusielokuva'))
# Poistaa vuokrauksen, jos voi.
@auth.requires_login()
def poistavuokraus():
vid = request.get_vars['id']
db(db.vuokraus.id == vid).delete()
redirect(URL('uusivuokraus'))
# Poistaa jäsenen, jos voi.
@auth.requires_login()
def poistajasen():
jid = request.get_vars['id']
if not db(db.vuokraus.jasenid == jid).select(db.vuokraus):
db(db.jasen.id == jid).delete()
redirect(URL('vuokraukset'))
redirect(URL('vuokraukset'))
# Listaa elokuvat ja niiden vuokraukset
# lajiteltuna niiden vuokrausmäärän mukaan
@auth.requires_login()
def elokuvat():
response.title = "Elokuvat"
elokuvat=[]
kaikki_el = db().select(db.elokuva.ALL)
for e in kaikki_el:
lkm=db(db.vuokraus.elokuvaid == e.id).count()
elokuvat.append(dict(nimi=e.nimi, lkm=lkm,id=e.id))
# Lajittelu tehty pythonilla, koska en osannut kiertää
# tämän non-relational -db:n rajoitteita liittyen
# Taulu linkittämiseen keskenään.
elokuvat.sort(key=lambda x: x['lkm'], reverse=True)
return dict(elokuvat=elokuvat)
# Jäsenet-sivu. Ei vielä kovin hyvä kokonaisuus.
@auth.requires_login()
def jasenet():
response.title = "Jäsenet"
jasenet=db().select(db.jasen.ALL)
return dict(jasenet=jasenet)
# Käytetään jäsenet-sivulla, tämä kokonaisuus ei vielä ole kovin hyvä.
@auth.requires_login()
def naytavuokraukset():
if request.get_vars['id'] != None:
jasenid=request.get_vars['id']
jasen=db.jasen(jasenid)
vuokraukset=[]
vuokraukset_jasen = db(db.vuokraus.jasenid == jasenid).select(db.vuokraus, orderby=db.vuokraus.vuokrauspvm)
# tiettyyn vuokraukseen liittyvä elokuva
for v in vuokraukset_jasen:
elokuva = db(db.elokuva.id == v.elokuvaid).select(db.elokuva.ALL).first()
#vuokraukset.append(dict(jasen=j, elokuva=elokuva, vuokraus=v))
vuokraukset.append(dict(elokuva=elokuva, vuokraus=v))
return dict(vuokraukset=vuokraukset, jasen=jasen)
else:
redirect(URL('jasenet'))
# Ei oikein hyvä, mutta tällä hetkellä mennään tällä
@auth.requires_login()
def vuokrauslomake():
if request.get_vars['id'] != None:
vuokraus = db.vuokraus( request.get_vars['id'] )
form = SQLFORM(db.vuokraus, vuokraus, showid=False,buttons=[INPUT(_type='submit'),INPUT(_type='hidden', _name="_formname", _value="test")])
else:
form = SQLFORM(db.vuokraus)
if not request.post_vars:
response.flash = 'Muokkaa vuokrausta'
return dict(form=form)
if form.process(session=None, formname="test").accepted:
response.flash = 'Vuokrausta on muokattu, klikkaa nimeä niin näet muutokset'
form = SQLFORM(db.vuokraus,buttons=[])
elif form.errors:
response.flash = 'Lomakkeen tiedoissa on virheitä, klikkaa elokuvaa uudelleen'
form = SQLFORM(db.vuokraus,buttons=[])
else:
response.flash = 'Täytä lomake lisätäksesi uuden vuokrauksen(/muokataksesi vuokrausta)'
return dict(form=form)
# Listaa kaikki jäsenet ja niihin liittyvät vuokraukset.
@auth.requires_login()
def vuokraukset():
response.title = "Kaikki vuokraukset"
jasenet_lista=[]
#liitos pitää tehdä ohjelmallisesti
jasenet = db().select(db.jasen.ALL,orderby=db.jasen.nimi)
# jäseneen liittyvät vuokraukset
for j in jasenet:
vuokraukset=[]
vuokraukset_jasen = db(db.vuokraus.jasenid == j.id).select(db.vuokraus, orderby=db.vuokraus.vuokrauspvm)
# tiettyyn vuokraukseen liittyvä elokuva
for v in vuokraukset_jasen:
elokuva = db(db.elokuva.id == v.elokuvaid).select(db.elokuva.ALL).first()
#vuokraukset.append(dict(jasen=j, elokuva=elokuva, vuokraus=v))
vuokraukset.append(dict(elokuva=elokuva, vuokraus=v))
jasenet_lista.append(dict(jasen=j,vuokraukset=vuokraukset))
return dict(jasenet=jasenet_lista)
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_password
http://..../[app]/default/user/bulk_register
use @auth.requires_login()
@auth.requires_membership('group name')
@auth.requires_permission('read','table name',record_id)
to decorate functions that need access control
also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users
"""
return dict(form=auth())
@cache.action()
def download():
"""
allows downloading of uploaded files
http://..../[app]/default/download/[filename]
"""
return response.download(request, db)
def call():
"""
exposes services. for example:
http://..../[app]/default/call/jsonrpc
decorate with @services.jsonrpc the functions to expose
supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
"""
return service()
|
print('\033[34m-='*20)
print(' DETECTOR DE PALÍDROMO')
print('-='*20, '\033[m')
fr = str(input('Qual frase deseja verificar: ')).strip().upper()
palavra = fr.split()
junto = ''.join(palavra)
inverso = ''
for letra in range(len(junto) -1, -1, -1):
inverso += junto[letra]
print('O inverso de {} é {}'.format(junto, inverso))
if inverso == junto:
print('Temos um palídromo!')
else:
print('A frase não é um palídromo!')
|
# Min Heap implementation
def swap(h, i, j):
h[i], h[j] = h[j], h[i]
def _min_heap_sift_up(h, k):
while k//2 >= 0:
if h[k] < h[k//2]:
swap(h, k, k//2)
k = k//2
else:
break
def _min_heap_sift_down(h, k):
last = len(h)-1
while (2*k+1) < last:
child = 2*k+1
if child < last and h[child+1] < h[child]:
child = child+1
if h[child] > h[k]:
break
swap(h, child, k)
k = child
def min_heap_heapify(h):
for k in range(len(h)//2, 0, -1):
_min_heap_sift_up(h, k)
def min_heap_insert(h, key):
h.append(key)
k = len(h)-1
print("appended", k, key, h)
_min_heap_sift_up(h, k)
print("appended", k, key, h)
def min_heap_getmin(h):
if len(h) == 0:
return None
return h[0]
def min_heap_deletemin(h):
if len(h) == 0:
return None
last = len(h)-1
first = 0
min = h[0]
swap(h, first, last)
h.pop()
print("deleted", min, h)
_min_heap_sift_down(h, 0)
print("deleted", min, h)
return min
# Min heap usage
#a = ['s', 'o', 'r', 't', 'e', 'x', 'a', 'm', 'p', 'l', 'e']
a = [1, -1, 0, 3, 9, 8, 3]
print(a)
min_heap_heapify(a)
print("Heapified", a)
min_heap_insert(a, 2)
print(a)
min_heap_insert(a, 0)
print(a)
min_heap_insert(a, -1)
print(min_heap_getmin(a))
print(a)
min_heap_deletemin(a)
print(a)
min_heap_deletemin(a)
print(a)
min_heap_deletemin(a)
print(a)
|
{
"targets": [
{
"target_name": "node-cursor",
"sources": [ "node-cursor.cc" ]
}
]
}
|
"""
A stub module to house pyrolite extensions,
where they are installed.
"""
|
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = []
common = [res.append(list(set(a))[0]) for a in itertools.takewhile(lambda x: len(set(x)) == 1, [x for x in zip(*strs)])]
return "".join(res)
# Enumeration soln
# def longestCommonPrefix(self, strs):
# """
# :type strs: List[str]
# :rtype: str
# """
# if not strs:
# return ""
# shortest = min(strs,key=len)
# for i, ch in enumerate(shortest):
# for other in strs:
# if other[i] != ch:
# return shortest[:i]
# return shortest
|
def solution(coins, amount):
coins = sorted(coins)
minCoins = [0] * (amount + 1)
for k in range(1, amount+1):
minCoins[k] = amount + 1
i = 0
while i < len(coins) and coins[i] <= k:
minCoins[k] = min(minCoins[k], minCoins[k - coins[i]] + 1)
i += 1
if minCoins[amount] == amount + 1:
return -1
else:
return minCoins[amount]
coins = [2, 4, 8, 16]
amount = 100
print(solution(coins, amount))
|
amount = int(input('''Copyright © 2021 Ashfaaq Rifath
CURRENCY CONVERTER.lk
---------------------
Please enter amount(LKR): '''))
con_currency = input("Please enter convert currency: ")
if con_currency.upper() == "USD":
converted = amount * 200
print(f"🛑🛑🛑 {amount} LKR is {converted} 💲")
if con_currency.upper() == "EUR":
converted = amount * 239
print(f"🛑🛑🛑 {amount} LKR is {converted} EUR")
if con_currency.upper() == "GBP":
converted = amount * 280
print(f"🔴🔴🔴 {amount} LKR is {converted} GBP")
|
class Node:
def __init__(self, value, _next=None):
self._value = value
self._next = _next
def __str__(self):
return f'{self._value}'
def __repr__(self):
return f'<Node | Val: {self._value} | Next: {self._next}>'
|
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
# click to show follow up.
# 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:
# @param {integer[][]} matrix
# @return {void} Do not return anything, modify matrix in-place instead.
def setZeroes(self, matrix):
fr = fc = False
for i in xrange(len(matrix)):
for j in xrange(len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
if i == 0:
fr = True
if j == 0:
fc = True
for j in xrange(1, len(matrix[0])):
if matrix[0][j] == 0:
for i in xrange(1, len(matrix)):
matrix[i][j] = 0
for i in xrange(1, len(matrix)):
if matrix[i][0] == 0:
for j in xrange(1, len(matrix[0])):
matrix[i][j] = 0
if fr:
for j in xrange(len(matrix[0])):
matrix[0][j] = 0
if fc:
for i in xrange(len(matrix)):
matrix[i][0] = 0
# for test
# return matrix
|
x=input('enter str1')
y=input('enter str2')
a=[]
b=[];c=[];max=-1
for i in range(len(x)+1):
for j in range(i+1,len(x)+1):
a.append(x[i:j])
for i in range(len(y)+1):
for j in range(i+1,len(y)+1):
b.append(y[i:j])
for i in range(len(a)):
for j in range(len(b)):
if a[i]==b[j]:
if len(a[i])>max:
max=len(a[i])
c=a[i]
print(c)
|
altitude = int(input("CURRENT ALTITUDE:"))
if altitude <=1000:
print("You can land the plan")
elif altitude > 1000 and altitude < 5000:
print("Come down to 1000")
else:
print("Turn around")
|
class Solution:
def myPow(self, x: float, n: int) -> float:
'''
x^n = x^2 ^ (n//2) if n is even
x^n = x * x^2 ^ (n//2) is n is odd
'''
if n == 0: return 1
result = self.myPow(x*x, abs(n) //2)
if n % 2:
result *= x
if n < 0: return 1/result
return result
|
# Python snippets
#################################
class MetaClass(type):
"""Return a class object with the __class__ attribute equal to the class object.
This allows interesting things within the class, such as __class__.__name__,
which are otherwise not available.
This class is used as a metaclass by including it in the class definition:
class SomeClass(object, metaclass=MetaClass):
Then within the class, attributes of the class can be accessed, such as
__class__.__name__. This is different from type(self).__name__,
as the latter gives the class of self, which may not be the same as the
surrounding class definition, due to inheritance.
"""
def __new__(mcs, name, bases, attrs):
attrs['__class__'] = name
return type.__new__(mcs, name, bases, attrs)
#################################
|
# -*- coding: utf-8 -*-
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
return ''.join(reversed(word[:word.find(ch) + 1])) + word[word.find(ch) + 1:]
if __name__ == '__main__':
solution = Solution()
assert 'dcbaefd' == solution.reversePrefix('abcdefd', 'd')
assert 'zxyxxe' == solution.reversePrefix('xyxzxe', 'z')
assert 'abcd' == solution.reversePrefix('abcd', 'z')
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
start, end = 0, len(nums)- 1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] < target:
start = mid + 1
elif nums[mid] > target:
end = mid - 1
else:
return mid
return -1
|
class GameRules:
"""
A list of gamerules used by the world.
Contains all gamerules for Java edition as of 1.16.5.
"""
def __init__(self):
"""
Creates the rules of the class.
"""
self.rules = []
self.create_game_rules()
def create_game_rules(self):
"""
Saves every gamerule to the self.rules array.
"""
self.rules.extend([
{
"name": "announceAdvancements",
"value": "true",
"type": "bool"
},
{
"name": "commandBlockOutput",
"value": "true",
"type": "bool"
},
{
"name": "disableElytraMovementCheck",
"value": "false",
"type": "bool"
},
{
"name": "disableRaids",
"value": "false",
"type": "bool"
},
{
"name": "doDaylightCycle",
"value": "true",
"type": "bool"
},
{
"name": "doEntityDrops",
"value": "true",
"type": "bool"
},
{
"name": "doFireTick",
"value": "true",
"type": "bool"
},
{
"name": "doInsomnia",
"value": "true",
"type": "bool"
},
{
"name": "doImmediateRespawn",
"value": "false",
"type": "bool"
},
{
"name": "doLimitedCrafting",
"value": "false",
"type": "bool"
},
{
"name": "doMobLoot",
"value": "true",
"type": "bool"
},
{
"name": "doMobSpawning",
"value": "true",
"type": "bool"
},
{
"name": "doPatrolSpawning",
"value": "true",
"type": "bool"
},
{
"name": "doTileDrops",
"value": "true",
"type": "bool"
},
{
"name": "doTraderSpawning",
"value": "true",
"type": "bool"
},
{
"name": "doWeatherCycle",
"value": "true",
"type": "bool"
},
{
"name": "drowningDamage",
"value": "true",
"type": "bool"
},
{
"name": "fallDamage",
"value": "true",
"type": "bool"
},
{
"name": "fireDamage",
"value": "true",
"type": "bool"
},
{
"name": "forgiveDeadPlayers",
"value": "true",
"type": "bool"
},
{
"name": "freezeDamage",
"value": "true",
"type": "bool"
},
{
"name": "keepInventory",
"value": "false",
"type": "bool"
},
{
"name": "logAdminCommands",
"value": "true",
"type": "bool"
},
{
"name": "maxCommandChainLength",
"value": "65536",
"type": "int"
},
{
"name": "maxEntityCramming",
"value": "24",
"type": "int"
},
{
"name": "mobGriefing",
"value": "true",
"type": "bool"
},
{
"name": "naturalRegeneration",
"value": "true",
"type": "bool"
},
{
"name": "playersSleepingPercentage",
"value": "100",
"type": "int"
},
{
"name": "randomTickSpeed",
"value": "3",
"type": "int"
},
{
"name": "reducedDebugInfo",
"value": "false",
"type": "bool"
},
{
"name": "sendCommandFeedback",
"value": "true",
"type": "bool"
},
{
"name": "showDeathMessages",
"value": "true",
"type": "bool"
},
{
"name": "spawnRadius",
"value": "10",
"type": "int"
},
{
"name": "spectatorsGenerateChunks",
"value": "true",
"type": "bool"
},
{
"name": "universalAnger",
"value": "false",
"type": "bool"
}
])
def set_rule(self, name, value):
"""
Sets a rule. The value must be the type (bool, int) of the gamerule.
:param name: the name of the rule
:param value: the value to set the rule to
"""
for rule in self.rules:
if rule["name"] == name:
if rule["type"] == "bool" and not isinstance(value, bool):
raise ValueError("Given value is not of correct type")
elif not isinstance(value, int):
raise ValueError("Given value is not of correct type")
rule["value"] = str(value).lower()
return True
raise ValueError(f"Game rule {name} could not be found")
|
#!/usr/bin/env python3
def mysteryAlgorithm(lst):
for i in range(1,len(lst)):
while i > 0 and lst[i-1] > lst[i]:
lst[i], lst[i-1] = lst[i-1], lst[i]
i -= 1
return lst
print(mysteryAlgorithm([6, 4, 3, 8, 5]))
|
'''
practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses
by Aashik J Krishnan/Aash Gates
'''
x = 10
y ="ten"
#step 1
temp = x
#temp variable now holds the value of x
#step 2
x = y
#the variable x now holds the value of y
#step 3
y = temp
# y now holds the value of temp which is the orginal value of x
print (x)
print (y)
print (temp)
#end of the Program
|
#
# @lc app=leetcode id=541 lang=python3
#
# [541] Reverse String II
#
# https://leetcode.com/problems/reverse-string-ii/description/
#
# algorithms
# Easy (49.66%)
# Total Accepted: 117.1K
# Total Submissions: 235.8K
# Testcase Example: '"abcdefg"\n2'
#
# Given a string s and an integer k, reverse the first k characters for every
# 2k characters counting from the start of the string.
#
# If there are fewer than k characters left, reverse all of them. If there are
# less than 2k but greater than or equal to k characters, then reverse the
# first k characters and left the other as original.
#
#
# Example 1:
# Input: s = "abcdefg", k = 2
# Output: "bacdfeg"
# Example 2:
# Input: s = "abcd", k = 2
# Output: "bacd"
#
#
# Constraints:
#
#
# 1 <= s.length <= 10^4
# s consists of only lowercase English letters.
# 1 <= k <= 10^4
#
#
#
class Solution:
def reverseStr(self, s: str, k: int) -> str:
if len(s) < k:
return self.reverseAllStr(s)
elif len(s) >= k and len(s) < 2 * k:
return self.reverseAllStr(s[:k]) + s[k:]
else:
return self.reverseAllStr(s[:k]) + s[k:2*k] + self.reverseStr(s[2*k:], k)
def reverseAllStr(self, s: str):
return s[::-1]
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
def load_command_table(self, _):
with self.command_group("approle", is_preview=True) as g:
g.custom_command("list", "list_app_roles")
g.custom_command("assignment list", "list_role_assignments")
g.custom_command("assignment add", "add_role_assignment")
g.custom_command("assignment remove", "remove_role_assignment")
|
'''
Url: https://www.hackerrank.com/challenges/write-a-function/problem
Name: Write a function
'''
def is_leap(year):
'''
For this reason, not every four years is a leap year. The rule is that if the year is divisible by 100 and not divisible by 400, leap year is skipped. The year 2000 was a leap year, for example, but the years 1700, 1800, and 1900 were not. The next time a leap year will be skipped is the year 2100
'''
if year % 100 == 0 and year % 400 != 0:
return False
return True if year % 4 == 0 else False
year = int(input())
print(is_leap(year))
|
class Solution(object):
# O(Nlog(N))
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
for i in range(len(citations)):
if citations[i] < i + 1:
return i
return len(citations)
def hIndex2(self, citations):
N = len(citations)
log = [0] * (N + 1)
for i in range(N):
if citations[i] >= N:
log[N] += 1
else:
log[citations[i]] += 1
cnt = 0
for i in range(N + 1)[::-1]:
cnt += log[i]
if cnt >= i:
return i
|
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
E = len(trust)
if E < N - 1:
return -1
trustScore = [0] * N
for a, b in trust:
trustScore[a - 1] -= 1
trustScore[b - 1] += 1
for index, t in enumerate(trustScore, 1):
if t == N - 1:
return index
return -1
|
line = '-'*39
bases = '|' + ' ' + 'decimal' + ' ' + '|' + ' ' + 'octal' + ' ' + '|' + ' ' + 'Hexadecimal' + ' ' + '|'
blankNum1 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*4 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|'
blankNum2 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*3 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|'
blankNum3 = '|' + ' '*5 + '{0}' + ' '*4 + '|' + ' '*3 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|'
print(line)
print(bases)
print(line)
for k in range(8):
print(blankNum1.format(k, oct(k)[2:], hex(k)[2:]))
for k in range(8,10):
print(blankNum2.format(k, oct(k)[2:], hex(k)[2:].upper()))
for k in range(10,16):
print(blankNum3.format(k, oct(k)[2:], hex(k)[2:].upper()))
print(line)
|
"""
A feature-based chart parser.
"""
|
def dfs(u, graph, visited):
visited.add(u)
for v in graph[u]:
if v not in visited:
dfs(v, graph, visited)
def count_dfs(u, graph, visited=None, depth=0):
if visited is None:
visited = set()
visited.add(u)
res = 1
for v, count in graph[u]:
if v not in visited:
x = count_dfs(v, graph, visited, depth + 1)
res += int(count) * x
visited.remove(u)
return res
def parse_rule(rule):
rule = rule[:-1]
rule_bag, insides = rule.split(' bags contain ')
if insides == 'no other bags.':
insides = []
else:
insides = insides[:-1].split(', ')
insides = [tuple(bag.split()[:-1]) for bag in insides]
return rule_bag, insides
def base_graph(rules):
bags = set()
for bag, insides in rules:
bags.add(bag)
for count, spec, color in insides:
other_bag = f'{spec} {color}'
bags.add(other_bag)
return {bag: set() for bag in bags}
def inward_graph(rules):
graph = base_graph(rules)
for bag, insides in rules:
for count, spec, color in insides:
other_bag = f'{spec} {color}'
graph[other_bag].add(bag)
return graph
def outward_graph(rules):
graph = base_graph(rules)
for bag, insides in rules:
for count, spec, color in insides:
other_bag = f'{spec} {color}'
graph[bag].add((other_bag, count))
return graph
if __name__ == '__main__':
with open('input.txt') as input_file:
rules = [parse_rule(line) for line in input_file]
graph = outward_graph(rules)
print(count_dfs('shiny gold', graph) - 1)
|
# -*- coding: utf-8 -*-
def seconds_to_human(seconds):
"""Convert seconds to a human readable format.
Args:
seconds (int): Seconds.
Returns:
str: Return seconds into human readable format.
"""
units = (
('week', 60 * 60 * 24 * 7),
('day', 60 * 60 * 24),
('hour', 60 * 60),
('min', 60),
('sec', 1)
)
if seconds == 0:
return '0 secs'
parts = []
for unit, div in units:
amount, seconds = divmod(int(seconds), div)
if amount > 0:
parts.append('{} {}{}'.format(
amount, unit, '' if amount == 1 else 's'))
return ' '.join(parts)
|
def selection_sort(arr):
for num in range(0, len(arr)):
min_position = num
for i in range(num, len(arr)):
if arr[i] < arr[min_position]:
min_position = i
temp = arr[num]
arr[num] = arr[min_position]
arr[min_position] = temp
arr = [6, 3, 8, 5, 2, 7, 4, 1]
print(f'Unordered: {arr}')
selection_sort(arr)
print(f'Ordered: {arr}')
|
def queens(board):
"""
Doesn't work because the solution is not recursive. It constraints to only
checking the possible solutions of plaicng the queen in a given spot.
Another thing, no need to store the whole board, it's just enough to have a
one dimensional array of the columns.
One more thing, the diagonal cna be calculated byt the distance between rows
and columns. when r1 - r2 == c1 - c2 then they are in a diagonal.
How to fix it?
Regardless of how to validate that is valid, what we needed to check, recursively,
if there was a solution from the starting point. And if not, try the next
possible solution. We tried that artificially by storing the last result but
that was a hacky solution.
"""
r = len(board)
c = len(board[0])
i = 0
j = 0
x,y=-1,-1
while i < r:
while j < c:
# skip first space found
if board[i][j] == 0:
if x == -1 and canPlaceQueen(board, i,j, r, c):
y = i
x = j
continue
else:
if canPlaceQueen(board, i,j, r, c):
board[i][j] = 1
else:
board[y][x] = 1
j+=1
i+=1
def canPlaceQueen(board, i,j, r, c):
# if i < 0 or j < 0 or i == r or j ==c:
# return True
if isVerticalFree(board, j, r, c) and \
isHorizontalFree(board, i, r, c) and \
isDiagonalFree(board, i,j, r, c):
return True
return False
def isVerticalFree(board, j, r, c):
for i in range(r):
if board[i][j] != 0:
return False
return True
def isHorizontalFree(board, i, r, c):
for j in range(c):
if board[i][j] != 0:
return False
return True
def isDiagonalFree(board, i, j, r, c):
# find the begining of the diagonal
y = i
x = j
while y >= 0 and x >= 0:
y -= 1
x -= 1
while y < r and x < c:
if board[y][x] != 0:
return False
x += 1
y += 1
y = i
x = j
while y >= 0 and x < c:
y -= 1
x += 1
while y < r and x >=0:
if board[y][x] != 0:
return False
y += 1
x -= 1
return True
def queues_book_solution(row, columns, result):
"""
columns - onedimanesional array. each position represents the row, the value represents the column
"""
if row == len(columns):
result.append(columns.copy())
return
# we want to iterate over all the possible columns
for col in range(len(columns)):
# at first, i thought that we needed a flag to detect if we couldn't find a solution after iterating
# all the columsn. but then realized that if we don't find it, then the base condition would never be
# called. that's why we don't need it.
if canPlace(columns, row, col):
columns[row] = col
queues_book_solution(row + 1, columns, result)
def canPlace(columns, row, col):
# We only need to check all rows from 0 to row and not the 8 rows becasue we have
# only placed a value all the way until row.
for row2 in range(row):
col2 = columns[row2]
if col2 == col:
return False
# we need the absolute value because we don't know which column is bigger
col_distance = abs(col - col2)
row_distance = row - row2
if col_distance == row_distance:
return False
return True
if __name__ == "__main__":
# board = [[0 for _ in range(8)] for _ in range(8)]
# queens(board)
# for i in 8:
# print(board[i])
results = []
columns = [0] * 8
queues_book_solution(0, columns, results)
for i in range(len(results)):
r = results[i]
print(r)
# for j in range(len(r)):
# print(r[j])
|
print('<AMO FAZER EXERCICIO NO URI>')
print('< AMO FAZER EXERCICIO NO URI>')
print('<AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO NO URI>')
print('<AMO FAZER EXERCICIO NO URI >')
print('<AMO FAZER EXERCICIO NO URI>')
print('< AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO >')
|
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for idx in range(len(image)):
image[idx] = list(reversed(image[idx]))
image[idx] = [1 if b == 0 else 0 for b in image[idx]]
return image
|
# Leia nome e peso de várias pessoas, em uma lista composta só
# Diga:
# 1) quantas pessoas foram cadastradas
# 2) a lista das pessoas que têm o maior peso
# 3) a lista das pessoas que têm o menor peso
pessoas = []
maiorPeso = 0
menorPeso = 0
print("PARA PARAR, DEIXE EM BRANCO!\n-------")
while True:
try:
pessoa = [ ]
print(f"Digite o nome e o peso da {len(pessoas)+1}ª pessoa")
pessoa.append( input('>>> ') )
if pessoa[0] == '':
print('Nome vazio. saindo')
break
pessoa.append( int(input('>>> ')) )
pessoas.append(pessoa)
if len(pessoas) == 1:
maiorPeso = menorPeso = pessoa[1]
if pessoa[1] > maiorPeso :
maiorPeso = pessoa[1]
elif pessoa[1] < menorPeso:
menorPeso = pessoa[1]
except Exception as e:
print(f'Erro! Saindo do cadastro. {e}')
print(f'Foram inseridas as {len(pessoas)} pessoas!')
print('Quem tem o maior peso: ', end='')
for pessoa in pessoas:
if pessoa[1] == maiorPeso:
print(f'"{pessoa[0]}"', end=' ')
print('\nQuem tem o menor peso: ', end='')
for pessoa in pessoas:
if pessoa[1] == menorPeso:
print(f'"{pessoa[0]}"', end=' ')
|
WINSTRIDE = (8, 8)
PADDING = (8, 8)
SCALE = 1.15
MIN_NEIGHBORS = 5
OVERLAP_NMS = 0.9
|
index_definition = {
"name": "id",
"field_type": "int",
"index_type": "hash",
"is_pk": True,
"is_array": False,
"is_dense": False,
"is_sparse": False,
"collate_mode": "none",
"sort_order_letters": "",
"expire_after": 0,
"config": {
},
"json_paths": [
"id"
]
}
updated_index_definition = {
"name": "id",
"field_type": "int64",
"index_type": "hash",
"is_pk": True,
"is_array": False,
"is_dense": False,
"is_sparse": False,
"collate_mode": "none",
"sort_order_letters": "",
"expire_after": 0,
"config": {
},
"json_paths": [
"id_new"
]
}
special_namespaces = [{"name": "#namespaces"},
{"name": "#memstats"},
{"name": "#perfstats"},
{"name": "#config"},
{"name": "#queriesperfstats"},
{"name": "#activitystats"},
{"name": "#clientsstats"}]
special_namespaces_cluster = [{"name": "#namespaces"},
{"name": "#memstats"},
{"name": "#perfstats"},
{"name": "#config"},
{"name": "#queriesperfstats"},
{"name": "#activitystats"},
{"name": "#clientsstats"},
{"name": "#replicationstats"}]
item_definition = {'id': 100, 'val': "testval"}
|
def fac(n):
if n==1 or n==0:
return 1
else:
return n*fac(n-1)
print(fac(10))
|
#-------------------------------------------------------------------#
# Returns the value of the given card
#-------------------------------------------------------------------#
def get_value(card):
value = card[0:len(card)-1]
return int(value)
#-------------------------------------------------------------------#
# Returns the suit of the given card
#-------------------------------------------------------------------#
def get_suit(card):
suit = card[len(card)-1:]
return suit
#-------------------------------------------------------------------#
# Returns a tuple of all the cards in dealerCard that have the
# given suit
#-------------------------------------------------------------------#
def get_cards_of_same_suit(suit, dealerCards):
cardsOfSameSuit = tuple() # assign to empty tuple
for c in dealerCards:
if get_suit(c) == suit:
if cardsOfSameSuit == tuple():
cardsOfSameSuit = (c,)
else:
cardsOfSameSuit = cardsOfSameSuit + (c,)
return cardsOfSameSuit
#-------------------------------------------------------------------#
# This function can be called in three different ways:
#
# 1) You can call it with 1 argument (e.g. dealerCards) which
# returns the lowest value card in dealerCards, regardless of suit
# and any value restrictions. Here is an example function call:
#
# lowest = get_lowest_card(dealerCards)
#
# 2) You can call it with 2 arguments (e.g. dealerCards, oppSuit)
# which returns the lowest value card in dealerCards of a given suit,
# regardless of any value restrictions. If no cards of that suit
# exist, an an empty string ("") is returned. Here is an example
# function call:
#
# lowest = get_lowest_card(dealerCards, oppSuit)
#
# 3) You can call it with 3 arguments (e.g. dealerCards, oppSuit,
# oppValue) which returns the lowest value card in dealerCards of
# a given suit that has a value > oppValue. If no such card exists,
# an empty string ("") is returned. Here is an example function call:
#
# lowest = get_lowest_card(dealerCards, oppSuit, oppValue)
#
#-------------------------------------------------------------------#
def get_lowest_card(dealerCards, oppSuit="", oppValue=0):
lowestSoFar = ""
if oppSuit == "":
cards = dealerCards
else:
cards = get_cards_of_same_suit(oppSuit, dealerCards)
for c in cards:
value = get_value(c)
suit = get_suit(c)
if value > oppValue:
if lowestSoFar == "" or value < get_value(lowestSoFar):
lowestSoFar = c
return lowestSoFar
#-------------------------------------------------------------------#
# Returns the dealers card to play
#-------------------------------------------------------------------#
def get_dealer_play(cardsInTuple):
# set oppLeadCard to the first card in cardsInTuple
oppLeadCard = cardsInTuple[0]
# set oppSuit to suit of oppLeadCard; use get_suit(oppLeadCard)
oppSuit = get_suit(oppLeadCard)
# set oppValue to value of oppLeadCard; use get_value(oppLeadCard)
oppValue = get_value(oppLeadCard)
# set dealerCards to the last 5 cards of cardsInTuple
dealerCards = cardsInTuple[1:]
# get the lowest valued card in the dealer hand that is the same
# suit as the oppSuit and has value greater than oppValue. if such
# a card does NOT exist, lowest gets assigned ""
lowest = get_lowest_card(dealerCards, oppSuit, oppValue)
# if lowest is not "" (i.e. lowest stores a card)
if lowest != "":
print(lowest)
else:
lowestSuit = get_lowest_card(dealerCards, oppSuit)
lowestCard = get_lowest_card(dealerCards)
if lowestSuit == "":
print(lowestCard)
elif lowestCard != "":
print(lowestSuit)
#-------------------------------------------------------------------#
# -- Main Section
#-------------------------------------------------------------------#
# read in user input as string, such as: "5D 2D 6H 9D 10D 6H"
cardsInString = input()
# place cards in tuple, such as: ("5D", "2D", "6H", "9D", "10D", "6H")
cardsInTuple = tuple(cardsInString.split())
# The first card in cardsInTuple represents the opponents lead card
# and the remaining five cards represent the dealer cards. This tuple
# is passed to get_dealer_play() to help determine which card
# the dealar should play next.
dealerPlayCard = get_dealer_play(cardsInTuple)
# diplay the dealer card to play
#print(dealerPlayCard)
|
# we prompt the user for the code.
# enters beginning meter reading
# Enters ending meter reading.
# we compute the gallons of water as a 10th of the gotten gallons.
# we print out the bill meant to be paid the user
def bill_calculator(code, gallons):
if code == "r":
bill = 5.00 + (gallons * 0.0005)
return round(bill, 2)
elif code == "c":
if gallons <= 4000000:
bill = 1000.00
return round(bill, 2)
else:
first_half = 1000.00
sec_half = (gallons - 4000000) * 0.00025
summed_bill = first_half + sec_half
return round(summed_bill, 2)
elif code == "i":
if gallons <= 10000000:
bill = 1000.00
return round(bill, 2)
elif 4000000 < gallons < 10000000:
bill = 2000.00
return round(bill, 2)
elif gallons > 10000000:
first_half = 2000.00
sec_half = (gallons - 10000000) * 0.00025
summed_bill = first_half + sec_half
return round(summed_bill, 2)
while True:
# promp the user for the code.
list_codes = ['r', 'c', 'i']
customer_code = input("\nEnter customer code:")
if len(customer_code) > 0 and customer_code.lower() in list_codes:
cus_code = customer_code.lower()
begin_exact = 0
end_exact = 0
while True:
begin_r = input("\nEnter Beginning meter reading:")
if len(begin_r) > 0 and begin_r.isnumeric() and 0 < int(begin_r) < 999999999:
begin_exact = int(begin_r)
break
else:
print("Enter valid input or meter reading!")
continue
while True:
end_r = input("\nEnter End meter reading:")
if len(end_r) > 0 and end_r.isnumeric() and 0 < int(end_r) < 999999999:
end_exact = int(end_r)
break
else:
print("Enter valid input or meter reading!")
continue
gallons = (end_exact - begin_exact) / 10
customer_bill = bill_calculator(cus_code, gallons)
print("\nCustomer Code:", cus_code)
print("Beginning meter reading:", begin_exact)
print("Ending meter reading:", end_exact)
print("Gallons of water used:", str(gallons))
print("Amount billed:$" + str(customer_bill))
else:
print("Please enter a valid customer code!")
continue
|
class VoetbalClub:
"""
VoetbalClub is een simpele class.
Gemaakt om het aantal punten van de clubs bij te kunnen houden.
"""
def __init__(self, naam):
self.naam = naam
self.punten = 0
|
'''
exceptions.py: exceptions defined by textform
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2020 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" for more information.
'''
# Base class.
# .............................................................................
# The base class makes it possible to use a single test to distinguish between
# exceptions generated by Documentarist code and exceptions generated by
# something else.
class DocumentaristException(Exception):
'''Base class for Documentarist exceptions.'''
pass
# Exception classes.
# .............................................................................
class CannotProceed(DocumentaristException):
'''A recognizable condition caused an early exit from the program.'''
pass
class UserCancelled(DocumentaristException):
'''The user elected to cancel/quit the program.'''
pass
class CorruptedContent(DocumentaristException):
'''Content corruption has been detected.'''
pass
class InternalError(DocumentaristException):
'''Unrecoverable problem involving textform itself.'''
pass
|
"""
画出下列代码内存图,说出终端显示结果
"""
# insert 键:切换插入或者改写模式
name_of_beijing, region = "北京", "市"
name_of_beijing_region = name_of_beijing + region
region = "省"
print(name_of_beijing_region) # 北京市
del name_of_beijing
print(name_of_beijing_region) # 北京市
|
def default_pipe(data, config):
subjects = config.get("subjects")
mutated_data = []
for row in data:
# Nest the subjects defined in config into a single dict
# and add it to mutated_row with the key "Subjects".
row_subjects = {k: int(v) for k, v in row.items() if k in subjects and bool(v)}
mutated_row = {k: v for k, v in row.items() if k not in subjects}
mutated_row["Subjects"] = row_subjects
mutated_data.append(mutated_row)
return mutated_data
def marks_validator_pipe(data, config):
"""
Pipe to validate the marks' entries for every student.
Checks happening here:
1. If marks for a particular subject exceed the maximum possible marks
"""
subjects = config.get("subjects")
for row in data:
if "Subjects" in row:
for k, v in row["Subjects"].items():
if v > subjects[k]:
print(
f"VALIDATION ERROR: '{k}' subject of {row.get('Name')} has more marks than the max possible marks."
)
exit(1)
return data
def percentage_and_total_marks_pipe(data, config):
"""
Pipe to calculate maximum marks possible, total marks and percentage obtained by the student.
1. Total marks obtained are available in the 'TotalMarksObtained' key.
2. Maximum marks possible for the student are available in the 'MaxMarks' key.
3. Percentage obtained is available in the 'Percentage' key.
"""
mutated_data = []
subjects = config.get("subjects")
for row in data:
max_marks = 0
marks_obtained = 0
student_subjects: dict = row.get("Subjects")
for [subject, marks] in student_subjects.items():
marks_obtained += marks
max_marks += subjects[
subject
] # .get is not required since the subject should exist in the dictionary.
percentage = round(100 * marks_obtained / max_marks, 2)
mutated_row = dict(row)
mutated_row["TotalMarksObtained"] = marks_obtained
mutated_row["MaxMarks"] = max_marks
mutated_row["Percentage"] = percentage
mutated_data.append(mutated_row)
return mutated_data
|
expected_normal_output = """Title Release Year Estimated Budget
Shawshank Redemption 1994 $25 000 000
The Godfather 1972 $6 000 000
The Godfather: Part II 1974 $13 000 000
The Dark Knight 2008 $185 000 000
12 Angry Men 1957 $350 000"""
expected_markdown_output = """Title | Release Year | Estimated Budget
:----------------------|:-------------|:----------------
Shawshank Redemption | 1994 | $25 000 000
The Godfather | 1972 | $6 000 000
The Godfather: Part II | 1974 | $13 000 000
The Dark Knight | 2008 | $185 000 000
12 Angry Men | 1957 | $350 000"""
expected_right_justified_output = """ Title Release Year Estimated Budget
Shawshank Redemption 1994 $25 000 000
The Godfather 1972 $6 000 000
The Godfather: Part II 1974 $13 000 000
The Dark Knight 2008 $185 000 000
12 Angry Men 1957 $350 000"""
expected_tab_output = """Some parameter Other parameter Last parameter
CONST 123456 12.45"""
expected_header_output = """------------------------------------------------------
Title Release Year Estimated Budget
------------------------------------------------------
Shawshank Redemption 1994 $25 000 000
The Godfather 1972 $6 000 000
The Godfather: Part II 1974 $13 000 000
The Dark Knight 2008 $185 000 000
12 Angry Men 1957 $350 000"""
expected_short_output = """Title Release Year Estimated Budget
Shawshank Redemption 1994 $25 000 000
The Godfather 1972 $6 000 000"""
expected_oneline_output = """Title Release Year Estimated Budget"""
expected_one_column_output = """Estimated Budget
$25 000 000
$6 000 000
$13 000 000
$185 000 000
$350 000"""
expected_justified_markdown_output = """Title | Release Year | Estimated Budget
:----------------------|-------------:|----------------:
Shawshank Redemption | 1994 | $25 000 000
The Godfather | 1972 | $6 000 000
The Godfather: Part II | 1974 | $13 000 000
The Dark Knight | 2008 | $185 000 000
12 Angry Men | 1957 | $350 000"""
expected_header_with_decorator_output = """----------------------- o -------------- o -----------------
Title o Release Year o Estimated Budget
----------------------- o -------------- o -----------------
Shawshank Redemption o 1994 o $25 000 000
The Godfather o 1972 o $6 000 000
The Godfather: Part II o 1974 o $13 000 000
The Dark Knight o 2008 o $185 000 000
12 Angry Men o 1957 o $350 000"""
expected_latex_output = r"""\begin{tabular}{lll}
Title & Release Year & Estimated Budget \\
Shawshank Redemption & 1994 & 25 000 000 \\
The Godfather & 1972 & 6 000 000 \\
The Godfather: Part II & 1974 & 13 000 000 \\
The Dark Knight & 2008 & 185 000 000 \\
12 Angry Men & 1957 & 350 000 \\
\end{tabular}"""
expected_latex_with_justification_output = r"""\begin{tabular}{lrr}
Title & Release Year & Estimated Budget \\
Shawshank Redemption & 1994 & 25 000 000 \\
The Godfather & 1972 & 6 000 000 \\
The Godfather: Part II & 1974 & 13 000 000 \\
The Dark Knight & 2008 & 185 000 000 \\
12 Angry Men & 1957 & 350 000 \\
\end{tabular}"""
NORMAL_FILENAME = 'examples/imdb.csv'
test_cases = [
([NORMAL_FILENAME], expected_normal_output),
([NORMAL_FILENAME, '--markdown'], expected_markdown_output),
([NORMAL_FILENAME, '-a', 'l'], expected_normal_output),
([NORMAL_FILENAME, '-a', 'r'], expected_right_justified_output),
(['examples/small.tsv', '-s', 'tab'], expected_tab_output),
([NORMAL_FILENAME, '-s', 'comma'], expected_normal_output),
([NORMAL_FILENAME, '--header'], expected_header_output),
([NORMAL_FILENAME, '-n', '3'], expected_short_output),
([NORMAL_FILENAME, '-n', '1'], expected_oneline_output),
([NORMAL_FILENAME, '--markdown', '-a', 'l', 'r', 'r'], expected_justified_markdown_output),
([NORMAL_FILENAME, '--header', '-d', ' o '], expected_header_with_decorator_output),
(['examples/imdb-latex.csv', '--latex'], expected_latex_output),
(['examples/imdb-latex.csv', '--latex', '-a', 'l', 'r', 'r'], expected_latex_with_justification_output),
([NORMAL_FILENAME, '--c', '3'], expected_one_column_output)
]
|
#Written for Python 3.4.2
data = [line.rstrip('\n') for line in open("input.txt")]
blacklist = ["ab", "cd", "pq", "xy"]
vowels = ['a', 'e', 'i', 'o', 'u']
def contains(string, samples):
for sample in samples:
if string.find(sample) > -1:
return True
return False
def isNicePart1(string):
if contains(string, blacklist):
return False
vowelcount = 0
for vowel in vowels:
vowelcount += string.count(vowel)
if vowelcount < 3:
return False
for i in range(len(string)-1):
if string[i] == string[i+1]:
return True
return False
def isNicePart2(string):
for i in range(len(string)-3):
pair = string[i]+string[i+1]
if string.find(pair, i+2) > -1:
for j in range(len(string)-2):
if string[j] == string[j+2]:
return True
return False
return False
nicePart1Count = 0
nicePart2Count = 0
for string in data:
if isNicePart1(string):
nicePart1Count += 1
if isNicePart2(string):
nicePart2Count += 1
print(nicePart1Count)
print(nicePart2Count)
#Test cases part1
##print(isNicePart1("ugknbfddgicrmopn"), True)
##print(isNicePart1("aaa"), True)
##print(isNicePart1("jchzalrnumimnmhp"), False)
##print(isNicePart1("haegwjzuvuyypxyu"), False)
##print(isNicePart1("dvszwmarrgswjxmb"), False)
#Test cases part1
##print(isNicePart2("qjhvhtzxzqqjkmpb"), True)
##print(isNicePart2("xxyxx"), True)
##print(isNicePart2("uurcxstgmygtbstg"), False)
##print(isNicePart2("ieodomkazucvgmuy"), False)
|
class MyStr(str):
def __format__(self, *args, **kwargs):
print("my format")
return str.__format__(self, *args, **kwargs)
def __mod__(self, *args, **kwargs):
print("mod")
return str.__mod__(self, *args, **kwargs)
if __name__ == "__main__":
ms = MyStr("- %s - {} -")
print(ms.format("test"))
print(ms % "test")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
树:是由结点与节点之间的链接关系组成
树的特征:
1、存在唯一的起始点,树根
2、树根外的其他结点都有且只有一个前驱结点;但每个结点可以有0-n个后继
树可以有多个尾结点
3、树根可以到达任意结点(有限跳)
4、任意两个不同结点向下出发,无交叉
二叉树:
树中每个结点最多关联到两个后继结点
后继结点明确分左右
左右子树必须明确说明
几个基本概念:(都是对于二叉树而言)
空树:不包含任何结点
单点树:只包含一个结点
父结点和子节点是相对而言的
边:父到子,具有方向性
兄弟结点:具有相同的父结点的结点
树叶:没有子节点的二叉树
分支结点
度数:一个结点的子结点的个数
路径边的条数 -- 路径的长度
到自身,长度为0
路径唯一性
从树根到树中任一结点的路径长度 --- 结点的层数
二叉树的高度(深度) -- 树中结点最大层数
二叉树的性质:
1、在非空二叉树第i层中至多有2^i个结点(i >=0)
2、高度为h的二叉树至多有2^(h+1)-1个结点 (h>=0)
3、对于任何非空二叉树,如果叶结点的个数为n0,度数为2的结点个数为n2
n0 = n2 + 1
满二叉树;
所有分支结点的度数都为2
性质; 满二叉树里的叶结点比分支结点多一个
扩充二叉树:
将非满二叉树扩充成满 -- 外部结点:内部结点
完全二叉树:
最后一层排不满,且空位都在右边(如果有空位的话)
n个结点的完全二叉树高度 h =[log_2(n)], 即为不大于它的最大整数
notes: 从上到下,从左到右编号,0开始,对任意结点i都有
1、0 -- 根结点
2、i>0, 父结点编号int((i-1)/2)
3、2*i + 1 < n, 左子结点序号为 2*i + 1, 否则它没有子节点
4、2*i + 2 < n ,右子结点序号为 2*i + 2, 否则没有子结点
(i-1)/2
i i+1
2*i +1 2*i + 2
总结:
"""
|
#
# AGENT
# Sanjin
#
# STRATEGY
# This agent always defects, if the opponent defected too often. Otherwise it cooperates.
#
def getGameLength(history):
return history.shape[1]
def getChoice(snitch):
return "tell truth" if snitch else "stay silent"
def strategy(history, memory):
if getGameLength(history) == 0:
return getChoice(False), None
average = sum(history[1]) / history.shape[1]
snitch = average <= 0.3 # Defect if the opponent defected > 30% of times
return getChoice(snitch), None
|
#! /usr/bin/env python
#-----------------------------------------------------------------------
# COPYRIGHT_BEGIN
# Copyright (C) 2017, FixFlyer, LLC.
# All rights reserved.
# COPYRIGHT_END
#-----------------------------------------------------------------------
class Event(object):
"""Base class for API events."""
pass
class OnLogonEvent(Event):
"""Login response event.
Sent by the Flyer Engine to an application in response to a call
to ApplicationManager::logon()."""
def __init__(self):
self.success = False
return
class OnSessionLogonEvent(Event):
"""Subscribed session logon event."""
def __init__(self):
self._session_id = ""
self._connected = False
self._current_trading_session_id = 0
self._out_msg_seq_no = 0
self._in_msg_seq_no = 0
self._last_client_message_id = ""
self._scheduled_down = False
return
class OnSessionLogoutEvent(Event):
"""Subscribed session logout event."""
def __init__(self):
self._session_id = ""
self._connected = False
self._current_trading_session_id = 0
self._out_msg_seq_no = 0
self._in_msg_seq_no = 0
self._last_client_message_id = ""
self._scheduled_down = False
return
class OnCommitEvent(Event):
"""Report confirming the engine has persisted the described message."""
def __init__(self):
self._session_id = ""
self._client_message_id = ""
self._last_outgoing_msg_seq_num = 0
return
class OnResendEvent(Event):
"""Description of resent messages; response to restore() request."""
def __init__(self):
self._session_id = ""
self._begin = 0
self._end = 0
self._complete = False
return
class OnHeartbeatEvent(Event):
"""Report of heartbeat received request from Flyer Engine."""
def __init__(self):
self._id = ""
return
class OnErrorEvent(Event):
"""Report of an asynchronous error from the engine or API."""
def __init__(self):
self._code = 0
self._message = ""
self._fix_message = ""
self._client_message_id = ""
return
class OnPayloadEvent(Event):
"""Delivery of an application protocol message from Flyer Engine."""
def __init__(self):
self._session_id = ""
self._fix_message = ""
return
|
VERSION = (0, 1)
YFANTASY_MAIN = 'yfantasy'
def get_package_version():
return '%s.%s' % (VERSION[0], VERSION[1])
|
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
class Solution:
def maxProfit_as_many_transactions(self, prices):
if not prices:
return 0
profit, prev = 0, prices[0]
for i in range(1, len(prices)):
if prices[i] >= prices[i-1]:
profit = profit + prices[i]-prices[i-1]
return profit
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if len(prices) <= 1 or k == 0: return 0
k = min(k, len(prices)-1)
if k >= len(prices) - 1:
return self.maxProfit_as_many_transactions(prices)
# Create 2d array
maxes = []
for _ in range(k+1):
maxes.append([0]*len(prices))
# Set values in 2d array of max profits
# k -> number of transactions
# i -> the current day
for k in range(1, k+1):
curr = -prices[0]
for i in range(1, len(prices)):
maxes[k][i] = max(maxes[k][i-1], curr + prices[i])
curr = max(curr, maxes[k-1][i-1] - prices[i])
return maxes[k][len(prices)-1]
#-------------------------------------------------------------------------------
# Testing
|
# -*- coding: utf-8 -*-
"""Dashboard routes that lead to JSONs without providing parameters."""
routes = {
'netwide': {
'client_list': '/usage/client_list_json',
'topology': '/l3_topology/show',
'event_types': '/dashboard/event_autocomplete_types',
'alerts': '/alerts/show',
'admin_emails': '/alerts/typeahead_emails',
'possible_clients': '/alerts/possible_clients',
'inventory': '/organization/inventory_data',
'event_log': '/dashboard/event_log#',
'users': '/configure/guests',
},
'node': {
'node_info': '/nodes/json?orgwide=true',
'node_settings': '/configure/settings',
},
'mx': {
'dhcp_subnet': '/nodes/dhcp_subnet_json',
'router_settings': '/configure/router_settings_json',
'wireless': '/configure/radio_json',
'routes': '/nodes/get_routes_json',
'fetch_networks': '/vpn/fetch_networks',
'fetch_inter': '/vpn/fetch_inter_usage',
},
'ms': {
'switchports': '/nodes/ports_json',
'dai': '/configure/switch_heterogeneous_features_json/dai',
'switch_l3': '/switch_l3/show',
'ipv6_acl': '/configure/switch_heterogeneous_features_json/ipv6_acl',
'ipv4_meraki_acl': '/configure/switch_meraki_acl_json',
'ipv4_user_acl': '/configure/switch_user_acl_json',
'switch_walled_garden': '/configure/switch_heterogeneous_features_json'
'/sm_and_walled_garden',
'qos': '/configure/switch_heterogeneous_features_json/port_range_qos',
'firmware_upgrades': '/configure/firmware_upgrades_json',
},
'mr': {
'rf_profiles': '/configure/render_rf_profiles_json',
'rf_interference': '/configure/interference_json',
'ssids': '/configure/ssids_json',
'mr_topology': '/nodes/get_topology',
'air_marshal_config': '/dashboard/load_air_marshal_config',
'air_marshal_containment': '/dashboard/load_air_marshal_containment',
'foreign_ssids': '/dashboard/foreign_ssids',
'rf_overview': '/nodes/rf_overview_data',
'wireless_health': '/network_health/data_json',
'raw_connections': '/network_health/raw_connections_json',
'rf_profiles_config': '/configure/radio2_json'
},
'org': {
'administered_orgs': '/organization/administered_orgs',
'FILL ME OUT': 'I am incomplete!'
},
'insight': {
'FILL ME OUT': 'I am incomplete!'
}
}
|
nums = []
with open("day1_input", "r") as f:
for line in f:
nums.append(int(line))
# part 1
# for numA in nums:
# for numB in nums:
# # find two entries that sum to 2020:
# if (numA + numB == 2020):
# print(numA, numB)
# # their product is:
# print(numA * numB)
# part 2
for numA in nums:
for numB in nums:
for numC in nums:
# find two entries that sum to 2020:
if (numA + numB + numC == 2020):
print(numA, numB, numC)
# their product is:
print(numA * numB * numC)
|
text = input("Enter A sentence: ")
bad_words = [BADWORDSHERE]
for words in bad_words:
if words in text:
text_length = len(words)
hide_word = "*" * text_length
text = text.replace(words, hide_word)
print(text)
|
Clock.clear()
# controll #######################################################
Clock.bpm = 120
Scale.default = Scale.chromatic
Root.default = 0
p1 >> keys(
[4,6,11,13,16,18,23,25]
,dur=[0.25]
,oct=4
,vibdepth=0.3 ,vib=0.01
)
p2 >> blip(
[4,6,11,13,15,16,18,23,25]
,dur=[0.25]
,oct=3
,sus=2
,vibdepth=0.3 ,vib=0.01
,amp=0.35
)
p3 >> bass(
[(11,16),[(11,16,18),(11,16,23)]]
,dur=[3.5]
,oct=6
,sus=6
,vibdepth=0.1 ,vib=0.01
,amp=0.25
)
p4 >> bell(
[23,22,18,13,11,6]
,dur=[0.25,0.25,0.25,0.25,0.25,0.25,4]
,oct=6
,vibdepth=0.2 ,vib=0.01
,amp=0.125
)
p5 >> swell(
[(11,6),(11,16),[(11,20),(16,23)]]
,dur=[1.25]
,amp=0.5
,vib=4, vibdepth=0.01
,oct=6
,sus=1.5
,chop=3, coarse=0)
p6 >> pasha(
[-1,6,11,(4,1,11)]
,dur=[1,1,rest(0.5),1.5]
,vibdepth=0.3 ,vib=0.21
,amp=0.15
,sus=[0.25,2]
,oct=3
)
Clock.clear()
print(Samples)
print(SynthDefs)
|
"""
Faça um programa que peça para o usuário que digite 10 valores e some-os.
qtd = int(input('Quantas vezes esse loop deve rodar? ')) # montando a estrutura do loop
soma = 0
for n in range(1, qtd+1): # loop vai rodar quantas vezes informar acima
num=int(input(f'Informe o {n}/{qtd} valor: '))
soma=soma+num
print(f'A soma é {soma}: ')
"""
qtd = int(input('Digite quantas vezes desaja receber os valores: '))
soma = 0
# +1 porque o ultimo numero do range é não inclusive
for n in range(1, qtd + 1):
num = int(input(f'Informe o {n}/{qtd} valor: '))
soma = soma + num
print(f'A soma é {soma} ')
|
"""
funcs
Descript:
File name: funcs.py
Maintainer: Kyle Gortych
created: 03-22-2022
"""
def skip(s,n):
"""
Returns a copy of s, only including positions that are multiples of n
A position is a multiple of n if pos % n == 0.
Examples:
skip('hello world',1) returns 'hello world'
skip('hello world',2) returns 'hlowrd'
skip('hello world',3) returns 'hlwl'
skip('hello world',4) returns 'hor'
Parameter s: the string to copy
Precondition: s is a nonempty string
Parameter n: the letter positions to accept
Precondition: n is an int > 0
"""
assert type(s) == str and len(s) != 0
assert type(n) == int and n > 0
s2 = ''
idx = 0
for element in s:
if idx % n == 0:
s2 = s[idx] + s2
idx += 1
return s2[::-1]
# pass
def fixed_points(tup):
"""
Returns a copy of tup, including only the "fixed points".
A fixed point of a tuple is an element that is equal to its position in the tuple.
For example 0 and 2 are fixed points of (0,3,2). The fixed points are returned in
the order that they appear in the tuple.
Examples:
fixed_points((0,3,2)) returns (0,2)
fixed_points((0,1,2)) returns (0,1,2)
fixed_points((2,1,0)) returns (1,)
Parameter tup: the tuple to copy
Precondition: tup is a tuple of ints
"""
assert type(tup) == tuple
tuplist = list(tup)
tuplist2 = []
idx = 0
for element in tuplist:
if idx == element:
tuplist2.append(tuplist[idx])
idx += 1
return tuple(tuplist2)
#pass
|
numero1 = int(input('Digite um numero: '))
numero2 = int(input('Digite um numero: '))
numero3 = int(input('Digite um numero: '))
if numero1 <= numero2 and numero1 < numero3 and numero2 <= numero3:
print('crescente')
else:
print('não está em ordem crescente')
|
# How to merge two dicts
x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}
z = {**x, **y}
print(z)
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/xavier_ssd/TrekBot/TrekBot2_WS/src/navigation/nav_core/include".split(';') if "/xavier_ssd/TrekBot/TrekBot2_WS/src/navigation/nav_core/include" != "" else []
PROJECT_CATKIN_DEPENDS = "std_msgs;geometry_msgs;tf2_ros;costmap_2d".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "nav_core"
PROJECT_SPACE_DIR = "/xavier_ssd/TrekBot/TrekBot2_WS/devel/.private/nav_core"
PROJECT_VERSION = "1.16.2"
|
# Copyright (c) 2008, Michael Lunnay <mlunnay@gmail.com.au>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""This module provides the ViewElement base class for user interface representations."""
__all__ = ['ViewElement']
class ViewElement(object):
"""This is a base class for user interface items."""
__id_store = {}
__next_id = 1
def __init__(self):
"""ViewElement initialiser."""
self.container = None
self.id = None
def set_container(self, container):
"""Set the container this ViewElement is held by.
@param container: A ViewElement subclass the holds this item.
@raise ValueError: Raised if container is not a subclass of ViewElement.
"""
if not isinstance(container, ViewElement):
raise ValueError('container must be a subclass of ViewElement.')
self.container = container
def get_container(self):
"""Return the container that holds this ViewElement."""
return self.container
def set_id(self, id):
"""Set the id for this ViewElement.
@param id: A unique identifier for this ViewElement.
@raise ValueError: Raised if id is not unique.
"""
if id == self.id:
return # nothing to do as no-op
if id in self.__id_store:
raise ValueError('ViewElement id %s is already assigned.' % id)
# remove the old id if applicable
if self.id != None and self.id in seld.__id_store:
del self.__id_store[id]
self.__id_store[id] = self
def get_id(self):
"""Return the current unique id of this ViewElement, creating a new id
if one does not yet exist."""
if self.id == None:
while self.__next_id in self.__id_store:
self.__next_id += 1
self.id = self.__next_id
self.__id_store[self.id] = self
self.id += 1
return self.id
def __eq__(self, other):
"""ViewElement comparison.
@raise NotImplemented: Raised if other is not a ViewElement subclass.
"""
if not isinstance(other, ViewElement):
raise NotImplemented('ViewElement only supports comparison with other ViewElement subclasses.')
return self.get_id() == other.get_id()
|
#!/usr/bin/env python
# coding: utf-8
# In[9]:
for i in range(int(input())) :
print('Distances: ', end='')
X,Y = input().split()
Z = zip(X, Y)
for S in Z :
x = ord(S[0]) - ord('A') + 1
y = ord(S[1]) - ord('A') + 1
if x <= y :
print(y-x, end= ' ')
else :
print((y+26)-x, end=' ')
print()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.