content stringlengths 7 1.05M |
|---|
class DBSession(object):
def __init__(self, pool, select_func):
"""得到一个线程安全连接"""
self.__conn = pool.dedicated_connection()
self.__cursor = self.__conn.cursor()
self.__select = select_func
def insert(self, sql: str, values: tuple = None, lastrowid: bool = False) -> int:
... |
#!/usr/bin/env python3
# encoding: utf-8
# author: cappyclearl
# Given an array and a value, remove all instances of that value in-place and return the new length.
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
# The order of elements can... |
# Link: https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
d = {}
start = 0
maxlen = 0
for i, c in enumerate(s):
if c not in d.keys():
if (i - sta... |
class Number_Pad_To_Words():
let_to_num = {
'a': '2',
'b': '2',
'c': '2',
'd': '3',
'e': '3',
'f': '3',
'g': '4',
'h': '4',
'i': '4',
'j': '5',
'k': '5',
'l': '5',
'm': '6',
'n': '6',
'o': '6',
... |
JOB_TYPES = [
('Delivery driver'),
('Web developer'),
('Lecturer'),
]
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 30 18:05:06 2017
@author: pfduc
"""
class BookingError(Exception):
def __init__(self, arg):
self.message = arg
class TimeSlotError(BookingError):
def __init__(self, arg):
self.message = arg |
class Shazam:
pass
def foo(p):
"""
@param p: the magic word
@type p: Shazam
@return:
""" |
#!/usr/bin/env python3
"""
Write a function called in_bisect that takes a sorted list and a target
value and returns True if the word is in the list and False if it’s not.
"""
def in_bisect(li, value):
upper_limit = len(li)-1
lower_limit = 0
while upper_limit >= lower_limit:
word_position = (lo... |
'''
mymod.py - counts the number of lines and chars in the file.
'''
def countLines(name):
'''
countLines(name) - counts the number of lines in the file "name".
Example: countLines("/home/test_user1/test_dir1/test.txt")
'''
file = open(name)
return len(file.readlines())
d... |
#!/usr/bin/env python3
# Parse input
with open("14/input.txt", "r") as fd:
seq = list(fd.readline().rstrip())
fd.readline()
line = fd.readline().rstrip()
instr = dict()
while line:
i = tuple([x for x in line.split(" -> ")])
instr[i[0]] = i[1]
line = fd.readline().rstrip()
... |
x=5
while x < 10:
print(x)
x += 1
|
num = int(input('digite um numero para saber se ele é par ou impar: '))
poi = num%2
if poi == 0:
print('este numero é par')
else:
print('este numero é ímpar')
|
src = Split('''
prov_app.c
''')
if aos_global_config.get("ERASE") == 1:
component.add_macros(CONFIG_ERASE_KEY);
component = aos_component('prov_app', src)
component.add_comp_deps('kernel/yloop', 'tools/cli', 'security/prov', 'security/prov/test')
component.add_global_macros('AOS_NO_WIFI')
|
#!/usr/bin/env python3
# https://agc001.contest.atcoder.jp/tasks/agc001_a
n = int(input())
l = [int(x) for x in input().split()]
l.sort()
print(sum(l[::2]))
|
"""
This module provides basic methods for unit conversion and calculation of basic wind plant variables
"""
def convert_power_to_energy(power_col, sample_rate_min="10T"):
"""
Compute energy [kWh] from power [kw] and return the data column
Args:
df(:obj:`pandas.DataFrame`): the existing data fram... |
"""
Pattern Matching: You are given two strings, pattern and value. The pattern string consists of
just the letters a and b, describing a pattern within a string. For example, the string "catcatgocatgo"
matches the pattern "aabab" (where cat is a and go is b). It also matches patterns like a, ab, and b.
Write a met... |
"""
This program repeatedly asks a user to guess a number. The program ends
when they're geussed correctly.
"""
# Secret number
my_number = 10
# Ask the user to guess
guess = int(input("Enter a guess: "))
# Keep asking until the guess becomes equal to the secret number
while guess != my_number:
prin... |
N,*H = [int(x) for x in open(0).read().split()]
def solve(l, r):
if l>r:
return 0
min_=min(H[l:r+1])
for i in range(l,r+1):
H[i]-=min_
count=min_
i=l
while i<r:
while i<=r and H[i]==0: i+=1
s=i
while i<=r and H[i]>0: i+=1
count+=solve(s,i-1)
re... |
# FizzBuzz
# Getting input from users for the max number to go to for FizzBuzz
ip = input("Enter the max number to go for FizzBuzz: \n")
# If user inputs a number this is executed
if (ip != ""):
for i in range(1, int(ip) + 1):
if (i % 3 == 0 and i%5 == 0):
print("FizzBuzz")
elif (i % 3... |
town = input().lower()
sell_count = float(input())
if 0<=sell_count<=500:
if town == "sofia":
comission = sell_count*0.05
print(f'{comission:.2f}')
elif town=="varna":
comission = sell_count * 0.045
print(f'{comission:.2f}')
elif town == "plovdiv":
comission = sell_c... |
class Keyword(object):
"""
Represents a keyword that can be intercepted from a message.
"""
def __init__(self, keyword, has_args, handler):
self.keyword = keyword
self.has_args = has_args
self.handler = handler
def handle(self, args=None):
"""
Calls the hand... |
class Compass(object):
def __init__(self, spacedomains):
self.categories = tuple(spacedomains)
self.spacedomains = spacedomains
# check time compatibility between components
self._check_spacedomain_compatibilities(spacedomains)
def _check_spacedomain_compatibilities(self, spa... |
"""
LeetCode Problem 801. Minimum Swaps To Make Sequences Increasing
Link: https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/
Written by: Mostofa Adib Shakib
Language: Python
Time complexity: O(n)
Space complexity: O(n)
Explanation:
1) A[i - 1] < A[i] && B[i - 1] < B[i].
In this case, if ... |
time1 = int(input())
time2 = int(input())
time3 = int(input())
sum = time1 + time2 + time3
minutes = int(sum / 60)
seconds = sum % 60
if seconds <= 9:
print('{0}:0{1}'.format(minutes, seconds))
else:
print('{0}:{1}'.format(minutes, seconds))
|
"""packer_builder/release.py"""
# Version tracking for package.
__author__ = 'Larry Smith Jr.'
__version__ = '0.1.0'
__package_name__ = 'packer_builder'
|
#
# @lc app=leetcode id=908 lang=python3
#
# [908] Smallest Range I
#
# @lc code=start
class Solution:
def smallestRangeI(self, A: List[int], K: int) -> int:
mi, ma = min(A), max(A)
return 0 if ma - mi - 2*K <= 0 else ma - mi - 2*K
# @lc code=end
|
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {} # key - position in list
self.l = [] # numbers
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contai... |
a = [[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0]]
step=30
def setup():
size(500,500)
smooth()
noStroke()
myInit()
def myInit():
for i in range(len(a)):
a[i]=[random(0,10)]
for j in range(len(a[i])):
a[i][j]=random(0,30)
def draw():
global ste... |
#Crie um algoritimo que leia um número e imprima na tela
#o mesmo, o seu antecessor e o seu sucessor.
n1 = int(input("Digite um número para essa operação: "))
print("O nuúmero que você digitou foi {}.\nO seu antecessor é {}.\nO seu sucessor é {}.".format(n1, (n1-1), (n1+1))) |
# porownania
print('----------')
print((1, 2, 3) < (1, 2, 4))
print([1, 2, 3] < [1, 2, 4])
print('ABC' < 'C' < 'Pascal' < 'Python')
print((1, 2, 3, 4) < (1, 2, 4))
print((1, 2) < (1, 2, -1))
print((1, 2, 3) == (1.0, 2.0, 3.0))
print((1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4))
print('--- inne ---')
print(list((1, ... |
# Error handler
class GeneralError(Exception):
"""
This is for general error
"""
def __init__(self, error, severity, status_code):
self.error = error
self.severity = severity
self.status_code = status_code
|
################################### SERVER'S SIDE ###################################
#const
mask = 0xffffffff
#bitwise operations have the least priority
#Note 1: all variables are unsigned 32-bit quantities and wrap modulo 2**32 when calculating, except for
#ml, message length: 64-bit quantity, and
... |
# DOCUMENTATION
# main
def main():
canadian = {"red", "white"}
british = {"red", "blue", "white"}
italian = {"red", "white", "green"}
if canadian.issubset(british):
print("canadian flag colours occur in british")
if not italian.issubset(british):
print("not all italian flag colors... |
#encoding = utf-8
__author__ = 'lg'
with open('H:\Programming\Python_Workspace\in.txt','r') as f:
list1 = f.readline().split()
list2 = f.readline().split()
print(list1)
print(list2)
#两个list的交集(法一) 时间复杂度为O(n^2)
def intersect(a,b):
listRes = []
for i in range(len(a)):
for j in range(len(... |
# @desc Predict the returned value
# @desc by Savonnah '23
def calc(num):
if num <= 10:
result = num * 2
else:
result = num * 10
return result
def main():
print(calc(1))
print(calc(41))
print(calc(-5))
print(calc(3))
print(calc(10))
if __name__ == '__main__':
main... |
### PROBLEM 3
degF = 40.5
degC = (5/9) * (degF - 32)
print(degC)
#when degF is -40.0, degC is -40.0
##when degF is 40.5, degC is 4.72 |
#
# @lc app=leetcode id=1290 lang=python3
#
# [1290] Convert Binary Number in a Linked List to Integer
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
a = [1, 3, -1, -7, 2, 4, -6]
b = [n if n > 0 else 0 for n in a]
print(b)
c = [n for n in a if n > 0]
print(c)
"""
c = (a > b) ? a : b
等价于
c = a if a > b else b
"""
|
#!/usr/bin/python3
def palindrome(num):
if num == num[::-1]:
return True
return False
def addOne(num):
num = int(num) + 1
return str(num)
def isPalindrome(num):
num = str(num)
num = num.zfill(6)
value = palindrome(num[2:])
if value:
num = num.zfill(6)
value... |
a = int(input())
b = int(a/5)
if (a%5 == 0):
print(b)
else:
print(b+1)
|
# Day8 of my 100DaysOfCode Challenge
# Program to open a file in append mode
file = open('Day8/new.txt', 'a')
file.write("This is a really great experience")
file.close()
|
#!/usr/bin/python
def max_in_list(list_of_numbers):
'''
Finds the largest number in a list
'''
biggest_num = 0
for i in list_of_numbers:
if i > biggest_num:
biggest_num = i
return(biggest_num)
|
{
"targets":[
{
"target_name": "accessor",
"sources": ["accessor.cpp"]
}
]
} |
# terrascript/data/Trois-Six/sendgrid.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:26:45 UTC)
__all__ = []
|
__author__ = 'arobres, jfernandez'
# PUPPET WRAPPER CONFIGURATION
PUPPET_MASTER_PROTOCOL = 'https'
PUPPET_WRAPPER_IP = 'puppet-master.dev-havana.fi-ware.org'
PUPPET_WRAPPER_PORT = 8443
PUPPET_MASTER_USERNAME = 'root'
PUPPET_MASTER_PWD = '**********'
PUPPET_WRAPPER_MONGODB_PORT = 27017
PUPPET_WRAPPER_MONGODB_DB_NAME = ... |
'''
A simple programme to print hex grid on terminal screen.
Tip: I have used `raw` strings.
Author: Sunil Dhaka
'''
GRID_WIDTH=20
GRID_HEIGHT=16
def main():
for _ in range(GRID_HEIGHT):
for _ in range(GRID_WIDTH):
print(r'/ \_',end='')
print()
for _ in range(GRID_WIDTH):
... |
'''
Order the following functions by asymptotic growth rate.
4nlog n+2n 210 2log n
3n+100log n 4n 2n
n2 +10n n3 nlog n
'''
'''
2^10 O(1)
3n+100log(n) O(log(n))
4n O(n)
4nlog(n)+2n and O(nlog(n))
n^2+10n and O(n^2)
n^3 O(n^3... |
# encoding = utf-8
class GreekGetter:
def get(self, msgid):
return msgid[::-1]
class EnglishGetter:
def get(self, msgid):
return msgid[:]
def get_localizer(language="English"):
languages = dict(English=EnglishGetter, Greek=GreekGetter)
return languages[language]()
# Create our localizers
e, g = get_l... |
print("Enter the number of terms:")
n=int(input())
a=0
b=1
for i in range(n+1):
c=a+b
a=b
b=c
print(c,end=" ")
|
class Foo:
def __init__(self):
self.tmp = False
def extract_method(self, condition1, condition2, condition3, condition4):
list = (1, 2, 3)
a = 6
b = False
if a in list or self.tmp:
if condition1:
print(condi... |
# Escape Sequences
# \\
# \'
# \"
# \n
course_name = "Pyton Mastery \n with Mosh"
print(course_name)
|
# @Title: 二进制矩阵中的特殊位置 (Special Positions in a Binary Matrix)
# @Author: KivenC
# @Date: 2020-09-13 10:54:22
# @Runtime: 64 ms
# @Memory: 13.7 MB
class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
row = [sum(r) == 1 for r in mat]
col = [sum([mat[... |
# Section05-2
# 파이썬 흐름제어(반복문)
# 반복문 실습
# 코딩의 핵심 -> 조건 해결 중요
# 기본 반복문 : for, while
v1 = 1
while v1 < 11:
print("v1 is :", v1)
v1 += 1
for v2 in range(10):
print("v2 is: ", v2)
for v3 in range(1,11):
print("v3 is :", v3)
# 1 ~ 100합
sum1 = 0
cnt1 = 0
while cnt1 <= 100:
... |
class VolumeRaidLevels(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_lun_raid_type(idx_name)
class VolumeRaidLevelsColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_luns()
|
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
X_MOD = [0,1,0,-1]
Y_MOD = [1,0,-1,0]
num_states = 0
state_trans = []
infected_state = 0
class Node:
def __init__(self, state, x, y):
self.x = x
self.y = y
self.state = state
def updateDir(self, dir):
'''
Directions can be anyth... |
class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def __str__(self):
p = self
nums = []
while p:
nums.append(p.data)
p = p.next_node
return "[" + ", ".join(map(str, nums)) + "]"
@st... |
# #todo -- make these constants configurable via admin
# https://django-constance.readthedocs.io/en/latest/
# note that the constants below are example only (different constants were used during the application process)
R0_YESES_NEEDED = 2
# R0_NOS_NEEDED = 2
R0_RATINGS_NEEDED = 3 # changed from 2 to 3 in 2018 (this n... |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.makeapirate.MakeAPirateGlobals
BODYSHOP = 0
HEADSHOP = 1
MOUTHSHOP = 2
EYESSHOP = 3
NOSESHOP = 4
EARSHOP = 5
HAIRSHOP = 6
CLOTHE... |
def bubble_sort(nums: list[float]) -> list[float]:
is_sorted = True
for loop in range(len(nums) - 1):
for indx in range(len(nums) - loop - 1):
if nums[indx] > nums[indx + 1]:
is_sorted = False
nums[indx], nums[indx + 1] = nums[indx + 1], nums[indx]
i... |
#
# PySNMP MIB module MPLS-LSR-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MPLS-LSR-STD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:43:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
n = int(input('How many sides the convex polygon have: '))
nd = (n * (n - 3)) / 2
print(f'The convex polygon have {nd} sides.')
|
"""
PSEUDO CODE:
function mergesort(m)
var list left, right
if length(m) ≤ 1
return m
else
middle = length(m) / 2
for each x in m up to middle
add x to left
for each x in m after middle
add x to right
left = mergesort(left)
right = mergesort(righ... |
# Minimal django settings to run tests
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = ()
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': './sqlite3.db',
}
}
SECRET_KEY = 'alksjdf93jqpijsdaklfjq;3lejqklejlakefjas'
TEMPLATE_LOADERS = (
'django.tem... |
#!/usr/bin/env python
TOOL = "tool"
PRECISION = "precision"
RECALL = "recall"
AVG_PRECISION = "avg_precision"
STD_DEV_PRECISION = "std_dev_precision"
SEM_PRECISION = "sem_precision"
AVG_RECALL = "avg_recall"
STD_DEV_RECALL = "std_dev_recall"
SEM_RECALL = "sem_recall"
RI_BY_BP = "rand_index_by_bp"
RI_BY_SEQ = "rand_ind... |
# parameters used in experiment
# ==============================================================================
# optitrack communication ip (win10 is the server, the ubuntu receiving data is client)
# ==============================================================================
ip_win10 = '192.168.1.5'
ip_ubuntu_pc... |
Vocales = ("a","e","i","o","u", " ")
texto = input("Ingresar el texto: ")
texto_nuevo = 0
for letters in texto:
if letters not in Vocales:
texto_nuevo = texto_nuevo + 1
print("El numero de consonantes es: ", texto_nuevo) |
FILE_PATH = "data/cows.mp4"
MODEL_PATH = "model/mobilenet_v2_ssd_coco_frozen_graph.pb"
CONFIG_PATH = "model/mobilenet_v2_ssd_coco_config.pbtxt"
LABEL_PATH = "model/coco_class_labels.txt"
WINDOW_NAME = "detection"
MIN_CONF = 0.4
MAX_IOU = 0.5 |
'''
data structures that used executive architecture
'''
class Command(object):
def __init__(self, Name, Payload):
self.Name = Name
self.Payload = Payload
class Gesture(object):
def __init__(self, ID, NAME, LastTimeSync,
IterableGesture, NumberOfGestureRepetitions,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Olivier Noguès
DSC = {
}
class JsBillboard(object):
"""
:category: RecordSet to Billboard Object
:rubric: JS
:type: Data Transformation
:dsc:
Function to convert an AReS recordSet to a valid object for Billboard.
"""
alias ... |
timezone_translation = {
'国际日期变更线西': {'en': ' Intern. Date Line West'},
'萨摩亚群岛': {'en': ' Samoa'},
'协调世界时': {'en': ' Coordinated Universal Time'},
'夏威夷': {'en': ' Hawaii'},
'马克萨斯群岛标准时间': {'en': ' Marquesas Standard Time'},
'阿拉斯加': {'en': ' Alaska'},
'太平洋时间(美国和加拿大)': {'en': ' Pacific Time (US... |
class Pattern:
"""
This class is used for N:M conversions.
"""
def __init__(self, name=""):
"""
Patterns are described by the components which make up the pattern
and the connections between those components.
"""
#
# Pattern name is used in the conversio... |
# Description: Count number of *.mtz files in current directory.
# Source: placeHolder
"""
cmd.do('print("Count the number of mtz structure factor files in current directory.");')
cmd.do('print("Usage: cntmtzs");')
cmd.do('myPath = os.getcwd();')
cmd.do('mtzCounter = len(glob.glob1(myPath,"*.mtz"));')
cmd.do('print(... |
'''FreeProxy exceptions module'''
class FreeProxyException(Exception):
'''Exception class with message as a required parameter'''
def __init__(self, message) -> None:
self.message = message
super().__init__(self.message)
|
__all__ = ["SENTINEL1_COLLECTION_ID", "VV", "VH", "IW", "ASCENDING", "DESCENDING"]
SENTINEL1_COLLECTION_ID = "COPERNICUS/S1_GRD_FLOAT"
VV = "VV"
VH = "VH"
IW = "IW"
ASCENDING = "ASCENDING"
DESCENDING = "DESCENDING"
GEE_PROPERTIES = [
"system:id",
"sliceNumber",
"system:time_start",
"relativeOrbitNumber... |
def problem303():
"""
# This function computes and returns the smallest positive multiple of n such that the result
# uses only the digits 0, 1, 2 in base 10. For example, fmm(2) = 2, fmm(3) = 12, fmm(5) = 10.
As an overview, the algorithm has two phases:
# 0. Determine whether a k-digit solution is... |
start = 1
end = 100
for x in range(start,end):
if (x % 2 == 0):
continue
print(x) |
'''12、 统计不同类型的字符
【问题描述】
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
【输入】
一行字符。
【输出】
分别输出英文字母、空格、数字和其它字符的个数,具体格式见输出样例。
【输入样例】
123runoobc kdf235*(dfl
【输出样例】
char = 13,space = 2,digit = 6,others = 2'''
str = input()
alphaNum=0
numbers=0
spaceNum=0
otherNum=0
for i in str:
if i.isalpha():
alphaNum +=1
elif i.isnume... |
"""
You are given an n x n 2D matrix representing an image. Rotate the matrix 90 degrees clockwise in-place.
Example 1:
[[1, 2, 3], [[7, 4, 1],
[4, 5, 6], -> [8, 5, 2],
[7, 8, 9]], [9, 6, 3]]
Example 2:
[[ 5, 1, 9, 11], [[15, 13, 2, 5],
[ 2, 4, 8, 10], -> [14, 3, 4, 1],
[13, 3, 6, 7], ... |
"""
1356. Sort Integers by The Number of 1 Bits
Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the sorted array... |
class AggResult:
def __init__(self, agg_key, result=None, return_counts=True):
self.return_counts = return_counts
if result is None:
self.total = 0
self._hits = []
else:
self.total = result['hits']['total']['value']
self._hits = result['aggrega... |
input = """
a(1).
a(2).
b(1,2).
c(2).
c(3).
q(X,Y) :- a(X), c(Y).
p(X,Y,Z) :- a(X), q(Y,Z), m(X,Z).
m(X,Y) :- a(Z), p(Z,X,Y).
m(X,Y) :- b(X,Y), not n(X,Y).
n(X,Y) :- q(X,Y).
n(X,Y) :- b(X,Y), m(X,Y).
"""
output = """
a(1).
a(2).
b(1,2).
c(2).
c(3).
q(X,Y) :- a(X), c(Y).
p(X,Y,Z) :- a(X)... |
# -*- coding: utf-8 -*-
"""
Created on 2018/10/31
@author: gaoan
"""
class HourTrading(object):
def __init__(self):
self.trading_session = None # 盘前/盘后
self.latest_price = None # 最新价
self.prev_close = None # 昨日收盘价
self.latest_time = None # 最后交易时间
self.volume = None # ... |
"""
백준 14623번 : 감정이입
"""
B1 = int(input(), 2)
B2 = int(input(), 2)
print(bin(B1 * B2)[2:]) |
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
s = set()
for path in paths:
s.add(path[0])
s.add(path[1])
for path in paths:
s.remove(path[0])
return list(s).pop()
|
class Solution:
def checkString(self, s: str) -> bool:
flag = 0
for ch in s:
if flag == 0 and ch == 'b':
flag = 1
elif flag == 1 and ch == 'a':
return False
return True |
class Node:
def __init__(self, data=None) -> None:
self.data = data
self.next = None
self.prev = None
class DoublyList:
def __init__(self) -> None:
self.front = None
self.back = None
self.size = 0
def add_back(self, data: int) -> None:
... |
class AlmostPrimeNumbers:
def getNext(self, m):
sieve = [True]*(10**6+2)
for i in xrange(2, 10**6+2):
if sieve[i]:
for j in xrange(2*i, 10**6+2, i):
sieve[j] = False
def is_almost(n):
return not sieve[n] and not any(n%i == 0 for i i... |
class LandingType(object):
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
INSIGHTS = 5
CHAMPS = 6
NAMES = {
KICKOFF: 'Kickoff',
BUILDSEASON: 'Build Season',
COMPETITIONSEASON: 'Competition Seas... |
#!/usr/bin/env python
polymer = input()
letters = [ord(c) for c in set(polymer.upper())]
polymer = [ord(c) for c in polymer]
def react(polymer, forbidden=set()):
stack = []
for unit in polymer:
if unit not in forbidden:
if stack and abs(unit - stack[-1]) == 32:
stack.po... |
HANGMAN_ASCII_ART = ("""
_ _
| | | |
| |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __
| __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_|... |
#!/usr/bin/env python3
class colors:
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RED = '\033[91m'
BOLD = '\033[1m'
RESET = '\033[0m' |
nombre_usuario = input("Introduce tu nombre de usuario: ")
print("El nombre es:", nombre_usuario)
print("El nombre es:", nombre_usuario.upper())
print("El nombre es:", nombre_usuario.lower())
print("El nombre es:", nombre_usuario.capitalize())
|
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node != N... |
RELEVANT_COLUMNS = [
"HONG KONG",
"JAPAN",
"CANADA",
"FINLAND",
"DENMARK",
"ESTONIA",
"POLAND",
"CZECH REPUBLIC",
"SLOVENIA and BALKANs",
"ITALY",
"SPAIN",
"SWITZERLAND",
"BENELUX",
"UK",
"ISLAND",
"USA Wholesale",
"Germany/ Austria",
"Sweden/ Norw... |
'''
Author : MiKueen
Level : Hard
Company : Stripe
Problem Statement : First Missing Positive
Given an array of integers, find the first missing positive integer in linear time and constant space.
In other words, find the lowest positive integer that does not exist in the array.
The array can contain duplicates and ... |
#*****************************************************************************#
#* Copyright (c) 2004-2008, SRI International. *#
#* All rights reserved. *#
#* ... |
API = "api"
API_DEFAULT_DESCRIPTOR = "default"
API_ERROR_MESSAGES = "errorMessages"
API_QUERY_STRING = "query_string"
API_RESOURCE = "resource_name"
API_RETURN = "on_return"
COLUMN_FORMATING = "column_formating"
COLUMN_CLEANING = "column_cleaning"
COLUMN_EXPANDING = "column_expending"
DEFAULT_COLUMNS_TO_EXPAND = ["chan... |
region = 'us-west-2'
default_vpc = dict(
enable_dns_hostnames=True,
cidr_block='10.0.0.0/16',
tags={'Name': 'default'},
)
default_gateway = dict(vpc_id='${aws_vpc.default.id}')
internet_access_route = dict(
route_table_id='${aws_vpc.default.main_route_table_id}',
destination_cidr_block='0.0.0.0/0',
g... |
ants_picture = """
.`
/
`:`
.-` ... |
class BlackjackWinner:
def winnings(self, bet, dealer, dealerBlackjack, player, blackjack):
if player > 21 or (player < dealer and dealer <= 21):
return -bet
if dealerBlackjack and blackjack:
return 0
if dealerBlackjack and not blackjack:
return -bet
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.