content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
class Tree(object):
def __init__(self):
self.children = []
self.metadata = []
def add_child(self, leaf):
self.children.append(leaf)
def add_metadata(self, metadata):
self.metadata.append(metadata)
def sum_metadata(self):
metasum = sum(self.metadata)
for c in self.children:
metasum += c.sum_metadata()
return metasum
def sum_tree(self):
child_count = len(self.children)
if child_count > 0:
metasum = 0
for x in self.metadata:
if 0 < x <= child_count:
metasum += self.children[x - 1].sum_tree()
else:
metasum = self.sum_metadata()
return metasum
class Datapump(object):
def __init__(self, data):
self.data = data
self.point = 0
def __iter__(self):
return self
def __next__(self):
if self.point < len(self.data):
res, self.point = self.data[self.point], self.point + 1
return res
else:
raise StopIteration()
def next(self):
return self.__next__()
def parse_tree(tree_data):
leaf = Tree()
children = tree_data.next()
metadata = tree_data.next()
for _ in range(children):
leaf.add_child(parse_tree(tree_data))
for _ in range(metadata):
leaf.add_metadata(tree_data.next())
return leaf
def memory_maneuver_part_1(inp):
datapump = Datapump([int(i) for i in inp[0].split()])
tree = parse_tree(datapump)
return tree.sum_metadata()
def memory_maneuver_part_2(inp):
datapump = Datapump([int(i) for i in inp[0].split()])
tree = parse_tree(datapump)
return tree.sum_tree()
if __name__ == '__main__':
with open('input.txt') as license_file:
license_lines = license_file.read().splitlines(keepends=False)
print(f'Day 8, part 1: {memory_maneuver_part_1(license_lines)}')
print(f'Day 8, part 2: {memory_maneuver_part_2(license_lines)}')
# Day 8, part 1: 45618
# Day 8, part 2: 22306
|
class Tree(object):
def __init__(self):
self.children = []
self.metadata = []
def add_child(self, leaf):
self.children.append(leaf)
def add_metadata(self, metadata):
self.metadata.append(metadata)
def sum_metadata(self):
metasum = sum(self.metadata)
for c in self.children:
metasum += c.sum_metadata()
return metasum
def sum_tree(self):
child_count = len(self.children)
if child_count > 0:
metasum = 0
for x in self.metadata:
if 0 < x <= child_count:
metasum += self.children[x - 1].sum_tree()
else:
metasum = self.sum_metadata()
return metasum
class Datapump(object):
def __init__(self, data):
self.data = data
self.point = 0
def __iter__(self):
return self
def __next__(self):
if self.point < len(self.data):
(res, self.point) = (self.data[self.point], self.point + 1)
return res
else:
raise stop_iteration()
def next(self):
return self.__next__()
def parse_tree(tree_data):
leaf = tree()
children = tree_data.next()
metadata = tree_data.next()
for _ in range(children):
leaf.add_child(parse_tree(tree_data))
for _ in range(metadata):
leaf.add_metadata(tree_data.next())
return leaf
def memory_maneuver_part_1(inp):
datapump = datapump([int(i) for i in inp[0].split()])
tree = parse_tree(datapump)
return tree.sum_metadata()
def memory_maneuver_part_2(inp):
datapump = datapump([int(i) for i in inp[0].split()])
tree = parse_tree(datapump)
return tree.sum_tree()
if __name__ == '__main__':
with open('input.txt') as license_file:
license_lines = license_file.read().splitlines(keepends=False)
print(f'Day 8, part 1: {memory_maneuver_part_1(license_lines)}')
print(f'Day 8, part 2: {memory_maneuver_part_2(license_lines)}')
|
print("RENTAL MOBIL ABCD")
print("-------------------------------")
#Input
nama = input("Masukkan Nama Anda : ")
umur = int(input("Masukkan Umur Anda : "))
if umur < 18:
print("Maaf", nama, "anda belum bisa meminjam kendaraan")
else:
ktp = int(input("Masukkan Nomor KTP Anda : "))
k_mobil = input("Kategori Mobil [4/6/8 orang] : ")
if k_mobil == "4" :
kapasitasmobil = "4 orang"
harga = 300000
elif k_mobil == "6" :
kapasitasmobil = "6 orang"
harga = 350000
else:
kapasitasmobil = "8 orang"
harga = 500000
jam = int(input("Masukkan Durasi Peminjaman (dalam hari): "))
if jam > 6:
diskon = (jam*harga)*0.1
else:
diskon = 0
total = (jam*harga)
print("-------------------------------")
print("RENTAL MOBIL ABCD")
print("-------------------------------")
print("Masukkan Nama Anda : "+str(nama))
print("Masukkan Umur Anda : "+str(umur))
print("Masukkan Nomor KTP Anda : "+str(ktp))
print("Kapasitas Mobil : "+str(k_mobil))
print("Harga : ",+(harga))
print("Potongan yang didapat : ",+(diskon))
print("-------------------------------")
print("Total Bayar : ",+(total))
|
print('RENTAL MOBIL ABCD')
print('-------------------------------')
nama = input('Masukkan Nama Anda : ')
umur = int(input('Masukkan Umur Anda : '))
if umur < 18:
print('Maaf', nama, 'anda belum bisa meminjam kendaraan')
else:
ktp = int(input('Masukkan Nomor KTP Anda : '))
k_mobil = input('Kategori Mobil [4/6/8 orang] : ')
if k_mobil == '4':
kapasitasmobil = '4 orang'
harga = 300000
elif k_mobil == '6':
kapasitasmobil = '6 orang'
harga = 350000
else:
kapasitasmobil = '8 orang'
harga = 500000
jam = int(input('Masukkan Durasi Peminjaman (dalam hari): '))
if jam > 6:
diskon = jam * harga * 0.1
else:
diskon = 0
total = jam * harga
print('-------------------------------')
print('RENTAL MOBIL ABCD')
print('-------------------------------')
print('Masukkan Nama Anda : ' + str(nama))
print('Masukkan Umur Anda : ' + str(umur))
print('Masukkan Nomor KTP Anda : ' + str(ktp))
print('Kapasitas Mobil : ' + str(k_mobil))
print('Harga : ', +harga)
print('Potongan yang didapat : ', +diskon)
print('-------------------------------')
print('Total Bayar : ', +total)
|
def func_that_raises():
raise ValueError('Error message')
def func_no_catch():
func_that_raises()
|
def func_that_raises():
raise value_error('Error message')
def func_no_catch():
func_that_raises()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 07:34:02 2020
@author: krishan
"""
class BaseClass:
num_base_calls = 0
def call_me(self):
print("Calling method on Base Class")
self.num_base_calls += 1
class LeftSubclass(BaseClass):
num_left_calls = 0
def call_me(self):
BaseClass.call_me(self)
print("Calling method on Left Subclass")
self.num_left_calls += 1
class RightSubclass(BaseClass):
num_right_calls = 0
def call_me(self):
BaseClass.call_me(self)
print("Calling method on Right Subclass")
self.num_right_calls += 1
class Subclass(LeftSubclass, RightSubclass):
num_sub_calls = 0
def call_me(self):
LeftSubclass.call_me(self)
RightSubclass.call_me(self)
print("Calling method on Subclass")
self.num_sub_calls += 1
|
"""
Created on Tue Jun 16 07:34:02 2020
@author: krishan
"""
class Baseclass:
num_base_calls = 0
def call_me(self):
print('Calling method on Base Class')
self.num_base_calls += 1
class Leftsubclass(BaseClass):
num_left_calls = 0
def call_me(self):
BaseClass.call_me(self)
print('Calling method on Left Subclass')
self.num_left_calls += 1
class Rightsubclass(BaseClass):
num_right_calls = 0
def call_me(self):
BaseClass.call_me(self)
print('Calling method on Right Subclass')
self.num_right_calls += 1
class Subclass(LeftSubclass, RightSubclass):
num_sub_calls = 0
def call_me(self):
LeftSubclass.call_me(self)
RightSubclass.call_me(self)
print('Calling method on Subclass')
self.num_sub_calls += 1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2017 JiNong Inc. All right reserved.
#
__title__ = 'python-pyjns'
__version__ = '0.40'
__author__ = 'Kim, JoonYong'
__email__ = 'joonyong.jinong@gmail.com'
__copyright__ = 'Copyright 2016-2017 JiNong Inc.'
|
__title__ = 'python-pyjns'
__version__ = '0.40'
__author__ = 'Kim, JoonYong'
__email__ = 'joonyong.jinong@gmail.com'
__copyright__ = 'Copyright 2016-2017 JiNong Inc.'
|
"""
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines,
which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
Example 1
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
Example 3:
Input: height = [4,3,2,1,4]
Output: 16
Example 4:
Input: height = [1,2,1]
Output: 2
Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
"""
# V0
# IDEA : TWO POINTERS
class Solution(object):
def maxArea(self, height):
ans = 0
l = 0
r = len(height) - 1
while l < r:
ans = max(ans, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return ans
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82822939
# IDEA : TWO POINTERS
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
ans = 0
l = 0
r = len(height) - 1
while l < r:
ans = max(ans, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return ans
# V1'
# https://www.jiuzhang.com/solution/container-with-most-water/#tag-highlight-lang-python
class Solution(object):
def maxArea(self, height):
left, right = 0, len(height) - 1
ans = 0
while left < right:
if height[left] < height[right]:
area = height[left] * (right - left)
left += 1
else:
area = height[right] * (right - left)
right -= 1
ans = max(ans, area)
return ans
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
# @return an integer
def maxArea(self, height):
max_area, i, j = 0, 0, len(height) - 1
while i < j:
max_area = max(max_area, min(height[i], height[j]) * (j - i))
if height[i] < height[j]:
i += 1
else:
j -= 1
return max_area
|
"""
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines,
which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
Example 1
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
Example 3:
Input: height = [4,3,2,1,4]
Output: 16
Example 4:
Input: height = [1,2,1]
Output: 2
Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
"""
class Solution(object):
def max_area(self, height):
ans = 0
l = 0
r = len(height) - 1
while l < r:
ans = max(ans, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return ans
class Solution(object):
def max_area(self, height):
"""
:type height: List[int]
:rtype: int
"""
ans = 0
l = 0
r = len(height) - 1
while l < r:
ans = max(ans, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return ans
class Solution(object):
def max_area(self, height):
(left, right) = (0, len(height) - 1)
ans = 0
while left < right:
if height[left] < height[right]:
area = height[left] * (right - left)
left += 1
else:
area = height[right] * (right - left)
right -= 1
ans = max(ans, area)
return ans
class Solution(object):
def max_area(self, height):
(max_area, i, j) = (0, 0, len(height) - 1)
while i < j:
max_area = max(max_area, min(height[i], height[j]) * (j - i))
if height[i] < height[j]:
i += 1
else:
j -= 1
return max_area
|
extensions = [
"cogs.help",
"cogs.game_punishments.ban",
"cogs.game_punishments.kick",
"cogs.game_punishments.unban",
"cogs.game_punishments.warn",
"cogs.settings.setchannel",
"cogs.verification.verify"
]
|
extensions = ['cogs.help', 'cogs.game_punishments.ban', 'cogs.game_punishments.kick', 'cogs.game_punishments.unban', 'cogs.game_punishments.warn', 'cogs.settings.setchannel', 'cogs.verification.verify']
|
def __getitem__(self,idx):
if idx < self.lastIndex:
return self.myArray[idx]
else:
raise LookupError('index out of bounds')
def __setitem__(self,idx,val):
if idx < self.lastIndex:
self.myArray[idx] = val
else:
raise LookupError('index out of bounds')
|
def __getitem__(self, idx):
if idx < self.lastIndex:
return self.myArray[idx]
else:
raise lookup_error('index out of bounds')
def __setitem__(self, idx, val):
if idx < self.lastIndex:
self.myArray[idx] = val
else:
raise lookup_error('index out of bounds')
|
__author__ = "Amane Katagiri"
__contact__ = "amane@ama.ne.jp"
__copyright__ = "Copyright (C) 2016 Amane Katagiri"
__credits__ = ""
__date__ = "2016-12-07"
__license__ = "MIT License"
__version__ = "0.1.0"
|
__author__ = 'Amane Katagiri'
__contact__ = 'amane@ama.ne.jp'
__copyright__ = 'Copyright (C) 2016 Amane Katagiri'
__credits__ = ''
__date__ = '2016-12-07'
__license__ = 'MIT License'
__version__ = '0.1.0'
|
example_dict = {}
for idx in range(0, 10):
example_dict[idx] = idx
for key, value in example_dict.items():
formmating = f'key is {key}, value is {value}'
print(formmating)
|
example_dict = {}
for idx in range(0, 10):
example_dict[idx] = idx
for (key, value) in example_dict.items():
formmating = f'key is {key}, value is {value}'
print(formmating)
|
def minimumSwaps(arr):
a = dict(enumerate(arr,1))
b = {v:k for k,v in a.items()}
count = 0
for i in a:
x = a[i]
if x!=i:
y = b[i]
a[y] = x
b[x] = y
count+=1
return count
n = int(input())
arr = list(map(int,input().split()))
print(minimumSwaps(arr))
|
def minimum_swaps(arr):
a = dict(enumerate(arr, 1))
b = {v: k for (k, v) in a.items()}
count = 0
for i in a:
x = a[i]
if x != i:
y = b[i]
a[y] = x
b[x] = y
count += 1
return count
n = int(input())
arr = list(map(int, input().split()))
print(minimum_swaps(arr))
|
class TMVError(Exception):
""" Base exception """
class CameraError(Exception):
"""" Hardware camera problem"""
class ButtonError(Exception):
""" Problem with (usually hardware) buttons """
class VideoMakerError(Exception):
""" Problem making images into a video """
class ImageError(Exception):
""" Problem with an image """
class ConfigError(TMVError):
""" TOML or config error """
class PiJuiceError(TMVError):
""" Cound't power off"""
class PowerOff(TMVError):
""" Camera can power off """
class SignalException(TMVError):
""" Camera got a sigint """
|
class Tmverror(Exception):
""" Base exception """
class Cameraerror(Exception):
"""" Hardware camera problem"""
class Buttonerror(Exception):
""" Problem with (usually hardware) buttons """
class Videomakererror(Exception):
""" Problem making images into a video """
class Imageerror(Exception):
""" Problem with an image """
class Configerror(TMVError):
""" TOML or config error """
class Pijuiceerror(TMVError):
""" Cound't power off"""
class Poweroff(TMVError):
""" Camera can power off """
class Signalexception(TMVError):
""" Camera got a sigint """
|
def extract_characters(*file):
with open("file3.txt") as f:
while True:
c = f.read(1)
if not c:
break
print(c)
extract_characters('file3.txt')
|
def extract_characters(*file):
with open('file3.txt') as f:
while True:
c = f.read(1)
if not c:
break
print(c)
extract_characters('file3.txt')
|
class MTUError(Exception):
pass
class MACError(Exception):
pass
class IPv4AddressError(Exception):
pass
|
class Mtuerror(Exception):
pass
class Macerror(Exception):
pass
class Ipv4Addresserror(Exception):
pass
|
def cyclesort(lst):
for i in range(len(lst)):
if i != lst[i]:
n = i
while 1:
tmp = lst[int(n)]
if n != i:
lst[int(n)] = last_value
lst.log()
else:
lst[int(n)] = None
lst.log()
last_value = tmp
n = last_value
if n == i:
lst[int(n)] = last_value
lst.log()
break
|
def cyclesort(lst):
for i in range(len(lst)):
if i != lst[i]:
n = i
while 1:
tmp = lst[int(n)]
if n != i:
lst[int(n)] = last_value
lst.log()
else:
lst[int(n)] = None
lst.log()
last_value = tmp
n = last_value
if n == i:
lst[int(n)] = last_value
lst.log()
break
|
# -*- 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)
|
"""
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.
"""
def find_empty(grid):
grid_dim = 9
for row in range(gridDim):
for col in range(gridDim):
if grid[row][col] == 0:
return (row, col)
return None
def is_valid(num, pos, grid):
grid_dim = 9
box_dim = 3
row_num = pos[0]
col_num = pos[1]
for col in range(gridDim):
if grid[row_num][col] == num:
return False
for row in range(gridDim):
if grid[row][col_num] == num:
return False
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
return True
def sudoku_solver(grid):
grid_dim = 9
start = 1
empty_pos = find_empty(grid)
if bool(empty_pos):
(row, col) = empty_pos
else:
return True
for n in range(start, gridDim + 1):
if is_valid(n, (row, col), grid):
grid[row][col] = n
if sudoku_solver(grid):
return True
grid[row][col] = 0
return False
def print_solution(grid):
if sudoku_solver(grid):
grid_dim = 9
for row in range(gridDim):
for col in range(gridDim):
print(grid[row][col], end=' ')
print('')
else:
print('No solution found')
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()
|
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'
|
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'
|
#
# 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)
|
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)
|
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])
|
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])
|
{
"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=''"
]
}
]
]
}
]
}
|
{'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'])
|
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)
|
"""
Author: ZHAO Zinan
Created: 10. March 2019
1005. Maximize Sum Of Array After K Negations
"""
class Solution:
def largest_sum_after_k_negations(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()
|
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
|
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"},
}
|
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")
|
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'
|
"""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
|
def add_time(start, duration, start_day=''):
new_time = ''
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
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)
hours_24h = int(start_hours) + 12 * (1 if AM_PM == 'PM' else 0) + mins_24h // 60 + int(duration_hours)
mins_24h = mins_24h % 60
days_24h = hours_24h // 24
hours_24h = hours_24h % 24
am_pm_12h = 'PM' if hours_24h >= 12 else 'AM'
hours_12h = hours_24h - 12 if AM_PM_12h == 'PM' else hours_24h
if hours_12h == 0:
hours_12h += 12
mins_12h = mins_24h
new_time = str(hours_12h) + ':' + str(mins_12h).rjust(2, '0') + ' ' + AM_PM_12h
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'
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
|
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
|
# 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")
|
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')
def julia_listlist_to_array(dat):
dat_new = [[], [], [], [], [], [], [], [], [], [], []]
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)
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)
|
#!/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
|
__doc__ = '3D obj file loader'
__status__ = 'Development'
__version__ = '2.0.0'
__license__ = 'public domain'
__date__ = '2010'
__author__ = 'N-zo syslog@laposte.net'
__maintainer__ = 'Nzo'
__credits__ = []
__contact__ = 'syslog@laposte.net'
def load_obj_file(filepath):
"""read 3D obj file and return data"""
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':
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)
|
def quick_sort(A, si, ei):
if si < ei:
pi = partition(A, si, ei)
quick_sort(A, si, pi - 1)
quick_sort(A, pi + 1, ei)
def partition(A, si, ei):
x = A[ei]
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
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
|
"""
@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
|
class Proxy:
proxies = []
def get_proxy_list(self):
url = 'https://www.sslproxies.org/'
header = {'User-Agent': str(ua.random)}
response = requests.get(url, headers=header)
soup = beautiful_soup(response.text, 'lxml')
proxies_table = soup.find(id='proxylisttable')
try:
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 get_proxy_list2(self, proxies):
try:
url = 'http://list.proxylistplus.com/SSL-List-1'
header = {'User-Agent': str(ua.random)}
response = requests.get(url, headers=header)
soup = beautiful_soup(response.text, 'lxml')
proxies_table = soup.find('table', {'class': 'bg'})
for row in proxies_table.find_all('tr', {'class': 'cells'}):
google = row.find_all('td')[5].string
if google == 'yes':
self.proxies.append({'ip': row.find_all('td')[1].string, 'port': row.find_all('td')[2].string})
except:
print('broken')
try:
url = 'http://list.proxylistplus.com/SSL-List-2'
header = {'User-Agent': str(ua.random)}
response = requests.get(url, headers=header)
soup = beautiful_soup(response.text, 'lxml')
proxies_table = soup.find('table', {'class': 'bg'})
for row in proxies_table.find_all('tr', {'class': 'cells'}):
google = row.find_all('td')[5].string
if google == 'yes':
self.proxies.append({'ip': row.find_all('td')[1].string, 'port': row.find_all('td')[2].string})
except:
print('broken')
return proxies
def get_proxy(self):
proxies = self.getProxyList()
proxies = self.getProxyList2(proxies)
proxy = random.choice(proxies)
return proxy
|
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).
"""
|
input = '\nmysum(X) :- #sum{P: c(P)} = X, dom(X).\nmycount(X) :- #count{P: c(P)} = X, dom(X).\n\ndom(0). dom(1).\nc(X) | d(X) :- dom(X).\n\n:- not c(0).\n:- not c(1).\n'
output = '\nmysum(X) :- #sum{P: c(P)} = X, dom(X).\nmycount(X) :- #count{P: c(P)} = X, dom(X).\n\ndom(0). dom(1).\nc(X) | d(X) :- dom(X).\n\n:- not c(0).\n:- not c(1).\n'
|
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]))
|
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)
|
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)
|
class Solution(object):
def __init__(self):
self.max = 0
self.min = 10000
def max_ancestor_diff(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.findMaxDiff(root, 10000, 0)
def iq_test(self, numbers):
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 find_max_diff(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)
|
# 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 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'})
|
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)
|
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion')
(entry_status,) = mibBuilder.importSymbols('RMON-MIB', 'EntryStatus')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, object_identity, unsigned32, iso, mib_identifier, ip_address, notification_type, integer32, time_ticks, 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')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
zte = mib_identifier((1, 3, 6, 1, 4, 1, 3902))
zxr10 = mib_identifier((1, 3, 6, 1, 4, 1, 3902, 3))
zxr10protocol = mib_identifier((1, 3, 6, 1, 4, 1, 3902, 3, 101))
zxr10vswitch = module_identity((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):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 2))
named_values = named_values(('ip', 0), ('vlan', 1), ('mix', 2))
class Vsiwtchvlandirection(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1))
named_values = named_values(('intoout', 0), ('both', 1))
zxr10vswitch_if_table = mib_table((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1))
if mibBuilder.loadTexts:
zxr10vswitchIfTable.setStatus('current')
zxr10vswitch_if_entry = mib_table_row((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1)).setIndexNames((0, 'ZXR10-VSWITCH-MIB', 'zxr10vsiwtchIfIndex'))
if mibBuilder.loadTexts:
zxr10vswitchIfEntry.setStatus('current')
zxr10vsiwtch_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vsiwtchIfIndex.setStatus('current')
zxr10vswitch_if_type = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchIfType.setStatus('current')
zxr10vswitch_if_trans_type = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 3), vsiwtch_trans_mode()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchIfTransType.setStatus('current')
zxr10vswitch_if_status = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 4), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchIfStatus.setStatus('current')
zxr10vswitch_if_addr = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 5), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchIfAddr.setStatus('current')
zxr10vswitch_if_desc = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
zxr10vswitchIfDesc.setStatus('current')
zxr10vswitch_if_table_lastchange = mib_scalar((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 2), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchIfTableLastchange.setStatus('current')
zxr10vswitch_vlan_table = mib_table((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3))
if mibBuilder.loadTexts:
zxr10vswitchVlanTable.setStatus('current')
zxr10vsiwtch_vlan_entry = mib_table_row((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')
zxr10vswitch_vlan_ingress_ext_vlanid = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchVlanIngressExtVlanid.setStatus('current')
zxr10vswitch_vlan_ingress_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchVlanIngressIfIndex.setStatus('current')
zxr10vswitch_vlan_ingress_int_vlanid = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 3), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchVlanIngressIntVlanid.setStatus('current')
zxr10vswitch_vlan_egress_ext_vlanid = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 4), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zxr10vswitchVlanEgressExtVlanid.setStatus('current')
zxr10vswitch_vlan_egress_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 5), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zxr10vswitchVlanEgressIfIndex.setStatus('current')
zxr10vswitch_vlan_egress_int_vlanid = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 6), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
zxr10vswitchVlanEgressIntVlanid.setStatus('current')
zxr10vswitch_vlan_vlanid_range = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 7), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zxr10vswitchVlanVlanidRange.setStatus('current')
zxr10vswitch_vland_direction = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 8), vsiwtch_vlan_direction()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zxr10vswitchVlandDirection.setStatus('current')
zxr10vswitch_vlan_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 9), entry_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zxr10vswitchVlanRowStatus.setStatus('current')
zxr10vswitch_vlan_desc = mib_table_column((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 10), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zxr10vswitchVlanDesc.setStatus('current')
zxr10vswitch_vlan_table_lastchange = mib_scalar((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 4), time_ticks()).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")
|
del_items(2148674112)
set_type(2148674112, 'struct Creds CreditsTitle[6]')
del_items(2148674536)
set_type(2148674536, 'struct Creds CreditsSubTitle[28]')
del_items(2148675716)
set_type(2148675716, 'struct Creds CreditsText[35]')
del_items(2148675996)
set_type(2148675996, 'int CreditsTable[224]')
del_items(2148680636)
set_type(2148680636, 'struct DIRENTRY card_dir[16][2]')
del_items(2148681916)
set_type(2148681916, 'struct file_header card_header[16][2]')
del_items(2148680416)
set_type(2148680416, 'struct sjis sjis_table[37]')
del_items(2148702140)
set_type(2148702140, 'unsigned char save_buffer[106496]')
del_items(2148701988)
set_type(2148701988, 'struct FeTable McLoadGameMenu')
del_items(2148701956)
set_type(2148701956, 'char *CharFileList[5]')
del_items(2148701976)
set_type(2148701976, 'char *Classes[3]')
del_items(2148702016)
set_type(2148702016, 'struct FeTable McLoadCharMenu')
del_items(2148702044)
set_type(2148702044, 'struct FeTable McLoadCard1Menu')
del_items(2148702072)
set_type(2148702072, 'struct FeTable McLoadCard2Menu')
|
# -*- coding: utf-8 -*-
class RegisterException(Exception):
"""Exception raised on a registration error."""
|
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")
|
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)
|
def print_factors(n):
for i in range(1, n + 1):
if n % i == 0:
print(i)
number = int(input('Enter a number : '))
print('The factors for {} are : '.format(number))
print_factors(number)
|
# 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)
|
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
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" ]
}
]
}
|
{'targets': [{'target_name': 'node-cursor', 'sources': ['node-cursor.cc']}]}
|
"""
A stub module to house pyrolite extensions,
where they are installed.
"""
|
"""
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
|
class Solution:
def longest_common_prefix(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)
|
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))
|
def solution(coins, amount):
coins = sorted(coins)
min_coins = [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))
|
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}>'
|
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
|
class Solution:
def set_zeroes(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
|
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)
|
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")
|
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
|
class Solution:
def my_pow(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)
#################################
|
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 reverse_prefix(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 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")
|
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 value_error('Given value is not of correct type')
elif not isinstance(value, int):
raise value_error('Given value is not of correct type')
rule['value'] = str(value).lower()
return True
raise value_error(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]))
|
def mystery_algorithm(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(mystery_algorithm([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
|
"""
practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses
by Aashik J Krishnan/Aash Gates
"""
x = 10
y = 'ten'
temp = x
x = y
y = temp
print(x)
print(y)
print(temp)
|
#
# @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]
|
class Solution:
def reverse_str(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 reverse_all_str(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")
|
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))
|
"""
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(object):
def h_index(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 h_index2(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
|
class Solution:
def find_judge(self, N: int, trust: List[List[int]]) -> int:
e = len(trust)
if E < N - 1:
return -1
trust_score = [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)
|
line = '-' * 39
bases = '|' + ' ' + 'decimal' + ' ' + '|' + ' ' + 'octal' + ' ' + '|' + ' ' + 'Hexadecimal' + ' ' + '|'
blank_num1 = '|' + ' ' * 6 + '{0}' + ' ' * 4 + '|' + ' ' * 4 + '{1}' + ' ' * 4 + '|' + ' ' * 7 + '{2}' + ' ' * 7 + '|'
blank_num2 = '|' + ' ' * 6 + '{0}' + ' ' * 4 + '|' + ' ' * 3 + '{1}' + ' ' * 4 + '|' + ' ' * 7 + '{2}' + ' ' * 7 + '|'
blank_num3 = '|' + ' ' * 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.
"""
|
"""
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)
|
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 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 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])
|
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:
if board[i][j] == 0:
if x == -1 and can_place_queen(board, i, j, r, c):
y = i
x = j
continue
elif can_place_queen(board, i, j, r, c):
board[i][j] = 1
else:
board[y][x] = 1
j += 1
i += 1
def can_place_queen(board, i, j, r, c):
if is_vertical_free(board, j, r, c) and is_horizontal_free(board, i, r, c) and is_diagonal_free(board, i, j, r, c):
return True
return False
def is_vertical_free(board, j, r, c):
for i in range(r):
if board[i][j] != 0:
return False
return True
def is_horizontal_free(board, i, r, c):
for j in range(c):
if board[i][j] != 0:
return False
return True
def is_diagonal_free(board, i, j, r, c):
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
for col in range(len(columns)):
if can_place(columns, row, col):
columns[row] = col
queues_book_solution(row + 1, columns, result)
def can_place(columns, row, col):
for row2 in range(row):
col2 = columns[row2]
if col2 == col:
return False
col_distance = abs(col - col2)
row_distance = row - row2
if col_distance == row_distance:
return False
return True
if __name__ == '__main__':
results = []
columns = [0] * 8
queues_book_solution(0, columns, results)
for i in range(len(results)):
r = results[i]
print(r)
|
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 >')
|
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
|
class Solution:
def flip_and_invert_image(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
|
WINSTRIDE = (8, 8)
PADDING = (8, 8)
SCALE = 1.15
MIN_NEIGHBORS = 5
OVERLAP_NMS = 0.9
|
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"}
|
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))
|
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)
|
def get_value(card):
value = card[0:len(card) - 1]
return int(value)
def get_suit(card):
suit = card[len(card) - 1:]
return suit
def get_cards_of_same_suit(suit, dealerCards):
cards_of_same_suit = tuple()
for c in dealerCards:
if get_suit(c) == suit:
if cardsOfSameSuit == tuple():
cards_of_same_suit = (c,)
else:
cards_of_same_suit = cardsOfSameSuit + (c,)
return cardsOfSameSuit
def get_lowest_card(dealerCards, oppSuit='', oppValue=0):
lowest_so_far = ''
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):
lowest_so_far = c
return lowestSoFar
def get_dealer_play(cardsInTuple):
opp_lead_card = cardsInTuple[0]
opp_suit = get_suit(oppLeadCard)
opp_value = get_value(oppLeadCard)
dealer_cards = cardsInTuple[1:]
lowest = get_lowest_card(dealerCards, oppSuit, oppValue)
if lowest != '':
print(lowest)
else:
lowest_suit = get_lowest_card(dealerCards, oppSuit)
lowest_card = get_lowest_card(dealerCards)
if lowestSuit == '':
print(lowestCard)
elif lowestCard != '':
print(lowestSuit)
cards_in_string = input()
cards_in_tuple = tuple(cardsInString.split())
dealer_play_card = get_dealer_play(cardsInTuple)
|
# 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
|
def bill_calculator(code, gallons):
if code == 'r':
bill = 5.0 + gallons * 0.0005
return round(bill, 2)
elif code == 'c':
if gallons <= 4000000:
bill = 1000.0
return round(bill, 2)
else:
first_half = 1000.0
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.0
return round(bill, 2)
elif 4000000 < gallons < 10000000:
bill = 2000.0
return round(bill, 2)
elif gallons > 10000000:
first_half = 2000.0
sec_half = (gallons - 10000000) * 0.00025
summed_bill = first_half + sec_half
return round(summed_bill, 2)
while True:
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
|
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
|
"""
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.
"""
class Documentaristexception(Exception):
"""Base class for Documentarist exceptions."""
pass
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
|
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
|
def default_pipe(data, config):
subjects = config.get('subjects')
mutated_data = []
for row in data:
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]
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)
]
|
expected_normal_output = 'Title Release Year Estimated Budget\nShawshank Redemption 1994 $25 000 000\nThe Godfather 1972 $6 000 000\nThe Godfather: Part II 1974 $13 000 000\nThe Dark Knight 2008 $185 000 000\n12 Angry Men 1957 $350 000'
expected_markdown_output = 'Title | Release Year | Estimated Budget\n:----------------------|:-------------|:----------------\nShawshank Redemption | 1994 | $25 000 000\nThe Godfather | 1972 | $6 000 000\nThe Godfather: Part II | 1974 | $13 000 000\nThe Dark Knight | 2008 | $185 000 000\n12 Angry Men | 1957 | $350 000'
expected_right_justified_output = ' Title Release Year Estimated Budget\n Shawshank Redemption 1994 $25 000 000\n The Godfather 1972 $6 000 000\nThe Godfather: Part II 1974 $13 000 000\n The Dark Knight 2008 $185 000 000\n 12 Angry Men 1957 $350 000'
expected_tab_output = 'Some parameter Other parameter Last parameter\nCONST 123456 12.45'
expected_header_output = '------------------------------------------------------\nTitle Release Year Estimated Budget\n------------------------------------------------------\nShawshank Redemption 1994 $25 000 000\nThe Godfather 1972 $6 000 000\nThe Godfather: Part II 1974 $13 000 000\nThe Dark Knight 2008 $185 000 000\n12 Angry Men 1957 $350 000'
expected_short_output = 'Title Release Year Estimated Budget\nShawshank Redemption 1994 $25 000 000\nThe Godfather 1972 $6 000 000'
expected_oneline_output = 'Title Release Year Estimated Budget'
expected_one_column_output = 'Estimated Budget\n$25 000 000\n$6 000 000\n$13 000 000\n$185 000 000\n$350 000'
expected_justified_markdown_output = 'Title | Release Year | Estimated Budget\n:----------------------|-------------:|----------------:\nShawshank Redemption | 1994 | $25 000 000\nThe Godfather | 1972 | $6 000 000\nThe Godfather: Part II | 1974 | $13 000 000\nThe Dark Knight | 2008 | $185 000 000\n12 Angry Men | 1957 | $350 000'
expected_header_with_decorator_output = '----------------------- o -------------- o -----------------\nTitle o Release Year o Estimated Budget\n----------------------- o -------------- o -----------------\nShawshank Redemption o 1994 o $25 000 000\nThe Godfather o 1972 o $6 000 000\nThe Godfather: Part II o 1974 o $13 000 000\nThe Dark Knight o 2008 o $185 000 000\n12 Angry Men o 1957 o $350 000'
expected_latex_output = '\\begin{tabular}{lll}\nTitle & Release Year & Estimated Budget \\\\\nShawshank Redemption & 1994 & 25 000 000 \\\\\nThe Godfather & 1972 & 6 000 000 \\\\\nThe Godfather: Part II & 1974 & 13 000 000 \\\\\nThe Dark Knight & 2008 & 185 000 000 \\\\\n12 Angry Men & 1957 & 350 000 \\\\\n\\end{tabular}'
expected_latex_with_justification_output = '\\begin{tabular}{lrr}\nTitle & Release Year & Estimated Budget \\\\\nShawshank Redemption & 1994 & 25 000 000 \\\\\nThe Godfather & 1972 & 6 000 000 \\\\\nThe Godfather: Part II & 1974 & 13 000 000 \\\\\nThe Dark Knight & 2008 & 185 000 000 \\\\\n12 Angry Men & 1957 & 350 000 \\\\\n\\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)
|
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 is_nice_part1(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 is_nice_part2(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
nice_part1_count = 0
nice_part2_count = 0
for string in data:
if is_nice_part1(string):
nice_part1_count += 1
if is_nice_part2(string):
nice_part2_count += 1
print(nicePart1Count)
print(nicePart2Count)
|
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")
|
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 = my_str('- %s - {} -')
print(ms.format('test'))
print(ms % 'test')
|
#
# 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
|
def get_game_length(history):
return history.shape[1]
def get_choice(snitch):
return 'tell truth' if snitch else 'stay silent'
def strategy(history, memory):
if get_game_length(history) == 0:
return (get_choice(False), None)
average = sum(history[1]) / history.shape[1]
snitch = average <= 0.3
return (get_choice(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
|
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])
|
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
|
class Solution:
def max_profit_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 max_profit(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)
maxes = []
for _ in range(k + 1):
maxes.append([0] * len(prices))
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]
|
# -*- 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!'
}
}
|
"""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)
|
nums = []
with open('day1_input', 'r') as f:
for line in f:
nums.append(int(line))
for num_a in nums:
for num_b in nums:
for num_c in nums:
if numA + numB + numC == 2020:
print(numA, numB, numC)
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)
|
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)
|
Clock.clear()
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)
|
"""
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
|
"""
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]
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)
|
# How to merge two dicts
x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}
z = {**x, **y}
print(z)
|
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"
|
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()
|
"""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 value_error('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
if id in self.__id_store:
raise value_error('ViewElement id %s is already assigned.' % id)
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 not_implemented('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()
|
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()
|
# from sw_site.settings.components import BASE_DIR, config
# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = config('DJANGO_SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'127.0.0.1:8000',
'localhost:8080',
'127.0.0.1:8080',
)
|
debug = True
cors_origin_whitelist = ('localhost:8000', '127.0.0.1:8000', 'localhost:8080', '127.0.0.1:8080')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.