content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort() #first sort two nums
nums2.sort()
l1, l2 = 0, 0 #use two pointers
N1, N2 = len(nums1), len(nums2)
re... | class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
(l1, l2) = (0, 0)
(n1, n2) = (len(nums1), len(nums2))
res = []
while l1 != N1 ... |
class MyObj():
"""docstring for MyObj"""
def __init__(self, name, age):
super(MyObj, self).__init__()
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
o1 = MyObj("Been", 32)
o2 ... | class Myobj:
"""docstring for MyObj"""
def __init__(self, name, age):
super(MyObj, self).__init__()
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
o1 = my_obj('Been', 32)
o2 = m... |
__all__ = [
'sigmoid',
'sigmoid_grad',
'cross_entropy',
'gini_impurity',
'make_linearly_separable_data',
'predict_by_mode',
]
| __all__ = ['sigmoid', 'sigmoid_grad', 'cross_entropy', 'gini_impurity', 'make_linearly_separable_data', 'predict_by_mode'] |
"""
Pagination: select how many results to display.
"""
# Maybe refactor later the same way as variant_filter,
# but maybe not necessary as long as they are so simple.
def pagination_from_request(request):
lim = request.args.get('limit')
off = request.args.get('offset', '0')
assert off.isdigit(), "Argument... | """
Pagination: select how many results to display.
"""
def pagination_from_request(request):
lim = request.args.get('limit')
off = request.args.get('offset', '0')
assert off.isdigit(), "Argument to 'offset' must be an integer"
off = int(off)
if lim is not None:
assert lim.isdigit(), "Argum... |
numbers=[]
f=open("./2020/data/09a.txt","r")
# f=open("./2020/data/test.txt","r")
# tofind=127
tofind=133015568
# preamble=5
preamble=25
for line in f:
numbers.append(int(line))
if len(numbers)>preamble:
for i in range(len(numbers)-1):
count=0
smallest=-1
largest=-1
... | numbers = []
f = open('./2020/data/09a.txt', 'r')
tofind = 133015568
preamble = 25
for line in f:
numbers.append(int(line))
if len(numbers) > preamble:
for i in range(len(numbers) - 1):
count = 0
smallest = -1
largest = -1
for j in range(i, len(numbers)):
... |
class FFT:
def __init__(self,filename):
self._base_pattern = [0,1,0,-1]
self._repeating_groups = {}
with open(filename,"r") as file_in:
self.fft_input = file_in.readline().strip('\n')
def run(self, phases):
elements = self.fft_input
for p in range(0,phases):
... | class Fft:
def __init__(self, filename):
self._base_pattern = [0, 1, 0, -1]
self._repeating_groups = {}
with open(filename, 'r') as file_in:
self.fft_input = file_in.readline().strip('\n')
def run(self, phases):
elements = self.fft_input
for p in range(0, ph... |
# JJ Small
# manga_model.py
# This class is a representation of what a manga series has/does
class Manga:
def __init__(self, title: str, volume_count: int) -> None:
self.local_title = title
self.site_title = None
self.site_id = None
self.my_volumes = volume_count
self.is_lic... | class Manga:
def __init__(self, title: str, volume_count: int) -> None:
self.local_title = title
self.site_title = None
self.site_id = None
self.my_volumes = volume_count
self.is_licensed: bool = False
self.eng_volumes = None
self.eng_status = None
se... |
# -*- coding: utf-8 -*-
class Playlist(object):
def __init__(self, library, id, name):
self._library = library
self._id = id
self._name = name
self._tracks = []
self._position = 0
@property
def name(self):
return self._name
@property
def tracks(se... | class Playlist(object):
def __init__(self, library, id, name):
self._library = library
self._id = id
self._name = name
self._tracks = []
self._position = 0
@property
def name(self):
return self._name
@property
def tracks(self):
return self._... |
# Program is to make ring shift or recycle items of list.
def ring_shift(first,next):
if next < 0:
next = abs(next)
for i in range(next):
first.append(first.pop(0))
else:
for i in range(next):
first.insert(0,first.pop())
values = [9, ... | def ring_shift(first, next):
if next < 0:
next = abs(next)
for i in range(next):
first.append(first.pop(0))
else:
for i in range(next):
first.insert(0, first.pop())
values = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(values)
ring_shift(values, -2)
print(valu... |
class RevitLinkLoadResult(object,IDisposable):
"""
This class stores the results of trying to load a single linked model.
RevitLinkLoadResult(other: RevitLinkLoadResult)
"""
def Dispose(self):
""" Dispose(self: RevitLinkLoadResult) """
pass
def GetCentralModelName(self):
"""
GetCentralModel... | class Revitlinkloadresult(object, IDisposable):
"""
This class stores the results of trying to load a single linked model.
RevitLinkLoadResult(other: RevitLinkLoadResult)
"""
def dispose(self):
""" Dispose(self: RevitLinkLoadResult) """
pass
def get_central_model_name(self):
... |
def is_equal(data):
data_to_compare_with = _ttp_["output_object"].attributes['load']
is_equal = False
if "_anonymous_" in data:
if data["_anonymous_"] == data_to_compare_with:
is_equal = True
elif data == data_to_compare_with:
is_equal = True
return {
... | def is_equal(data):
data_to_compare_with = _ttp_['output_object'].attributes['load']
is_equal = False
if '_anonymous_' in data:
if data['_anonymous_'] == data_to_compare_with:
is_equal = True
elif data == data_to_compare_with:
is_equal = True
return {'output_name': _ttp_[... |
def part1(inputMap):
rows = len(inputMap)
cols = len(inputMap[0])
rowIdx = 0
colIdx = 0
trees = 0
while rowIdx < rows - 1:
rowIdx += 1
colIdx += 3
# We went past the end of the column
if colIdx >= cols:
colIdx = colIdx - cols
row = inputMap[rowIdx]
spot = row[colIdx]
if... | def part1(inputMap):
rows = len(inputMap)
cols = len(inputMap[0])
row_idx = 0
col_idx = 0
trees = 0
while rowIdx < rows - 1:
row_idx += 1
col_idx += 3
if colIdx >= cols:
col_idx = colIdx - cols
row = inputMap[rowIdx]
spot = row[colIdx]
... |
class Job:
name = None
current_work_id = 0
farmer_public_key = None
pool_public_key = None
total_running = 0
total_completed = 0
max_concurrent = 0
max_concurrent_with_start_early = 0
max_plots = 0
temporary2_destination_sync = None
stagger_minutes = None
max_for_phase... | class Job:
name = None
current_work_id = 0
farmer_public_key = None
pool_public_key = None
total_running = 0
total_completed = 0
max_concurrent = 0
max_concurrent_with_start_early = 0
max_plots = 0
temporary2_destination_sync = None
stagger_minutes = None
max_for_phase_1 ... |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = "ID INTEGER FLOAT STRING CHAR WS COMMENT1 COMMENT2 POUND DPOUND SYNC VOID FOR GLOBAL TYPE QUALIFIER ELSE IF SHAREDfunction : signature '{' shared_buffer statements '}'signature : GLOBAL VOID ID... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = "ID INTEGER FLOAT STRING CHAR WS COMMENT1 COMMENT2 POUND DPOUND SYNC VOID FOR GLOBAL TYPE QUALIFIER ELSE IF SHAREDfunction : signature '{' shared_buffer statements '}'signature : GLOBAL VOID ID '(' parameters ')'parameters : parameter\n | paramet... |
def power(x,y):
res=1
while(y>0):
if((y&1)==1):
res=res*x
y=y>>1
x=x*x
return res
x=5
y=3
print(power(5,3))
| def power(x, y):
res = 1
while y > 0:
if y & 1 == 1:
res = res * x
y = y >> 1
x = x * x
return res
x = 5
y = 3
print(power(5, 3)) |
# Time Complexity : O(n) ... O(1) * n
def triangle_number(n):
if n == 1:
return 1
return n + triangle_number(n - 1)
for i in range(1, 11):
print(triangle_number(i)) | def triangle_number(n):
if n == 1:
return 1
return n + triangle_number(n - 1)
for i in range(1, 11):
print(triangle_number(i)) |
"""
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output:... | """
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output:... |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
break
if i == 0 or nums[i - 1] != nums[i]:
self.twoSumII(nums, i, res)
return res
def t... | class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
break
if i == 0 or nums[i - 1] != nums[i]:
self.twoSumII(nums, i, res)
return res
def... |
"""
Module viginere.py
"""
class Viginere:
"""
Class for text encryption and decryption
with viginere Cipher.
"""
__author__ = "Temuri Takalandze <me@abgeo.dev>"
__copyright__ = "Copyright 2019, abgeo.dev"
__license__ = "MIT"
__version__ = "0.9"
__maintainer__ = "Temrui Takalandze... | """
Module viginere.py
"""
class Viginere:
"""
Class for text encryption and decryption
with viginere Cipher.
"""
__author__ = 'Temuri Takalandze <me@abgeo.dev>'
__copyright__ = 'Copyright 2019, abgeo.dev'
__license__ = 'MIT'
__version__ = '0.9'
__maintainer__ = 'Temrui Takalandze'
... |
n=int(input())
synonymsDict={}
for k in range(0,n):
wordFound=False
word=input(); synon=input()
for j in synonymsDict:
if j==word:
synonymsDict[j]+=f", {synon}"
wordFound=True
if wordFound==False:
synonymsDict[word]=synon
output=""
for k in synonymsDic... | n = int(input())
synonyms_dict = {}
for k in range(0, n):
word_found = False
word = input()
synon = input()
for j in synonymsDict:
if j == word:
synonymsDict[j] += f', {synon}'
word_found = True
if wordFound == False:
synonymsDict[word] = synon
output = ''
for... |
#!/usr/bin/python3
with open('09_input', 'r') as f:
lines = f.readlines()
nums = [int(l.strip()) for l in lines]
preamble_size = 25
sum_cache = dict()
table = []
for i in range(preamble_size):
row = []
front = nums[i]
for j in range(i+1, preamble_size):
val = front + nums[j]
sum_cac... | with open('09_input', 'r') as f:
lines = f.readlines()
nums = [int(l.strip()) for l in lines]
preamble_size = 25
sum_cache = dict()
table = []
for i in range(preamble_size):
row = []
front = nums[i]
for j in range(i + 1, preamble_size):
val = front + nums[j]
sum_cache[val] = sum_cache.ge... |
def hashtags(string, hash=True):
hashtags = []
for word in string.replace('\n', '').split():
if word.startswith("#") and word != "#":
if hash:
hashtag = word
else:
hashtag = word.replace("#", "")
hashtags.append(hashtag)
return hash... | def hashtags(string, hash=True):
hashtags = []
for word in string.replace('\n', '').split():
if word.startswith('#') and word != '#':
if hash:
hashtag = word
else:
hashtag = word.replace('#', '')
hashtags.append(hashtag)
return hash... |
def fact(n):
if (n == 1):
return n;
else:
return n*fact(n-1);
test = int(input())
for i in range (0,test):
val = int(input())
print(fact(val))
##Example Test Case
# Sample input:
# 4
# 1
# 2
# 5
# 3
# Sample output:
#
# 1
# 2
# 120
# 6
| def fact(n):
if n == 1:
return n
else:
return n * fact(n - 1)
test = int(input())
for i in range(0, test):
val = int(input())
print(fact(val)) |
'''
GEOMETRIC PROGRESSION
Any sequence of elements where the quotient between any two
consecutive elements is equal is termed to be in G.P.
The nth term of an G.P. is defined as (a * r^(n-1))
where a is the first element of the G.P.
r is the common ratio of the G.P.
'''... | """
GEOMETRIC PROGRESSION
Any sequence of elements where the quotient between any two
consecutive elements is equal is termed to be in G.P.
The nth term of an G.P. is defined as (a * r^(n-1))
where a is the first element of the G.P.
r is the common ratio of the G.P.
"""... |
N = int(input())
ans = []
for i in range(N-1, 0, -1):
d = [int(d) for d in str(i)]
if N == i + sum(d):
ans.append(i)
if len(ans) > 0:
print(min(ans))
else:
print(0)
| n = int(input())
ans = []
for i in range(N - 1, 0, -1):
d = [int(d) for d in str(i)]
if N == i + sum(d):
ans.append(i)
if len(ans) > 0:
print(min(ans))
else:
print(0) |
n = int(input("Your number is: "))
sum = 0
for x in range(1, n + 1):
sum += x
print(sum) | n = int(input('Your number is: '))
sum = 0
for x in range(1, n + 1):
sum += x
print(sum) |
"""
This file contains the default config data for the reports system
On start-up thirtybirds loads config data. It loads default configs from config/ unless otherwise specified. New config data can be loaded dynamically at runtime.
Typical usage example:
from config import reports
foo = ClassFoo(reports.foo_conf... | """
This file contains the default config data for the reports system
On start-up thirtybirds loads config data. It loads default configs from config/ unless otherwise specified. New config data can be loaded dynamically at runtime.
Typical usage example:
from config import reports
foo = ClassFoo(reports.foo_conf... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... | """
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
class MyIgnorableClass :
def getServiceValue(self, argument) :
return f'ignorable service value: {argument}'
class MyOtherIgnorableClass :
def getServiceValue(self, argument) :
return f'other ignorable service value: {argument}'
| class Myignorableclass:
def get_service_value(self, argument):
return f'ignorable service value: {argument}'
class Myotherignorableclass:
def get_service_value(self, argument):
return f'other ignorable service value: {argument}' |
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
memo = collections.defaultdict(list)
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
memo[nums[i] + nums[j]].append((i, j))
ans = set()
for i in range(n)... | class Solution:
def four_sum(self, nums: List[int], target: int) -> List[List[int]]:
memo = collections.defaultdict(list)
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
memo[nums[i] + nums[j]].append((i, j))
ans = set()
for i in range(... |
class CapsuleNetwork(tf.keras.Model):
def __init__(self, no_of_conv_kernels, no_of_primary_capsules, primary_capsule_vector, no_of_secondary_capsules, secondary_capsule_vector, r):
super(CapsuleNetwork, self).__init__()
self.no_of_conv_kernels = no_of_conv_kernels
self.no_of_primary_caps... | class Capsulenetwork(tf.keras.Model):
def __init__(self, no_of_conv_kernels, no_of_primary_capsules, primary_capsule_vector, no_of_secondary_capsules, secondary_capsule_vector, r):
super(CapsuleNetwork, self).__init__()
self.no_of_conv_kernels = no_of_conv_kernels
self.no_of_primary_capsule... |
#day 1
# register = []
# with open('day5.txt', mode='r') as f:
# for l in f.readlines():
# register.append(int(l.strip()))
# step_count = 0
# index =0
# while index>=0 and index <len(register):
# step_count+=1
# old_index = index
# index += register[index]
# register[old_index]+=1
# print(... | register = []
with open('day5.txt', mode='r') as f:
for l in f.readlines():
register.append(int(l.strip()))
step_count = 0
index = 0
while index >= 0 and index < len(register):
step_count += 1
old_index = index
offset = register[index]
index += register[index]
if offset >= 3:
reg... |
class Participant(object):
def __init__(self, id, name, balance, volume):
self.__id = id
self.__name = str(name)
if balance < 0 or volume < 0:
raise ValueError()
self.__balance = float(balance)
self.__volume = int(volume)
@property
def id(self):
... | class Participant(object):
def __init__(self, id, name, balance, volume):
self.__id = id
self.__name = str(name)
if balance < 0 or volume < 0:
raise value_error()
self.__balance = float(balance)
self.__volume = int(volume)
@property
def id(self):
... |
class BusException(Exception):
'''
Class to represent an Exception
'''
def __init__(self):
pass | class Busexception(Exception):
"""
Class to represent an Exception
"""
def __init__(self):
pass |
def authentication(unamePasswordForVerification):
# unamePasswordForVerification = ["rabindra", "rabindra23"]
if ( getAuthenticatedUsersList() != -1 ):
verifiedUsersList = getAuthenticatedUsersList()
for verifiedUsers in verifiedUsersList:
if (verifiedUsers == unamePasswordForVerification):
message = "AUTH... | def authentication(unamePasswordForVerification):
if get_authenticated_users_list() != -1:
verified_users_list = get_authenticated_users_list()
for verified_users in verifiedUsersList:
if verifiedUsers == unamePasswordForVerification:
message = 'AUTH_SUCCESS'
... |
test = { 'name': 'eq1',
'points': 0,
'suites': [ { 'cases': [ { 'code': '>>> best_salesperson(["Alice", "Bob", "Cam"], [3, 4, 1.25, 6, "Shift Change", 2, 4, 5.75, "Shift Change", 10, 2, .25, "Shift Change"]) == "Alice"\n'
'True',
... | test = {'name': 'eq1', 'points': 0, 'suites': [{'cases': [{'code': '>>> best_salesperson(["Alice", "Bob", "Cam"], [3, 4, 1.25, 6, "Shift Change", 2, 4, 5.75, "Shift Change", 10, 2, .25, "Shift Change"]) == "Alice"\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> best_salesperson(["Alice", "Bob", "Cam"], [3, 4, ... |
# Contents of simple.py
def cells():
1 + 2
| def cells():
1 + 2 |
def largest_non_adjacent(numbers):
if len(numbers) == 0:
return 0
incl = numbers[0]
excl = 0
for i in range(1, len(numbers)):
print(f"incl={incl}, excl={excl}")
incl, excl = excl + numbers[i], max(excl, incl)
return max(incl, excl)
print(largest_non_adjacent([5,5,10,40,50... | def largest_non_adjacent(numbers):
if len(numbers) == 0:
return 0
incl = numbers[0]
excl = 0
for i in range(1, len(numbers)):
print(f'incl={incl}, excl={excl}')
(incl, excl) = (excl + numbers[i], max(excl, incl))
return max(incl, excl)
print(largest_non_adjacent([5, 5, 10, 40... |
phrase='British Library'
alpha=re.compile('[^a-zA-Z]')
def normalize_keep_case(word):
return re.sub(alpha,'',word)
def mapper(book):
def checker(first, second):
first_word=normalize_keep_case(first[1])
second_word=normalize_keep_case(second[1])
page=first[0]
if [first_wo... | phrase = 'British Library'
alpha = re.compile('[^a-zA-Z]')
def normalize_keep_case(word):
return re.sub(alpha, '', word)
def mapper(book):
def checker(first, second):
first_word = normalize_keep_case(first[1])
second_word = normalize_keep_case(second[1])
page = first[0]
if [fi... |
def findDuplicates(arr):
l = len(arr)
temp = []
isPresent = False
for i in range(1, l):
for j in range(i+1, l):
if arr[i] == arr[j]:
if arr[i] in temp:
break
else:
temp.append(arr[i])
... | def find_duplicates(arr):
l = len(arr)
temp = []
is_present = False
for i in range(1, l):
for j in range(i + 1, l):
if arr[i] == arr[j]:
if arr[i] in temp:
break
else:
temp.append(arr[i])
is_p... |
class Solution(object):
# recursive
def maxDepth(self,root):
if not root:
return 0
if not root.children: return 1
return max(self.maxDepth(node) for node in root.children) + 1
# BFS (use a queue, the last level we see will be the depth)
def maxDepth2(self,root)... | class Solution(object):
def max_depth(self, root):
if not root:
return 0
if not root.children:
return 1
return max((self.maxDepth(node) for node in root.children)) + 1
def max_depth2(self, root):
queue = []
if root:
queue.append((root... |
mc_version = "1.12.2"
mc_file_md5 = "8c0443868b9e46c77d39db61c755679d"
of_file_name = "1.12.2_HD_U_E3"
of_json_name = "1.12.2_HD_U_E3"
of_file_md5 = "7EC95C57AC1A224D6EB93BD370E4AC37"
of_build_md5 = "ca404859e7af955dd01a72bb75bd6e11"
minecrift_version_num = "1.12.2"
minecrift_build = "jrbudda-9-r3"
of_file_extension = ... | mc_version = '1.12.2'
mc_file_md5 = '8c0443868b9e46c77d39db61c755679d'
of_file_name = '1.12.2_HD_U_E3'
of_json_name = '1.12.2_HD_U_E3'
of_file_md5 = '7EC95C57AC1A224D6EB93BD370E4AC37'
of_build_md5 = 'ca404859e7af955dd01a72bb75bd6e11'
minecrift_version_num = '1.12.2'
minecrift_build = 'jrbudda-9-r3'
of_file_extension = ... |
# Dictionary full of info
my_info = {"name": "Rex",
"occupation": "dog",
"age": 21,
"hobbies": ["barking", "eating", "sleeping", "loving my owner"],
"wake-up": {"Mon": 5, "Friday": 5, "Saturday": 10, "Sunday": 9}}
# Print out results are stored in the dictionary
print(f'Hell... | my_info = {'name': 'Rex', 'occupation': 'dog', 'age': 21, 'hobbies': ['barking', 'eating', 'sleeping', 'loving my owner'], 'wake-up': {'Mon': 5, 'Friday': 5, 'Saturday': 10, 'Sunday': 9}}
print(f"Hello I am {my_info['name']} and I am a {my_info['occupation']}")
print(f"I have {len(my_info['hobbies'])} hobbies!")
print(... |
#
# PySNMP MIB module CTRON-SSR-L2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SSR-L2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:15:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
'''
Check whether a given term represents a binary tree
Write a predicate istree which returns true if and only if its argument is a list representing a binary tree.
Example:
* (istree (a (b nil nil) nil))
T
* (istree (a (b nil nil)))
NIL
'''
def isTree(tree):
if len(tree) != 3: # checkin... | """
Check whether a given term represents a binary tree
Write a predicate istree which returns true if and only if its argument is a list representing a binary tree.
Example:
* (istree (a (b nil nil) nil))
T
* (istree (a (b nil nil)))
NIL
"""
def is_tree(tree):
if len(tree) != 3:
re... |
# Copyright (c) 2017 https://github.com/ping
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
__version__ = '0.3.8'
| __version__ = '0.3.8' |
maior = menor_de_20_feminino = masc =0
while True:
print('_' * 25)
print('CADASTRE UMA PESSOA')
print('_' * 25)
idade = int(input('Idade: '))
if idade > 18:
maior += 1
sexo = str(input('Sexo: [M/F] ')).strip().upper()
if sexo == 'M':
masc += 1
if idade < 20 and sexo == 'F... | maior = menor_de_20_feminino = masc = 0
while True:
print('_' * 25)
print('CADASTRE UMA PESSOA')
print('_' * 25)
idade = int(input('Idade: '))
if idade > 18:
maior += 1
sexo = str(input('Sexo: [M/F] ')).strip().upper()
if sexo == 'M':
masc += 1
if idade < 20 and sexo == '... |
def setup():
size(500, 300)
background(0)
colorMode(HSB)
t1 = random(0, 10)
t2 = random(0, 10)
t3 = 0
t4 = 100
def draw():
global t1
global t2
global t3
global t4
fill(color(t3, 255, 255))
#noStroke()
x = map(noise(t1), 0, 1, -.5*width, 1.5*width)
y = map(noise(t2), 0,... | def setup():
size(500, 300)
background(0)
color_mode(HSB)
t1 = random(0, 10)
t2 = random(0, 10)
t3 = 0
t4 = 100
def draw():
global t1
global t2
global t3
global t4
fill(color(t3, 255, 255))
x = map(noise(t1), 0, 1, -0.5 * width, 1.5 * width)
y = map(noise(t2), 0, 1, -0.5 * heigh... |
#
# PySNMP MIB module NCD-MIB-1 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NCD-MIB-1
# Produced by pysmi-0.3.4 at Mon Apr 29 20:07:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
class CONVERTER:
def __init__(self, endian):
self.endian = endian
def bytes2int(self, bytes):
return int.from_bytes(bytes, byteorder=self.endian) | class Converter:
def __init__(self, endian):
self.endian = endian
def bytes2int(self, bytes):
return int.from_bytes(bytes, byteorder=self.endian) |
mood = False
if mood :
print('go to left')
# print('back away')
else :
print('go to right')
a = 1
b = 2
c = 3
d = []
# account password
if a>b :
print('go to left')
else :
print('go to right') | mood = False
if mood:
print('go to left')
else:
print('go to right')
a = 1
b = 2
c = 3
d = []
if a > b:
print('go to left')
else:
print('go to right') |
messageDigit = [
[0, 2],
[2, 12],
[12, 16],
[16, 19],
[19, 23],
[23, 25],
[25, 41],
[41, 45],
[45, 47],
[47, 51],
[51, 55],
[55, 71],
[71, 88],
[88, 92],
[92, 96],
[96, 101],
[101, 122]
]
fieldLen = [
2,
10,
4,
3,
4,
2,
5,
... | message_digit = [[0, 2], [2, 12], [12, 16], [16, 19], [19, 23], [23, 25], [25, 41], [41, 45], [45, 47], [47, 51], [51, 55], [55, 71], [71, 88], [88, 92], [92, 96], [96, 101], [101, 122]]
field_len = [2, 10, 4, 3, 4, 2, 5, 5, 6, 4, 2, 4, 4, 16, 17, 4, 4, 5, 21]
field_names = ['message type', 'from (country)', 'from (pro... |
"""
Module: 'flashbdev' on micropython-esp32-1.14
"""
# MCU: {'ver': '1.14', 'port': 'esp32', 'arch': 'xtensawin', 'sysname': 'esp32', 'release': '1.14.0', 'name': 'micropython', 'mpy': 10757, 'version': '1.14.0', 'machine': 'ESP32 module (spiram) with ESP32', 'build': '', 'nodename': 'esp32', 'platform': 'esp32', 'fam... | """
Module: 'flashbdev' on micropython-esp32-1.14
"""
class Partition:
""""""
boot = 0
running = 1
type_app = 0
type_data = 1
def find():
pass
def get_next_update():
pass
def info():
pass
def ioctl():
pass
def mark_app_valid_cancel_rollback()... |
#
# PySNMP MIB module SONOMASYSTEMS-SONOMA-ATM-DS3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-ATM-DS3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:09:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
a = int(input())
b = int(input())
if b > a:
print(tuple(range(a, b))) # [a,b)
if a > b:
print(tuple(range(b, a))) # [b,a)
| a = int(input())
b = int(input())
if b > a:
print(tuple(range(a, b)))
if a > b:
print(tuple(range(b, a))) |
""" Count sequences & characters in aligned fasta files """
def main():
with open(snakemake.input.fasta, "r") as infile:
n_gaps, total_chars = count_gaps(infile)
with open(snakemake.input.ref_accnos, "r") as infile:
num_refs = len(infile.readlines())
with open(snakemake.input.query_accnos,... | """ Count sequences & characters in aligned fasta files """
def main():
with open(snakemake.input.fasta, 'r') as infile:
(n_gaps, total_chars) = count_gaps(infile)
with open(snakemake.input.ref_accnos, 'r') as infile:
num_refs = len(infile.readlines())
with open(snakemake.input.query_accnos... |
# Note : Finds the index of minimum element of the sublist from lower to upper-1
def find_index(mylist, lower, upper):
'''
Objective : To find the index of minimum element of the sublist from lower to upper-1
parameters :
mylist : The list in which the min index is to be found
lower : The ... | def find_index(mylist, lower, upper):
"""
Objective : To find the index of minimum element of the sublist from lower to upper-1
parameters :
mylist : The list in which the min index is to be found
lower : The lower bound for the sublist in which min index is to be found
upper : Th... |
#
# PySNMP MIB module HH3C-DSP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-DSP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:13:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint, constraints_union) ... |
mealCost = float(input())
tipPercent = int(input())
taxPercent = int(input())
totalCost = mealCost + (mealCost * (tipPercent/100)) + (mealCost * (taxPercent/100))
print('The total meal cost is', round(totalCost), 'dollars.') | meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
total_cost = mealCost + mealCost * (tipPercent / 100) + mealCost * (taxPercent / 100)
print('The total meal cost is', round(totalCost), 'dollars.') |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | """Model features metadata utils."""
feature_names = ['trip_month', 'trip_day', 'trip_day_of_week', 'trip_hour', 'trip_seconds', 'trip_miles', 'payment_type', 'pickup_grid', 'dropoff_grid', 'euclidean', 'loc_cross']
target_feature_name = 'tip_bin'
target_labels = ['tip<20%', 'tip>=20%']
numerical_feature_names = ['trip... |
class InvertedIndexMapper(InvertedIndex):
def __getitem__(self, key):
return self._get_postings_list(key)
def _get_postings_list(self, term):
"""Gets a postings list (of docIds) for `term`.
This function should not iterate through the index file.
I.e., it should onl... | class Invertedindexmapper(InvertedIndex):
def __getitem__(self, key):
return self._get_postings_list(key)
def _get_postings_list(self, term):
"""Gets a postings list (of docIds) for `term`.
This function should not iterate through the index file.
I.e., it should only h... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold(arr, n, m):
max = 0
min = 0
arr.sort()
j = n - 1
for i in range(m):
min += arr[i]
... | def f_gold(arr, n, m):
max = 0
min = 0
arr.sort()
j = n - 1
for i in range(m):
min += arr[i]
max += arr[j]
j = j - 1
return max - min
if __name__ == '__main__':
param = [([2, 3, 6, 16, 21, 22, 23, 27, 27, 28, 29, 29, 31, 31, 37, 37, 38, 40, 41, 43, 51, 52, 53, 55, 55,... |
class PaymentLinkInfo:
def __init__(
self,
amountInt,
amountWithFeeInt,
payed,
**kwargs
):
self.__amount = amountInt / 100.0
self.__amountWithFee = amountWithFeeInt / 100.0
self.__payed = payed
@property
def amount(self):
""":rtype: float"""
return self.__amount
@prop... | class Paymentlinkinfo:
def __init__(self, amountInt, amountWithFeeInt, payed, **kwargs):
self.__amount = amountInt / 100.0
self.__amountWithFee = amountWithFeeInt / 100.0
self.__payed = payed
@property
def amount(self):
""":rtype: float"""
return self.__amount
... |
"""
Generalization operations on dataframes
=======================================
A generalization replaces some values with a parent value in the taxonomy
of an attribute. The reverse operation is called specialization.
"""
def generalize(data):
print("generalize 2")
| """
Generalization operations on dataframes
=======================================
A generalization replaces some values with a parent value in the taxonomy
of an attribute. The reverse operation is called specialization.
"""
def generalize(data):
print('generalize 2') |
# LTD simulation models / perturbances
# Attribute name case sensitive.
# Commented and empty lines are ignored during parsing.
# Double quoted variable names in model parameters also ignored
# Perturbances
mirror.sysPerturbances = [
'gen 5 : step Pm 20 -100 rel', # Step generator down
]
mirror.govDelay ={
... | mirror.sysPerturbances = ['gen 5 : step Pm 20 -100 rel']
mirror.govDelay = {'delaygen1': {'genBus': 2, 'genId': '1', 'wDelay': (0, 0, 1.0), 'PrefDelay': (0, 0)}} |
class Node(object):
def __init__(self, name):
self.name = name;
self.adjacenciesList = [];
self.visited = False;
self.predecessor = None;
class DepthFirstSearch(object): # BFS -> queue + layer by layer algorithm DFS -> stack + goes as deep aspossible into the tree !!!
def dfs(self, node):
... | class Node(object):
def __init__(self, name):
self.name = name
self.adjacenciesList = []
self.visited = False
self.predecessor = None
class Depthfirstsearch(object):
def dfs(self, node):
node.visited = True
print('%s ' % node.name)
for n in node.adjacen... |
N, D, H = map(int, input().split())
dh = [tuple(map(int, input().split())) for _ in range(N)]
def is_ok(n):
for d, h in dh:
if (H - n) / D * d + n >= h:
continue
return False
else:
return True
ng = 0
ok = 10 ** 3
for _ in range(10000):
m = (ok + ng) / 2
if is_ok(m... | (n, d, h) = map(int, input().split())
dh = [tuple(map(int, input().split())) for _ in range(N)]
def is_ok(n):
for (d, h) in dh:
if (H - n) / D * d + n >= h:
continue
return False
else:
return True
ng = 0
ok = 10 ** 3
for _ in range(10000):
m = (ok + ng) / 2
if is_ok(... |
#assignement 1
#write a program that asks and showsthe following from the user:
# 1. Your name
# 2. Your age
# 3. Your favorite color
# 4. Your favorite animal
name = input("please enter your name:\n")
age = input("please enter your age:\n")
color = input("what is your favorite color:\n")
animal = input("what is ... | name = input('please enter your name:\n')
age = input('please enter your age:\n')
color = input('what is your favorite color:\n')
animal = input('what is your favorite animal:\n')
print('Hello my name is', name)
print('I am', age, 'years old')
print('My favorite color is', color)
print('My favorite animal is', animal) |
#
# PySNMP MIB module FASTPATH-IPV6-LOOPBACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FASTPATH-IPV6-LOOPBACK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:12:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
#new function declaration
def password_check(oldpassword, newpassword):
if newpassword != oldpassword:
if len(newpassword) >= 8:
if newpassword.isalpha()== False:
return True
return False
| def password_check(oldpassword, newpassword):
if newpassword != oldpassword:
if len(newpassword) >= 8:
if newpassword.isalpha() == False:
return True
return False |
class Animal(object):
pass
class Dog(Animal):
def _init_(self,name):
self.name=name
class Cat(Animal):
def _init_(self,name):
self.name=name
class Person(object):
def _init_(self,name):
self.name=name
self.pet=None
class Employee(Person):
def _init_(self,name,salary):... | class Animal(object):
pass
class Dog(Animal):
def _init_(self, name):
self.name = name
class Cat(Animal):
def _init_(self, name):
self.name = name
class Person(object):
def _init_(self, name):
self.name = name
self.pet = None
class Employee(Person):
def _init_... |
def ncycle(input_iter, n: int):
r"""iterz.ncycle(input_iter)
This will cycle an iterator a certain number of times. Usage:
>>> alist = [1, 2, 4, 8]
>>> for item in iterz.ncycle(alist, 2)
... print(item)
1
2
4
8
1
2
4
8
In fact, it works with any iterable co... | def ncycle(input_iter, n: int):
"""iterz.ncycle(input_iter)
This will cycle an iterator a certain number of times. Usage:
>>> alist = [1, 2, 4, 8]
>>> for item in iterz.ncycle(alist, 2)
... print(item)
1
2
4
8
1
2
4
8
In fact, it works with any iterable con... |
class Model:
def db_data(self):
print('Model called for data.')
data = 'Model Data.'
return data
class View:
def render(self, data):
print('Rendering model on view :' , data)
class Controller:
def __init__(self):
self.model = Model()
self.view = View()
... | class Model:
def db_data(self):
print('Model called for data.')
data = 'Model Data.'
return data
class View:
def render(self, data):
print('Rendering model on view :', data)
class Controller:
def __init__(self):
self.model = model()
self.view = view()
... |
n = (int(input()) - 1) % 8
if n == 0:
print(1)
elif n == 1 or n == 7:
print(2)
elif n == 2 or n == 6:
print(3)
elif n == 3 or n == 5:
print(4)
else:
print(5)
| n = (int(input()) - 1) % 8
if n == 0:
print(1)
elif n == 1 or n == 7:
print(2)
elif n == 2 or n == 6:
print(3)
elif n == 3 or n == 5:
print(4)
else:
print(5) |
input=__import__('sys').stdin.readline;n=int(input());s=input();t=0;b=0
for i in range(n):
if s[i]=='O': t+=i+1+b;b+=1
else: b=0
print(t)
| input = __import__('sys').stdin.readline
n = int(input())
s = input()
t = 0
b = 0
for i in range(n):
if s[i] == 'O':
t += i + 1 + b
b += 1
else:
b = 0
print(t) |
"""
NAME
simple string manipulations on the user's name
Ported by Dave LeCompte
"""
def is_yes_ish(answer: str) -> bool:
cleaned = answer.strip().upper()
if cleaned in ["Y", "YES"]:
return True
return False
def main() -> None:
print(" " * 34 + "NAME")
print(" " * 15 + "CREATIVE COMPUTI... | """
NAME
simple string manipulations on the user's name
Ported by Dave LeCompte
"""
def is_yes_ish(answer: str) -> bool:
cleaned = answer.strip().upper()
if cleaned in ['Y', 'YES']:
return True
return False
def main() -> None:
print(' ' * 34 + 'NAME')
print(' ' * 15 + 'CREATIVE COMPUTING... |
# Copyright 2020-2021 Vytautas Liuolia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | class Closingstreamwrapper:
"""Iterator that wraps a WSGI response iterable with support for close().
This class is used to wrap WSGI response streams to provide a side effect
when the stream is closed.
If the provided response stream is file-like, i.e., it has a ``read``
attribute, that attribute... |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_specs2_classycle",
artifact = "org.specs2:classycle:1.4.3",
jar_sha256 = "9b8cc4f88a5fa8c0e9437ff72f472f9f8e2a7509d94261df6196d5570935d697",
srcjar_sha256... | load('//:import_external.bzl', import_external='safe_wix_scala_maven_import_external')
def dependencies():
import_external(name='org_specs2_classycle', artifact='org.specs2:classycle:1.4.3', jar_sha256='9b8cc4f88a5fa8c0e9437ff72f472f9f8e2a7509d94261df6196d5570935d697', srcjar_sha256='23e4f4afe7f91b882974fa7fa06164... |
def map_to_server_type(predicted_class):
server_type = ''
if (predicted_class == 'two_thousand'):
server_type = 7
elif (predicted_class == 'fifty'):
server_type = 1
elif (predicted_class == 'one_hundred'):
server_type = 2
elif (predicted_class == 'two_hundred'):
serv... | def map_to_server_type(predicted_class):
server_type = ''
if predicted_class == 'two_thousand':
server_type = 7
elif predicted_class == 'fifty':
server_type = 1
elif predicted_class == 'one_hundred':
server_type = 2
elif predicted_class == 'two_hundred':
server_type =... |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
try:
if number < 0 :
return 'complex numbers not supported'
elif number >= 0... | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
try:
if number < 0:
return 'complex numbers not supported'
elif number >= 0:
... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Special globbing for js libraries, including and excluding certain files"""
js_glob_exts = (
"gif",
"html",
"jpeg",
"jpg... | """Special globbing for js libraries, including and excluding certain files"""
js_glob_exts = ('gif', 'html', 'jpeg', 'jpg', 'js', 'js.flow', 'json', 'mp4', 'png')
def js_glob(dirs, excludes=[]):
globs = []
for glob_dir in dirs:
if glob_dir == '.':
globs.extend(['*.%s' % ext for ext in js_g... |
#values added to dictionary recursively to save some time over iterative
def encode(arr,dictionary,ind):
#if gone through whole array
if ind == len(arr):
return dictionary
#if the letter/number has been seen before and exists in dictionary, increase the value by 1
elif arr[ind] in dictionary:
dictionary[arr[ind... | def encode(arr, dictionary, ind):
if ind == len(arr):
return dictionary
elif arr[ind] in dictionary:
dictionary[arr[ind]] = dictionary.get(arr[ind]) + 1
encode(arr, dictionary, ind + 1)
else:
dictionary[arr[ind]] = 1
encode(arr, dictionary, ind + 1)
dictionary = {}
da... |
VERSION = "2.0.1"
if __name__ == "__main__":
print(VERSION)
| version = '2.0.1'
if __name__ == '__main__':
print(VERSION) |
def parse_yaml(input_file):
"""Parse yaml file of configuration parameters."""
with open(input_file, "r") as yaml_file:
params = yaml.load(yaml_file)
return params
params = parse_yaml("preprocess_config.yaml")
ROOT = params["dirs"]["root"]
DATASET = os.path.join(ROOT, params["dirs"]["dataset"])
... | def parse_yaml(input_file):
"""Parse yaml file of configuration parameters."""
with open(input_file, 'r') as yaml_file:
params = yaml.load(yaml_file)
return params
params = parse_yaml('preprocess_config.yaml')
root = params['dirs']['root']
dataset = os.path.join(ROOT, params['dirs']['dataset'])
reor... |
# -*- Python -*-
"""Repository rule for Openvino configuration.
`openvino_configure` depends on the following environment variables:
* `INTEL_CVSDK_DIR`: The intel cv sdk install path.
* `InferenceEngine_DIR`: The library path which include intel inference engine library path.
"""
_INTEL_CVSDK_DIR = "INTEL_CVSDK... | """Repository rule for Openvino configuration.
`openvino_configure` depends on the following environment variables:
* `INTEL_CVSDK_DIR`: The intel cv sdk install path.
* `InferenceEngine_DIR`: The library path which include intel inference engine library path.
"""
_intel_cvsdk_dir = 'INTEL_CVSDK_DIR'
_inference_e... |
class ProcessUtil:
pass
# TODO: in separated classes:
# facade the psutil lib (in this class)
# check for facilitating the Popen call (in Process class that should be instantiable, as well as providing static methods to spawn process returning the raw Popen object)
# keep track of spawned syst... | class Processutil:
pass |
class Node():
"""
Class to create a new node.
"""
def __init__(self, data):
"""
Initializes an instance of a node with a *data*
attribute value equal to *data*.
"""
self.data = data
self.nxt = None
class Stack():
"""
Method to generate and modify... | class Node:
"""
Class to create a new node.
"""
def __init__(self, data):
"""
Initializes an instance of a node with a *data*
attribute value equal to *data*.
"""
self.data = data
self.nxt = None
class Stack:
"""
Method to generate and modify a s... |
"""
We need the request object to get the user, so we'll slightly modify the
existing django.contrib.auth.get_user method. To do so we update the
auth middleware to point to our overridden method.
Calling the "patch_middleware_get_user" method somewhere like our urls.py
file takes care of hooking it in appropriately... | """
We need the request object to get the user, so we'll slightly modify the
existing django.contrib.auth.get_user method. To do so we update the
auth middleware to point to our overridden method.
Calling the "patch_middleware_get_user" method somewhere like our urls.py
file takes care of hooking it in appropriately.
... |
# str - immutable sequence of Unicode codepoints
# str can be specified by delimiting with single quotes or double quotes
print("Python is beautiful")
print('Yes, I agree')
print("Don't you?")
print('"Yes!"')
s = """This is a
multiline
string
with newlines intact"""
print (s)
# Raw strings do not support any esca... | print('Python is beautiful')
print('Yes, I agree')
print("Don't you?")
print('"Yes!"')
s = 'This is a \nmultiline \nstring \nwith newlines intact'
print(s)
m = 'C:\\Program Files\\Microsoft'
print(m)
n = 'Anand Saha'
print('n is ' + n)
print('type of n is ' + str(type(n)))
print('n[0] is ' + n[0])
print('type of n[0] i... |
# O(n*2^n) time | O(n*2^n) space
def powerset(array):
subsets = [[]]
for ele in array:
for i in range(len(subsets)):
currentSubset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets | def powerset(array):
subsets = [[]]
for ele in array:
for i in range(len(subsets)):
current_subset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets |
nums = {0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten"}
feature = {0: "z", 1: "o", 2: "w", 3: "r", 4: "u", 5: "v", 6: "x", 7: "s", 8: "g", 9: "i", 10: "t"}
class Solution(object):
def originalDigits(self, s):
"""
:type s: ... | nums = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'}
feature = {0: 'z', 1: 'o', 2: 'w', 3: 'r', 4: 'u', 5: 'v', 6: 'x', 7: 's', 8: 'g', 9: 'i', 10: 't'}
class Solution(object):
def original_digits(self, s):
"""
:type s: st... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( m , n ) :
T = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ]
for i in range ( m + 1 ) :
... | def f_gold(m, n):
t = [[0 for i in range(n + 1)] for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
T[i][j] = 0
elif i < j:
T[i][j] = 0
elif j == 1:
T[i][j] = i
else:
... |
PHONE_NOT_EMPTY=1000
PHONE_NOT_FORMAT=1001
SMS_ERROR=1002
PHONE_SMS_NOT_EMPTY=1003
| phone_not_empty = 1000
phone_not_format = 1001
sms_error = 1002
phone_sms_not_empty = 1003 |
name= input("Enter file name: ")
fh = open(name)
for line in fh:
#line = line.rstrip()
for letter in line:
letter = letter.upper()
print(letter, end='')
fh.close()
# ou
print("\n=-=-=-=-=-=-=-=-=-=-=-=\n")
fh2 = open(name)
for line2 in fh2:
line2 = line2.rstrip()
print(l... | name = input('Enter file name: ')
fh = open(name)
for line in fh:
for letter in line:
letter = letter.upper()
print(letter, end='')
fh.close()
print('\n=-=-=-=-=-=-=-=-=-=-=-=\n')
fh2 = open(name)
for line2 in fh2:
line2 = line2.rstrip()
print(line2.upper())
fh2.close() |
# Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
# The successor of a node p is the node with the smallest key greater than p.val.
# Example 1:
# Input: root = [2,1,3], p = 1
# Output: 2
# Explanation: 1's in-order successor node is 2. Note that both p and the return... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorder_successor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode':
if p.right:
succ = p.right
while succ.left:
succ = succ.le... |
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# 1st soluton
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
d = {}
for w in strs:
key = tuple(sorted(w))
... | class Solution:
def group_anagrams(self, strs: List[str]) -> List[List[str]]:
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
d = {}
for w in strs:
key = tuple(sorted(w))
d[key] = d.ge... |
# Licensed to the White Turing under one or more
# contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except ... | """Exceptions that may happen in all the androiddriver code."""
class Androiddriverexception(Exception):
"""Base androiddriver exception."""
pass
class Applicationsexception(AndroidDriverException):
"""Thrown when using the wrong command to run the application."""
pass
class Charactersexception(Andro... |
""" Asked by: Twitter [Hard].
You are given an array of length 24, where each element represents the number of new subscribers during the corresponding hour.
Implement a data structure that efficiently supports the following:
update(hour: int, value: int): Increment the element at index hour by value.
query(start: i... | """ Asked by: Twitter [Hard].
You are given an array of length 24, where each element represents the number of new subscribers during the corresponding hour.
Implement a data structure that efficiently supports the following:
update(hour: int, value: int): Increment the element at index hour by value.
query(start: i... |
class Movie:
def __init__(self,id,title,overview,poster,vote_average,vote_count):
self.id =id
self.title = title
self.overview = overview
self.poster = 'https://image.tmdb.org/t/p/w500/'+ poster
self.vote_average = vote_average
self.vote_count = vote_count
| class Movie:
def __init__(self, id, title, overview, poster, vote_average, vote_count):
self.id = id
self.title = title
self.overview = overview
self.poster = 'https://image.tmdb.org/t/p/w500/' + poster
self.vote_average = vote_average
self.vote_count = vote_count |
Class(className = "Main", body = [
includeExternalFile("external"),
Def(functionName = "mergeStringArray", isStatic=True, returnType = "String", parameterNames = ["stringArray", "separator"], parameterTypes = ["String[]", "string"], body=[
makevar(arrayDimensions=0, variableType="string", initialValue="\"\"", varia... | class(className='Main', body=[include_external_file('external'), def(functionName='mergeStringArray', isStatic=True, returnType='String', parameterNames=['stringArray', 'separator'], parameterTypes=['String[]', 'string'], body=[makevar(arrayDimensions=0, variableType='string', initialValue='""', variableName='toReturn'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.