content stringlengths 7 1.05M |
|---|
"""Tests package.
Dummy file for allowing exclusion from mypy
"""
|
"""
Copyright (c) 2010 Aldo Cortesi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, s... |
"""
An app for managing release notes. It reads in a configured release notes file from the source directory
(so that you don't have to do double documentation), then generates JSON and Atom feeds based on those.
It also has the ability to check to see if a given user has already seen a release notes entry which can be... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-CasTestMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-CasTestMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:29:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan... |
def solution(N, A):
ret = [0] * N
if sum(A)/len(A) == N + 1:
return ret
_max = 0
for a in A:
if 1 <= a <= N:
ret[a - 1] += 1
if ret[a - 1] > _max:
_max = ret[a - 1]
elif a == N + 1:
ret = [_max] * N
return ret
def test_... |
## N-th Power
## 8 kyu
## https://www.codewars.com/kata/57d814e4950d8489720008db
def index(array, n):
if len(array) > n:
return array[n] ** n
return -1 |
def useGenerator(gen):
gen(1, "Cocoa")
gen(2, "Chino")
gen(3, "Rize")
gen(4, "Chiya")
gen(5, "Sharo")
gen(6, "Daydream Cafe")
gen(7, "No Poi!")
gen(8, "Tenkuu Cafeteria")
gen(9, "Sekai ga Cafe ni Natchatta")
gen(10, "Nikkori Cafe no Mahou Tsukai")
|
# coding:utf-8
class Stack(object):
"""栈"""
def __init__(self):
self.__list = []
def push(self, item):
"""添加一个新的元素item到栈顶"""
self.__list.append(item)
def pop(self):
"""弹出栈顶元素"""
return self.__list.pop()
def peek(self):
"""返回栈顶元素"""
if self... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
len_nums = len(nums)
for i in range(len_nums):
for j in range(i+1,len_nums):
if nums[i]+nums[j] == target:
return [i,j]
return [None,None]
|
class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
s = sum(A)
if s % 3 != 0:
return False
s //= 3
cum = 0
total = 0
for a in A:
cum += a
if cum == s:
total += 1
cum = 0
if ... |
""" exceptions.py: PostcodeSearchBuilder Custom Exceptions """
class Error(Exception):
""" Base Exception Class """
pass
class StopSubjectBuilderErrorException(Error):
""" An error is raised during the ETL Pipeline """
pass
|
def calculate ():
a = float(input("Enter 1st number:"))
b = float(input("Enter 2nd number:"))
c = float(input("Enter 3rd number:"))
sum = a + b + c
if a == b == c:
return 3*sum
else:
return sum
print(calculate())
|
#This program used nested loops to display this pattern
for rows in range(6):
print('#',end ='')
for colums in range(rows):
print(' ',end='')
print('#')
|
total = mais1k = cheaper = cheaper_price = 0
while True:
print('-='*30)
produto = str(input('Produto: ')).strip()
price = float(input('Preço: R$'))
if price > 1000:
mais1k += 1
if cheaper == 0:
cheaper = produto
cheaper_price = price
if cheaper_price > price:
chea... |
def isVowel(c):
return c == "a" or c == "e" or c == "i" or c == "o" or c == "u"
# Function to return the count of sub-strings
# that contain every vowel at least
# once and no consonant
def countSubstringsUtil(s):
count = 0
# Map is used to store count of each vowel
mp = dict.fromkeys(s, 0)
n ... |
_verbose = False
def set_verbose(verbose):
global _verbose
_verbose = verbose
|
def rule(event):
return event.get("action") == "repo.create"
def title(event):
return f"Repository [{event.get('repo', '<UNKNOWN_REPO>')}] created."
|
class Event:
def __init__(self, eventType, playerId, timeStamp):
self.type = type(self).__name__
self.eventType = eventType
self.playerId = playerId
self.timeStamp = timeStamp
|
def iter(n, prev, curr):
if n == 0:
return curr
return iter(n-1, curr, prev + curr)
def fibonacci(n):
return iter(n, 1, 0)
if __name__ == '__main__':
print(fibonacci(int(input()))) |
txt = 'input'
with open(txt) as f:
lines = f.readlines()
aim = 0
depth = 0
horPos = 0
for line in lines:
line = line.strip()
line = line.split()
line[1] = int(line[1])
if line[0] == 'forward':
horPos += line[1]
depth += aim * line[1]
el... |
def makeprobability(hairetsu):
probability = []
for k in range(len(hairetsu)): # probabilityに確率を入れる
probability.append(hairetsu[k] / sum(hairetsu))
return probability
|
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# 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... |
"""
The constants used for Lobe Connect local API
"""
IMAGE_INPUT = 'image'
PREDICTIONS = 'predictions'
LABEL = 'label'
CONFIDENCE = 'confidence'
|
class AldebaranException(Exception):
""" Base exception for all Aldebaran API Exceptions. """
def __init__(self, status, message, data):
super(AldebaranException, self).__init__()
self.status = status
self.message = message
self.data = data
def __repr__(self):
ret... |
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description: refer https://github.com/ThilinaRajapakse/simpletransformers
"""
def sweep_config_to_sweep_values(sweep_config):
"""
Converts an instance of wandb.Config to plain values map.
wandb.Config varies across versions quite significantly... |
ROS_QUEUE_SIZE = 10
PATHFINDER_NODE_ID = "pathfinder"
PATHFINDER_SERVER_NODE = "action"
PATHFINDER_SERVER = "%s/%s" % (PATHFINDER_NODE_ID, PATHFINDER_SERVER_NODE)
# PATHFINDER_SERVER = "/rh/%s/%s" % (PATHFINDER_NODE_ID, PATHFINDER_SERVER_NODE)
PATHFINDER_INPUT_TOPIC = "%s/input" % PATHFINDER_NODE_ID
PATHFINDER_DEBUG_... |
a = "Glad to see you here"
# 很高兴在这里遇见你
print("这是使用str方法:",str(a))
b = "Same here"
# 我也一样
print("这是使用repr方法:",repr(b))
|
# dictionaries
CustomerData={
'Name': 'SAM', 'AGE':15,'ADDRESS':'Falastine St'
}
CustomerData['Name']='Ameer'
CustomerData['AGE']=17
CustomerData['ADDRESS']='Al-Mansour'
print(CustomerData.get('ADDRESS','ADDRESS Not Found'))
print(CustomerData.get('Name','Name Not Found'))
print(CustomerData.get('AGE',... |
"""
Wypisz spiralnie liste dwuwymiarowa.
"""
# Wersja 1
def spirala_v1(macierz, x=0, y=0):
wynik = []
if x == 0 and y == 0:
x, y = len(macierz[0]), len(macierz)
k = 0
l = 0
while k < y and l < x:
for i in range(l, x):
wynik.append(macierz[k][i])
k += 1
... |
"""Create a Tree data structure.
The structure must be recursive. A node may have zero or more children. A node has access to children nodes, but not to its parent.
Source: programming-idioms.org
"""
# Implementation author: nickname
# Created on 2016-02-18T16:57:57.310492Z
# Last modified on 2017-10-04T20:22:26.702... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause
"""
SPDX document formatting
"""
# document level strings
spdx_version = 'SPDX-2.2'
data_license = 'CC0-1.0'
spdx_id = 'SPDXRef-DOCUMENT'
document_name = 'Tern report for {image_name}'
document_co... |
#!/usr/bin/env python
#####################################
# Installation module for dnscat2
#####################################
# AUTHOR OF MODULE NAME
AUTHOR="Jens Muecke (ryd)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update dnscat2"
# INSTALL TYPE GIT, SVN, FILE DOWNLOAD
# OPTIONS = G... |
def insertShiftArray (arr, num) :
if len(arr) % 2 == 0 :
middle = len(arr) / 2
else :
middle = int(len(arr) / 2) + 1
newArr = []
i = 0
while (i < len(arr)) :
if i == middle and newArr[len(newArr) - 1] != num:
newArr.append(num)
else :
newArr.append(arr[i])
i+=1
return ne... |
class User:
"""
GitHub User
https://developer.github.com/v3/users/
Attributes:
login: GitHub user name
id: Internal GitHub id
avatar_url: URL of image like "https://avatars.githubusercontent.com/u/6752317?v=3",
html_url: Public user URL looks like "https://github.com/ba... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
# Example for break
i=3
j=5
while i:
i-=1
print("i",i)
while j:
j -=1
print("j",j)
if j == 4:
break
print("outside j loop")
print(j,i)
# In[ ]:
|
"""
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not... |
# 1- Declarando variáveis.
grupo_de_pessoas = list()
pessoa = dict()
escolha = ''
ultima_mulher = ''
soma_de_idades = 0
# 2- Adicionando valores ao dicionário "pessoa".
while True:
print('-=-' * 30)
pessoa.clear()
pessoa['nome'] = str(input('Nome: ')).strip().title()
pessoa['sexo'] = str(input('Sexo: [... |
"""
Version
"""
__version__ = "1.17"
RELEASE = "V01_17"
|
largest = None
smallest = None
while True:
nStr = input('Enter a number: ')
try:
if nStr == 'done':
break
n = float(nStr)
if largest is None or largest < n:
largest = n
if smallest is None or smallest > n:
smallest = n
except:
print... |
# Create dummy variables: df_region
df_region = pd.get_dummies(df)
# Print the columns of df_region
print(df_region.columns)
# Create dummy variables with drop_first=True: df_region
df_region = pd.get_dummies(df, drop_first=True)
# Print the new columns of df_region
print(df_region.columns)
|
access_key = 'xxx'
business_id = 1337
document_hash = 'xxx'
signer_email = 'test@example.com'
template_id = 'xxx'
field_identifier = 'xxx'
oauth_client_id = 'xxx'
oauth_client_secret = 'xxx'
code = ''
state = ''
|
# Time: O(n + l * h), l is the number of leaves
# Space: O(h)
# 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 smallestFromLeaf(self, root):
"""
:type root: ... |
def from_prefix_suffix(text, n, less = operator.__lt__):
def equal(a, b):
return not less(a, b) and not less(b, a)
B, t, out = [-1] + [0] * n, -1, 1
for i in range(1, n + 1):
# niezmiennik: out = maximum_suffix(text[0..i - 1]))
# niezmiennik: B[0..i - out] = prefix_suffix(text[out..i - 1])
# niezm... |
class DeltaLake(object):
class LandingZone:
def __init__(self, source_dataframe, file_path, stream_query):
self.source_dataframe = source_dataframe
self.file_path = file_path
self.stream_query = stream_query
def write_stream(self):
try:
... |
a = 1
b = 1.0
c = 4
d = 4.0
print (b / d) |
# This is a string object
name = 'Swaroop'
if name.startswith('Swa'):
print('Yes, the string starts with "Swa"')
if 'a' in name:
print('Yes, it contains the string "a"')
if name.find('war') != -1:
print('Yes, it contains the string "war"')
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China'... |
class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count('U')==moves.count('D') and moves.count('R')==moves.count('L')
"""
class Solution:
def judgeCircle(self, moves: str) -> bool:
v,h=0,0
for c in moves:
if c=='U':
... |
class Replace:
def __init__(self, data):
self.data = data
def replace(self, index):
if index == 0:
if self.data % 10 == 0:
self.data = "%d-%d" %((int(self.data / 10) - 1) * 10 + 1, self.data)
else:
self.data = "%d-%d" %((int(self.data ... |
class Error(Exception):
pass
class HttpError(Error):
def __init__(
self,
error,
error_description,
error_detail=None,
status_code=None,
url=None):
self.error = error
self.error_description = error_description
se... |
class SessionProxy:
@property
def session(self):
"""Proxy for ``self._session``."""
return self._session # pragma: no cover
@property
def query(self):
"""Proxy for ``self._session.query``."""
return self._session.query # pragma: no cover
def add(self, *args, **kwa... |
a = int(input())
t = 0
for x in range(a,50):
if x % 2 !=0 and t <6:
t = t+1
print(x)
|
def pangkat_tiga(angka):
return angka ** 3
# argumen # nilai kembalian
pangkat_tiga_1 = lambda angka_1, angka_2, larik : [angka_1 ** 3 if angka_1 % 3 == 0 else angka_1 + 3,
angka_2 ** 2,
... |
class Generator:
"""
Base generator class. Analogous to Input class.
Object Propertie(s):
------------------
data : Dict
A dictionary to hold all the node & edge information.
See also:
---------
RandomGNP
"""
def ... |
def solution(s, n):
answer = ''
for char in s:
if char == " ": answer += " "
else:
if (ord(char) + n > 90 and ord(char) >= 65
and ord(char) <= 90) or (ord(char) + n > 122
and ord(char) >= 97
... |
__all__ = ['SpikeSource']
class SpikeSource(object):
"""
A source of spikes.
An object that can be used as a source of spikes for objects such as
`SpikeMonitor`, `Synapses`, etc.
The defining properties of `SpikeSource` are that it should have:
* A length that can be extracted wi... |
# Prgram to demonstrate keyword argument
def display(name,course="AI"):
print("The name is",name)
print("The course is",course)
display(course="AI",name="adi")
display(name="ram")
|
class Transaction:
def __init__(self, ticker, trans_type, quantity, owned, balance):
self.ticker = ticker
self.trans_type = trans_type
self.quantity = quantity
self.owned = owned
self.balance = balance
@classmethod
def failed(cls):
return cls("FAILED", "FAILE... |
INITALQCFINISHEDLIB = {
'17' : 'Bioanalyzer QC (Library Validation) 4.0',
'20' : 'CaliperGX QC (DNA)',
'24' : 'Customer Gel QC',
'62' : 'qPCR QC (Library Validation) 4.0',
'64' : 'Quant-iT QC (Library Validation) 4.0',
'67' : 'Qubit QC (Library Validation) 4.0',
'904' : 'Automated Quant-iT Q... |
# Copyright 2020 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, ... |
# Longest Sequence with two unique numbers
class Solution:
def findSequence(self, arr):
last_num = -1
second_last_num = -1
last_num_count = 0
current_max = 0
maximum = 0
for num in arr:
if num == last_num or num == second_last_num:
curre... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
# 中序遍历是递增序列
def inorder(root):
... |
class Rate:
def buildRateRequest(self):
rateReq = {
"items": [
{
"productId": 3387821,
"variantId": 12009212,
"weight_unit": "grams",
"weight": 2,
"quantity": 1
}
... |
"""
Programming for linguists
Implementation of the data structures "Node" and "Binary Tree"
"""
class Node:
"""Node class."""
def __init__(self, val):
self.value = val
self.left_child = None
self.right_child = None
def insert(self, data):
"""Insert data as node's child"... |
# -*- coding: utf-8 -*-
{
'!langcode!': 'ro',
'!langname!': 'Română',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" (actualizează) este o expresie opțională precum "câmp1=\'valoare_nouă\'". Nu puteți actualiza sau șterge rezulta... |
nlinhas = input('linhas a serem lidas:')
frase = []
for i in range(len(nlinhas)):
s = input('digite a frase:')
frase.append(s)
cripto = []
for i in range(len(nlinhas)):
f = frase[i].split('')
print(f)
#primeiro
for k in range(len(f)):
if f[k] in '1234567890':
pass
... |
def get_date_restriction_text(tag, events):
"""Generates the text that tells the user the dates that the event they are adding/updating must be in between,
this text changes based on which events already exist, hence the if statements for when reminders are present."""
date_text_dict = {
"mps": [f"... |
def load_text(path, num_heads=0, num_samples=-1):
lines = []
with open(path, encoding="utf-8") as f:
if num_heads > 0:
for _ in range(num_heads):
next(f)
for i, line in enumerate(f):
if (num_samples > 0) and (i >= num_samples):
break
... |
"""Input an array of numbers, return the sum of all of the positives ones."""
def positive_sum(arr):
"""Return the sum of positive integers in a list of numbers."""
if arr:
return sum([a for a in arr if a > 0])
return 0
|
class animal():
def __init__(self):
print('ANIMAL CREATED')
def eat(self):
print('EATING')
def who_am_i(self):
print('ANIMAL')
# mya=animal()
# mya.eat()
# mya.who_am_i()
# حالا درایو کردن کلاس داگ از انیمال
class dog(animal):
def __init__(self):
# animal.__init... |
class Solution:
def numMatchingSubseq(self, S: str, words: List[str]) -> int:
"""Array.
Running time: O(s + w) where s == len(S) and w == sum(length of each word in words).
"""
n = len(words)
d = collections.defaultdict(list)
for word in words:
d[word[0]]... |
training_data = {
"politics": [
"Putin orders troops into pro-Russian regions of eastern Ukraine.",
"The president decided not to go through with his speech.",
"There is much uncertainty surrounding the coming elections.",
"Democrats are engaged in a ‘new politics of evasion’",
]... |
class Rec2TapsError(ValueError):
pass
class UnequalSampleRate(Rec2TapsError):
'Stimuli file and the recording file have unequal sample rate'
def __init__(self, stimuli_file, recording_file, stimuli_sr, recording_sr):
self.stimuli_file = stimuli_file
self.recording_file = recording_file
... |
'''
Title : Find the Second Largest Number
Subdomain : Basic Data Types
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
Problem :
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a lis... |
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
'''
class Solution:
# @param {integer[]} nums
# @return {integer}
def majorityEl... |
def addition(*numbers) -> int:
total_sum = 0
for number in numbers:
total_sum += number
return total_sum
sum = addition(2, 3)
print(f'sum: {sum}')
|
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
# Python merges dictionary keys
# in the order listed in the expression, overwriting
# duplicates from left to right.
#
# Works in Python 3.5+
print({**x, **y})
|
class Debt(object):
def __init__(self,data=None):
self.fromUser = data["from"]
self.toUser = data["to"]
self.amount = data["amount"]
if "currency_code" in data:
self.currency_code = data["currency_code"]
else:
self.currency_code = None
def ge... |
# Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
print('-' * 100)
print('{: ^100}'.format('EXERCÍCIO 033 - MAIOR E MENOR VALORES'))
print('-' * 100)
v1 = int(input('Primeiro valor: '))
v2 = int(input('Segundo valor: '))
v3 = int(input('Terceiro valor: '))
menor = v1 # Estamos reduzi... |
#
# PySNMP MIB module TPLINK-PRODUCTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-PRODUCTS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:25:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
def add(x:int, y:int) -> int:
pass
print(add.__annotations__)
# Annotations usually show up in documentation and also are used
# by third party tools
|
# https://app.codesignal.com/arcade/code-arcade/book-market/G9wj2j6zaWwFWsise
def isCaseInsensitivePalindrome(input_string):
# Check if word is a palindrome ignoring casing.
word = input_string.lower()
return word == word[::-1]
|
def spring(point, N, reeks):
if point in reeks:
print(reeks)
for i in (point.x, N):
point.x = + 1
if point.x <= N and (point.y + 1) <= N:
spring(Point(point.x + 2, point.y + 1), N, reeks)
point.x -= 1
reeks.append(point)
class Point:
def __init__(self, x, y... |
print('\033[32m---\033[m' * 20)
print('\033[32mDescubra se você está em regularidade com o alistamento militar obrigatório!\033[m')
per = int(input('Digite quantos anos você tem: '))
if per < 18:
print(f'Ainda falta(m) {18 - per} ano(s) para você se alistar! ')
elif per == 18:
print('Você está na idade de alist... |
# Instruksi:
# Buat variabel-variabel berikut dan definisikan sesuai nilai yang diminta:
#
# angka_saya memiliki nilai 1945
# float_saya diisi dengan desimal 17.8
# boolean_saya menjadi True
angka_saya = 1945
float_saya = 17.8
boolean = True
print(angka_saya,boolean) |
# 클래스 생성 => 계산기 클래스를 이미 생성했다고 가정해보자.
# 계산기 클래스를 활용한 예제
c1 = Cal(10,10)
print(c1.add())
print(c1.subtract())
c2 = Cal(30,20)
print(c2.add())
print(c2.subtract())
|
class Result:
def __init__(self, value, pos):
self.value = value
self.pos = pos
def __repr__(self):
return "Result(%s, %d)" % (self.value, self.pos)
class Parser:
def __add__(self, other):
return Concat(self, other)
def __mul__(self, other):
return Exp(self, o... |
"""
File:baginterface.py
Author:yeyuning
"""
class BagInterface(object):
"""Interface for all bag types"""
# Constructor
def __init__(self, SourceCollection=None):
"""Sets the initial state of self, which includes the contents of sourceCollection,
if it's present."""
... |
# Wraps DB-API 2.0 query results to provide a nice list and dictionary interface.
# Copyright (C) 2002 Dr. Conan C. Albrecht <conan_albrecht@byu.edu>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Softwa... |
class CleanUpTask:
def __init__(self, block_color, goal_room_color, block_name=None, goal_room_name=None):
'''
You can choose which attributes you would like to have represent the blocks and the rooms
'''
self.goal_room_name = goal_room_name
self.block_color = block_color
... |
class UnexpectedError(Exception):
"""Uneforseen Error."""
def __init__(self, message=None):
ErrorMsg = ("An Unexpected Error has occured.")
self.message = (ErrorMsg + " " + message) if message is not None else ErrorMsg
super().__init__(self.message)
class InvalidEncryptionMode(Exceptio... |
# Definition for binary tree with next pointer.
# class TreeLinkNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 22 18:27:25 2022
@author: victor
"""
def make_pizza(topping='bacon'):
"""Make a single-topping pizza."""
print("Have a " + topping + " pizza!")
make_pizza()
make_pizza('pepperoni') |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
head = ListNode(0)
result = head... |
class BottomReached(Exception):
pass
class TopReached(Exception):
pass
|
def validBraces(string):
open = ["(","[","{"]
close = [")","]","}"]
stack = []
for i in string:
if i in open:
stack.append(i)
else:
pos = close.index(i)
if len(stack) > 0 and open[pos] == stack[len(stack)-1]:
stack.pop()
e... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-10-15 20:03:00
# Description:
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
Medal = ["Gold Medal", "Silver Medal", "Bronze Medal"]
size = len(score)
res = [""] * size
my_map =... |
# -*- coding: utf-8 -*-
a = int(input("digite a primeira variavel: "))
b = int(input("digite a segunda variavel: "))
crescente = int(input("digite qualquer variavel: "))
if a < b:
print(a,b)
else:
crescente = b
b = a
a = crescente
print (a,b)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
stream = "{{{{{{{<\"\"!>,<!<'}'ui!!!>!!!>!<{!!!!!>>},{}},{<<'\"i!!a!{oe!>!!e!!!,<u!>},<a>,{<}{a\",!',!!!>},<u,!!!>!}<,'!o<!>,<>}},{<!!!>'\"i!!!>u!>uai!<o>,<i!!!>!>},<!>,<!>!>}o!>},<!>,<!>},<!>,<!!!>>}},{{{<!!,!!!>oo\"!!a>}},{{{{<i!!!!{,!!}>}},{{{<a>},{{<a!{!!>}}}},{<!>!!i'... |
class ViewHelpers:
def __init__(self, view):
self.view = view
def __iter__(self):
for sel in self.view.sel():
yield ViewHelper(self.view, sel)
class ViewHelper:
def __init__(self, view, sel):
self.view = view
self.sel = sel
def initial_xpos(self):
return self.view.text_to_layout(se... |
def common_elements(list1, list2):
"""common elements between two sorted arrays
Arguments:
list1 sorted array
list2 sorted array
Returns:
array with common elements
"""
result = []
visited_elements = []
for item in list1:
index = len(visited_elements)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.