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 n... | 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 ... |
# 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 widt... | 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
# b... | 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", "FrankiExcept... | 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 yo... | 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... |
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]]
st... | 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... |
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))
... | 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))
d... |
expected_output = {
'slot':{
2:{
'port_group':{
1:{
'port':{
'Hu2/0/25':{
'mode':'inactive'
},
'Hu2/0/26':{
'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': {... |
#!/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()... | 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]))
... |
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'],
... | 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... | 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, on... |
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 + " " ... | 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 + ' ... |
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.readl... | 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()... |
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 thi... | 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_... |
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 fina... | 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... |
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(... | 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))... |
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
... | 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_it... |
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_conflic... | 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
... |
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]
... | 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]
... |
# 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... | 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 = 'Ori... |
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"
e... | 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:
... |
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
d... | 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 = te... |
# 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 = 'fe65757e00193b8bc2e18444fa51d87... | 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 = 'noreply@yoursite.com'
user_register_email_subject = 'Thank you fo... |
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, 0... | 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,... |
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_NAMESPA... | 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, TA... |
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) a... | 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... |
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"
],
"librarie... | {'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', '-fram... |
# 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... | 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(d... | 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_UR... | 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_una... |
# 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 blo... | 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
sel... |
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 JsonL... | 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... |
# 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, 12... | 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 = (2... |
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... | 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... |
# 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)
# PROBL... | 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"))
p... | 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,... | 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... |
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 a... | 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?')
s... |
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(cha... | 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(answe... |
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()
acco... | 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.... |
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 d... | 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 = 'H... |
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... | 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
de... |
#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(prim... | 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 = num... |
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 c... | 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:... |
# 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_relea... | __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': '0... |
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 {
... | 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... |
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')
re... | 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')
... |
'''
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)... | """
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... |
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_int... | 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.... |
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 num... | 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 Fal... |
# 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... | 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)... |
#!/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... | 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='ta... |
# 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;gen... | 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/te... |
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... | 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... |
#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
# | | | | | |
# --... | 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,
conditi... | 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):
""" Constr... |
## 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)... | 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_ht... |
#%% 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-... | """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 + ' ... |
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())
i... | 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.rever... |
# --------------------------------------------------------------------------------------------
# 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 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... | 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):
ne... |
#
# @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:
... | 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])... |
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 cor... | 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?'
... |
# 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... | 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... |
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("Ent... | 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('Ent... |
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]=='... | 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)):
... |
# 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:
normal... | 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 - ... |
'''
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.
n... | """
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.
n... |
'''
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
... | 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)
... |
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):
... | 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 ... |
#
# @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 li... | 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]:
di... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.