content stringlengths 7 1.05M |
|---|
"""2020-08-07 migration"""
name = "20200807_landmarks_collection"
dependencies = ['20200406_users_collection']
def upgrade(db):
db.create_collection('landmarks')
db.landmarks.insert([
{
"tourId": "5f068e0cd4e3ebcf661f8733",
"landmarks": [
{
... |
#
# Demonstrate grid's "free unit"
#
# Column 1: fix width 60 px
# Column 2: 1 unit from the remaining free space
# Column 3: 2 unit from the remaining free space
col_dsc = [60, lv.grid_fr(1), lv.grid_fr(2), lv.GRID_TEMPLATE.LAST]
# Row 1: fix width 60 px
# Row 2: 1 unit from the remaining free space
# Row 3: fix wi... |
def get_name(first_name, last_name):
return f'{first_name} {last_name}'
def is_valid_card_number(card_number):
my_sum = sum(list(map(int, card_number)))
if my_sum % 7 == 0:
return True
return False
class ExistingCard:
def __init__(self, first_name, last_name, card_number):
self.n... |
INF = 987654321
def solution(arr):
size = len(arr) // 2 + 1
min_dp = [[INF for _ in range(size)] for _ in range(size)]
max_dp = [[-INF for _ in range(size)] for _ in range(size)]
for i in range(size):
min_dp[i][i] = int(arr[2 * i])
max_dp[i][i] = int(arr[2 * i])
for cnt in range(1,... |
#!/usr/bin/env python3
# coding:utf-8
class Solution:
def reOrderArray(self, array):
odd = []
even = []
for num in array:
if num % 2 == 1:
odd.append(num)
else:
even.append(num)
return odd + even
if __name__ == "__main__":
... |
class SeafileAdmin(object):
def lists_users(self, maxcount=100):
pass
def list_user_repos(self, username):
pass
|
# -*- coding: utf-8 -*-
#STIX open vocabulary and values
#simulate enums
TYPES = [
"attack-pattern",
"campaign",
"course-of-action",
"identity",
"indicator",
"intrusion-set",
"malware",
"observed-data",
"report",
"threat-actor",
"tool",
"vulnerability",
]
GENERATABLE_T... |
with open('src/base.rs', 'r') as f:
code = f.read()
for size in ['8', '16', '32', '64', 'size', '128']:
utype = 'u%s' % size
itype = 'i%s' % size
with open(f'src/{utype}_func.rs','w') as f:
f.write(code.replace('u8', utype))
with open(f'src/{itype}_func.rs','w') as f:
f.write(code.r... |
# In fact, there are not many values that evaluates to False, except empty values, such as (), [], {}, "",
# the number 0, and the value None. And of course the value False evaluates to False.
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
# One more value, or object in this case, evaluates to Fal... |
#
# PySNMP MIB module IRM-OIDS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IRM-OIDS
# Produced by pysmi-0.3.4 at Mon Apr 29 17:26:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... |
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=35):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá, meu nome é {self.nome}.'
@staticmethod
def metodo_estatico():
return 42
@class... |
# Write a program to display "Hello" if a number entered by user is a multiple of five ,
# otherwise print "Bye".
print("Program displayed - 'Hello' If user Entered Number multiple of 5 Other-wise displayed bye")
num = int(input("Enter the Number : "))
if(num%5==0):
print("Hello")
else:
print("Bye")
# For ... |
class Parser(object):
V_N = ['E', 'e', 'T', 't', 'F']
first = {
'E': ['(', 'i'],
'e': ['+', '-'],
'T': ['(', 'i'],
't': ['*', '/'],
'F': ['(', 'i']
}
follow = {
'E': [')', '#'],
'e': [')', '#'],
'T': ['+', '-', '#', ')'],
't': ['+', '-', '#', ')'],
'F': ['+', '-', '*',... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# california institute of technology
# (c) 1998-2021 all rights reserved
#
def requirements(package):
"""
Build a dictionary with the external dependencies of the {pyre} project
"""
# build the package instances
packages = [
package(name='c... |
# -*- coding: utf-8 -*-
'''Wrapper for MeCab node.'''
class MeCabNode(object):
'''Representation of a MeCab Node struct.
A list of MeCab nodes is returned when parsing a string of Japanese with
as_nodes=True. Each node will contain detailed information about the
morpheme encompassed.
:ivar ptr: T... |
# adaptive thresholding method
def adaptive_thresholding(img):
img_grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
adaptive_threshed = cv2.adaptiveThreshold(img_grey, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 1)
cv2.imshow("adaptive", adaptive_threshed)
return adaptive_threshed
# Nor... |
# Leia um valor em metros e em seguida exiba convertido em centímetros e milímetros.
m = float(input('Digite o comprimento em metros: '))
cm = m * 100
mm = m * 1000
print('O valor {} m pode ser convertido em {} cm ou {} mm.'.format(m, cm, mm)) |
"""Constants for broadlink platform."""
CONF_PACKET = 'packet'
DOMAIN = 'broadlink'
SERVICE_LEARN = 'learn'
SERVICE_SEND = 'send'
|
"""
DMFont
Copyright (c) 2020-present NAVER Corp.
MIT license
"""
COMPONENT_RANGE = (int('3131', 16), int('3163', 16)) # kr 자음/모음
COMPLETE_RANGE = (int('ac00', 16), int('d7a3', 16)) # kr all complete chars
COMPLETE_SET = frozenset(chr(code) for code in range(COMPLETE_RANGE[0], COMPLETE_RANGE[1]+1))
COMPLETE_LIST = s... |
n = (3, 6, 3)
transformers = [
lambda _: _.transpose(),
lambda _: _.rename_axis(
mapper='variable',
axis='index',
),
lambda _: _.rename_axis(
mapper='id',
axis='columns',
),
]
|
#!/usr/bin/python3
__doc__ = '''
abcdefg
'''
|
## Part 1: Standalone Functions
### Mean
def mean(input_list):
return sum(input_list) / len(input_list)
# Provided test, you should add more.
numbers = [5, 10, 15]
m = mean(numbers)
print(m) # 10
### Median
def median(input_list):
n = len(input_list)
sorted_list = sorted(input_list)
# No elements,... |
# DP, recurrsive and memorization
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
mem = [[0 for _ in range(n)] for _ in range(m)]
for i in range(n):
mem[0][i] = 1
for j in range(m):
... |
sp1 = ["яблоки", "бананы", "капуста", "картошка", "грибы"]
print(sp1)
print(sp1[2]) # вызов элемента по индексу
sp1[3] = 'морковь' # замена элемента
print(sp1)
sp1.append("сыр")
print(sp1)
del sp1[1]
print(sp1)
sp2 = [234, 235, 21, 43, 6565, 3344, 6564, 34]
sp3 = [3453, 'dfg', 667, 'df', 34]
sp4 = [sp2, sp3, sp1] # ... |
# 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 not u... |
lanche = ('Hambúrger', 'Suco','Pizza', 'Pudim', 'Batata Frita')
for pos, comida in enumerate(lanche):
print(f'Eu vou comer {comida} na posição {pos}')
print('Comi muito!')
|
class Image:
"""
A representation of graphical content.
:param path: Path to the image. Allowed values can be local file
(relative or absolute path) or URL (HTTP or HTTPS). Relative paths
will be interpreted relative to the application module directory.
"""
def __init__(self, path):... |
# VS Code Python Tutorial
# https://code.visualstudio.com/docs/python/python-tutorial
msg = "Hello World"
print(msg)
|
# -*- coding: utf-8 -*-
# This file is part of Shuup Admin Channel
#
# Copyright (c) 2019, Christian Hess. All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#: Set the channel layer to use when sending messages
#: Keep Non... |
# this is a base class
class WindSensor(object):
def __init__(self):
return
def read(self):
return 0
|
def euc_2d(n1, n2):
"""
The euclidean distance for 2D cartesian nodes
:param n1: first node
:type n1: Node
:param n2: second node
:type n2: Node
:return: the euclidean distance between first node and second node in 2D space
:rtype: float
"""
return ((n1.x - n2.x)**2 + (n1.y - n2... |
"""
This is my sixth prime number project,
it is the fastest function I have created untill now,
and it is also very optimised that can find lots of
prime numbers in short period of time.
It will find all prime numbers between 2 and 'End'.
1. At first we create an Prime array of [2, 3]
2. Then until we reach the En... |
def read_in():
data = []
while value := input():
level = 0
res = []
for s in value:
if s == '[':
level += 1
elif s == ']':
level -= 1
elif s != ',':
res.append((int(s), level))
data.append(res)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Permute vector to minimize scalar product
jill-jenn vie et christoph durr - 2014-2018
"""
# snip{
def min_scalar_prod(x, y):
"""Permute vector to minimize scalar product
:param x:
:param y: x, y are vectors of same size
:returns: min sum x[i] * y[si... |
class Node(object):
def __init__(self, v):
self.next = None
self.v = v
class LinkedList(object):
def __init__(self):
self.root = None
self.n = 0
def put(self, v):
node = Node(v)
node.next = self.root
self.root = node
self.n += 1
def __l... |
# You go on a wonderful holiday (perhaps to jail, if you don’t like happy exercises) leaving on day number 3 (a Wed).
# You return home after 137 sleeps.
# Write a general version of the program which asks for the starting day number, and the length of your stay,
# and it will tell you the name of day of the week you w... |
class Solution:
def XXX(self, head: ListNode) -> ListNode:
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
|
# https://leetcode.com/problems/letter-case-permutation/
# By Jiapeng
# Runtime: 64 ms, faster than 61.44% of Python3 online submissions for Letter Case Permutation.
# Memory Usage: 14.4 MB, less than 50.53% of Python3 online submissions for Letter Case Permutation.
class Solution:
def letterCasePermutation(self,... |
file_path_pharma_class = '/home/kevinxin/drug/drugcentral/2018.6/pharma_class.csv'
#df_drugcentral_pharma_class = pd.read_csv(file_path_pharma_class, sep=",", names=['_id', 'struc_id', 'role', 'description', 'code', 'source'])
file_path_faers = '/home/kevinxin/drug/drugcentral/2018.6/faers.csv'
#df_drugcentral_faers =... |
#!/usr/bin/env python
class Cow(object):
pass
class Fox(object):
def get_noise(self):
return "Ring-ding-ding-ding-dingeringeding"
def ask(obj):
print('What goes "{}?"'.format(obj.get_noise()))
ask(Fox())
ask(Cow())
|
class Tank:
"""My Aquarium.
Fish and shrimps can live in it.
The aquarium can be a freshwater or saltwater aquarium.
We can adjust PH and temperature up or down.
"""
def __init__(self, *, aquarium_type="freshwater", ph=7, temperature=30):
"""Initialize."""
self.aquarium_type =... |
# Find minimum swaps to satisfy a[i]%3 = i%3 property in a a given array
a = [0, 1, 3, 2, 1]
a_i = []
diff = 0 # difference in a,a_i values
n = len(a)
# hashmaps containing mod 3 values and indices 0(n)
index_hm, value_hm = dict(), dict()
for i in range(0, n):
# modded value hashmap
try:
value_hm[a[i] ... |
# -*- coding: utf-8 -*-
class MyCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def __privateCountFun(self):
print('这是私有方法')
self.__secretCount += 1
self.publicCount += 1
#print (self.__secretCount)
def publicCountFun(self):
print('这是公共方法'... |
cidade = ' Santo Dummond'
cidadeSeparado = cidade.split()
print('Santo' in cidadeSeparado[0])
#ou assim
#colocando um strip para eliminar espaços e deixando tudo maiusculo
#para conferir independente de como foi escrito
cidadeFormatada = cidade.strip()
print(cidadeFormatada[:5].upper() == 'SANTO')
|
########################
## GENERAL PARAMETERS ##
########################
DATA_PATH = "data/"
DATA_SETTINGS = "data_settings.py"
DATA_EXT = ".shelf"
MODEL_PATH = "models/"
MODEL_SETTINGS = "model_settings.py"
MODEL_SETTINGS_LOADER = "model_settings_loader.py"
SIMULATION_SETTINGS = "simulation_settings.py"
RESULTS_... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class Policy(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is ... |
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LnkdList:
def __init__(self):
self.head = None
l1 = LnkdList()
l1.head = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
# Link first Node to second node
l1.head.next = e2
# Link second Node to third node
e2.next ... |
class Credentials:
"""
Class that creates new instance for credentials
"""
credentials_list=[]#an empty credentials list
def __init__(self,account,username,password):
"""
new application and credentials are being generated
"""
self.account=account
se... |
# from resources.session import UserInfo
def router(api) -> None:
# api.add_resource(UserInfo, "/userinfo")
pass
|
#Load the data
DATA_DIR = "ml-25/"
rating = pd.read_csv(DATA_DIR + "ratings.csv")
nb_entries = rating.shape[0]
print("Number of entries : %d " %nb_entries)
#Load the movies files in order to create the id_to_title dictionary and complete the rating dataframe
movies = pd.read_csv(DATA_DIR + "movies.csv")
id_to_title = ... |
# -*- coding: utf-8 -*-
BOT_NAME = 'scouter'
SPIDER_MODULES = ['scouter.spiders']
NEWSPIDER_MODULE = 'scouter.spiders'
ROBOTSTXT_OBEY = False
CONCURRENT_REQUESTS = 16
DOWNLOAD_DELAY = 2
RANDOMIZE_DOWNLOAD_DELAY = True
COOKIES_ENABLED = False
MONGO_URI = 'mongodb://scouter:1A2B3C4D_@127.0.0.1:27017'
MONGO_DATABASE... |
# Interface which returns final rel scores after aggregation of different module scores
class Aggregator:
"""
Basic Interface for Aggregators of different relation linking module scores
"""
def __init__(self):
pass
def aggregate(self, scores_dict, params=None):
"""
Takes in ... |
class FileMetadataError(Exception):
"""Base file metadata driver exception."""
class FileMetadataDriverError(FileMetadataError):
"""Exception raised when a driver encounters an unexpected error."""
|
#
# PySNMP MIB module IPSEC-SPD-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/IPSEC-SPD-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:18:27 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( ... |
# Query to get water leak calls and daily precipitation
query = """
SELECT hpd311calls.*, weather.prcp
FROM hpd311calls
JOIN weather
ON hpd311calls.created_date = weather.date
WHERE hpd311calls.complaint_type = 'WATER LEAK';
"""
# Load query results into the leak_calls data frame
leak_calls = pd.read_sql(que... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def cats(number=100):
return "\U0001F431 " * number
def green_circle(number=1):
return "\U0001F7E2 " * number
def blue_circle(number=1):
return "\U0001F535 " * number
def red_circle(number=1):
return "\U0001F534 " * number
def yellow_circle(number=1):
... |
class Solution(object):
def subsets(self, nums):
res = []
def children(j, tmp):
res.append(tmp)
for i in range(j, len(nums)):
children(i + 1, tmp + [nums[i]])
children(0, [])
return res
class Solution:
def subsets(self, nums: [int]) -> [[i... |
# Exercise 5: Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
celsius = float(input('Enter celsius temperature: '));
fahrenheit = (celsius * 9/5) + 32;
print('Fahrenheit:',fahrenheit); |
# -*- coding: utf-8 -*-
X = int(input())
Y = int(input())
start, end = min(X, Y), max(X, Y)
for i in range(start + 1, end):
if ((i % 5) in [2, 3]):
print(i) |
keys = {
'MONGO_DBNAME' : 'your_database_name',
'MONGO_URI' : 'your_mongo_uri_name'
}
|
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'System and method are not included'},
{'abbr': 1, 'code': 1, 'title': 'System and method are included'},
{'abbr': 2,
'code': 2,
'title': 'System, method, reference date, climate date (from) and climate '
... |
# -*- coding: utf-8 -*-
# Apple Slicer
#
# Copyright (c) 2015 fedoco <fedoco@users.noreply.github.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including withou... |
def get_alignment(pairs, s1, s2):
if len(pairs) == 0: return s1, s2
m, n = len(s1), len(s2)
c1, c2 = [], []
ipairs, jpairs = zip(*sorted(pairs))
i,j = 1,1
while i <= m or j <= n:
iIsNotGap = j in jpairs or j > n
jIsNotGap = i in ipairs or i > m
if not(iIsNotGap or jIs... |
# Nícolas Ramos
# impressão colorida no console linux,
# para windows tem que incluir a biblioteca ansi no config.sys
# device=ANSI.SYS
print('meu programa em python')
a = 2
b = 3
soma = a + b
subtracao = a - b
multiplicacao = a * b
divisao = a / b
resto = a % b
vermelho = '\033[31m'
verde = '\033[32m'
azul = '\033[3... |
def isPalindrome(string):
i, j = 0, len(string) - 1
while i < j:
if string[i] != string[j]:
return False
i += 1
j -= 1
return True
|
class Solution:
"""
@param nums: an integer array
@return: the maximum product
"""
def maximumProduct(self, nums):
# Write your code here
nums=sorted(nums)
a = nums[-1]*nums[-2]*nums[-3]
b = nums[0]*nums[1]*nums[-1]
if a>b:
return a
else:
... |
TORTOISE_ORM = {
"connections": {"default": "postgres://blog:blog@localhost:5432/blog"},
"apps": {
"models": {
"models": ["src.app.user.models", "aerich.models"],
"default_connection": "default",
},
},
}
|
class BaseView:
def prepare_image(self): raise NotImplementedError
def show_image(self): raise NotImplementedError
def show_centered_string(self, text, font, y = None): raise NotImplementedError
def show_welcome(self): raise NotImplementedError
|
class PIWebAsyncException(Exception):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class APIException(PIWebAsyncException):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class SerializationError(APIException):
def __init__(self, *args: ... |
def index():
db.entidad.id.readable = False
create = editable = deletable = auth.has_membership('editor_economia')
grid = SQLFORM.grid(db.entidad, create=create, editable=editable, deletable=deletable)
return locals() |
class Note:
def __init__(self, name, note):
if type(name) is not str:
raise TypeError('Name must be a string')
if name is None:
raise TypeError('Name cannot be None')
if name == '':
raise ValueError('Name cannot be empty')
if type(note) is not floa... |
def main():
red = pygame.Rect(700,300,space_w,space_h)
yellow = pygame.Rect(100,300,space_w,space_h)
RED_bullets =[]
YELLOW_BULLETS = []
red_health = 20
yellow_health = 20
Clock = pygame.time.Clock()
run = True
while run:
Clock.tick(fps)
for event i... |
def iprint(text):
print ("INFO: " + str(text))
def dprint(desc, content):
print ("-" * 20 + desc + "-" * 20)
print (content)
print ("-" * 40) |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['theme']
# Cell
def theme():
"""Niklas Morberg's personal theme for Altair"""
return {
"config": {
"axis": {
"labelFontSize": 12,
"labelColor": "#666",
... |
s3gis_tests = load_module("tests.unit_tests.modules.s3.s3gis")
def test_OpenStreetMap():
s3gis_tests.layer_test(
db,
db.gis_layer_openstreetmap,
dict(
enabled = True,
name = "test OSM layer",
url1 = "http://otile1.example.com/tiles/1.0.0/osm/",
... |
__author__ = 'felix.shaw@tgac.ac.uk - 29/07/2016'
class CopoRuntimeError(RuntimeError):
def __init__(self, message, errors=dict()):
# Call the base class constructor with the parameters it needs
super(CopoRuntimeError, self).__init__(message)
self.errors = errors
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# __about__.py
"""PyEMD metadata"""
__title__ = 'pyemd'
__version__ = '0.5.1'
__description__ = ("A Python wrapper for Ofir Pele and Michael Werman's "
"implementation of the Earth Mover's Distance.")
__author__ = 'Will Mayner'
__author_email__ = 'wmay... |
#
# ktool | kswift
# demangle.py
#
#
#
# This file is part of ktool. ktool is free software that
# is made available under the MIT license. Consult the
# file "LICENSE" that is distributed together with this file
# for the exact licensing terms.
#
# Copyright (c) kat 2022.
#
def demangle(name):
... |
class Solution(object):
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
if __name__ == "__main__":
s = Solution()
assert s.toLowerCase("Hello") == "hello"
assert s.toLowerCase("here") == "here"
assert s.toLowerCase("LOVELY")... |
"""
File: class_reviews.py
Name: DiCheng
-------------------------------
At the beginning of this program, the user is asked to input
the class name (either SC001 or SC101).
Attention: your program should be case-insensitive.
If the user input -1 for class name, your program would output
the maximum, minimum, and avera... |
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'npapi',
'type': 'none',
'direct_dependent_settings': {
'include_dirs': [
# Som... |
# encoding: utf-8
# module cv2.motempl
# from /home/davtoh/anaconda3/envs/rrtools/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so
# by generator 1.144
# no doc
# no imports
# Variables with simple values
__loader__ = None
__spec__ = None
# functions
# real signature unknown; restored from __doc__
... |
hands = {'Aces', 'Kings', 'Queens', 'Jacks', 'Tens', 'Nines', 'Full House', 'Five of a Kind', 'Straight Flush', 'Royal Flush'}
# State
player_combos = dict() # dictionary of dictionaries: player => scores per combo
# setup the new game
while True:
name = input('Enter name of next player (or return if finished): ... |
"""
Award Budget Cuts
The awards committee of your alma mater (i.e. your college/university) asked for your assistance with a budget allocation problem they’re facing. Originally, the committee planned to give N research grants this year. However, due to spending cutbacks, the budget was reduced to newBudget dollars an... |
"""
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
合法的ip格式(0~255).(0~255).(0~255).(0~255)
"""
def restore_ip(ip_str):
ip_list=list(ip_str)
valid_list=[]
for i1 in range(1,4)... |
"""
1339. Maximum Product of Splitted Binary Tree
Medium
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.
Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return ... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class NodeWrapperCustom(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and th... |
class Solution:
# Loop and Divide (Accepted), O(log n) time, O(1) space
def isPowerOfThree(self, n: int) -> bool:
if n < 1:
return False
while n != 1:
n /= 3
if n != int(n):
return False
return True
# Two conditions (Top Voted), O(... |
t = int(input())
for i in range(t):
s = list(map(str, input().rstrip()))
answer = ''
if s.count('x') >= 8:
answer = 'NO'
else:
answer = 'YES'
print('#{} {}'.format(i+1, answer))
|
#!/usr/bin/env python3
def has_module(module):
try:
__import__(module)
return True
except ImportError:
pass
|
def main():
lenght = int(input('Lenght: '))
array = [None] * lenght
for i in range(lenght):
array[i] = int(input('Item {}: '.format(i)))
print('Source array: ', array)
for i in range(lenght):
key = array[i]
j = i - 1
while j >= 0 and array[j] > key:
... |
#Enter a number using custom input
a = int(input("Enter a nmber: "))
# if number is divisible by both 3 and 5 it returns fizzbuzz
if (a%5 == 0 and a%3 == 0):
print("FizzBuzz")
# if number is divisible by 3 it returns fizz
elif(a%3 == 0 ):
print("Fizz")
# if number is divisible by 5 it returns buzz
elif (a%5 ... |
"""
Product Store
Write a class Product that has three attributes:
type
name
price
Then create a class ProductStore, which will have some Products and will operate with
all products in the store. All methods, in case they can’t perform its action, should
raise ValueError with appropriate error information... |
# Copyright 2020 BlueCat Networks. All rights reserved.
# Default Configuration ID
DEFAULT_CONFIG_NAME = 'Default'
# Default View ID
DEFAULT_VIEW_NAME = 'test1'
DEFAULT_VIEW_ID = 100910
|
"""
The Program receives from the USER a MONTH and a DAY of the year
and returns (displaying it) the corresponding season, knowing that:
- March 20 -> first day of Spring
- June 21 -> first day of Summer
- September 22 -> first day of Fall (or Autumn)
- December 21 -> first day of Winter
"""
# START Definition of FUNC... |
"""
You are given a list of integers List[] of size N.
Your task is find a position p(0<=p<=N-1) in the List[], such that the addition
of all integers to the left of p should be exactly equal to addition of all the
integers to the right of p.
If all the integers are at one end of p ,assume the sum of other end is 0.
If... |
class BaseShoulderTap:
def __init__(self, payload, payloadId, imsi):
'''Creates a representation of a Shoulder-Tap.
Parameters
----------
payload : bytes
The payload contained by the shoulder-tap.
payloadId : int or str
The ID of the shoulder-tap, as p... |
#!/usr/bin/python3
def main():
n = 42
s = 'This is a {} \nstring!'.format(n)
i = r'This is a {} \nstring!'.format(n) # Raw string
y = '''multiple line of strings
this is a string'''
print(s)
print(i)
print(y)
if __name__ == "__main__" : main() |
class Employee:
"""Common base class for all employees"""
empCount =0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
... |
#
# class CSS(object):
# """
# This class helps with some html css parameters.
# """
# @staticmethod
# def basic():
# """
# Returns a simple css.
# """
# basic = """
# body {
# background-color: white;
# }
#
# h1 {
# color: black;
# text-align: center;
# }
#
# p {
# font-family: verd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.