content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def getHappyString(self, n: int, k: int) -> str:
base = 1 << (n - 1)
if k > 3 * base:
return ''
table = {'a': 'bc', 'b': 'ac', 'c': 'ab'}
k -= 1
index, k = divmod(k, base)
result = chr(ord('a') + index)
base >>= 1
while base... | class Solution:
def get_happy_string(self, n: int, k: int) -> str:
base = 1 << n - 1
if k > 3 * base:
return ''
table = {'a': 'bc', 'b': 'ac', 'c': 'ab'}
k -= 1
(index, k) = divmod(k, base)
result = chr(ord('a') + index)
base >>= 1
while b... |
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. #
#----------------------------------------... | """ Module containing metaclasses which are useful for the rest of pyccel
"""
__all__ = ('Singleton', 'ArgumentSingleton')
class Singleton(type):
""" Indicates that there is only one instance of the class
"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
... |
"""
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Runtime: 40 ms, faster than 84.44% of Python3 online submissions for Find the Difference.
Memory Usage: 13... | """
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Runtime: 40 ms, faster than 84.44% of Python3 online submissions for Find the Difference.
Memory Usage: 13... |
VARIABLE_STATIC_LENGTH = 5
TYPE_STRING = 1
TYPE_INT = 2
| variable_static_length = 5
type_string = 1
type_int = 2 |
def say_hello(name="world"):
print("hello " + name + "!")
say_hello()
| def say_hello(name='world'):
print('hello ' + name + '!')
say_hello() |
def upper_filename_before_dot(file):
name, dot, format = file.name.rpartition('.')
if len(name) > 4:
return f'{name[:-5]}/{name[-4:].upper()}{dot}{format}'
return f'{name.upper()}{dot}{format}'
def parse_filename(instance):
dir, slash, name = instance.file.name.rpartition('/')
name, dot, f... | def upper_filename_before_dot(file):
(name, dot, format) = file.name.rpartition('.')
if len(name) > 4:
return f'{name[:-5]}/{name[-4:].upper()}{dot}{format}'
return f'{name.upper()}{dot}{format}'
def parse_filename(instance):
(dir, slash, name) = instance.file.name.rpartition('/')
(name, do... |
""" This file is create and managed by Tahir Iqbal
----------------------------------------------
It can be use only for education purpose
"""
# Value vs Reference type Functions
# Value Type
print('*Value Type*')
num = 100
def change_num(n):
n += 100
print('Inner num : ', n)
change_num(num)
print(... | """ This file is create and managed by Tahir Iqbal
----------------------------------------------
It can be use only for education purpose
"""
print('*Value Type*')
num = 100
def change_num(n):
n += 100
print('Inner num : ', n)
change_num(num)
print('Outer num : ', num)
print('\n*Reference Type*')
l... |
""" helper functions """
def title_to_slug(title: str) -> str:
"""
:param title: (str) e.g. 'A Very Good Book'
:return: (str) 'a-very-good-book'
"""
return '-'.join(title.lower().split()) | """ helper functions """
def title_to_slug(title: str) -> str:
"""
:param title: (str) e.g. 'A Very Good Book'
:return: (str) 'a-very-good-book'
"""
return '-'.join(title.lower().split()) |
def int_diff(arr, n):
num=0
for i in range(len(arr)):
for j in range(i+1,len(arr)):
if abs(arr[i]-arr[j])==n:
num+=1
return num | def int_diff(arr, n):
num = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if abs(arr[i] - arr[j]) == n:
num += 1
return num |
# -*- coding: utf-8 -*-
LANGUAGES = [
'english',
'polish',
'german',
]
| languages = ['english', 'polish', 'german'] |
"""
LeetCode Problem: 40. Combination Sum II
Link: https://leetcode.com/problems/combination-sum-ii/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(2^N)
Space Complexity: O(N)
"""
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candida... | """
LeetCode Problem: 40. Combination Sum II
Link: https://leetcode.com/problems/combination-sum-ii/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(2^N)
Space Complexity: O(N)
"""
class Solution:
def combination_sum2(self, candidates: List[int], target: int) -> List[List[int]]:
candi... |
# This Python program displays ASCII art
#
# by Aleksander Rohozinski
# Febuary 14, 2022
# ICS 2O - Ashbury College
# Mr. Giansante
# -------------------------------------------------------
print(" _ _ _ _ _ _ _ _ ")
print("| | | | | | | | | ... | print(' _ _ _ _ _ _ _ _ ')
print('| | | | | | | | | | | | | | |')
print('| |_| | ___| | | ___ | | | | ___ _ __| | __| |')
print("| _ |/ _ \\ | |/ _ \\ | |/\\| |/ _ \\| '__| |/ _` |")
print('| | | | __/ | | (_) | \\ /\\ / (_) | | | | (_| |')
print('\\_| |_... |
__all__ = [
'GENERAL_SETTINGS_FILE',
'GUL_INPUT_FILES',
'GUL_SUMMARIES_FILE',
'INPUT_FILES',
'IL_INPUT_FILES',
'IL_SUMMARIES_FILE',
'MODEL_SETTINGS_FILE',
'OPTIONAL_INPUT_FILES',
'TAR_FILE'
]
INPUT_FILES = {
'complex_items': {'name': 'complex_items', 'type': 'gul', 'conversion_t... | __all__ = ['GENERAL_SETTINGS_FILE', 'GUL_INPUT_FILES', 'GUL_SUMMARIES_FILE', 'INPUT_FILES', 'IL_INPUT_FILES', 'IL_SUMMARIES_FILE', 'MODEL_SETTINGS_FILE', 'OPTIONAL_INPUT_FILES', 'TAR_FILE']
input_files = {'complex_items': {'name': 'complex_items', 'type': 'gul', 'conversion_tool': 'complex_itemtobin'}, 'items': {'name'... |
class BlackjackGameButtonView:
control_y_axis = 153
new_game_x_axis = 650
quit_x_axis = 760
control_button_width = 100
control_button_height = 40
| class Blackjackgamebuttonview:
control_y_axis = 153
new_game_x_axis = 650
quit_x_axis = 760
control_button_width = 100
control_button_height = 40 |
"""
https://www.hackerrank.com/challenges/2d-array/problem
"""
def main(arr):
max_so_far = -63 # Because 7 x 9 = 63
x = 1
y = 1
count = 0
while x <= 4:
y = 1
while y <= 4:
top = arr[x-1][y-1] + arr[x-1][y] + arr[x-1][y+1]
middle = arr[x][y]
bot... | """
https://www.hackerrank.com/challenges/2d-array/problem
"""
def main(arr):
max_so_far = -63
x = 1
y = 1
count = 0
while x <= 4:
y = 1
while y <= 4:
top = arr[x - 1][y - 1] + arr[x - 1][y] + arr[x - 1][y + 1]
middle = arr[x][y]
bottom = arr[x + ... |
def count_positives_sum_negatives(arr):
if not arr:
return []
pos = 0
neg = 0
for n in arr:
if n > 0:
pos = pos + 1
else:
neg = neg + n
return [pos, neg]
def count_positives_sum_negatives1(arr):
if not arr: return []
pos = 0
neg = 0
f... | def count_positives_sum_negatives(arr):
if not arr:
return []
pos = 0
neg = 0
for n in arr:
if n > 0:
pos = pos + 1
else:
neg = neg + n
return [pos, neg]
def count_positives_sum_negatives1(arr):
if not arr:
return []
pos = 0
neg = ... |
# -*- coding: utf-8 -*-
class Command(object):
def __init__(self, trigger):
self._trigger = trigger
def description(self, *args, **kwargs):
pass
def usage(self, *args, **kwargs):
pass
def run(self, *args, **kwargs):
pass
def trigger(self):
... | class Command(object):
def __init__(self, trigger):
self._trigger = trigger
def description(self, *args, **kwargs):
pass
def usage(self, *args, **kwargs):
pass
def run(self, *args, **kwargs):
pass
def trigger(self):
return self._trigger |
"""
Escrevendo um iterador customizado
"""
class Contador:
def __init__(self, menor, maior):
self.menor = menor
self.maior = maior
def __iter__(self):
return self
def __next__(self):
if self.menor < self.maior:
numero = self.menor
self.menor = s... | """
Escrevendo um iterador customizado
"""
class Contador:
def __init__(self, menor, maior):
self.menor = menor
self.maior = maior
def __iter__(self):
return self
def __next__(self):
if self.menor < self.maior:
numero = self.menor
self.menor = s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
S = str(input("What is your name?\n"))
print(S[::2])
print(S[2:8:-1]) | """
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
s = str(input('What is your name?\n'))
print(S[::2])
print(S[2:8:-1]) |
def get_num_teams(league_id='390.l.XXXXXX'):
url = 'https://fantasysports.yahooapis.com/fantasy/v2/leagues;league_keys={}'.format('390.l.227235')
response = oauth.session.get(url, params={'format': 'json'})
r = response.json()
return r['fantasy_content']['leagues']['0']['league'][0]['num_teams']
| def get_num_teams(league_id='390.l.XXXXXX'):
url = 'https://fantasysports.yahooapis.com/fantasy/v2/leagues;league_keys={}'.format('390.l.227235')
response = oauth.session.get(url, params={'format': 'json'})
r = response.json()
return r['fantasy_content']['leagues']['0']['league'][0]['num_teams'] |
# t > 25 >>>>> vay cheghad garmame!
# t < 15 >>>>> kapshen niyaz shodam man!
# ajab havaye mizuniye!
# temperature
print("***Temperature Checker***")
temperature = int(input("Enter Temperature: "))
if temperature > 25:
print("Weather is EXTREMLY HOT!")
elif temperature < 15:
print("I really need WARM cloth!")... | print('***Temperature Checker***')
temperature = int(input('Enter Temperature: '))
if temperature > 25:
print('Weather is EXTREMLY HOT!')
elif temperature < 15:
print('I really need WARM cloth!')
else:
print('Such a great WEATHER!!!') |
num1 = 19
num2 = 22
num6 = 9999
num3 = 666
num4 = 878
num8 = 10000
| num1 = 19
num2 = 22
num6 = 9999
num3 = 666
num4 = 878
num8 = 10000 |
# 0 1 1 2 3 5
def fibonacci(n):
if n == 0 or n == 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(5))
# Normal way to do fibonacci
class A:
def fibo(n):
f1 = 0
f2 = 1
test = ""
for i in range(1,n):
test = f1 + f2
f1 = f2
... | def fibonacci(n):
if n == 0 or n == 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(5))
class A:
def fibo(n):
f1 = 0
f2 = 1
test = ''
for i in range(1, n):
test = f1 + f2
f1 = f2
f2 = test
return tes... |
minimal_map ="""
<map version="freeplane 1.7.0">
<!--To view this file, download free mind mapping software Freeplane from http://freeplane.sourceforge.net -->
<node TEXT="new_mindmap" FOLDED="false" ID="ID_1723255651" CREATED="1283093380553" MODIFIED="1283093380553"><hook NAME="MapStyle">
<properties edgeColorConf... | minimal_map = '\n<map version="freeplane 1.7.0">\n<!--To view this file, download free mind mapping software Freeplane from http://freeplane.sourceforge.net -->\n<node TEXT="new_mindmap" FOLDED="false" ID="ID_1723255651" CREATED="1283093380553" MODIFIED="1283093380553"><hook NAME="MapStyle">\n <properties edgeColorC... |
'''
BGP Genie Ops Object Outputs for IOSXE.
'''
class BgpOutput(object):
show_bgp_all_summary = '''\
show bgp all summary
For address family: IPv4 Unicast
BGP router identifier 1.1.1.1, local AS number 65000
BGP table version is 4, main routing table version 4
3 network e... | """
BGP Genie Ops Object Outputs for IOSXE.
"""
class Bgpoutput(object):
show_bgp_all_summary = ' show bgp all summary\n For address family: IPv4 Unicast\n BGP router identifier 1.1.1.1, local AS number 65000\n BGP table version is 4, main routing table version 4\n 3 network ent... |
def count_substring(string, sub_string):
# there are two ways of acheieving it, as usual one we will put in comments.
# 1st method as suggested in concept of question
count = 0
#sub_string_len =len(sub_string) # Finding length of sub_string
#for i in range(0, len(string)): # Looping through string f... | def count_substring(string, sub_string):
count = 0
index_of_sub_string = string.find(sub_string)
while index_of_sub_string != -1:
count += 1
index_of_sub_string = string.find(sub_string, index_of_sub_string + 1)
return count
if __name__ == '__main__':
string = input().strip()
sub... |
"""
## Question : Medium
### 238. [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of
all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output:... | """
## Question : Medium
### 238. [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of
all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output:... |
#!/usr/bin/env python
"""Provides classes and algorithms for dealing with matrices.
"""
__all__ = ['distance']
__author__ = ""
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Greg Caporaso", "Rob Knight"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Greg Caporaso"
__email__ = ... | """Provides classes and algorithms for dealing with matrices.
"""
__all__ = ['distance']
__author__ = ''
__copyright__ = 'Copyright 2007-2012, The Cogent Project'
__credits__ = ['Greg Caporaso', 'Rob Knight']
__license__ = 'GPL'
__version__ = '1.5.3'
__maintainer__ = 'Greg Caporaso'
__email__ = 'caporaso@colorado.edu'
... |
number = int(input())
price = 5 * number
if number > 1:
price *= 0.9 # 10% discount
price *= 1.07 # Tax
print("%.2f" % price)
| number = int(input())
price = 5 * number
if number > 1:
price *= 0.9
price *= 1.07
print('%.2f' % price) |
# Map for SVG graphics from HTML
num_class = ['M8.954 30V3.545h-.267c-.738.41-6.706 4.655-7.71 5.311V5.883c.635-.41 6.767-4.758 7.977-5.476h2.789V30h-2.79z',
'M.12 9.57C.16 4.462 4.057.791 9.41.791c5.209 0 9.187 3.568 9.187 8.224 0 3.076-1.415 5.475-6.275 10.664l-7.998 8.53v.247h15.012V31H.284v-1.969L10.... | num_class = ['M8.954 30V3.545h-.267c-.738.41-6.706 4.655-7.71 5.311V5.883c.635-.41 6.767-4.758 7.977-5.476h2.789V30h-2.79z', 'M.12 9.57C.16 4.462 4.057.791 9.41.791c5.209 0 9.187 3.568 9.187 8.224 0 3.076-1.415 5.475-6.275 10.664l-7.998 8.53v.247h15.012V31H.284v-1.969L10.62 17.854c4.122-4.43 5.168-6.193 5.168-8.736 0-3... |
"""
Day 7 - Part 2
https://adventofcode.com/2021/day/7#part2
By NORXND @ 07.12.2021
(C) NORXND 2021 - Under The MIT License
"""
input_file = open('Day7/input.txt', 'r')
crab_positions = []
l = input_file.read().split(",")
for x in l:
crab_positions.append(int(x))
fuel_cost = {}
for dest in range(0, max(crab_p... | """
Day 7 - Part 2
https://adventofcode.com/2021/day/7#part2
By NORXND @ 07.12.2021
(C) NORXND 2021 - Under The MIT License
"""
input_file = open('Day7/input.txt', 'r')
crab_positions = []
l = input_file.read().split(',')
for x in l:
crab_positions.append(int(x))
fuel_cost = {}
for dest in range(0, max(crab_positi... |
class Constraint(object):
def __init__(self, parent, cat_constructor,*args):
self.parentsDict = parent
self.parent=parent[parent[-1]]
self.cat_constructor = cat_constructor
self.references = [i for i in args]
@property
def name(self):
return self.cat_const... | class Constraint(object):
def __init__(self, parent, cat_constructor, *args):
self.parentsDict = parent
self.parent = parent[parent[-1]]
self.cat_constructor = cat_constructor
self.references = [i for i in args]
@property
def name(self):
return self.cat_constructor.... |
# Run tests
if __name__ == '__main__':
print('Running all the tests...')
| if __name__ == '__main__':
print('Running all the tests...') |
class Maths(object):
MATHS_CLASS_MEMBER=0.1
def __init__(self, num):
self.maths_instance_member = num
def maths_instance_method(self):
print("Hello from instance method")
class MultipleArg(object):
def __init__(self, num, str, other = 0):
self.multipleArg_instance_member_num = num + other
s... | class Maths(object):
maths_class_member = 0.1
def __init__(self, num):
self.maths_instance_member = num
def maths_instance_method(self):
print('Hello from instance method')
class Multiplearg(object):
def __init__(self, num, str, other=0):
self.multipleArg_instance_member_num ... |
db_host="127.0.0.1"
db_port="3306"
db_user=""
db_pass=""
db_database=""
twitch_key=""
twitch_channel="" | db_host = '127.0.0.1'
db_port = '3306'
db_user = ''
db_pass = ''
db_database = ''
twitch_key = ''
twitch_channel = '' |
def valid_character(number):
return True if int(number) > 0 and int(number) < 27 else False
def solve(message):
if message == '':
return 1
else:
number_of_solutions = 0
if valid_character(message[:1]):
number_of_solutions += (solve(message[1:]))
if len(message... | def valid_character(number):
return True if int(number) > 0 and int(number) < 27 else False
def solve(message):
if message == '':
return 1
else:
number_of_solutions = 0
if valid_character(message[:1]):
number_of_solutions += solve(message[1:])
if len(message) > 1... |
def text_to_words(the_text):
""" return a list of words with all punctuation removed,
and all in lowercase.
"""
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these
... | def text_to_words(the_text):
""" return a list of words with all punctuation removed,
and all in lowercase.
"""
my_substitutions = the_text.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&()*+,-./:;<=>?@[]^_`{|}~\'\\', 'abcdefghijklmnopqrstuvwxyz ')
... |
# Function to to check null in dataset
def null_check(df):
for _ in df:
if None in df.isnull():
print("No Error")
else:
print("Error")
| def null_check(df):
for _ in df:
if None in df.isnull():
print('No Error')
else:
print('Error') |
class Solution:
def removeDuplicates(self, nums: [int]) -> int:
if len(nums) == 0:
return 0
order = 0
for i in range(1, len(nums)):
if nums[order] != nums[i]:
order += 1
nums[order] = nums[i]
return order + 1 | class Solution:
def remove_duplicates(self, nums: [int]) -> int:
if len(nums) == 0:
return 0
order = 0
for i in range(1, len(nums)):
if nums[order] != nums[i]:
order += 1
nums[order] = nums[i]
return order + 1 |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2021 Apple Inc. All Rights Reserved.
#
# Architecture parameters
DEFAULT_PARAMS = {
"epochs": 200,
"test_freq": 20,
"batch_size": 128,
"momentum": 0.9,
"weight_decay": 0.0005,
}
DEFAULT_IMAGENET_PARAMS = {
**DEFAULT_PARAMS,
"... | default_params = {'epochs': 200, 'test_freq': 20, 'batch_size': 128, 'momentum': 0.9, 'weight_decay': 0.0005}
default_imagenet_params = {**DEFAULT_PARAMS, 'epochs': 90, 'test_freq': 1, 'batch_size': 128, 'weight_decay': 5e-05}
vgg_imagenet_params = {**DEFAULT_IMAGENET_PARAMS, 'batch_size': 256}
def model_data_params(a... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | Test.Summary = '\nTest reloading ssl_multicert.config with errors and keeping around the old ssl config structure\n'
sni_domain = 'example.com'
ts = Test.MakeATSProcess('ts', command='traffic_manager', select_ports=True, enable_tls=True)
server = Test.MakeOriginServer('server')
server2 = Test.MakeOriginServer('server3'... |
class BaseError(Exception):
pass
class UserTokenRequiredError(BaseError):
pass
class XboxUserTokenRequiredError(BaseError):
pass
class XstsXboxTokenRequiredError(BaseError):
pass
class XstsHaloTokenRequiredError(BaseError):
pass
class SpartanTokenRequiredError(BaseError):
pass
class ... | class Baseerror(Exception):
pass
class Usertokenrequirederror(BaseError):
pass
class Xboxusertokenrequirederror(BaseError):
pass
class Xstsxboxtokenrequirederror(BaseError):
pass
class Xstshalotokenrequirederror(BaseError):
pass
class Spartantokenrequirederror(BaseError):
pass
class Cleara... |
class GrowthCalculator(object):
def __init__(self):
"""
Sets default values for the following instance variables:
Lotka-Volterra equation coefficients:
self.a - Growing rate of prey when there's no predators
self.b - Dying rate of prey due to predation
se... | class Growthcalculator(object):
def __init__(self):
"""
Sets default values for the following instance variables:
Lotka-Volterra equation coefficients:
self.a - Growing rate of prey when there's no predators
self.b - Dying rate of prey due to predation
s... |
a = input()
b = input()
x = min(len(a), len(b))
correct = []
for c in range(1, x+1):
if b.endswith(a[:c]):
correct.append(c)
if correct:
print(max(correct))
else:
print(0)
| a = input()
b = input()
x = min(len(a), len(b))
correct = []
for c in range(1, x + 1):
if b.endswith(a[:c]):
correct.append(c)
if correct:
print(max(correct))
else:
print(0) |
class ScriptError(Exception):
pass
class SheetsNotSelected(ScriptError):
pass
class ElemNotFound(ScriptError):
pass
| class Scripterror(Exception):
pass
class Sheetsnotselected(ScriptError):
pass
class Elemnotfound(ScriptError):
pass |
"""
Minion status monitoring
Maps to the `status` execution module.
"""
__monitor__ = [
"loadavg",
"process",
]
def loadavg(name, maximum=None, minimum=None):
"""
Return the current load average for the specified minion. Available values
for name are `1-min`, `5-min` and `15-min`. `minimum` and ... | """
Minion status monitoring
Maps to the `status` execution module.
"""
__monitor__ = ['loadavg', 'process']
def loadavg(name, maximum=None, minimum=None):
"""
Return the current load average for the specified minion. Available values
for name are `1-min`, `5-min` and `15-min`. `minimum` and `maximum` val... |
"""
Easy, Wayfair
You are given a 2 x N board, and instructed to completely cover the board with
the following shapes:
* Dominoes, or 2 x 1 rectangles.
* Trominoes, or L-shapes.
For example, if N = 4, here is one possible configuration, where A is a domino,
and B and C are trominoes.
```
A B B C
A B C C
```
Given ... | """
Easy, Wayfair
You are given a 2 x N board, and instructed to completely cover the board with
the following shapes:
* Dominoes, or 2 x 1 rectangles.
* Trominoes, or L-shapes.
For example, if N = 4, here is one possible configuration, where A is a domino,
and B and C are trominoes.
```
A B B C
A B C C
```
Given ... |
#All three functions
#repss the number of time and element appear
def count(s):
l1=[]
for i in s:
l1.append(i.lower())
a = [ord(x) for x in l1]
b = [(a.reps(x)) for x in a]
char = [x for x in s]
x = dict(zip(char,b))
return x
def count_list(string): #Works with lists
... | def count(s):
l1 = []
for i in s:
l1.append(i.lower())
a = [ord(x) for x in l1]
b = [a.reps(x) for x in a]
char = [x for x in s]
x = dict(zip(char, b))
return x
def count_list(string):
reps_l = [0 for i in range(ord('z') - ord('a') + 1)]
for char in string:
if char >... |
"""
Problem 3_1:
Write a function that reads a text file and counts the number of characters in
it. Print both the text file and the number of characters. Do this so that the
printout isn't doubled space (use an end="" argument in the print statement).
Also, skip a line before printing the count. Note that it is easy... | """
Problem 3_1:
Write a function that reads a text file and counts the number of characters in
it. Print both the text file and the number of characters. Do this so that the
printout isn't doubled space (use an end="" argument in the print statement).
Also, skip a line before printing the count. Note that it is easy... |
"""
File: caesar.py
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic sequence
ALPHABE... | """
File: caesar.py
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
"""
The prog... |
class TraceLogger( object ):
def __init__( self, name ):
self.name = name
def log( **kwargs ):
raise TypeError( "Abstract Method" )
| class Tracelogger(object):
def __init__(self, name):
self.name = name
def log(**kwargs):
raise type_error('Abstract Method') |
"""Helper classes for managing state"""
class GithubSearchContext():
"""Search Context class for manageing search state.
Parameters:
-----------
context = The name of the repo, org, or user you are searching
scope = {user, org, repo}
find = Text to find in the repo
replace_with = Replacement str... | """Helper classes for managing state"""
class Githubsearchcontext:
"""Search Context class for manageing search state.
Parameters:
-----------
context = The name of the repo, org, or user you are searching
scope = {user, org, repo}
find = Text to find in the repo
replace_with = Replacement str... |
def get_binary_nmubmer(decimal_number):
assert isinstance(decimal_number, int)
return bin(decimal_number)
print(get_binary_nmubmer("10"))
| def get_binary_nmubmer(decimal_number):
assert isinstance(decimal_number, int)
return bin(decimal_number)
print(get_binary_nmubmer('10')) |
"""
Adding a small value several times to a large value leads to an error.
Adding 10^-6 to 10^9 over 10^6 times and then subtracting 10^9.
Ideally the answer should be 1, but the program gives output as 0.9537
which is large error. Run the same program by replacing 10^9 with 1
The error becomes very tiny.
"""
big_num =... | """
Adding a small value several times to a large value leads to an error.
Adding 10^-6 to 10^9 over 10^6 times and then subtracting 10^9.
Ideally the answer should be 1, but the program gives output as 0.9537
which is large error. Run the same program by replacing 10^9 with 1
The error becomes very tiny.
"""
big_num =... |
r"""
Pore-scale models for calculating the conductance of conduits.
"""
__all__ = ["_poisson_conductance"]
def _poisson_conductance(target,
pore_conductivity=None,
throat_conductivity=None,
size_factors=None):
r"""
Calculates the condu... | """
Pore-scale models for calculating the conductance of conduits.
"""
__all__ = ['_poisson_conductance']
def _poisson_conductance(target, pore_conductivity=None, throat_conductivity=None, size_factors=None):
"""
Calculates the conductance of the conduits in the network, where a
conduit is (1/2 pore - full... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 8 16:07:04 2018
@author: wolfensb
"""
| """
Created on Tue May 8 16:07:04 2018
@author: wolfensb
""" |
x = 20
y = 30
print((x==25 and y==30))
print((x==25 or y==30))
print(not(x==25 or y==30))
print((not(x==25) and y==30)) | x = 20
y = 30
print(x == 25 and y == 30)
print(x == 25 or y == 30)
print(not (x == 25 or y == 30))
print(not x == 25 and y == 30) |
def contains_only_pdf(files):
file_paths = []
for file_path in files:
file_paths.append(file_path)
for file_path in file_paths:
pd = file_path.lower()[-4:-1]
if pd + 'f' != '.pdf':
return False
return True
| def contains_only_pdf(files):
file_paths = []
for file_path in files:
file_paths.append(file_path)
for file_path in file_paths:
pd = file_path.lower()[-4:-1]
if pd + 'f' != '.pdf':
return False
return True |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 28 09:04:40 2021
@author: zmg
"""
| """
Created on Fri May 28 09:04:40 2021
@author: zmg
""" |
"""
Ejercicio 4
Para tomar texto por consola se utiliza el comando: input()
Tome un nombre por consola y presente en pantalla de la consola
la oracion:
Hola nombre bienvenido!
"""
print(f"Ingrese su nombre:")
p = input()
print(f"Hola {p} bienvenido") | """
Ejercicio 4
Para tomar texto por consola se utiliza el comando: input()
Tome un nombre por consola y presente en pantalla de la consola
la oracion:
Hola nombre bienvenido!
"""
print(f'Ingrese su nombre:')
p = input()
print(f'Hola {p} bienvenido') |
myFile = open("system-charset.bin", "rb")
unshiftedFileBytes = myFile.read()
myFile.close()
myFile = open("system-charset-lower.bin", "rb")
shiftedFileBytes = myFile.read()
myFile.close()
asciiBytes = [0]*8*32 # control characters
asciiBytes += shiftedFileBytes[32*8:64*8] # punctuation and numbers
asciiBytes += ... | my_file = open('system-charset.bin', 'rb')
unshifted_file_bytes = myFile.read()
myFile.close()
my_file = open('system-charset-lower.bin', 'rb')
shifted_file_bytes = myFile.read()
myFile.close()
ascii_bytes = [0] * 8 * 32
ascii_bytes += shiftedFileBytes[32 * 8:64 * 8]
ascii_bytes += shiftedFileBytes[64 * 8:91 * 8]
ascii... |
# AISH AND XOR
N = int(input().strip())
Arr = [0] + [int(a) for a in input().strip().split()]
for i in range(int(input())):
q = [int(a) for a in input().strip().split()]
l = q[0]
r = q[1]
subArr = Arr[l:r+1]
subArr1 = subArr.count(1)
subArr0 = subArr.count(0)
ans = ""
if (subArr1)%2==0:... | n = int(input().strip())
arr = [0] + [int(a) for a in input().strip().split()]
for i in range(int(input())):
q = [int(a) for a in input().strip().split()]
l = q[0]
r = q[1]
sub_arr = Arr[l:r + 1]
sub_arr1 = subArr.count(1)
sub_arr0 = subArr.count(0)
ans = ''
if subArr1 % 2 == 0:
... |
class Email:
def __init__(self, subject: str = "None", plaintext: str = "None",
attachments: list = [],
from_address: str = None,
recipients: str = None, html: str = None):
self.subject = subject
self.plaintext = plaintext
self.attachments =... | class Email:
def __init__(self, subject: str='None', plaintext: str='None', attachments: list=[], from_address: str=None, recipients: str=None, html: str=None):
self.subject = subject
self.plaintext = plaintext
self.attachments = attachments
self.from_address = from_address
... |
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | hosts = ['root@192.168.100.17', 'root@192.168.100.18']
'\nworkspace configuration\n'
root_dir = '/home/paddle'
'\nnetwork configuration\n'
paddle_nic = 'eth0'
paddle_port = 7164
paddle_ports_num = 2
paddle_ports_num_for_sparse = 2
ld_library_path = '/usr/local/cuda/lib64:/usr/lib64' |
for count in range(1,10):
print(count)
print(count * count)
for letter in "coffee":
print(letter) | for count in range(1, 10):
print(count)
print(count * count)
for letter in 'coffee':
print(letter) |
class BaseHandler:
'''Abstract handler for send emails'''
def send_mail(self, message):
raise NotImplementedError('Not implemented in abstract class')
| class Basehandler:
"""Abstract handler for send emails"""
def send_mail(self, message):
raise not_implemented_error('Not implemented in abstract class') |
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '8/17/2020 3:31 PM'
class Solution:
def merge(self, nums1, m: int, nums2, n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if n != 0:
nums1[m:m + n] = nums2
... | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '8/17/2020 3:31 PM'
class Solution:
def merge(self, nums1, m: int, nums2, n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if n != 0:
nums1[m:m + n] = nums2
d... |
t = int(input())
while t:
t-=1
n = int(input())
print(n//2)
| t = int(input())
while t:
t -= 1
n = int(input())
print(n // 2) |
{
"targets": [
{
"target_name": "re2",
"sources": [
"lib/addon.cc",
"lib/new.cc",
"lib/exec.cc",
"lib/test.cc",
"lib/match.cc",
"lib/replace.cc",
"lib/search.cc",
"lib/split.cc",
"lib/to_string.cc",
"lib/accessors.cc",
... | {'targets': [{'target_name': 're2', 'sources': ['lib/addon.cc', 'lib/new.cc', 'lib/exec.cc', 'lib/test.cc', 'lib/match.cc', 'lib/replace.cc', 'lib/search.cc', 'lib/split.cc', 'lib/to_string.cc', 'lib/accessors.cc', 'lib/util.cc', 'vendor/re2/bitstate.cc', 'vendor/re2/compile.cc', 'vendor/re2/dfa.cc', 'vendor/re2/filter... |
# 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 constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
""... | class Solution(object):
def construct_maximum_binary_tree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums) == 0:
return None
max = 0
for i in range(len(nums)):
if nums[i] > nums[max]:
max = i
... |
Sbox =( 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
... | sbox = (99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26,... |
# 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
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if root == N... | class Solution:
def has_path_sum(self, root, sum):
if root == None:
return False
diff = sum - root.val
if root.left == None and root.right == None and (diff == 0):
return True
a = self.hasPathSum(root.left, diff)
b = self.hasPathSum(root.right, diff)
... |
def same_doc_as(source):
def wrapper(target):
target.__doc__ = source.__doc__
return target
return wrapper
| def same_doc_as(source):
def wrapper(target):
target.__doc__ = source.__doc__
return target
return wrapper |
""" This file creates a grid of stars for the HRD plot """
# use solar and low metallicity
metallicities = [0.0142, 0.001]
# circular binaries with a separation so wide that they are effectively single
eccentricity = 0.0
a = 1e20
with open("grid.txt", "w") as f:
# mass range: basically logspace from 0.5 to 50 bu... | """ This file creates a grid of stars for the HRD plot """
metallicities = [0.0142, 0.001]
eccentricity = 0.0
a = 1e+20
with open('grid.txt', 'w') as f:
masses = [0.5, 0.65, 0.8, 1.0, 1.3, 1.6, 2.0, 2.5, 3.2, 4.0, 5.2, 6.5, 8.2, 10.3, 13.0, 16.5, 21, 26, 33, 45, 65, 90, 115, 150]
grid_lines = ['--initial-mass-1... |
button_icon=b'''
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7E
AAAOxAGVKw4bAAABg0lEQVQ4jZ3TvWsVQRQF8N9bwhZiZWFlMQSxsFIEW9eY
gCEKIgj2IsFWwX9ALAQbOz/KlFZWIsjLFMFKgoSg2MgSgqBFCBIkDEEsdvZl
XJ4Wnmpn9pw7c+49MzJA29SncBvzmM3bWxjjWYjpY8kfFcIZPMRdzAwLZ/zC
U9wLMe1PCmTxS1z7i3CIt7gaYtqv8saDQryH7S... | button_icon = b'\n iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7E\n AAAOxAGVKw4bAAABg0lEQVQ4jZ3TvWsVQRQF8N9bwhZiZWFlMQSxsFIEW9eY\n gCEKIgj2IsFWwX9ALAQbOz/KlFZWIsjLFMFKgoSg2MgSgqBFCBIkDEEsdvZl\n XJ4Wnmpn9pw7c+49MzJA29SncBvzmM3bWxjjWYjpY8kfFcIZPMRdzAwLZ/zC\n U9wLMe1PCmTxS1z7i3CIt7gaYtqv8saDQr... |
"""
Given a string, find the length of the longest substring
without repeating characters.
"""
def longest_no_repeat(string: str) -> int:
"""Return longest length of a substring with no repeating characters."""
last_seen = {}
max_so_far = 0
current_streak = 0
for i, letter in enumerate(string):
... | """
Given a string, find the length of the longest substring
without repeating characters.
"""
def longest_no_repeat(string: str) -> int:
"""Return longest length of a substring with no repeating characters."""
last_seen = {}
max_so_far = 0
current_streak = 0
for (i, letter) in enumerate(string):
... |
ar = list(map(int, input().split()))
for i in range(len(ar)):
nr = ar[i]
is_top = True
for next_i in range (i +1, len(ar)):
next_nr = ar[next_i]
if nr <= next_nr:
is_top = False
break
if is_top:
print(nr, end = ' ') | ar = list(map(int, input().split()))
for i in range(len(ar)):
nr = ar[i]
is_top = True
for next_i in range(i + 1, len(ar)):
next_nr = ar[next_i]
if nr <= next_nr:
is_top = False
break
if is_top:
print(nr, end=' ') |
#!/usr/bin/env python
NAME = 'Armor Defense (Armor)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, page = r
# Armor reveals itself only in blockpage twice.
if any(i in page for i in (b'blocked by website protection from... | name = 'Armor Defense (Armor)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
(_, page) = r
if any((i in page for i in (b'blocked by website protection from Armor', b'please create an Armor support ticket'))):
return True
... |
__version__ = "0.1.1"
__author__ = "Arie Bovenberg"
__copyright__ = "2018, Arie Bovenberg"
__license__ = 'Apache 2.0'
__description__ = 'Capable GraphQL client'
| __version__ = '0.1.1'
__author__ = 'Arie Bovenberg'
__copyright__ = '2018, Arie Bovenberg'
__license__ = 'Apache 2.0'
__description__ = 'Capable GraphQL client' |
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
L = [None, None]
sorted_nums = sorted(nums)
prev = 0
for current in sorted_nums:
if current - prev == 1:
pass
elif current - prev == 0:
L[0] = current
... | class Solution:
def find_error_nums(self, nums: List[int]) -> List[int]:
l = [None, None]
sorted_nums = sorted(nums)
prev = 0
for current in sorted_nums:
if current - prev == 1:
pass
elif current - prev == 0:
L[0] = current
... |
'''
map loop
'''
def main():
a = {'x':100, 'y':200}
b = ''
c = 0
for key,value in a:
b += key
c += value
print( b )
print( c ) | """
map loop
"""
def main():
a = {'x': 100, 'y': 200}
b = ''
c = 0
for (key, value) in a:
b += key
c += value
print(b)
print(c) |
class Parameters:
def __init__(self, server: str, login: str, password: str, period: float):
self.server = server
self.login = login
self.password = password
self.period = period
@classmethod
def from_dict(cls, config: dict):
return cls(str(config['imap_server']),
... | class Parameters:
def __init__(self, server: str, login: str, password: str, period: float):
self.server = server
self.login = login
self.password = password
self.period = period
@classmethod
def from_dict(cls, config: dict):
return cls(str(config['imap_server']), s... |
#two dimentional lists
#inside number_grid list there are four elements which themselves are lists.
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
#prints the first index of the first array.
print(number_grid[0][0])
#prints the second index of the third array.
print(number_grid[2][1])
#how... | number_grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]
print(number_grid[0][0])
print(number_grid[2][1])
for row in number_grid:
for col in row:
print(col) |
my_dict = {"one":1, "two":2, "three":3}
print (my_dict)
print(len(my_dict))
if ("one" in my_dict):
print (my_dict["one"])
else:
print("nothing found")
| my_dict = {'one': 1, 'two': 2, 'three': 3}
print(my_dict)
print(len(my_dict))
if 'one' in my_dict:
print(my_dict['one'])
else:
print('nothing found') |
#!/usr/bin/python
def printme3( str ):
"This prints a passed string into this function"
print(str)
return
def printme3too( str ):
"This prints a passed string into this function"
print(str)
return
| def printme3(str):
"""This prints a passed string into this function"""
print(str)
return
def printme3too(str):
"""This prints a passed string into this function"""
print(str)
return |
'''
Accept a number and reverse it
account for leading zeros
'''
n=int(input("No.: "))
n=str(n)
w=''
'''
Using the opposite indexing
i.e. if s= '2 3 4'
then indices= -3 -2 -1
'''
for i in range(1,len(n)+1):
w+=n[-i]
n=''
print(int(w))
| """
Accept a number and reverse it
account for leading zeros
"""
n = int(input('No.: '))
n = str(n)
w = ''
"\nUsing the opposite indexing\ni.e. if s= '2 3 4'\nthen indices= -3 -2 -1\n"
for i in range(1, len(n) + 1):
w += n[-i]
n = ''
print(int(w)) |
# The name of the panel group to be added to HORIZON_CONFIG. Required.
PANEL_GROUP = 'second_panel_group'
# The display name of the PANEL_GROUP. Required.
PANEL_GROUP_NAME = 'Second Plugin Panel Group'
# The name of the dashboard the PANEL_GROUP associated with. Required.
PANEL_GROUP_DASHBOARD = 'admin'
| panel_group = 'second_panel_group'
panel_group_name = 'Second Plugin Panel Group'
panel_group_dashboard = 'admin' |
# Copyright (c) 2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
####### Expressions ########
class Expression:
'''Base class for expression node'''
pass
class OpExpression(Expression):
'... | class Expression:
"""Base class for expression node"""
pass
class Opexpression(Expression):
"""Operation"""
def __init__(self, op, args):
self.op = op
self.args = args
def __repr__(self):
return '%s(%s)' % (self.op, ', '.join((repr(s) for s in self.args)))
class Constante... |
list = \
[
unichr(79) + unichr(110) + unichr(32) + unichr(109) + unichr(121) + unichr(32) + unichr(119) + unichr(97) + unichr(121),
unichr(65) + unichr(108) + unichr(109) + unichr(111) + unichr(115) + unichr(116) + unichr(32) + unichr(104) + unichr(111) + unichr(109) + unichr(101),
unichr(73) + unichr(110) + uni... | list = [unichr(79) + unichr(110) + unichr(32) + unichr(109) + unichr(121) + unichr(32) + unichr(119) + unichr(97) + unichr(121), unichr(65) + unichr(108) + unichr(109) + unichr(111) + unichr(115) + unichr(116) + unichr(32) + unichr(104) + unichr(111) + unichr(109) + unichr(101), unichr(73) + unichr(110) + unichr(32) + ... |
def rabbit_fib(n, k, start):
if n == 0:
return 0
if n == 1:
return start
else:
return rabbit_fib(n - 1, k, start) + (k * rabbit_fib(n - 2, k, start))
print(rabbit_fib(5, 3, 1))
| def rabbit_fib(n, k, start):
if n == 0:
return 0
if n == 1:
return start
else:
return rabbit_fib(n - 1, k, start) + k * rabbit_fib(n - 2, k, start)
print(rabbit_fib(5, 3, 1)) |
#Clase Nodo
class Nodo:
def __init__(self, id):
self.id = id
self.grado=0
#Parametros algoritmo de dijkstra
self.padre=None
self.visitado=False
self.distancia=float('inf')
def __str__(self):
return str(self.id)
def __eq__(self, otroNodo):
return self.id == otroN... | class Nodo:
def __init__(self, id):
self.id = id
self.grado = 0
self.padre = None
self.visitado = False
self.distancia = float('inf')
def __str__(self):
return str(self.id)
def __eq__(self, otroNodo):
return self.id == otroNodo.id
def __lt__(se... |
"""
Question:
Valid parenthesis
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Performance:
1. Total Accepted: 71155 Total... | """
Question:
Valid parenthesis
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Performance:
1. Total Accepted: 71155 Total... |
class Parser:
def __init__(self, builtins):
self.builtins = builtins
def parse(self):
pass
def get_parser(self):
pass
| class Parser:
def __init__(self, builtins):
self.builtins = builtins
def parse(self):
pass
def get_parser(self):
pass |
"Este script es para saber que usuarios tengo definido"
"seria mi ""base de datos"" jaja"
class DatosUsuarios():
def leer_datos(self):
archivo = open("wsgi/module_login/usuarios", "r")
self.list_usuarios = []
self.list_password = []
self.list_permisos = []
for line in archivo.readlines():
... | """Este script es para saber que usuarios tengo definido"""
'seria mi base de datos jaja'
class Datosusuarios:
def leer_datos(self):
archivo = open('wsgi/module_login/usuarios', 'r')
self.list_usuarios = []
self.list_password = []
self.list_permisos = []
for line in archivo... |
'''
A dictionary that maps a file extension to its type.
'''
FILE_TYPES = {
"!BT": "Misc",
"!QB": "Misc",
"!SYNC": "Misc",
"!UT": "Misc",
"$$$": "Backup",
"$01": "Code",
"$DB": "Backup",
"$ER": "Database",
"0": "Compressed",
"00": "Game file",
"000": "Misc",
"001": "Back... | """
A dictionary that maps a file extension to its type.
"""
file_types = {'!BT': 'Misc', '!QB': 'Misc', '!SYNC': 'Misc', '!UT': 'Misc', '$$$': 'Backup', '$01': 'Code', '$DB': 'Backup', '$ER': 'Database', '0': 'Compressed', '00': 'Game file', '000': 'Misc', '001': 'Backup', '002': 'Backup', '003': 'Backup', '0CC': 'Aud... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
""" Describes cellular model for development purposes. """
__author__ = 'Ari Saha (arisaha@icloud.com)'
__date__ = 'Tuesday, March 6th 2018, 10:08:50 am'
| """ Describes cellular model for development purposes. """
__author__ = 'Ari Saha (arisaha@icloud.com)'
__date__ = 'Tuesday, March 6th 2018, 10:08:50 am' |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
class Suite:
def named_method(self):
return 0
named_method.benchmark_name = 'custom.track_method'
def named_function():
pass
named_function.benchmark_name = 'custom.time_function'
named_function.pretty_name = 'My Custom Function'... | class Suite:
def named_method(self):
return 0
named_method.benchmark_name = 'custom.track_method'
def named_function():
pass
named_function.benchmark_name = 'custom.time_function'
named_function.pretty_name = 'My Custom Function'
def track_custom_pretty_name():
return 42
track_custom_pretty_n... |
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# BFS, min minutes is how many level to reach the bottom
queue = collections.deque()
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 2:
... | class Solution:
def oranges_rotting(self, grid: List[List[int]]) -> int:
queue = collections.deque()
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 2:
queue.append((i, j, 0))
level = 0
while queue:
... |
# Time: O(n * 2^n)
# Space: O(n), longest possible path in tree, which is if all numbers are increasing.
class Solution(object):
def findSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def findSubsequencesHelper(nums, pos, seq, resul... | class Solution(object):
def find_subsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def find_subsequences_helper(nums, pos, seq, result):
if len(seq) >= 2:
result.append(list(seq))
lookup = set()
... |
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
self.reverseString1(s)
def reverseString1(self, s: List[str]) -> None:
end = len(s)
last_index = len(s) - 1
for offset in range(len(s... | class Solution:
def reverse_string(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
self.reverseString1(s)
def reverse_string1(self, s: List[str]) -> None:
end = len(s)
last_index = len(s) - 1
for offset in range(le... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.