content stringlengths 7 1.05M |
|---|
def insertion_sort(lst):
"""
Sorts list using insertion sort
:param lst: list of unsorted elements
:return comp: number of comparisons
"""
comp = 0
for i in range(1, len(lst)):
key = lst[i]
j = i - 1
cur_comp = 0
while j >= 0 and key < lst[j]:
lst[... |
# Financial events the contract logs
Transfer: __log__({_from: indexed(address), _to: indexed(address), _value: currency_value})
Buy: __log__({_buyer: indexed(address), _buy_order: currency_value})
Sell: __log__({_seller: indexed(address), _sell_order: currency_value})
Pay: __log__({_vendor: indexed(address), _amount: ... |
n = int(input("Enter the number of of rows: "))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end="")
print() |
def verify_format(_, res):
return res
def format_index(body): # pragma: no cover
"""Format index data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
result = {
'id': body['id'].split('/', 1)[-1],
'fields': body['fields']
}
... |
# exc. 9.1.2
def file_options(file_name, task):
if task == 'sort':
edit_file = open(file_name, 'r')
file_list = edit_file.read().split(' ')
print(sorted(file_list))
edit_file.close()
elif task == 'rev':
edit_file = open(file_name, 'r')
for line in edit_file:
print(line[::-1])
edit_file.... |
# Singly Linked List
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.valu... |
# -*- coding: utf-8 -*-
"""Top-level package for pyqmc."""
__author__ = """Maxime Godin"""
__email__ = 'maximegodin@polytechnique.org'
__version__ = '0.1.0'
|
# Fibonacci Sequence: 0 1 1 2 3 5 8 13 ...
def fibonacci(num):
if num == 1:
return 0
if num == 2:
return 1
return fibonacci(num-1) + fibonacci(num-2)
print(fibonacci(1))
print(fibonacci(2))
print(fibonacci(3))
print(fibonacci(4))
print(fibonacci(5))
|
cities = [
'Sao Paulo',
'Rio de Janeiro',
'Salvador',
'Fortaleza',
'Belo Horizonte',
'Brasilia',
'Curitiba',
'Manaus',
'Recife',
'Belem',
'Porto Alegre',
'Goiania',
'Guarulhos',
'Campinas',
'Nova Iguacu',
'Maceio',
'Sao Luis',
'Duque de Caxias',
... |
##############class#####################
class Board:
""" This class defines the board object used in the game"""
##############constructeur##################
def __init__(self):
#self.boardTab = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
self.boardDic = {"A1":[0,"A2"],"A2":[0,"A3"],"A3":[0,"A4"... |
'''
Given a m x n grid filled with non-negative numbers,
find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Exp... |
__all__ = ('BaseIDGenerationStrategy', )
class BaseIDGenerationStrategy:
def get_next_id(self, instance):
raise NotImplementedError
|
# coding=utf-8
n, m = map(int, input().split())
s = [ list(str(input())) for _ in range(n) ]
add = [[1, 0],[-1, 0],[0, 1],[0, -1]]
ans = 'Yes'
for i in range(n):
for j in range(m):
if s[i][j] == '.': continue
mid = False
for k in range(4):
ii = i + add[k][0]
jj = j ... |
orbits = dict()
with open('input.txt') as f:
for line in f:
center, satellite = line.strip().split(")")
orbits[satellite] = center
def calc_distance_to_com(orbs, sat):
dist = 1
cent = orbs[sat]
while cent != "COM":
cent = orbs[cent]
dist += 1
return dist
def find_ro... |
# The diameter of a tree (sometimes called the width)
# is the number of nodes on the longest path between
# two end nodes.
# The diameter of a tree T is the largest of the following quantities:
# * the diameter of T’s left subtree
# * the diameter of T’s right subtree
# * the longest path between leaves that goes ... |
class ParseError(Exception) :
"""Super class for exception classes used in Parsers package.
"""
def __init__(self, file='', msg=''):
self.file = str(file)
self.msg = str(msg)
def __str__(self):
if self.msg :
s = self.msg + ': '
else :
s = ''
... |
# Commonly used java test dependencies
def java_test_repositories():
native.maven_jar(
name = "junit",
artifact = "junit:junit:4.12",
sha1 = "2973d150c0dc1fefe998f834810d68f278ea58ec",
)
native.maven_jar(
name = "hamcrest_core",
artifact = "org.hamcrest:hamcrest-core:1.3",
sha1 = "42a25dc... |
#
# PySNMP MIB module CISCO-VLAN-BRIDGING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-BRIDGING-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
def run():
# nombre = input('Escribe tu nombre: ')
# for letra in nombre:
# print(letra)
frase = input('Escribe una frase: ')
for c in frase:
print(c.upper())
if __name__ == '__main__':
run()
|
def choose6(n,k): #computes nCk, the number of combinations n choose k
result = 1
for i in range(n):
result*=(i+1)
for i in range(k):
result/=(i+1)
for i in range(n-k):
result/=(i+1)
return result |
class ResultSet(list):
"""A list like object that holds results from a Unsplash API query."""
class Model(object):
def __init__(self, **kwargs):
self._repr_values = ["id"]
@classmethod
def parse(cls, data):
"""Parse a JSON object into a model instance."""
raise NotImplement... |
class Rect(object):
def __init__(self, cx, cy, width, height, confidence):
self.cx = cx
self.cy = cy
self.width = width
self.height = height
self.confidence = confidence
self.true_confidence = confidence
def overlaps(self, other):
if abs(self.cx - other.c... |
class Transformer:
def __init__(self, name, allegiance, strength, intelligence, speed, endurance, rank, courage, firepower, skill):
"""Initialization function for a Transformer."""
self.name = name
self.allegiance = allegiance
self.strength = strength
self.intelligence = inte... |
def main(request, response):
headers = [("Content-Type", "text/plain")]
command = request.GET.first("cmd").lower();
test_id = request.GET.first("id")
header = request.GET.first("header")
if command == "put":
request.server.stash.put(test_id, request.headers.get(header, ""))
elif command... |
n, k = map(int, input().split())
A = list(map(int, input().split()))
step = 0
cnt = 0
# robot 위치
robot = []
while True:
step += 1
# 벨트 한 칸 이동
A = [A[-1]] + A[:-1]
for i in range(len(robot)):
robot[i] += 1
# 로봇 내리는 위치 확인
if (n - 1) in robot:
robot.remove(n - 1)
... |
no_steps = 359
pos = 0
lst = [0]
for x in range(1, 50000001):
pos += no_steps
pos %= len(lst)
lst.insert(pos+1, x)
pos += 1
print(lst[lst.index(0)+1])
|
#!/usr/bin/env python
# AUTHOR: jo
# DATE: 2019-08-12
# DESCRIPTION: Tuse homework assignment #1.
def partitionOnZeroSumAndMax(row):
# Ex. Passing in [1,1,0,1] returns [2,0,1].
# max([2,0,1]) -> 2
localSums = [0]
for val in row:
if val != 0:
localSums.append(localSums.pop() + val)
... |
# -*- coding: utf-8 -*-
"""
@contact: lishulong.never@gmail.com
@time: 2018/5/8 上午10:17
"""
|
#!/usr/bin/env python2
def main():
n = input('')
for i in range(0, n):
rows = input('')
matrix = []
for j in range(0, rows):
matrix.append([int(x) for x in raw_input('').split()])
print(weight(matrix, 0, 0))
def weight(matrix, i, j):
#print('weight called with',... |
"""This module consist of API Groups.
All the REST APIs are divided into several groups
1) Access
2) General
3) Organization
4) Service
5) Service Action
Each group has a set of APIs with their own models and schemas.
"""
|
codon_protein = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCG": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UAU": "Tyrosine",
"UAC": "Tyrosine",
"UGU": "Cysteine",
"UGC": "Cysteine",
... |
# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other
# Hatchet Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
__version_info__ = ("2022", "1", "0")
__version__ = ".".join(__version_info__)
|
def solution(s):
res = ''
if s == s.lower():
res += s
return res
for i in range(len(s)):
if s[i] == ' ':
continue
elif s[i] == s[i].upper():
res += ' ' + s[i]
else:
res += s[i]
return res
def te... |
# Functions (Funções)
# DRY - Don't repeat yourself
# Parametro --> Argumento
# Default = Aquele que você define o valor no parametro
# Non-Default = Aquele que você não define o valor do parametro
'''
No exemplo abaixo NOME é o Non-Default, pq o valor dele ainda
será atribuido posteriormente podendo ser trocado a atr... |
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
s, b = sorted([p.val, q.val])
while not s <= root.val <= b:
# Keep searching since ro... |
n = int(input())
nsum = 0
for i in range(1, n+1):
nsum += i
if nsum == 1:
print('BOWWOW')
elif nsum <= 3:
print('WANWAN')
else:
for i in range(2, n+1):
if n % i == 0:
print('BOWWOW')
break
else:
print('WANWAN')
|
#!/usr/bin/env python3
def find_array_intersection(A, B):
ai = 0
bi = 0
ret = []
while ai < len(A) and bi < len(B):
if A[ai] < B[bi]:
ai += 1
elif A[ai] > B[bi]:
bi += 1
else:
ret.append(A[ai])
v = A[ai]
while ai < len(... |
"""
--- Day 18: Duet ---
You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the instructions mean on your own.
It seems like... |
v = float(input('Valor da casa a ser comprada: R$'))
s = float(input('Salário do comprador: R$'))
qa = float(input('Quantos anos irá pagar: '))
print('Para pagar uma casa de R${:.2f} em {:.0f} anos'.format(v, qa), end='')
print(' a prestação sera de R${:.2f}'.format(v / (qa * 12)))
if v / (qa* 12) >= s * 0.3:
prin... |
def do_stuff(fn, lhs, rhs):
return fn(lhs, rhs)
def add(lhs, rhs):
return lhs + rhs
def multiply(lhs, rhs):
return lhs * rhs
def exponent(lhs, rhs):
return lhs ** rhs
print(do_stuff(add, 2, 3))
print(do_stuff(multiply, 2, 3))
print(do_stuff(exponent, 2, 3))
|
# A tuple operates like a list but it's initial values can't be modified
# Tuples are declared using the ()
# Use case examples of using Tuple - Dates of the week, Months of the Year, Hours of the clock
# we can create a tuple like this...
monthsOfTheYear = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug... |
tot=0
n=int(input('\033[mDigite um numero: '))
for c in range(1, n+1):
if n%c==0:
print('\033[34m',end='')
tot+=1
else:
print('\033[31m',end='')
print('{} '.format(c), end='')
print(f'\033[m\nO numero {n} foi divisível {tot} vezes') |
# class Solution:
# def lengthOfLIS(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# O(n^2) complexity
# if not nums:
# return 0
# n = len(nums)
# aux = [1] * n
# for i in range(n):
# for j in range(i):
... |
class Solution:
def updateMatrix(self, matrix: list) -> list:
# m, n = len(matrix), len(matrix[0])
# SomeZerosInds, SomeOnesInds = [], [] #01边界的0的索引 和 被1包围的1的索引
# ans = [ [0] * len(matrix[0]) for _ in range(len(matrix)) ]
# for p in range(len(matrix)):
# for q in range(le... |
def solve(array):
even = []
odd = []
for i in range(len(array)):
if array[i] % 2 == 0:
even.append(i)
else:
odd.append(i)
if even:
return f"1\n{even[-1] + 1}"
if len(odd) > 1:
return f"2\n{odd[-1] + 1} {odd[-2] + 1}"
else:
retur... |
array = [5, 3, 2, 1, 6, 8, 7, 4]
def merge_sort(array):
if len(array) <= 1:
return array
mid = len(array) //2
left_array = array[:mid]
right_array = array[mid:]
print(left_array)
print(right_array)
return merge(merge_sort(left_array), merge_sort(right_array))
def merge(array1, ar... |
# These constants can be set by the external UI-layer process, don't change them manually
is_ui_process = False
execution_id = ''
task_id = ''
executable_name = 'insomniac'
do_location_permission_dialog_checks = True # no need in these checks if location permission is denied beforehand
def callback(profile_name):
... |
defaults = '''
const vec4 light = vec4(4.0, 3.0, 10.0, 0.0);
const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0);
const mat4 mvp = mat4(
-0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972,
1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057617... |
# UTF-8
#
# For more details about fixed file info 'ffi' see:
# http://msdn.microsoft.com/en-us/library/ms646997.aspx
VSVersionInfo(
ffi=FixedFileInfo(
# filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4)
# Set not needed items to zero 0.
filevers=(0, 5, 0, 0),
prodvers=(0, 5... |
class OutOfService(Exception):
def __init__(self,Note:str=""):
pass
class InternalError(Exception):
def __init__(self,Note:str=""):
pass
class NothingFoundError(Exception):
def __init__(self,Note:str=""):
pass
class DummyError(Exception):
def __init__(self,Note:str=""):... |
"""Cayley 2020, Problem 20"""
def is_divisible(n, d):
return (n % d) == 0
def solutions():
a = range(1, 101)
b = range(101, 206)
return [(m, n) for m in a for n in b if is_divisible(3**m + 7**n, 10)]
s = solutions()
a = len(s)
print(f'Answer = {a}') |
a = [1, 4, 5, 7, 19, 24]
b = [4, 6, 7, 18, 24, 134]
i = 0
j = 0
ans = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
ans.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
print(*ans)
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue(object):
def __init__(self, size):
self.queue = []
self.size = size
def enqueue(self, value):
'''This function adds an value to the rear end of the queue '''
if(self.isFull() !... |
# -*- coding: utf-8 -*-
"""Order related definitions."""
definitions = {
"OrderType": {
"MARKET": "A Market Order",
"LIMIT": "A Limit Order",
"STOP": "A Stop Order",
"MARKET_IF_TOUCHED": "A Market-if-touched Order",
"TAKE_PROFIT": "A Take Profit Order",
"STOP_LOSS": ... |
bill_board = list(map(int, input().split()))
tarp = list(map(int, input().split()))
xOverlap = max(min(bill_board[2], tarp[2]) - max(bill_board[0], tarp[0]), 0)
yOverlap = max(min(bill_board[3], tarp[3]) - max(bill_board[1], tarp[1]), 0)
if xOverlap == 0 or yOverlap == 0:
print((bill_board[2] - bill_boar... |
numero = int(input('Digite um numero'))
fatorial = numero
contador = 1
while (numero - contador) > 1:
fatorial = fatorial * (numero-contador)
contador +=1
print('O fatorial de ', numero,'é', fatorial) |
"""
--- Day 21: RPG Simulator 20XX ---
Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what
equipment to buy at the shop. He hands you the controller.
In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes firs... |
'''
Edges in a block diagram computational graph. The edges themselves don't have direction,
but the ports that they attach to may.
'''
class WireConnection:
pass
class NamedConnection(WireConnection):
def __init__(self, target_uid: int, target_port: str):
self.target_uid = target_uid
self.t... |
with open('model_translations_bpe_dropout.txt', 'r') as f:
data = f.read().split("\n")
with open('model_translations_bpe_dropout_decoded.txt', 'w') as f:
for sentence in data:
word_list = sentence.split(" ")
detokenized = ''.join(word_list).replace('▁', ' ').strip()
... |
RADIO_ENABLED = ":white_check_mark: **Radio enabled**"
RADIO_DISABLED = ":x: **Radio disabled**"
SKIPPED = ":fast_forward: **Skipped** :thumbsup:"
NO_MATCH = ":x: **No matches**"
SEARCHING = ":trumpet: **Searching** :mag_right:"
PAUSE = "**Paused** :pause_button:"
STOP = "**Stopped** :stop_button:"
LOOP_ENABLED =... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# List of contributors:
# Jordi Esteve <jesteve@zikzakmedia.com>
# Ignacio Ibeas <ignacio@acysos.com>
# Dpto. Consultoría Grupo Opentia <consultoria@opentia.es>
# Pedro M. Baeza <pedro.baeza@tecnativa.com>
# Carlos Liéba... |
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('Erro: Por favor, digite um numero valido')
continue
except (KeyboardInterrupt):
print('Entrada interromepida pelo usuario')
return 0
else:
... |
#leia um numero inteiro e
#imprima a soma do sucessor de seu triplo com
#o antecessor de seu dobro
num=int(input("Informe um numero: "))
valor=((num*3)+1)+((num*2)-1)
print(f"A soma do sucessor de seu triplo com o antecessor de seu dobro eh {valor}") |
"""
[Weekly #22] Machine Learning
https://www.reddit.com/r/dailyprogrammer/comments/3206mk/weekly_22_machine_learning/
# [](#WeeklyIcon) Asimov would be proud!
[Machine learning](http://en.wikipedia.org/wiki/Machine_learning) is a diverse field spanning from optimization and
data classification, to computer vision an... |
input = open('input.txt', 'r').read().split("\n")
depths = list(map(lambda s: int(s), input))
increases = 0;
for i in range(1, len(depths)):
if depths[i-2] + depths[i-1] + depths[i] > depths[i-3] + depths[i-2] + depths[i-1]:
increases += 1
print(increases) |
#!/usr/bin/env python
#
# Copyright 2019 DFKI GmbH.
#
# 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, merg... |
"""
Support for forex pip calculations.
Resources:
https://forums.babypips.com/t/having-problem-finding-number-of-pips/111993/2
https://stackoverflow.com/questions/48038949/find-pips-value-3-to-5-digits-forex-pricing-calculation
https://www.luckscout.com/how-to-measure-the-number-of-pips-of-a-price-move-on-mt4/
"""
... |
class NasmPackage (Package):
def __init__ (self):
Package.__init__ (self, 'nasm', '2.10.07', sources = [
'http://www.nasm.us/pub/nasm/releasebuilds/2.10.07/nasm-%{version}.tar.xz'
])
NasmPackage ()
|
'''
Description:
Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree ... |
# 所有对话信息
level_chats = (((1, "Hello there new challenger!"),
(1, "Welcome to Snake Quest, where you will face multiple challenges!"),
(2, "What's the prize?"),
(1, "The prize is endless food!"),
(2, "yeye how do I start"),
(1, "But first... |
number_of_drugs = 5
max_id = 1<<5
string_length = len("{0:#b}".format(max_id-1)) -2
EC50_for_0 = 0.75
EC50_for_1 = 1.3
f = lambda x: EC50_for_0 if x=='0' else EC50_for_1
print("[\n", end="")
for x in range(0,max_id):
gene_string = ("{0:0"+str(string_length)+"b}").format(x)
ec50 = list(map(f, list(gene_strin... |
# 30.python代码实现删除一个list里面的重复元素
a = [1,2,3,4,5,6,5,4,3,2,0]
b = list(set(a))
print(b)
# 或者可以考虑创建一个新的 空列表,然后遍历原列表,不在新列表中的进行append |
frutas = {"maça","Laranja","Abacaxi"}
frutas.add("Pera")
frutas.remove("maça")
frutas.pop()
print(frutas)
set1 = {"maça","Laranja","Abacaxi"}
set2 = {0,3,50,-74}
set3 = {True,False,False,False}
set4 = {"Roger",34,True}
print(set4) |
input1='389125467'
input2='496138527'
lowest=1
highest=1000000
class Node:
def __init__(self, val, next_node=None):
self.val=val
self.next=next_node
cups=list(input2)
cups=list(map(int,cups))
lookup_table={}
prev=None
# form linked list from the end node to beginning node
for i in range(len(cups)... |
def counting_sort(arr):
k = max(arr)
count = [0] * k + [0]
for x in arr:
count[x] += 1
for i in range(1, len(count)):
count[i] = count[i] + count[i-1]
output = [0] * len(arr)
for x in arr:
output[count[x]-1] = x
yield output, count[x]-1
count[x] -= 1
... |
number = int(input())
if 100 <= number <= 200 or number == 0:
pass
else:
print('invalid') |
def nth(test, items):
if test > 0:
test -= 1
else:
test = 0
for i, v in enumerate(items):
if i == test: return v
|
# Combinations
class Solution:
def combine(self, n, k):
ans = []
def helper(choices, start, count, ans):
if count == k:
# cloning the list here
ans.append(list(choices))
return
for i in range(start, n + 1):
ch... |
class PyTime:
def printTime(self,input):
time_in_string = str(input)
length = len(time_in_string)
if length == 3:
hour,minute1,minute2 = time_in_string
hours = "0" + hour
minutes = minute1 + minute2
converted_time = self.calculate... |
# create sets
names = {'anonymous','tazri','farha'};
extra_name = {'tazri','farha','troy'};
name_list = {'solus','xenon','neon'};
name_tuple = ('helium','hydrogen');
print("names : ",names);
# add focasa in names
print("add 'focasa' than set : ");
names.add("focasa");
print(names);
# update method
print("\n\nadd ext... |
#! /usr/bin/python3.6
def create_spa_workbench(document):
"""
:param document:
:return: workbench com object
"""
return document.GetWorkbench("SPAWorkbench")
|
user = int(input("ENTER NUMBER OF STUDENTS IN CLASS : "))
i = 1
marks = []
absent = []
# mark = marks.copy()
print("FOR ABSENT STUDENTS TYPE -1 AS MARKS")
for j in range(user):
student = int(input("ENTER MARKS OF STUDENT {} : ".format(i)))
if student == -1:
absent.append(i)
else:
... |
def sum_func(num1,num2 =30,num3=40):
return num1 + num2 + num3
print(sum_func(10))
print(sum_func(10,20))
print(sum_func(10,20,30))
|
#!/usr/bin/env python
# -*- config : utf-8 -*-
'help'
class Report(object):
"""
You can wirte the report has created into a html file.
"""
def __init__(self, headtitle, content):
self.headtitle = 'Bat''s' + headtitle
self.content = content
def replace(self):
self.cont... |
'''
No automobilismo é bastante comum que o líder de uma prova, em determinado momento, ultrapasse o último colocado. O líder, neste momento, está uma volta à frente do último colocado, que se torna, assim, um retardatário. Neste problema, dados os tempos que o piloto mais rápido e o piloto mais lento levam para comple... |
def variableName(name):
str_name = [i for i in str(name)]
non_acc_chars = [
" ",
">",
"<",
":",
"-",
"|",
".",
",",
"!",
"[",
"]",
"'",
"/",
"@",
"#",
"&",
"%",
"?",
... |
# 372.在O(1)时间复杂度删除链表节点 / delete-node-in-the-middle-of-singly-linked-lis
# http://www.lintcode.com/problem/delete-node-in-the-middle-of-singly-linked-list
# 给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在O(1)时间复杂度删除该链表节点。
# Exa
# 给定 1->2->3->4,和节点 3,删除 3 之后,链表应该变为 1->2->4。
"""
Definition of ListNode
class ListNode(object):
def ... |
class Vector2d(
object,
ISerializable,
IEquatable[Vector2d],
IComparable[Vector2d],
IComparable,
IEpsilonComparable[Vector2d],
):
"""
Represents the two components of a vector in two-dimensional space,
using System.Double-precision floating point numbers.
Vector2d(x... |
def palindrome(num):
return str(num) == str(num)[::-1]
# Bots are software programs that combine requests
# top Returns a reference to the top most element of the stack
def largest(bot, top):
z = 0
for i in range(top, bot, -1):
for j in range(top, bot, -1):
if palindrome(i ... |
#
# Copyright (c) 2020 Xilinx, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
#
plnx_package_boot = True # Generate Package Boot Images
|
#
# PySNMP MIB module AGG-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGG-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:15:43 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,... |
nums = [int(input()) for _ in range(int(input()))]
nums_count = [nums.count(a) for a in nums]
min_count, max_count - min(nums_count), max(nums_count)
min_num, max_num = 0, 0
a, b = 0, 0
for i in range(len(nums)):
if nums_count[i] > b:
max_num = nums[i]
elif nums_count[i] == b:
if nums[i] > max_num:
max_num... |
# File: phishtank_consts.py
#
# Copyright (c) 2016-2021 Splunk Inc.
#
# 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 a... |
# coding:utf-8
# File Name: bit_operator_test
# Author : yifengyou
# Date : 2021/07/18
print(5|9) |
# -*- coding: utf-8 -*-
{
'name': 'Events',
'category': 'Website/Website',
'sequence': 166,
'summary': 'Publish events, sell tickets',
'website': 'https://www.odoo.com/page/events',
'description': "",
'depends': ['website', 'website_partner', 'website_mail', 'event'],
'data': [
... |
Ds = [1, 1.2, 1.5, 2, 4]
file_name = "f.csv"
f = open(file_name, 'r')
for depth in Ds:
print('\n\n DEALING WITH ALL D = ', depth-1)
DATA['below_depth'] = (depth - 1) * HEIGHT
for angle in range(2,90,1):
if angle %5 ==0: continue
if angle >= 50 and angle <=60: continue
f.close... |
class lista:
def __init__(self,list):
self.list=list
def tamaño(self):
for i in range(len(self.list)):
print(f'{i+1}- {self.list[i]}')
print(len(self.list))
lista1=[1,2,3,4,5]
lista(lista1).tamaño() |
class Db():
def __init__(self, section, host, wiki):
self.section = section
self.host = host
self.wiki = wiki
|
"""Classes for handling geometry.
Geometric objects (see :class:`GeometricObject`) are usually
used in :class:`~ihm.restraint.GeometricRestraint` objects.
"""
class Center(object):
"""Define the center of a geometric object in Cartesian space.
:param float x: x coordinate
:param float y: y co... |
# a dp method
class Solution:
def longestPalindrome(self, s: str) -> str:
size = len(s)
if size < 2:
return s
dp = [[False for _ in range(size)] for _ in range(size)]
maxLen = 1
start = 0
for i in range(size):
dp[i][i] = True
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.