content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Car(object):
"""A car class"""
def __init__(self, model, make, color):
self.model = model
self.make = make
self.color = color
self.price = None
def get_price(self):
return self.price
def set_price(self, value):
self.price = value
availableCars = ... | class Car(object):
"""A car class"""
def __init__(self, model, make, color):
self.model = model
self.make = make
self.color = color
self.price = None
def get_price(self):
return self.price
def set_price(self, value):
self.price = value
available_cars = ... |
"""
URL: https://leetcode.com/explore/learn/card/linked-list/219/classic-problems/1207/
Problem Statement:
------------------
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6... | """
URL: https://leetcode.com/explore/learn/card/linked-list/219/classic-problems/1207/
Problem Statement:
------------------
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6... |
class Solution:
def __init__(self):
self.ret = []
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
# dp[i][j] means starting from [i for j ele can be slice
dp = [[0 for _ in range(len(s)+1)] for _ in ... | class Solution:
def __init__(self):
self.ret = []
def word_break(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [[0 for _ in range(len(s) + 1)] for _ in range(len(s) + 1)]
for j in range(1, len(s) + 1):
... |
password = input()
alpha = False
upalpha = False
digit = False
for i in password:
if i.isspace():
print("NOPE")
break
if i.isdigit():
digit = True
if i.isalpha():
if i.isupper():
upalpha = True
if i.islower():
alpha = True
else:
if alpha an... | password = input()
alpha = False
upalpha = False
digit = False
for i in password:
if i.isspace():
print('NOPE')
break
if i.isdigit():
digit = True
if i.isalpha():
if i.isupper():
upalpha = True
if i.islower():
alpha = True
else:
if alpha an... |
"""
Best Solution
Space : O(1)
Time : O(n log n)
"""
class Solution:
def smallestRangeII(self, A: List[int], K: int) -> int:
A.sort()
ans = A[-1] - A[0]
for x, y in zip(A, A[1:]):
ans = min(ans, max(A[-1]-K, x+K) - min(A[0]+K, y-K))
return ans
| """
Best Solution
Space : O(1)
Time : O(n log n)
"""
class Solution:
def smallest_range_ii(self, A: List[int], K: int) -> int:
A.sort()
ans = A[-1] - A[0]
for (x, y) in zip(A, A[1:]):
ans = min(ans, max(A[-1] - K, x + K) - min(A[0] + K, y - K))
return ans |
###########################
# 6.0002 Problem Set 1b: Space Change
# Name:
# Collaborators:
# Time:
# Author: charz, cdenise
#================================
# Part B: Golden Eggs
#================================
# Problem 1
# Method 1
# def dp_make_weight(egg_weights, target_weight, memo = {}):
# ... | def dp_make_weight(egg_weights, target_weight, memo={}):
least_taken = float('inf')
if target_weight == 0:
return 0
elif target_weight in memo:
return memo[target_weight]
elif target_weight > 0:
for weight in egg_weights:
sub_result = dp_make_weight(egg_weights, targe... |
"""Miscellaneous stuff for Coverage."""
def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
... | """Miscellaneous stuff for Coverage."""
def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
(start, end) = pair
if start == end:
... |
# Ideas
"""
server = dkeras.DataServer()
model1.link(model3)
model1.postprocess = lambda z: np.float16(z)
server = model1 + model2 + model3
server.add(camera1, dest=('m1', 'm2'))
server.add_address('192.168.1.42')
"""
| """
server = dkeras.DataServer()
model1.link(model3)
model1.postprocess = lambda z: np.float16(z)
server = model1 + model2 + model3
server.add(camera1, dest=('m1', 'm2'))
server.add_address('192.168.1.42')
""" |
#!/usr/bin/env python3
class IndexCreator:
def __init__(self):
self._index = 0
def generate(self):
r = self._index
self._index += 1
return r
def clear(self):
self._index = 0
if __name__ == "__main__":
i = IndexCreator()
print(i.generate(), i.genera... | class Indexcreator:
def __init__(self):
self._index = 0
def generate(self):
r = self._index
self._index += 1
return r
def clear(self):
self._index = 0
if __name__ == '__main__':
i = index_creator()
print(i.generate(), i.generate(), i.generate(), i.generate(... |
#Drinklist by Danzibob Credits to him!
drink_list = [{
'name': 'Vesper',
'ingredients': {
'gin': 60,
'vodka': 15.0,
'vermouth': 7.5
},
},
{
'name': 'Bacardi',
'ingredients': {
'whiteRum': 45.0,
'lij': 20,
... | drink_list = [{'name': 'Vesper', 'ingredients': {'gin': 60, 'vodka': 15.0, 'vermouth': 7.5}}, {'name': 'Bacardi', 'ingredients': {'whiteRum': 45.0, 'lij': 20, 'grenadine': 10}}, {'name': 'Kryptonite', 'ingredients': {'vodka': 8.0, 'whiskey': 7.0, 'lej': 6.0, 'oj': 5.0, 'grenadine': 4.0, 'cj': 3.0, 'rum': 2.0, 'vermouth... |
'''
Thanks to "Primo" for the amazing code found in this .py.
'''
# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
return pow(a, (m-1) >> 1, m)
# strong probable prime
def is_sprp(n, b=2):
d = n-1
s = 0
while d & 1 == 0:
s... | """
Thanks to "Primo" for the amazing code found in this .py.
"""
def legendre(a, m):
return pow(a, m - 1 >> 1, m)
def is_sprp(n, b=2):
d = n - 1
s = 0
while d & 1 == 0:
s += 1
d >>= 1
x = pow(b, d, n)
if x == 1 or x == n - 1:
return True
for r in range(1, s):
... |
a = "Hello World"
b = a[3]
c = a[-2]
d = a[5::]
e = a[:5]
print(b)
print(c)
print(d)
print(e)
| a = 'Hello World'
b = a[3]
c = a[-2]
d = a[5:]
e = a[:5]
print(b)
print(c)
print(d)
print(e) |
overlapped_classes = ["Alarm clock",
"Backpack",
"Banana",
"Band Aid",
"Basket",
"Bath towel",
"Beer bottle",
"Bench",
"Bicycle",
"Binder (closed)",
"Bottle cap",
"Bread loaf",
"Broom",
"Bucket",
"Butcher's knife",
"Can opener",
"Candle",
"Cellphone",
"Chair",
"Clothes hamper",
"Combination lock",
"Computer mouse",
"De... | overlapped_classes = ['Alarm clock', 'Backpack', 'Banana', 'Band Aid', 'Basket', 'Bath towel', 'Beer bottle', 'Bench', 'Bicycle', 'Binder (closed)', 'Bottle cap', 'Bread loaf', 'Broom', 'Bucket', "Butcher's knife", 'Can opener', 'Candle', 'Cellphone', 'Chair', 'Clothes hamper', 'Combination lock', 'Computer mouse', 'De... |
indexes = range(5)
same_indexes = range(0, 5)
print("indexes are:")
for i in indexes:
print(i)
print("same_indexes are:")
for i in same_indexes:
print(i)
special_indexes = range(5, 9)
print("special_indexes are:")
for i in special_indexes:
print(i) | indexes = range(5)
same_indexes = range(0, 5)
print('indexes are:')
for i in indexes:
print(i)
print('same_indexes are:')
for i in same_indexes:
print(i)
special_indexes = range(5, 9)
print('special_indexes are:')
for i in special_indexes:
print(i) |
print('\nCalculate the midpoint of a line :')
x1 = float(input('The value of x (the first endpoint) '))
y1 = float(input('The value of y (the first endpoint) '))
x2 = float(input('The value of x (the first endpoint) '))
y2 = float(input('The value of y (the first endpoint) '))
x_m_point = (x1 + x2)/2
y_m_point = (y1... | print('\nCalculate the midpoint of a line :')
x1 = float(input('The value of x (the first endpoint) '))
y1 = float(input('The value of y (the first endpoint) '))
x2 = float(input('The value of x (the first endpoint) '))
y2 = float(input('The value of y (the first endpoint) '))
x_m_point = (x1 + x2) / 2
y_m_point = (y1 ... |
ts = [
# example tests
14,
16,
23,
# small numbers
5,
4,
3,
2,
1,
# random bit bigger numbers
10,
20,
31,
32,
33,
46,
# perfect squares
25,
36,
49,
# random incrementally larger numbers
73,
89,
106,
132,
182,
258,
299,... | ts = [14, 16, 23, 5, 4, 3, 2, 1, 10, 20, 31, 32, 33, 46, 25, 36, 49, 73, 89, 106, 132, 182, 258, 299, 324, 359, 489, 512, 581, 713, 834, 952, 986, 996, 997, 998, 999]
for (i, n) in enumerate(ts):
with open('T%02d.in' % i, 'w') as f:
f.write('%d\n' % n) |
n=int(input())
while n:
n-=1
print(pow(*map(int,input().split()),10**9+7))
| n = int(input())
while n:
n -= 1
print(pow(*map(int, input().split()), 10 ** 9 + 7)) |
# Wrapper class to make dealing with logs easier
class ChannelLog():
__channel = ""
__logs = []
unread = False
mentioned_in = False
# the index of where to start printing the messages
__index = 0
def __init__(self, channel, logs):
self.__channel = channel
self.__logs = list... | class Channellog:
__channel = ''
__logs = []
unread = False
mentioned_in = False
__index = 0
def __init__(self, channel, logs):
self.__channel = channel
self.__logs = list(logs)
def get_server(self):
return self.__channel.server
def get_channel(self):
r... |
l= int(input("Enter the size of array \n"))
a=input("Enter the integer inputs\n").split()
c=0
a[0]=int(a[0])
for i in range(1,l):
a[i]=int(a[i])
while a[i]<a[i-1]:
c+=1
a[i]+=1
print(c)
| l = int(input('Enter the size of array \n'))
a = input('Enter the integer inputs\n').split()
c = 0
a[0] = int(a[0])
for i in range(1, l):
a[i] = int(a[i])
while a[i] < a[i - 1]:
c += 1
a[i] += 1
print(c) |
1 == 2
segfault()
class Dupe(object):
pass
class Dupe(Dupe):
pass
| 1 == 2
segfault()
class Dupe(object):
pass
class Dupe(Dupe):
pass |
# General Errors
NO_ERROR = 0
USER_EXIT = 1
ERR_SUDO_PERMS = 100
ERR_FOUND = 101
ERR_PYTHON_PKG = 154
# Warnings
WARN_FILE_PERMS = 115
WARN_LOG_ERRS = 126
WARN_LOG_WARNS = 127
WARN_LARGE_FILES = 151
# Installation Errors
ERR_BITS = 102
ERR_OS_VER = 103
ERR_OS = 104
ERR_FINDING_OS = 105
ERR_FREE_SPACE = 106
ERR_PKG_MA... | no_error = 0
user_exit = 1
err_sudo_perms = 100
err_found = 101
err_python_pkg = 154
warn_file_perms = 115
warn_log_errs = 126
warn_log_warns = 127
warn_large_files = 151
err_bits = 102
err_os_ver = 103
err_os = 104
err_finding_os = 105
err_free_space = 106
err_pkg_manager = 107
err_omsconfig = 108
err_omi = 109
err_sc... |
"{variable_name:format_description}"
print('{a:<10}|{a:^10}|{a:>10}'.format(a='test'))
print('{a:~<10}|{a:~^10}|{a:~>10}'.format(a='test'))
person = {"first":"Joran","last":"Beasley"}
print("{p[first]} {p[last]}".format(p=person))
data = range(100)
print("{d[0]}...{d[99]}".format(d=data))
print("normal:{num:d}".forma... | """{variable_name:format_description}"""
print('{a:<10}|{a:^10}|{a:>10}'.format(a='test'))
print('{a:~<10}|{a:~^10}|{a:~>10}'.format(a='test'))
person = {'first': 'Joran', 'last': 'Beasley'}
print('{p[first]} {p[last]}'.format(p=person))
data = range(100)
print('{d[0]}...{d[99]}'.format(d=data))
print('normal:{num:d}'.... |
def solution(A,B,K):
count = 0
for i in range(A,B):
if(i%K==0):
count += 1
#print(count)
return count
solution(6,11,2) | def solution(A, B, K):
count = 0
for i in range(A, B):
if i % K == 0:
count += 1
return count
solution(6, 11, 2) |
# -*- coding: utf-8 -*-
class Solution:
def getLucky(self, s: str, k: int) -> int:
result = ''.join(str(ord(c) - ord('a') + 1) for c in s)
for _ in range(k):
result = sum(int(digit) for digit in str(result))
return result
if __name__ == '__main__':
solution = Solution()
... | class Solution:
def get_lucky(self, s: str, k: int) -> int:
result = ''.join((str(ord(c) - ord('a') + 1) for c in s))
for _ in range(k):
result = sum((int(digit) for digit in str(result)))
return result
if __name__ == '__main__':
solution = solution()
assert 36 == soluti... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 3 10:38:41 2018
@author: lenovo
"""
# =============================================================================
# 13. Roman to Integer
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
#
# Symbol Value
# I 1
# V ... | """
Created on Fri Aug 3 10:38:41 2018
@author: lenovo
"""
class Solution:
def roman_to_int(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
if length == 0:
return 0
d1 = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
... |
def calc_average(case):
sum = 0
count = int(case[0])
for i in range(1, count + 1):
sum += int(case[i])
return sum / count
def count_average(case, average):
count = 0
count_num = int(case[0])
for i in range(1, count_num + 1):
if average < int(case[i]):
count += 1... | def calc_average(case):
sum = 0
count = int(case[0])
for i in range(1, count + 1):
sum += int(case[i])
return sum / count
def count_average(case, average):
count = 0
count_num = int(case[0])
for i in range(1, count_num + 1):
if average < int(case[i]):
count += 1
... |
"""
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
"""
class Solution:
def generateParenthesis(self, n: int... | """
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
"""
class Solution:
def generate_parenthesis(self, n: ... |
def decorator(func):
def wrapper():
print("Decoring")
func()
print("Done!")
return wrapper
@decorator
def say_hi():
print("Hi!")
if __name__ == "__main__":
say_hi()
| def decorator(func):
def wrapper():
print('Decoring')
func()
print('Done!')
return wrapper
@decorator
def say_hi():
print('Hi!')
if __name__ == '__main__':
say_hi() |
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if (n < 3):
# Special cases
# 0 = 0:
# 1 = 1: 1
# 2 = 2: 2, 1 1
return n
else: # Fibonaci from here onward
... | class Solution:
def climb_stairs(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return n
else:
preprev = 1
prev = 2
for i in range(n - 2):
temp = preprev
preprev = prev
... |
s = pd.Series(
data=np.random.randn(NUMBER),
index=pd.date_range('2000-01-01', freq='D', periods=NUMBER))
result = s['2000-02-14':'2000-02']
| s = pd.Series(data=np.random.randn(NUMBER), index=pd.date_range('2000-01-01', freq='D', periods=NUMBER))
result = s['2000-02-14':'2000-02'] |
# https://edabit.com/challenge/Yx2a9B57vXRuPevGh
# Create a function that takes length and width and finds the perimeter of a rectangle.
def find_perimeter(x: int, y: int) -> int:
perimeter = (x * 2) + (y * 2)
return perimeter
print(find_perimeter(20, 10))
| def find_perimeter(x: int, y: int) -> int:
perimeter = x * 2 + y * 2
return perimeter
print(find_perimeter(20, 10)) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
... | class Solution(object):
def is_same_tree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
return self.iterative(p, q)
def recursive(self, p, q):
check = self.nodeCheck(p, q)
if check == 0:
return True
elif... |
"""
Chapter 02 - Problem 01 - remove duplicates - CTCI 6th Edition
Problem Statement:
Write code to remove duplicates from unsorted linked list
FOLLOW UP : How would you solve this problem if temporary buffer is not allowed.
"""
def remove_dups(head): # O(n) speed with O(n) space for hash table
hash_table = {hea... | """
Chapter 02 - Problem 01 - remove duplicates - CTCI 6th Edition
Problem Statement:
Write code to remove duplicates from unsorted linked list
FOLLOW UP : How would you solve this problem if temporary buffer is not allowed.
"""
def remove_dups(head):
hash_table = {head.value: True}
while head is not None:
... |
# -*- coding: utf-8 -*-
# This file is generated from NI Switch Executive API metadata version 21.0.0d1
config = {
'api_version': '21.0.0d1',
'c_function_prefix': 'niSE_',
'close_function': 'CloseSession',
'context_manager_name': {
},
'custom_types': [
],
'driver_name': 'NI Switch Execut... | config = {'api_version': '21.0.0d1', 'c_function_prefix': 'niSE_', 'close_function': 'CloseSession', 'context_manager_name': {}, 'custom_types': [], 'driver_name': 'NI Switch Executive', 'driver_registry': 'Switch Executive', 'extra_errors_used': ['InvalidRepeatedCapabilityError'], 'init_function': 'OpenSession', 'libr... |
"""A utility module turning English into machine-readable data."""
def oxford_comma_text_to_list(phrase):
"""Examples:
- 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe']
- 'Black and White' --> ['Black', 'White']
- 'San Francisco and Saint Francis' -->
['San Francisco', 'S... | """A utility module turning English into machine-readable data."""
def oxford_comma_text_to_list(phrase):
"""Examples:
- 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe']
- 'Black and White' --> ['Black', 'White']
- 'San Francisco and Saint Francis' -->
['San Francisco', 'Sa... |
class DomainServiceBase:
def __init__(self, repository):
self.repository = repository
def update(self, obj, updated_data={}):
self.repository.update(obj, updated_data)
def delete(self, obj):
self.repository.delete(obj)
def create(self, obj):
obj = self.repository.creat... | class Domainservicebase:
def __init__(self, repository):
self.repository = repository
def update(self, obj, updated_data={}):
self.repository.update(obj, updated_data)
def delete(self, obj):
self.repository.delete(obj)
def create(self, obj):
obj = self.repository.crea... |
# score_manager.py
#Score Manager
ENEMY_SCORE = 300
RUPEE_SCORE = 500
scores = {
"ENEMY": ENEMY_SCORE,
"RUPEE": RUPEE_SCORE,
}
my_scores = {
"ENEMY": 300,
"MONEY": 1000,
"LASER": 1000,
"HP": 200,
"DEFENSE": 100
}
def calculate_score(score_type):
return my_scores[score_type]
| enemy_score = 300
rupee_score = 500
scores = {'ENEMY': ENEMY_SCORE, 'RUPEE': RUPEE_SCORE}
my_scores = {'ENEMY': 300, 'MONEY': 1000, 'LASER': 1000, 'HP': 200, 'DEFENSE': 100}
def calculate_score(score_type):
return my_scores[score_type] |
'''
Created on Mar 1, 2016
@author: kashefy
'''
class Phase:
TRAIN = 'Train'
TEST = 'Test'
| """
Created on Mar 1, 2016
@author: kashefy
"""
class Phase:
train = 'Train'
test = 'Test' |
class Node:
#Initialize node oject
def __init__(self, data):
self.data = data #assign data
self.next = None #declare next as null
class LinkedList:
#Initialize head
def __init__(self):
self.head = None
#### Insert in the beginning
def push(self, content):
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def push(self, content):
new_node = node(content)
new_node.next = self.head
self.head = new_node
def insert_after(self, prev... |
"""
Lab 7 python file
"""
#
print("\n3.1")
current_number=-1
while current_number<6:
current_number +=1
if (current_number==3 or current_number==6):
continue
print(current_number)
#
print("\n3.2")
n=int(input("Enter a number:"))
factorial=1
while n>=1:
factorial=factorial*n
n=n-1
pr... | """
Lab 7 python file
"""
print('\n3.1')
current_number = -1
while current_number < 6:
current_number += 1
if current_number == 3 or current_number == 6:
continue
print(current_number)
print('\n3.2')
n = int(input('Enter a number:'))
factorial = 1
while n >= 1:
factorial = factorial * n
n = ... |
class Solution:
# @param {character[][]} matrix
# @return {integer}
def maximalSquare(self, matrix):
if not matrix:
return 0
max_square = 0
self.visited = []
for line in matrix:
row = []
for c in line:
row.append(0)
... | class Solution:
def maximal_square(self, matrix):
if not matrix:
return 0
max_square = 0
self.visited = []
for line in matrix:
row = []
for c in line:
row.append(0)
self.visited.append(row)
self.visited[0] = [in... |
#!/usr/bin/python
#------------------------------------------------------------------------------
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
result = floa... | class Solution:
def three_sum_closest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
result = float('inf')
for i in range(len(nums) - 2):
(l, r) = (i + 1, len(nums) - 1)
while l < r... |
#! /usr/bin/python3.7
# soh cah toa
def sin():
o = float(input('What is the oppisite?: '))
h = float(input("What is the hypotnuse?: "))
s = o / h
print("sin = {}".format(s))
def cos():
a = float(input('What is the ajacent?: '))
h = float(input("What is the hypotnuse?: "))
c = a / h
print('cos = {}'.format(c))... | def sin():
o = float(input('What is the oppisite?: '))
h = float(input('What is the hypotnuse?: '))
s = o / h
print('sin = {}'.format(s))
def cos():
a = float(input('What is the ajacent?: '))
h = float(input('What is the hypotnuse?: '))
c = a / h
print('cos = {}'.format(c))
def tan():
... |
# Scale Settings
# For 005.mp4
SCALE_WIDTH = 25
SCALE_HEIGHT = 50
# SCALE_WIDTH = 100
# SCALE_HEIGHT = 100
# Video Settings
DETECT_AFTER_N = 50
# NMS Settings
NMS_CONFIDENCE = 0.1
NMS_THRESHOLD = 0.1
# Detection Settings
DETECTION_CONFIDENCE = 0.9
# Tracker Settings
MAX_DISAPPEARED = 50 | scale_width = 25
scale_height = 50
detect_after_n = 50
nms_confidence = 0.1
nms_threshold = 0.1
detection_confidence = 0.9
max_disappeared = 50 |
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
c=int(input("Enter the third number:"))
if a<b in c>a:
min=a
elif a<b in c>b:
min=b
else:
min=c
print(min)
| a = int(input('Enter the first number:'))
b = int(input('Enter the second number:'))
c = int(input('Enter the third number:'))
if a < b in c > a:
min = a
elif a < b in c > b:
min = b
else:
min = c
print(min) |
class setx:
def __init__(self, iterable=[]):
self.iterable = set(iterable)
self.size = len(self.iterable)
def __repr__(self):
return f"<{self.__class__.__name__.lower() !a}> {self.iterable}"
def add(self, element):
if element not in self.iterable:
self.iterable... | class Setx:
def __init__(self, iterable=[]):
self.iterable = set(iterable)
self.size = len(self.iterable)
def __repr__(self):
return f'<{self.__class__.__name__.lower()!a}> {self.iterable}'
def add(self, element):
if element not in self.iterable:
self.iterable.... |
def cycles_until_reseen(bins):
configs = set()
curr = bins
while tuple(curr) not in configs:
configs.add(tuple(curr))
min_idx = 0
for i in range(1, len(curr)):
if curr[i] > curr[min_idx]:
min_idx = i
redistribute = curr[min_idx]
curr[min_i... | def cycles_until_reseen(bins):
configs = set()
curr = bins
while tuple(curr) not in configs:
configs.add(tuple(curr))
min_idx = 0
for i in range(1, len(curr)):
if curr[i] > curr[min_idx]:
min_idx = i
redistribute = curr[min_idx]
curr[min_id... |
n = int(input())
count_2 = 0
count_5 = 0
for i in range(2,n+1):
num = i
while(1):
if num%2 == 0:
count_2 += 1
num //= 2
elif num%5 == 0:
count_5 += 1
num //= 5
else: break
print(min(count_2,count_5)) | n = int(input())
count_2 = 0
count_5 = 0
for i in range(2, n + 1):
num = i
while 1:
if num % 2 == 0:
count_2 += 1
num //= 2
elif num % 5 == 0:
count_5 += 1
num //= 5
else:
break
print(min(count_2, count_5)) |
# Copyright 2016-2020 Blue Marble Analytics LLC. All rights reserved.
"""
**Relevant tables:**
+--------------------------------+----------------------------------------------+
|:code:`scenarios` table column |:code:`project_new_potential_scenario_id` |
+--------------------------------+------------------------... | """
**Relevant tables:**
+--------------------------------+----------------------------------------------+
|:code:`scenarios` table column |:code:`project_new_potential_scenario_id` |
+--------------------------------+----------------------------------------------+
|:code:`scenarios` table feature |N/A ... |
if 1:
N = int(input())
Q = int(input())
queries = []
for i in range(Q):
queries.append([int(x) for x in input().split()])
else:
N = 100000
queries = [
[2, 1, 2],
[4, 1, 2]
] * 10000
queries.append([4, 1, 2])
Q = len(queries)
isTransposed = False
xs = list(ra... | if 1:
n = int(input())
q = int(input())
queries = []
for i in range(Q):
queries.append([int(x) for x in input().split()])
else:
n = 100000
queries = [[2, 1, 2], [4, 1, 2]] * 10000
queries.append([4, 1, 2])
q = len(queries)
is_transposed = False
xs = list(range(N + 1))
ys = list(r... |
# Location of the data.
reference_data_path = '/p/cscratch/acme/data/obs_for_acme_diags/'
test_data_path = '/p/cscratch/acme/data/test_model_data_for_acme_diags/'
# Name of the test model data, used to find the climo files.
test_name = '20161118.beta0.FC5COSP.ne30_ne30.edison'
# An optional, shorter name to be used ins... | reference_data_path = '/p/cscratch/acme/data/obs_for_acme_diags/'
test_data_path = '/p/cscratch/acme/data/test_model_data_for_acme_diags/'
test_name = '20161118.beta0.FC5COSP.ne30_ne30.edison'
short_test_name = 'beta0.FC5COSP.ne30'
sets = ['lat_lon']
results_dir = 'era_tas_land'
backend = 'mpl'
diff_title = 'Model - Ob... |
#
# Problem: Given an undirected graph with maximum degree, find a graph coloring using at most D+1 colors.
#
def color_graph_first_available(graph, colors):
"""
Solution: For each graph node, assign to it the first color not in the list of neighbor colors.
Complexity: (where n is # nodes, d is max degrees)
Time... | def color_graph_first_available(graph, colors):
"""
Solution: For each graph node, assign to it the first color not in the list of neighbor colors.
Complexity: (where n is # nodes, d is max degrees)
Time: O(n * (d + d+1 + 1)) -> O(n * d)
Space: O(g) -> size of graph
"""
for node in graph:
if node... |
file_name=str(input("Input the Filename:"))
if(file_name.split('.')[1]=='c'):
print('The extension of the file is C')
if(file_name.split('.')[1]=='cpp'):
print('The extension of the file is C++')
if(file_name.split('.')[1]=='java'):
print('The extension of the file is Java')
if(file_name.split('.')[1]=='py'):
p... | file_name = str(input('Input the Filename:'))
if file_name.split('.')[1] == 'c':
print('The extension of the file is C')
if file_name.split('.')[1] == 'cpp':
print('The extension of the file is C++')
if file_name.split('.')[1] == 'java':
print('The extension of the file is Java')
if file_name.split('.')[1] ... |
#
# PySNMP MIB module INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:54:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by u... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
def delUser(cur,con,loginid):
try:
query = "DELETE FROM USER WHERE Login_id='%s'" % (loginid)
#print(query)
cur.execute(query)
con.commit()
print("Deleted from Database")
except Exception as e:
con.rollback()
print("Failed to delete from database")
... | def del_user(cur, con, loginid):
try:
query = "DELETE FROM USER WHERE Login_id='%s'" % loginid
cur.execute(query)
con.commit()
print('Deleted from Database')
except Exception as e:
con.rollback()
print('Failed to delete from database')
print('>>>>>>>>>>>>>... |
# program to generate the combinations of n distinct objects taken from the elements of a given list.
def combination(n, n_list):
if n<=0:
yield []
return
for i in range(len(n_list)):
c_num = n_list[i:i+1]
for a_num in combination(n-1, n_list[i+1:]):
yield c_num + a_n... | def combination(n, n_list):
if n <= 0:
yield []
return
for i in range(len(n_list)):
c_num = n_list[i:i + 1]
for a_num in combination(n - 1, n_list[i + 1:]):
yield (c_num + a_num)
n_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print('Original list:')
print(n_list)
n = 2
result =... |
def install(job):
service = job.service
# create user if it doesn't exists
username = service.model.dbobj.name
password = service.model.data.password
email = service.model.data.email
provider = service.model.data.provider
username = "%s@%s" % (username, provider) if provider else username... | def install(job):
service = job.service
username = service.model.dbobj.name
password = service.model.data.password
email = service.model.data.email
provider = service.model.data.provider
username = '%s@%s' % (username, provider) if provider else username
password = password if not provider e... |
if condition1:
...
elif condition2:
...
elif condition3:
...
elif condition4:
...
elif condition5:
...
elif condition6:
...
else:
...
| if condition1:
...
elif condition2:
...
elif condition3:
...
elif condition4:
...
elif condition5:
...
elif condition6:
...
else:
... |
MIN_DRIVING_AGE = 18
group = {'tim': 17, 'bob': 18, 'ana': 24}
def allowed_driving(name):
"""Print '{name} is allowed to drive' or '{name} is not allowed to drive'
checking the passed in age against the MIN_DRIVING_AGE constant
"""
is_found = False
if name in group:
if group[nam... | min_driving_age = 18
group = {'tim': 17, 'bob': 18, 'ana': 24}
def allowed_driving(name):
"""Print '{name} is allowed to drive' or '{name} is not allowed to drive'
checking the passed in age against the MIN_DRIVING_AGE constant
"""
is_found = False
if name in group:
if group[name] >= ... |
# Python - 3.6.0
test.assert_equals(relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]), [1, 3, 5, 7])
test.assert_equals(relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]), [32, 61, 77, 11])
test.assert_equals(relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]), [])
| test.assert_equals(relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]), [1, 3, 5, 7])
test.assert_equals(relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]), [32, 61, 77, 11])
test.assert_equals(relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]), []) |
def save_file(contents):
with open("path_to_save_the_file.wav", 'wb') as f:
f.write(contents)
return "path_to_save_the_file.wav"
| def save_file(contents):
with open('path_to_save_the_file.wav', 'wb') as f:
f.write(contents)
return 'path_to_save_the_file.wav' |
expected_output = {
"main": {
"chassis": {
"ASR1002-X": {
"descr": "Cisco ASR1002-X Chassis",
"name": "Chassis",
"pid": "ASR1002-X",
"sn": "FOX1111P1M1",
"vid": "V07",
}
}
},
"slot": {
... | expected_output = {'main': {'chassis': {'ASR1002-X': {'descr': 'Cisco ASR1002-X Chassis', 'name': 'Chassis', 'pid': 'ASR1002-X', 'sn': 'FOX1111P1M1', 'vid': 'V07'}}}, 'slot': {'0': {'lc': {'ASR1002-X': {'descr': 'Cisco ASR1002-X SPA Interface Processor', 'name': 'module 0', 'pid': 'ASR1002-X', 'sn': '', 'subslot': {'0'... |
input = """
c(1).
c(2).
c(3).
a(X) | -a(X) :- c(X).
minim(X) :- a(X), #min{ D : a(D) } = X.
"""
output = """
c(1).
c(2).
c(3).
a(X) | -a(X) :- c(X).
minim(X) :- a(X), #min{ D : a(D) } = X.
"""
| input = '\nc(1).\nc(2).\nc(3).\n\na(X) | -a(X) :- c(X).\n\nminim(X) :- a(X), #min{ D : a(D) } = X.\n'
output = '\nc(1).\nc(2).\nc(3).\n\na(X) | -a(X) :- c(X).\n\nminim(X) :- a(X), #min{ D : a(D) } = X.\n' |
A = 1
connection= {
A : ['B'],
'B' : ['A', 'B', 'D'],
'C' : ['A'],
'D' : ['E','A'],
'E' : ['B']
}
for f in connection:
print(connection['B'])
print(connection[id])
| a = 1
connection = {A: ['B'], 'B': ['A', 'B', 'D'], 'C': ['A'], 'D': ['E', 'A'], 'E': ['B']}
for f in connection:
print(connection['B'])
print(connection[id]) |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class AugmentedTaskDTO(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the... | class Augmentedtaskdto(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {'i... |
"""
EDX_DATABASES = {
'think_101x': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'},
'hypers_301x': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-pro... | """
EDX_DATABASES = {
'think_101x': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'},
'hypers_301x': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-pro... |
def insertion_sort(the_list):
"""
In-place list sorting method
"""
i = 1
while i < len(the_list):
elem = the_list[i]
sorted_iterator = i-1
while elem < the_list[sorted_iterator] and sorted_iterator >= 0:
the_list[sorted_iterator+1] = the_list[sorted_iterator]
... | def insertion_sort(the_list):
"""
In-place list sorting method
"""
i = 1
while i < len(the_list):
elem = the_list[i]
sorted_iterator = i - 1
while elem < the_list[sorted_iterator] and sorted_iterator >= 0:
the_list[sorted_iterator + 1] = the_list[sorted_iterator]
... |
# emacs: -*- mode: python-mode; py-indent-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
# ex: set sts=2 ts=2 sw=2 et:
__all__ = ['classify', 'cluster', 'decode', 'meta', 'network', 'reduce', 'stats']
| __all__ = ['classify', 'cluster', 'decode', 'meta', 'network', 'reduce', 'stats'] |
def f1(x, *args):
pass
f1(42, 'spam')
| def f1(x, *args):
pass
f1(42, 'spam') |
{
'includes': [
'./common.gypi'
],
'target_defaults': {
'defines' : [
'PNG_PREFIX',
'PNGPREFIX_H',
'PNG_USE_READ_MACROS',
],
# 'include_dirs': [
# '<(DEPTH)/third_party/pdfium',
# '<(DEPTH)/third_party/pdfium/third_party/freetype/include',
# ],
'conditions': [
... | {'includes': ['./common.gypi'], 'target_defaults': {'defines': ['PNG_PREFIX', 'PNGPREFIX_H', 'PNG_USE_READ_MACROS'], 'conditions': [['OS=="linux"', {'conditions': [['target_arch=="x64"', {'defines': ['_FX_CPU_=_FX_X64_'], 'cflags': ['-fPIC']}], ['target_arch=="ia32"', {'defines': ['_FX_CPU_=_FX_X86_']}]]}]], 'msvs_disa... |
def normalizer(x, norm):
if norm == 'l2':
norm_val = sum(xi ** 2 for xi in x) ** .5
elif norm == 'l1':
norm_val = sum(abs(xi) for xi in x)
elif norm == 'max':
norm_val = max(abs(xi) for xi in x)
return [xi / norm_val for xi in x]
def standard_scaler(x, mean_, var_, with_mean, ... | def normalizer(x, norm):
if norm == 'l2':
norm_val = sum((xi ** 2 for xi in x)) ** 0.5
elif norm == 'l1':
norm_val = sum((abs(xi) for xi in x))
elif norm == 'max':
norm_val = max((abs(xi) for xi in x))
return [xi / norm_val for xi in x]
def standard_scaler(x, mean_, var_, with_m... |
def pascal_case(text):
"""Returns text converted to PascalCase"""
if text.count('_') == 0:
return text
s1 = text.split('_')
return ''.join([s.lower().capitalize() for s in s1])
def integral_type(member):
type = {
'char': 'char',
'signed char': 'sbyte',
'unsigned ch... | def pascal_case(text):
"""Returns text converted to PascalCase"""
if text.count('_') == 0:
return text
s1 = text.split('_')
return ''.join([s.lower().capitalize() for s in s1])
def integral_type(member):
type = {'char': 'char', 'signed char': 'sbyte', 'unsigned char': 'byte', 'short': 'shor... |
print('Enter any integer: ')
n = str(input().strip())
num_places = len(n)
for i in range(num_places) :
x = num_places - i
if x >= 10 :
suffix = "Billion "
elif x <= 9 and x >= 7 :
suffix = "Million "
elif x == 6 :
suffix = "Hundred "
elif x == 5 :
suffix = "Thousan... | print('Enter any integer: ')
n = str(input().strip())
num_places = len(n)
for i in range(num_places):
x = num_places - i
if x >= 10:
suffix = 'Billion '
elif x <= 9 and x >= 7:
suffix = 'Million '
elif x == 6:
suffix = 'Hundred '
elif x == 5:
suffix = 'Thousand '
... |
def search(arr, d, y):
for m in range(0, d):
if (arr[m] == y):
return m;
return -1;
arr = [4, 8, 26, 30, 13];
p = 30;
k = len(arr);
result = search(arr, k, p)
if (result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result... | def search(arr, d, y):
for m in range(0, d):
if arr[m] == y:
return m
return -1
arr = [4, 8, 26, 30, 13]
p = 30
k = len(arr)
result = search(arr, k, p)
if result == -1:
print('Element is not present in array')
else:
print('Element is present at index', result) |
# Turns an RPN expression to normal mathematical notation
_VARIABLES = {
"0": "0",
"1": "1",
"P": "pi",
"a": "x0",
"b": "x1",
"c": "x2",
"d": "x3",
"e": "x4",
"f": "x5",
"g": "x6",
"h": "x7",
"i": "x8",
"j": "x9",
"k": "x10",
"l": "x11",
"m": "x12",
"... | _variables = {'0': '0', '1': '1', 'P': 'pi', 'a': 'x0', 'b': 'x1', 'c': 'x2', 'd': 'x3', 'e': 'x4', 'f': 'x5', 'g': 'x6', 'h': 'x7', 'i': 'x8', 'j': 'x9', 'k': 'x10', 'l': 'x11', 'm': 'x12', 'n': 'x13'}
_ops_unary = {'>': '({}+1)', '<': '({}-1)', '~': '(-{})', '\\': '({})**(-1)', 'L': 'log({})', 'E': 'exp({})', 'S': 's... |
#converts the pixel bytes to binary
def decToBin(dec):
secret_bin = []
for i in dec:
secret_bin.append(f'{i:08b}')
return secret_bin
#gets the last 2 LSB of each byte
def get2LSB(secret_bin):
last2 = []
for i in secret_bin:
for j in i[6:8]:
last2.append(j... | def dec_to_bin(dec):
secret_bin = []
for i in dec:
secret_bin.append(f'{i:08b}')
return secret_bin
def get2_lsb(secret_bin):
last2 = []
for i in secret_bin:
for j in i[6:8]:
last2.append(j)
return last2
def filter2_lsb(listdict, last2):
piclsb = []
replace_n... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def buildfarm():
http_archive(
name="buildfarm" ,
build_file="//bazel/deps/buildfarm:build.BUILD" ,
sha256="de2a18... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def buildfarm():
http_archive(name='buildfarm', build_file='//bazel/deps/buildfarm:build.BUILD', sha256='de2a18bbe1e6770be0cd54e93630fb1ee7bce937bff708eed16329033fbfe32b', strip_prefix='bazel-buildfarm-355f816acf3531e9e37d860acf9ebbb89c9041c2', u... |
"""
Choose i/o filename here:
- a_example
- b_should_be_easy
- c_no_hurry
- d_metropolis
- e_high_bonus
"""
filename = 'b_should_be_easy' # choose input and output file names here
ride_pool = []
ride_id = 0
with open(filename + '.in', 'r') as file:
args = file.readline().split()
for line in file:
... | """
Choose i/o filename here:
- a_example
- b_should_be_easy
- c_no_hurry
- d_metropolis
- e_high_bonus
"""
filename = 'b_should_be_easy'
ride_pool = []
ride_id = 0
with open(filename + '.in', 'r') as file:
args = file.readline().split()
for line in file:
r = line.split()
ride_pool.append((ride_... |
class ReporterInterface(object):
def notify_before_console_output(self):
pass
def notify_after_console_output(self):
pass
def report_session_start(self, session):
pass
def report_session_end(self, session):
pass
def report_file_start(self, filename):
pass... | class Reporterinterface(object):
def notify_before_console_output(self):
pass
def notify_after_console_output(self):
pass
def report_session_start(self, session):
pass
def report_session_end(self, session):
pass
def report_file_start(self, filename):
pass... |
def read_as_strings(filename):
f = open(filename, "r")
res = f.read().split("\n")
return res
def read_as_ints(filename):
f = open(filename, "r")
res = map(int, f.read().split("\n"))
return list(res)
| def read_as_strings(filename):
f = open(filename, 'r')
res = f.read().split('\n')
return res
def read_as_ints(filename):
f = open(filename, 'r')
res = map(int, f.read().split('\n'))
return list(res) |
n = int(input("Qual o tamanho do vetor?"))
x = [int(input()) for x in range(n)]
for i in range(0, n, 2):
print(x[i])
| n = int(input('Qual o tamanho do vetor?'))
x = [int(input()) for x in range(n)]
for i in range(0, n, 2):
print(x[i]) |
# function for merge sort
def merge_sort(arr):
if len(arr) > 1:
# mid element of array
mid = len(arr) // 2
# Dividing the array and calling merge sort on array
left = arr[:mid]
# into 2 halves
right = arr[mid:]
# merge sort for array first
merge_so... | def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
merge_array(arr, left, right)
def merge_array(arr, left, right):
i = j = k = 0
while i < len(left) and j < len(right):
if l... |
def test_fake_hash(fake_hash):
assert fake_hash(b'rainstorms') == b"HASH(brainstorms)"
| def test_fake_hash(fake_hash):
assert fake_hash(b'rainstorms') == b'HASH(brainstorms)' |
"""Constants for Fama
RANKS(list of str): taxonomical ranks, top to bottom
LOWER_RANKS(dict of str): rank as key, child rank as value
ROOT_TAXONOMY_ID (str): taxonomy identifier of root node
UNKNOWN_TAXONOMY_ID (str): taxonomy identifier of 'Unknown' node
ENDS (list of str): identifiers of first and second end for pai... | """Constants for Fama
RANKS(list of str): taxonomical ranks, top to bottom
LOWER_RANKS(dict of str): rank as key, child rank as value
ROOT_TAXONOMY_ID (str): taxonomy identifier of root node
UNKNOWN_TAXONOMY_ID (str): taxonomy identifier of 'Unknown' node
ENDS (list of str): identifiers of first and second end for pai... |
supported_browsers = (
"system_default",
"chrome",
"chromium",
"chromium-browser",
"google-chrome",
"safari",
"firefox",
"opera",
"mozilla",
"netscape",
"galeon",
"epiphany",
"skipstone",
"kfmclient",
"konqueror",
"kfm",
"mosaic",
"grail",
"lin... | supported_browsers = ('system_default', 'chrome', 'chromium', 'chromium-browser', 'google-chrome', 'safari', 'firefox', 'opera', 'mozilla', 'netscape', 'galeon', 'epiphany', 'skipstone', 'kfmclient', 'konqueror', 'kfm', 'mosaic', 'grail', 'links', 'elinks', 'lynx', 'w3m', 'windows-default', 'macosx')
supported_image_ex... |
class BasePermission:
def __init__(self, user):
self.user = user
def has_permission(self, action):
raise NotImplementedError
class AllowAny:
def has_permission(self, action):
return True
class IsAuthenticated(BasePermission):
def has_permission(self, action):
return ... | class Basepermission:
def __init__(self, user):
self.user = user
def has_permission(self, action):
raise NotImplementedError
class Allowany:
def has_permission(self, action):
return True
class Isauthenticated(BasePermission):
def has_permission(self, action):
return... |
# Description: Count number of *.log files in current directory.
# Source: placeHolder
"""
cmd.do('print("Count the number of log image files in current directory.");')
cmd.do('print("Usage: cntlogs");')
cmd.do('myPath = os.getcwd();')
cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));')
cmd.do('print("Number of ... | """
cmd.do('print("Count the number of log image files in current directory.");')
cmd.do('print("Usage: cntlogs");')
cmd.do('myPath = os.getcwd();')
cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));')
cmd.do('print("Number of number of log image files in the current directory: ", logCounter);')
"""
cmd.do('print("C... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 06:33:05 2020
@author: ucobiz
"""
def happy():
print("Happy Bday to you!")
def sing(person, age):
happy()
happy()
print("Happy Bday,", person)
print("You're already", age, "years old")
happy()
def main():
sing("Fred", 30... | """
Created on Wed Oct 28 06:33:05 2020
@author: ucobiz
"""
def happy():
print('Happy Bday to you!')
def sing(person, age):
happy()
happy()
print('Happy Bday,', person)
print("You're already", age, 'years old')
happy()
def main():
sing('Fred', 30)
main() |
#counter part of inheritance
#inheritance means by this program- a bookself is a book
#composition is -
class Bookself:
def __init__(self, *books):
self.books=books
def __str__(self):
return f"Bookself with {len(self.books)} books."
class Book:
def __init__(self... | class Bookself:
def __init__(self, *books):
self.books = books
def __str__(self):
return f'Bookself with {len(self.books)} books.'
class Book:
def __init__(self, name):
self.name = name
def __str__(self):
return f'Book {self.name}'
book = book('Harry potter')
book2 =... |
def fake_get_value_from_db():
return 5
def check_outdated():
total = fake_get_value_from_db()
return total > 10
def task_put_more_stuff_in_db():
def put_stuff(): pass
return {'actions': [put_stuff],
'uptodate': [check_outdated],
}
| def fake_get_value_from_db():
return 5
def check_outdated():
total = fake_get_value_from_db()
return total > 10
def task_put_more_stuff_in_db():
def put_stuff():
pass
return {'actions': [put_stuff], 'uptodate': [check_outdated]} |
#!/usr/bin/env python3
def solution(s: str, p: list, q: list) -> list:
"""
>>> solution('CAGCCTA', [2, 5, 0], [4, 5, 6])
[2, 4, 1]
"""
response = ['T'] * len(p)
for i, s in enumerate(s):
for k, (p, q) in enumerate(zip(p, q)):
if p <= i <= q and s < response[k]:
... | def solution(s: str, p: list, q: list) -> list:
"""
>>> solution('CAGCCTA', [2, 5, 0], [4, 5, 6])
[2, 4, 1]
"""
response = ['T'] * len(p)
for (i, s) in enumerate(s):
for (k, (p, q)) in enumerate(zip(p, q)):
if p <= i <= q and s < response[k]:
response[k] = s
... |
'''
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0... | """
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0... |
# coding:utf-8
unconfirmed_users = ['liuhanyu', 'luoliuzhou', 'wangyue', 'xiaolizi']
confirmed_users = []
while unconfirmed_users:
user = unconfirmed_users.pop()
confirmed_users.append(user)
print(confirmed_users)
print(unconfirmed_users) | unconfirmed_users = ['liuhanyu', 'luoliuzhou', 'wangyue', 'xiaolizi']
confirmed_users = []
while unconfirmed_users:
user = unconfirmed_users.pop()
confirmed_users.append(user)
print(confirmed_users)
print(unconfirmed_users) |
# link: https://leetcode.com/problems/longest-string-chain/
"""
Sort the words by word's length. (also can apply bucket sort)
For each word, loop on all possible previous word with 1 letter missing.
If we have seen this previous word, update the longest chain for the current word.
Finally return the longest word chain.... | """
Sort the words by word's length. (also can apply bucket sort)
For each word, loop on all possible previous word with 1 letter missing.
If we have seen this previous word, update the longest chain for the current word.
Finally return the longest word chain.
"""
class Solution(object):
def longest_str_chain(sel... |
"""typecats"""
__version__ = "1.7.0"
__author__ = "Peter Gaultney"
__author_email__ = "pgaultney@xoi.io"
| """typecats"""
__version__ = '1.7.0'
__author__ = 'Peter Gaultney'
__author_email__ = 'pgaultney@xoi.io' |
num = int(input("Enter a number: "))
if ((num % 2 == 0) and (num % 3 == 0) and (num % 5 == 0)):
print("Divisible")
else:
print("Not Divisible")
| num = int(input('Enter a number: '))
if num % 2 == 0 and num % 3 == 0 and (num % 5 == 0):
print('Divisible')
else:
print('Not Divisible') |
"""Environment Variables to be used inside the CloudConvert-Python-REST-SDK"""
CLOUDCONVERT_API_KEY = "API_KEY"
"""Environment variable defining the Cloud Convert REST API default
credentials as Access Token."""
CLOUDCONVERT_SANDBOX = "true"
"""Environment variable defining if the sandbox API is used instead of the l... | """Environment Variables to be used inside the CloudConvert-Python-REST-SDK"""
cloudconvert_api_key = 'API_KEY'
'Environment variable defining the Cloud Convert REST API default\ncredentials as Access Token.'
cloudconvert_sandbox = 'true'
'Environment variable defining if the sandbox API is used instead of the live API... |
# f[i][j] = f[i - 1][j - 1] where s[i - 1] == p[j - 1] || p[j - 1] == '.' case p[j - 1] != '*'
# f[i][j] = f[i][j - 2] or f[i - 1][j] where s[i - 1] == p[j - 2] || p[j - 2] == '.' case p[j - 1] == '*'
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:r... | class Solution(object):
def is_match(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
m = len(s)
n = len(p)
table = [[False for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
... |
'''
Descripttion:
version:
Author: HuSharp
Date: 2021-02-21 22:59:41
LastEditors: HuSharp
LastEditTime: 2021-02-21 23:12:36
@Email: 8211180515@csu.edu.cn
'''
def countdown_1(k):
if k > 0:
yield k
for i in countdown_1(k-1):
yield i
def countdown(k):
if k > 0:
yield k
... | """
Descripttion:
version:
Author: HuSharp
Date: 2021-02-21 22:59:41
LastEditors: HuSharp
LastEditTime: 2021-02-21 23:12:36
@Email: 8211180515@csu.edu.cn
"""
def countdown_1(k):
if k > 0:
yield k
for i in countdown_1(k - 1):
yield i
def countdown(k):
if k > 0:
yield k
... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrderBottom(self, root):
x = self.solve(root)
... | class Solution:
def level_order_bottom(self, root):
x = self.solve(root)
return list(reversed(x))
def solve(self, root):
if root is None:
return []
l = self.solve(root.left)
r = self.solve(root.right)
m = [(l[i] if i < len(l) else []) + (r[i] if i < ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.