content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
class Solution:
def InsertInterval(self, Interval, newInterval):
nums,mid = list(), 0
int_len = len(Interval)
for s,e in Interval:
if s < newInterval[0]:
nums.append([s,e])
mid += 1
else:
break
if not nums or nums[-1][1] < newInterval[0]:
nums.append(newInterval)
else:
nums[-1][1] = max(newInterval[1], nums[-1][1])
for s,e in Interval[mid:]:
if s > nums[-1][1]:
nums.append([s,e])
else:
nums[-1][1] = max(nums[-1][1], e)
return nums
if __name__ == "__main__":
a = Solution()
print(a.InsertInterval([[2,3],[6,9]], [5,7]))
print(a.InsertInterval([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]))
print(a.InsertInterval([], [4,8]))
| class Solution:
def insert_interval(self, Interval, newInterval):
(nums, mid) = (list(), 0)
int_len = len(Interval)
for (s, e) in Interval:
if s < newInterval[0]:
nums.append([s, e])
mid += 1
else:
break
if not nums or nums[-1][1] < newInterval[0]:
nums.append(newInterval)
else:
nums[-1][1] = max(newInterval[1], nums[-1][1])
for (s, e) in Interval[mid:]:
if s > nums[-1][1]:
nums.append([s, e])
else:
nums[-1][1] = max(nums[-1][1], e)
return nums
if __name__ == '__main__':
a = solution()
print(a.InsertInterval([[2, 3], [6, 9]], [5, 7]))
print(a.InsertInterval([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]))
print(a.InsertInterval([], [4, 8])) |
# Peter Thornton, 04 Mar 18
# Exercise 5
# Please complete the following exercise this week.
# Write a Python script that reads the Iris data set in and prints the four numerical values on each row in a nice format.
# That is, on the screen should be printed the petal length, petal width, sepal length and sepal width, and these values should have the decimal places aligned, with a space between the columns.
with open("iris.data.csv") as t:
for line in t:
print(line.split(',')[0], line.split(',')[1], line.split(',')[2], line.split(',')[3])
| with open('iris.data.csv') as t:
for line in t:
print(line.split(',')[0], line.split(',')[1], line.split(',')[2], line.split(',')[3]) |
EPSILON = "epsilon"
K = "k"
MAX_VALUE = "max_value"
MIN_VALUE = "min_value"
ATTRIBUTE = "attribute"
NAME = "name"
SENSITIVITY_TYPE = "sensitivity_type"
ATTRIBUTE_TYPE = "attribute_type"
# window size is used in the disclosure risk calculation
# it indicates the % of the num of records in the dataset
WINDOW_SIZE = 1
# border margin is used in differential privacy anonymization
# it indicates the margin to be applied to the attribute domain
BORDER_MARGIN = 1.5
| epsilon = 'epsilon'
k = 'k'
max_value = 'max_value'
min_value = 'min_value'
attribute = 'attribute'
name = 'name'
sensitivity_type = 'sensitivity_type'
attribute_type = 'attribute_type'
window_size = 1
border_margin = 1.5 |
pdrop = 0.1
tau = 0.1
lengthscale = 0.01
N = 364
print(lengthscale ** 2 * (1 - pdrop) / (2. * N * tau)) | pdrop = 0.1
tau = 0.1
lengthscale = 0.01
n = 364
print(lengthscale ** 2 * (1 - pdrop) / (2.0 * N * tau)) |
a = 1
b = 1
a = 1
b = 1
| a = 1
b = 1
a = 1
b = 1 |
class FrankiException(Exception):
pass
class FrankiInvalidFormatException(Exception):
pass
class FrankiFileNotFound(Exception):
pass
class FrankiInvalidFileFormat(Exception):
pass
__all__ = ("FrankiInvalidFormatException", "FrankiFileNotFound",
"FrankiInvalidFileFormat", "FrankiException")
| class Frankiexception(Exception):
pass
class Frankiinvalidformatexception(Exception):
pass
class Frankifilenotfound(Exception):
pass
class Frankiinvalidfileformat(Exception):
pass
__all__ = ('FrankiInvalidFormatException', 'FrankiFileNotFound', 'FrankiInvalidFileFormat', 'FrankiException') |
T = int(input())
for i in range(T):
m, n, a, b = map(int, input().split())
count = 0
for num in range(m, n + 1):
if num % a == 0 or num % b == 0:
count += 1
print(count)
| t = int(input())
for i in range(T):
(m, n, a, b) = map(int, input().split())
count = 0
for num in range(m, n + 1):
if num % a == 0 or num % b == 0:
count += 1
print(count) |
# This problem was asked by Airbnb.
#
# Given a list of integers, write a function that returns the largest sum of non-adjacent numbers.
# Numbers can be 0 or negative.
# For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10,
# since we pick 5 and 5.
# Follow-up: Can you do this in O(N) time and constant space?
# Input examples
input_1 = [2, 4, 6, 2, 5] # return 13
input_2 = [5, 1, 1, 5] # return 10
input_3 = [2, 14, 6, 2, 15] # return 29
input_4 = [2, 5, 11, 8, 3] # return 16
input_5 = [90, 15, 10, 30, 100] # return 200
input_6 = [29, 51, 8, 10, 43, 28] # return 94
def largest_sum_adj(arr):
result = 0
size = len(arr)
# validate the input list. It must be a length greater than 2
if size > 2:
arr[2] += arr[0]
result = arr[2]
for i in range(3, size):
tmp = arr[i-3]
if arr[i-2] > arr[i-3]:
tmp = arr[i-2]
tmp_addition = tmp + arr[i]
arr[i] = tmp_addition
if tmp_addition > result:
result = tmp_addition
else:
print("The length of input list must be greater than 2")
return result
| input_1 = [2, 4, 6, 2, 5]
input_2 = [5, 1, 1, 5]
input_3 = [2, 14, 6, 2, 15]
input_4 = [2, 5, 11, 8, 3]
input_5 = [90, 15, 10, 30, 100]
input_6 = [29, 51, 8, 10, 43, 28]
def largest_sum_adj(arr):
result = 0
size = len(arr)
if size > 2:
arr[2] += arr[0]
result = arr[2]
for i in range(3, size):
tmp = arr[i - 3]
if arr[i - 2] > arr[i - 3]:
tmp = arr[i - 2]
tmp_addition = tmp + arr[i]
arr[i] = tmp_addition
if tmp_addition > result:
result = tmp_addition
else:
print('The length of input list must be greater than 2')
return result |
def status(bot, update, webcontrol):
chat_id = update.message.chat_id
code, text = webcontrol.execute('detection', 'status')
if code == 200:
bot.sendMessage(chat_id=chat_id, text=text)
else:
bot.sendMessage(chat_id=chat_id, text="Try it later")
| def status(bot, update, webcontrol):
chat_id = update.message.chat_id
(code, text) = webcontrol.execute('detection', 'status')
if code == 200:
bot.sendMessage(chat_id=chat_id, text=text)
else:
bot.sendMessage(chat_id=chat_id, text='Try it later') |
eg = [
'forward 5',
'down 5',
'forward 8',
'up 3',
'down 8',
'forward 2',
]
def load(file):
with open(file) as f:
data = f.readlines()
return data
def steps(lines, pos_char, neg_char):
directions = [ln.split(' ') for ln in lines if ln[0] in [pos_char, neg_char]]
steps = [int(ln[1]) * (1 if ln[0][0] == pos_char else -1) for ln in directions]
return steps
def split(data):
horiz = steps(data, 'f', 'b')
vert = steps(data, 'd', 'u')
return horiz, vert
hh, vv = split(eg)
assert (sum(hh) * sum(vv)) == 150
dd = load('data.txt')
hh, vv = split(dd)
ans = sum(hh) * sum(vv)
print(f"Answer: {ans}") | eg = ['forward 5', 'down 5', 'forward 8', 'up 3', 'down 8', 'forward 2']
def load(file):
with open(file) as f:
data = f.readlines()
return data
def steps(lines, pos_char, neg_char):
directions = [ln.split(' ') for ln in lines if ln[0] in [pos_char, neg_char]]
steps = [int(ln[1]) * (1 if ln[0][0] == pos_char else -1) for ln in directions]
return steps
def split(data):
horiz = steps(data, 'f', 'b')
vert = steps(data, 'd', 'u')
return (horiz, vert)
(hh, vv) = split(eg)
assert sum(hh) * sum(vv) == 150
dd = load('data.txt')
(hh, vv) = split(dd)
ans = sum(hh) * sum(vv)
print(f'Answer: {ans}') |
def test():
print("test successful...")
def update():
print("Updating DSA")
if __name__=='__main__':
pass | def test():
print('test successful...')
def update():
print('Updating DSA')
if __name__ == '__main__':
pass |
class Component:
def __init__(self, fail_ratio, repair_ratio, state):
self.fail_ratio = fail_ratio
self.repair_ratio = repair_ratio
self.state = state | class Component:
def __init__(self, fail_ratio, repair_ratio, state):
self.fail_ratio = fail_ratio
self.repair_ratio = repair_ratio
self.state = state |
def parse():
with open("input16") as f:
n = [int(x) for x in f.read()]
return n
n = parse()
for _ in range(100):
result = []
for i in range(1, len(n) + 1):
digit = 0
start = i - 1
add = 1
while start < len(n):
end = min(start + i, len(n))
digit += add * sum(n[start:end])
add *= -1
start += 2*i
result.append(abs(digit) % 10)
n = result
print("".join([str(x) for x in n[:8]]))
# part 2
n = parse()
k = int("".join([str(x) for x in n[:7]]))
total_len = 10000 * len(n)
relevant_len = total_len - k
offset = k % len(n)
l = n[offset:] + (relevant_len // len(n)) * n
for nr in range(100):
print(nr)
result = []
cache = {}
for i in range(0, len(l)):
digit = 0
start = i
add = 1
while start < len(l):
end = min(start + i + k, len(l))
if (start - 1, end) in cache:
q = (cache[(start - 1,end)] - l[start - 1])
else:
q = sum(l[start:end])
digit += add * q
cache[(start, end)] = q
add *= -1
start += 2 * (i + k)
result.append(abs(digit) % 10)
l = result
print("".join([str(x) for x in l[:8]])) | def parse():
with open('input16') as f:
n = [int(x) for x in f.read()]
return n
n = parse()
for _ in range(100):
result = []
for i in range(1, len(n) + 1):
digit = 0
start = i - 1
add = 1
while start < len(n):
end = min(start + i, len(n))
digit += add * sum(n[start:end])
add *= -1
start += 2 * i
result.append(abs(digit) % 10)
n = result
print(''.join([str(x) for x in n[:8]]))
n = parse()
k = int(''.join([str(x) for x in n[:7]]))
total_len = 10000 * len(n)
relevant_len = total_len - k
offset = k % len(n)
l = n[offset:] + relevant_len // len(n) * n
for nr in range(100):
print(nr)
result = []
cache = {}
for i in range(0, len(l)):
digit = 0
start = i
add = 1
while start < len(l):
end = min(start + i + k, len(l))
if (start - 1, end) in cache:
q = cache[start - 1, end] - l[start - 1]
else:
q = sum(l[start:end])
digit += add * q
cache[start, end] = q
add *= -1
start += 2 * (i + k)
result.append(abs(digit) % 10)
l = result
print(''.join([str(x) for x in l[:8]])) |
expected_output = {
'slot':{
2:{
'port_group':{
1:{
'port':{
'Hu2/0/25':{
'mode':'inactive'
},
'Hu2/0/26':{
'mode':'inactive'
},
'Fou2/0/27':{
'mode':'400G'
},
'Hu2/0/28':{
'mode':'inactive'
}
}
},
2:{
'port':{
'Hu2/0/29':{
'mode':'inactive'
},
'Hu2/0/30':{
'mode':'inactive'
},
'Fou2/0/31':{
'mode':'400G'
},
'Hu2/0/32':{
'mode':'inactive'
}
}
}
}
}
}
}
| expected_output = {'slot': {2: {'port_group': {1: {'port': {'Hu2/0/25': {'mode': 'inactive'}, 'Hu2/0/26': {'mode': 'inactive'}, 'Fou2/0/27': {'mode': '400G'}, 'Hu2/0/28': {'mode': 'inactive'}}}, 2: {'port': {'Hu2/0/29': {'mode': 'inactive'}, 'Hu2/0/30': {'mode': 'inactive'}, 'Fou2/0/31': {'mode': '400G'}, 'Hu2/0/32': {'mode': 'inactive'}}}}}}} |
#!/usr/bin/env python
# coding: utf-8
# # *section 2: Basic Data Type*
#
# ### writer : Faranak Alikhah 1954128
# ### 4. Lists :
#
# In[ ]:
if __name__ == '__main__':
N = int(input())
my_list=[]
for i in range(N):
A=input().split();
if A[0]=="sort":
my_list.sort();
elif A[0]=="insert":
my_list.insert(int(A[1]),int(A[2]))
elif A[0]=="remove":
my_list.remove(int(A[1]))
elif A[0]=="append":
my_list.append(int(A[1]))
elif A[0]=="pop":
my_list.pop()
elif A[0]=="reverse":
my_list.reverse()
elif A[0]=="print":
print(my_list)
#
| if __name__ == '__main__':
n = int(input())
my_list = []
for i in range(N):
a = input().split()
if A[0] == 'sort':
my_list.sort()
elif A[0] == 'insert':
my_list.insert(int(A[1]), int(A[2]))
elif A[0] == 'remove':
my_list.remove(int(A[1]))
elif A[0] == 'append':
my_list.append(int(A[1]))
elif A[0] == 'pop':
my_list.pop()
elif A[0] == 'reverse':
my_list.reverse()
elif A[0] == 'print':
print(my_list) |
class Solution:
def hasZeroSumSubarray(self, nums: List[int]) -> bool:
vis = set()
x = 0
for n in nums :
x+=n
if x==0 or x in vis :
return 1
vis.add(x)
return 0
| class Solution:
def has_zero_sum_subarray(self, nums: List[int]) -> bool:
vis = set()
x = 0
for n in nums:
x += n
if x == 0 or x in vis:
return 1
vis.add(x)
return 0 |
# -*- coding: utf-8 -*-
# File defines a single function, a set cookie that takes a configuration
# Use only if the app cannot be imported, otherwise use .cookies
def set_cookie(config, response, key, val):
response.set_cookie(key, val,
secure = config['COOKIES_SECURE'],
httponly = config['COOKIES_HTTPONLY'],
samesite = config['COOKIES_SAMESITE']) | def set_cookie(config, response, key, val):
response.set_cookie(key, val, secure=config['COOKIES_SECURE'], httponly=config['COOKIES_HTTPONLY'], samesite=config['COOKIES_SAMESITE']) |
class Solution:
def minSwaps(self, data: List[int]) -> int:
k = data.count(1)
ones = 0 # ones in window
maxOnes = 0 # max ones in window
for i, num in enumerate(data):
if i >= k and data[i - k]:
ones -= 1
if num:
ones += 1
maxOnes = max(maxOnes, ones)
return k - maxOnes
| class Solution:
def min_swaps(self, data: List[int]) -> int:
k = data.count(1)
ones = 0
max_ones = 0
for (i, num) in enumerate(data):
if i >= k and data[i - k]:
ones -= 1
if num:
ones += 1
max_ones = max(maxOnes, ones)
return k - maxOnes |
class DNSimpleException(Exception):
def __init__(self, message=None, errors=None):
self.message = message
self.errors = errors
| class Dnsimpleexception(Exception):
def __init__(self, message=None, errors=None):
self.message = message
self.errors = errors |
polygon = [
[2000, 1333],
[2000, 300],
[500, 900],
[0, 1333],
[2000, 1333]
]
'''
polygon = [
[0, 0],
[0, 600],
[900, 600],
[1800, 0],
[0, 0]
]
''' | polygon = [[2000, 1333], [2000, 300], [500, 900], [0, 1333], [2000, 1333]]
'\npolygon = [\n\t[0, 0],\n\t[0, 600],\n\t[900, 600],\n\t[1800, 0],\n\t[0, 0]\n]\n' |
class A:
def __init__(self):
self._x = 5
class B(A):
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main() | class A:
def __init__(self):
self._x = 5
class B(A):
def display(self):
print(self._x)
def main():
obj = b()
obj.display()
main() |
arr = []
for x in range(100):
arr.append([])
arr[x] = [0 for i in range(100)]
n = int(input())
ans=0
for x in range(n):
a, b, c, d = map(int, input().split())
ans=ans+(c-a+1)*(d-b+1)
print(ans) | arr = []
for x in range(100):
arr.append([])
arr[x] = [0 for i in range(100)]
n = int(input())
ans = 0
for x in range(n):
(a, b, c, d) = map(int, input().split())
ans = ans + (c - a + 1) * (d - b + 1)
print(ans) |
alp = "abcdefghijklmnopqrstuvwxyz"
res = ""
while True:
s = __import__('sys').stdin.readline().strip()
if s == "#":
break
x, y, z = s.split()
t = ""
for i in range(len(x)):
dif = (ord(y[i]) - ord(x[i]) + 26) % 26
t += alp[(ord(z[i]) - ord('a') + dif) % 26]
res += s + " " + t + "\n"
print(res, end="")
| alp = 'abcdefghijklmnopqrstuvwxyz'
res = ''
while True:
s = __import__('sys').stdin.readline().strip()
if s == '#':
break
(x, y, z) = s.split()
t = ''
for i in range(len(x)):
dif = (ord(y[i]) - ord(x[i]) + 26) % 26
t += alp[(ord(z[i]) - ord('a') + dif) % 26]
res += s + ' ' + t + '\n'
print(res, end='') |
class Day10:
ILLEGAL_CHAR_TO_POINTS = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
def __init__(self, input="src/input/day10.txt"):
self.INPUT = input
def read_input(self):
input = []
with open(self.INPUT, "r") as fp:
lines = fp.readlines()
input = [line.strip() for line in lines]
return input
def part1(self):
input = self.read_input()
# remove all legal chunks
legal_chunks = ["()", "{}", "<>", "[]"]
cleaned_input = []
for line in input:
prev_length = float("inf")
while prev_length > len(line):
prev_length = len(line)
for chunk in legal_chunks:
line = line.replace(chunk, "")
cleaned_input.append(line)
# check if incomplete or illegal
illegal_characters = []
for line in cleaned_input:
for char in line:
if char not in ["(", "{", "<", "["]:
illegal_characters.append(char)
break
return sum([self.ILLEGAL_CHAR_TO_POINTS[char] for char in illegal_characters])
def part2(self):
input = self.read_input()
# remove all legal chunks
legal_chunks = ["()", "{}", "<>", "[]"]
cleaned_input = []
for line in input:
prev_length = float("inf")
while prev_length > len(line):
prev_length = len(line)
for chunk in legal_chunks:
line = line.replace(chunk, "")
cleaned_input.append(line)
# discard corrupted lines
incomplete_input = []
for line in cleaned_input:
closings = [")", "}", ">", "]"]
check = False
for closing in closings:
if closing in line:
check = True
if not check:
incomplete_input.append(line)
# reverse the order
missing_input = [line[::-1] for line in incomplete_input]
# reverse doesn't change opening to closing brackets,
# which is why we use opening brackets to calculate the final score
char_to_points = {
"(": 1,
"[": 2,
"{": 3,
"<": 4,
}
# calculate result
scores = []
for line in missing_input:
score = 0
for char in line:
score *= 5
score += char_to_points[char]
scores.append(score)
# sort scores and return middle
return sorted(scores)[len(scores) // 2]
def execute(self):
print(f"Solution for part 1: {self.part1()}")
print(f"Solution for part 2: {self.part2()}")
if __name__ == "__main__":
Day10().execute()
| class Day10:
illegal_char_to_points = {')': 3, ']': 57, '}': 1197, '>': 25137}
def __init__(self, input='src/input/day10.txt'):
self.INPUT = input
def read_input(self):
input = []
with open(self.INPUT, 'r') as fp:
lines = fp.readlines()
input = [line.strip() for line in lines]
return input
def part1(self):
input = self.read_input()
legal_chunks = ['()', '{}', '<>', '[]']
cleaned_input = []
for line in input:
prev_length = float('inf')
while prev_length > len(line):
prev_length = len(line)
for chunk in legal_chunks:
line = line.replace(chunk, '')
cleaned_input.append(line)
illegal_characters = []
for line in cleaned_input:
for char in line:
if char not in ['(', '{', '<', '[']:
illegal_characters.append(char)
break
return sum([self.ILLEGAL_CHAR_TO_POINTS[char] for char in illegal_characters])
def part2(self):
input = self.read_input()
legal_chunks = ['()', '{}', '<>', '[]']
cleaned_input = []
for line in input:
prev_length = float('inf')
while prev_length > len(line):
prev_length = len(line)
for chunk in legal_chunks:
line = line.replace(chunk, '')
cleaned_input.append(line)
incomplete_input = []
for line in cleaned_input:
closings = [')', '}', '>', ']']
check = False
for closing in closings:
if closing in line:
check = True
if not check:
incomplete_input.append(line)
missing_input = [line[::-1] for line in incomplete_input]
char_to_points = {'(': 1, '[': 2, '{': 3, '<': 4}
scores = []
for line in missing_input:
score = 0
for char in line:
score *= 5
score += char_to_points[char]
scores.append(score)
return sorted(scores)[len(scores) // 2]
def execute(self):
print(f'Solution for part 1: {self.part1()}')
print(f'Solution for part 2: {self.part2()}')
if __name__ == '__main__':
day10().execute() |
def ways(n, m):
grid = [[None]*m]*n
for i in range(m):
grid[n-1][i] = 1
for i in range(n):
grid[i][m-1] = 1
for i in range(n-2,-1,-1):
for j in range(m-2,-1,-1):
grid[i][j] = grid[i][j+1] + grid[i+1][j]
return grid[0][0]
if __name__ == "__main__":
t = int(input("Number of times you want to run this Program: "))
for i in range(t):
n, m = map(int, input(f"\n{i+1}. Grid Size (n*m): ").split())
result = ways(n, m)
print(f"There are {result} ways.\n")
| def ways(n, m):
grid = [[None] * m] * n
for i in range(m):
grid[n - 1][i] = 1
for i in range(n):
grid[i][m - 1] = 1
for i in range(n - 2, -1, -1):
for j in range(m - 2, -1, -1):
grid[i][j] = grid[i][j + 1] + grid[i + 1][j]
return grid[0][0]
if __name__ == '__main__':
t = int(input('Number of times you want to run this Program: '))
for i in range(t):
(n, m) = map(int, input(f'\n{i + 1}. Grid Size (n*m): ').split())
result = ways(n, m)
print(f'There are {result} ways.\n') |
message = input().split()
def asci_change(message):
numbers = [num for num in i if num.isdigit()]
numbers_in_chr = chr(int(''.join(numbers)))
letters = [letter for letter in i if not letter.isdigit()]
letters_split = ''.join(letters)
final_word = numbers_in_chr + str(letters_split)
return final_word
def index_change(message):
letters = [letter for letter in j]
letters[1], letters[-1] = letters[-1], letters[1]
letters_split = ''.join(letters)
return letters_split
index_i = 0
for i in message:
message[index_i] = asci_change(message)
index_i += 1
index_j = 0
for j in message:
message[index_j] = index_change(message)
index_j += 1
print(' '.join(message)) | message = input().split()
def asci_change(message):
numbers = [num for num in i if num.isdigit()]
numbers_in_chr = chr(int(''.join(numbers)))
letters = [letter for letter in i if not letter.isdigit()]
letters_split = ''.join(letters)
final_word = numbers_in_chr + str(letters_split)
return final_word
def index_change(message):
letters = [letter for letter in j]
(letters[1], letters[-1]) = (letters[-1], letters[1])
letters_split = ''.join(letters)
return letters_split
index_i = 0
for i in message:
message[index_i] = asci_change(message)
index_i += 1
index_j = 0
for j in message:
message[index_j] = index_change(message)
index_j += 1
print(' '.join(message)) |
star_wars = [125, 1977]
raiders = [115, 1981]
mean_girls = [97, 2004]
def distance(movie1, movie2):
length_difference = (movie1[0] - movie2[0]) ** 2
year_difference = (movie1[1] - movie2[1]) ** 2
distance = (length_difference + year_difference) ** 0.5
return distance
print(distance(star_wars, raiders))
print(distance(star_wars, mean_girls)) | star_wars = [125, 1977]
raiders = [115, 1981]
mean_girls = [97, 2004]
def distance(movie1, movie2):
length_difference = (movie1[0] - movie2[0]) ** 2
year_difference = (movie1[1] - movie2[1]) ** 2
distance = (length_difference + year_difference) ** 0.5
return distance
print(distance(star_wars, raiders))
print(distance(star_wars, mean_girls)) |
def get_distribution_steps(distribution):
i = 0
distributed_loaves = 0
while i < len(distribution):
if distribution[i] % 2 == 0:
i += 1
continue
next_item_index = i + 1
if next_item_index == len(distribution):
return -1
distribution[next_item_index] += 1
distributed_loaves += 2
i += 1
return distributed_loaves
N = int(input().strip())
current_distribution = [
int(B_temp)
for B_temp
in input().strip().split(' ')
]
steps = get_distribution_steps(current_distribution)
print(steps if steps != -1 else 'NO')
| def get_distribution_steps(distribution):
i = 0
distributed_loaves = 0
while i < len(distribution):
if distribution[i] % 2 == 0:
i += 1
continue
next_item_index = i + 1
if next_item_index == len(distribution):
return -1
distribution[next_item_index] += 1
distributed_loaves += 2
i += 1
return distributed_loaves
n = int(input().strip())
current_distribution = [int(B_temp) for b_temp in input().strip().split(' ')]
steps = get_distribution_steps(current_distribution)
print(steps if steps != -1 else 'NO') |
class File:
def __init__(
self,
name: str,
display_str: str,
short_status: str,
has_staged_change: bool,
has_unstaged_change: bool,
tracked: bool,
deleted: bool,
added: bool,
has_merged_conflicts: bool,
has_inline_merged_conflicts: bool,
) -> None:
self.name = name
self.display_str = display_str
self.short_status = short_status
self.has_staged_change = has_staged_change
self.has_unstaged_change = has_unstaged_change
self.tracked = tracked
self.deleted = deleted
self.added = added
self.has_merged_conflicts = has_merged_conflicts
self.has_inline_merged_conflicts = has_inline_merged_conflicts
| class File:
def __init__(self, name: str, display_str: str, short_status: str, has_staged_change: bool, has_unstaged_change: bool, tracked: bool, deleted: bool, added: bool, has_merged_conflicts: bool, has_inline_merged_conflicts: bool) -> None:
self.name = name
self.display_str = display_str
self.short_status = short_status
self.has_staged_change = has_staged_change
self.has_unstaged_change = has_unstaged_change
self.tracked = tracked
self.deleted = deleted
self.added = added
self.has_merged_conflicts = has_merged_conflicts
self.has_inline_merged_conflicts = has_inline_merged_conflicts |
with open('input') as f:
instructions = []
for line in f:
op, arg = line.split()
instructions.append((op, int(arg)))
# Part 1
executed = [False] * len(instructions)
accumulator = 0
i = 0
while i < len(instructions):
if executed[i]: break
executed[i] = True
op, n = instructions[i]
if op == 'acc':
accumulator += n
i += 1
elif op == 'jmp':
i += n
elif op == 'nop':
i += 1
else:
print('invalid operator')
exit(1)
print(accumulator)
# Part 2
mod = ['jmp', 'nop']
def fix(j):
executed = [False] * len(instructions)
accumulator = 0
i = 0
while i < len(instructions):
if executed[i]:
return False
executed[i] = True
op, n = instructions[i]
if i == j:
op = mod[mod.index(op) ^ 1] # Swap
if op == 'acc':
accumulator += n
i += 1
elif op == 'jmp':
i += n
elif op == 'nop':
i += 1
else:
print('invalid operator')
exit(1)
return accumulator
for i, (op, _) in enumerate(instructions):
if op in mod:
res = fix(i)
if res != False:
print(res)
break
| with open('input') as f:
instructions = []
for line in f:
(op, arg) = line.split()
instructions.append((op, int(arg)))
executed = [False] * len(instructions)
accumulator = 0
i = 0
while i < len(instructions):
if executed[i]:
break
executed[i] = True
(op, n) = instructions[i]
if op == 'acc':
accumulator += n
i += 1
elif op == 'jmp':
i += n
elif op == 'nop':
i += 1
else:
print('invalid operator')
exit(1)
print(accumulator)
mod = ['jmp', 'nop']
def fix(j):
executed = [False] * len(instructions)
accumulator = 0
i = 0
while i < len(instructions):
if executed[i]:
return False
executed[i] = True
(op, n) = instructions[i]
if i == j:
op = mod[mod.index(op) ^ 1]
if op == 'acc':
accumulator += n
i += 1
elif op == 'jmp':
i += n
elif op == 'nop':
i += 1
else:
print('invalid operator')
exit(1)
return accumulator
for (i, (op, _)) in enumerate(instructions):
if op in mod:
res = fix(i)
if res != False:
print(res)
break |
# encoding: utf-8
SECRET_KEY = 'a unique and long key'
TITLE = 'Riki'
HISTORY_SHOW_MAX = 30
PIC_BASE = '/static/content/'
CONTENT_DIR = '///D:\\School\\Riki\\content'
USER_DIR = '///D:\\School\\Riki\\user'
NUMBER_OF_HISTORY = 5
PRIVATE = False
| secret_key = 'a unique and long key'
title = 'Riki'
history_show_max = 30
pic_base = '/static/content/'
content_dir = '///D:\\School\\Riki\\content'
user_dir = '///D:\\School\\Riki\\user'
number_of_history = 5
private = False |
#!/usr/bin/env python
OUTPUT_FILENAME = "output"
TOTAL_OF_FILES = 2
if __name__ == "__main__":
# make an array of files of size 100
results = []
for i in range(1, TOTAL_OF_FILES+1):
a = open("./{}{}.txt".format(OUTPUT_FILENAME, i), 'r')
text = a.read()
a.close()
text = text.split('\n')
results.append(text[1:-2])
text = "Original_variable | real_parameters | number_of_observations | log-likelihood_of_real_params | Estim_params_T2_SSPSC | log-likelihood_T2_SSPSC | p-value_T2_SSPSC | Estim_params_T2_StSI | log-likelihood_T2_StSI | p-value_T2_StSI | AIC_selected_model | AIC_relative_prob\n"
for line in range(len(results[0])):
for i in range(TOTAL_OF_FILES):
text+=(i+1).__str__() + ' | ' + results[i][line]+'\n'
a = open('100exp_OUTPUT', 'w')
a.write(text)
a.close()
| output_filename = 'output'
total_of_files = 2
if __name__ == '__main__':
results = []
for i in range(1, TOTAL_OF_FILES + 1):
a = open('./{}{}.txt'.format(OUTPUT_FILENAME, i), 'r')
text = a.read()
a.close()
text = text.split('\n')
results.append(text[1:-2])
text = 'Original_variable | real_parameters | number_of_observations | log-likelihood_of_real_params | Estim_params_T2_SSPSC | log-likelihood_T2_SSPSC | p-value_T2_SSPSC | Estim_params_T2_StSI | log-likelihood_T2_StSI | p-value_T2_StSI | AIC_selected_model | AIC_relative_prob\n'
for line in range(len(results[0])):
for i in range(TOTAL_OF_FILES):
text += (i + 1).__str__() + ' | ' + results[i][line] + '\n'
a = open('100exp_OUTPUT', 'w')
a.write(text)
a.close() |
def func(word):
word = word.split(", ")
dic = {"Magic":[],"Normal":[]}
for elm in word:
decide = ""
first = elm[0]
first = int(first)
sum1 = 0
for sval in elm[1::]:
sum1 += int(sval)
if first == sum1:
decide = "Magic"
else:
decide = "Normal"
dic[decide].append(int(elm))
fdic = {}
for key,val in dic.items():
fdic[key] = tuple(val)
return fdic
word = input("Enter your numbers: ")
print(func(word))
| def func(word):
word = word.split(', ')
dic = {'Magic': [], 'Normal': []}
for elm in word:
decide = ''
first = elm[0]
first = int(first)
sum1 = 0
for sval in elm[1:]:
sum1 += int(sval)
if first == sum1:
decide = 'Magic'
else:
decide = 'Normal'
dic[decide].append(int(elm))
fdic = {}
for (key, val) in dic.items():
fdic[key] = tuple(val)
return fdic
word = input('Enter your numbers: ')
print(func(word)) |
class Node:
def __init__(self, data):
self.data = data # Assign the data here
self.next = None # Set next to None by default.
class LinkedList:
def __init__(self):
self.head = None
# Display the list. Linked list traversal.
def display(self):
temp = self.head
display = ""
while temp:
display+=(str(temp.data)+" -> ")
temp = temp.next
display+="None"
print(display)
def push(self, data):
# Create the new node before we insert it at the beginning of the LL
new_node = Node(data)
# Assign the next pointer to the head
new_node.next = self.head
# Move the head pointer to the new node.
self.head = new_node
def append(self, data):
# Inserting data at the end of the linked list.
new_node = Node(data)
if self.head == None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def insert(self, previous_node, data):
if previous_node == None:
return
# Create a new node with new data
new_node = Node(data)
new_node.next = previous_node.next
previous_node.next = new_node
# Tests
# Initialize linked list
llist = LinkedList()
# Create some nodes.
llist.push(2)
llist.push(3)
llist.push(4)
llist.append(1)
llist.display()
| class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def display(self):
temp = self.head
display = ''
while temp:
display += str(temp.data) + ' -> '
temp = temp.next
display += 'None'
print(display)
def push(self, data):
new_node = node(data)
new_node.next = self.head
self.head = new_node
def append(self, data):
new_node = node(data)
if self.head == None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def insert(self, previous_node, data):
if previous_node == None:
return
new_node = node(data)
new_node.next = previous_node.next
previous_node.next = new_node
llist = linked_list()
llist.push(2)
llist.push(3)
llist.push(4)
llist.append(1)
llist.display() |
# You can gen a bcrypt hash here:
## http://bcrypthashgenerator.apphb.com/
pwhash = 'bcrypt'
# You can generate salts and other secrets with openssl
# For example:
# $ openssl rand -hex 16
# 1ca632d8567743f94352545abe2e313d
salt = "141202e6b20aa53596a339a0d0b92e79"
secret_key = 'fe65757e00193b8bc2e18444fa51d873'
mongo_db = 'mydatabase'
mongo_host = 'localhost'
mongo_port = 27017
user_enable_registration = True
user_enable_tracking = True
user_from_email = "[email protected]"
user_register_email_subject = "Thank you for signing up"
mail_url = "mail.yoursite.com"
mail_port = "25"
mail_SSL = False
mail_TLS = False
mail_user = "username_goes_here"
mail_pass = "password_goes_here"
| pwhash = 'bcrypt'
salt = '141202e6b20aa53596a339a0d0b92e79'
secret_key = 'fe65757e00193b8bc2e18444fa51d873'
mongo_db = 'mydatabase'
mongo_host = 'localhost'
mongo_port = 27017
user_enable_registration = True
user_enable_tracking = True
user_from_email = '[email protected]'
user_register_email_subject = 'Thank you for signing up'
mail_url = 'mail.yoursite.com'
mail_port = '25'
mail_ssl = False
mail_tls = False
mail_user = 'username_goes_here'
mail_pass = 'password_goes_here' |
sbox = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x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a, 0x58, 0x56,
0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d,
0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d] | sbox = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22]
sbox_inv = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125]
r_con = [141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141]
vector_table = [2, 3, 1, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 1, 1, 2]
table_2 = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 27, 25, 31, 29, 19, 17, 23, 21, 11, 9, 15, 13, 3, 1, 7, 5, 59, 57, 63, 61, 51, 49, 55, 53, 43, 41, 47, 45, 35, 33, 39, 37, 91, 89, 95, 93, 83, 81, 87, 85, 75, 73, 79, 77, 67, 65, 71, 69, 123, 121, 127, 125, 115, 113, 119, 117, 107, 105, 111, 109, 99, 97, 103, 101, 155, 153, 159, 157, 147, 145, 151, 149, 139, 137, 143, 141, 131, 129, 135, 133, 187, 185, 191, 189, 179, 177, 183, 181, 171, 169, 175, 173, 163, 161, 167, 165, 219, 217, 223, 221, 211, 209, 215, 213, 203, 201, 207, 205, 195, 193, 199, 197, 251, 249, 255, 253, 243, 241, 247, 245, 235, 233, 239, 237, 227, 225, 231, 229]
table_3 = [0, 3, 6, 5, 12, 15, 10, 9, 24, 27, 30, 29, 20, 23, 18, 17, 48, 51, 54, 53, 60, 63, 58, 57, 40, 43, 46, 45, 36, 39, 34, 33, 96, 99, 102, 101, 108, 111, 106, 105, 120, 123, 126, 125, 116, 119, 114, 113, 80, 83, 86, 85, 92, 95, 90, 89, 72, 75, 78, 77, 68, 71, 66, 65, 192, 195, 198, 197, 204, 207, 202, 201, 216, 219, 222, 221, 212, 215, 210, 209, 240, 243, 246, 245, 252, 255, 250, 249, 232, 235, 238, 237, 228, 231, 226, 225, 160, 163, 166, 165, 172, 175, 170, 169, 184, 187, 190, 189, 180, 183, 178, 177, 144, 147, 150, 149, 156, 159, 154, 153, 136, 139, 142, 141, 132, 135, 130, 129, 155, 152, 157, 158, 151, 148, 145, 146, 131, 128, 133, 134, 143, 140, 137, 138, 171, 168, 173, 174, 167, 164, 161, 162, 179, 176, 181, 182, 191, 188, 185, 186, 251, 248, 253, 254, 247, 244, 241, 242, 227, 224, 229, 230, 239, 236, 233, 234, 203, 200, 205, 206, 199, 196, 193, 194, 211, 208, 213, 214, 223, 220, 217, 218, 91, 88, 93, 94, 87, 84, 81, 82, 67, 64, 69, 70, 79, 76, 73, 74, 107, 104, 109, 110, 103, 100, 97, 98, 115, 112, 117, 118, 127, 124, 121, 122, 59, 56, 61, 62, 55, 52, 49, 50, 35, 32, 37, 38, 47, 44, 41, 42, 11, 8, 13, 14, 7, 4, 1, 2, 19, 16, 21, 22, 31, 28, 25, 26]
table_9 = [0, 9, 18, 27, 36, 45, 54, 63, 72, 65, 90, 83, 108, 101, 126, 119, 144, 153, 130, 139, 180, 189, 166, 175, 216, 209, 202, 195, 252, 245, 238, 231, 59, 50, 41, 32, 31, 22, 13, 4, 115, 122, 97, 104, 87, 94, 69, 76, 171, 162, 185, 176, 143, 134, 157, 148, 227, 234, 241, 248, 199, 206, 213, 220, 118, 127, 100, 109, 82, 91, 64, 73, 62, 55, 44, 37, 26, 19, 8, 1, 230, 239, 244, 253, 194, 203, 208, 217, 174, 167, 188, 181, 138, 131, 152, 145, 77, 68, 95, 86, 105, 96, 123, 114, 5, 12, 23, 30, 33, 40, 51, 58, 221, 212, 207, 198, 249, 240, 235, 226, 149, 156, 135, 142, 177, 184, 163, 170, 236, 229, 254, 247, 200, 193, 218, 211, 164, 173, 182, 191, 128, 137, 146, 155, 124, 117, 110, 103, 88, 81, 74, 67, 52, 61, 38, 47, 16, 25, 2, 11, 215, 222, 197, 204, 243, 250, 225, 232, 159, 150, 141, 132, 187, 178, 169, 160, 71, 78, 85, 92, 99, 106, 113, 120, 15, 6, 29, 20, 43, 34, 57, 48, 154, 147, 136, 129, 190, 183, 172, 165, 210, 219, 192, 201, 246, 255, 228, 237, 10, 3, 24, 17, 46, 39, 60, 53, 66, 75, 80, 89, 102, 111, 116, 125, 161, 168, 179, 186, 133, 140, 151, 158, 233, 224, 251, 242, 205, 196, 223, 214, 49, 56, 35, 42, 21, 28, 7, 14, 121, 112, 107, 98, 93, 84, 79, 70]
table_11 = [0, 11, 22, 29, 44, 39, 58, 49, 88, 83, 78, 69, 116, 127, 98, 105, 176, 187, 166, 173, 156, 151, 138, 129, 232, 227, 254, 245, 196, 207, 210, 217, 123, 112, 109, 102, 87, 92, 65, 74, 35, 40, 53, 62, 15, 4, 25, 18, 203, 192, 221, 214, 231, 236, 241, 250, 147, 152, 133, 142, 191, 180, 169, 162, 246, 253, 224, 235, 218, 209, 204, 199, 174, 165, 184, 179, 130, 137, 148, 159, 70, 77, 80, 91, 106, 97, 124, 119, 30, 21, 8, 3, 50, 57, 36, 47, 141, 134, 155, 144, 161, 170, 183, 188, 213, 222, 195, 200, 249, 242, 239, 228, 61, 54, 43, 32, 17, 26, 7, 12, 101, 110, 115, 120, 73, 66, 95, 84, 247, 252, 225, 234, 219, 208, 205, 198, 175, 164, 185, 178, 131, 136, 149, 158, 71, 76, 81, 90, 107, 96, 125, 118, 31, 20, 9, 2, 51, 56, 37, 46, 140, 135, 154, 145, 160, 171, 182, 189, 212, 223, 194, 201, 248, 243, 238, 229, 60, 55, 42, 33, 16, 27, 6, 13, 100, 111, 114, 121, 72, 67, 94, 85, 1, 10, 23, 28, 45, 38, 59, 48, 89, 82, 79, 68, 117, 126, 99, 104, 177, 186, 167, 172, 157, 150, 139, 128, 233, 226, 255, 244, 197, 206, 211, 216, 122, 113, 108, 103, 86, 93, 64, 75, 34, 41, 52, 63, 14, 5, 24, 19, 202, 193, 220, 215, 230, 237, 240, 251, 146, 153, 132, 143, 190, 181, 168, 163]
table_13 = [0, 13, 26, 23, 52, 57, 46, 35, 104, 101, 114, 127, 92, 81, 70, 75, 208, 221, 202, 199, 228, 233, 254, 243, 184, 181, 162, 175, 140, 129, 150, 155, 187, 182, 161, 172, 143, 130, 149, 152, 211, 222, 201, 196, 231, 234, 253, 240, 107, 102, 113, 124, 95, 82, 69, 72, 3, 14, 25, 20, 55, 58, 45, 32, 109, 96, 119, 122, 89, 84, 67, 78, 5, 8, 31, 18, 49, 60, 43, 38, 189, 176, 167, 170, 137, 132, 147, 158, 213, 216, 207, 194, 225, 236, 251, 246, 214, 219, 204, 193, 226, 239, 248, 245, 190, 179, 164, 169, 138, 135, 144, 157, 6, 11, 28, 17, 50, 63, 40, 37, 110, 99, 116, 121, 90, 87, 64, 77, 218, 215, 192, 205, 238, 227, 244, 249, 178, 191, 168, 165, 134, 139, 156, 145, 10, 7, 16, 29, 62, 51, 36, 41, 98, 111, 120, 117, 86, 91, 76, 65, 97, 108, 123, 118, 85, 88, 79, 66, 9, 4, 19, 30, 61, 48, 39, 42, 177, 188, 171, 166, 133, 136, 159, 146, 217, 212, 195, 206, 237, 224, 247, 250, 183, 186, 173, 160, 131, 142, 153, 148, 223, 210, 197, 200, 235, 230, 241, 252, 103, 106, 125, 112, 83, 94, 73, 68, 15, 2, 21, 24, 59, 54, 33, 44, 12, 1, 22, 27, 56, 53, 34, 47, 100, 105, 126, 115, 80, 93, 74, 71, 220, 209, 198, 203, 232, 229, 242, 255, 180, 185, 174, 163, 128, 141, 154, 151]
table_14 = [0, 14, 28, 18, 56, 54, 36, 42, 112, 126, 108, 98, 72, 70, 84, 90, 224, 238, 252, 242, 216, 214, 196, 202, 144, 158, 140, 130, 168, 166, 180, 186, 219, 213, 199, 201, 227, 237, 255, 241, 171, 165, 183, 185, 147, 157, 143, 129, 59, 53, 39, 41, 3, 13, 31, 17, 75, 69, 87, 89, 115, 125, 111, 97, 173, 163, 177, 191, 149, 155, 137, 135, 221, 211, 193, 207, 229, 235, 249, 247, 77, 67, 81, 95, 117, 123, 105, 103, 61, 51, 33, 47, 5, 11, 25, 23, 118, 120, 106, 100, 78, 64, 82, 92, 6, 8, 26, 20, 62, 48, 34, 44, 150, 152, 138, 132, 174, 160, 178, 188, 230, 232, 250, 244, 222, 208, 194, 204, 65, 79, 93, 83, 121, 119, 101, 107, 49, 63, 45, 35, 9, 7, 21, 27, 161, 175, 189, 179, 153, 151, 133, 139, 209, 223, 205, 195, 233, 231, 245, 251, 154, 148, 134, 136, 162, 172, 190, 176, 234, 228, 246, 248, 210, 220, 206, 192, 122, 116, 102, 104, 66, 76, 94, 80, 10, 4, 22, 24, 50, 60, 46, 32, 236, 226, 240, 254, 212, 218, 200, 198, 156, 146, 128, 142, 164, 170, 184, 182, 12, 2, 16, 30, 52, 58, 40, 38, 124, 114, 96, 110, 68, 74, 88, 86, 55, 57, 43, 37, 15, 1, 19, 29, 71, 73, 91, 85, 127, 113, 99, 109, 215, 217, 203, 197, 239, 225, 243, 253, 167, 169, 187, 181, 159, 145, 131, 141] |
TAG_TYPE = "#type"
TAG_XML = "#xml"
TAG_VERSION = "@version"
TAG_UIVERSION = "@uiVersion"
TAG_NAMESPACE = "@xmlns"
TAG_NAME = "@name"
TAG_META = "meta"
TAG_FORM = 'form'
ATTACHMENT_NAME = "form.xml"
MAGIC_PROPERTY = 'xml_submission_file'
RESERVED_WORDS = [TAG_TYPE, TAG_XML, TAG_VERSION, TAG_UIVERSION, TAG_NAMESPACE,
TAG_NAME, TAG_META, ATTACHMENT_NAME, 'case', MAGIC_PROPERTY]
DEVICE_LOG_XMLNS = 'http://code.javarosa.org/devicereport'
| tag_type = '#type'
tag_xml = '#xml'
tag_version = '@version'
tag_uiversion = '@uiVersion'
tag_namespace = '@xmlns'
tag_name = '@name'
tag_meta = 'meta'
tag_form = 'form'
attachment_name = 'form.xml'
magic_property = 'xml_submission_file'
reserved_words = [TAG_TYPE, TAG_XML, TAG_VERSION, TAG_UIVERSION, TAG_NAMESPACE, TAG_NAME, TAG_META, ATTACHMENT_NAME, 'case', MAGIC_PROPERTY]
device_log_xmlns = 'http://code.javarosa.org/devicereport' |
def Merge_Sort(list):
n= len(list)
if n > 1 :
mid = int(n/2)
left =list[0:mid]
right = list[mid:n]
Merge_Sort(left)
Merge_Sort(right)
Merge (left, right, list)
return list
def Merge(left, right, list):
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
list[k] = left[i]
i = i + 1
else :
list[k] = right[j]
j = j + 1
k = k + 1
while i < len(left):
list[k] = left[i]
i += 1
k += 1
while j < len(right):
list[k] = right[j]
j += 1
k += 1
if __name__=="__main__":
list1=[8,4,23,42,16,15]
print(Merge_Sort(list1))
list_2=[20,18,12,8,5,-2] #Reverse-sorted
print(Merge_Sort(list_2)) #[-2, 5, 8, 12, 18, 20]
list_3=[5,12,7,5,5,7] #Few uniques
print(Merge_Sort(list_3)) #[5, 5, 5, 7, 7, 12]
list_4=[2,3,5,7,13,11] #Nearly-sorted
print(Merge_Sort(list_4)) #[2, 3, 5, 7, 11, 13]
| def merge__sort(list):
n = len(list)
if n > 1:
mid = int(n / 2)
left = list[0:mid]
right = list[mid:n]
merge__sort(left)
merge__sort(right)
merge(left, right, list)
return list
def merge(left, right, list):
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
list[k] = left[i]
i = i + 1
else:
list[k] = right[j]
j = j + 1
k = k + 1
while i < len(left):
list[k] = left[i]
i += 1
k += 1
while j < len(right):
list[k] = right[j]
j += 1
k += 1
if __name__ == '__main__':
list1 = [8, 4, 23, 42, 16, 15]
print(merge__sort(list1))
list_2 = [20, 18, 12, 8, 5, -2]
print(merge__sort(list_2))
list_3 = [5, 12, 7, 5, 5, 7]
print(merge__sort(list_3))
list_4 = [2, 3, 5, 7, 13, 11]
print(merge__sort(list_4)) |
def default_copts(ignored = []):
opts = [
"-std=c++20",
"-Wall",
"-Werror",
"-Wextra",
"-Wno-ignored-qualifiers",
"-Wvla",
]
ignored_map = {opt: opt for opt in ignored}
return [opt for opt in opts if ignored_map.get(opt) == None]
| def default_copts(ignored=[]):
opts = ['-std=c++20', '-Wall', '-Werror', '-Wextra', '-Wno-ignored-qualifiers', '-Wvla']
ignored_map = {opt: opt for opt in ignored}
return [opt for opt in opts if ignored_map.get(opt) == None] |
{
"targets": [
{
"target_name": "usb",
"conditions": [
[
"OS==\"win\"",
{
"sources": [
"third_party/usb/src/win.cc"
],
"libraries": [
"-lhid"
]
}
],
[
"OS==\"linux\"",
{
"sources": [
"third_party/usb/src/linux.cc"
],
"libraries": [
"-ludev"
]
}
],
[
"OS==\"mac\"",
{
"sources": [
"third_party/usb/src/mac.cc"
],
"LDFLAGS": [
"-framework IOKit",
"-framework CoreFoundation",
"-framework AppKit"
],
"xcode_settings": {
"OTHER_LDFLAGS": [
"-framework IOKit",
"-framework CoreFoundation",
"-framework AppKit"
],
}
}
]
]
},
{
"target_name": "sign",
"conditions": [
[
"OS==\"win\"",
{
"sources": [
"third_party/sign/src/win.cc"
],
"libraries": [
"-lcrypt32"
]
}
],
[
"OS==\"linux\"",
{
"sources": [
"third_party/sign/src/linux.cc"
]
}
],
[
"OS==\"mac\"",
{
"sources": [
"third_party/sign/src/mac.cc"
],
"LDFLAGS": [
"-framework CoreFoundation",
"-framework AppKit"
],
"xcode_settings": {
"OTHER_LDFLAGS": [
"-framework CoreFoundation",
"-framework AppKit"
],
}
}
]
]
},
{
"target_name": "pcsc",
"sources": [
"third_party/pcsc/src/pcsc.cc",
"third_party/pcsc/src/service.cc",
"third_party/pcsc/src/card.cc",
"third_party/pcsc/src/device.cc"
],
"include_dirs": [
"third_party/pcsc/src"
],
"conditions": [
[
"OS==\"win\"",
{
"libraries": [
"-lwinscard"
]
}
],
[
"OS==\"mac\"",
{
"LDFLAGS": [
"-framework PCSC"
],
"xcode_settings": {
"OTHER_LDFLAGS": [
"-framework PCSC"
]
}
}
],
[
"OS==\"linux\"",
{
"include_dirs": [
"/usr/include/PCSC"
],
"cflags": [
"-pthread",
"-Wno-cast-function-type"
],
"libraries": [
"-lpcsclite"
]
}
]
]
}
]
} | {'targets': [{'target_name': 'usb', 'conditions': [['OS=="win"', {'sources': ['third_party/usb/src/win.cc'], 'libraries': ['-lhid']}], ['OS=="linux"', {'sources': ['third_party/usb/src/linux.cc'], 'libraries': ['-ludev']}], ['OS=="mac"', {'sources': ['third_party/usb/src/mac.cc'], 'LDFLAGS': ['-framework IOKit', '-framework CoreFoundation', '-framework AppKit'], 'xcode_settings': {'OTHER_LDFLAGS': ['-framework IOKit', '-framework CoreFoundation', '-framework AppKit']}}]]}, {'target_name': 'sign', 'conditions': [['OS=="win"', {'sources': ['third_party/sign/src/win.cc'], 'libraries': ['-lcrypt32']}], ['OS=="linux"', {'sources': ['third_party/sign/src/linux.cc']}], ['OS=="mac"', {'sources': ['third_party/sign/src/mac.cc'], 'LDFLAGS': ['-framework CoreFoundation', '-framework AppKit'], 'xcode_settings': {'OTHER_LDFLAGS': ['-framework CoreFoundation', '-framework AppKit']}}]]}, {'target_name': 'pcsc', 'sources': ['third_party/pcsc/src/pcsc.cc', 'third_party/pcsc/src/service.cc', 'third_party/pcsc/src/card.cc', 'third_party/pcsc/src/device.cc'], 'include_dirs': ['third_party/pcsc/src'], 'conditions': [['OS=="win"', {'libraries': ['-lwinscard']}], ['OS=="mac"', {'LDFLAGS': ['-framework PCSC'], 'xcode_settings': {'OTHER_LDFLAGS': ['-framework PCSC']}}], ['OS=="linux"', {'include_dirs': ['/usr/include/PCSC'], 'cflags': ['-pthread', '-Wno-cast-function-type'], 'libraries': ['-lpcsclite']}]]}]} |
# Challenge 4 : Create a function named movie_review() that has one parameter named rating.
# If rating is less than or equal to 5, return "Avoid at all costs!".
# If rating is between 5 and 9, return "This one was fun.".
# If rating is 9 or above, return "Outstanding!"
# Date : Thu 28 May 2020 07:31:11 AM IST
def movie_review(rating):
if rating <= 5:
return "Avoid at all costs!"
elif (rating >= 5) and (rating <= 9):
return "This one was fun."
elif rating >= 9:
return "Outstanding!"
print(movie_review(9))
print(movie_review(4))
print(movie_review(6))
| def movie_review(rating):
if rating <= 5:
return 'Avoid at all costs!'
elif rating >= 5 and rating <= 9:
return 'This one was fun.'
elif rating >= 9:
return 'Outstanding!'
print(movie_review(9))
print(movie_review(4))
print(movie_review(6)) |
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
msg = "Hello World!!!"
print("{}{}".format(colors["cian"], msg))
| colors = {'clean': '\x1b[m', 'red': '\x1b[31m', 'green': '\x1b[32m', 'yellow': '\x1b[33m', 'blue': '\x1b[34m', 'purple': '\x1b[35m', 'cian': '\x1b[36m'}
msg = 'Hello World!!!'
print('{}{}'.format(colors['cian'], msg)) |
def difference(a, b):
c = []
for el in a:
if el not in b:
c.append(el)
return c
ll = [1, 2, 3, 4, 5]
ll2 = [4, 5, 6, 7, 8]
# print(difference(ll, ll2))
# = CTRL + /
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set_difference = set1.difference(set2)
# print(set_difference)
# print(difference(ll, ll2) == list(set_difference))
| def difference(a, b):
c = []
for el in a:
if el not in b:
c.append(el)
return c
ll = [1, 2, 3, 4, 5]
ll2 = [4, 5, 6, 7, 8]
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set_difference = set1.difference(set2) |
# --
# File: a1000_consts.py
#
# Copyright (c) ReversingLabs Inc 2016-2018
#
# This unpublished material is proprietary to ReversingLabs Inc.
# All rights reserved.
# Reproduction or distribution, in whole
# or in part, is forbidden except by express written permission
# of ReversingLabs Inc.
#
# --
A1000_JSON_BASE_URL = "base_url"
A1000_JSON_TASK_ID = "task_id"
A1000_JSON_API_KEY = "api_key"
A1000_JSON_MALWARE = "malware"
A1000_JSON_TASK_ID = "id"
A1000_JSON_VAULT_ID = "vault_id"
A1000_JSON_URL = "url"
A1000_JSON_HASH = "hash"
A1000_JSON_PLATFORM = "platform"
A1000_JSON_POLL_TIMEOUT_MINS = "timeout"
A1000_ERR_UNABLE_TO_PARSE_REPLY = "Unable to parse reply from device"
A1000_ERR_REPLY_FORMAT_KEY_MISSING = "None '{key}' missing in reply from device"
A1000_ERR_REPLY_NOT_SUCCESS = "REST call returned '{status}'"
A1000_SUCC_REST_CALL_SUCCEEDED = "REST Api call succeeded"
A1000_ERR_REST_API = "REST Api Call returned error, status_code: {status_code}, detail: {detail}"
A1000_TEST_PDF_FILE = "a1000_test_connectivity.pdf"
A1000_SLEEP_SECS = 3
A1000_MSG_REPORT_PENDING = "Report Not Found"
A1000_MSG_MAX_POLLS_REACHED = "Reached max polling attempts. Please use the MD5 or Sha256 of the file as a parameter to <b>get report</b> to query the report status."
A1000_PARAM_LIST = {
"fields": [
"file_type",
"file_subtype",
"file_size",
"extracted_file_count",
"local_first_seen",
"local_last_seen",
"classification_origin",
"classification_reason",
"threat_status",
"trust_factor",
"threat_level",
"threat_name",
"summary"]
}
# in minutes
A1000_MAX_TIMEOUT_DEF = 10
| a1000_json_base_url = 'base_url'
a1000_json_task_id = 'task_id'
a1000_json_api_key = 'api_key'
a1000_json_malware = 'malware'
a1000_json_task_id = 'id'
a1000_json_vault_id = 'vault_id'
a1000_json_url = 'url'
a1000_json_hash = 'hash'
a1000_json_platform = 'platform'
a1000_json_poll_timeout_mins = 'timeout'
a1000_err_unable_to_parse_reply = 'Unable to parse reply from device'
a1000_err_reply_format_key_missing = "None '{key}' missing in reply from device"
a1000_err_reply_not_success = "REST call returned '{status}'"
a1000_succ_rest_call_succeeded = 'REST Api call succeeded'
a1000_err_rest_api = 'REST Api Call returned error, status_code: {status_code}, detail: {detail}'
a1000_test_pdf_file = 'a1000_test_connectivity.pdf'
a1000_sleep_secs = 3
a1000_msg_report_pending = 'Report Not Found'
a1000_msg_max_polls_reached = 'Reached max polling attempts. Please use the MD5 or Sha256 of the file as a parameter to <b>get report</b> to query the report status.'
a1000_param_list = {'fields': ['file_type', 'file_subtype', 'file_size', 'extracted_file_count', 'local_first_seen', 'local_last_seen', 'classification_origin', 'classification_reason', 'threat_status', 'trust_factor', 'threat_level', 'threat_name', 'summary']}
a1000_max_timeout_def = 10 |
# Provided by Dr. Marzieh Ahmadzadeh & Nick Cheng. Edited by Yufei Cui
class DNode(object):
'''represents a node as a building block of a double linked list'''
def __init__(self, element, prev_node=None, next_node=None):
'''(Node, obj, Node, Node) -> NoneType
construct a Dnode as building block of a double linked list'''
# Representation invariant:
# element is an object, that is hold this node
# _prev is a DNode
# _next is a DNode
# _prev is the node immediately before this node (i.e. self)
# _next is the node immediately after this node (i.e. self)
self._element = element
self._next = next_node
self._prev = prev_node
def set_next(self, next_node):
'''(Node, Node) -> NoneType
set node to point to next_node'''
self._next = next_node
def set_prev(self, prev_node):
'''(Node, Node) -> NoneType
set node to point to prev_node'''
self._prev = prev_node
def set_element(self, element):
'''(Node, obj) ->NoneType
set the _element to a new value'''
self._element = element
def get_next(self):
'''(Node) -> Node
returns the reference to next node'''
return self._next
def get_prev(self):
'''(Node) -> Node
returns the reference to previous node'''
return self._prev
def get_element(self):
'''(Node) -> obj
returns the element of this node'''
return self._element
def __str__(self):
'''(Node) -> str
returns the element of this node and the reference to next node'''
return "(" + str(hex(id(self._prev))) + ", " + str(self._element) + ", " + str(hex(id(self._next))) + ")"
class DoubleLinkedList(object):
''' represents a double linked list'''
def __init__(self):
'''(DoubleLinkedList) ->NoneType
initializes the references of an empty DLL'''
# set the size
self._size = 0
# head and tails are a dummy node
self._head = DNode(None, None, None)
self._tail = DNode(None, None, None)
# head points to tail and tail to head
self._head.set_next(self._tail)
self._tail.set_prev(self._head)
def is_empty(self):
'''(DoubleLinkedList) -> bool
returns true if no item is in this DLL'''
return self._size == 0
def size(self):
'''(DoubleLinkedList) -> int
returns the number of items in this DLL'''
return self._size
def add_first(self, element):
'''(DoubleLinkedList, obj) -> NoneType
adds a node to the front of the DLL, after the head'''
# create a node that head points to. Also the node points to the node after the head
node = DNode(element, self._head, self._head.get_next())
# have the node after head to point to this node (_prev)
self._head.get_next().set_prev(node)
# have the head to point to this new node
self._head.set_next(node)
# increment the size
self._size += 1
def add_last(self, element):
'''(DoubleLinkedList, obj) -> NoneType
adds a node to the end of this DLL'''
# create a DNode with the given element that points to tail from right and to the node before the tail from left
node = DNode(element, self._tail.get_prev(), self._tail)
# let the node to the left of the tail to point to this new node
self._tail.get_prev().set_next(node)
# let the _prev part of the tail to point to newly created node
self._tail.set_prev(node)
# increment the size
self._size += 1
def remove_first(self):
'''(DoubleLinkedList, obj) -> obj
remove the node from the head of this DLL and returns the element stored in this node'''
# set element to None in case DLL was empty
element = None
# if DLL is not empty
if not self.is_empty():
# get the first node to the right of the head
node = self._head.get_next()
# have head point to the second node after the head
self._head.set_next(node.get_next())
# have the second node after the head to point to head from left
node.get_next().set_prev(self._head)
# decrement the size
self._size -= 1
# set the _next & _prev of the removed node to point to None (for garbage collection purpose)
node.set_next(None)
node.set_prev(None)
# get the element stored in the node
element = node.get_element()
# return the element of the removed node
return element
def remove_last(self):
'''(DoubleLinkedList, obj) -> obj
remove the node from the tail of this DLL and returns the element stored in this node'''
# set element to None in case DLL was empty
element = None
# if DLL is not empty
if not self.is_empty():
# get the first node to the left of the tail
node = self._tail.get_prev()
# have tail point to the second node before the tail
self._tail.set_prev(node.get_prev())
# have the second node before the tail to point to tail from right
node.get_prev().set_next(self._tail)
# decrement the size
self._size -= 1
# set the _next, _prev of removed node to point to None (for garbage collection purpose)
node.set_next(None)
node.set_prev(None)
# get the element stored in the node
element = node.get_element()
# return the element of the removed node
return element
def __str__(self):
'''(DoubleLinkedList) -> str
returns the items in the DLL in a string form
'''
# define a node, which points to the first node after the head
cur = self._head.get_next()
# define an empty string to be used as a container for the items in the SLL
result = ""
# loop over the DLL until you get to the end of the DLL
while cur is not self._tail:
# get the element of the current node and attach it to the final result
result = result + str(cur.get_element()) + ", "
# proceed to next node
cur = cur.get_next()
# enclose the result in a parentheses
result = "(" + result[:-2] + ")"
# return the result
return result
if __name__ == "__main__":
node_1 = DNode("A")
node_2 = DNode("B", node_1)
node_3 = DNode("C", node_1, node_2)
print(node_1)
print(node_2)
print(node_3)
print(str(hex(id(node_1))))
print(str(hex(id(node_2))))
dll = DoubleLinkedList()
print(dll)
dll.add_first("A")
dll.add_first("B")
dll.add_last("C")
dll.add_last("D")
print(dll)
print(dll.remove_last())
print(dll.remove_last())
print(dll.remove_last())
print(dll.remove_last())
print(dll)
| class Dnode(object):
"""represents a node as a building block of a double linked list"""
def __init__(self, element, prev_node=None, next_node=None):
"""(Node, obj, Node, Node) -> NoneType
construct a Dnode as building block of a double linked list"""
self._element = element
self._next = next_node
self._prev = prev_node
def set_next(self, next_node):
"""(Node, Node) -> NoneType
set node to point to next_node"""
self._next = next_node
def set_prev(self, prev_node):
"""(Node, Node) -> NoneType
set node to point to prev_node"""
self._prev = prev_node
def set_element(self, element):
"""(Node, obj) ->NoneType
set the _element to a new value"""
self._element = element
def get_next(self):
"""(Node) -> Node
returns the reference to next node"""
return self._next
def get_prev(self):
"""(Node) -> Node
returns the reference to previous node"""
return self._prev
def get_element(self):
"""(Node) -> obj
returns the element of this node"""
return self._element
def __str__(self):
"""(Node) -> str
returns the element of this node and the reference to next node"""
return '(' + str(hex(id(self._prev))) + ', ' + str(self._element) + ', ' + str(hex(id(self._next))) + ')'
class Doublelinkedlist(object):
""" represents a double linked list"""
def __init__(self):
"""(DoubleLinkedList) ->NoneType
initializes the references of an empty DLL"""
self._size = 0
self._head = d_node(None, None, None)
self._tail = d_node(None, None, None)
self._head.set_next(self._tail)
self._tail.set_prev(self._head)
def is_empty(self):
"""(DoubleLinkedList) -> bool
returns true if no item is in this DLL"""
return self._size == 0
def size(self):
"""(DoubleLinkedList) -> int
returns the number of items in this DLL"""
return self._size
def add_first(self, element):
"""(DoubleLinkedList, obj) -> NoneType
adds a node to the front of the DLL, after the head"""
node = d_node(element, self._head, self._head.get_next())
self._head.get_next().set_prev(node)
self._head.set_next(node)
self._size += 1
def add_last(self, element):
"""(DoubleLinkedList, obj) -> NoneType
adds a node to the end of this DLL"""
node = d_node(element, self._tail.get_prev(), self._tail)
self._tail.get_prev().set_next(node)
self._tail.set_prev(node)
self._size += 1
def remove_first(self):
"""(DoubleLinkedList, obj) -> obj
remove the node from the head of this DLL and returns the element stored in this node"""
element = None
if not self.is_empty():
node = self._head.get_next()
self._head.set_next(node.get_next())
node.get_next().set_prev(self._head)
self._size -= 1
node.set_next(None)
node.set_prev(None)
element = node.get_element()
return element
def remove_last(self):
"""(DoubleLinkedList, obj) -> obj
remove the node from the tail of this DLL and returns the element stored in this node"""
element = None
if not self.is_empty():
node = self._tail.get_prev()
self._tail.set_prev(node.get_prev())
node.get_prev().set_next(self._tail)
self._size -= 1
node.set_next(None)
node.set_prev(None)
element = node.get_element()
return element
def __str__(self):
"""(DoubleLinkedList) -> str
returns the items in the DLL in a string form
"""
cur = self._head.get_next()
result = ''
while cur is not self._tail:
result = result + str(cur.get_element()) + ', '
cur = cur.get_next()
result = '(' + result[:-2] + ')'
return result
if __name__ == '__main__':
node_1 = d_node('A')
node_2 = d_node('B', node_1)
node_3 = d_node('C', node_1, node_2)
print(node_1)
print(node_2)
print(node_3)
print(str(hex(id(node_1))))
print(str(hex(id(node_2))))
dll = double_linked_list()
print(dll)
dll.add_first('A')
dll.add_first('B')
dll.add_last('C')
dll.add_last('D')
print(dll)
print(dll.remove_last())
print(dll.remove_last())
print(dll.remove_last())
print(dll.remove_last())
print(dll) |
class ProductLabels(object):
def __init__(self, labels, labels_tags, labels_fr):
self.Labels = labels
self.LabelsTags = labels_tags
self.LabelsFr = labels_fr
def __str__(self):
return self .Labels
| class Productlabels(object):
def __init__(self, labels, labels_tags, labels_fr):
self.Labels = labels
self.LabelsTags = labels_tags
self.LabelsFr = labels_fr
def __str__(self):
return self.Labels |
def dds_insert(d, s, p, o):
if d.get(s) is None:
d[s] = {}
if d[s].get(p) is None:
d[s][p] = set()
d[s][p].add(o)
def dds_remove(d, s, p, o):
if d.get(s) is not None and d[s].get(p) is not None:
d[s][p].remove(o)
if not d[s][p]:
del d[s][p]
if not d[s]:
del d[s]
class JsonLDIndex:
def __init__(self, spo=None, pos=None):
self.spo = {} if spo is None else spo
self.pos = {} if pos is None else pos
#
def insert_triples(self, triples):
for subj, pred, obj in triples:
dds_insert(self.spo, subj, pred, obj)
# dds_insert(self.spo, obj, '~'+pred, subj)
dds_insert(self.pos, pred, obj, subj)
dds_insert(self.pos, '~'+pred, subj, obj)
#
return self
#
def remove_triples(self, triples):
for subj, pred, obj in triples:
dds_remove(self.spo, subj, pred, obj)
# dds_remove(self.spo, obj, '~'+pred, subj)
dds_remove(self.pos, pred, obj, subj)
dds_remove(self.pos, '~'+pred, subj, obj)
#
return self
| def dds_insert(d, s, p, o):
if d.get(s) is None:
d[s] = {}
if d[s].get(p) is None:
d[s][p] = set()
d[s][p].add(o)
def dds_remove(d, s, p, o):
if d.get(s) is not None and d[s].get(p) is not None:
d[s][p].remove(o)
if not d[s][p]:
del d[s][p]
if not d[s]:
del d[s]
class Jsonldindex:
def __init__(self, spo=None, pos=None):
self.spo = {} if spo is None else spo
self.pos = {} if pos is None else pos
def insert_triples(self, triples):
for (subj, pred, obj) in triples:
dds_insert(self.spo, subj, pred, obj)
dds_insert(self.pos, pred, obj, subj)
dds_insert(self.pos, '~' + pred, subj, obj)
return self
def remove_triples(self, triples):
for (subj, pred, obj) in triples:
dds_remove(self.spo, subj, pred, obj)
dds_remove(self.pos, pred, obj, subj)
dds_remove(self.pos, '~' + pred, subj, obj)
return self |
# BGR colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY25 = (64, 64, 64)
GRAY50 = (128, 128, 128)
GRAY75 = (192, 192, 192)
GRAY33 = (85, 85, 85)
GRAY66 = (170, 170, 170)
BLUE = (255, 0, 0)
GREEN = (0, 255, 0)
RED = (0, 0, 255)
CYAN = (255, 255, 0)
MAGENTA = (255, 0, 255)
YELLOW = (0, 255, 255)
ORANGE = (0, 128, 255)
PURPLE = (255, 0, 128)
MINT = (128, 255, 0)
LIME = (0, 255, 128)
PINK = (128, 0, 255)
| white = (255, 255, 255)
black = (0, 0, 0)
gray25 = (64, 64, 64)
gray50 = (128, 128, 128)
gray75 = (192, 192, 192)
gray33 = (85, 85, 85)
gray66 = (170, 170, 170)
blue = (255, 0, 0)
green = (0, 255, 0)
red = (0, 0, 255)
cyan = (255, 255, 0)
magenta = (255, 0, 255)
yellow = (0, 255, 255)
orange = (0, 128, 255)
purple = (255, 0, 128)
mint = (128, 255, 0)
lime = (0, 255, 128)
pink = (128, 0, 255) |
class Node(object):
value = None
left_child = None
right_child = None
def __init__(self, value, left=None, right=None):
self.value = value
if left:
self.left_child = left
if right:
self.right_child = right
def __str__(self):
return self.value
def has_left(self):
return True if self.left_child else False
def has_right(self):
return True if self.right_child else False
class BinaryTree(object):
root: Node = None
def __init__(self, node: Node = None):
if not self.root and node:
self.root = node
def __add__(self, node: Node, parent: Node = None):
if not self.root:
self.__init__(node=node)
else:
if parent:
if parent.value >= node.value:
if parent.has_right():
self.__add__(node=node, parent=parent.right_child)
else:
parent.right_child = node
else:
if parent.has_left():
self.__add__(node=node, parent=parent.left_child)
else:
parent.left_child = node
else:
self.__add__(node=node, parent=self.root)
def search_back(self, number, node: Node, level_count):
if number == node.value:
return level_count, True
else:
if number < node.value:
if node.has_left():
self.search_back(number=number, node=node.left_child, level_count=level_count + 1)
else:
return False
else:
if node.has_right():
self.search_back(number=number, node=node.right_child, level_count=level_count + 1)
else:
return False
def search(self, number):
return self.search_back(number=number, node=self.root, level_count=0)
def print_level(self, level_count, node: Node, result: list):
if not node:
return
else:
if level_count == 0:
result.append(node)
self.print_level(level_count=level_count - 1, node=node.left_child, result=result)
self.print_level(level_count=level_count - 1, node=node.right_child, result=result)
def print_tree(self, result: list, node: Node):
result.append(node)
if node.has_left():
self.print_tree(result=result, node=node.left_child)
elif node.has_right():
self.print_tree(result=result, node=node.right_child)
def height(self, node: Node):
if not node:
return 0
else:
if node.has_left():
l_height = self.height(node=node.left_child)
else:
l_height = -1
if node.has_right():
r_height = self.height(node=node.right_child)
else:
r_height = -1
max_height = l_height if l_height > r_height else r_height
return max_height + 1
def to_array_values(self, result: list, node: Node):
result.append(node.value)
if node.has_left():
self.to_array_values(result=result, node=node.left_child)
elif node.has_right():
self.to_array_values(result=result, node=node.right_child)
def to_array_nodes(self, result: list, node: Node):
result.append(node)
if node.has_left():
self.to_array_values(result=result, node=node.left_child)
elif node.has_right():
self.to_array_values(result=result, node=node.right_child)
def join_trees(bst_1: BinaryTree, bst_2: BinaryTree):
tree_array_1 = []
tree_array_2 = []
bst_1.to_array_values(tree_array_1, bst_1.root)
bst_2.to_array_values(tree_array_2, bst_2.root)
result_array = [*tree_array_1, *tree_array_2]
bst_result = BinaryTree()
for item in result_array:
node = Node(item)
bst_result.__add__(node=node)
return bst_result
| class Node(object):
value = None
left_child = None
right_child = None
def __init__(self, value, left=None, right=None):
self.value = value
if left:
self.left_child = left
if right:
self.right_child = right
def __str__(self):
return self.value
def has_left(self):
return True if self.left_child else False
def has_right(self):
return True if self.right_child else False
class Binarytree(object):
root: Node = None
def __init__(self, node: Node=None):
if not self.root and node:
self.root = node
def __add__(self, node: Node, parent: Node=None):
if not self.root:
self.__init__(node=node)
elif parent:
if parent.value >= node.value:
if parent.has_right():
self.__add__(node=node, parent=parent.right_child)
else:
parent.right_child = node
elif parent.has_left():
self.__add__(node=node, parent=parent.left_child)
else:
parent.left_child = node
else:
self.__add__(node=node, parent=self.root)
def search_back(self, number, node: Node, level_count):
if number == node.value:
return (level_count, True)
elif number < node.value:
if node.has_left():
self.search_back(number=number, node=node.left_child, level_count=level_count + 1)
else:
return False
elif node.has_right():
self.search_back(number=number, node=node.right_child, level_count=level_count + 1)
else:
return False
def search(self, number):
return self.search_back(number=number, node=self.root, level_count=0)
def print_level(self, level_count, node: Node, result: list):
if not node:
return
else:
if level_count == 0:
result.append(node)
self.print_level(level_count=level_count - 1, node=node.left_child, result=result)
self.print_level(level_count=level_count - 1, node=node.right_child, result=result)
def print_tree(self, result: list, node: Node):
result.append(node)
if node.has_left():
self.print_tree(result=result, node=node.left_child)
elif node.has_right():
self.print_tree(result=result, node=node.right_child)
def height(self, node: Node):
if not node:
return 0
else:
if node.has_left():
l_height = self.height(node=node.left_child)
else:
l_height = -1
if node.has_right():
r_height = self.height(node=node.right_child)
else:
r_height = -1
max_height = l_height if l_height > r_height else r_height
return max_height + 1
def to_array_values(self, result: list, node: Node):
result.append(node.value)
if node.has_left():
self.to_array_values(result=result, node=node.left_child)
elif node.has_right():
self.to_array_values(result=result, node=node.right_child)
def to_array_nodes(self, result: list, node: Node):
result.append(node)
if node.has_left():
self.to_array_values(result=result, node=node.left_child)
elif node.has_right():
self.to_array_values(result=result, node=node.right_child)
def join_trees(bst_1: BinaryTree, bst_2: BinaryTree):
tree_array_1 = []
tree_array_2 = []
bst_1.to_array_values(tree_array_1, bst_1.root)
bst_2.to_array_values(tree_array_2, bst_2.root)
result_array = [*tree_array_1, *tree_array_2]
bst_result = binary_tree()
for item in result_array:
node = node(item)
bst_result.__add__(node=node)
return bst_result |
# START LAB EXERCISE 04
print('Lab Exercise 04 \n')
# SETUP
city_state = ["Detroit|MI", "Philadelphia|PA", "Hollywood|CA",
"Oakland|CA", "Boston|MA", "Atlanta|GA",
"Phoenix|AZ", "Birmingham|AL", "Houston|TX", "Tampa|FL"]
# END SETUP
# PROBLEM 1.0 (5 Points)
# PROBLEM 2.0 (5 Points)
# PROBLEM 3.0 (10 Points)
# END LAB EXERCISE | print('Lab Exercise 04 \n')
city_state = ['Detroit|MI', 'Philadelphia|PA', 'Hollywood|CA', 'Oakland|CA', 'Boston|MA', 'Atlanta|GA', 'Phoenix|AZ', 'Birmingham|AL', 'Houston|TX', 'Tampa|FL'] |
# -*- coding: utf-8 -*-
string1 = "Becomes"
string2 = "becomes"
string3 = "BEAR"
string4 = " bEautiful"
string1 = string1.lower()
# (string2 will pass unmodified)
string3 = string3.lower()
string4 = string4.strip().lower()
print(string1.startswith("be"))
print(string2.startswith("be"))
print(string3.startswith("be"))
print(string4.startswith("be"))
| string1 = 'Becomes'
string2 = 'becomes'
string3 = 'BEAR'
string4 = ' bEautiful'
string1 = string1.lower()
string3 = string3.lower()
string4 = string4.strip().lower()
print(string1.startswith('be'))
print(string2.startswith('be'))
print(string3.startswith('be'))
print(string4.startswith('be')) |
class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
class BinarySearchTree(object):
def __init__(self, root=None):
self.root = root
def get_root(self):
return self.root
def insert(self, item):
if self.root is None:
self.root = Node(item)
else:
cur_node = self.root
while cur_node is not None:
if item < cur_node.data:
if cur_node.left is None:
cur_node = Node(item)
return
else:
cur_node = cur_node.left
else:
if cur_node.right is None:
cur_node = Node(item)
return
else:
cur_node = cur_node.right
| class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
class Binarysearchtree(object):
def __init__(self, root=None):
self.root = root
def get_root(self):
return self.root
def insert(self, item):
if self.root is None:
self.root = node(item)
else:
cur_node = self.root
while cur_node is not None:
if item < cur_node.data:
if cur_node.left is None:
cur_node = node(item)
return
else:
cur_node = cur_node.left
elif cur_node.right is None:
cur_node = node(item)
return
else:
cur_node = cur_node.right |
def ask_question():
print("Who is the founder of Facebook?")
option=["Mark Zuckerberg","Bill Gates","Steve Jobs","Larry Page"]
for i in option:
print(i)
ask_question()
i=0
while i<100:
ask_question()
i+=1
def say_hello(name):
print ("Hello ", name)
print ("Aap kaise ho?")
say_hello("jai")
def add_number(num1,num2):
print("hum2 numbers ko add krenge")
print(num1+num2)
add_number(112,3)
varx=10
vary=20
add_number(varx,vary)
def say_lang(name,language):
if language=="punjabi":
print("sat sri akaal",name)
elif language=="hindi":
print("Namestye",name)
elif language=="English":
print("good morning",name)
say_lang("rishabh","hindi")
say_lang("jai","English")
def print_lines(name,position):
print("mera naam "+str(name)+" hai")
print("mein "+str(position)+" ka co-founder hu")
print_lines("jai","Navgurkul")
def add_numbers(number1,number2):
add=number1+number2
print(number1,"aur",number2," ka sum:-",add)
add_numbers(56,12)
num1=[15,20,30]
num2=[20,30,40]
def add_num_list(num1,num2):
i=0
b = []
while i<len(num1):
add = num1[i]+num2[i]
i+=1
b.append(add)
return (b)
print(add_num_list(num1,num2))
num1=[15,20,30,2, 6, 18, 10, 3, 75]
num2=[20,30,40,6, 19, 24, 12, 3, 87]
def add_num_list(num1,num2):
i=0
while i<len(num1):
if num1[i]%2==0 and num2[i]%2==0:
print("even hai")
else:
print("odd hai")
i+=1
(add_num_list(num1,num2))
def add_numbers_print(number_x, number_y):
number_sum = number_x + number_y
return number_sum
sum4 = add_numbers_print(4, 5)
print (sum4)
print (type(sum4))
def calculator(numx,numy,operator):
if operator=="add":
add=numx+numy
return add
elif operator=="subtract":
subtract=numx-numy
return subtract
elif operator=="multiply":
multiply=numx*numy
return multiply
elif operator=="divide":
divide=numx/numy
return divide
num1=int(input("Enter the 1st number :- "))
num2=int(input("Enter the 2nd number :- "))
num3=input("which action you want to perform (add/subtract/multiply/divide)")
print(calculator(num1,num2,num3))
a=[3,4,5,6]
b=[2,4,5,6]
def list_change(a,b):
i=0
multiply=0
c=[]
while i<len(a):
multiply=a[i]*b[i]
c.append(multiply)
i+=1
return c
print(list_change(a,b))
| def ask_question():
print('Who is the founder of Facebook?')
option = ['Mark Zuckerberg', 'Bill Gates', 'Steve Jobs', 'Larry Page']
for i in option:
print(i)
ask_question()
i = 0
while i < 100:
ask_question()
i += 1
def say_hello(name):
print('Hello ', name)
print('Aap kaise ho?')
say_hello('jai')
def add_number(num1, num2):
print('hum2 numbers ko add krenge')
print(num1 + num2)
add_number(112, 3)
varx = 10
vary = 20
add_number(varx, vary)
def say_lang(name, language):
if language == 'punjabi':
print('sat sri akaal', name)
elif language == 'hindi':
print('Namestye', name)
elif language == 'English':
print('good morning', name)
say_lang('rishabh', 'hindi')
say_lang('jai', 'English')
def print_lines(name, position):
print('mera naam ' + str(name) + ' hai')
print('mein ' + str(position) + ' ka co-founder hu')
print_lines('jai', 'Navgurkul')
def add_numbers(number1, number2):
add = number1 + number2
print(number1, 'aur', number2, ' ka sum:-', add)
add_numbers(56, 12)
num1 = [15, 20, 30]
num2 = [20, 30, 40]
def add_num_list(num1, num2):
i = 0
b = []
while i < len(num1):
add = num1[i] + num2[i]
i += 1
b.append(add)
return b
print(add_num_list(num1, num2))
num1 = [15, 20, 30, 2, 6, 18, 10, 3, 75]
num2 = [20, 30, 40, 6, 19, 24, 12, 3, 87]
def add_num_list(num1, num2):
i = 0
while i < len(num1):
if num1[i] % 2 == 0 and num2[i] % 2 == 0:
print('even hai')
else:
print('odd hai')
i += 1
add_num_list(num1, num2)
def add_numbers_print(number_x, number_y):
number_sum = number_x + number_y
return number_sum
sum4 = add_numbers_print(4, 5)
print(sum4)
print(type(sum4))
def calculator(numx, numy, operator):
if operator == 'add':
add = numx + numy
return add
elif operator == 'subtract':
subtract = numx - numy
return subtract
elif operator == 'multiply':
multiply = numx * numy
return multiply
elif operator == 'divide':
divide = numx / numy
return divide
num1 = int(input('Enter the 1st number :- '))
num2 = int(input('Enter the 2nd number :- '))
num3 = input('which action you want to perform (add/subtract/multiply/divide)')
print(calculator(num1, num2, num3))
a = [3, 4, 5, 6]
b = [2, 4, 5, 6]
def list_change(a, b):
i = 0
multiply = 0
c = []
while i < len(a):
multiply = a[i] * b[i]
c.append(multiply)
i += 1
return c
print(list_change(a, b)) |
input_file = open("input.txt","r")
lines = input_file.readlines()
count = 0
answers = set()
for line in lines:
if line == "\n":
count += len(answers)
print(answers)
answers.clear()
for character in line:
#print(character)
if character != "\n":
answers.add(character)
count += len(answers)
print(answers)
answers.clear()
print(count) | input_file = open('input.txt', 'r')
lines = input_file.readlines()
count = 0
answers = set()
for line in lines:
if line == '\n':
count += len(answers)
print(answers)
answers.clear()
for character in line:
if character != '\n':
answers.add(character)
count += len(answers)
print(answers)
answers.clear()
print(count) |
class BankAccount:
def __init__(self):
self.accountNum = 0
self.accountOwner = ""
self.accountBalance = 0.00
def ModifyAccount(self, id, name, balance):
self.accountNum = id
self.accountOwner = name
self.accountBalance = balance
account = BankAccount()
account.ModifyAccount(12345, "John Doe", 123456.78)
print("Account ID: {}, Name: {}, Balance: ${}".format(account.accountNum, account.accountOwner, account.accountBalance)) | class Bankaccount:
def __init__(self):
self.accountNum = 0
self.accountOwner = ''
self.accountBalance = 0.0
def modify_account(self, id, name, balance):
self.accountNum = id
self.accountOwner = name
self.accountBalance = balance
account = bank_account()
account.ModifyAccount(12345, 'John Doe', 123456.78)
print('Account ID: {}, Name: {}, Balance: ${}'.format(account.accountNum, account.accountOwner, account.accountBalance)) |
class Solution:
def maxDepth(self, root):
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
| class Solution:
def max_depth(self, root):
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) |
lis = []
for i in range (10):
num = int(input())
lis.append(num)
print(lis)
for i in range (len(lis)):
print(lis[i])
| lis = []
for i in range(10):
num = int(input())
lis.append(num)
print(lis)
for i in range(len(lis)):
print(lis[i]) |
n = int(input('enter number to find the factorial: '))
fact=1;
for i in range(1,n+1,1):
fact=fact*i
print(fact)
| n = int(input('enter number to find the factorial: '))
fact = 1
for i in range(1, n + 1, 1):
fact = fact * i
print(fact) |
Automoviles=['Dodge Challeger', 'VW Gti', 'Jeep Rubicon', 'Alfa Romeo Quadro', 'Ford ST', 'Dodge RAM', 'Ford FX4']
M1="Me gustaria compar un " + Automoviles[0].title()+"."
M2="Mi vecino choco su nuevo " + Automoviles[1].title() + "."
M3="El nuevo " + Automoviles[2].title()+ " es mucho mas economico."
M4="Hay una gran diferencia entre el " + Automoviles[3].title() + " y el " + Automoviles[4].title()+"."
M5="La camioneta " + Automoviles[5].title() + " es de gasolina, mientras que la " + Automoviles[6].title() +" es de Diesel."
print(M1)
print(M2)
print(M3)
print(M4)
print(M5)
| automoviles = ['Dodge Challeger', 'VW Gti', 'Jeep Rubicon', 'Alfa Romeo Quadro', 'Ford ST', 'Dodge RAM', 'Ford FX4']
m1 = 'Me gustaria compar un ' + Automoviles[0].title() + '.'
m2 = 'Mi vecino choco su nuevo ' + Automoviles[1].title() + '.'
m3 = 'El nuevo ' + Automoviles[2].title() + ' es mucho mas economico.'
m4 = 'Hay una gran diferencia entre el ' + Automoviles[3].title() + ' y el ' + Automoviles[4].title() + '.'
m5 = 'La camioneta ' + Automoviles[5].title() + ' es de gasolina, mientras que la ' + Automoviles[6].title() + ' es de Diesel.'
print(M1)
print(M2)
print(M3)
print(M4)
print(M5) |
class Stock:
def __init__(self, symbol, name):
self.__name = name
self.__symbol = symbol
self.__stockPlate = []
self.__carePlate = []
@property
def name(self):
return self.__name
@property
def symbol(self):
return self.__symbol
@property
def stockPlate(self):
return self.stockPlate
@property
def carePlate(self):
return self.__carePlate
def addCarePlate(self, cp):
if cp in self.__carePlate:
print("Already exist!")
else:
self.__carePlate.append(cp)
def addStockPlate(self, sp):
if sp in self.__stockPlate:
print("Already exist!")
else:
self.__stockPlate.append(sp)
# print("Success")
def formatPlateInfo(self):
# print(self.__carePlate)
return {"name": self.__name, "carePlate":self.__carePlate, "stockPlate": self.__stockPlate} | class Stock:
def __init__(self, symbol, name):
self.__name = name
self.__symbol = symbol
self.__stockPlate = []
self.__carePlate = []
@property
def name(self):
return self.__name
@property
def symbol(self):
return self.__symbol
@property
def stock_plate(self):
return self.stockPlate
@property
def care_plate(self):
return self.__carePlate
def add_care_plate(self, cp):
if cp in self.__carePlate:
print('Already exist!')
else:
self.__carePlate.append(cp)
def add_stock_plate(self, sp):
if sp in self.__stockPlate:
print('Already exist!')
else:
self.__stockPlate.append(sp)
def format_plate_info(self):
return {'name': self.__name, 'carePlate': self.__carePlate, 'stockPlate': self.__stockPlate} |
#Programa para evaluar si un numero es feliz
numero_a_evaluar = input("Introduce el numero a evaluar: ")
n = numero_a_evaluar
suma = 2
primer_digito = 0
segundo_digito = 0
tercer_digito = 0
cuarto_digito = 0
while suma > 1:
primer_digito = numero_a_evaluar[0]
primer_digito = int(primer_digito)
print(primer_digito)
try:
segundo_digito = numero_a_evaluar[1]
segundo_digito = int(segundo_digito)
print(segundo_digito)
except IndexError as Numeromenorandigits:
pass
try:
tercer_digito = numero_a_evaluar[2]
tercer_digito = int(tercer_digito)
print(tercer_digito)
except IndexError as Numeromenorandigits:
pass
try:
cuarto_digito = numero_a_evaluar[3]
cuarto_digito = int(cuarto_digito)
print(cuarto_digito)
except IndexError as Numeromenorandigits:
pass
suma = primer_digito ** 2 + segundo_digito ** 2 + tercer_digito ** 2
print (suma)
numero_a_evaluar = suma
numero_a_evaluar = str(numero_a_evaluar)
if suma == 1:
print(n,"es un numero feliz")
| numero_a_evaluar = input('Introduce el numero a evaluar: ')
n = numero_a_evaluar
suma = 2
primer_digito = 0
segundo_digito = 0
tercer_digito = 0
cuarto_digito = 0
while suma > 1:
primer_digito = numero_a_evaluar[0]
primer_digito = int(primer_digito)
print(primer_digito)
try:
segundo_digito = numero_a_evaluar[1]
segundo_digito = int(segundo_digito)
print(segundo_digito)
except IndexError as Numeromenorandigits:
pass
try:
tercer_digito = numero_a_evaluar[2]
tercer_digito = int(tercer_digito)
print(tercer_digito)
except IndexError as Numeromenorandigits:
pass
try:
cuarto_digito = numero_a_evaluar[3]
cuarto_digito = int(cuarto_digito)
print(cuarto_digito)
except IndexError as Numeromenorandigits:
pass
suma = primer_digito ** 2 + segundo_digito ** 2 + tercer_digito ** 2
print(suma)
numero_a_evaluar = suma
numero_a_evaluar = str(numero_a_evaluar)
if suma == 1:
print(n, 'es un numero feliz') |
def read_label_pbtxt(label_path: str) -> dict:
with open(label_path, "r") as label_file:
lines = label_file.readlines()
labels = {}
for row, content in enumerate(lines):
labels[row] = {"id": row, "name": content.strip()}
return labels
| def read_label_pbtxt(label_path: str) -> dict:
with open(label_path, 'r') as label_file:
lines = label_file.readlines()
labels = {}
for (row, content) in enumerate(lines):
labels[row] = {'id': row, 'name': content.strip()}
return labels |
co2 = input("Please input air quality value: ")
co2 = int(co2)
if co2 > 399 and co2 < 698:
print("Excelent")
elif co2 > 699 and co2 < 898:
print("Good")
elif co2 > 899 and co2 < 1098:
print("Fair")
elif co2 > 1099 and co2 < 1598:
print("Mediocre, contaminated indoor air")
elif co2 > 1599 and co2 < 2101:
print("Bad, heavily contaminated indoor air")
| co2 = input('Please input air quality value: ')
co2 = int(co2)
if co2 > 399 and co2 < 698:
print('Excelent')
elif co2 > 699 and co2 < 898:
print('Good')
elif co2 > 899 and co2 < 1098:
print('Fair')
elif co2 > 1099 and co2 < 1598:
print('Mediocre, contaminated indoor air')
elif co2 > 1599 and co2 < 2101:
print('Bad, heavily contaminated indoor air') |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"GH_HOST": "00_core.ipynb",
"GhApi": "00_core.ipynb",
"date2gh": "00_core.ipynb",
"gh2date": "00_core.ipynb",
"print_summary": "00_core.ipynb",
"GhApi.delete_release": "00_core.ipynb",
"GhApi.upload_file": "00_core.ipynb",
"GhApi.create_release": "00_core.ipynb",
"GhApi.list_tags": "00_core.ipynb",
"GhApi.list_branches": "00_core.ipynb",
"EMPTY_TREE_SHA": "00_core.ipynb",
"GhApi.create_branch_empty": "00_core.ipynb",
"GhApi.delete_tag": "00_core.ipynb",
"GhApi.delete_branch": "00_core.ipynb",
"GhApi.get_branch": "00_core.ipynb",
"GhApi.list_files": "00_core.ipynb",
"GhApi.get_content": "00_core.ipynb",
"GhApi.update_contents": "00_core.ipynb",
"GhApi.enable_pages": "00_core.ipynb",
"contexts": "01_actions.ipynb",
"env_github": "01_actions.ipynb",
"user_repo": "01_actions.ipynb",
"Event": "01_actions.ipynb",
"create_workflow_files": "01_actions.ipynb",
"fill_workflow_templates": "01_actions.ipynb",
"env_contexts": "01_actions.ipynb",
"def_pipinst": "01_actions.ipynb",
"create_workflow": "01_actions.ipynb",
"gh_create_workflow": "01_actions.ipynb",
"example_payload": "01_actions.ipynb",
"github_token": "01_actions.ipynb",
"actions_output": "01_actions.ipynb",
"actions_debug": "01_actions.ipynb",
"actions_warn": "01_actions.ipynb",
"actions_error": "01_actions.ipynb",
"actions_group": "01_actions.ipynb",
"actions_endgroup": "01_actions.ipynb",
"actions_mask": "01_actions.ipynb",
"set_git_user": "01_actions.ipynb",
"Scope": "02_auth.ipynb",
"scope_str": "02_auth.ipynb",
"GhDeviceAuth": "02_auth.ipynb",
"GhDeviceAuth.url_docs": "02_auth.ipynb",
"GhDeviceAuth.open_browser": "02_auth.ipynb",
"GhDeviceAuth.auth": "02_auth.ipynb",
"GhDeviceAuth.wait": "02_auth.ipynb",
"paged": "03_page.ipynb",
"parse_link_hdr": "03_page.ipynb",
"GhApi.last_page": "03_page.ipynb",
"pages": "03_page.ipynb",
"GhApi.list_events": "04_event.ipynb",
"GhApi.list_events_parallel": "04_event.ipynb",
"GhEvent": "04_event.ipynb",
"GhApi.fetch_events": "04_event.ipynb",
"load_sample_events": "04_event.ipynb",
"save_sample_events": "04_event.ipynb",
"full_type": "04_event.ipynb",
"evt_emojis": "04_event.ipynb",
"description": "04_event.ipynb",
"emoji": "04_event.ipynb",
"text": "04_event.ipynb",
"described_evts": "04_event.ipynb",
"ghapi": "10_cli.ipynb",
"ghpath": "10_cli.ipynb",
"ghraw": "10_cli.ipynb",
"completion_ghapi": "10_cli.ipynb",
"GH_OPENAPI_URL": "90_build_lib.ipynb",
"build_funcs": "90_build_lib.ipynb",
"GhMeta": "90_build_lib.ipynb"}
modules = ["core.py",
"actions.py",
"auth.py",
"page.py",
"event.py",
"cli.py",
"build_lib.py"]
doc_url = "https://ghapi.fast.ai/"
git_url = "https://github.com/fastai/ghapi/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'GH_HOST': '00_core.ipynb', 'GhApi': '00_core.ipynb', 'date2gh': '00_core.ipynb', 'gh2date': '00_core.ipynb', 'print_summary': '00_core.ipynb', 'GhApi.delete_release': '00_core.ipynb', 'GhApi.upload_file': '00_core.ipynb', 'GhApi.create_release': '00_core.ipynb', 'GhApi.list_tags': '00_core.ipynb', 'GhApi.list_branches': '00_core.ipynb', 'EMPTY_TREE_SHA': '00_core.ipynb', 'GhApi.create_branch_empty': '00_core.ipynb', 'GhApi.delete_tag': '00_core.ipynb', 'GhApi.delete_branch': '00_core.ipynb', 'GhApi.get_branch': '00_core.ipynb', 'GhApi.list_files': '00_core.ipynb', 'GhApi.get_content': '00_core.ipynb', 'GhApi.update_contents': '00_core.ipynb', 'GhApi.enable_pages': '00_core.ipynb', 'contexts': '01_actions.ipynb', 'env_github': '01_actions.ipynb', 'user_repo': '01_actions.ipynb', 'Event': '01_actions.ipynb', 'create_workflow_files': '01_actions.ipynb', 'fill_workflow_templates': '01_actions.ipynb', 'env_contexts': '01_actions.ipynb', 'def_pipinst': '01_actions.ipynb', 'create_workflow': '01_actions.ipynb', 'gh_create_workflow': '01_actions.ipynb', 'example_payload': '01_actions.ipynb', 'github_token': '01_actions.ipynb', 'actions_output': '01_actions.ipynb', 'actions_debug': '01_actions.ipynb', 'actions_warn': '01_actions.ipynb', 'actions_error': '01_actions.ipynb', 'actions_group': '01_actions.ipynb', 'actions_endgroup': '01_actions.ipynb', 'actions_mask': '01_actions.ipynb', 'set_git_user': '01_actions.ipynb', 'Scope': '02_auth.ipynb', 'scope_str': '02_auth.ipynb', 'GhDeviceAuth': '02_auth.ipynb', 'GhDeviceAuth.url_docs': '02_auth.ipynb', 'GhDeviceAuth.open_browser': '02_auth.ipynb', 'GhDeviceAuth.auth': '02_auth.ipynb', 'GhDeviceAuth.wait': '02_auth.ipynb', 'paged': '03_page.ipynb', 'parse_link_hdr': '03_page.ipynb', 'GhApi.last_page': '03_page.ipynb', 'pages': '03_page.ipynb', 'GhApi.list_events': '04_event.ipynb', 'GhApi.list_events_parallel': '04_event.ipynb', 'GhEvent': '04_event.ipynb', 'GhApi.fetch_events': '04_event.ipynb', 'load_sample_events': '04_event.ipynb', 'save_sample_events': '04_event.ipynb', 'full_type': '04_event.ipynb', 'evt_emojis': '04_event.ipynb', 'description': '04_event.ipynb', 'emoji': '04_event.ipynb', 'text': '04_event.ipynb', 'described_evts': '04_event.ipynb', 'ghapi': '10_cli.ipynb', 'ghpath': '10_cli.ipynb', 'ghraw': '10_cli.ipynb', 'completion_ghapi': '10_cli.ipynb', 'GH_OPENAPI_URL': '90_build_lib.ipynb', 'build_funcs': '90_build_lib.ipynb', 'GhMeta': '90_build_lib.ipynb'}
modules = ['core.py', 'actions.py', 'auth.py', 'page.py', 'event.py', 'cli.py', 'build_lib.py']
doc_url = 'https://ghapi.fast.ai/'
git_url = 'https://github.com/fastai/ghapi/tree/master/'
def custom_doc_links(name):
return None |
def wypisz(par1, par2):
print('{0} {1}'.format(par1, par2))
def sprawdz(arg1, arg2):
if arg1 > arg2:
return True
else:
return False
| def wypisz(par1, par2):
print('{0} {1}'.format(par1, par2))
def sprawdz(arg1, arg2):
if arg1 > arg2:
return True
else:
return False |
ce,nll=input("<<")
lx=ce*(nll/1200)
print("The interest is",lx)
| (ce, nll) = input('<<')
lx = ce * (nll / 1200)
print('The interest is', lx) |
class Edge:
def __init__(self, src, dst, line):
self.src = src
self.dst = dst
self.line = line
assert src != dst, f"Source and destination are the same!"
def reverse(self):
return Edge(self.dst, self.src, self.line.reverse())
def to_dict(self):
return {
"src": self.src.id if self.src else None,
"dst": self.dst.id if self.dst else None,
}
def __str__(self):
src_id = self.src.id if self.src else "None"
dst_id = self.dst.id if self.dst else "None"
return f"{src_id} -> {dst_id}"
| class Edge:
def __init__(self, src, dst, line):
self.src = src
self.dst = dst
self.line = line
assert src != dst, f'Source and destination are the same!'
def reverse(self):
return edge(self.dst, self.src, self.line.reverse())
def to_dict(self):
return {'src': self.src.id if self.src else None, 'dst': self.dst.id if self.dst else None}
def __str__(self):
src_id = self.src.id if self.src else 'None'
dst_id = self.dst.id if self.dst else 'None'
return f'{src_id} -> {dst_id}' |
with open('log', 'r') as logfile:
for line in logfile:
if line.__contains__('LOG'):
print(line)
#pvahdatn@cs-arch-20:~/git/dandelion-lib$ sbt "testOnly dataflow.test03Tester" > log
| with open('log', 'r') as logfile:
for line in logfile:
if line.__contains__('LOG'):
print(line) |
class SortStrategy:
def sort(self, dataset):
pass
class BubbleSortStrategy(SortStrategy):
def sort(self, dataset):
print('Sorting using bubble sort')
return dataset
class QuickSortStrategy(SortStrategy):
def sort(self, dataset):
print('Sorting using quick sort')
return dataset
class Sorter:
_sorter = None
def __init__(self, sorter):
self._sorter = sorter
def sort(self, dataset):
return self._sorter.sort(dataset)
dataset = [1, 5, 4, 3, 2, 8]
sorter = Sorter(BubbleSortStrategy())
sorter.sort(dataset)
sorter = Sorter(QuickSortStrategy())
sorter.sort(dataset) | class Sortstrategy:
def sort(self, dataset):
pass
class Bubblesortstrategy(SortStrategy):
def sort(self, dataset):
print('Sorting using bubble sort')
return dataset
class Quicksortstrategy(SortStrategy):
def sort(self, dataset):
print('Sorting using quick sort')
return dataset
class Sorter:
_sorter = None
def __init__(self, sorter):
self._sorter = sorter
def sort(self, dataset):
return self._sorter.sort(dataset)
dataset = [1, 5, 4, 3, 2, 8]
sorter = sorter(bubble_sort_strategy())
sorter.sort(dataset)
sorter = sorter(quick_sort_strategy())
sorter.sort(dataset) |
'''
BF C(n,k)*n O(n!)
LeetCode 516
DP find the longest palindrome sequence O(n^2)
'''
class Solution:
def isValidPalindrome(self, s: str, k: int) -> bool:
n = len(str)
dp = [[0]*n for _ in range(n)]
for i in range(n-2, -1, -1):
dp[i][i] = 1
for j in range(i+1, n):
if s[i]==s[j]:
dp[i][j] = dp[i+1][j-1] + 2
else:
dp[i][j] = max(dp[i+1][j], dp[i][j-1])
return dp[0][n-1]+k >=len(s) | """
BF C(n,k)*n O(n!)
LeetCode 516
DP find the longest palindrome sequence O(n^2)
"""
class Solution:
def is_valid_palindrome(self, s: str, k: int) -> bool:
n = len(str)
dp = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][n - 1] + k >= len(s) |
def calcula_se_um_numero_eh_par(numero):
if type(numero) == int:
if numero % 2 == 0:
return True
return False
| def calcula_se_um_numero_eh_par(numero):
if type(numero) == int:
if numero % 2 == 0:
return True
return False |
class StompError(Exception):
def __init__(self, message, detail):
super(StompError, self).__init__(message)
self.detail = detail
class StompDisconnectedError(Exception):
pass
class ExceededRetryCount(Exception):
pass
| class Stomperror(Exception):
def __init__(self, message, detail):
super(StompError, self).__init__(message)
self.detail = detail
class Stompdisconnectederror(Exception):
pass
class Exceededretrycount(Exception):
pass |
description = 'setup for the NICOS collector'
group = 'special'
devices = dict(
CacheKafka=device(
'nicos_ess.devices.cache_kafka_forwarder.CacheKafkaForwarder',
dev_ignore=['space', 'sample'],
brokers=configdata('config.KAFKA_BROKERS'),
output_topic="nicos_cache",
update_interval=10.
),
Collector=device('nicos.services.collector.Collector',
cache='localhost:14869',
forwarders=['CacheKafka'],
),
)
| description = 'setup for the NICOS collector'
group = 'special'
devices = dict(CacheKafka=device('nicos_ess.devices.cache_kafka_forwarder.CacheKafkaForwarder', dev_ignore=['space', 'sample'], brokers=configdata('config.KAFKA_BROKERS'), output_topic='nicos_cache', update_interval=10.0), Collector=device('nicos.services.collector.Collector', cache='localhost:14869', forwarders=['CacheKafka'])) |
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
if 1 not in nums: return True
start, end = nums.index(1), nums.index(1)+1
while end < len(nums):
if nums[start] == 1 and nums[end] == 1 and end - start <= k:
return False
elif nums[start] == 1 and nums[end] == 1:
start = end
end += 1
else:
end += 1
return True | class Solution:
def k_length_apart(self, nums: List[int], k: int) -> bool:
if 1 not in nums:
return True
(start, end) = (nums.index(1), nums.index(1) + 1)
while end < len(nums):
if nums[start] == 1 and nums[end] == 1 and (end - start <= k):
return False
elif nums[start] == 1 and nums[end] == 1:
start = end
end += 1
else:
end += 1
return True |
# Copyright https://www.globaletraining.com/
# List comprehensions provide a concise way to create lists.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def main():
final_list = []
for n in my_list:
final_list.append(n + 10)
print(final_list)
# TODO: Using Comprehension
final_list_comp1 = [n + 10 for n in my_list]
print(final_list_comp1)
# TODO: Using Comprehension & condition
final_list_comp2 = [n + 10 for n in my_list if n % 2 == 0]
print(final_list_comp2)
if __name__ == '__main__':
main() | my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def main():
final_list = []
for n in my_list:
final_list.append(n + 10)
print(final_list)
final_list_comp1 = [n + 10 for n in my_list]
print(final_list_comp1)
final_list_comp2 = [n + 10 for n in my_list if n % 2 == 0]
print(final_list_comp2)
if __name__ == '__main__':
main() |
#!/usr/local/bin/python3
def main():
for i in range(1, 8):
print("============================")
print("Towers of Hanoi: {} Disks".format(i))
towers_of_hanoi(i)
print("Number of moves: {}".format(2**i - 1))
print("============================")
return 0
def towers_of_hanoi(n, s="source", t="target", b="buffer"):
# n is number of disks, smaller disk must always be on top of larger one
assert n > 0
if n == 1:
print("Move {} to {}".format(s, t))
return
else:
# Recursively move n-1 disks from source to buffer
towers_of_hanoi(n-1, s, b, t)
# Move largest disk from source to target
towers_of_hanoi(1, s, t, b)
# Recursively move n-1 disks from buffer to target
towers_of_hanoi(n-1, b, t, s)
if __name__ == '__main__':
main()
| def main():
for i in range(1, 8):
print('============================')
print('Towers of Hanoi: {} Disks'.format(i))
towers_of_hanoi(i)
print('Number of moves: {}'.format(2 ** i - 1))
print('============================')
return 0
def towers_of_hanoi(n, s='source', t='target', b='buffer'):
assert n > 0
if n == 1:
print('Move {} to {}'.format(s, t))
return
else:
towers_of_hanoi(n - 1, s, b, t)
towers_of_hanoi(1, s, t, b)
towers_of_hanoi(n - 1, b, t, s)
if __name__ == '__main__':
main() |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/Dummy.msg;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/answer.msg"
services_str = ""
pkg_name = "meturone_egitim"
dependencies_str = "std_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = "meturone_egitim;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg;std_msgs;/opt/ros/noetic/share/std_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python3"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/noetic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
| messages_str = '/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/Dummy.msg;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/answer.msg'
services_str = ''
pkg_name = 'meturone_egitim'
dependencies_str = 'std_msgs'
langs = 'gencpp;geneus;genlisp;gennodejs;genpy'
dep_include_paths_str = 'meturone_egitim;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg;std_msgs;/opt/ros/noetic/share/std_msgs/cmake/../msg'
python_executable = '/usr/bin/python3'
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = '/opt/ros/noetic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py' |
XK_Greek_ALPHAaccent = 0x7a1
XK_Greek_EPSILONaccent = 0x7a2
XK_Greek_ETAaccent = 0x7a3
XK_Greek_IOTAaccent = 0x7a4
XK_Greek_IOTAdiaeresis = 0x7a5
XK_Greek_OMICRONaccent = 0x7a7
XK_Greek_UPSILONaccent = 0x7a8
XK_Greek_UPSILONdieresis = 0x7a9
XK_Greek_OMEGAaccent = 0x7ab
XK_Greek_accentdieresis = 0x7ae
XK_Greek_horizbar = 0x7af
XK_Greek_alphaaccent = 0x7b1
XK_Greek_epsilonaccent = 0x7b2
XK_Greek_etaaccent = 0x7b3
XK_Greek_iotaaccent = 0x7b4
XK_Greek_iotadieresis = 0x7b5
XK_Greek_iotaaccentdieresis = 0x7b6
XK_Greek_omicronaccent = 0x7b7
XK_Greek_upsilonaccent = 0x7b8
XK_Greek_upsilondieresis = 0x7b9
XK_Greek_upsilonaccentdieresis = 0x7ba
XK_Greek_omegaaccent = 0x7bb
XK_Greek_ALPHA = 0x7c1
XK_Greek_BETA = 0x7c2
XK_Greek_GAMMA = 0x7c3
XK_Greek_DELTA = 0x7c4
XK_Greek_EPSILON = 0x7c5
XK_Greek_ZETA = 0x7c6
XK_Greek_ETA = 0x7c7
XK_Greek_THETA = 0x7c8
XK_Greek_IOTA = 0x7c9
XK_Greek_KAPPA = 0x7ca
XK_Greek_LAMDA = 0x7cb
XK_Greek_LAMBDA = 0x7cb
XK_Greek_MU = 0x7cc
XK_Greek_NU = 0x7cd
XK_Greek_XI = 0x7ce
XK_Greek_OMICRON = 0x7cf
XK_Greek_PI = 0x7d0
XK_Greek_RHO = 0x7d1
XK_Greek_SIGMA = 0x7d2
XK_Greek_TAU = 0x7d4
XK_Greek_UPSILON = 0x7d5
XK_Greek_PHI = 0x7d6
XK_Greek_CHI = 0x7d7
XK_Greek_PSI = 0x7d8
XK_Greek_OMEGA = 0x7d9
XK_Greek_alpha = 0x7e1
XK_Greek_beta = 0x7e2
XK_Greek_gamma = 0x7e3
XK_Greek_delta = 0x7e4
XK_Greek_epsilon = 0x7e5
XK_Greek_zeta = 0x7e6
XK_Greek_eta = 0x7e7
XK_Greek_theta = 0x7e8
XK_Greek_iota = 0x7e9
XK_Greek_kappa = 0x7ea
XK_Greek_lamda = 0x7eb
XK_Greek_lambda = 0x7eb
XK_Greek_mu = 0x7ec
XK_Greek_nu = 0x7ed
XK_Greek_xi = 0x7ee
XK_Greek_omicron = 0x7ef
XK_Greek_pi = 0x7f0
XK_Greek_rho = 0x7f1
XK_Greek_sigma = 0x7f2
XK_Greek_finalsmallsigma = 0x7f3
XK_Greek_tau = 0x7f4
XK_Greek_upsilon = 0x7f5
XK_Greek_phi = 0x7f6
XK_Greek_chi = 0x7f7
XK_Greek_psi = 0x7f8
XK_Greek_omega = 0x7f9
XK_Greek_switch = 0xFF7E
| xk__greek_alph_aaccent = 1953
xk__greek_epsilo_naccent = 1954
xk__greek_et_aaccent = 1955
xk__greek_iot_aaccent = 1956
xk__greek_iot_adiaeresis = 1957
xk__greek_omicro_naccent = 1959
xk__greek_upsilo_naccent = 1960
xk__greek_upsilo_ndieresis = 1961
xk__greek_omeg_aaccent = 1963
xk__greek_accentdieresis = 1966
xk__greek_horizbar = 1967
xk__greek_alphaaccent = 1969
xk__greek_epsilonaccent = 1970
xk__greek_etaaccent = 1971
xk__greek_iotaaccent = 1972
xk__greek_iotadieresis = 1973
xk__greek_iotaaccentdieresis = 1974
xk__greek_omicronaccent = 1975
xk__greek_upsilonaccent = 1976
xk__greek_upsilondieresis = 1977
xk__greek_upsilonaccentdieresis = 1978
xk__greek_omegaaccent = 1979
xk__greek_alpha = 1985
xk__greek_beta = 1986
xk__greek_gamma = 1987
xk__greek_delta = 1988
xk__greek_epsilon = 1989
xk__greek_zeta = 1990
xk__greek_eta = 1991
xk__greek_theta = 1992
xk__greek_iota = 1993
xk__greek_kappa = 1994
xk__greek_lamda = 1995
xk__greek_lambda = 1995
xk__greek_mu = 1996
xk__greek_nu = 1997
xk__greek_xi = 1998
xk__greek_omicron = 1999
xk__greek_pi = 2000
xk__greek_rho = 2001
xk__greek_sigma = 2002
xk__greek_tau = 2004
xk__greek_upsilon = 2005
xk__greek_phi = 2006
xk__greek_chi = 2007
xk__greek_psi = 2008
xk__greek_omega = 2009
xk__greek_alpha = 2017
xk__greek_beta = 2018
xk__greek_gamma = 2019
xk__greek_delta = 2020
xk__greek_epsilon = 2021
xk__greek_zeta = 2022
xk__greek_eta = 2023
xk__greek_theta = 2024
xk__greek_iota = 2025
xk__greek_kappa = 2026
xk__greek_lamda = 2027
xk__greek_lambda = 2027
xk__greek_mu = 2028
xk__greek_nu = 2029
xk__greek_xi = 2030
xk__greek_omicron = 2031
xk__greek_pi = 2032
xk__greek_rho = 2033
xk__greek_sigma = 2034
xk__greek_finalsmallsigma = 2035
xk__greek_tau = 2036
xk__greek_upsilon = 2037
xk__greek_phi = 2038
xk__greek_chi = 2039
xk__greek_psi = 2040
xk__greek_omega = 2041
xk__greek_switch = 65406 |
#moveable_player
class MoveablePlayer:
def __init__(self, x=2, y=2, dir="FORWARD", color="170"):
self.x = x
self.y = y
self.direction = dir
self.color = color
| class Moveableplayer:
def __init__(self, x=2, y=2, dir='FORWARD', color='170'):
self.x = x
self.y = y
self.direction = dir
self.color = color |
# =============================================================================================
#
# =============================================================================================
#
# 2 16 20 3 4 21 # GPIO Pin number
# | | | | | |
# -----|-----|-----|-----|-----|-----|-----
# 12 11 10 9 8 7 # Display Pin number
# 1 a f 2 3 b # Segment/Digit Identifier
#
#
# e d h c g 4 # Segment/Digit Identifier
# 1 2 3 4 5 6 # Display Pin number
# -----|-----|-----|-----|-----|-----|-----
# 5 6 13 19 20 17 # GPIO Pin number
#
digits = [2,3,4,17]
One = [2]
Two = [3]
Three = [4]
Four = [17]
| digits = [2, 3, 4, 17]
one = [2]
two = [3]
three = [4]
four = [17] |
# -*- coding: utf-8 -*-
class Trial(object):
'''
Created Fri 2 Aug 2013 - ajl
Last edited: Sun 4 Aug 2013 - ajl
This class contains all variables and methods associated with a single trial
'''
def __init__(self, trialid = 0, staircaseid = 0,
condition = 0, stimval = 0, interval = 1):
''' Constructor '''
self._TrialID = trialid;
self._StaircaseID = staircaseid;
self._Condition = condition;
self._Stimval = stimval;
self._Interval = interval;
self._Response = None;
self._ReactionTime = None;
# show the values of this specific trial
def __str__(self):
return '#%2.f \t %2.f \t %2.f' % (self._TrialID, self._StaircaseID, self._Stimval);
# s = '[ #%2.f ] \t (%.f) \t\t Stim(%4.f) \t Interval(%.f) \t Resp(%.f)' % \
# (self._TrialID+1, self._Condition, self._Stimval, self._Interval, self._Response)
''' Fields or properties '''
@property
def Response(self):
return self._Response;
@Response.setter
def Response(self, value):
self._Response = value;
''' Methods '''
# returns the name of the current condition
def GetConditionName(self):
# this is really quite awkward
return
| class Trial(object):
"""
Created Fri 2 Aug 2013 - ajl
Last edited: Sun 4 Aug 2013 - ajl
This class contains all variables and methods associated with a single trial
"""
def __init__(self, trialid=0, staircaseid=0, condition=0, stimval=0, interval=1):
""" Constructor """
self._TrialID = trialid
self._StaircaseID = staircaseid
self._Condition = condition
self._Stimval = stimval
self._Interval = interval
self._Response = None
self._ReactionTime = None
def __str__(self):
return '#%2.f \t %2.f \t %2.f' % (self._TrialID, self._StaircaseID, self._Stimval)
' Fields or properties '
@property
def response(self):
return self._Response
@Response.setter
def response(self, value):
self._Response = value
' Methods '
def get_condition_name(self):
return |
## Q2: What is the time complexity of
## O(n), porque es un for de i=n hasta i=1
# Algoritmo
# for (i = n; i > 0; i--) { # n
# statement; # 1
# }
n = 5
for i in range(n, 0, -1): # n
print(i); # 1 | n = 5
for i in range(n, 0, -1):
print(i) |
# pylint: disable=redefined-outer-name,protected-access
# pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring
def test_can_construct_author(author):
assert isinstance(author.name, str)
assert isinstance(author.url, str)
assert isinstance(author.github_url, str)
assert isinstance(author.github_avatar_url, str)
assert str(author) == author.name
assert repr(author) == author.name
assert author._repr_html_(width="21x", height="22px") == (
'<a href="https://github.com/holoviz/" title="Author: panel" target="_blank">'
'<img application="https://avatars2.githubusercontent.com/u/51678735" alt="panel" '
'style="border-radius: 50%;width: 21x;height: 22px;vertical-align: text-bottom;">'
"</img></a>"
)
| def test_can_construct_author(author):
assert isinstance(author.name, str)
assert isinstance(author.url, str)
assert isinstance(author.github_url, str)
assert isinstance(author.github_avatar_url, str)
assert str(author) == author.name
assert repr(author) == author.name
assert author._repr_html_(width='21x', height='22px') == '<a href="https://github.com/holoviz/" title="Author: panel" target="_blank"><img application="https://avatars2.githubusercontent.com/u/51678735" alt="panel" style="border-radius: 50%;width: 21x;height: 22px;vertical-align: text-bottom;"></img></a>' |
#%% VARIABLES
'Variables'
# var1 = 10
# var2 = "Hello World"
# var3 = None
# var4 = 3.5
# if 0:
# print ("hello world 0") #el 0 fnciona como Falsey
# if 1:
# print ("hello world 1") #el 1 funciona como Truthy
# x1 = 100
# x2 = 20
# x3 = -5
# y = x1 + x2 + x3
# z = x1 - x2 * x3
# w = (x1+x2+x3) - (x1-x2*x3)
# num = 23
# data = True
# var = 40.0
# res1 = num + data
# res2 = data/var
# res3 = num*var
# num = 23
# data = False
# var = 40.0
# res1 = num + data
# res2 = data/var
# res3 = num*var
# result = 70
# data = False
# value = '158'
# var1 = result*data
# var2 = data+value
# var3 = result/value
# result = 5
# value = '158'
# location = 'payunia'
# name = 'Mike '
# phrase = 'needs a coffee'
# full_phrase = name + phrase
# extended_phrase = full_phrase + ' urgente!'
# subnet = '192.168.0'
# host = '34'
# ip = subnet + '.' + host
# message = 'IP address: ' + ip
#%% ACTIVIDADES
'Actividad 1'
a = 50
b = 6
c = 8
d = 2*a + 1/(b-5*c)
d1 = ((a*b+c)/(2-a) + ((a*b+c)/(2-a) + 2)/(c+b)) * (1 + (a*b+c)/(2-a))
'Actividad 2'
# word0 = 'Life'
# word1 = 'ocean'
# word2 = 'up'
# word3 = 'down'
# word4 = word0 + ' is like the ' + word1 + ", it goes " + word2 +\
# " and " + word3
word0 ='Mars'
word1 = 'Earth'
word2 = 'round'
word3 = 'round'
word4 = word0 + ' is like the ' + word1 + ", it goes " + word2 +\
" and " + word3 | """Variables"""
'Actividad 1'
a = 50
b = 6
c = 8
d = 2 * a + 1 / (b - 5 * c)
d1 = ((a * b + c) / (2 - a) + ((a * b + c) / (2 - a) + 2) / (c + b)) * (1 + (a * b + c) / (2 - a))
'Actividad 2'
word0 = 'Mars'
word1 = 'Earth'
word2 = 'round'
word3 = 'round'
word4 = word0 + ' is like the ' + word1 + ', it goes ' + word2 + ' and ' + word3 |
class PingPacket:
def __init__(self):
self.type = "PING"
self.serial = 0
def read(self, reader):
self.serial = reader.readInt32()
| class Pingpacket:
def __init__(self):
self.type = 'PING'
self.serial = 0
def read(self, reader):
self.serial = reader.readInt32() |
n = int(input())
for teste in range(n):
m = int(input())
lista = [int(x) for x in input().split()]
impares = []
for x in lista:
if x%2 == 1:
impares.append(x)
impares.sort()
laercio = []
while len(impares) > 0:
laercio.append(impares.pop())
impares.reverse()
print(*laercio)
| n = int(input())
for teste in range(n):
m = int(input())
lista = [int(x) for x in input().split()]
impares = []
for x in lista:
if x % 2 == 1:
impares.append(x)
impares.sort()
laercio = []
while len(impares) > 0:
laercio.append(impares.pop())
impares.reverse()
print(*laercio) |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
class ProjectFailed(object):
def __init__(self, message):
self.valid = False
self.message = message
| class Projectfailed(object):
def __init__(self, message):
self.valid = False
self.message = message |
class Matrix:
def __init__(self, *args, **kwargs):
if len(args) > 0:
if isinstance(args[0], Matrix):
m = args[0].copy()
else:
m = {'vals': [], 'w': 0, 'h': 0}
self.vals = m.vals
self.w = m.w
self.h = m.h
def copy(self):
new_m = Matrix()
for i in self.vals:
new_m.vals.append(i)
new_m.w = self.w
new_m.h = self.h
return new_m
@property
def width(self):
return self.w
@property
def height(self):
return self.h
def value_at(self, row, col):
return self.vals[row*self.w + col]
def at(self, row, col):
return self.value_at(row, col)
def row(self, pos):
return [self.vals[pos*self.w + i] for i in range(self.w)]
@property
def rows(self):
return [self.row(i) for i in range(self.h)]
def col(self, pos):
return [self.vals[i*self.w + pos] for i in range(self.h)]
@property
def cols(self):
return [self.col(i) for i in range(self.w)]
@staticmethod
def _isnumeric(i):
return isinstance(i, float) or isinstance(i, int)
def _add(self, r, p, q, *args):
r = len(args) if r <= 0 else r
for i in range(r):
try:
if self._isnumeric(args[i]):
self.vals.insert(i*(p + 1) + self.w*q, args[i])
except IndexError:
self.vals.insert(i*(p + 1) + self.w*q, 0)
return r
def addrow(self, *args):
self.w = self._add(self.w, 0, self.h, *args)
self.h += 1
def addcol(self, *args):
self.h = self._add(self.h, self.w, 1, *args)
self.w += 1
def _fill(self, val, pos, r, lt, p, q, addfunc):
if self._isnumeric(val):
if pos < lt:
for i in range(self.w):
self.vals[pos*p + i*q] = val
else:
addfunc(*[val for _ in range(r)])
def rowfill(self, val, pos):
self._fill(val, pos, self.w, self.h, self.w, 1, self.addrow)
def colfill(self, val, pos):
self._fill(val, pos, self.h, self.w, 1, self.w, self.addcol)
def removerow(self, pos):
if self.h > 0 and pos < self.h:
for _ in range(self.w):
self.vals.pop(self.w*pos)
self.h -= 1
if self.h == 0:
self.w = 0
def removecol(self, pos):
if self.w > 0 and pos < self.w:
pos %= self.w
for i in range(self.h):
self.vals.pop(i*(self.w-1) + pos)
self.w -= 1
if self.w == 0:
self.h = 0
def __add__(self, other):
new_m = Matrix()
def __mul__(self, other):
new_m = Matrix()
for col in other.cols:
s = [sum([self.at(l, i)*c for i, c in enumerate(col)]) for l in range(self.h)]
print(s)
#new_m.addcol()
return new_m
@property
def det(self):
if self.w * self.h == 1:
return self.vals[0]
if (self.w, self.h) == (2,2):
return self.at(0, 0)*self.at(1, 1) - self.at(0, 1)*self.at(1, 0)
d = 0
for i in range(self.h):
for j in range(self.w):
b = [[y for y in (x[:j] + x[j+1:])] for x in self.cols[:i] + self.cols[i+1:]]
d += det(val) if (i+j)%2 == 0 else -det(val)
return d
def __len__(self):
return self.w * self.h
def __repr__(self):
if (self.w, self.h) == (0, 0):
return "()"
res = ""
for i, val in enumerate(self.vals):
end = "\n" if (i+1)%self.w == 0 else "\t"
res += f"{val}{end}"
return res
def __str__(self):
return self.__repr__() | class Matrix:
def __init__(self, *args, **kwargs):
if len(args) > 0:
if isinstance(args[0], Matrix):
m = args[0].copy()
else:
m = {'vals': [], 'w': 0, 'h': 0}
self.vals = m.vals
self.w = m.w
self.h = m.h
def copy(self):
new_m = matrix()
for i in self.vals:
new_m.vals.append(i)
new_m.w = self.w
new_m.h = self.h
return new_m
@property
def width(self):
return self.w
@property
def height(self):
return self.h
def value_at(self, row, col):
return self.vals[row * self.w + col]
def at(self, row, col):
return self.value_at(row, col)
def row(self, pos):
return [self.vals[pos * self.w + i] for i in range(self.w)]
@property
def rows(self):
return [self.row(i) for i in range(self.h)]
def col(self, pos):
return [self.vals[i * self.w + pos] for i in range(self.h)]
@property
def cols(self):
return [self.col(i) for i in range(self.w)]
@staticmethod
def _isnumeric(i):
return isinstance(i, float) or isinstance(i, int)
def _add(self, r, p, q, *args):
r = len(args) if r <= 0 else r
for i in range(r):
try:
if self._isnumeric(args[i]):
self.vals.insert(i * (p + 1) + self.w * q, args[i])
except IndexError:
self.vals.insert(i * (p + 1) + self.w * q, 0)
return r
def addrow(self, *args):
self.w = self._add(self.w, 0, self.h, *args)
self.h += 1
def addcol(self, *args):
self.h = self._add(self.h, self.w, 1, *args)
self.w += 1
def _fill(self, val, pos, r, lt, p, q, addfunc):
if self._isnumeric(val):
if pos < lt:
for i in range(self.w):
self.vals[pos * p + i * q] = val
else:
addfunc(*[val for _ in range(r)])
def rowfill(self, val, pos):
self._fill(val, pos, self.w, self.h, self.w, 1, self.addrow)
def colfill(self, val, pos):
self._fill(val, pos, self.h, self.w, 1, self.w, self.addcol)
def removerow(self, pos):
if self.h > 0 and pos < self.h:
for _ in range(self.w):
self.vals.pop(self.w * pos)
self.h -= 1
if self.h == 0:
self.w = 0
def removecol(self, pos):
if self.w > 0 and pos < self.w:
pos %= self.w
for i in range(self.h):
self.vals.pop(i * (self.w - 1) + pos)
self.w -= 1
if self.w == 0:
self.h = 0
def __add__(self, other):
new_m = matrix()
def __mul__(self, other):
new_m = matrix()
for col in other.cols:
s = [sum([self.at(l, i) * c for (i, c) in enumerate(col)]) for l in range(self.h)]
print(s)
return new_m
@property
def det(self):
if self.w * self.h == 1:
return self.vals[0]
if (self.w, self.h) == (2, 2):
return self.at(0, 0) * self.at(1, 1) - self.at(0, 1) * self.at(1, 0)
d = 0
for i in range(self.h):
for j in range(self.w):
b = [[y for y in x[:j] + x[j + 1:]] for x in self.cols[:i] + self.cols[i + 1:]]
d += det(val) if (i + j) % 2 == 0 else -det(val)
return d
def __len__(self):
return self.w * self.h
def __repr__(self):
if (self.w, self.h) == (0, 0):
return '()'
res = ''
for (i, val) in enumerate(self.vals):
end = '\n' if (i + 1) % self.w == 0 else '\t'
res += f'{val}{end}'
return res
def __str__(self):
return self.__repr__() |
#
# @lc app=leetcode id=67 lang=python3
#
# [67] Add Binary
#
# @lc code=start
class Solution:
def addBinary(self, a: str, b: str) -> str:
m = len(a)
n = len(b)
i = m - 1
j = n - 1
extra = 0
res = ''
while i >=0 or j >= 0:
if i < 0:
x = int(b[j]) + extra
elif j < 0:
x = int(a[i]) + extra
else:
x = int(a[i]) + int(b[j]) + extra
extra = x // 2
res = str(x%2) + res
i -= 1
j -= 1
if extra:
return str(extra) + res
else:
return res
tests = [
('11', '1', '100'),
('1010', '1011', '10101')
]
# @lc code=end
| class Solution:
def add_binary(self, a: str, b: str) -> str:
m = len(a)
n = len(b)
i = m - 1
j = n - 1
extra = 0
res = ''
while i >= 0 or j >= 0:
if i < 0:
x = int(b[j]) + extra
elif j < 0:
x = int(a[i]) + extra
else:
x = int(a[i]) + int(b[j]) + extra
extra = x // 2
res = str(x % 2) + res
i -= 1
j -= 1
if extra:
return str(extra) + res
else:
return res
tests = [('11', '1', '100'), ('1010', '1011', '10101')] |
def test():
# if an assertion fails, the message will be displayed
# --> must have the output in a comment
assert "Mean: 5.0" in __solution__, "Did you record the correct program output as a comment?"
# --> must have the output in a comment
assert "Mean: 4.0" in __solution__, "Did you record the correct program output as a comment?"
# --> must have the first function call
assert "mean(numbers_one)" in __solution__, "Did you call the mean function with numbers_one as input?"
# --> must have the second function call
assert "mean(numbers_two)" in __solution__, "Did you call the mean function with numbers_two as input?"
# --> must not have a TODO marker in the solution
assert "TODO" not in __solution__, "Did you remove the TODO marker when finished?"
# display a congratulations for a correct solution
__msg__.good("Well done!")
| def test():
assert 'Mean: 5.0' in __solution__, 'Did you record the correct program output as a comment?'
assert 'Mean: 4.0' in __solution__, 'Did you record the correct program output as a comment?'
assert 'mean(numbers_one)' in __solution__, 'Did you call the mean function with numbers_one as input?'
assert 'mean(numbers_two)' in __solution__, 'Did you call the mean function with numbers_two as input?'
assert 'TODO' not in __solution__, 'Did you remove the TODO marker when finished?'
__msg__.good('Well done!') |
# 17. Distinct strings in the first column
# Find distinct strings (a set of strings) of the first column of the file. Confirm the result by using cut, sort, and uniq commands.
def removeDuplicates(list):
newList = []
for i in list:
if not(i in newList):
newList.append(i)
return newList
with open('popular-names.txt') as f:
firstColumn = []
lines = f.readlines()
for i in lines:
lineArray = i.split('\t')
firstColumn.append(lineArray[0])
size = len(removeDuplicates(firstColumn))
print(f'There are {size} set of strings')
f.close | def remove_duplicates(list):
new_list = []
for i in list:
if not i in newList:
newList.append(i)
return newList
with open('popular-names.txt') as f:
first_column = []
lines = f.readlines()
for i in lines:
line_array = i.split('\t')
firstColumn.append(lineArray[0])
size = len(remove_duplicates(firstColumn))
print(f'There are {size} set of strings')
f.close |
name = input("Enter your name: ")
date = input("Enter a date: ")
adjective = input("Enter an adjective: ")
noun = input("Enter a noun: ")
verb = input("Enter a verb in past tense: ")
adverb = input("Enter an adverb: ")
adjective = input("Enter another adjective: ")
noun = input("Enter another noun: ")
noun = input("Enter another noun: ")
adjective = input("Enter another adjective: ")
verb = input("Enter a verb: ")
adverb = input("Enter another adverb: ")
verb = input("Enter another verb in past tense: ")
adjective = input("Enter another adjective: ")
print("Name: " + name + " Date: " + date )
print("Today I went to the zoo. I saw a " + adjective + " " + noun + " jumping up and down in its tree.")
print("He " + verb + " " + adverb + " through the large tunnel that led to its " + adjective + " " + noun + ".")
print("I got some peanuts and passed them through the cage to a gigantic gray " + noun + " towering above my head.")
print("Feeding the animals made me hungry. I went to get a " + adjective + " scoop of ice cream. It filled my stomach.")
print("Afterwards I had to " + verb + " " + adverb + " to catch our bus.")
print("When I got home I " + verb + " my mom for a " + adjective + " day at the zoo.")
| name = input('Enter your name: ')
date = input('Enter a date: ')
adjective = input('Enter an adjective: ')
noun = input('Enter a noun: ')
verb = input('Enter a verb in past tense: ')
adverb = input('Enter an adverb: ')
adjective = input('Enter another adjective: ')
noun = input('Enter another noun: ')
noun = input('Enter another noun: ')
adjective = input('Enter another adjective: ')
verb = input('Enter a verb: ')
adverb = input('Enter another adverb: ')
verb = input('Enter another verb in past tense: ')
adjective = input('Enter another adjective: ')
print('Name: ' + name + ' Date: ' + date)
print('Today I went to the zoo. I saw a ' + adjective + ' ' + noun + ' jumping up and down in its tree.')
print('He ' + verb + ' ' + adverb + ' through the large tunnel that led to its ' + adjective + ' ' + noun + '.')
print('I got some peanuts and passed them through the cage to a gigantic gray ' + noun + ' towering above my head.')
print('Feeding the animals made me hungry. I went to get a ' + adjective + ' scoop of ice cream. It filled my stomach.')
print('Afterwards I had to ' + verb + ' ' + adverb + ' to catch our bus.')
print('When I got home I ' + verb + ' my mom for a ' + adjective + ' day at the zoo.') |
input=__import__('sys').stdin.readline
n,m=map(int,input().split());g=[list(input()) for _ in range(n)];c=[[0]*m for _ in range(n)]
q=__import__('collections').deque();q.append((0,0));c[0][0]=1
while q:
x,y=q.popleft()
for nx,ny in (x+1,y),(x-1,y),(x,y+1),(x,y-1):
if 0<=nx<n and 0<=ny<m and g[nx][ny]=='1' and c[nx][ny]==0:
c[nx][ny]=c[x][y]+1
q.append((nx,ny))
print(c[n-1][m-1])
| input = __import__('sys').stdin.readline
(n, m) = map(int, input().split())
g = [list(input()) for _ in range(n)]
c = [[0] * m for _ in range(n)]
q = __import__('collections').deque()
q.append((0, 0))
c[0][0] = 1
while q:
(x, y) = q.popleft()
for (nx, ny) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
if 0 <= nx < n and 0 <= ny < m and (g[nx][ny] == '1') and (c[nx][ny] == 0):
c[nx][ny] = c[x][y] + 1
q.append((nx, ny))
print(c[n - 1][m - 1]) |
# normalize data 0-1
def normalize(data):
normalized = []
for i in range(len(data[0])):
col_min = min([item[i] for item in data])
col_max = max([item[i] for item in data])
for q, item in enumerate([item[i] for item in data]):
if len(normalized) > q:
normalized[q].append((item - col_min) / (col_max - col_min))
else:
normalized.append([])
normalized[q].append((item - col_min) / (col_max - col_min))
return normalized
| def normalize(data):
normalized = []
for i in range(len(data[0])):
col_min = min([item[i] for item in data])
col_max = max([item[i] for item in data])
for (q, item) in enumerate([item[i] for item in data]):
if len(normalized) > q:
normalized[q].append((item - col_min) / (col_max - col_min))
else:
normalized.append([])
normalized[q].append((item - col_min) / (col_max - col_min))
return normalized |
'''
You are given a linked list with one pointer of each node pointing to the next node just like the usual.
Every node, however, also has a second pointer that can point to any node in the list.
Now write a program to deep copy this list.
Solution 1:
First backup all the nodes' next pointers node to another array.
next_backup = [node1, node2, node3 ... None]
Meaning next_backup[0] = node[0].next = node1.
Note that these are just references.
Now just deep-copy the original linked list, only considering the next pointers.
While copying (or after it), point
`original_0.next = copy_0`
and
`copy_0.random = original_0`
Now, while traversing the copy list, set the random pointers of copies correctly:
copy.random = copy.random.random.next
Now, traverse the original list and fix back the next pointers using the next_backup array.
Total complexity -> O(n+n+n) = O(n)
Space complexity = O(n)
SOLUTION 2:
We can also do it in space complexity O(1).
This is actually easier to understand. ;)
For every node original_i, make a copy of it just in front of it.
For example, if original_0.next = original_1, then now it will become
`original_0.next = copy_0`
`copy_0.next = original_1`
Now, set the random pointers of copies:
`copy_i.random = original_i.random.next`
We can do this because we know that the copy of a node is just after the original.
Now, fix the next pointers of all the nodes:
original_i.next = original_i.next.next
copy_i.next = copy_i.next.next
Time complexity = O(n)
Space complexity = O(1)
'''
| """
You are given a linked list with one pointer of each node pointing to the next node just like the usual.
Every node, however, also has a second pointer that can point to any node in the list.
Now write a program to deep copy this list.
Solution 1:
First backup all the nodes' next pointers node to another array.
next_backup = [node1, node2, node3 ... None]
Meaning next_backup[0] = node[0].next = node1.
Note that these are just references.
Now just deep-copy the original linked list, only considering the next pointers.
While copying (or after it), point
`original_0.next = copy_0`
and
`copy_0.random = original_0`
Now, while traversing the copy list, set the random pointers of copies correctly:
copy.random = copy.random.random.next
Now, traverse the original list and fix back the next pointers using the next_backup array.
Total complexity -> O(n+n+n) = O(n)
Space complexity = O(n)
SOLUTION 2:
We can also do it in space complexity O(1).
This is actually easier to understand. ;)
For every node original_i, make a copy of it just in front of it.
For example, if original_0.next = original_1, then now it will become
`original_0.next = copy_0`
`copy_0.next = original_1`
Now, set the random pointers of copies:
`copy_i.random = original_i.random.next`
We can do this because we know that the copy of a node is just after the original.
Now, fix the next pointers of all the nodes:
original_i.next = original_i.next.next
copy_i.next = copy_i.next.next
Time complexity = O(n)
Space complexity = O(1)
""" |
'''
Kattis - lineup
Compare list with the sorted version of the list.
Time: O(n log n), Space: O(n)
'''
n = int(input())
arr = [input() for _ in range(n)]
if arr == sorted(arr):
print("INCREASING")
elif arr == sorted(arr, reverse=True):
print("DECREASING")
else:
print("NEITHER") | """
Kattis - lineup
Compare list with the sorted version of the list.
Time: O(n log n), Space: O(n)
"""
n = int(input())
arr = [input() for _ in range(n)]
if arr == sorted(arr):
print('INCREASING')
elif arr == sorted(arr, reverse=True):
print('DECREASING')
else:
print('NEITHER') |
#program to find the single element appears once in a list where every element
# appears four times except for one.
class Solution_once:
def singleNumber(self, arr):
ones, twos = 0, 0
for x in arr:
ones, twos = (ones ^ x) & ~twos, (ones & x) | (twos & ~x)
assert twos == 0
return ones
class Solution_twice:
def single_number(arr):
ones, twos, threes = 0, 0, 0
for x in arr:
ones, twos, threes = (~x & ones) | (x & ~ones & ~twos & ~threes), (~x & twos) | (x & ones), (~x & threes) | (x & twos)
return twos
if __name__ == "__main__":
print(Solution_once().singleNumber([1, 1, 1, 2, 2, 2, 3]))
print(Solution_once().singleNumber([5, 3, 0, 3, 5, 5, 3]))
| class Solution_Once:
def single_number(self, arr):
(ones, twos) = (0, 0)
for x in arr:
(ones, twos) = ((ones ^ x) & ~twos, ones & x | twos & ~x)
assert twos == 0
return ones
class Solution_Twice:
def single_number(arr):
(ones, twos, threes) = (0, 0, 0)
for x in arr:
(ones, twos, threes) = (~x & ones | x & ~ones & ~twos & ~threes, ~x & twos | x & ones, ~x & threes | x & twos)
return twos
if __name__ == '__main__':
print(solution_once().singleNumber([1, 1, 1, 2, 2, 2, 3]))
print(solution_once().singleNumber([5, 3, 0, 3, 5, 5, 3])) |
class Bank:
def __init__(self,owner,balance):
self.owner=owner
self.balance=balance
def deposit(self,d):
self.balance=d+self.balance
print("amount : {}".format(d))
print("deposit accepted!!")
return self.balance
def withdraw(self,w):
if w>self.balance:
print("amount has exceeded the limit!!")
print('balance : {}'.format(self.balance))
else:
self.balance= self.balance-w
print("amount withdrawn : {}".format(w))
print("withdrawal completed!!")
return self.balance
def __str__(self):
return (f"Account owner : {self.owner} \nAccount balance : {self.balance}")
| class Bank:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, d):
self.balance = d + self.balance
print('amount : {}'.format(d))
print('deposit accepted!!')
return self.balance
def withdraw(self, w):
if w > self.balance:
print('amount has exceeded the limit!!')
print('balance : {}'.format(self.balance))
else:
self.balance = self.balance - w
print('amount withdrawn : {}'.format(w))
print('withdrawal completed!!')
return self.balance
def __str__(self):
return f'Account owner : {self.owner} \nAccount balance : {self.balance}' |
#
# @lc app=leetcode id=206 lang=python3
#
# [206] Reverse Linked List
#
# https://leetcode.com/problems/reverse-linked-list/description/
#
# algorithms
# Easy (65.21%)
# Likes: 6441
# Dislikes: 123
# Total Accepted: 1.3M
# Total Submissions: 2M
# Testcase Example: '[1,2,3,4,5]'
#
# Given the head of a singly linked list, reverse the list, and return the
# reversed list.
#
#
# Example 1:
#
#
# Input: head = [1,2,3,4,5]
# Output: [5,4,3,2,1]
#
#
# Example 2:
#
#
# Input: head = [1,2]
# Output: [2,1]
#
#
# Example 3:
#
#
# Input: head = []
# Output: []
#
#
#
# Constraints:
#
#
# The number of nodes in the list is the range [0, 5000].
# -5000 <= Node.val <= 5000
#
#
#
# Follow up: A linked list can be reversed either iteratively or recursively.
# Could you implement both?
#
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# class Solution:
# def reverseList(self, head: ListNode) -> ListNode:
# rever_tail = ListNode()
# curr = rever_tail
# while head != None:
# curr.val = head.val
# new_node = ListNode()
# new_node.next = curr
# curr = new_node
# head = head.next
# return curr.next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
# @lc code=end
| class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev |
# Bubble Sort
#
# Time Complexity: O(n*log(n))
# Space Complexity: O(1)
class Solution:
def bubbleSort(self, array: [int]) -> [int]:
dirty = False
for i in range(len(array)):
for j in range(0, len(array) - 1 - i):
if array[j] > array[j + 1]:
dirty = True
array[j], array[j + 1] = array[j + 1], array[j]
if not dirty:
break
dirty = False
return array | class Solution:
def bubble_sort(self, array: [int]) -> [int]:
dirty = False
for i in range(len(array)):
for j in range(0, len(array) - 1 - i):
if array[j] > array[j + 1]:
dirty = True
(array[j], array[j + 1]) = (array[j + 1], array[j])
if not dirty:
break
dirty = False
return array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.