content stringlengths 7 1.05M |
|---|
# To Find The Total Number Of Digits In A Number
N = int(input("Enter The number"))
count = 0
while(N!=0):
N = (N-N%10)/10
count+=1
print(count) |
# Napisz funkcję, która obliczy pole powierzchni prostokąta na podstawie długości jego boków.
def rectangle_area(long, width):
return long * width
print(f"Pole prostokąta o bokach 5 i 18 to {rectangle_area(5, 18)}")
|
class DummyObject:
# When we try to access any attribute of the
# dummy object, it will return himself.
def __getattr__(self, item):
return self
# And if dummy object is called, nothing is being done,
# and error created if the function did not exist.
def __call__(self, *args, **kwargs)... |
#Calculate Value of PI using the Neelkantha method to nth digit using upto 50 trailing digits
j = 3.0
k=1
for i in range(2, 4000000, 2): #Change the Desired End Step to get a better nth value
k = k+1
if k % 2 ==0:
j = j+ 4/(i*(i+1)*(i+2))
else:
j = j- 4/(i*(i+1)*(i+2))
kaggle = inpu... |
class Solution:
# bottom up
def minimumTotal(self, triangle: 'List[List[int]]') -> 'int':
if not triangle:
return
rst = triangle[-1]
for level in range(len(triangle)-2,-1,-1):
for i in range(0,len(triangle[level]),1):
rst[i] = triangle[le... |
# -*- coding: utf-8 -*-
"""
Exceptions
==========
Specific application exceptions.
"""
class PyCssStyleguideException(Exception):
"""
Exception base.
You should never use it directly except for test purpose. Instead make or
use a dedicated exception related to the error context.
"""
pass
c... |
def digit_sum():
a=int(input('Enter an integer '))
sum=0
for i in range(1,a+1):
sum+=i
if(i!=a):
print(i,end='+')
else:
print(a,'=',sum)
digit_sum()
|
"""
map applies a function to all values in one or more iterables
filter runs each value through a function and creates an iterable with all truthy values
"""
# map
a_list = list(range(10))
b_list = list(range(10, 30))
c_list = list(range(30, 60))
def add(value1, value2):
return value1 + value2
added = []
for val... |
with open("Crime.csv",'r') as file:
mainlist=[]
list2=[]
count=[]
i=0
j=1
k=2
countvalue=0
for line in file:
line.strip()
line.split(",")
print(line)
"""
if line[2] in mainlist:
mainlist.index(line[7])
count[index]+=1
list2[k]=count[index]
else:
list1.append(line[7])
list2[i]=list[8]
... |
"""
Sams Teach Yourself Python in 24 Hours
by Katie Cunningham
Hour 3: Logic in Programming
Exercise:
1.
a) Given a number, write a snippet of code that will print
"You have money" if the number is positive,
"You're out" if the number is zero,
"You seem to be in debt" if less... |
"""init py module tells python this folder contains a package.
You don't particularly need this file for python 3.6.
"""
|
# commaCode script
# Chapter 4 - Lists
def func(arg):
text = ""
for i in range(len(arg)):
text = text + arg[i] + ". "
if i == len(arg) - 2:
text += "and "
return text
spam = ['apples', 'bananas', 'tofu', 'cats']
print(func(spam))
|
# https://leetcode.com/problems/is-subsequence/
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s:
return True
if len(t) < len(s):
return False
s_idx = 0
for t_idx in range(len(t)):
if s[s_idx] == t[t_idx]:
... |
class Validator(object):
def __init__(self):
self.isValid = False
def validate(self, number):
try:
if number is None:
return self.isValid
if isinstance(number, str) and number.find(' ') >= 0:
number = number.replace(' ', '')
s... |
def loss_disc(disc, x_real, x_fake):
"""Compute the discriminator loss for `x_real` and `x_fake` given `disc`
Args:
disc: The discriminator
x_real (ndarray): An array of shape (N,) that contains the real samples
x_fake (ndarray): An array of shape (N,) that contains the fake samples
Returns:
nda... |
message = input().split()
for word in message:
number = ""
letters = ""
for char in word:
if char.isdigit():
number += char
else:
letters += char
first_letter = chr(int(number))
current_word = first_letter + letters
current_word = list(current_word)
c... |
def prog(l, noun=12, verb=2):
res = list(map(int, l.split(',')))
res[1] = noun
res[2] = verb
for i in range(0, len(l), 4):
if res[i] == 1:
res[res[i+3]] = res[res[i+1]] + res[res[i+2]]
elif res[i] == 2:
res[res[i+3]] = res[res[i+1]] * res[res[i+2]]
elif re... |
#
# PySNMP MIB module CISCO-LWAPP-AAA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-AAA-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:47:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
class Solution:
def gcdOfStrings(self, str1, str2):
if len(str1)<=len(str2):
temp = str1
else:
temp = str2
m = len(temp)
x = 1
res=[""]
while x<=m:
if m%x==0 and temp[:x] * (len(str1)//x) == str1 and temp[:x] * (len(str2)//x) == str2:
res.append(temp[:x])
x+=1
return res[-... |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/extract-maximum/0
def sol(s, n):
"""
If the character is a number and l is not set set it to that index, if it
is set the r.
If character is not a number set both l and r as None
"""
l = None
r = None
mx = 0
for i in r... |
# Magatia (261000000) / NLC Town Center (600000000) => Free Market
sm.setReturnField()
sm.setReturnPortal()
sm.warp(910000000, 36)
|
class KeywordError(Exception):
pass
class SingletonError(Exception):
pass
class StepNotFoundError(Exception):
pass
class EmptyFeatureError(Exception):
pass
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rty... |
# Number of motors
NUM_MOTORS = 12
# Number of legs
NUM_LEGS = 4
# //////
# Legs
# //////
LEG_NAMES = ["FR", # Front Right
"FL", # Front Left
"RR", # Rear Right
"RL"] # Rear Left
# //////////////
# Joint Types:
# //////////////
JOINT_TYPES = [0, # Hip
1,... |
# draw a playing board
def DrawBoard(rows,cols):
dash = " ---"
hline = "| "
for i in range(0,rows):
print (dash * (cols))
print (hline * (cols +1))
DrawBoard(3, 3)
|
#
# 给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
#
# 示例 1:
#
# 输入: [10,2]
# 输出: 210
# 示例 2:
#
# 输入: [3,30,34,5,9]
# 输出: 9534330
# 说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
def bi(i):
if i == 0:
return 0
s = 0
k = i
while i >= 1 :
i=i/ 10
s+=1
return k /( 10 **s)
class Solution(object):
def la... |
def read_file(test = True):
if test:
filename = '../tests/day3.txt'
else:
filename = '../input/day3.txt'
with open(filename) as file:
temp = list()
for line in file:
temp.append(line.strip())
return temp
def puzzle1():
temp = read_file(False)
houses ... |
data = open("input.txt", "r").readlines()
score_map = {
")": 3,
"]": 57,
"}": 1197,
">": 25137
}
def get_opening_bracket(bracket):
if bracket == ")":
return "("
if bracket == "]":
return "["
if bracket == "}":
return "{"
if bracket == ">":
return "<"
... |
#write a program to check whether the given number is Disarium or not?
n = int(input("Enter number:"))
i= 1
sum = 0
num = n
while(num!=0):
rem = num%10
sum = sum*10+rem
num = num//10
num = sum
sum = 0
while(num!= 0):
rem = num % 10
sum = sum + pow(rem,i)
num = num//10
i+=1
if sum == n:
... |
'''
Created by Vedant Christian
Created on 18 / 08 / 2020
'''
terms = int(input("How many terms? "))
base = int(input("What is the base? "))
result = list(map(lambda x: base ** x, range(terms+1)))
print("The total terms is: ", terms)
print("The base is ", base)
for i in range(terms+1):
print(base,... |
x=10;
print(x); #输出10
str="I am a student";
print(str); #输出I am a student
#print(y); #y没有定义,所以这里必定会报错
num=1;
print(num); #输出1
Num=2.8;
NUM=1+2j; #python中的复数形式:m+nj(其中m,n分别为实数部和虚数部)
print(num,Num,NUM); #输出1 2.8 (1+2j)
print(type(num)); #输出<cl... |
class TryNode(object):
def __init__(self, line, start, end, handler):
self.buf = ""
self.exception = ""
self.start = None
self.end = None
self.handler = None
self.__parse(line, start, end, handler)
def __repr__(self):
return "Try: %s {%s .. %s} %s" % \... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
first_buy, first_sell = inf, 0
second_buy, second_sell = inf, 0
for price in prices:
first_buy = min(first_buy, price)
first_sell = max(first_sell, price - first_buy)
second_buy = min(second_... |
# Copyright (c) 2007-2010 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.internet.application}.
"""
|
n, k = input().split(' ')
n, k = int(n), int(k)
c = sorted(list(map(int, input().split(' '))))
count = [0] * k
count_i, min_sum = 0, 0
for i in reversed(range(n)):
min_sum += (count[count_i]+1) * c[i]
count[count_i] += 1
count_i += 1
if count_i >= k:
count_i = 0
#print (count) ... |
def split(word):
return [int(char) for char in word]
data = '22222120221222212222221122222222222222222222220222202222222222200222122222222222022220222220212222202022222202102022002212222222222022222220222222222222222120220222212222222222222222222222222222220222202222222222202222022222222222022221222221222222222022222... |
def find_short(s):
l = len(s) #conta a quantidade caracteres apenas para ter um número alto o suficiente para comparação.
a = s.split() #separa as palavras
for x in a:
if l > len(x): #se l for maior que a quantidade de letras na palavra x, desse jeito l vai receber o valor menor sempre
... |
name, age = "Aromal S", 20
username = "aromalsanthosh"
print ('Hello!')
print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username))
|
"""
document.py
Contains a simple class that represents a Twitter-esque comment, with hashtags.
"""
class Document:
"""
This class essentially takes in a list of tokenized words and stores two lists, one containing the words
in the order that they appear and a set containing any hashtags in the comment.
... |
# -*- coding: utf-8 -*-
"""
ジェネレーターの利用例
"""
def tuggle():
"""
>>> g = tuggle()
>>> next(g)
True
>>> next(g)
False
>>> next(g)
True
"""
r = False
while True:
r = not r
yield r
def file_read(file_name):
with open(file_name) as f:
for line in f:
... |
class Solution(object):
# dutch partitioning problem
def sortColors(self, nums):
low, mid, high = 0, 0, len(nums)-1
while(mid <= high):
if(nums[mid] == 0):
nums[low],nums[mid] = nums[mid], nums[low]
low +=1
mid += 1
e... |
def definition():
view = f"""
-- Exists just as a reference, to check the categorisation of accounts to super-sections. Built 'right to left'
SELECT e.super_section_id, e.description as Super,
d.section_id, d.description as Section,
c.sub_section_id, c.description as SubSection,
b.summary_code, ... |
# name this file 'solutions.py'.
"""Volume II Lab 15: Line Search Algorithms
<name>
<class>
<date>
"""
# Problem 1
def newton1d(f, df, ddf, x, niter=10):
"""
Perform Newton's method to minimize a function from R to R.
Parameters:
f (function): The twice-differentiable objective function.
... |
vocales ='aeiou'
while True:
palabra = input("Escriba una palabra: ")
letras = palabra.split()
if len(letras) == 1:
break
else:
print("Eso no es solo una palabra")
pass
posicion = -1
puntos_kevin = 0
puntos_stuart = 0
for letras in palabra:
if vocales.__contains__(letras):
... |
kheader = '''
<head>
<style>
<!--
body {font-size:12px; font-family:verdana,arial,helvetica,sans-serif; background-color:#ffffff}
.text {font-size:12px; font-family:verdana,arial,helvetica,sans-serif}
h1 {font-size:24px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif; color:#005050}
h2 {font-size:18px... |
def linear_search(list, target):
result = False
if not target:
return "Error: target is None"
if not list:
return "Error: list is None"
for n in list:
if n == target:
result = True
return result
return result
list = [1,5,2,3,6,10,2]
targe... |
# Copyright (c) 2011 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.
{
'variables': {
'chromium_code': 1, # Use higher warning level.
},
'includes': [
'content_browser.gypi',
'content_common.gypi',
'... |
par = []
impar = []
for i in range(0, 10):
num = int(input("escreva um número: "))
if num % 2 == 0:
par.append(num)
else:
impar.append(num)
print(f"Essa lista tem {len(par)} números pares e {len(impar)} impares")
|
cx = 250
cy = 250
cRadius = 200
i=0
def setup():
size(500, 500)
smooth()
background(50)
strokeWeight(5)
stroke(250)
noLoop()
def draw():
global i
while i <2*PI :
x1 = cos(i)*cRadius + cx
y1 = sin(i)*cRadius + cy
line(x1 , y1 , x1 , y1)
line(cx , cy... |
#desenvolva um pograma que mostre as duas notas de um aluno calcule, e mostre a sua média
np1 = float(input('Me diga sua nota da np1:'))
np2 = float(input('Me diga a sua notada np2:'))
print('Sua média é ', float((np1+np2)/2 ))
#outra forma
'''resultado = (np1+np2)/2
print('Sua média é {}'.format(resultado)'''
#essa l... |
def m(a,n,b,c,d):
if n<0:
return(abs(b-c))
k = str(n)+'|'+str(b)
try:
return d[k]
except:
inc = m(a,n-1,b+a[n],c,d)
exc = m(a,n-1,b,c+a[n],d)
d[k] = min(inc,exc)
return d[k]
for i in range(int(input())):
d = {}
n = int(input())
a = [int(j... |
class DocumentFileContentToolsViewsTestMixin:
def _request_document_parsing_error_list_view(self):
return self.get(viewname='document_parsing:error_list')
def _request_document_type_parsing_view(self):
return self.post(
viewname='document_parsing:document_type_submit', data={
... |
class SqlQueries:
create_staging_events = ("""
CREATE TABLE IF NOT EXISTS public.events_stage (
index integer,
concert varchar(256),
artist varchar(256),
location varchar(256),
start_date date
);
""")
create_staging_songs = (... |
# Excel Sheet Column Number
'''
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Out... |
'''
Add two numbers
'''
def add(a, b):
return a + b
'''
Concatenate two lists
'''
def concat(L1, L2, L3):
return L1 + L2 + L3
'''
Get length of a list
'''
def length(L):
# We will make this one wrong to test failed tests
return len(L) - 1
|
#Lo que se busca es, dependiendo de la posición Y del peón en el tablero, los peones decidan poner una pared vertical en frente de su oponente
posPeon1Y = 0
posPeon1X = 4
posPeon2Y = 8
posPeon2X = 4
peonWall1 = 10
peonWall2 = 10
coolDown1 = 2
coolDown2 = 2
while(posPeon1Y != 8 or posPeon2Y != 0):
if(posPeon1Y... |
# -*- coding: utf-8 -*-
def __reversed__(self):
"""Built-in to implement reverse iteration"""
return self._statements.__reversed__()
|
# -*- coding:utf-8 -*-
"""
@author: SiriYang
@file: __init__.py
@createTime: 2021-01-23 13:51:53
@updateTime: 2021-01-23 13:51:53
@codeLines: 0
"""
|
"""
home.ts.__init__
================
Nothing to see here!
"""
|
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... |
def mul(x, y):
return x * y % 1337
class Solution(object):
def superPow(self, a, b):
"""
:type a: int
:type b: List[int]
:rtype: int
"""
if a >= 1337:
return self.superPow(a % 1337, b)
if a == 0 or a == 1:
return a
n = len... |
Terrain = [
{"stop": 0.00, "color": {'r': 0x00, 'g': 0x9a, 'b': 0x24}},
{"stop": 0.45, "color": {'r': 0xff, 'g': 0xff, 'b': 0x00}},
{"stop": 0.90, "color": {'r': 0xff, 'g': 0x00, 'b': 0x00}},
{"stop": 1.00, "color": {'r': 0xff, 'g': 0xe0, 'b': 0xe0}}
]
Water = [
{"stop": 0.00, "color": {'r': 0x34, ... |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Unknown'},
{'abbr': 'fg', 'code': 1, 'title': 'First guess'},
{'abbr': 'an', 'code': 2, 'title': 'Analysis'},
{'abbr': 'ia', 'code': 3, 'title': 'Initialised analysis'},
{'abbr': 'oi', 'code': 4, 'title': 'Oi analy... |
class Solution:
def maxSubArray(self, nums: [int]) -> int:
tmp = nums[0]
maxv = tmp
for i in range(1, len(nums)):
if tmp + nums[i] > nums[i]:
maxv = max(maxv, tmp + nums[i])
tmp = tmp + nums[i]
else:
maxv = max(maxv, tmp... |
class SimulationParameters:
start_time = 0. # start time for simulation
end_time = 50000. # end time for simulation
dt_video = 0.1
dt_simulation = 0.03 # smallest time step for simulation
dt_plotting = 0.3 # refresh rate for plots
dt_controller = dt_simulation # sample rate for the control... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
resul... |
__all__ = [
'FeatureEncoder'
]
class FeatureEncoder():
r"""Class for implementing feature encoders.
Date:
2020
Author:
Luka Pečnik
License:
MIT
Attributes:
Name (str): Name of the feature encoder.
"""
Name = None
def __init__(self, **kwargs):... |
class CyclesCurveSettings:
radius_scale = None
root_width = None
shape = None
tip_width = None
use_closetip = None
|
#from .atributo import Atributo
class TablaDestino:
nombre = " "
atributos = []
datos=[]
funcion=False
atributo=''
proceso=''
def __init__(self,nombre,atributos,funcion=False,atributo=None,proceso=None):
self.nombre=nombre
self.atributos=atributos
self.funcion=funci... |
#ordena a lista em ordem crescente sem o SORT/SORTED
numeros = list()
for n in range(0,5):
numero = int(input("Digite um numero: "))
for chave, valor in enumerate(numeros):
if numero < valor:
numeros.insert(chave, numero)
break
else:
numeros.append(numero)
print(n... |
#
# Copyright (c) 2021 salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#
"""
Contains all anomaly detection models. Forecaster-based anomaly detection models
may be found in... |
# -*-coding:utf-8 -*-
# Reference:**********************************************
# @Time : 2019-12-31 19:53
# @Author : Fabrice LI
# @File : 20191231_106_convert_sorted_list_to_binary_search_tree.py
# @User : liyihao
# @Software : PyCharm
# @Description: Given a singly linked list where elements are sorte... |
valid_address_types = [
['ant', 'antenna'],
['mbth', 'marine berth'],
['allotment', 'allotment'],
['atm', 'auto teller machine'],
['bbox', 'bathing box'],
['bbq', 'barbeque'],
['berths', 'berths'],
['berth', 'berth'],
['bldgs', 'buildings'],
['bldg', 'building'],
[... |
def get_oauth():
pass
def get_repo(owner, name):
pass
|
def decompress(nums):
keep = []
for i in range (0,len(nums),2):
x = nums[i]
while x > 0:
keep.append(nums[i+1])
x-=1
return keep
#nums = [1,2,3,4]
nums = [1,1,2,3]
print(decompress(nums)) |
def weekday(n):
'returns the name of the nth day of the week'
days = ['Monday', 'Tuesday', 'Wednesday']
if 1 <= n and n <= 7:
return days[n-1]
|
'''
Write and test a program that computes the area of a circle.
Request a number representing a radius as input from the user.
Use the formula 3.14 × radius^2 to compute the area.
Output this result with a suitable label.
An example of the program input and output is shown below:
Enter the radius: 5
The are... |
while True:
enemy = hero.findNearestEnemy()
friend = hero.findNearestFriend()
hero.moveXY((friend.pos.x + enemy.pos.x) / 2, (friend.pos.y + enemy.pos.y) / 2);
|
'''
Faça um Programa que leia 10 números inteiros e armazene-os num vetor.
Armazene os números pares no vetor PAR e os números IMPARES no vetor impar. Imprima os três vetores.
'''
# Resposta:
num = []
par = []
imp = []
for n in range(10):
num.append(int(input('Digite um número: ')))
for n in num:
if n % 2 ==... |
r_fib = {}
LIMIT = 100 + 1
fib = [1,2]
for i in range(LIMIT):
fib.append(fib[-1] + fib[-2])
for i in range(LIMIT):
r_fib[fib[i]] = i
num_cases = int(input())
for c in range(num_cases):
input()
code = list(map(int, input().split()))
cipher = input().strip()
out_text = [' '] * 100
i = 0
str_len = 0
... |
"""
Exception for use in the telemetry agent
Copyright (C) 2017-2022 Intel Corporation
SPDX-License-Identifier: Apache-2.0
"""
class TelemetryException(Exception):
pass
|
# O(N * logN)
# https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = []
for n in nums:
index = self.binary_search(res, ... |
g = 85
h = 85
if g < h:
print("g is less than h")
else:
if g == h:
print("g is equal to h")
else:
print("g is greater than h")
|
# -*- coding:utf-8 -*-
# Copyright 2019 TEEX
#
# 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 ... |
def soma_imposto(custo,taxa_imposto):
preco = custo +(custo * taxa_imposto/100)
return preco
x = float(input("Digite o valor de custo:"))
y = float(input("Digite o valor de porcentagem de imposto:"))
result = soma_imposto(x,y)
print("O preço final do produto é:",result)
|
"""
# SEARCH IN ROTATED ARRAY
You are given an integer array nums sorted in ascending order, and an integer target.
Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
If target is found in the array return its index, otherwise, return -1.
Exam... |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
length = 0
for s_i in reversed(s):
if(s_i != ' '):
length += 1
elif (length != 0):
break
return length
# input = "Hello World"
input = "a "
output = Solution().lengthOfLastWo... |
# -*- coding: utf-8 -*-
moves = {
0x01: "POUND",
0x02: "KARATE_CHOP",
0x03: "DOUBLESLAP",
0x04: "COMET_PUNCH",
0x05: "MEGA_PUNCH",
0x06: "PAY_DAY",
0x07: "FIRE_PUNCH",
0x08: "ICE_PUNCH",
0x09: "THUNDERPUNCH",
0x0A: "SCRATCH",
0x0B: "VICEGRIP",
0x0C: "GUILLOTINE",
0x0D: "RAZOR_WIND",
0x0E: "SWORDS_DANCE",
0x0F: "CUT",
... |
# Configs
# Just Monika.
# MongoDB数据库链接
## Example: mongodb://root:password@192.168.1.9:3821
MONGO_DB_URL = "MONGO_DB_ADDR"
# 历史记录最多显示条数
MAX_HISTORY_DISPLAY = 5
# 白名单用户最多显示条数
MAX_WHITELIST_DIAPLAY = 10
# 签到最多尝试次数
TRY_TIME = 5
# 签到失败后延时
LATER_TIME = 60
# 程序启动广播
START_BROADCAST_STR = \
'''Hello World!
QQ机器人程序启动成功
软件版本@... |
x,y,z = 32,31,23;
list = ['Apple','Benana','Mango'];
a,b,c = list;
print(">>> x y z <<<");
print("> x : " + str(x));
print("> y : " + str(y));
print("> z : " + str(z));
print("\n>>> a b c <<<");
print("> a : " + a);
print("> b : " + b);
print("> c : " + c);
|
def addr(regs, a, b, c):
result = regs[:]
result[c] = regs[a] + regs[b]
return result
def addi(regs, a, b, c):
result = regs[:]
result[c] = regs[a] + b
return result
def mulr(regs, a, b, c):
result = regs[:]
result[c] = regs[a] * regs[b]
return result
def muli(regs, a, b, c):
... |
class Solution(object):
def freqAlphabets(self, s):
"""
:type s: str
:rtype: str
"""
res = []
n = len(s) - 1
while n >= 0:
if s[n] == '#':
res.append(s[n - 2:n])
n -= 3
else:
res.append(s[... |
languages = [
"afrikaans",
"albanian",
"amharic",
"arabic",
"armenian",
"assamese",
"azerbaijani",
"basque",
"belarusian",
"bengali",
"bengali romanize",
"bosnian",
"breton",
"bulgarian",
"burmese",
"burmese zawgyi font",
"catalan",
"chinese (simpl... |
{
"name": "PerUDT",
"version": "1.0.0",
"task": "Treebank",
"splits": ["train", "test", "dev"],
"description": "The Persian Universal Dependency Treebank (PerUDT) is the result of automatic coversion of Persian Dependency Treebank (PerDT) with extensive manual corrections",
"size": {"train": 26196, "test": ... |
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
target = int(a, 2)+ int(b, 2)
ans = ""
while target//2:
ans = str(target%2) + ans
target = target//2
ans = str(target) + an... |
#
# PySNMP MIB module BNET-ATM-TOPOLOGY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BNET-ATM-TOPOLOGY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:22:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
# sorting algorithm
# insertion sorting
def insertion_sort(a):
for i in range(1, len(a)):
print("In the i {%s} A : {%s}" % (i, a))
key = a[i]
j = i - 1
print('Before entering in the while j : {%s} , i : {%s} , key : {%s}' % (j, i, key))
while j >= 0 and a[j] > key:
... |
"""
Global exception registry
"""
class APIException(Exception):
"""
Generic Exception wrapper
"""
status_code = 500
def __init__(self, message, user_details=None, internal_details=None):
"""
Create a new APIException
:param message: General exception messag... |
expected_output = {
"lldp-global-status": "Disabled",
"lldp-advertisement-interval": "30",
"lldp-transmit-delay-interval": "0",
"lldp-hold-time-interval": "120",
"lldp-notification-interval": "5",
"ptopo-configuration-trap-interval": "0",
"ptopo-maximum-hold-time": "300",
"lldp-med-globa... |
"""
Least Recently Used Cache
We have briefly discussed caching as part of a practice problem while studying hash maps.
The lookup operation (i.e., get()) and put() / set() is supposed to be fast for a cache memory.
While doing the get() operation, if the entry is found in the cache, it is known as a cache hit. If, h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.