content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class NasSourceThrottlingParams(object):
"""Implementation of the 'NasSourceThrottlingParams' model.
Specifies the NAS specific source throttling parameters during source
registration or during backup of the source.
Attributes:
max_para... | class Nassourcethrottlingparams(object):
"""Implementation of the 'NasSourceThrottlingParams' model.
Specifies the NAS specific source throttling parameters during source
registration or during backup of the source.
Attributes:
max_parallel_metadata_fetch_full_percentage (int): Specifies the
... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = "3.10"
_lr_method = "LALR"
_lr_signature = "A AFTER_TOMORROW AM AT BEFORE_YESTERDAY COLON DATE_END DAY MINUS MONTH NUMBER OF ON PAST_PHRASE PHRASE PLUS PM THE TIME TODAY TOMORROW WORD_NUMBER YEAR YESTERDAY\n da... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'A AFTER_TOMORROW AM AT BEFORE_YESTERDAY COLON DATE_END DAY MINUS MONTH NUMBER OF ON PAST_PHRASE PHRASE PLUS PM THE TIME TODAY TOMORROW WORD_NUMBER YEAR YESTERDAY\n date_object :\n date_object : date_list\n date_list : date_list date\n date_list : dat... |
def fakulteta(n):
if n == 0:
return 1
else:
return n * fakulteta(n - 1)
def vsota_stevk_fakultete(n):
seznam = [int(d) for d in str(fakulteta(n))]
vsota = 0
for i in range(0, len(seznam)):
vsota = vsota + seznam[i]
return(vsota)
print(vsota_stevk_fakultete(100)) | def fakulteta(n):
if n == 0:
return 1
else:
return n * fakulteta(n - 1)
def vsota_stevk_fakultete(n):
seznam = [int(d) for d in str(fakulteta(n))]
vsota = 0
for i in range(0, len(seznam)):
vsota = vsota + seznam[i]
return vsota
print(vsota_stevk_fakultete(100)) |
class Motor:
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade = max(0, self.velocidade)
NORTE = 'Norte'
SUL = 'Sul'
LESTE = 'Leste'
OESTE = 'Oeste'
class Direcao:
rotacao_a_direita_dc... | class Motor:
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade = max(0, self.velocidade)
norte = 'Norte'
sul = 'Sul'
leste = 'Leste'
oeste = 'Oeste'
class Direcao:
rotacao_a_direita_d... |
# -*- coding: utf-8 -*-
"""
.. _Docutils Configuration: http://docutils.sourceforge.net/docs/user/config.html
.. _registry-intro:
Configuration registry
======================
Registry store configurations by the way of its interface.
Default global registry is available at ``rstview.registry.rstview_registry``
an... | """
.. _Docutils Configuration: http://docutils.sourceforge.net/docs/user/config.html
.. _registry-intro:
Configuration registry
======================
Registry store configurations by the way of its interface.
Default global registry is available at ``rstview.registry.rstview_registry``
and is global for the whol... |
# (C) Datadog, Inc. 2010-2017
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
PORT = 11211
SERVICE_CHECK = 'memcache.can_connect'
| port = 11211
service_check = 'memcache.can_connect' |
PI = 3.1415 # Globale Variable
def kreisumfang(radius):
kreisumfang = 2 * PI * radius
return kreisumfang
def zylinder(radius, hoehe):
return hoehe * kreisumfang(radius)
print(zylinder(50, 20)) | pi = 3.1415
def kreisumfang(radius):
kreisumfang = 2 * PI * radius
return kreisumfang
def zylinder(radius, hoehe):
return hoehe * kreisumfang(radius)
print(zylinder(50, 20)) |
"""
A python package to update stuff.
This code is released under the terms of the MIT license. See the LICENSE
file for more details.
"""
| """
A python package to update stuff.
This code is released under the terms of the MIT license. See the LICENSE
file for more details.
""" |
def help_normalize_variations(variations: list[dict]) -> list[dict]:
list_normalized = []
obj_normalized = {}
list_obj_normalized = []
last_color = ""
count = 0
for element in variations:
if last_color == element.color or last_color == "":
list_normalized.append(
... | def help_normalize_variations(variations: list[dict]) -> list[dict]:
list_normalized = []
obj_normalized = {}
list_obj_normalized = []
last_color = ''
count = 0
for element in variations:
if last_color == element.color or last_color == '':
list_normalized.append({'size': elem... |
#!/usr/bin/env python
def construct_fip_id(subscription_id, group_name, lb_name, fip_name):
"""Build the future FrontEndId based on components name.
"""
return ('/subscriptions/{}'
'/resourceGroups/{}'
'/providers/Microsoft.Network'
'/loadBalancers/{}'
'/fron... | def construct_fip_id(subscription_id, group_name, lb_name, fip_name):
"""Build the future FrontEndId based on components name.
"""
return '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/loadBalancers/{}/frontendIPConfigurations/{}'.format(subscription_id, group_name, lb_name, fip_name)
def... |
class aSumPrint:
def run(self, context): #include context
a_sum = context["aSum"] #to extract from shared dictionary
print(f'a_sum = {a_sum}')
def __call__(self, context):
self.run(context) #to run the function
| class Asumprint:
def run(self, context):
a_sum = context['aSum']
print(f'a_sum = {a_sum}')
def __call__(self, context):
self.run(context) |
"""
Beautiful Arrangement
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:
perm[i] is divisible by i.
i is divisible by perm[i].
Given an integer n, return t... | """
Beautiful Arrangement
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:
perm[i] is divisible by i.
i is divisible by perm[i].
Given an integer n, return t... |
#set following variables
types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
#print variables "x" and "y" to create sentences
print(x)
print(y)
#print f-strings, notated with "f" in initial position.
#Using... | types_of_people = 10
x = f'There are {types_of_people} types of people.'
binary = 'binary'
do_not = "don't"
y = f'Those who know {binary} and those who {do_not}.'
print(x)
print(y)
print(f'I said: {x}')
print(f"I also said: '{y}'")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluatio... |
comida = ["tacos", "pozole", "pan de muerto", "pastel", "spaghetti", "gorditas"]
print("Acceder a los elementos de la lista individualmente")
print(comida[0])
print(comida[2])
print(comida[5])
print("Mostrar todos los elementos")
print(comida)
print()
print("Eliminar algun elemento")
del comida[3]
comida.pop()
print... | comida = ['tacos', 'pozole', 'pan de muerto', 'pastel', 'spaghetti', 'gorditas']
print('Acceder a los elementos de la lista individualmente')
print(comida[0])
print(comida[2])
print(comida[5])
print('Mostrar todos los elementos')
print(comida)
print()
print('Eliminar algun elemento')
del comida[3]
comida.pop()
print(co... |
class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
def helper(current, depth):
res = 0
for item in current:
if item.isInteger():
res += item.getInteger() * depth
else:
res += helper(it... | class Solution:
def depth_sum(self, nestedList: List[NestedInteger]) -> int:
def helper(current, depth):
res = 0
for item in current:
if item.isInteger():
res += item.getInteger() * depth
else:
res += helper(it... |
"""
Constants that are used throughout Zen.
"""
# Graph directedness
DIRECTED = 'directed'
UNDIRECTED = 'undirected'
# Direction constants
BOTH_DIR = 'both_dir'
IN_DIR = 'in_dir'
OUT_DIR = 'out_dir'
# Constants for specifying how weights should be merged.
# These values are accepted by the DiGraph.skeleton function.... | """
Constants that are used throughout Zen.
"""
directed = 'directed'
undirected = 'undirected'
both_dir = 'both_dir'
in_dir = 'in_dir'
out_dir = 'out_dir'
avg_of_weights = 0
max_of_weights = 1
min_of_weights = 2
no_none_list_of_data = 0
list_of_data = 1 |
argv = ['']
def exit(n):
pass
exit(0)
stdout = open("/dev/null")
stderr = open("/dev/null")
stdin = open("/dev/null")
| argv = ['']
def exit(n):
pass
exit(0)
stdout = open('/dev/null')
stderr = open('/dev/null')
stdin = open('/dev/null') |
class Eval:
"""
Eval
"""
def __init__(self):
self.predict_num = 0
self.correct_num = 0
self.gold_num = 0
self.precision = 0
self.recall = 0
self.fscore = 0
def clear(self):
"""
:return:
"""
self.predict_num = 0
... | class Eval:
"""
Eval
"""
def __init__(self):
self.predict_num = 0
self.correct_num = 0
self.gold_num = 0
self.precision = 0
self.recall = 0
self.fscore = 0
def clear(self):
"""
:return:
"""
self.predict_num = 0
... |
x = int(input())
n = int(input())
a = []
for y in range(n):
a.append(input().split())
for y in range(n):
if x >= int(a[y][0]) and x <= int(a[y][1]):
print(a[y][2])
| x = int(input())
n = int(input())
a = []
for y in range(n):
a.append(input().split())
for y in range(n):
if x >= int(a[y][0]) and x <= int(a[y][1]):
print(a[y][2]) |
print("Sartu zenbakiak...")
a=int(input("Sartu lehenengoa: "))
b=int(input("sartu bigarrena: "))
def baino_haundiagoa(a, b):
if a > b:
return("Lehenengo zenbakia haundiagoa da.")
elif a < b:
return("Bigarren zenbakia haundiagoa da.")
else:
return("Zenbaki berdina sartu dezu.")
pr... | print('Sartu zenbakiak...')
a = int(input('Sartu lehenengoa: '))
b = int(input('sartu bigarrena: '))
def baino_haundiagoa(a, b):
if a > b:
return 'Lehenengo zenbakia haundiagoa da.'
elif a < b:
return 'Bigarren zenbakia haundiagoa da.'
else:
return 'Zenbaki berdina sartu dezu.'
prin... |
'''
@author: Kittl
'''
def exportSubstations(dpf, exportProfile, tables, colHeads):
# Get the index in the list of worksheets
if exportProfile is 2:
cmpStr = "Substation"
elif exportProfile is 3:
cmpStr = ""
idxWs = [idx for idx,val in enumerate(tables[exportProfile-1]) if val == cm... | """
@author: Kittl
"""
def export_substations(dpf, exportProfile, tables, colHeads):
if exportProfile is 2:
cmp_str = 'Substation'
elif exportProfile is 3:
cmp_str = ''
idx_ws = [idx for (idx, val) in enumerate(tables[exportProfile - 1]) if val == cmpStr]
if not idxWs:
dpf.Print... |
array=list(map(int,input().split()))
print('Your Array :',array)
for i in range(0,len(array)-1):
if(array[i+1]<array[i]):
temp=array[i+1]
j=i
while(temp<array[j] and j>=0):
array[j+1]=array[j]
j-=1
array[j+1]=temp
print('Sorted Array : ',array) | array = list(map(int, input().split()))
print('Your Array :', array)
for i in range(0, len(array) - 1):
if array[i + 1] < array[i]:
temp = array[i + 1]
j = i
while temp < array[j] and j >= 0:
array[j + 1] = array[j]
j -= 1
array[j + 1] = temp
print('Sorted Arr... |
ENDINGS = ['.', '!', '?', ';']
def count_sentences(text):
text = text.strip()
if len(text) == 0:
return 0
split_result = None
for ending in ENDINGS:
separator = f'{ending} '
if split_result is None:
split_result = text.split(separator)
else:
split_result = [y for x in split_result for y in x.spli... | endings = ['.', '!', '?', ';']
def count_sentences(text):
text = text.strip()
if len(text) == 0:
return 0
split_result = None
for ending in ENDINGS:
separator = f'{ending} '
if split_result is None:
split_result = text.split(separator)
else:
split... |
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
... | def cheeseshop(kind, *arguments, **keywords):
print('-- Do you have any', kind, '?')
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print('-' * 40)
for kw in keywords:
print(kw, ':', keywords[kw])
cheeseshop('Limburger', "It's very runny, sir.", "It's ... |
# Under MIT License, see LICENSE.txt
__author__ = 'RoboCupULaval'
class TaskController:
"""Class added by composition to any task,
to keep track of the Task state
and logic flow.
This state-control class is separated
from the Task class so the Decorators
have a chance at compile-time security... | __author__ = 'RoboCupULaval'
class Taskcontroller:
"""Class added by composition to any task,
to keep track of the Task state
and logic flow.
This state-control class is separated
from the Task class so the Decorators
have a chance at compile-time security.
@author Ying"""
def __init_... |
'''
Get an undefined numbers of values and put them in a list.
In the end, show all the unique values in ascendent order.
'''
values = []
while True:
number = int(input('Choose a number: '))
if number not in values:
print(f'\033[32mAdd the number {number} to the list.\033[m')
values.ap... | """
Get an undefined numbers of values and put them in a list.
In the end, show all the unique values in ascendent order.
"""
values = []
while True:
number = int(input('Choose a number: '))
if number not in values:
print(f'\x1b[32mAdd the number {number} to the list.\x1b[m')
values.appe... |
class Context(dict):
"""Model the execution context for a Resource.
"""
def __init__(self, request):
"""Takes a Request object.
"""
self.website = None # set in dynamic_resource.py
self.body = request.body
self.headers = request.headers
self.cooki... | class Context(dict):
"""Model the execution context for a Resource.
"""
def __init__(self, request):
"""Takes a Request object.
"""
self.website = None
self.body = request.body
self.headers = request.headers
self.cookie = request.headers.cookie
self.p... |
VOWELS = { c for c in "aeouiAEOUI" }
def swap_vowel_case_char(c :str) -> str:
return c.swapcase() if c in VOWELS else c
def swap_vowel_case(st: str) -> str:
return "".join(swap_vowel_case_char(c) for c in st)
| vowels = {c for c in 'aeouiAEOUI'}
def swap_vowel_case_char(c: str) -> str:
return c.swapcase() if c in VOWELS else c
def swap_vowel_case(st: str) -> str:
return ''.join((swap_vowel_case_char(c) for c in st)) |
"""Base classes for pipelines and pipeline blocks."""
class Block(object):
"""Base class for all blocks.
Notes
-----
Blocks should take their parameters in ``__init__`` and provide at least
the ``process`` method for taking in data and returning some result.
"""
def __init__(self, name=N... | """Base classes for pipelines and pipeline blocks."""
class Block(object):
"""Base class for all blocks.
Notes
-----
Blocks should take their parameters in ``__init__`` and provide at least
the ``process`` method for taking in data and returning some result.
"""
def __init__(self, name=No... |
PuzzleInput = "PuzzleInput.txt"
f = open(PuzzleInput)
txt = f.readlines()
sums = []
k=0
for j in range(len(txt)):
for i in range(25):
for k in range(25):
if i == k:
continue
else:
sums.append(int(txt[i])+int(txt[k]))
if int(txt[25])... | puzzle_input = 'PuzzleInput.txt'
f = open(PuzzleInput)
txt = f.readlines()
sums = []
k = 0
for j in range(len(txt)):
for i in range(25):
for k in range(25):
if i == k:
continue
else:
sums.append(int(txt[i]) + int(txt[k]))
if int(txt[25]) in sums:
... |
if __name__ == '__main__':
# Creating a tuple
x = ()
x = (1, )
print(type(x))
x = (1)
print(type(x))
x = (1, 2, 3, "Apple", True, 4.0)
x = ((1, 2, 3), (4, 5, 6))
#Accessing Tuple
x = (1, 2, 3, "Apple", True, (7, 7, 7), 4.0)
print(x[3])
print(x[-2])
print(x[1:2])... | if __name__ == '__main__':
x = ()
x = (1,)
print(type(x))
x = 1
print(type(x))
x = (1, 2, 3, 'Apple', True, 4.0)
x = ((1, 2, 3), (4, 5, 6))
x = (1, 2, 3, 'Apple', True, (7, 7, 7), 4.0)
print(x[3])
print(x[-2])
print(x[1:2])
print(x[1:3])
print(x[::2])
(_, _, _, _,... |
#
# @lc app=leetcode id=108 lang=python3
#
# [108] Convert Sorted Array to Binary Search Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution... | class Solution:
def sorted_array_to_bst(self, nums: List[int]) -> TreeNode:
def helper(left, right):
if left > right:
return None
p = (left + right) // 2
root = tree_node(nums[p])
root.left = helper(left, p - 1)
root.right = helpe... |
class DecorationRepository:
def __init__(self):
self.decorations = []
@staticmethod
def get_obj_by_type(objects, obj_type):
result = [obj for obj in objects if obj.__class__.__name__ == obj_type]
return result
def add(self, decoration):
self.decorations.append(decoratio... | class Decorationrepository:
def __init__(self):
self.decorations = []
@staticmethod
def get_obj_by_type(objects, obj_type):
result = [obj for obj in objects if obj.__class__.__name__ == obj_type]
return result
def add(self, decoration):
self.decorations.append(decorati... |
class Envelope:
"""
Envelope to add metadata to a message.
This is an internal type and is not part of the public API.
:param message: the message to send
:type message: any
:param reply_to: the future to reply to if there is a response
:type reply_to: :class:`pykka.Future`
"""
# ... | class Envelope:
"""
Envelope to add metadata to a message.
This is an internal type and is not part of the public API.
:param message: the message to send
:type message: any
:param reply_to: the future to reply to if there is a response
:type reply_to: :class:`pykka.Future`
"""
__s... |
class NotValidAttributeException(Exception):
def __init__(self, message, errors):
super(NotValidAttributeException, self).__init__(message)
self.errors = errors
class NoReportFoundException(Exception):
def __init__(self, message, errors):
super(NoReportFoundException, self... | class Notvalidattributeexception(Exception):
def __init__(self, message, errors):
super(NotValidAttributeException, self).__init__(message)
self.errors = errors
class Noreportfoundexception(Exception):
def __init__(self, message, errors):
super(NoReportFoundException, self).__init__(m... |
n = int (input('Enter a number for prime number series : '))
for i in range(2,n):
for j in range(2,i):
if i % j == 0:
print(i,"is not a prime number because",j,"*",i//j,"=",i)
break
else:
print(i,"is a prime number") | n = int(input('Enter a number for prime number series : '))
for i in range(2, n):
for j in range(2, i):
if i % j == 0:
print(i, 'is not a prime number because', j, '*', i // j, '=', i)
break
else:
print(i, 'is a prime number') |
# -*- coding: utf-8 -*-
#################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# All Rights Reserved.
#
#
#
# This program is copyright property of the author mentioned abo... | {'name': 'SEO-URL Redirect/Rewrite', 'summary': 'SEO-URL Redirect/Rewrite module helps to redirect or redirect a URL to another URL to avoid page not found error.', 'category': 'Website', 'version': '1.2', 'sequence': 1, 'author': 'Webkul Software Pvt. Ltd.', 'license': 'Other proprietary', 'website': 'https://store.we... |
"""
Implement an algorithm to delete a node in the middle (ie., any node but the first and last node,
not necessarily the exact middle) of a singly linked list, given only access to that node.
Input: the node c from the linked list a -> b -> c -> d -> e -> f
Result: nothing is returned, but the new linked list looks ... | """
Implement an algorithm to delete a node in the middle (ie., any node but the first and last node,
not necessarily the exact middle) of a singly linked list, given only access to that node.
Input: the node c from the linked list a -> b -> c -> d -> e -> f
Result: nothing is returned, but the new linked list looks ... |
class Solution:
def threeSumClosest(self, num, target):
num = sorted(num)
best_sum = num[0] + num[1] + num[2]
for i in range(len(num)):
j = i + 1
k = len(num) - 1
while j < k:
current_sum = num[i] + num[j] + num[k]
... | class Solution:
def three_sum_closest(self, num, target):
num = sorted(num)
best_sum = num[0] + num[1] + num[2]
for i in range(len(num)):
j = i + 1
k = len(num) - 1
while j < k:
current_sum = num[i] + num[j] + num[k]
if cur... |
# -*- coding: utf-8 -*-
"""
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
empty_tuple = tuple()
print(empty_tuple)
# %%
amazon = ('Amazon', 'USA', 'Technology', 1)
google = ('Google', 'USA', 'Technology', 2)
# %%
name_google = google[0]
# %%
data = (amazon, google)
print(data)
# %%
a = ('Pawel', '... | """
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
empty_tuple = tuple()
print(empty_tuple)
amazon = ('Amazon', 'USA', 'Technology', 1)
google = ('Google', 'USA', 'Technology', 2)
name_google = google[0]
data = (amazon, google)
print(data)
a = ('Pawel', 'Krakowiak')
print(a)
imie = 'Pawel'
nazwisko = 'Kr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#======================================================================
# Code for solving day 8 of AoC 2018
#======================================================================
VERBOSE = True
#------------------------------------------------------------------
#-----... | verbose = True
def load_input(filename):
with open(filename, 'r') as f:
content = f.read()
return content.strip()
def part_one():
print('Performing part one.')
my_input = load_input('puzzle_input_day_8.txt')
print('Answer for part one: %d')
def part_two():
print('Performing part two.'... |
flag=[0]*35
box = [
253, 194, 15, 13, 82,
129, 244, 80, 193, 233,
36, 54, 199, 69, 219,
74, 136, 6, 190, 144,
68, 57, 156, 153, 240,
65, 95, 135, 61, 179,
159, 183, 182, 130, 107]
target = [
174, 178, 102, 127, 22,
245, 143, 226, 245, 131,
65, 105, 135, 48, 94,
21, 185, 188, 225, 211,
116, 11,... | flag = [0] * 35
box = [253, 194, 15, 13, 82, 129, 244, 80, 193, 233, 36, 54, 199, 69, 219, 74, 136, 6, 190, 144, 68, 57, 156, 153, 240, 65, 95, 135, 61, 179, 159, 183, 182, 130, 107]
target = [174, 178, 102, 127, 22, 245, 143, 226, 245, 131, 65, 105, 135, 48, 94, 21, 185, 188, 225, 211, 116, 11, 178, 184, 248, 18, 47, ... |
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
i = 0
while 2**i <n:
i+=1
if 2**i==n:
return True
return False | class Solution:
def is_power_of_two(self, n: int) -> bool:
i = 0
while 2 ** i < n:
i += 1
if 2 ** i == n:
return True
return False |
def feast(beast, dish):
x = len(beast)
y = len(dish)
if beast[0] == dish[0]:
if beast[x-1] == dish[y-1]:
return True
else:
return False
else:
return False
def feast1(beast, dish):
return beast[0]==dish[0] and dish[-1]==beast[-1] | def feast(beast, dish):
x = len(beast)
y = len(dish)
if beast[0] == dish[0]:
if beast[x - 1] == dish[y - 1]:
return True
else:
return False
else:
return False
def feast1(beast, dish):
return beast[0] == dish[0] and dish[-1] == beast[-1] |
# encoding: utf-8
"""
location.py
Created by Thomas Mangin on 2014-06-22.
Copyright (c) 2014-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
# ===================================================================== Location
# file location
class Location(object):
def __... | """
location.py
Created by Thomas Mangin on 2014-06-22.
Copyright (c) 2014-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
class Location(object):
def __init__(self, index_line=0, index_column=0, line=''):
self.line = line
self.index_line = index_line
... |
#Dictionary is key value pairs.
d1 = {}
print(type(d1))
d2 ={ "Jiggu":"Burger", "Rohan":"Fish", "Ravi":"Roti"}
#print(d2["Jiggu"]) case sensitive,tell about there syn...
#we can make dictionary inside a dictionary
d3 = {"Jiggu":"Burger", "Rohan":"Fish", "Ravi":"Roti",
"Pagal":{"B":"Oats","L": "Rice","D":"C... | d1 = {}
print(type(d1))
d2 = {'Jiggu': 'Burger', 'Rohan': 'Fish', 'Ravi': 'Roti'}
d3 = {'Jiggu': 'Burger', 'Rohan': 'Fish', 'Ravi': 'Roti', 'Pagal': {'B': 'Oats', 'L': 'Rice', 'D': 'Chicken'}}
'\nd3["Ankit"] = "Junk Food"\nd3[3453] = "Kabab"\ndel d3[3453]\n'
print(d3.get('Jiggu')) |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isValidBST(root):
arr = []
def inOrderTraversal(root):
if not root: return
if root.left: inOrderTraversal(root.left)
arr.append(root.val)
if root.right: inOrde... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_valid_bst(root):
arr = []
def in_order_traversal(root):
if not root:
return
if root.left:
in_order_traversal(root.left)
arr.append(root.val... |
class CycleSetupCommon:
"""
realization needs self.h_int, self.gloc, self.g0, self.se, self.mu, self.global_moves,
self.quantum_numbers
"""
def initialize_cycle(self):
return {'h_int': self.h_int,'g_local': self.gloc, 'weiss_field': self.g0,
'self_energy': self.se, 'mu': self... | class Cyclesetupcommon:
"""
realization needs self.h_int, self.gloc, self.g0, self.se, self.mu, self.global_moves,
self.quantum_numbers
"""
def initialize_cycle(self):
return {'h_int': self.h_int, 'g_local': self.gloc, 'weiss_field': self.g0, 'self_energy': self.se, 'mu': self.mu, 'global_m... |
#!/usr/bin/env python
def simple_generator():
yield 1
yield 2
yield 3
simple_generator()
print(simple_generator)
print(simple_generator()) | def simple_generator():
yield 1
yield 2
yield 3
simple_generator()
print(simple_generator)
print(simple_generator()) |
#
# PySNMP MIB module HH3C-VOICE-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-VOICE-IF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint) ... |
# Python3 Finding Lowest Common Ancestor in Binary Tree ----> O(N)
def find_lca_bt(root, n1, n2):
if not root:
return None
left_lca = find_lca_bt(root.left, n1, n2)
right_lca = find_lca_bt(root.right, n1, n2)
if left_lca and right_lca:
return root
return left_lca if left_lca else right_lca
# Python3 Findi... | def find_lca_bt(root, n1, n2):
if not root:
return None
left_lca = find_lca_bt(root.left, n1, n2)
right_lca = find_lca_bt(root.right, n1, n2)
if left_lca and right_lca:
return root
return left_lca if left_lca else right_lca
def find_lca_bst(root, n1, n2):
if not root:
re... |
class DF_Filter(dict):
'''
store and format query where clause
'''
def __init__(self,filter_value={}):
self['filter_list'] = []
def add(self,val):
self['filter_list'].append(val)
return self
def getFilter(self):
if len(self['filter_list'])==0:
ms... | class Df_Filter(dict):
"""
store and format query where clause
"""
def __init__(self, filter_value={}):
self['filter_list'] = []
def add(self, val):
self['filter_list'].append(val)
return self
def get_filter(self):
if len(self['filter_list']) == 0:
... |
def my_count(lst, e):
res = 0
if type(lst) == list:
res = lst.count(e)
return res
print(my_count([1, 2, 3, 4, 3, 2, 1], 3))
print(my_count([1, 2, 3], 4))
print(my_count((2, 3, 5), 3)) | def my_count(lst, e):
res = 0
if type(lst) == list:
res = lst.count(e)
return res
print(my_count([1, 2, 3, 4, 3, 2, 1], 3))
print(my_count([1, 2, 3], 4))
print(my_count((2, 3, 5), 3)) |
def mdc(x1, x2):
while x1%x2 != 0:
nx1 = x1
nx2 = x2
# Trocando os valores de variavel
x1 = nx2
x2 = nx1 % nx2 # x2 recebe o resto da divisao entre nx1 e nx2
return x2
class Fracao:
def __init__(self, numerador, denominador):
self.num = numerador
sel... | def mdc(x1, x2):
while x1 % x2 != 0:
nx1 = x1
nx2 = x2
x1 = nx2
x2 = nx1 % nx2
return x2
class Fracao:
def __init__(self, numerador, denominador):
self.num = numerador
self.den = denominador
def __str__(self):
return str(self.num) + '/' + str(se... |
# ============================================================================#
# author : louis TOMCZYK
# goal : Definition of personalized Mathematics Basics functions
# ============================================================================#
# version : 0.0.1 - 2021 09 27 - derivati... | def derivative(Y, dx):
d_ydx = []
for k in range(len(Y) - 1):
dYdx.append((Y[k + 1] - Y[k]) / dx)
return dYdx
def average(arr, n):
end = n * int(len(arr) / n)
return np.mean(arr[:end].reshape(-1, n), 1)
def moving_average(List, N_samples):
return np.convolve(List, np.ones(N_samples), '... |
def Bonjour(name):
print(f"Bonjour, {name} comment allez vous ?")
Bonjour("wassila")
| def bonjour(name):
print(f'Bonjour, {name} comment allez vous ?')
bonjour('wassila') |
"""
A simple package that does nothing.
"""
__version__ = '0.0.3'
| """
A simple package that does nothing.
"""
__version__ = '0.0.3' |
# test async with, escaped by a break
class AContext:
async def __aenter__(self):
print('enter')
return 1
async def __aexit__(self, exc_type, exc, tb):
print('exit', exc_type, exc)
async def f1():
while 1:
async with AContext():
print('body')
break
... | class Acontext:
async def __aenter__(self):
print('enter')
return 1
async def __aexit__(self, exc_type, exc, tb):
print('exit', exc_type, exc)
async def f1():
while 1:
async with a_context():
print('body')
break
print('no 1')
pri... |
file_name = 'words_ex1~' # <= Error file name
try:
content = open(file_name, 'r', encoding='utf-8')
for line in content:
print(line)
except IOError as io_err:
print(io_err) # Output the exception message
# [Errno 2] No such file or directory: 'words_ex1~'
# You can use 'with' statement
with op... | file_name = 'words_ex1~'
try:
content = open(file_name, 'r', encoding='utf-8')
for line in content:
print(line)
except IOError as io_err:
print(io_err)
with open(file_name, 'r', encoding='utf-8') as content:
for line in content:
print(line) |
def product_sans_n(nums):
if nums.count(0)>=2:
return [0]*len(nums)
elif nums.count(0)==1:
temp=[0]*len(nums)
temp[nums.index(0)]=product(nums)
return temp
res=product(nums)
return [res//i for i in nums]
def product(arr):
total=1
for i in arr:
if i==0:
... | def product_sans_n(nums):
if nums.count(0) >= 2:
return [0] * len(nums)
elif nums.count(0) == 1:
temp = [0] * len(nums)
temp[nums.index(0)] = product(nums)
return temp
res = product(nums)
return [res // i for i in nums]
def product(arr):
total = 1
for i in arr:
... |
# Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: Dictionary Programming Exercises 7.1
# Q1(e) solution
car = dict( {
'reg': "131 CN 6439",
'make': "Audi",
'model' : "A6",
'year' : 2013,
'kms' : 52... | car = dict({'reg': '131 CN 6439', 'make': 'Audi', 'model': 'A6', 'year': 2013, 'kms': 52739, 'colour': 'Silver', 'diesel': True})
print(car['make'])
print(car['colour'][0])
print(car['reg'][4:5]) |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 08 13:55:56 2017
@author: Keerthi
"""
# def subseq_gen(newsubseq):
# subseq.append(dum)
def subseq_rule(seq): # Import the subsequence
subseq = []
# Rule 1 - subsequence is derived by removing the first element from the sequence
if len(seq[0]) ... | """
Created on Tue Aug 08 13:55:56 2017
@author: Keerthi
"""
def subseq_rule(seq):
subseq = []
if len(seq[0]) == 1:
dum = []
dum = list(seq[1:])
subseq.append(dum)
if len(seq[-1]) == 1:
dum = list(seq[0:-1])
subseq.append(dum)
for k in xrange(len(seq)):
... |
n = int(input())
continents = {}
for i in range(n):
str = input().split(' ')
if str[0] in continents:
if str[1] in continents[str[0]]:
continents[str[0]][str[1]].append(str[2])
else:
continents[str[0]][str[1]] = [str[2]]
else:
continents[str[0]] = {
... | n = int(input())
continents = {}
for i in range(n):
str = input().split(' ')
if str[0] in continents:
if str[1] in continents[str[0]]:
continents[str[0]][str[1]].append(str[2])
else:
continents[str[0]][str[1]] = [str[2]]
else:
continents[str[0]] = {str[1]: [st... |
#! /usr/bin/python3
vorname = "Joe"
nachname = "Biden"
print("{0} {1} is elected!".format(vorname, nachname))
print("Hallo World!")
| vorname = 'Joe'
nachname = 'Biden'
print('{0} {1} is elected!'.format(vorname, nachname))
print('Hallo World!') |
class Node:
def __init__(self, valor):
self.valor = valor
self.hijo_izquierdo = None
self.hijo_derecho = None
self.altura = 0
class AVLTree:
def __init__(self):
self.raiz = None
def add(self, valor):
self.raiz = self._add(valor, self.raiz)
... | class Node:
def __init__(self, valor):
self.valor = valor
self.hijo_izquierdo = None
self.hijo_derecho = None
self.altura = 0
class Avltree:
def __init__(self):
self.raiz = None
def add(self, valor):
self.raiz = self._add(valor, self.raiz)
def _add(se... |
p = 196732205348849427366498732223276547339
secret = REDACTED
def calc_root(num, mod, n):
f = GF(mod)
temp = f(num)
return temp.nth_root(n)
def gen_v_list(primelist, p, secret):
a = []
for prime in primelist:
a.append(calc_root(prime, p, secret))
return a
def decodeInt(i, primelist):
... | p = 196732205348849427366498732223276547339
secret = REDACTED
def calc_root(num, mod, n):
f = gf(mod)
temp = f(num)
return temp.nth_root(n)
def gen_v_list(primelist, p, secret):
a = []
for prime in primelist:
a.append(calc_root(prime, p, secret))
return a
def decode_int(i, primelist):... |
def for_e():
""" Pattern of Small Alphabet: 'e' using for loop"""
for i in range(5):
for j in range(5):
if i%4==0 and j not in(0,4) or j==0 and i in(1,2,3) or i==2 and j>1 or i==1 and j==4:
print('*',end=' ')
... | def for_e():
""" Pattern of Small Alphabet: 'e' using for loop"""
for i in range(5):
for j in range(5):
if i % 4 == 0 and j not in (0, 4) or (j == 0 and i in (1, 2, 3)) or (i == 2 and j > 1) or (i == 1 and j == 4):
print('*', end=' ')
else:
print('... |
#2
total=0
for number in range(1, 10 + 1):
print(number)
total = total + number
print(total)
#3
def add_numbers (x,y):
for number in range (x,y):
print (number)
tot= total+number
print(total)
add_numbers(10,45)
#4
def jamie_1(x,y):
total=0
for jamie in range(x,y+1):
print(... | total = 0
for number in range(1, 10 + 1):
print(number)
total = total + number
print(total)
def add_numbers(x, y):
for number in range(x, y):
print(number)
tot = total + number
print(total)
add_numbers(10, 45)
def jamie_1(x, y):
total = 0
for jamie in range(x, y + 1):
print... |
product_map = { 1: 'Original 1000',
3: 'Color 650',
10: 'White 800 (Low Voltage)',
11: 'White 800 (High Voltage)',
18: 'White 900 BR30 (Low Voltage)',
20: 'Color 1000 BR30',
22: 'Color 1000',
27: 'LIFX A19',
28: 'LIFX BR30',
29: 'LIFX+ A19',
30: 'LIFX+ BR30',
31: 'LIFX Z',
... | product_map = {1: 'Original 1000', 3: 'Color 650', 10: 'White 800 (Low Voltage)', 11: 'White 800 (High Voltage)', 18: 'White 900 BR30 (Low Voltage)', 20: 'Color 1000 BR30', 22: 'Color 1000', 27: 'LIFX A19', 28: 'LIFX BR30', 29: 'LIFX+ A19', 30: 'LIFX+ BR30', 31: 'LIFX Z', 32: 'LIFX Z 2', 36: 'LIFX Downlight', 37: 'LIFX... |
x,y,z=0,1,0
print(x,',',y,end="")
for i in range(1,49):
z=x+y
print(',',z,end="")
x=y
y=z
| (x, y, z) = (0, 1, 0)
print(x, ',', y, end='')
for i in range(1, 49):
z = x + y
print(',', z, end='')
x = y
y = z |
class RocketNotEnoughInfo(Exception):
"""
Exception raised when not enough information is provided to fetch/find a Rocket.
"""
def __init__(self, message, errors=None):
# Call the base class constructor with the parameters it needs
super().__init__(message)
class RocketInfoFormat(Exc... | class Rocketnotenoughinfo(Exception):
"""
Exception raised when not enough information is provided to fetch/find a Rocket.
"""
def __init__(self, message, errors=None):
super().__init__(message)
class Rocketinfoformat(Exception):
"""
Exception raised when the format of a Rocket's infor... |
def first_last(full_name):
first_name = ''
last_name = ''
has_been_a_space = False
for letter in full_name:
if letter == ' ':
has_been_a_space = True
elif has_been_a_space:
last_name = last_name + letter
else:
first_name = first_name + letter
... | def first_last(full_name):
first_name = ''
last_name = ''
has_been_a_space = False
for letter in full_name:
if letter == ' ':
has_been_a_space = True
elif has_been_a_space:
last_name = last_name + letter
else:
first_name = first_name + letter
... |
"""
for case if find caesar message bruteforce
"""
message = "GIEWIVrGMTLIVrHIQS"
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(letters)):
translated = ''
for symbol in message:
if symbol in letters:
num = letters.find(symbol)
num = num - key
if num <... | """
for case if find caesar message bruteforce
"""
message = 'GIEWIVrGMTLIVrHIQS'
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(letters)):
translated = ''
for symbol in message:
if symbol in letters:
num = letters.find(symbol)
num = num - key
if num < 0:... |
RUN_STRINGS = (
"Where do you think you're going?",
"Huh? what? did they get away?",
"ZZzzZZzz... Huh? what? oh, just them again, nevermind.",
"Get back here!",
"Not so fast...",
"Look out for the wall!",
"Don't leave me alone with them!!",
"You run, you die.",
"Jokes on you, I'm eve... | run_strings = ("Where do you think you're going?", 'Huh? what? did they get away?', 'ZZzzZZzz... Huh? what? oh, just them again, nevermind.', 'Get back here!', 'Not so fast...', 'Look out for the wall!', "Don't leave me alone with them!!", 'You run, you die.', "Jokes on you, I'm everywhere", "You're gonna regret that..... |
""" Expose PV data """
#
# import logging
# from datetime import datetime, timedelta
# from typing import List
#
# from fastapi import APIRouter, Depends
# from nowcasting_datamodel.models import PVYield
# from nowcasting_datamodel.read.read_pv import get_latest_pv_yield, get_pv_systems
# from sqlalchemy.orm.session im... | """ Expose PV data """ |
class Solution:
def word_pattern(self, pattern: str, str: str) -> bool:
words = str.split(" ")
return len(pattern) == len(words) and len(set(pattern)) == len(set(words)) == len(set(zip(pattern, words)))
| class Solution:
def word_pattern(self, pattern: str, str: str) -> bool:
words = str.split(' ')
return len(pattern) == len(words) and len(set(pattern)) == len(set(words)) == len(set(zip(pattern, words))) |
print('Hello')
print('World')
# adding a keyword argument will get "Hello World" on the same line.
print('Hello', end=' ')
print('World')
# the "end=' '" adds a single space character at the end of Hello starts the next print right next ot it
print('cat', 'dog', 'mouse')
#the above will have a single spac... | print('Hello')
print('World')
print('Hello', end=' ')
print('World')
print('cat', 'dog', 'mouse')
print('cat', 'dog', 'mouse', sep='ABC') |
#
# PySNMP MIB module ASCEND-MIBINET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBINET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:27:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_unio... |
def main():
s = input("")
x = s.isdigit()
print(x, end="")
main()
| def main():
s = input('')
x = s.isdigit()
print(x, end='')
main() |
# 1. Two Sum
class Solution:
# Approach 1 : Naive
def twoSum1(self, nums, target):
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return [i, j]
return None
# Approach 2: Two-pass Hash Table
d... | class Solution:
def two_sum1(self, nums, target):
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return None
def two_sum2(self, nums, target):
foo = {}
for (i, j) in ... |
class Node:
pass
class Edge:
pass
class Graph:
pass
| class Node:
pass
class Edge:
pass
class Graph:
pass |
def highest_product_of_3(list_of_ints):
# initialize lowest to the minimum of the first two integers
lowest = min(list_of_ints[0], list_of_ints[1])
# initialize highest to the maximum of the first two integers
highest = max(list_of_ints[0], list_of_ints[1])
# initialize lowest_product_of_two and hi... | def highest_product_of_3(list_of_ints):
lowest = min(list_of_ints[0], list_of_ints[1])
highest = max(list_of_ints[0], list_of_ints[1])
(lowest_product_of_two, highest_product_of_two) = (list_of_ints[0] * list_of_ints[1], list_of_ints[0] * list_of_ints[1])
highest_product_of_three = list_of_ints[0] * lis... |
ll = [1, 2, 3]
def increment(x):
print(f'Old value: {x}')
return x + 1
print(map(increment, ll))
for x in map(increment, ll):
print(x)
iter = map(increment, ll)
| ll = [1, 2, 3]
def increment(x):
print(f'Old value: {x}')
return x + 1
print(map(increment, ll))
for x in map(increment, ll):
print(x)
iter = map(increment, ll) |
class MessageTypes:
InstrumentStateChange = 505
ClassStateChange = 516
Mail = 523
IndicativeMatchingPrice = 530
Collars = 537
SessionTimetable = 539
StartReferential = 550
EndReferential = 551
Referential = 556
ShortSaleChange = 560
SessionSummary = 561
GenericMessage = 592
OpenPosition = 59... | class Messagetypes:
instrument_state_change = 505
class_state_change = 516
mail = 523
indicative_matching_price = 530
collars = 537
session_timetable = 539
start_referential = 550
end_referential = 551
referential = 556
short_sale_change = 560
session_summary = 561
generi... |
# -*- coding: utf-8 -*-
# Scrapy settings for newblogs project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'newblogs'
SPIDER_MODULES = ['newblogs.spiders']
N... | bot_name = 'newblogs'
spider_modules = ['newblogs.spiders']
newspider_module = 'newblogs.spiders'
item_pipelines = {'newblogs.pipelines.NormalPipeline': 1, 'newblogs.pipelines.SaveDbPipeline': 2} |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 6 08:39:12 2021
@author: ELCOT
"""
"""
Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, ... | """
Created on Tue Apr 6 08:39:12 2021
@author: ELCOT
"""
'\nGiven an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.\n\nFollow up:\n\nA straight forward solution using O(mn) space is probably a bad idea.\nA simple improvement uses O(m + n) space, but still not the best solution.... |
route = [(1, -1), (1, 1), (1, -1), (-1, 1), (-1, 1), (1, -1), (1, -1), (1, 1), (-1, -1), (1, 1), (1, -1), (-1, 1), (1, -1), (-1, 1), (-1, 1), (-1, -1), (1, -1), (1, 1), (-1, -1), (1, -1), (1, -1), (1, 1), (1, -1), (-1, 1), (-1, 1), (-1, 1), (-1, -1), (1, -1), (1, -1), (1, 1), (-1, -1), (1, 1), (1, -1), (1, -1), (-1, -1... | route = [(1, -1), (1, 1), (1, -1), (-1, 1), (-1, 1), (1, -1), (1, -1), (1, 1), (-1, -1), (1, 1), (1, -1), (-1, 1), (1, -1), (-1, 1), (-1, 1), (-1, -1), (1, -1), (1, 1), (-1, -1), (1, -1), (1, -1), (1, 1), (1, -1), (-1, 1), (-1, 1), (-1, 1), (-1, -1), (1, -1), (1, -1), (1, 1), (-1, -1), (1, 1), (1, -1), (1, -1), (-1, -1... |
TEMPLATE = """\
# Include the license file
include LICENSE.md
include README.rst
# Include the data files
{include_data_files}
# Include the docs
# {include_docs_folder}
""" | template = '# Include the license file\ninclude LICENSE.md\ninclude README.rst\n\n# Include the data files\n{include_data_files}\n\n# Include the docs\n# {include_docs_folder}\n' |
lista = [['edu', 'joao', 'luizr'], ['maria', ' aline', 'joana'],['helena', 'ed', 'lu']]
enumerada = list(enumerate(lista))
print(enumerada[1][1][2][0]) | lista = [['edu', 'joao', 'luizr'], ['maria', ' aline', 'joana'], ['helena', 'ed', 'lu']]
enumerada = list(enumerate(lista))
print(enumerada[1][1][2][0]) |
"""
Serialization is the process of converting a data structure or object into
a sequence of bits so that it can be stored in a file or memory buffer, or
transmitted across a network connection link to be reconstructed later in
the same or another computer environment.
Design an algorithm to seri... | """
Serialization is the process of converting a data structure or object into
a sequence of bits so that it can be stored in a file or memory buffer, or
transmitted across a network connection link to be reconstructed later in
the same or another computer environment.
Design an algorithm to seri... |
"""
* Author: ZHAO Zinan
* Created: 01/25/2019
341. Flatten Nested List Iterator
"""
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
... | """
* Author: ZHAO Zinan
* Created: 01/25/2019
341. Flatten Nested List Iterator
"""
def flatten(nestedList):
result = []
if len(nestedList) == 0:
return []
for ele in nestedList:
if ele.isInteger():
result.append(ele)
else:
result.extend(flatten(ele... |
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918,
237,
412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379,
843, 831, 445, 742, 717, 958,743, 527
]
for number in numbers:
if ... | numbers = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 743, 527]
for number in numbers:
if number is 237:
p... |
# Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
class Solution:
def toLowerCase(self, str):
res = []
for char in str:
if ord(char) >= 65 and ord(char) <= 90:
res += chr(ord(char) + 32)
# res +=... | class Solution:
def to_lower_case(self, str):
res = []
for char in str:
if ord(char) >= 65 and ord(char) <= 90:
res += chr(ord(char) + 32)
else:
res += char
return ''.join(res)
s = solution().toLowerCase('HELwwLO')
print(s) |
def foo():
if 1:
if 2:
pass
| def foo():
if 1:
if 2:
pass |
#!/usr/bin/python
# https://practice.geeksforgeeks.org/problems/relative-sorting/0
def sol(a, b, m, n):
"""
Store the counts of each element, traverse through the second array and
keep building a temp. array, finally insert the elements which are not in
the second array
complextiy = m+n
"""
... | def sol(a, b, m, n):
"""
Store the counts of each element, traverse through the second array and
keep building a temp. array, finally insert the elements which are not in
the second array
complextiy = m+n
"""
me = max(a)
c = [0 for i in range(me + 1)]
for x in a:
c[x] += 1
... |
SQL_INIT_TABLES_AND_TRIGGERS = '''
CREATE TABLE consumers
(
component TEXT NOT NULL,
subcomponent TEXT NOT NULL,
host TEXT NOT NULL,
itype TEXT NOT NULL,
iprimary TEXT NOT NULL,
isecondary TEXT NOT NULL,
itertiary TEXT NOT NULL,
optional BOOLEAN NO... | sql_init_tables_and_triggers = '\n CREATE TABLE consumers\n (\n component TEXT NOT NULL,\n subcomponent TEXT NOT NULL,\n host TEXT NOT NULL,\n itype TEXT NOT NULL,\n iprimary TEXT NOT NULL,\n isecondary TEXT NOT NULL,\n itertiary TEXT NOT NULL,\n optional BO... |
"""Isotopic Abundances for each isotope"""
class Natural_Isotope(object):
def __init__(self, symbol, mass_number, mass, isotopic_abundance,
cross_section):
self.symbol = symbol
self.mass_number = mass_number
self.mass = mass
self.isotopic_abundance = .01 *... | """Isotopic Abundances for each isotope"""
class Natural_Isotope(object):
def __init__(self, symbol, mass_number, mass, isotopic_abundance, cross_section):
self.symbol = symbol
self.mass_number = mass_number
self.mass = mass
self.isotopic_abundance = 0.01 * isotopic_abundance
... |
__project__ = 'OCRErrorCorrectpy3'
__author__ = 'jcavalie'
__email__ = "Jcavalieri8619@gmail.com"
__date__ = '10/25/14'
EpsilonTransition = None
TransitionWeight = None
outputsModel=None
NUM_PARTITIONS=None
EM_STEP=True
| __project__ = 'OCRErrorCorrectpy3'
__author__ = 'jcavalie'
__email__ = 'Jcavalieri8619@gmail.com'
__date__ = '10/25/14'
epsilon_transition = None
transition_weight = None
outputs_model = None
num_partitions = None
em_step = True |
def test_get_page_hierarchy_as_xml():
given_pages('PageOne', 'PageOne.ChildOne', 'PageTwo')
when_request_is_issued('root', 'type:pages')
then_response_should_be_xml()
def test_get_page_hierarchy_has_right_tags():
given_pages('PageOne', 'PageOne.ChildOne', 'PageTwo')
when_request_is_issued('root'... | def test_get_page_hierarchy_as_xml():
given_pages('PageOne', 'PageOne.ChildOne', 'PageTwo')
when_request_is_issued('root', 'type:pages')
then_response_should_be_xml()
def test_get_page_hierarchy_has_right_tags():
given_pages('PageOne', 'PageOne.ChildOne', 'PageTwo')
when_request_is_issued('root', '... |
def new_file(filename, content):
with open(filename, 'w+') as f:
f.write(content)
print('Created at', filename)
| def new_file(filename, content):
with open(filename, 'w+') as f:
f.write(content)
print('Created at', filename) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.