content stringlengths 7 1.05M |
|---|
def countAndSay(n):
seq = "1"
for i in range(n-1):
seq = getNext(seq)
return seq
def getNext(seq):
i, next_seq = 0, ""
while i < len(seq):
count = 1
while i < len(seq) -1 and seq[i] == seq[i+1]:
count += 1
i += 1
next_seq += str(count) + seq[... |
# coding=utf-8
"""Edit distance problem Python solution."""
def edit_dist(s1, s2):
dp = [[None for y in range(len(s2) + 1)] for x in range(len(s1) + 1)]
for x in range(len(s1) + 1):
for y in range(len(s2) + 1):
if not x:
dp[x][y] = y
elif not y:
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
sunpy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
class SunpyWarning(Warning):
"""
The base warni... |
# -*- coding: utf-8 -*-
def get_default_options(num_machines=1, max_wallclock_seconds=1800):
"""
Return an instance of the options dictionary with the minimally required parameters
for a JobCalculation and set to default values unless overriden
:param num_machines: set the number of nodes, default=1
... |
# Instead of parsing cromwell metadata we pass the intermediate SS2 files
ANALYSIS_FILE_INPUT = {
"input_uuid": "0244354d-cf37-4483-8db3-425b7e504ca6",
"input_file": "",
"pipeline_type": "SS2",
"workspace_version": "2021-10-19T17:43:52.000000Z",
"ss2_bam_file": "call-HISAT2PairedEnd/cacheCopy/02443... |
def login():
for n in range(3):
username = input("username: ")
password = input("password: ")
print()
if username == "admin" and password == "super_secure":
return True
print("Nice try @ssh013")
def main():
session = login()
if session:
print("Welcom... |
'''
Rooms
'''
f_number = int(input())
l_number = int(input())
step = l_number - f_number + 1
if ((l_number % step == 0) and (f_number % step == 1)):
print('YES')
elif (step == 1):
print('YES')
else:
print('NO')
|
class ConfigError(Exception):
...
class HTTPException(Exception):
def __init__(self, status_code: int, detail: str = None) -> None:
self.status_code = status_code
self.detail = detail or 'no detail'
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{... |
# https://leetcode.com/problems/find-numbers-with-even-number-of-digits/
class Solution:
def findNumbers(self, nums):
#1 with string and len
count=0
for i in range(0,len(nums)):
if (len(str(nums[i]))%2==0): count+=1
return count
'''
#2 Using... |
sounds = {
#'ON': 'data/bin/sounds/on.mp3',
'SUCCESS': ['data/bin/sounds/wicked_sick.mp3', 'data/bin/sounds/holyshit.mp3'],
#'FAIL': 'data/bin/sounds/fail.mp3',
'STAGED': 'data/bin/sounds/pwned.mp3',
'KILL': 'data/bin/sounds/killing_spree.mp3',
'STAGER': 'data/bin/sounds/firstblood.mp3'
} |
class CodeforcesException(Exception):
"""Exception raised for errors in the input salary.
Attributes:
message -- explanation of the error
"""
def __init__(self, message="Salary is not in (5000, 15000) range"):
self.message = message
super().__init__(self.message)
class Codefo... |
# Data mapping functions
def zigbee2mqtt_device_name(topic, data, srv=None):
"""Return the last part of the MQTT topic name."""
return dict(name=topic.split("/")[-1])
# Filter functions
def filter_xiaomi_aqara_battery_low(topic, message):
"""Ignore messages from Xiaomi Aqara when the battery is OK."""... |
# 코딩도장 문제풀이
# Question number. 414
# Special Sort
# http://codingdojang.com/scode/414
# Author: Lee Jeongwoo
# Github name: zao95
# ========== Question ==========
# 구글 전화면접 문제
# n개의 정수를 가진 배열이 있다. 이 배열은 양의정수와 음의 정수를 모두 가지고 있다. 이제 당신은 이 배열을 좀 특별한 방법으로 정렬해야 한다.
# 정렬이 되고 난 후, 음의 정수는 앞쪽에 양의정수는 뒷쪽에 있어야 한다. 또한 양의정수와 음의정수의... |
# link:
#########
# Approach1: find rotation index using BS and using BS search on left and
# right part of rotation index
#
########
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0:
return -1
if len(nums) == 1:
... |
# -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-03-25
算法思想:字符串相乘
"""
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if len(num1) > len(num2):
return self.multiply(num2, num... |
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
# Time complexity O(n)
array = [0] * len(indices)
for idx in range(len(indices)):
array[indices[idx]] = s[idx]
return "".join(array)
class Solution:
def restoreString(self,... |
FI_NAME, PYPATH = (
"preparation.py",
"/home/nversbra/anaconda3/envs/py36/bin/python"
)
with open('command_lines.txt', 'w') as f_output:
for i in range(4096):
n, file_name = i, ""
while n > 0:
file_name += str(n % 2)
n //= 2
file_name = file_name +... |
# Scrapy settings for news project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.ht... |
{
"targets" : [
{
"target_name" : "edflib",
"sources" : ["../lib/edf.cpp", "edfjs.cpp"],
"conditions" : [
[ "OS == \"mac\"", {
"xcode_settings": {
"OTHER_CPLUSPLUSFLAGS" : ["-std=c++11","-stdlib=libc++"],
"OTHER_LDFLAGS": ["-stdlib=libc++"],
"MA... |
# 配置cookies
COOKIES = None
# 配置代理
PROXIES = None
# 是否正在登录
BEING_LOG = False
|
def number(a,b):
if(a%2==0 and b%2==0):
print(min(a,b))
# if(a>b):
# print (b)
# else:
# print (a)
elif(a%2!=0 and b%2!=0):
print(max(a,b))
# if(a>b):
# print (a)
# else:
# print (b)
else:
print(max(... |
class Bin:
def __init__(self, index, floor, ceiling, is_last_bin):
self.index = index
self.floor = floor
self.ceiling = ceiling
self.range = self.floor - self.ceiling
self.is_last_bin = is_last_bin
self.members_asc = []
def count(self):
return len(self.members_asc)... |
class PlayerBase:
def __init__(self, position=None, team=None):
self.position = position
self.team = team
self.hand = []
class Players(PlayerBase):
def __init__(self, number_of_players=4):
if number_of_players % 2:
raise Exception('Error: number of players must ... |
logo_array = [['--------------------------------------',
'--------------------------------------',
'--------------------------------------',
'---\\\\\\\\\\\\\\\\\\\\\\\\-----------------------',
'----\\\\\\ \\\\\\----------------------',
'-----\\\\\\ \\\\\\---------------------',
'------\\\\\\ \\\\\\\\\\... |
with open("./../dataset/pib_municipio_2010_a_2018.txt", "r", encoding="utf8") as file:
file = file.readlines()
content = []
names = []
# Armazena os nomes dos municípios na lista 'names'
for line in file[1:]:
line = line.strip().split(";")
if line[0] == "2010":
if lin... |
if '폐업' in '폐업자':
print(1)
|
def remove_none_entries(dictionary):
keys = [k for k in dictionary if dictionary[k] is None]
for k in keys:
del dictionary[k]
def make_dict_body(object):
if object is None:
return dict()
if hasattr(object, 'to_dict'):
return object.to_dict()
return object
def get_body_o... |
class Environment(object):
def __init__(self, fl_server):
self.fl_server = fl_server
self.fl_server.boot()
# Run federated learning
self.fl_server.run()
def reset(self):
pass
# Delete global model
os.remove(self.fl_server.paths.mod... |
#
# PySNMP MIB module SWL2MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SWL2MGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:13:33 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,... |
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def is_multiple(number, multiple):
return number % multiple == 0
def main():
i = 1
j = 0
while(i < 1000):
if(is_mul... |
#@title Train TUNIT Epoch
def train_TUNIT(data_loader, networks, opts, epoch, args, additional):
# avg meter
d_losses = AverageMeter()
d_advs = AverageMeter()
d_gps = AverageMeter()
g_losses = AverageMeter()
g_advs = AverageMeter()
g_imgrecs = AverageMeter()
g_styconts = AverageMeter... |
class BaseSave:
def file(self, path, *args, **kwargs):
raise NotImplementedError("Not implemented yet")
def csv(self, path, *args, **kwargs):
raise NotImplementedError("Not implemented yet")
def xml(self, path, *args, **kwargs):
raise NotImplementedError("Not implemented y... |
#Number letter counts#
"""
If the numbers 1 to 5 are written out in words: one, two, three, four, five,
then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand)
inclusive were written out in words,
how many letters would be used?
NOTE: Do not count spaces or hyph... |
#!/usr/bin/env python
"""
_BossAir_
MySQL DAO libraries for BossAir
"""
__all__ = []
|
#!/usr/bin/python
class Toy():
"""
Toy definition
"""
# static class data
count = 1
def __init__(self,name):
"""
Constructor
"""
self.name = name
self.id = Toy.count
Toy.count += 1
|
class Constants:
ha2kcalmol = 627.509 # Hartee^-1 kcal mol^-1
ha2kJmol = 2625.50 # Hartree^-1 kJ mol^-1
eV2ha = 0.0367493 # Hartree ev^-1
a02ang = 0.529177 # Å bohr^-1
ang2a0 = 1.0 / a02ang # bohr Å^-1
kcal2kJ = 4.184 # kJ kcal^-1
class Unit:
pass
class KjMol(Uni... |
#! /usr/bin/env python3
# -*- encoding: utf-8 -*-
# import os
# import sys
press_id_file = "/boot/PRESS_ID"
def get_press_id():
# Get the press_id from /boot/PRESS_ID file
try:
with open(press_id_file) as f:
PRESS_ID = f.read()
if PRESS_ID is not None:
return... |
class MemoryStorage:
def __init__(self) -> None:
self.data: dict[str, str] = {}
def set(self, key: str, value: str) -> None:
self.data[key] = value
def get(self, key: str) -> str:
return self.data.get(key, "")
def close(self) -> bool:
# NOTE: ideally, I would want this... |
'''
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def mergeTwoLists1(self, l1, l2):
... |
'''
Run this file as is from cp,,and line as :
python file1.py
'''
print("File1 __name__ = %s" % __name__)
print("Full path/location for File1 __file__ = %s" % __file__)
if __name__ == "__main__":
print("File1 is being run directly")
else:
print("File1 is being imported")
# Output:
# File1 __name__ = __main_... |
# Code generated by font_to_py.py.
# Font: Robotol.ttf
# Cmd: ./font_to_py.py -x Robotol.ttf 30 myfont.py
version = '0.33'
def height():
return 31
def baseline():
return 24
def max_width():
return 26
def hmap():
return True
def reverse():
return False
def monospaced():
return False
def mi... |
# Declaracion de operaciones
def swap(a, b):
''' Recibe dos elementos y los intercambia '''
aux = a
a = b
b = aux
return (a, b)
def main():
''' Cuerpo principal '''
# Entrada
a = input('Ingrese el valor de a: ')
b = input('Ingrese el valor de b: ')
# Proceso
print('Antes: ... |
# El * se usa para indicarle una cantidad indefinida
def devuelveSubElementos(*elementos):
for iterador in elementos:
# Devuelve un subelemento del elemento elemento dado
yield from iterador
nombres = devuelveSubElementos("John", "Doe")
# Imprime los sub elementos del primer elemento
print(next(no... |
sample_rate = 16000
content_factor = 5 * 1e-9
loudness_factor = 0
style_factor = 1
variation_factor = 0
zero_factor = 0
fft_size = 1024
|
# The if and else blocks allow us to branch execution depending on
# whether a condition is true or false. But what if there are more conditions
# to take into account? This is where the elif statement, which is short for
# else if, comes into play. But before we jump into how to use it, let's take a
# look at why we n... |
class NoClassificationError (Exception):
"""
When a ClassificationElement has no mapping yet set, but an operation
required it.
"""
class MissingLabelError(Exception):
"""
Raised by ClassifierCollection.classify when requested classifier labels
are missing from collection.
"""
def... |
"""939. Binary Tree Kth Floor Node
"""
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root node
@param k: an integer
@return: the number of nodes in the k-th layer of the... |
# OCR Calculator
# Copyright (C) 2019 Rudolf Copi Eckelberg
#
# This module is part of OCR Calculator and is under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
'''Example of a valid settings.py file and default script behavior.
Copy or link this file as settings.py to start using the ocr_calcu... |
N,x=map(int,input().split())
A=list(map(int,input().split()))+[0]
ans=0
for i in range(N):
eated=max(0,A[i]+A[i-1]-x)
ans+=eated
A[i]-=eated
print(ans) |
num = int(input())
if num >= 1 and num <= 9:
print('한 자리 숫자입니다')
elif num >= 10 and num <= 99:
print('두 자리 숫자입니다')
else:
print('세 자리 숫자입니다')
|
# 5. Pounds to Dollars
# Write a program that converts British pounds to US dollars formatted to the 3th decimal point.
# 1 British Pound = 1.31 Dollars
pound = int(input())
dollars = pound * 1.31
print(f'{dollars:.3f}')
|
class I2C():
def __init__(self, interfaceNo):
self.interfaceNo = interfaceNo
self._read_result = {}
self._read_arguments = {}
self._write_arguments = {}
def set_readfrom_mem_result(self, register, result_bytes):
self._read_result[register] = result_bytes
def readfr... |
# encoding: utf-8
# module Tekla.Structures.Plugins calls itself Plugins
# from Tekla.Structures.Plugins,Version=2017.0.0.0,Culture=neutral,PublicKeyToken=2f04dbe497b71114
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class AutoDirectionTypeAttribute(Attribute):
"""
AutoDirectionTy... |
# List variables are iterable and hold elements in series
shopping_list = ["Tomatoes", "Bananas", "Crackers",
"Sugar", "Icecream", "Bread", "Bananas", "Chocolate"]
print(f"Here's the shopping list:\n{shopping_list}.\n")
# You can count the number of items in a list
num_items = len(shopping_list)
pri... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2018, 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
# Stubs for commonly-mocked classes
class StubConfig(object):
image_build_method = None
release_env_va... |
class HaydiException(BaseException):
pass
class TimeoutException(HaydiException):
pass
|
"""
SimPy's monitoring capabilities will be added in version 3.1.
"""
|
#map(funcao, *sequencia de args) --> Object map
def qua(x): return x**2
mapa = map(qua, [1, 2, 3, 4, 5])
listmap = list(map(qua, [1, 2, 3, 4, 5]))
ran = tuple(map(qua, range(10)))
lamb = list(map(lambda x: x**3, range(10)))
print(f'''
map(...) = {mapa}\n
list(map(...)) = {listmap}\n
tuple(map(..., range(10))) = {... |
# Your Romeo API key, required for accessing the FACT API
# override this in your local config
ROMEO_API_KEY = ""
# Base URL for requests against the FACT API
FACT_BASE_URL = "http://www.sherpa.ac.uk/fact/api-beta"
CLIENTJS_FACT_PROXY_ENDPOINT = "/fact"
|
class AssignmentCode:
def __init__(self,var,left,op=None,right=None):
self.var = var
self.left = left
self.op = op
self.right = right
def __str__(self):
if(self.op==None):
return f'{self.var} = {self.left}'
return f'{self.var} = {self.left}{self.op}{s... |
# -*- coding: utf-8 -*-
class Animal:
pass
class Dog(Animal):
def __init__(self,name):
self.name=name
class Cat(Animal):
def __init__(self,name):
self.name=name
class Person:
def __init__(self,name):
self.name=name
self.pet=None
class Employee(Person):
def __init... |
SEARCH_PARAMS = {
"Sect1": "PTO2",
"Sect2": "HITOFF",
"u": "/netahtml/PTO/search-adv.htm",
"r": "0",
"p": "1",
"f": "S",
"l": "50",
"Query": "",
"d": "PTXT",
}
SEARCH_FIELDS = {
"patent_number": "PN",
"issue_date": "ISD",
"title": "TTL",
"abstract": "ABST",
"clai... |
class Params:
DATA_PATH = '../data/mimic-iii-clinical-database-1.4/NOTEEVENTS.csv'
# Table attributes
HADM_ID_STR = 'HADM_ID'
CATEGORY_STR = 'CATEGORY'
DESCRIPTION_STR = 'DESCRIPTION'
TEXT_STR = 'TEXT'
STORETIME_STR = 'STORETIME'
# Category attribute - table values
DISCHARGE_SUM... |
#!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'yīnlián'
CN=u'阴廉'
NAME=u'yinlian12'
CHANNEL='liver'
CHANNEL_FULLNAME='LiverChannelofFoot-Jueyin'
SEQ='LR11'
if __name__ == '__main__':
pass
|
class MockError(object):
def __init__(self, status, reason):
self.status = status
self.reason = reason
self.extra = {'retry_after': 9, 'retry_limit': 10}
def resolve_submitted(error_message, name):
return MockError('submitted', 'a reason')
def resolve_unavailable(error_message, name):... |
"""
Module to allow for the details on the extension to be encapsulated.
"""
# pylint: disable=too-many-instance-attributes
class ExtensionDetails:
"""
Class to allow for the details on the extension to be encapsulated.
"""
# pylint: disable=too-many-arguments
def __init__(
self,
... |
with open("data.txt", 'w') as f:
f.write("2 10 1 2 10\n")
f.writelines(["1 2 1\n" for i in range(5)] + ["2 1 1\n" for i in range(5)])
# f.write("1 2 2\n")
|
test = {
'name': 'Problem 1',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> ps = ['short', 'really long', 'tiny']
>>> s = lambda p: len(p) <= 5
>>> choose(ps, s, 0)
'short'
>>> choose(ps, s, 1)
'tiny'
>>> ... |
def str_to_bool(x):
x = str(x)
return x.lower() in ('true', 't', 'yes', 'y', '1')
|
DEFAULT_ENDPOINTS_PATH = "endpoints.yml"
DEFAULT_CREDENTIALS_PATH = "credentials.yml"
DEFAULT_CONFIG_PATH = "config.yml"
DEFAULT_DOMAIN_PATH = "domain.yml"
DEFAULT_ACTIONS_PATH = "actions"
DEFAULT_MODELS_PATH = "models"
DEFAULT_DATA_PATH = "data"
DEFAULT_RESULTS_PATH = "results"
|
#grid setup
path = 'out'
Nx = 20
Ny = 20
NxCell = 2
NyCell = 2
xmin = ymin = 0.0
xmax = ymax = 1.0
|
def calcular_itbms(valor):
"""
Calcualr el ITBMS (7%)
Admite un valor subtotal para calcular el total (incluyendo el 7% del ITBMS)
Parameters
-----------
valor : float
subtotal a aplicar ITBMS
Returns
-------
float
Total con el ITBMS aplicado
"""
return val... |
a=str(input("Enter the string:"))
b=a.split()
b.sort()
print("The sorted words are:")
for i in b:
print(i)
|
# Необходимо реализовать модуль divisor_master. Все функции модуля принимают на вход натуральные числа от 1 до 1000.
# Модуль содержит функции:
# 1) проверка числа на простоту (простые числа - это те числа у которых делители единица и они сами);
def PrimeNum(n):
if n % 2 == 0:
return n == 2
d = 3
wh... |
# pull an actual user out of the db to associate with these ideas
ideas =[
{
'users_id': 1,
'title':'My color pallete for my home',
"description":'Here is the color pallete for my apartment',
'image_url':'https://i.pinimg.com/564x/8c/f0/60/8cf06020e82ca94ddd8f65b990e84621.jpg',
... |
word = input()
word_list = list(word)
reduce = []
pattern = int(input())
for index, letter in enumerate(word):
counter = 0
oindex=index
for i in range(pattern):
if index > (len(word)-1):
counter = 1
break
if letter == word[index]:
counter == 0
el... |
with open('somefile.txt', 'a') as the_file:
with open("wider_face_train_bbx_gt.txt") as fp:
currentFileName = ""
nextFileName = 0
nextBoundry = 1
boundryStart = 0
isValidBoundry = False
wroteFileName = False
for i, line in enum... |
class Cat:
def __init__(self, new_name, new_age):
self.name = new_name
self.age = new_age
def __str__(self):
return "name: %s, age: %d." % (self.name, self.age)
def eat(self):
print("%s eat fish." % self.name)
def drink(self):
print("%s is drinking Cola..." % s... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
head = now = ListNode(0)
... |
def abc(base,powe):
result = 1
for index in range(powe):
result = result * base
return result
def add(a,b):
sumb = a + b
return sumb
print(abc( int(input("Enter the base num : ")),int(input("Enter the power num : "))))
print(add( int(input("Enter num1 : ")),int(input("Enter num2 : ")))) |
description = 'Stanford SR-850 lock-in amplifier, for susceptibility measurements'
group = 'optional'
includes = ['base']
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(
M = device('nicos_mlz.mira.devices.sr850.Amplifier',
description = 'SR850 lock-in amplifier',
tangodevice... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 07:37:45 2020
染病正確率計算,有病率估計
參考: https://www.facebook.com/permalink.php?story_fbid=2965126610218341&id=100001630939939
@author: wuulong
"""
#sick_rate = 0.014 # 有病率
#detect_rate = 0.99 # 準確率
sick_tbl = [0.0001,0.001,0.014,0.1]
detect_tbl = [0.3,0.... |
def getsidelen(num: int):
i = 3
while True:
if i*i > num:
return i
i += 2
# inp = 44
inp = 361527
steps = 0
field = getsidelen(inp)
print(field) # we need 603x603 fields = 363609
steps += field // 2 # steps to the center of 1 of the axis
diff = 0
mid1 = (field * field) - fiel... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashTable = dict()
for i in range(len(nums)):
delta = target - nums[i]
if delta in hashTable:
return (i, hashTable[delta])
else:
hashTable[nums[i]] = i
... |
class Bar: pass
def func(foo):
"""
Parameters:
foo (Bar): ignored
"""
pass
|
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def permuteUnique(self, nums):
if len(nums) == 1:
return [nums]
nums.sort()
res = []
i = 0
while i < len(nums):
sym = nums[i]
tmp = nums[:i] + nums[i + 1:]
... |
#PRIMEIROLISTA1
'''m = int(input('Digite um número: '))
k = int(input('Digite outro número: '))
print ('Soma = %d' %(m + k))'''
#SEGUNDOLISTA1
'''m = int(input('Digite um valor em metros: '))
print ('Isso equivale a %d milímetros' %(m*1000))'''
#TERCEIROLISTA1
dias = int(input('Digite a quantidade de dias: '))
horas = ... |
"""
Buttons and actions
"""
EXIT_BUTTON = '🚪 Выйты'
CONFIRM_BUTTON = '✅ Подтвердить'
GO_BUTTON = 'Go 🚀'
PRODUCTS_BUTTON = '☕️ Товары'
CART_BUTTON = '🛒 Корзина'
EMPTY_CART_BUTTON = '🧹 Очистить корзину'
(ID, ACTION) = range(2)
|
def sumOfDigit(n):
if (n==0):
return 0
return(n%10+sumOfDigit(int(n/10)))
num=int(input("Enter number: "))
result=sumOfDigit(num)
print("Output:",result) |
#-*- coding: utf-8 -*-
# Release details for package
name = "PyWavelets"
version = "0.1.7"
#revision = "$Revision: 118 $".split()[1]
author = "Filip Wasilewski"
author_email = "filip.wasilewski@gmail.com"
url = "http://www.pybytes.com/pywavelets/"
download_url = "http://pypi.python.org... |
"""
Python 3 Object-Oriented Programming Case Study
Chapter 10. The iterator pattern
"""
def test_placeholder():
pass
|
valores = [334, 567, 435, 678]
print( max(valores) )#exibe valor mais alto
print( min(valores) )#exibe valor mais baixo
pares = list(range(0,100, 2))#listando pares
impar = list(range(1,101, 2))#listyando impares
print(pares)
print(impar)
for valor in pares:#iterando valores range
print(valor) |
class Animal:
name = "Nieznane"
legs = 4
ears = 2
def __init__(self, name):
self.name = name
def move(self):
print(self.name + " biegnie...")
def stop(self):
print(self.name + " zatrzymuje się.")
def make_noise(self):
print(self.name + " szczeka!")
class... |
class DFA:
# DFA初始化来源:默认为0,用文件初始化,为1时用dfa的各属性初始化
def __init__(self, states, alphabet, functions, start_state, accept_state, source=0):
if source == 0:
# 将状态文件中的状态集合读取至self.states中,状态文件中每个状态占一行
self.states = list()
with open(states, 'r') as f:
for line... |
# https://leetcode.com/problems/maximum-product-subarray/
class Solution(object):
def maxProduct(self, nums):
"""
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. It is guaranteed that the answer will fit in a 3... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given a 2D binary matrix filled with 0's and 1's, find the largest square
containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
>>> s = Solution()
>>> s.maximalSquare([['1', '1'], ... |
#
# PySNMP MIB module REDLINE-AN80I-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDLINE-AN80I-IF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:46:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
class Solution:
def permuteUnique(self, nums):
dic = set()
for p in itertools.permutations(nums):
if p not in dic:
dic.add(p)
return list(dic) |
def plot_series(time, series, format="-", start=0, end=None):
plt.plot(time[start:end], series[start:end], format)
plt.xlabel("Time")
plt.ylabel("Value")
plt.grid(True) |
# the drivers that can be used to create thumbnails
drivers = ["gee", "planet"]
# the file types that can be digested by the app
types = ["points", "shapes"]
# define the extrems size of the thumbnails
min_image = 500
max_image = 10000
# define the extreme size of the square
min_square = 10
max_square = 500
# the c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.