content stringlengths 7 1.05M |
|---|
class DestinyPyError(Exception):
...
class APIError(DestinyPyError):
...
class InvalidJSONResponse(APIError):
...
class APIResponseError(APIError):
def __init__(self, errorCode: int) -> None:
super().__init__(f'API returned an error code {errorCode}')
self.errorCode = errorCode
c... |
"""__init__.py."""
__title__ = 'hammingambuj'
__version__ = '0.0.3'
__author__ = 'Ambuj Dubey' |
"""
@file
@brielf Shortcut to *sphinxext*.
"""
|
# -*- coding: utf-8 -*-
def fibonacci(ene):
a = 0
b = 1
contador = 1
fibo = 0
while contador < ene:
fibo = b + a
a = b
b = fibo
contador += 1
return fibo
print('fibonacci(5) = ' + str(fibonacci(5)))
print('fibonacci(10) = ' + str(fibonacci(10)))
print('fibonac... |
# model settings
_base_ = "swin_tiny_my_MM_supervised.py"
model = dict(type="Recognizer3DJoint", backbone=dict(generative=True, discriminative=True),
cls_head=dict(type='JointHead'))
|
'''
Given three arrays sorted in increasing order. Find the elements that are common in all three arrays.
Input:
A = {1, 5, 10, 20, 40, 80}
B = {6, 7, 20, 80, 100}
C = {3, 4, 15, 20, 30, 70, 80, 120}
Output: [20, 80]
Explanation: 20 and 80 are the only
common elements in A, B and C.
'''
def common_elements(arr1,ar... |
'''
Author: He,Yifan
Date: 2022-02-16 21:46:19
LastEditors: He,Yifan
LastEditTime: 2022-02-16 21:52:34
'''
__version__ = "0.0.0" |
name = "John Smith"
print("Hi, %s!" %name)
age = 40
print("%s is %d years old" % (name, age))
list = [1, 2, 3]
print("The list: %s", list)
data = ("John", "Smith", 1000.55)
format_string = "Hello, %s %s! Your balance is £%.0f"
print(format_string % data)
|
def countSumOfTwoRepresentations2(n, l, r):
noWays = 0
for x in range(l, r + 1):
if (n - x >= x) and (n - x <= r):
noWays += 1
return noWays
|
# 给定n个不同的整数,问这些数中有多少对整数,它们的值正好相差1。
def st140901():
n = int(input())
numbers=list(map(int,input().split()))
temp=0
for num in numbers:
if num+1 in numbers:temp+=1
print(temp)
if __name__ == '__main__':
st140901() |
__author__ = 'jkm4ca'
def greeting(msg):
print(msg)
|
"""Binary Tree level order traversal 2"""
class Node:
def __init__(self, id):
self.id = id
self.left = None
self.right = None
def __repr__(self):
return f'Node: {self.id}'
def build_bin_tree(root):
if not root:
return
queue = []
queue.append(root)
... |
x = int(input('Digite um valor: '))
y = int(input('Digite outro valor: '))
if x > y:
print (f'{x} é maior que {y}')
elif y > x:
print (f'{y} é maior que {x}')
else:
print ('Os dois valores são iguais') |
#-*- codeing = utf-8 -*-
#@Time : 2021-01-08 20:26
#@Author : 苏苏
#@File : 第三节课作业3.py
#@Software : PyCharm
#左旋转字符串
class Solution:
def reverseLeftWords(self,s:str,n:int) ->str:
res = ""
for i in range(n,len(s)):
res += s[i]
for i in range(n):
res +=s[i]
... |
#help(object)
#the object will be the built-in functions
#it returns the object details clearly
print(help('print'))
|
#
# PySNMP MIB module AI198CLC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AI198CLC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:15:57 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,... |
def lineplot(x_data, y_data, x_label="", y_label="", title=""):
# Create the plot object
_, ax = plt.subplots()
# Plot the best fit line, set the linewidth (lw), color and
# transparency (alpha) of the line
ax.plot(x_data, y_data, lw = 2, color = '#539caf', alpha = 1)
# Label the axes and prov... |
# https://app.codesignal.com/arcade/intro/level-2/2mxbGwLzvkTCKAJMG
def almostIncreasingSequence(sequence):
out_of_place = 0
for i in range(len(sequence) - 1):
if sequence[i] >= sequence[i + 1]:
out_of_place += 1
if i+2 < len(sequence) and sequence[i] >= sequence[i + 2]:
... |
"""OAuth 2.0 WSGI server middleware providing MyProxy certificates as access tokens
"""
__author__ = "R B Wilkinson"
__date__ = "12/12/11"
__copyright__ = "(C) 2011 Science and Technology Facilities Council"
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ = "Philip.Kershaw@stfc.ac.uk"
__revisi... |
class ContentIsEmpty(Exception):
def __str__(self) -> str:
return "No string was passed for content. You must add a text content to a DiscordResponse"
def __repr__(self) -> str:
return "No string was passed for content. You must add a text content to a DiscordResponse"
class InvalidDiscordRes... |
'''bytes and bytearray both do not supports slicing and repitition'''
# Convert a List to bytes
lst = [1,2,3,234] # bytes cannot be more than '255'
print(lst)
print(type(lst))
b = bytes(lst) # Converting a List to create bytes
print(b) # OutPut: b'\x01\x02\x03\xea'
print(type(b)) ... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Recursive approach using merge sort. Time O(nlogn). Space O(n) since it's recursive approach. To make it iterative, implement the merge sort iteratively
class Solution(object... |
vlr_casa = float(input('Qual o valor da casa? R$ '))
salario = float(input('Qual é o seu salário? R$ '))
anos = float(input('Em quantos anos você deseja financiar a casa? '))
parcela = vlr_casa/(anos*12)
print(f'Para pagar uma casa de R$ {vlr_casa:.2f} em {anos:.0f} anos, a prestação será de R$ {parcela:.2f}.')
if pa... |
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
sampleDict['location'] = sampleDict.pop('city')
print(sampleDict) |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
x, y = [], []
for i in s:
x.append(s.index(i))
for i in t:
y.append(t.index(i))
if x == y:
return True
return False
|
def is_paired(input_string):
stack = []
for char in input_string:
if char in "{([":
stack += [char]
elif(char == "}"):
if (stack[-1:] == ["{"]):
stack.pop()
else:
return False
elif(char == ")"):
if (stack[-1:] == ["("]):
stack.pop()
else:
return False
elif(char == "]"):
if (s... |
def test_top_tv_should_contain_100_entries(ia):
chart = ia.get_top250_tv()
assert len(chart) == 250
def test_top_tv_entries_should_have_rank(ia):
movies = ia.get_top250_tv()
for rank, movie in enumerate(movies):
assert movie['top tv 250 rank'] == rank + 1
def test_top_tv_entries_should_have_... |
# https://www.hearthpwn.com/news/8230-mysteries-of-the-phoenix-druid-and-hunter-puzzles
# Baloon_Merchant 0
# Armor_Vender 1
# Barrens_Blacksmith 2
# Darkshire_Alchemist 3
# Shady_dealer 4
# Master_Swordsmith 5
# Drakkari_Enchanter 6
# dalaran_mage 7
# bloodsail_corsair 8
# violet_apprentice 9
# silver_hand_knight 10
... |
# 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, software
# distributed under t... |
case_1 = """somevar = 4
anotherVar = 5
def function(a, b):
some function
some very small function
which will
be considered good;
function(4, 5)"""
case_2 = """somevar = 4
anotherVar = 5
def func... |
class Solution:
def largestPerimeter(self, A: List[int]) -> int:
perimeter = 0
A.sort(reverse=True)
for k in range(len(A)-2):
if self.fun(A[k], A[k+1], A[k+2]):
perimeter = max(perimeter, A[k] + A[k+1] + A[k+2])
return perimeter
return peri... |
'''
It is important to have some understanding of what commonly-used functions are doing under the hood. Though you may already know how to compute variances, this is a beginner course that does not assume so. In this exercise, we will explicitly compute the variance of the petal length of Iris veriscolor using the equ... |
class Singleton:
ans = None
@staticmethod
def instance():
if '_instance' not in Singleton.__dict__:
Singleton._instance = Singleton()
return Singleton._instance
s1 = Singleton.instance()
s2 = Singleton.instance()
s1.ans = 10
assert s1 is s2
assert s1.ans == s2.ans
print("Test Passed")
|
"""
Created on Fri Nov 12 12:28:01 2021
@author: DW
"""
class ORR_Tafel:
"""Class for calculating Tafel plots of the ORR scans"""
def __init__():
pass
def export(
ORR_dest_dir,
rTFxy,
i,
TFll,
dest_file,
TFfit,
): # noqa : F821
TafelD... |
class Game:
def __init__(self, id):
# initially player 1's move is false
self.p1Went = False
# initially player 2's move is false
self.p2Went = False
self.ready = False
# current game's id
self.id = id
# two players move, initially none[player1's move,... |
########################## THE TOON LAND PROJECT ##########################
# Filename: _BarkingBoulevard.py
# Created by: Cody/Fd Green Cat Fd (February 19th, 2013)
####
# Description:
#
# The Barking Boulevard added Python implementation.
####
filepath = __filebase__ + '/toonland/playground/funnyfarm/maps/%s'
sidewa... |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = None
if isinstance(data, list) and len(data) > 0:
self.data = data.pop(0)
for item in data:
self.AddNode(item)
else:
self.data = data
... |
"""
Copyright 2020 The Secure, Reliable, and Intelligent Systems Lab, ETH Zurich
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 appl... |
total_amount = float(input('Enter Groupon payment amount: '))
tickets = round((total_amount * 0.5875), 2) # 58.75% for ticket sales
concessions = round((total_amount * 0.4125), 2) # 41.25% for concession sales
print()
print(f'GL 4005: {tickets}')
print(f'GL 4200: {concessions}')
input('Press enter to exit: ') # ke... |
# ECE 486 Project
# Ali Saad, Disha Shetty, Pooja
# Mips Simulation
# Professor Zeshan Chishti
# Open memory image file and read it(take it's inputs)
# Need to change the numbers in the file from Hex to binary
# Then parse it to get Rs, Rt, Rd intaking the correct numbers
# To run the correct operation ... |
"""
utilapi.
A Cloud Util api.
"""
__version__ = "0.1.0"
__author__ = 'Kishore'
__credits__ = 'Tealpod' |
#!/bin/python3
# -*- coding: utf-8 -*-
"""
Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in
the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
"""
def cou... |
#--- Exercicio 1 - Input, Estrutura de decisão e operações matemáticas
#--- Crie um programa que leia dois números inteiros
#--- Realize as 4 operações matemáticas básicas com os números lidos
#--- Imprima os resultados das operações
#--- Informe qual número é maior ou se os dois são iguais
a = int(input('Digite o ... |
start = int(input('Choose the start of the Aritimetic Progression: '))
rate = int(input('Choose the rate of the Aritimetic Progression: '))
cont = 10
while cont != 0:
print(start)
start = start + rate
cont = cont - 1
|
# This program is about Quick Sort
# an advanced version of Bubble Sort
# Time complexity is O(nlog(n))
# Version 1
class SQList:
def __init__(self, lis=None):
self.r = lis
# define a method to exchange elements
def swap(self, i, j):
temp = self.r[i]
self.r[i] = self.r[j]
... |
"""
Description: Functions that handle country codes and country names.
"""
__author__ = ["Karolina Pantazatou"]
__credits__ = "ICOS Carbon Portal"
__license__ = "GPL-3.0"
__version__ = "0.1.0"
__maintainer__ = "ICOS Carbon Portal, elaborated products team"
__email__ = ['info@icos-cp.eu', ... |
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
SNAKE_TO_CAMEL_CASE_TABLE = {
"api_key": "apiKey",
"api_version": "apiVersion",
"binding_from": "bindingFrom",
"config_map_key_ref": "configMapKeyRef... |
'''
File: 1038.py
File Created: 2021-01-12 13:43:24 -08:00
Author: Taowyoo (caoyxsh@outlook.com)
Brief: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
-----
Last Modified: 2021-01-12 13:43:57 -08:00
Modified By: Taowyoo (caoyxsh@outlook.com>)
-----
Copyright 2020 - 2021
'''
# Definition for a ... |
def fibonacci_iterative(n):
a = 0
b = 1
if n == 0:
return 0
if n == 1:
return 1
for i in range(0, n - 1):
c = a + b
a = b
b = c
return b
for i in range(0, 20):
print(fibonacci_iterative(i))
|
#
# PySNMP MIB module PW-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PW-STD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:30:09 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:... |
numbers=[0, 1, 153, 370, 371, 407]
def is_sum_of_cubes(s):
res=[]
temp=""
for i in s:
if i.isdigit():
temp+=i
else:
res.extend([temp[i:i+3] for i in range(0, len(temp), 3) if int(temp[i:i+3]) in numbers])
temp=""
res.extend([temp[i:i+3] for i in range(... |
###############################################
# Main UI component sizes
###############################################
COLS = 6
ROWS = 6
CELL_WIDTH = 50
CELL_HEIGHT = CELL_WIDTH
TOTAL_DICE = 7
WINDOW_WIDTH = CELL_WIDTH * TOTAL_DICE
ROLL_DICE_LABEL_WIDTH = WINDOW_WIDTH
ROLL_DICE_LABEL_HEIGHT = CELL_HEIGHT
DICE_... |
class FrontMiddleBackQueue:
def __init__(self):
self.f = deque()
self.b = deque()
def pushFront(self, val: int) -> None:
self.f.appendleft(val)
self._balance()
def pushMiddle(self, val: int) -> None:
if len(self.f) > len(self.b):
self.b.appendleft(self.... |
class Contact:
def __init__(self, firstname, middlename, address, mobile, lastname, nickname, title, company, home_phone_number,
work_phone_number, fax_number, email_1,
email_2, email_3, bday, bmonth, byear, aday, amonth, ayear, address_2, phone_2, notes):
self.firstname =... |
n = int(input())
res = 1
f = 1
for i in range(1, n + 1):
f *= i
res += 1 / f
print(res) |
""" Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último
nome separadamente.
Ex: Fulana de souza melo
primeiro: Fulana
ultimo: melo
"""
nome = str(input('Digite seu nome completo: ')).strip()
p = nome.split()
print('O primeiro nome é \033[1;31m{}\033[m e o ultimo nome é \0... |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def print_tree(self):
if self.left:
self.left.print_tree()
print(self.data),
if self.right:
self.right.print_tree()
def min_num(node):
current... |
class EdgeData(object):
"""Class used to store edge settings.
Attributes
----------
type: str
Shape of edge: 'Triangular', 'Rectangular', 'Custom, 'User Q'
distance_m: float
Distance to shore, in m.
cust_coef: float
Custom coefficient provided by user.
number_ensembl... |
# -*- coding: utf-8 -*-
"""
author :: @adityac8
"""
## SET PATHS ACCORDING TO WHERE DATA SHOULD BE STORED
# This is where all audio files reside and features will be extracted
audio_ftr_path='D:/workspace/aditya_akshita/temp/dcase_data'
# We now tell the paths for audio, features and texts.
wav_dev_fd = audio_ftr_p... |
# pylint: skip-file
# flake8: noqa
def main():
'''
ansible oc module for project
'''
module = AnsibleModule(
argument_spec=dict(
kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
state=dict(default='present', type='str',
... |
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if root.left is None and root.right is None:
return root.val == sum
new_sum = sum - root.val
return self.hasPathSum(root.left, new_sum) or self.hasPathSum(root.ri... |
n1 = float(input('\nPRIMEIRO VALOR: '))
n2 = float(input('SEGUNDO VALOR: '))
print('\nOQUE DESEJA FAZER?')
menu = int(input('[ 1 ] - SOMAR\n[ 2 ] - MULTIPLICAR\n[ 3 ] - SUBTRAIR\n[ 4 ] - DIVIDIR\n[ 5 ] - MAIOR OU MENOR\n[ 6 ] - NOVOS NÚMEROS\n[ 7 ] - SAIR\n-> QUAL SUA OPÇÃO: '))
while menu != 7:
if menu == 1:
... |
def diagonal_sum(n):
"""
Finds the diagonal sum of a spiral of n by n
An example:
>>> diagonal_sum(5)
101
:param n: Number of rows and columns of the grid
:type n int
:return: Total of the numbers along the diagonal
:rtype: int
"""
count = 1
last = 1
total = last
... |
# O(P + S)
class Solution(object):
def findAnagrams(self, s, p):
p_count, cur_count, result = [0]*26, [0]*26, []
for c in p:
p_count[self._char2ind(c)] += 1
p_len = len(p)
a_start = 0
for i, c in enumerate(s):
c_ind = self._char2ind(c)
... |
model_raw_data = [
{
"Field": "Description",
"model_id": "",
"host_strain": "",
"host_strain_full": "",
"engraftment_site": "",
"engraftment_type": "",
"sample_type": "",
"sample_state": "",
"passage_number": "",
"publications": ""
... |
def convert_into_24hr(time_12hr):
if time_12hr[-2:] == "AM":
remove_am = time_12hr.replace('AM', '')
if time_12hr[:2] == "12":
x = remove_am.replace('12', '00')
return x
return remove_am
elif time_12hr[-2:] == "PM":
remove_pm = time_12hr.replace('PM', ''... |
#https://www.lintcode.com/problem/wildcard-matching/description?_from=ladder&&fromId=1
class Solution:
"""
@param s: A string
@param p: A string includes "?" and "*"
@return: is Match?
"""
def isMatch(self, s, p):
# write your code here
memo = {}
return self.dfs(s, 0, p... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 2 00:59:53 2017
@author: azkei
"""
# |
#Ex.14
num = int(input())
if num >= 0:
res = pow(num, 1/2)
else:
res = pow(num, 2)
print(res)
|
# https://github.com/EricCharnesky/CIS2001-Winter2022/blob/main/Week5-StacksAndQueues/main.py
class Stack:
# O(1)
def __init__(self):
self._data = []
# O(1)
def push(self, item):
self._data.append(item)
# O(1)
def pop(self):
return self._data.pop()
# O(1)
de... |
class Hello:
def __init__(self):
self._message = 'Hello world!'
def get_message(self):
return self._message
def main(self):
message = self.get_message()
print(message)
Hello().main()
|
"""Heuristic demonstrating conversion of the PhoenixZIPReport from Siemens.
It only cares about converting a series with have PhoenixZIPReport in their
series_description and outputs **only to sourcedata**.
"""
def create_key(template, outtype=('nii.gz',), annotation_classes=None):
if template is None or not tem... |
"""
Author: Tong
Time: --2021
"""
dataset_map = {"seq-clinc150": "c", "seq-maven": "m", "seq-webred": "w"}
def generate_cmd():
cmd_list = []
info_list = []
for dataset in ["seq-clinc150"]:
for ptm in ["bert"]:
info = "{description}_{var}_{var1}_{var2}".format(description="e10",... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
__author__ = 'wangqiang'
'''
选择排序
'''
def selection_sort(lst):
if not lst or len(lst) == 1:
return lst
for i in range(0, len(lst) - 1):
k = i
# 每次子循环,都从未排序序列中选择最小的值
for j in range(i + 1, len(lst)):
if lst[j] < lst[k]:
... |
"""pyavreceiver errors."""
class AVReceiverError(Exception):
"""Base class for library errors."""
class AVReceiverInvalidArgumentError(AVReceiverError):
"""Invalid argument error."""
class AVReceiverIncompatibleDeviceError(AVReceiverError):
"""Invalid argument error."""
class QosTooHigh(AVReceiverEr... |
class Solution:
def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
n = len(indexes)
changes = []
for i in range(n):
idx = indexes[i]
source = sources[i]
target = targets[i]
m = len(source)
... |
#proof of concept
def set_logger(custom_log):
set_logger.__custom_logger = custom_log
def log(text):
set_logger.__custom_logger.log(text)
|
my_list = []
n = int(input('Введите число: '))
for a in range(1, n+1):
if a % 2 != 0:
my_list.append(a)
print(my_list)
|
# Semigroup + identity property = Monoid
# The number 0 works well as an identity element for addition
print(2 + 0 == 2)
# Monoids don't have to be numbers |
cx_db = 'plocal://localhost:2424/na_server'
cx_version = 'wild_type'
initial_drop = False
model_version = "Givon17"
|
deps = [
"pip", # install dependencies
"pyglet", # rendering engine
"pyjsparser", # javascript parser
]
|
for tt in range(int(input())):
n,m,k = map(int,input().split())
k1 = m-1 + m*(n-1)
if k1 == k:
print('YES')
else:
print('NO') |
'''Programe que lê um inteiro positivo n e imprime os n primeiros inteiros positivos.
'''
print("Gerador do n primeiros números ímpares positivos\n")
'''
# leia o valor de n
n = int(input("Digite o valor de n: "))
# contador de ímpares impressos
i = 0
# imprima os n primeiros impares, um por linha
while i < ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_stack_n.py
# Create Date: 2015-07-26 10:53:38
# Usage: AC_stack_n.py
# Descripton:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = ... |
def to_digits(n):
list = []
while n:
list.append(n%10)
n //= 10
list.reverse()
return list
def main():
print(to_digits(123))
# Expected output : [1, 2, 3]
print(to_digits(99999))
# Expected output : [9, 9, 9, 9, 9]
print(to_digits(123023))
# Expected output : [1, 2, 3, 0, 2, 3]
if __name__ == '__... |
# -*- coding: utf-8 -*-
# Copyright © 2018 Sergei Kuznetsov. All rights reserved.
def semiai_command(director):
money = director.company.money
price = director.company.world.price
product_amount = director.company.goody
credit = director.company.credit
credit_sum = director.parameters['credit_sum... |
#
# PySNMP MIB module LM-SENSORS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LM-SENSORS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:58:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
"""
link: https://leetcode.com/problems/third-maximum-number
problem: 求数组第三大数,要求时间 O(n)
solution: 遍历记录前三值
"""
class Solution:
def thirdMax(self, nums: List[int]) -> int:
m1, m2, m3 = float("-inf"), float("-inf"), float("-inf")
for x in nums:
if x > m1:
m1, m2, m3 = x... |
# https://cses.fi/problemset/task/1618
def zeros(n):
return 0 if n < 5 else zeros(n // 5) + n // 5
print(zeros(int(input())))
|
class Solution:
"""
@param ages:
@return: nothing
"""
def numFriendRequests(self, ages):
counts = [0] * 121
presum = [0] * 121
for age in ages:
counts[age] += 1
for i in range(1, 121):
presum[i] = presum[i - 1] + counts[i]
... |
"""
test_tui_tools
--------------
Test module for testint TUI_tools
"""
#check_quest_info
#automatic_questioner
#get_default
#get_default3
#automatic_questioner3
#
#
#selection_list_options
#selection_options
#confirmation_question
#simple_input
#
#general_questioner
def test():
pass
|
"""Constants for YT-MX0404V2 component."""
DOMAIN = "yt_mx0404v2"
DEFAULT_NAME = "YT-MX0404V2"
DEFAULT_PORT = 23
DEFAULT_RECONNECT_INTERVAL = 10
DEFAULT_POLLING_INTERVAL = 3
CONNECTION_TIMEOUT = 10
CONF_INPUTS1 = "input1"
CONF_INPUTS2 = "input2"
CONF_INPUTS3 = "input3"
CONF_INPUTS4 = "input4"
DEFAULT_INPUTS1 = "I... |
jogadores = {}
geral = []
gols = []
print('='*70)
print(' ESTATÍSTICA DE JOGADOR')
print(f'='*70)
while True:
jogadores['nome'] = str(input('Qual o nome do jogador: ')).strip().title()
partidas = int(input(f'Quantas partidas {jogadores["nome"]} jogou? '))
if partidas != 0:
... |
# Variables
pierre = ['P', 'PIERRE', 'PIERE', 'PIERRES']
feuille = ['F', 'FEUILLE', 'FEUILL', 'FEUILLES']
ciseaux = ['C', 'CISEAUX', 'CISEAU', 'CISEAUS']
sc_o = 0
sc_j = 0
esp = "\n"
jouer = 1
oui = ['OUI', 'YES', 'YEP', 'UI', 'OIU']
non = ['NON', 'NO', 'NOPE', 'NNO', 'NONN']
partie = 1
# https://en.wikipedia.org/wiki/... |
#
# @lc app=leetcode id=405 lang=python
#
# [405] Convert a Number to Hexadecimal
#
# https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/
#
# algorithms
# Easy (41.68%)
# Total Accepted: 45.5K
# Total Submissions: 108.9K
# Testcase Example: '26'
#
#
# Given an integer, write an algorithm to ... |
#Title:-DiameterOfBinaryTree
#Explanation:-https://www.youtube.com/watch?v=v8U4Wi6ZwKE&list=PLmpbOouoNZaP5M275obyC44n3I3nCFk8Q&index=12
#Author : Tanay Chauli
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Function to find height of a tree
def height(root... |
class BallastControl:
def __init__(self, mass: float, center_of_mass: tuple, center_of_buoyancy: tuple):
# initialize syringe controls
self.constant_mass = mass
self.constant_COM = center_of_mass
self.constant_COB = center_of_buoyancy
|
# 6 из 36 + Результаты тиража + предыдущий тираж к примеру 1600
def test_6x36_results_draw_previous_draw(app):
app.ResultAndPrizes.open_page_results_and_prizes()
app.ResultAndPrizes.click_game_6x36()
app.ResultAndPrizes.click_the_results_of_the_draw()
app.ResultAndPrizes.select_draw_1600_in_draw_numb... |
#
# PySNMP MIB module DRAFT-MSDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DRAFT-MSDP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:54:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
# Simon McLain 208-03-11 Phython Tutorial 4.7.2
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.