content stringlengths 7 1.05M |
|---|
'''
You can verify if a specified item
is exists in a tuple using in keyword:
'''
test=[]
n=int(input('Enter size of tuple: '))
for i in range(n):
data=input(f'Elements of tuple are: ')
test.append(data)
test=tuple(test)
print(f'Elements of the tuple are: {test}')
if "israel" in test:
print('yes')
else... |
#Q
row=0
while row<8:
col =0
while col<8:
if (col==1 and row==0)or (col==2 and row==0)or (col==3 and row==0)or (col==4 and row==1)or (col==4 and row==2)or (col==4 and row==3)or (col==5 and row==5)or (col==6 and row==6)or (col==1 and row==4)or (col==2 and row==4)or (col==3 and row==4)or (col==4 and ... |
"""
What you will learn:
- What is an if statement
- How does this relate to boolean logic
- Using if to check conditions
- dealing with else
- dealing with ifelse
Okay, let's say your mom said "If you clean your room you can have a cookie" what is going on here. You have been given
a statement: is room clean? Now if... |
# crie um programa que leia o nome e o preço de varios produtos
# o programa deve perguntar se o usuario quer algo mais
# no final deve ter um output de
# qual é o total de gastos na compraX
# quantos produtos custam mais de 1kX
# qual foi o produto mais barato e o preço dele
cpreco = 0
maisde1k = 0
nomebarato = str
p... |
# User defined functions
# Example 1
def function_name():
print("my first user-defined function!")
function_name()
function_name()
function_name()
function_name()
# Example 2
def welcome_msg():
print("Welcome to Python 101")
welcome_msg()
# Example 3
def welcome_msg(name):
print(f"Welcome to Python 101,... |
q=int(input("Enter large prime integer(q):"))
a=int(input("Enter primitive root(a):"))
xa=int(input("Enter Xa:"))
ya=(a**xa)%q
k=int(input("Enter the value of k:"))
m=int(input("Enter Message:"))
print("Public key (Ya):",ya)
S1=(a**k)%q
print("S1:",S1)
i=1
while True:
x=(k*i)%(q-1)
if x==1:
break
els... |
###Titulo: Calculo de multa
###Função: Este programa calcula o valor da multa de acordo com a velocidade
###Autor: Valmor Mantelli Jr.
###Data: 08/12/20148
###Versão: 0.0.1
# Declaração de variável
v = 0
resultado = 0
# Atribuição de valor a variavel
v = int(input("Diga qual a velocidade do seu carro(em km/h): "))... |
s = "I'm a string."
print(type(s))
yes = True #Bool true
print(type(yes))
no = False #Bool false
print(type(no))
#List - ordered and changeable
alpha_list = ["a", "b", "c"] #list init
print(type(alpha_list)) #tuple
print(type(alpha_list[0])) #string
alpha_list.append("d") #will add "d" to list
print(al... |
class Grid:
def __init__(self, row, col, gsize):
self.row = row
self.col = col
self.gsize = gsize
self.walls = {} # top, left, bottom, right
def connections(self):
my_list = []
for key, val in self.walls.items():
if val != None:
... |
# https://www.hackerrank.com/challenges/python-loops/problem
n = int(input())
# 5
for i in range(n):
print(i ** 2)
# 0
# 1
# 4
# 9
# 16 |
TRANSACTIONALSET_ADD = 0x1201
TRANSACTIONALSET_REMOVE = 0x1202
TRANSACTIONALSET_SIZE = 0x1203
|
'''https://leetcode.com/problems/climbing-stairs/
70. Climbing Stairs
Easy
8813
261
Add to List
Share
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation:... |
# Lec 2.6, slide 2
x = int(raw_input('Enter an integer: '))
if x%2 == 0:
print('Even')
else:
print('Odd') |
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def print_board(board):
for i in range(len(board)):
if i % 3 == 0:
... |
II = lambda : int(input())
a1 = II()
a2 = II()
k1 = II()
k2 = II()
n = II()
if(k1>k2):
k1,k2 = k2,k1
a1,a2 = a2,a1
auxM = min(a1,n//k1)
restM = n-auxM*k1
M = auxM+min(a2,restM//k2)
if((k1-1)*a1+(k2-1)*a2>=n):
m = 0
else:
m = n-((k1-1)*a1+(k2-1)*a2)
print(m,M)
|
def buttons(ceiling):
connections = ((1, 0), (0, 1), (0, -1), (-1, 0))
g = [[int(c) for c in line] for line in ceiling.strip().splitlines()]
sizex, sizey = len(g), len(g[0])
visited = set()
def is_new(x, y):
return (x, y) not in visited and 0 <= x < sizex and 0 <= y < sizey and g[x][y] != 0... |
def maior(* param):
print('')
listanum = []
maior = 0
menor = 0
for c in range(0,5):
listanum.append(int(input(f'Digite um valor para a posicao {c}')))
if c == 0:
mai = men = listanum[c]
else:
if listanum[c] > mai:
mai = listanum[c]
if listanum[c] < men:
... |
"""
Definition of SegmentTreeNode:
class SegmentTreeNode:
def __init__(self, start, end):
self.start, self.end = start, end
self.left, self.right = None, None
"""
class Solution:
"""
@param: start: start value.
@param: end: end value.
@return: The root of Segment Tree.... |
pkgname = "python-setuptools"
version = "57.0.0"
revision = 0
build_style = "python_module"
hostmakedepends = ["python-devel"]
depends = ["python"]
short_desc = "Easily build and distribute Python packages"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
homepage = "https://github.com/pypa/setuptools"
distfi... |
def main():
count = 0
sum_ = 0
while True:
try:
number = float(input(f"Number {count+1}: "))
count += 1
sum_ += number
except ValueError:
if not count:
count = 1
break
print(sum_)
print(sum_ / count)
if __n... |
# Released under the MIT License. See LICENSE for details.
#
# This file was automatically generated from "happy_thoughts.ma"
# pylint: disable=all
points = {}
# noinspection PyDictCreation
boxes = {}
boxes['area_of_interest_bounds'] = (-1.045859963, 12.67722855,
-5.401537075) + (0.... |
# Lecture 09_02 Exercise Objectives
# 01. Work with nested lists
# 02. Write function to extract locations
# 03. Write function to format location string
# 04. Control execution path from main() function
# 05. Implement accumulator pattern
# 06. Write for loops and conditional statements to filter data
# 08. Write exp... |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __str__(self):
current = self
ret = ''
while current:
ret += str(current.value)
current = current.next
return ret
# Time: O(n)
# Space: O(1)
def rot... |
load(
":download.bzl",
"TerraformBinaryInfo",
"TerraformProviderInfo",
)
TerraformModuleInfo = provider(
"Provider for the terraform_module rule",
fields={
"source_files": "depset of source Terraform files",
"modules": "depset of modules",
"providers": "depset of providers",... |
#
## https://leetcode.com/problems/longest-palindromic-substring/
#
#
## Cannot fully pass the performance test.
#
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if s is None:
raise ValueError('Input must be a String.')
if len(s) == 0 or len(s)... |
class ColorConstants(object):
#QLineEdit colours
QLE_GREEN = '#c4df9b' # green
QLE_YELLOW = '#fff79a' # yellow
QLE_RED = '#f6989d' # red
#see http://cloford.com/resources/colours/500col.htm
|
# -*- coding: utf-8 -*-
# @version : Python3.6
# @Time : 2017/3/31 16:45
# @Author : Jianyang-Hu
# @contact : jianyang1993@163.com
# @File : class_02_0331.py
# @Software: PyCharm
"""
面向对象:封装
"""
class Foo:
def __init__(self, bk):
""" 构造方法 """ # 析构方法在垃圾回收是解释器自己调用
self.name = bk
sel... |
class BaseServer:
def __init__(self, app, **kwargs):
"""
Construct method
"""
self.kwargs = kwargs
self.app = app
def run_serve(self):
raise NotImplementedError
|
#bmi calculator
print("YOU ARE WELCOME TO BMI CALCULATOR BUILT BY IDRIS")
print("")
print(" PLEASE KINDLY ENTER YOUR VALUE IN KG FOR WEIGHT AND IN METERS FOR HEIGHT ")
print("")
w=float(input("please enter the value for weight in KG = "))
print("")
h=float(input("please enter the value for height in METERS = "))
bmi=w/... |
def mergesort(m):
if len(m) == 1:
return m
mid = len(m) // 2
left = m[:mid]
right = m[mid:]
left = mergesort(left)
right = mergesort(right)
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 or len(right) > 0:
if len(left) > 0 and l... |
# One can use pretty unicode characters here ('\u25EF', '\u2A09'), if their terminal emulator supports it
PLAYER_TOKENS = ('O', 'X')
TOKEN_EMPTY = '-'
VALID_TOKENS = PLAYER_TOKENS + tuple(TOKEN_EMPTY)
|
num = 253
total = 0
while(num != 0):
rem = num % 10
total = total + rem
num = num // 10
print("Sum of number's digit:", total)
|
def run_xnli(model):
pass |
# Challenge 2.3
# Favourite Team
# =================
games = ["Manchester Utd v Liverpool", "Liverpool v Southampton", "Liverpool v Stoke", "Chelsea v Liverpool"]
|
HOST = "Enter your host details"
USERNAME ="Enter your username"
PASSWORD="Enter your password"
#PASSWORD=""
PORT = 22
TIMEOUT = 10
PKEY = "Enter your key filename here"
#Sample commands to execute(Add your commands here)
COMMANDS = ['ls;mkdir sample']
|
#
# PySNMP MIB module CISCO-WAN-ANNOUNCEMENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-ANNOUNCEMENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:18:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
a = input('Enter a: ')
b = input('Enter b: ')
if a > b:
a = int(a)
b = int(b)
while a <= b:
print(a)
a += 1
else:
a = int(a)
b = int(b)
while b <= a:
print(b)
b += 1 |
#encoding:utf-8
#采集功能启动方式
COLLECT_MODE_CMD_PLUGIN = 1; #插件启动,采集默认配置模板BASIC信息
COLLECT_MODE_CMD_TOTAL = 2; #命令行启动,采集默认配置模板所有信息
COLLECT_MODE_CMD_FILE = 3; #命令行启动,采集指定配置模板所有信息
#字符串常量
NAGIOS_STATUS_UNKNOWN = "3";
NAGIOS_INFORMATION_UNKNOWN = "Unknown";
NAGIOS_INFORMATION_SEP = " "
NAGIOS_CMD = "[%s] PROCESS_SERV... |
"""
适配器模式
把一个类的接口变换成客户端所期待的另一种接口,使原本因接口不兼容而无法在一起工作的两个类能够在一起工作;
在本例中旧课程类通过一个 show 方法显示三种信息,在新课程类中则改为 show_desc、show_teacher、show_labs 方法分别展示三类信息;
对于客户端而言,要查询三种信息还是使用旧接口 show,所以新课程类需要接入适配器;
从提供课程对象改为提供适配器对象,但客户端的接口调用方式不会改变。
"""
""" 旧的课程类 """
class OldCourse(object):
def show(self):
print("s... |
'''
9. Faça um Programa que leia um vetor A com 10 números inteiros, calcule e mostre a soma dos quadrados dos elementos do vetor.
'''
vetorA = []
soma = 0
for i in range(10):
vetorA.append(int(input(f'Num {i+1}: ')))
for i in range(len(vetorA)):
soma += vetorA[i]**2
print(f'A soma dos quadrados dos elementos ... |
def Insertion_Sort_Recursive(arr, p, q):
if(p==q): return
Insertion_Sort_Recursive(arr, p, q-1)
last = arr[q]
j = q-1
while(j>=0 and arr[j] > last):
arr[j+1] = arr[j]
j = j-1
arr[j+1] = last
array = [3, 6, 1, 7, 8, 2, 5, 4, 0, 9]
Insertion_Sort_Recursive(array, 0, len(array)-1)
print(array) |
__all__ = ['XsecRecord']
class XsecRecord:
""":class:`XsecRecord` implements the same-named ARTS datatype.
Contains the reference cross section data at low pressure and
the coefficients for the broadening formula.
"""
def __init__(self, species=None, coeffs=None, fmin=None, fmax=None,
... |
cells_conv_areas = [prop.convex_area for prop in properties]
cells_orientation = [prop.orientation for prop in properties]
print('Convex areas: {}'.format(cells_conv_areas))
print('Orientation: {}'.format(cells_orientation))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Funciones para conversión a tipos de datos básicos.
Definición de Exceptions para integer,Float,Boolean
Funciones de conversión a int,bool,float
"""
__author__ = "Esteban Barón"
__copyright__ = "Copyright 2020, Esteban Barón ,EBP"
__license__ = "MIT"
__email__ = "es... |
def part1(lines):
x, y = 0, 0
for line in lines:
movement, amount = line.split(' ')
if movement == 'forward':
x += int(amount)
elif movement == 'down':
y += int(amount)
else:
y -= int(amount)
print(x * y)
def part2(lines):
x, y, aim =... |
SUCCESS = 0
ERROR = 1
UNKNOWN_ERROR = 2
VIRTUALENV_NOT_FOUND = 3
PREVIOUS_BUILD_DIR_ERROR = 4
NO_MATCHES_FOUND = 23
|
df_train = pd.get_dummies(df_train, columns=['Initial'], prefix='Initial')
df_test = pd.get_dummies(df_test, columns=['Initial'], prefix='Initial')
df_train.head()
df_train = pd.get_dummies(df_train, columns=['Embarked'], prefix='Embarked')
df_test = pd.get_dummies(df_test, columns=['Embarked'], prefix='Embarked')
|
install_dependencies = '''
#!/bin/bash
[COMMANDS]
'''.strip() |
MONGODB_DB = 'mongomail'
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
MONGODB_USER = None
MONGODB_PASSWORD = None
MAIL_HOST = "0.0.0.0"
MAIL_PORT = 8025
DEBUG = False
|
#import pprint
class Node():
def __init__(self):
self.name = None # node name
self.data = None # data string
self.attribute = None # attribute dictionary
self.child = None # child node list
self.parent = None # parent node
self.is_contain = None # boolean, tag contai... |
def read_each():
with open('input.txt') as fh:
for line in fh.readlines():
policy, pwd = line.split(':')
yield policy.strip(), pwd.strip()
def validate(policy, pwd):
rng, req_char = policy.split()
pos1, pos2 = rng.split('-')
pos1 = int(pos1)-1
pos2 = int(pos2)-1
... |
# 34. Find First and Last Position of Element in Sorted Array
# Runtime: 93 ms, faster than 27.31% of Python3 online submissions for Find First and Last Position of Element in Sorted Array.
# Memory Usage: 15.6 MB, less than 12.09% of Python3 online submissions for Find First and Last Position of Element in Sorted Ar... |
'''
In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.
Return the element repeated N times.
Example 1:
Input: [1,2,3,3]
Output: 3
Example 2:
Input: [2,1,2,5,3,2]
Output: 2
Example 3:
Input: [5,1,5,2,5,3,5,4]
Output: 5
Note:
4 <= A.length <= 10000
0... |
print("Rechnung")
Eingabe = str(input())
Rechenzeichenpos = 0
Rechenzeichen = ""
Plus_pos = []
Minus_pos = []
Mal_pos = []
Durch_pos = []
Klammern_auf = []
Klammern_zu = []
Liste_Rechenzeichen_gesamt = []
for Pos in range(len(Eingabe)):
if Eingabe[Pos] == "+": Rechenzeichen = "+"; Plus_pos.append(Pos+1)
... |
QUALITY = 50
STOPSTREAM = -1
FRAMEMISS = -2
TRACKMISS = -3
COLLECT_TIMESTEP = 0.01
DEC_TIMESTEP = 0.01
DIST_TIMESTEP = 0.01
ENC_TIMESTEP = 0.01
PUB_TIMESTEP = 0.01
SUB_TIMESTEP = 0.01
REQ_TIMESTEP = 0.03
COLLECT_HWM = 3
DEC_HWM = 3
ENC_HWM = 3
DIST_HWM = 3
PUB_HWM = 3
SUB_HWM = 3
REQ_HWM = 3
|
# 面试题 17.14. 最小K个数
# https://leetcode-cn.com/problems/smallest-k-lcci/
# 设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。
# 示例:
# 输入: arr = [1,3,5,7,2,4,6,8], k = 4
# 输出: [1,2,3,4]
# 提示:
# 0 <= len(arr) <= 100000
# 0 <= k <= min(100000, len(arr))
# 1. Solution1,排序后输出前`k`个, Time: O(nlogn), Space: O(logn), Runtime: 92%
c... |
plotSize =1
# MARE for regressors, accuracy for classifiers
lrCurve = 0
|
# from functools import lru_cache
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
prev = 1
cur = 2
for i in range(2, n):
cur, prev = cur + prev, cur
return cur
|
#
# Copyright (c) 2017 Joy Diamond. All rights reserved.
#
if __name__ == '__main__':
def gem(module_name):
def execute(f):
return f()
return execute
@gem('Ivory.Boot')
def gem():
PythonSystem = __import__('sys')
is_python_2 = PythonSystem.version_info.ma... |
class User:
def __init__(self, id, name, birthday, description, genderId, prefectureId, imageName, hobby, favoriteType):
self.id = id
self.name = name
self.birthday = birthday
self.description = description
self.genderId = genderId
self.prefectureId = prefectureId
... |
# List of Basic configurations
#Login Configs
clientID='JL53WY5Cw2WK8g'
clientSecret='fKqCZ44PIIFdqOjemTIKab0BfEs'
agent='popularWordBot Script'
username='popularWordBot'
#Action Considerations
#targetSub = ['testabot','australia'] #consider making this a list
targetSub = ['brisbane','melbourne','austr... |
# 异常 exception
a = 2
b = 0
try:
print(a / b)
except ZeroDivisionError:
print("除数不能为0")
else:
print(a / b)
print("END")
|
"""
知识点:
条件语句
"""
def p(arg):
print(arg)
score = 90
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
p(grade)
if 90 > 80 and 90 < 100 :
print('90 > 80 and 90 < 100') |
# -*- coding: utf-8 -*-
"""
Bombolone
~~~~~~~~~~~~~~~~~~~~~
Bombolone is a tasty Content Management System for Python based on Flask,
MongoDB, AngularJS, Sass and Bootstrap. It's designed to be a simple,
flexible toolset for projects of any size.
:copyright: (c) 2014 by @zizzamia
:license: BSD (See LICENSE for deta... |
class RobustGridRouter(object):
"""
A router to control all database operations on models in the
grid_core application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read grid_core models go to robust_grid.
"""
if model._meta.app_label == 'grid_core':
... |
DATABASES = {
'default': {
'NAME': 'ietf_utf8',
'ENGINE': 'django.db.backends.mysql',
'USER': 'matheuspfitscher',
'PASSWORD': 'ietf', # Contact henrik@levkowetz.com to get the password
'HOST': '127.0.0.1'
},
'datatracker': {
'NAME': 'ietf_utf8',
'ENGI... |
#%%
msg = "Hello world"
print(msg)
#%%
msg2 = "Hello world"
print(msg2)
# %%
|
class Two_Dimensional_Matrix:
def isValidSize(self):
for i in range(1, self.m):
if (self.n != len(self.matrix[i])):
return False
return True
# def isValidType(self, expectedType=int):
# for i in range(len(self.matrix)):
# for j in rang... |
"""
Make a program that reads tha name of a city from
california, and returns:
1-if its starts or not with 'san'.
2-if its has of not san in any part of name.
"""
city = str(input('Enter a city of California:\n')).strip().title()
city = city.split()
print('Does this city name begin with San?\n','San' in city[0])
prin... |
def aspect(fontid, aspect):
'''Set the aspect for drawing text.
:param fontid: The id of the typeface as returned by blf.load(), for default font use 0.
:type fontid: int
:param aspect: The aspect ratio for text drawing to use.
:type aspect: float
'''
pass
def blur(fontid, radius):
... |
class Solution:
def XXX(self, height: [int]) -> int:
area = 0
y = len(height)-1
x = 0
while x != y:
a = min(height[y],height[x]) * abs(x-y)
if a > area:
area = a
if height[x] < height[y]:
x += 1
else:
... |
"""
.. module:: dj-stripe.contrib.
:synopsis: Extra modules not pertaining to core logic of dj-stripe.
"""
|
def insertion_sort_general(arr):
if not arr:
return arr
size = len(arr)
for i in range(size):
for j in range(i + 1, size):
while i < j:
if arr[j] < arr[j - 1]:
arr[j], arr[j - 1] = arr[j - 1], arr[j]
j -= 1
return arr
arr ... |
phone_to_id = {
"n": 0,
"s": 1,
"ER": 2,
"iong": 3,
"AE": 4,
"HH": 5,
"h": 6,
"S": 7,
"JH": 8,
"AY": 9,
"W": 10,
"DH": 11,
"SH": 12,
"5": 13,
"4": 14,
"t": 15,
"AA": 16,
"c": 17,
"EY": 18,
"j": 19,
"ian": 20,
"x": 21,
"uan": 22,... |
def double(val):
return val + val
print(double(3))
print(double(3.3))
print(double('3'))
|
def prim(n, adj):
total_weight = 0
selected, min_e = [False] * n, [[float('inf'), -1] for _ in range(n)]
mst_edges = []
min_e[0][0] = 0
for i in range(n):
v = -1
for j in range(n):
if (not selected[j]) and ((v == -1) or (min_e[j][0] < min_e[v][0])):
v =... |
class Command:
def __init__(self, function, *args):
self.function = function
self.args = list(args)
def execute(self):
self.function(*self.args)
|
class Arbol:
def __init__(self, instructions):
self.instrucciones:list = instructions
self.console:list = []
|
"""
This program demonstrates printing output.
"""
room = 503 #Represents a hotel room number that a person is staying in
print("I am staying in room number", room) #Prints the person's room number
top_speed = 125 ... |
# tag::Map[]
class SeatMap():
def loadFromFile(self, filename):
"""Read file to map"""
self._rows = []
self.width = 0
file = open(filename, "r")
for line in file:
self._rows.append(line.strip())
self.width = max(self.width,len(line.strip()))
... |
#
# PySNMP MIB module ZHNSYSMON (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHNSYSMON
# Produced by pysmi-0.3.4 at Mon Apr 29 21:40:22 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... |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: ProteinDataBank.py
#
# Tests: mesh - 3D points
# plots - Molecule
#
# Programmer: Brad Whitlock
# Date: Tue Mar 28 15:46:53 PST 2006
#
# Modifications:
# Jeremy Mer... |
# bot token (from @BotFather)
TOKEN = ''
LOG_FILE = './logs/botlog.log'
|
def countSquareMatrices(a, N, M):
count = 0
for i in range(1, N):
for j in range(1, M):
if (a[i][j] == 0):
continue
# Calculating number of square submatrices ending at (i, j)
a[i][j] = min([a[i - 1][j], a[i][j - 1], a[i - 1][j - 1]])+1
# Calc... |
'''You are given a binary array nums (0-indexed).
We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit).
For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5.
Return an array of booleans answer where answer[i] is true if xi is... |
class QueryNotYetStartError(Exception):
"""Raises error if the query has not yet started"""
class NotFetchQueryResultError(Exception):
"""Raises error if the query result could not be fetched"""
class QueryTimeoutError(Exception):
"""Raises timeout error if the query timeout"""
class QueryAlreadyCance... |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-cord_anatomy'
ES_DOC_TYPE = 'anatomy'
API_PREFIX = 'cord_anatomy'
API_VERSION = ''
|
my_cars = ["Lamborghini","Ford","Ferrari"]
my_cars[1] = "Ford Titanium"
print (my_cars)
my_cars = ["Lamborghini","Ford","Ferrari"]
print (len(my_cars))
my_cars = ["Lamborghini","Ford","Ferrari"]
del my_cars [0]
print (my_cars)
my_cars = ["Lamborghini","Ford","Ferrari"]
my_cars0 = list(my_cars)
print (my_cars0)
my_c... |
print('------Caixa Eletrônico-------')
print(40*'-')
valor = int(input('Qual o valor a ser sacado :'))
total = valor
cedulas = 50
totced = 0
while True:
if total >= cedulas:
total = total - cedulas
totced = totced + 1
else:
print(f'Total de {totced} cédulas de {cedulas} R$')
if c... |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
"""
File Name: utils.py
Author : jynnezhang
Date: 2020/4/27 3:34 下午
Description:
"""
def toByte(input):
if type(input) is str:
return input.encode('utf8')
return input
|
class LandException(Exception):
"""
Custom exception to instruct the tello_script_runner that a user script
would like to land.
"""
pass |
s=input("Enter string:")
n=int(input("Enter no. of substring:"))
l=[]
print("Enter substrings: ")
for i in range(n):
substr1=input()
substr2=list(substr1)
a=[]
count=0
l1=[a]
for i in range(len(s)):
x=l1[:]
new=s[i]
for j in range(len(l1)):
l1[j]=l1[j]+[new]
... |
"""
"""
class LoadError(Exception):
""" Represents the error raised from loading a library """
def __init__(self, message):
super().__init__(message)
self.message = message # Added because it is missing after super init
def __repr__(self):
return f'ParserError(message="{self.mes... |
print("hello")
'''
import streamlit as st
from streamlit_webrtc import (
ClientSettings,
VideoTransformerBase,
WebRtcMode,
webrtc_streamer,
)
webrtc_ctx = webrtc_streamer(
key="object-detection",
mode=WebRtcMode.SENDRECV,
client_settings=WEBRTC_CLIENT_SETTINGS,
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 5 11:26:08 2020
@author: Administrator
"""
"""
对于一棵给定的排序二叉树,求两个结点的共同父节点,例如在下图中,结点1和结点5的共同父节点为3.
6
3 9
2 5 8 10
1 4 7
"""
class BiTNode:
def __init__(self , x):
self.Lch... |
# Definition for a binary tree node.
"""
timecomplexity = O(n)
Space complexity : O(log(N)) in the best case of completely balanced tree and )O(N) in the worst case of completely unbalanced tree, to keep a recursion stack.
construct recusive function check the special tase: two empty tree and one empty one unempty ,... |
{
"targets": [
{
"target_name": "addon",
"sources": [ "src/addon.cc" ],
"include_dirs": ["<!(node -p \"require('node-addon-api').include_dir\")"],
"defines": [ "NAPI_DISABLE_CPP_EXCEPTIONS" ],
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"conditi... |
"""
Mol_config
==========
"""
class MolConfig:
"""Configuration object for environments.
Specifies parameters for :class:`~conformer_rl.environments.conformer_env.ConformerEnv`
conformer environments.
Attributes
----------
mol : rdkit Mol, required for all environments
The molecule to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.