content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
CS241 Checkpoint 02B
Written by Chad Macbeth
"""
### Get file name from the user
def get_filename():
filename = input("Enter file: ")
return filename
### Open the file and analyze words and lines
### Returns a tuple (word count, line count)
def read_file(filename):
file_in = open(filename, "r")
line_c... | """
CS241 Checkpoint 02B
Written by Chad Macbeth
"""
def get_filename():
filename = input('Enter file: ')
return filename
def read_file(filename):
file_in = open(filename, 'r')
line_count = 0
word_count = 0
for line in file_in:
line_count += 1
words = line.split()
word_... |
REDIS_URL = 'redis://redis/0'
ERROR_NO_IMAGE = 'Please provide an image'
ERROR_NO_TEXT = 'Please provide some text'
MAX_SIZE = (512, 512)
# Where to store the models weights
# (except for Keras' that are stored in ~/.keras)
WEIGHT_PATH = './weights'
# Original model source: https://drive.google.com/drive/folders/0B... | redis_url = 'redis://redis/0'
error_no_image = 'Please provide an image'
error_no_text = 'Please provide some text'
max_size = (512, 512)
weight_path = './weights'
deeplab_url = 'http://eliot.andres.free.fr/models/deeplab_resnet.ckpt'
deeplab_filename = 'deeplab_resnet.ckpt'
ssd_inception_url = 'http://download.tensorf... |
s = input()
print(any(char.isalnum() for char in s))
print(any(char.isalpha() for char in s))
print(any(char.isdigit() for char in s))
print(any(char.islower() for char in s))
print(any(char.isupper() for char in s)) | s = input()
print(any((char.isalnum() for char in s)))
print(any((char.isalpha() for char in s)))
print(any((char.isdigit() for char in s)))
print(any((char.islower() for char in s)))
print(any((char.isupper() for char in s))) |
"""Kata url: https://www.codewars.com/kata/544675c6f971f7399a000e79."""
def string_to_number(s: int) -> int:
return int(s)
| """Kata url: https://www.codewars.com/kata/544675c6f971f7399a000e79."""
def string_to_number(s: int) -> int:
return int(s) |
# -*- coding: utf-8 -*-
# @Author: jpch89
# @Email: jpch89@outlook.com
# @Time: 2018/7/28 20:29
def convert_number(s):
try:
return int(s)
except ValueError:
return None
| def convert_number(s):
try:
return int(s)
except ValueError:
return None |
# This test verifies that __name__ == "__main__" works properly in Python Loader
if __name__ == "__main__":
print('Test: 1234567890abcd')
| if __name__ == '__main__':
print('Test: 1234567890abcd') |
def run():
my_list = [1, 'Hi', True, 4.5]
my_dict = {
"first_name": "Hernan",
"last_name": "Chamorro",
}
super_list = [
{ "first_name": "Hernan", "last_name": "Chamorro",},
{ "first_name": "Gustavo", "last_name": "Ramon",},
{ "first_name": "Bruno", "last_name": "... | def run():
my_list = [1, 'Hi', True, 4.5]
my_dict = {'first_name': 'Hernan', 'last_name': 'Chamorro'}
super_list = [{'first_name': 'Hernan', 'last_name': 'Chamorro'}, {'first_name': 'Gustavo', 'last_name': 'Ramon'}, {'first_name': 'Bruno', 'last_name': 'Facundo'}, {'first_name': 'Geronimo', 'last_name': 'At... |
friends = ['Mark', 'Simona', 'Paul', 'Jeremy', 'Colin', 'Sophie']
counter = 0
for counter, friend in enumerate(friends, start=1):
print(counter, friend)
print(list(enumerate(friends)))
print(dict(enumerate(friends)))
| friends = ['Mark', 'Simona', 'Paul', 'Jeremy', 'Colin', 'Sophie']
counter = 0
for (counter, friend) in enumerate(friends, start=1):
print(counter, friend)
print(list(enumerate(friends)))
print(dict(enumerate(friends))) |
def removeElement_1(nums, val):
"""
Brute force solution
Don't preserve order
"""
# count the frequency of the val
val_freq = 0
for num in nums:
if num == val:
val_freq += 1
# print(val_freq)
new_len = len(nums) - val_freq
# remove the element from the list
... | def remove_element_1(nums, val):
"""
Brute force solution
Don't preserve order
"""
val_freq = 0
for num in nums:
if num == val:
val_freq += 1
new_len = len(nums) - val_freq
i = 0
j = len(nums) - 1
while val_freq > 0 and i < new_len:
if nums[i] == val:
... |
#
# @lc app=leetcode id=109 lang=python3
#
# [109] Convert Sorted List to Binary Search Tree
#
# https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/
#
# algorithms
# Medium (49.90%)
# Likes: 2801
# Dislikes: 95
# Total Accepted: 287.7K
# Total Submissions: 568.6K
# Testcase Exampl... | class Solution:
def sorted_list_to_bst(self, head: ListNode) -> TreeNode:
return self.create_bst(head)
def create_bst(self, head):
if not head or not head.next:
return tree_node(head.val) if head else None
(slow, fast) = (head, head.next)
while fast.next and fast.ne... |
# Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Tests for shared flocker components.
"""
| """
Tests for shared flocker components.
""" |
class Tree_node:
def __init__(self,data):
self.data = data
self.parent = None
self.left = None
self.right = None
def __repr__(self):
return repr(self.data)
def add_left(self, node):
self.left = node
if node is not None:
node.parent = sel... | class Tree_Node:
def __init__(self, data):
self.data = data
self.parent = None
self.left = None
self.right = None
def __repr__(self):
return repr(self.data)
def add_left(self, node):
self.left = node
if node is not None:
node.parent = se... |
"""
Write a function that satisfies the following rules:
Return true if the string in the first element of the list contains all of the letters of the string in the second element of the list.
"""
def mutation(input_list):
short, long = sorted(map(lambda l: l.lower(), input_list), key=lambda item: len(item))
... | """
Write a function that satisfies the following rules:
Return true if the string in the first element of the list contains all of the letters of the string in the second element of the list.
"""
def mutation(input_list):
(short, long) = sorted(map(lambda l: l.lower(), input_list), key=lambda item: len(item))
... |
class Solution(object):
def numberOfBeams(self, bank):
"""
:type bank: List[str]
:rtype: int
"""
beams = 0
bank_len = len(bank)
if bank_len == 1:
return 0
else:
i = 0
j = 1
while(j < bank_len):
... | class Solution(object):
def number_of_beams(self, bank):
"""
:type bank: List[str]
:rtype: int
"""
beams = 0
bank_len = len(bank)
if bank_len == 1:
return 0
else:
i = 0
j = 1
while j < bank_len:
... |
class RegularExpression():
def __init__(self, regexStr):
self.regexStr = regexStr
def __str__(self):
return self.regexStr
| class Regularexpression:
def __init__(self, regexStr):
self.regexStr = regexStr
def __str__(self):
return self.regexStr |
def pythonic_solution(S, P, Q):
I = {'A': 1, 'C': 2, 'G': 3, 'T': 4}
# Obvious solution, scalable and compact. But slow for very large S
# with plenty of entropy.
result = []
for a, b in zip(P, Q):
i = min(S[a:b+1], key=lambda x: I[x])
result.append(I[i])
return result
def pr... | def pythonic_solution(S, P, Q):
i = {'A': 1, 'C': 2, 'G': 3, 'T': 4}
result = []
for (a, b) in zip(P, Q):
i = min(S[a:b + 1], key=lambda x: I[x])
result.append(I[i])
return result
def prefix_sum_solution(S, P, Q):
i = {'A': 1, 'C': 2, 'G': 3, 'T': 4}
n = len(S)
ps = [[0, 0, ... |
class shapeCharacter:
rotationNumber = 1
def moveRight(self):
self.x1 = self.x1 + 1
self.x2 = self.x2 + 1
self.x3 = self.x3 + 1
self.x4 = self.x4 + 1
self.cordinates = [(self.y1,self.x1), (self.y2,self.x2), (self.y3,self.x3), (self.y4,self.x4)]
self.rotationCord... | class Shapecharacter:
rotation_number = 1
def move_right(self):
self.x1 = self.x1 + 1
self.x2 = self.x2 + 1
self.x3 = self.x3 + 1
self.x4 = self.x4 + 1
self.cordinates = [(self.y1, self.x1), (self.y2, self.x2), (self.y3, self.x3), (self.y4, self.x4)]
self.rotatio... |
""" My implementation of fizzbuzz. """
def fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
print ('fizzbuzz')
elif number % 3 == 0:
print ('fizz')
elif number % 5 != 0:
print ('buzz')
if __name__ == '__main__':
fizzbuzz(15)
| """ My implementation of fizzbuzz. """
def fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
print('fizzbuzz')
elif number % 3 == 0:
print('fizz')
elif number % 5 != 0:
print('buzz')
if __name__ == '__main__':
fizzbuzz(15) |
# class Solution(object):
# def isValid(self, s):
#
class Solution:
def isValid(self, s):
stack = []
dic = {']' :'[', '}':'{', ')':'('}
for c in s:
if c in dic.values():
stack.ap... | class Solution:
def is_valid(self, s):
stack = []
dic = {']': '[', '}': '{', ')': '('}
for c in s:
if c in dic.values():
stack.append(c)
elif c in dic.keys():
if stack == [] or dic[c] != stack.pop():
return False
... |
'''
Project: SingleLinkedList
File: SingleLinkedList.py
Author: Sanjay Vyas
Description:
Implementation of a simple linked list in Python
Revision History:
2018-November-17: Initial Creation
Copyright (c) 2019 Sanjay Vyas
License:
This code is meant for learning algorithms and writing clean c... | """
Project: SingleLinkedList
File: SingleLinkedList.py
Author: Sanjay Vyas
Description:
Implementation of a simple linked list in Python
Revision History:
2018-November-17: Initial Creation
Copyright (c) 2019 Sanjay Vyas
License:
This code is meant for learning algorithms and writing clean c... |
"""
[2015-12-09] Challenge #244 [Easy]er - Array language (part 3) - J Forks
https://www.reddit.com/r/dailyprogrammer/comments/3wdm0w/20151209_challenge_244_easyer_array_language_part/
This challenge does not require doing the previous 2 parts. If you want something harder, the rank conjunction from
Wednesday's chal... | """
[2015-12-09] Challenge #244 [Easy]er - Array language (part 3) - J Forks
https://www.reddit.com/r/dailyprogrammer/comments/3wdm0w/20151209_challenge_244_easyer_array_language_part/
This challenge does not require doing the previous 2 parts. If you want something harder, the rank conjunction from
Wednesday's chal... |
#MODIFICANDO UMA TUPLA
tpl_values = (10, 14, 16, 20)
try:
tpl_values[1] = 26
except (TypeError) as err:
print(f"Error: {err}")
#ALTERANDO LISTA DENTRO DE UMA TUPLA
tpl_values = (10, 14, 16, 20, [24,26])
try:
tpl_values[4].append(30)
print(tpl_values)
except (TypeError) as err:
print(f"Error: {er... | tpl_values = (10, 14, 16, 20)
try:
tpl_values[1] = 26
except TypeError as err:
print(f'Error: {err}')
tpl_values = (10, 14, 16, 20, [24, 26])
try:
tpl_values[4].append(30)
print(tpl_values)
except TypeError as err:
print(f'Error: {err}') |
# -*- coding: utf-8 -*-
def __download(core, filepath, request):
request['stream'] = True
with core.request.execute(core, request) as r:
with open(filepath, 'wb') as f:
core.shutil.copyfileobj(r.raw, f)
def __extract_gzip(core, archivepath, filename):
filepath = core.os.path.join(core.... | def __download(core, filepath, request):
request['stream'] = True
with core.request.execute(core, request) as r:
with open(filepath, 'wb') as f:
core.shutil.copyfileobj(r.raw, f)
def __extract_gzip(core, archivepath, filename):
filepath = core.os.path.join(core.utils.temp_dir, filename)... |
if __name__ == '__main__':
try:
main()
log.info("Script completed successfully")
except Exception as e:
log.critical("The script did not complete successfully")
log.exception(e)
sys.exit(1)
| if __name__ == '__main__':
try:
main()
log.info('Script completed successfully')
except Exception as e:
log.critical('The script did not complete successfully')
log.exception(e)
sys.exit(1) |
bind = '127.0.0.1:8000'
workers = 3
user = 'web'
timeout = 120
| bind = '127.0.0.1:8000'
workers = 3
user = 'web'
timeout = 120 |
user_input = input("Input two words separated by space to create key value pairs, or enter nothing to quit")
empty_dict = {}
while user_input != "":
words = user_input.split(" ")
if len(words) >= 2:
empty_dict[words[0]] = words[1]
else:
print("not enough words to create an entry")
user_i... | user_input = input('Input two words separated by space to create key value pairs, or enter nothing to quit')
empty_dict = {}
while user_input != '':
words = user_input.split(' ')
if len(words) >= 2:
empty_dict[words[0]] = words[1]
else:
print('not enough words to create an entry')
user_i... |
class Snapshot:
def __init__(self, state: any, index: int):
self.state = state
self.index = index
class RecoverSnapshot(Snapshot):
def __init__(self, data: any, index: int):
super().__init__(data, index)
class PersistedSnapshot(Snapshot):
def __init__(self, data: any, index: int)... | class Snapshot:
def __init__(self, state: any, index: int):
self.state = state
self.index = index
class Recoversnapshot(Snapshot):
def __init__(self, data: any, index: int):
super().__init__(data, index)
class Persistedsnapshot(Snapshot):
def __init__(self, data: any, index: int... |
def positive_sum(arr):
positive_list = []
for i in arr:
if i > 0:
positive_list.append(i)
return(sum(positive_list))
# Best Practices
def positive_sum(arr):
return sum(x for x in arr if x > 0)
| def positive_sum(arr):
positive_list = []
for i in arr:
if i > 0:
positive_list.append(i)
return sum(positive_list)
def positive_sum(arr):
return sum((x for x in arr if x > 0)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`orion.core.cli.checks.presence` -- Presence stage for database checks
===========================================================================
.. module:: presence
:platform: Unix
:synopsis: Checks for the presence of a configuration.
"""
class Pres... | """
:mod:`orion.core.cli.checks.presence` -- Presence stage for database checks
===========================================================================
.. module:: presence
:platform: Unix
:synopsis: Checks for the presence of a configuration.
"""
class Presencestage:
"""The presence stage of the che... |
'''
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.
Example 1:
Input: A = 'abc... | """
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.
Example 1:
Input: A = 'abc... |
myfile= open("running-config.cfg")
def process_line(word):
str=word.split()
lst=str[2:]
mytpl = tuple(lst)
return(mytpl)
def check(line):
if "no ip address" in line:
return
elif "ip address" in line:
return(process_line(line))
else:
return
myfinlist=[]
for line in myfile:
mytpl3=check(line)
if mytp... | myfile = open('running-config.cfg')
def process_line(word):
str = word.split()
lst = str[2:]
mytpl = tuple(lst)
return mytpl
def check(line):
if 'no ip address' in line:
return
elif 'ip address' in line:
return process_line(line)
else:
return
myfinlist = []
for line... |
"""Config for sending email via Mailgun"""
MAILGUN = {
"from": "XXXX",
"url": "XXXX",
"api_key": "XXXX"
}
NOTIFICATIONS = ["XX@XX.com"]
| """Config for sending email via Mailgun"""
mailgun = {'from': 'XXXX', 'url': 'XXXX', 'api_key': 'XXXX'}
notifications = ['XX@XX.com'] |
# 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 postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... | class Solution(object):
def postorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
revres = []
cur = root
while cur:
if cur.right:
temp = cur.right
while temp.left and temp.left != cur:
... |
# Create two lists of zeros; rows and cols. Keep incrementing count in the lists. Increment total_odd by r+c%2==1
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
rows, cols = [0]*n, [0]*m
for i in indices:
rows[i[0]] += 1
... | class Solution:
def odd_cells(self, n: int, m: int, indices: List[List[int]]) -> int:
(rows, cols) = ([0] * n, [0] * m)
for i in indices:
rows[i[0]] += 1
cols[i[1]] += 1
count = 0
for r in rows:
for c in cols:
if (r + c) % 2 == 1:
... |
I=input('Enter String: ')
if I.count('4')==0 and I.count('7')==0:
print('Output:',-1)
else:
if I.count('4')>=I.count('7'):
print('Output:',4)
else:
print('Output:',7)
| i = input('Enter String: ')
if I.count('4') == 0 and I.count('7') == 0:
print('Output:', -1)
elif I.count('4') >= I.count('7'):
print('Output:', 4)
else:
print('Output:', 7) |
# Window-handling features of PyAutoGUI
# UNDER CONSTRUCTION
"""
Window handling features:
- pyautogui.getWindows() # returns a dict of window titles mapped to window IDs
- pyautogui.getWindow(str_title_or_int_id) # returns a "Win" object
- win.move(x, y)
- win.resize(width, height)
- win.maximize()
- wi... | """
Window handling features:
- pyautogui.getWindows() # returns a dict of window titles mapped to window IDs
- pyautogui.getWindow(str_title_or_int_id) # returns a "Win" object
- win.move(x, y)
- win.resize(width, height)
- win.maximize()
- win.minimize()
- win.restore()
- win.close()
- win.position() ... |
def can_build(env, platform):
return (platform == "x11")
# for futur: or platform == "windows" or platform == "osx" or platform == "android"
def configure(env):
pass
def get_doc_classes():
return [
"Bluetooth",
"NetworkedMultiplayerBt",
]
def get_doc_path():
return "doc_cla... | def can_build(env, platform):
return platform == 'x11'
def configure(env):
pass
def get_doc_classes():
return ['Bluetooth', 'NetworkedMultiplayerBt']
def get_doc_path():
return 'doc_classes' |
def fib(n):
if(n <= 1): return n
return fib(n-1) + fib(n-2)
print(fib(30))
| def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print(fib(30)) |
NAME = 'Little Wolf'
def extract_upper(phrase):
return list(filter(str.isupper, phrase))
def extract_lower(phrase):
return list(filter(str.islower, phrase))
| name = 'Little Wolf'
def extract_upper(phrase):
return list(filter(str.isupper, phrase))
def extract_lower(phrase):
return list(filter(str.islower, phrase)) |
def main() -> None:
N, M, K = map(int, input().split())
A = [0] * M
B = [0] * M
for i in range(M):
A[i], B[i] = map(int, input().split())
X = list(map(int, input().split()))
assert 2 <= N <= 50
assert 1 <= M <= (N * (N - 1))
assert 1 <= K <= 10
assert len(X) == N
asse... | def main() -> None:
(n, m, k) = map(int, input().split())
a = [0] * M
b = [0] * M
for i in range(M):
(A[i], B[i]) = map(int, input().split())
x = list(map(int, input().split()))
assert 2 <= N <= 50
assert 1 <= M <= N * (N - 1)
assert 1 <= K <= 10
assert len(X) == N
assert... |
{
'targets': [{
'target_name': 'talib',
'sources': [
'src/talib.cpp'
],
"include_dirs": [
"<!(node -e \"require('nan')\")"
],
'conditions': [
['OS=="linux"', {
"libraries": [
"../src/lib/lib/libta... | {'targets': [{'target_name': 'talib', 'sources': ['src/talib.cpp'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'conditions': [['OS=="linux"', {'libraries': ['../src/lib/lib/libta_abstract_csr.a', '../src/lib/lib/libta_func_csr.a', '../src/lib/lib/libta_common_csr.a', '../src/lib/lib/libta_libc_csr.a']}], ['OS=... |
n = input("Enter a number: ")
n = int(n)
if n > 1000:
print("PLEASE ENTER A NUMBER THAT IS LESS THAN 1000!")
else:
n = str(n)
if len(n) == 2:
if n[0] == "2":
a = "Twenty"
if n[0] == "3":
a = "Thirty"
if n[0] == "4":
a = "Fourty"
if n[0] == ... | n = input('Enter a number: ')
n = int(n)
if n > 1000:
print('PLEASE ENTER A NUMBER THAT IS LESS THAN 1000!')
else:
n = str(n)
if len(n) == 2:
if n[0] == '2':
a = 'Twenty'
if n[0] == '3':
a = 'Thirty'
if n[0] == '4':
a = 'Fourty'
if n[0] == ... |
def test1(foo, bar):
foo = 3
def test2(quix):
foo = 4
test2(123)
print(foo)
# Should be 3
| def test1(foo, bar):
foo = 3
def test2(quix):
foo = 4
test2(123)
print(foo) |
temp: int = int(input())
temp_range: int = 0 if (10 <= temp <= 18) else 1 if (18 < temp <= 24) else 2
day_time: int = ('Morning', 'Afternoon', 'Evening',).index(input())
options: tuple = (
(('Sweatshirt', 'Sneakers',),('Shirt','Moccasins',),('Shirt','Moccasins',),),
(('Shirt','Moccasins',),('T-Shirt','Sandals',... | temp: int = int(input())
temp_range: int = 0 if 10 <= temp <= 18 else 1 if 18 < temp <= 24 else 2
day_time: int = ('Morning', 'Afternoon', 'Evening').index(input())
options: tuple = ((('Sweatshirt', 'Sneakers'), ('Shirt', 'Moccasins'), ('Shirt', 'Moccasins')), (('Shirt', 'Moccasins'), ('T-Shirt', 'Sandals'), ('Shirt', ... |
def tmembership(my_tuple1,my_tuple2):
for item in my_tuple1:
# membership in and not in operator in tuple
if item in my_tuple2:
print(str(item) + ' in my_tuple2')
if item not in my_tuple2:
print(str(item) + ' not in my_tuple2')
print(tmembership((1, 2, 3, 4, 5), (1,... | def tmembership(my_tuple1, my_tuple2):
for item in my_tuple1:
if item in my_tuple2:
print(str(item) + ' in my_tuple2')
if item not in my_tuple2:
print(str(item) + ' not in my_tuple2')
print(tmembership((1, 2, 3, 4, 5), (1, 2, 3))) |
# Exceptions
# Problem Link: https://www.hackerrank.com/challenges/exceptions/problem
for _ in range(int(input())):
try:
a, b = [int(x) for x in input().split()]
print(a // b)
except Exception as e:
print("Error Code:", e)
| for _ in range(int(input())):
try:
(a, b) = [int(x) for x in input().split()]
print(a // b)
except Exception as e:
print('Error Code:', e) |
TYPEKRUISING = {
1: "aquaduct",
2: "brug",
3: "duiker",
4: "sifon",
5: "hevel",
6: "bypass"
}
MATERIAALKUNSTWERK = {
1: "aluminium",
2: "asbestcement",
3: "beton",
4: "gegolfd plaatstaal",
5: "gewapend beton",
6: "gietijzer",
7: "glad staal",
8: ... | typekruising = {1: 'aquaduct', 2: 'brug', 3: 'duiker', 4: 'sifon', 5: 'hevel', 6: 'bypass'}
materiaalkunstwerk = {1: 'aluminium', 2: 'asbestcement', 3: 'beton', 4: 'gegolfd plaatstaal', 5: 'gewapend beton', 6: 'gietijzer', 7: 'glad staal', 8: 'glas', 9: 'grasbetontegels', 10: 'hout', 11: 'ijzer', 12: 'koper', 13: 'kuns... |
# -*- coding: utf-8 -*-
EMPTY_STR = ""
def is_empty(word):
return bool(word == EMPTY_STR)
def is_empty_strip(word):
return bool(str(word).strip() == EMPTY_STR)
| empty_str = ''
def is_empty(word):
return bool(word == EMPTY_STR)
def is_empty_strip(word):
return bool(str(word).strip() == EMPTY_STR) |
"""
0849. Maximize Distance to Closest Person
Easy
In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him... | """
0849. Maximize Distance to Closest Person
Easy
In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him... |
# This is a sample module used for testing doctest.
#
# This module is for testing how doctest handles a module with no
# docstrings.
class Foo(object):
# A class with no docstring.
def __init__(self):
pass
| class Foo(object):
def __init__(self):
pass |
# generating magic square
# note only works with odd number input
# conditions and procedure in readme.md file at https://github.com/ThayalanGR/competitive-programs
def generateMagicSquare(n):
mSquare = [[0 for _ in range(n)] for _ in range(n)]
# initialize row and col value
i = int(n/2)
j = n-1
... | def generate_magic_square(n):
m_square = [[0 for _ in range(n)] for _ in range(n)]
i = int(n / 2)
j = n - 1
num = 1
while num <= pow(n, 2):
if i == -1 and j == n:
i = 0
j = n - 2
else:
if j == n:
j = 0
if i < 0:
... |
# Created by MechAviv
# Map ID :: 940012010
# Hidden Street : Decades Later
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.removeSkill(60011219)
if not "1" in sm.getQRValue(25807):
sm.levelUntil(10)
sm.setJob(6500)
sm.createQuestWithQRValue(25807... | sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.removeSkill(60011219)
if not '1' in sm.getQRValue(25807):
sm.levelUntil(10)
sm.setJob(6500)
sm.createQuestWithQRValue(25807, '1')
sm.resetStats()
sm.addSP(5, True)
sm.giveSkill(60011216, 1,... |
def tabuada(num):
for x in range (11):
print(num*x)
num = int(input('Digite um valor: '))
tabuada(num)
| def tabuada(num):
for x in range(11):
print(num * x)
num = int(input('Digite um valor: '))
tabuada(num) |
class Environment:
def __init__(self, rows, columns, turns, drones_count, drone_max_payload):
self.rows = rows
self.columns = columns
self.turns = turns
self.drones_count = drones_count
self.drone_max_payload = drone_max_payload
| class Environment:
def __init__(self, rows, columns, turns, drones_count, drone_max_payload):
self.rows = rows
self.columns = columns
self.turns = turns
self.drones_count = drones_count
self.drone_max_payload = drone_max_payload |
class DeviceInfo(object):
"""Device Info class"""
@staticmethod
def get_serial():
# Extract serial from cpuinfo file
cpuserial = "0000000000000000"
try:
f = open('/proc/cpuinfo','r')
for line in f:
if line[0:6]=='Serial':
c... | class Deviceinfo(object):
"""Device Info class"""
@staticmethod
def get_serial():
cpuserial = '0000000000000000'
try:
f = open('/proc/cpuinfo', 'r')
for line in f:
if line[0:6] == 'Serial':
cpuserial = line[10:26]
f.clo... |
# Time: O(nlog*n) ~= O(n), n is the length of the positions
# Space: O(n)
# In this problem, a rooted tree is a directed graph such that,
# there is exactly one node (the root) for
# which all other nodes are descendants of this node, plus every node has exactly one parent,
# except for the root node which has no par... | class Unionfind(object):
def __init__(self, n):
self.set = range(n)
self.count = n
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x])
return self.set[x]
def union_set(self, x, y):
(x_root, y_root) = map(self.find_set, (... |
f1 = open("slurm-3101.out", 'r')
lines = f1.readlines()
count = 0
d = {}
for line in lines:
s = line.split(' + ')
s.remove('\n')
print(s)
count += 1
for x in s:
s1 = x.split('A^')
if (float(s1[0]) != 0 or int(s1[1]) != 0):
print(s1)
res = d.get(int(s1[1]))
... | f1 = open('slurm-3101.out', 'r')
lines = f1.readlines()
count = 0
d = {}
for line in lines:
s = line.split(' + ')
s.remove('\n')
print(s)
count += 1
for x in s:
s1 = x.split('A^')
if float(s1[0]) != 0 or int(s1[1]) != 0:
print(s1)
res = d.get(int(s1[1]))
... |
input = """
bk(a,b).
bk(b,c).
bk(m,m).
bk(x,y).
"""
output = """
bk(a,b).
bk(b,c).
bk(m,m).
bk(x,y).
"""
| input = '\nbk(a,b).\nbk(b,c).\nbk(m,m).\nbk(x,y).\n'
output = '\nbk(a,b).\nbk(b,c).\nbk(m,m).\nbk(x,y).\n' |
#recursive factorial
def factorial(n):
if (n == 0):
return 1
else:
return n * factorial(n - 1)
#iterative factorial
def factorial(n):
total = 1
for i in range(1,n+1,1):
total *= i
return total
#recursive greatest common divisor
def gcd(a,b):
if (b == 0):
return ... | def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def factorial(n):
total = 1
for i in range(1, n + 1, 1):
total *= i
return total
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def gcd_bad(a, b):
while b != ... |
# Extended Euclid's Algorithm for Modular Multiplicative Inverse
def euclidean_mod_inverse(a, b):
temp = b
# Initialize variables
t1, t2 = 0, 1
if b == 1:
return 0
# Perform extended Euclid's algorithm until a > 1
while a > 1:
quotient, remainder = divmod(a, b)
a, b = ... | def euclidean_mod_inverse(a, b):
temp = b
(t1, t2) = (0, 1)
if b == 1:
return 0
while a > 1:
(quotient, remainder) = divmod(a, b)
(a, b) = (b, remainder)
(t1, t2) = (t2 - t1 * quotient, t1)
if t2 < 0:
t2 += temp
return t2
if __name__ == '__main__':
num... |
"""
Given the array nums, obtain a subsequence of the array whose sum of
elements is strictly greater than the sum of the non included elements in
such subsequence.
If there are multiple solutions, return the subsequence with minimum size
and if there still exist multiple solutions, return the ... | """
Given the array nums, obtain a subsequence of the array whose sum of
elements is strictly greater than the sum of the non included elements in
such subsequence.
If there are multiple solutions, return the subsequence with minimum size
and if there still exist multiple solutions, return the ... |
budget = float(input("Enter the budget: "))
amount_of_video_card = int(input("Enter the number of video cards: "))
amount_of_processor = int(input("Enter the number of processors: "))
amount_of_ram_memory = int(input("Enter the number of ram memory: "))
video_card_price_per_one = 250
video_card_total_price = amount_of... | budget = float(input('Enter the budget: '))
amount_of_video_card = int(input('Enter the number of video cards: '))
amount_of_processor = int(input('Enter the number of processors: '))
amount_of_ram_memory = int(input('Enter the number of ram memory: '))
video_card_price_per_one = 250
video_card_total_price = amount_of_... |
pysmt_op = ["forall", "exists", "and", "or", "not", "=>", "iff", "symbol", "function", "real_constant", "bool_constant",
"int_constant", "str_constant", "+", "-", "*", "<=", "<", "=", "ite", "toreal", "bv_constant", "bvnot", "bvand",
"bvor", "bvxor", "concat", "extract", "bvult", "bvule", "bvneg", "bvadd", ... | pysmt_op = ['forall', 'exists', 'and', 'or', 'not', '=>', 'iff', 'symbol', 'function', 'real_constant', 'bool_constant', 'int_constant', 'str_constant', '+', '-', '*', '<=', '<', '=', 'ite', 'toreal', 'bv_constant', 'bvnot', 'bvand', 'bvor', 'bvxor', 'concat', 'extract', 'bvult', 'bvule', 'bvneg', 'bvadd', 'bvsub', 'bv... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def main():
x = 0
for n in range(1, 1000):
if n % 3 == 0:
x += n
eli... | """
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def main():
x = 0
for n in range(1, 1000):
if n % 3 == 0:
x += n
elif n % 5 == 0:
... |
"""
limis core - environment
Environment variables set for a project.
"""
LIMIS_PROJECT_NAME_ENVIRONMENT_VARIABLE = 'LIMIS_PROJECT_NAME'
LIMIS_PROJECT_SETTINGS_ENVIRONMENT_VARIABLE = 'LIMIS_PROJECT_SETTINGS'
| """
limis core - environment
Environment variables set for a project.
"""
limis_project_name_environment_variable = 'LIMIS_PROJECT_NAME'
limis_project_settings_environment_variable = 'LIMIS_PROJECT_SETTINGS' |
class CyclicQ(object):
'''
Queue.
read parameter is next scheduled for dequeue, write parameter is
most recently queued.
'''
def __init__(self, length):
self.width = length
self.length = 0
self.array = [None] * length
self.read = 0
self.write = -1
... | class Cyclicq(object):
"""
Queue.
read parameter is next scheduled for dequeue, write parameter is
most recently queued.
"""
def __init__(self, length):
self.width = length
self.length = 0
self.array = [None] * length
self.read = 0
self.write = -1
... |
########################################################
# Copyright (c) 2015-2017 by European Commission. #
# All Rights Reserved. #
########################################################
extends("BaseKPI.py")
"""
Marginal costs statistics (euro/MWh)
---------------------------... | extends('BaseKPI.py')
'\nMarginal costs statistics (euro/MWh)\n-------------------------------------\n\nIndexed by\n\t* scope\n\t* delivery point\n\t* energy (electricity, reserve or gas)\n\t* test case\n\t* statistics (min, max, average or demand average)\n\nComputes the minimum, maximum and average value of the margi... |
def response_json(target):
def decorator(*args, **kwargs):
response = target(*args, **kwargs)
# TODO: you can add your error handling in here
return response.json()
return decorator
| def response_json(target):
def decorator(*args, **kwargs):
response = target(*args, **kwargs)
return response.json()
return decorator |
NON_CORE_DEPDENDENT_TASKS_FIRST_PRIORITY = 9999
# MessageProcessor
# priority constants for message processors between modules
ASSETS_PRIORITY_PARSE_ISSUANCE = NON_CORE_DEPDENDENT_TASKS_FIRST_PRIORITY - 0
ASSETS_PRIORITY_PARSE_DESTRUCTION = NON_CORE_DEPDENDENT_TASKS_FIRST_PRIORITY - 1
ASSETS_PRIORITY_BALANCE_CHANGE =... | non_core_depdendent_tasks_first_priority = 9999
assets_priority_parse_issuance = NON_CORE_DEPDENDENT_TASKS_FIRST_PRIORITY - 0
assets_priority_parse_destruction = NON_CORE_DEPDENDENT_TASKS_FIRST_PRIORITY - 1
assets_priority_balance_change = NON_CORE_DEPDENDENT_TASKS_FIRST_PRIORITY - 2
dex_priority_parse_tradebook = NON_... |
#coding: utf8
def get_data_by_binary_search(target, source_list):
min=0
max=len(source_list)-1
while min<=max:
mid=(min+max)//2
if source_list[mid]==target:
return mid
if source_list[mid]>target:
max=mid-1
else:
min=mid+1
if __name__==... | def get_data_by_binary_search(target, source_list):
min = 0
max = len(source_list) - 1
while min <= max:
mid = (min + max) // 2
if source_list[mid] == target:
return mid
if source_list[mid] > target:
max = mid - 1
else:
min = mid + 1
if __n... |
# -*- coding: utf-8 -*-
"""Binary Search.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1pgYTs84FYj7s3soy6YSyOLeeo6y34p0U
"""
def binary_search(arr, target):
first = 0
last = len(arr)-1
found = False
while first <= last and not found:
... | """Binary Search.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1pgYTs84FYj7s3soy6YSyOLeeo6y34p0U
"""
def binary_search(arr, target):
first = 0
last = len(arr) - 1
found = False
while first <= last and (not found):
mid = ... |
# # WAP accept a number and check even or odd..
number = int(input("Enter number: "))
if(number == 0):
print("Zero")
elif(number % 2 == 0):
print("Even")
else:
print("Odd")
# # WAP accept three subject marks . Calculate % marks. and display grade as per following condition...
# # 80 - 100 > A... ..... 60... | number = int(input('Enter number: '))
if number == 0:
print('Zero')
elif number % 2 == 0:
print('Even')
else:
print('Odd')
marks1 = float(input('Enter marks for subject 1: '))
marks2 = float(input('Enter marks for subject 2: '))
marks3 = float(input('Enter marks for subject 3: '))
percent = (marks1 + marks2... |
pizzas = ['hawaiian', 'pepperoni', 'margherita']
friend_pizzas = pizzas[:]
pizzas.append('marinara')
friend_pizzas.append('vegetariana')
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
print(pizza) | pizzas = ['hawaiian', 'pepperoni', 'margherita']
friend_pizzas = pizzas[:]
pizzas.append('marinara')
friend_pizzas.append('vegetariana')
print('My favorite pizzas are:')
for pizza in pizzas:
print(pizza)
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
print(pizza) |
#
# PySNMP MIB module DOCS-IETF-BPI2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-IETF-BPI2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:43:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
grid = []
n = int(raw_input())
for i in range(n):
arr = []
s = raw_input()
for j in range(n):
arr.append(s[j])
grid.append(arr)
status = True
for i in range(n):
b = 0
c = 0
lastChar = ' '
lastCount = 0
for x in range(n):
if grid[x][i] == 'B': b += 1
else: c +=... | grid = []
n = int(raw_input())
for i in range(n):
arr = []
s = raw_input()
for j in range(n):
arr.append(s[j])
grid.append(arr)
status = True
for i in range(n):
b = 0
c = 0
last_char = ' '
last_count = 0
for x in range(n):
if grid[x][i] == 'B':
b += 1
... |
#This is a simple class definition to hold information about each judge. Is used by other files, and is not to be run directly.
class judge(object):
#initialized using a "line". This should be a line from the .csv file produced by judgeMetaDataExtractor.py
def __init__(self,line):
parts = line.strip().spl... | class Judge(object):
def __init__(self, line):
parts = line.strip().split(',')
self.circuit = parts[1]
self.start = int(parts[3])
self.end = int(parts[4])
self.party = parts[2]
self.fullName = parts[0]
self.lastName = parts[0].split('<')[0].lower()
se... |
USER_CREDENTIALS = [
("user1", "user1@example.com", "pass1"),
("user2", "user2@example.com", "pass2"),
("user3", "user3@example.com", "pass3"),
("user4", "user4@example.com", "pass4"),
("user5", "user5@example.com", "pass5")
] | user_credentials = [('user1', 'user1@example.com', 'pass1'), ('user2', 'user2@example.com', 'pass2'), ('user3', 'user3@example.com', 'pass3'), ('user4', 'user4@example.com', 'pass4'), ('user5', 'user5@example.com', 'pass5')] |
def _compute_lcs(source, target):
"""Computes the Longest Common Subsequence (LCS).
Description of the dynamic programming algorithm:
https://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
source: List of source tokens.
target: List of target tokens.
Returns:
List ... | def _compute_lcs(source, target):
"""Computes the Longest Common Subsequence (LCS).
Description of the dynamic programming algorithm:
https://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
source: List of source tokens.
target: List of target tokens.
Returns:
List of tokens i... |
##defines
SWARM = ["SeqSwarm", "PyramidSwarm", "RingSwarm", "LocalSwarm"]
FUNCTION = ["Sphere", "Rastrigin", "Rosenbrock", "Schaffer", "Griewank","Ackley", "Schwefel", "Levy No.5"]
DISPLAYDIGITS = 3
##end defines
class PsoParameter:
steps = 0
stepwidth = 1
runs = 0
#the actual settings for the batch r... | swarm = ['SeqSwarm', 'PyramidSwarm', 'RingSwarm', 'LocalSwarm']
function = ['Sphere', 'Rastrigin', 'Rosenbrock', 'Schaffer', 'Griewank', 'Ackley', 'Schwefel', 'Levy No.5']
displaydigits = 3
class Psoparameter:
steps = 0
stepwidth = 1
runs = 0
param = []
logdir = ''
attributeslist = []
attri... |
a, b, c, d, e, f, g, h = '00000000'
cell = ''
with open(input('What file to execute?> '), 'r') as F:
for row in F:
for x in str(row):
if x == '!':
if cell == '': cell = 'a'
elif 'a' <= cell <= 'g': cell = chr(ord(cell) + 1)
elif cell == 'h': cell = ''
if x == '?':... | (a, b, c, d, e, f, g, h) = '00000000'
cell = ''
with open(input('What file to execute?> '), 'r') as f:
for row in F:
for x in str(row):
if x == '!':
if cell == '':
cell = 'a'
elif 'a' <= cell <= 'g':
cell = chr(ord(cell) + 1... |
# noinspection SpellCheckingInspection
"""
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number
of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code tha... | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number
of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conv... |
person = {
"first_name": "Bob",
"last_name": "Smith"
}
# for key in person:
# print(key)
# for key in person.keys():
# print(key)
# for value in person.values():
# print(value)
# for key, value in person.items():
# print(key, value)
the_keys = person.keys()
person["age"] = 23
print(the_ke... | person = {'first_name': 'Bob', 'last_name': 'Smith'}
the_keys = person.keys()
person['age'] = 23
print(the_keys) |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 10:24:30 2020
@author: roger luo
"""
def example():
"""show example code
Returns
-------
None.
Example
--------
>>> 1+2
3
>>> d = sum([1,2,3])
>>>
pd.Series([1,2,3])
Out[15]:
0 1
1 2
2 3
d... | """
Created on Wed Sep 2 10:24:30 2020
@author: roger luo
"""
def example():
"""show example code
Returns
-------
None.
Example
--------
>>> 1+2
3
>>> d = sum([1,2,3])
>>>
pd.Series([1,2,3])
Out[15]:
0 1
1 2
2 3
dtype: int64
""" |
WELCOME_BRIEF = "Configures welcoming people to the server."
WELCOME_DESCRIPTION = "Configures welcoming people to the server, what channel it occurs and, and what welcome " \
"messages are sent."
WELCOME_INFO_BRIEF = "Lists basic Welcome info for this server."
WELCOME_ENABLE_BRIEF = "Enables Welc... | welcome_brief = 'Configures welcoming people to the server.'
welcome_description = 'Configures welcoming people to the server, what channel it occurs and, and what welcome messages are sent.'
welcome_info_brief = 'Lists basic Welcome info for this server.'
welcome_enable_brief = 'Enables Welcomes for this server.'
welc... |
def thread_colorize(area, lexer, theme, index, stopindex):
for pos, token, value in lexer.get_tokens_unprocessed(area.get(index, stopindex)):
area.tag_add(str(token), '%s +%sc' % (index, pos),
'%s +%sc' % (index, pos + len(value)))
yield
def matrix_step(map):
count, offse... | def thread_colorize(area, lexer, theme, index, stopindex):
for (pos, token, value) in lexer.get_tokens_unprocessed(area.get(index, stopindex)):
area.tag_add(str(token), '%s +%sc' % (index, pos), '%s +%sc' % (index, pos + len(value)))
yield
def matrix_step(map):
(count, offset) = (0, 0)
for ... |
#!/usr/bin/env python3
def solution(array):
"""
Finds the number of combinations (ai, aj), given:
- ai == 0
- aj == 1
- j > i
Time Complexity: O(n), as we go through the array only once (in reverse order)
Space Complexity O(1), as we store three variables and create one iterator
"""
... | def solution(array):
"""
Finds the number of combinations (ai, aj), given:
- ai == 0
- aj == 1
- j > i
Time Complexity: O(n), as we go through the array only once (in reverse order)
Space Complexity O(1), as we store three variables and create one iterator
"""
result = 0
count ... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'ACCEPTING COMMA ENVIRONMENT EQUALS FILE INCLUDE INPUTS INPUT_ENABLED INPUT_STATES LEFT_BRACE LEFT_BRACKET LEFT_PAREN LIVENESS NAME OUTPUTS OUTPUT_STATES PROCESS RECEIVE... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'ACCEPTING COMMA ENVIRONMENT EQUALS FILE INCLUDE INPUTS INPUT_ENABLED INPUT_STATES LEFT_BRACE LEFT_BRACKET LEFT_PAREN LIVENESS NAME OUTPUTS OUTPUT_STATES PROCESS RECEIVE RIGHT_BRACE RIGHT_BRACKET RIGHT_PAREN SAFETY SEND STATES STRONG_FAIRNESS STRONG_NON_BLOCKINGa... |
#1. get input
#2. store each character into an array
#3. convert to ascii
#4. change even to odd and odd to even
#5. convert from ascii to char
#6. convert array to string
#7. print string
#1
"""
print("#1")
text = input("Enter text for encryption or decryption")
#2
print("#2")
letters = []
character = text.split()
fo... | """
print("#1")
text = input("Enter text for encryption or decryption")
#2
print("#2")
letters = []
character = text.split()
for character in text:
print(character)
letters.append(character)
#3
print("#3")
i=0
while(i<len(letters)):
letters[i] = ord(letters[i])
print(letters[i])
i += 1
#4
print("... |
# Class Hero, containig all the
# current information about the hero
class Hero:
"""Hero"""
def __init__(self, health=100, magic=0):
self.health = health
self.magic = magic
self.x = None
self.y = None
def printH(self):
print('Health: {0}, Magic: ... | class Hero:
"""Hero"""
def __init__(self, health=100, magic=0):
self.health = health
self.magic = magic
self.x = None
self.y = None
def print_h(self):
print('Health: {0}, Magic: {1}, X: {2}, Y: {3}'.format(self.health, self.magic, self.x, self.y))
def set_healt... |
class Heap:
def __init__(self,maxSize):
self.heapList = (maxSize+1)*[None]
self.heapSize = 0
self.maxSize = maxSize
def __str__(self):
return str(self.heapList)
def size(self,root):
return root.heapSize
def peek(self,root):
if root.heapList[... | class Heap:
def __init__(self, maxSize):
self.heapList = (maxSize + 1) * [None]
self.heapSize = 0
self.maxSize = maxSize
def __str__(self):
return str(self.heapList)
def size(self, root):
return root.heapSize
def peek(self, root):
if root.heapList[1] =... |
class Lock:
def __init__(self):
self.locked = False
def lock(self, msg):
assert not self.locked, msg
self.locked = True
def unlock(self):
self.locked = False | class Lock:
def __init__(self):
self.locked = False
def lock(self, msg):
assert not self.locked, msg
self.locked = True
def unlock(self):
self.locked = False |
# Author: Luka Maletin
class GraphError(Exception):
pass
class Graph(object):
class Vertex(object):
def __init__(self, x):
self._element = x
def element(self):
return self._element
def __hash__(self):
return hash(id(self))
class Edge(object)... | class Grapherror(Exception):
pass
class Graph(object):
class Vertex(object):
def __init__(self, x):
self._element = x
def element(self):
return self._element
def __hash__(self):
return hash(id(self))
class Edge(object):
def __init__(... |
def add(*lists_of_numbers):
lengths = set(tuple(tuple(len(sublist) for sublist in outer_list) for outer_list in lists_of_numbers))
if len(lengths) != 1:
raise ValueError
return [[sum(p) for p in zip(*sublists)] for sublists in zip(*lists_of_numbers)]
| def add(*lists_of_numbers):
lengths = set(tuple((tuple((len(sublist) for sublist in outer_list)) for outer_list in lists_of_numbers)))
if len(lengths) != 1:
raise ValueError
return [[sum(p) for p in zip(*sublists)] for sublists in zip(*lists_of_numbers)] |
# 8zxx xxxx - Mobile, Data Services, New Numbers and Prepaid Numbers
# 9yxx xxxx - Mobile, Data Services and Pager (until May 2012)
# x denotes 0 to 9
# y denotes 0 to 8 only
# z denotes 1 to 8 only
min8range = 81000000
max8range = 88000000
min9range = 90000000
max9range = 98000000
eight = []
for i ... | min8range = 81000000
max8range = 88000000
min9range = 90000000
max9range = 98000000
eight = []
for i in range(min8range, max8range):
eight.append(i)
print('appended')
nine = []
for i in range(min9range, max9range):
nine.append(i)
print('appended')
def printnumbers():
return nine
return eight
pr... |
"""
A file containing validator functions to make sure
the input from SQS Message is correct.
Every function follows the logic of checking the values and
returning True or False depending on whether or not they are correct.
"""
supported_input_formats = [
"WAV",
"FLAC",
"MP3",
"AIFF",
"AAC",
"... | """
A file containing validator functions to make sure
the input from SQS Message is correct.
Every function follows the logic of checking the values and
returning True or False depending on whether or not they are correct.
"""
supported_input_formats = ['WAV', 'FLAC', 'MP3', 'AIFF', 'AAC', 'OGG', 'OPUS', 'WMA', 'FLV'... |
if True:
print("It's IF!!!")
while True:
print("It's WHILE!!!") | if True:
print("It's IF!!!")
while True:
print("It's WHILE!!!") |
POSTS = [
[
'Microsoft Is Hiring!',
'We are looking for a delivry driver to work at our Haifa office',
'Bill Gates',
True,
'Delivery driver',
],
[
'Apple Is Hiring!',
'We are looking for a web developer to work at our Tel Aviv office',
'Tim Coo... | posts = [['Microsoft Is Hiring!', 'We are looking for a delivry driver to work at our Haifa office', 'Bill Gates', True, 'Delivery driver'], ['Apple Is Hiring!', 'We are looking for a web developer to work at our Tel Aviv office', 'Tim Cook', True, 'Web developer'], ['Microsoft Is Hiring!', 'We are looking for a graphi... |
class TextureNodeTexBlend:
pass
| class Texturenodetexblend:
pass |
num1=10
num2=20
num3=30
num4=40
| num1 = 10
num2 = 20
num3 = 30
num4 = 40 |
# lc643.py
# LeetCode 643. Maximum Average Subarray I `E`
# 1sk | 98% | 9'
# A~0g17
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
maxsum = cursum = sum(nums[0:k])
for i in range(len(nums)-k):
cursum += nums[i+k] - nums[i]
maxsum = max(cursum, m... | class Solution:
def find_max_average(self, nums: List[int], k: int) -> float:
maxsum = cursum = sum(nums[0:k])
for i in range(len(nums) - k):
cursum += nums[i + k] - nums[i]
maxsum = max(cursum, maxsum)
return maxsum / k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.