content stringlengths 7 1.05M |
|---|
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses")
print(f"You have {boxes_of_crackers} boxes of crackers")
print("That's a lot")
print("Get a blanket\n")
print("We can just give the function numbers directly")
cheese_and_crackers(20, 30)
print("Or, we can use ... |
class Solution:
def rob(self, nums):
n = len(nums)
if n == 1:
return nums[0]
dpa = [0] * (n + 1)
dpb = [0] * (n + 1)
for i in range(2, n + 1):
dpa[i] = max(dpa[i - 1], dpa[i - 2] + nums[i - 2])
dpb[i] = max(dpb[i - 1], dpb[i - 2] + nums[i ... |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = 'Zhiquan Wang'
__date__ = '2018/8/15 10:44'
class MessageType(object):
login_request = u'LoginRequest'
login_reply = u'LoginReply'
attack_request = u'AttackRequest'
attack_reply = u'AttackReply'
game_info = u'GameInfo'
class JsonAttribu... |
#!/usr/bin/python3
# Because I decided to use the ThreadingMixIn in the HTTPServer
# we will need to persist the data on disk...
# DB_FILE = ':memory:'
DB_FILE = 'db.sqlite3'
|
"""
Variables Globales.
Elle permettent de rendre le code plus digeste.
On pourrais en theorie les remplaces par leurs nombres respectif mais ce serais illisible.
"""
NULL = (0)
BOAT = (1)
DESTROYED = (2)
HIT_SUCCESS = (3)
HIT_MISS = (4)
DIRECTION_UP = (5)
DIRECTION_DOWN = (6)
DIRECTION_LEFT = (7)
DIRECTIO... |
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
d = {}
def dfs(node, level):
if level not in d:
d[level] = []
d[level].append(node.val)
if node.left:
dfs(node.left, level + 1)... |
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
# Primes are hard....recycle code from problem 7...
n = 2
limit = 1000
primes = []
prime = 0
primeSum = 0
while prime <= limit:
for i in range(2,n):
if (n % i) == 0:
break
else:
... |
"""
Sharingan project
We will try to find your visible basic footprint from social media as much as possible
"""
|
"""
This is a demo task.
Write a function:
def solution(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−... |
# String Literals
hello_world = "Hello, World"
hello_world_two = " Hello World "
print(hello_world[1])
print(hello_world[0:5])
# Length of the string
print(len(hello_world))
# Strip
print(hello_world_two)
print(hello_world_two.strip())
# Lower
print(hello_world.lower())
# Upper
print(hello_world.upper())
# Replace... |
"""
This program calculates an exponential using the fast exponential algorithm.
"""
def fast_exponential(base: int, exponent: int) -> int:
if not isinstance(base, int):
raise ValueError("Invalid Base")
if not isinstance(exponent, int):
raise ValueError("Invalid Exponent")
if exponent < 0:... |
# -*- coding: utf-8 -*-
#
# Copyright 2014 Jaime Gil de Sagredo Luna
#
# 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... |
#Needs more comments
#Node class
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def getData(self):
return self.data
#Adjanceny List graph implementation
class ALGraph:
#initialize list
def __init__(self):
self.table = []
#ad... |
"""
Name: polynom.py
Goal: operations with of polynoms
Author: HOUNSI madouvi antoine-sebastien
Date: 8/03/2022
"""
class Polynom:
def mult(self, P1, P2):
""" Multiplication between P1 and P2 """
maxArray = [x for x in P1]
minArray = [x for x in P2]
if len(P1) == 1... |
larg = float(input('Quanto de largura tem ? '))
alt = float(input('Quanto de altura tem ? '))
a = larg*alt
t = a / 2
print(f'A área do compartimento é de {a :.3f} m**2. \n'
f'E precisa de {t :.3f} litros de tinta.')
|
"""
Calculate minimum steps of raffle shuffle (alternating shuffle)
of a deck of cards to get to max degree of disorder.
Disorder of a = sum(abs(i-a[i]) for i in range(...))
"""
def steps(n):
deck = [*range(n)]
p = []
for _ in range(n):
deck = deck[::2] + deck[1::2]
p += sum(abs(i-deck[i... |
class CalculateAccount:
def __init__(self, **kwargs):
self.account = kwargs.get('account')
self.agency = kwargs.get('agency')
def calculate_account_bb(self):
"""
Calcula o dígito verificador da conta do Banco do Brasil
"""
numbers = [number for number in self... |
FLOWERS = r"""
vVVVv vVVVv
(___) vVVVv (___) vVVVv
~Y~ (___) ~Y~ (___)
\| \~Y~/ \| \~Y~/
\\|// \\|// \\|// \\|//
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"""
SAMPLE = r"""
.--. ... |
s = float(input('Digite o salario do funcionario: R$ '))
if s>1250:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora.'.format(s,s+(s*10/100)))
else:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora'.format(s,s+(s*15/100)))
|
# -*- coding: utf-8 -*-
"""
@project: Sorting-Algorithms
@version: v1.0.0
@file: selection_sort.py
@brief: Selection Sort
@software: PyCharm
@author: Kai Sun
@email: autosunkai@gmail.com
@date: 2021/8/1 21:41
@updated: 2021/8/1 21:41
"""
def selection_sort(arr):
for i in range... |
# Data Type in Python is an attribute of data which tells the interpreter how the programmer intends to use the data
# There are three numeric data types in Python:
# Integers
# Integers (e.g. 2, 4, 20)
# - Boolean (e.g. False and True, acting like 0 and 1)
# Floating Point Numbers (e.g. 3.0, 5.2)
# Complex Number... |
class Quadrilatero:
def __init__(self, lado1, lado2):
self.__lado1 = lado1
self.__lado2 = lado2
def retangulo():
pass
def retangulo():
pass
def retangulo():
pass |
#creating a node
class Node:
def __init__(self,data):
self.value=data
self.left=None
self.right=None
#function to check if the tree is a mirror image of another tree
def isMirror(troot1, troot2):
if troot1 == None and troot2 == None:
return True;
if (troot1 != None and t... |
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class GcloudResourceBuilder(object):
''' Class to wrap the gcloud deployment manager '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
clusterid,
project,
r... |
"""
0758. Bold Words in String
Easy
Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b> tags become bold.
The returned string should use the least number of tags possible, and of course the tags should form a valid combination.
For example, g... |
# Outputs strings with inverted commas
# Author: Isabella Doyle
message = 'John said "hi", I said "bye.'
print(message) |
# 000758_02_02_ifStatements.py
print("000758_02_02_ifStatements:01")
if 10 > 5:
print("10 greater than 5")
print("Program ended")
print("")
print("000758_02_02_ifStatements:02:nested")
num = 12
if num > 5:
print("Bigger than 5")
if num <= 47:
print("Between 5 and 47")
print("")
print("000758_02_02_... |
PREFIX = "/api"
CORS_POLICY = {"origins": ("*",), "max_age": 3600}
class Base:
def __init__(self, request, context=None):
self.request = request
@property
def _index(self):
return self.request.registry.settings["pyfapi.es.index"]
def _result(self, result):
return {"result": ... |
numerospares = list()
numerosimpares = list()
while True:
numero = int(input("Digite um número "))
continuar = str(input("Deseja continuar S/N: "))
if numero % 2 == 0:
numerospares.append(numero)
else:
numerosimpares.append(numero)
if continuar == "N":
break
todosnumeros ... |
###Titulo: Soma e média
###Função: Este programa soma números e apresenta média aritmética
###Autor: Valmor Mantelli Jr.
###Data: 20/12/2018
###Versão: 0.0.8
# Declaração de variáve
s = 0
n = 0
v= 0
# Atribuição de valor a variavel e processamento
while True:
v = int(input("Digite um número inteiro ou 0 para sa... |
# Exer 8
# # Creating a list of nice places to visit
places_to_visit = ['island', 'australia', 'cananda', 'thailand']
print(places_to_visit)
# putting the list into alphabetic order
print(sorted(places_to_visit))
# putting the list back to its original order
print(places_to_visit)
# putting the list backwards
place... |
def print_matrix(matrix):
for row in matrix:
for elem in row:
print(elem, end='\t')
print()
print(__name__)
if __name__ == "__main__":
print("Something to run as stand alone script")
|
"""
In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.
Example 1:
Input: nums = [3, 6, 1, 0]
Output: 1
Explanat... |
class Solution:
"""
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Given a string, you need to reverse the order of characters in each
word within a sentence while still preserving whitespace and
initial word order.
Example 1:
Input: "Let's take LeetCode contest"
... |
#!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
__all__ = [
'datastructures',
'exception',
'funcs',
'info',
'kprobe',
'... |
l=[]
print(l)
l.append(10)
print(l)
l.append(11)
print(l) |
# coding = utf-8
# @time : 2019/6/30 6:41 PM
# @author : alchemistlee
# @fileName: filter_long_tk.py
# @abstract:
if __name__ == '__main__':
input_zh = '/root/workspace/translate_data/my_corpus_v6.zh-cut.processed6-bpe-v6-2-.test'
input_en = '/root/workspace/translate_data/my_corpus_v6.en.tok.processed6-... |
#
# @lc app=leetcode id=677 lang=python3
#
# [677] Map Sum Pairs
#
# @lc code=start
class MapSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {}
def insert(self, key, val):
self.d[key] = val
def sum(self, prefix):
return sum(... |
#
# PySNMP MIB module Fore-frs-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-frs-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:04: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,... |
## pure function: has no side effect and returns a value based on their arguments
def pure_function(x,y):
temp = x + 2*y
return temp / y + 2*x
##impure function
some_list = []
def impure(arg):
some_list.append(arg) |
# coding: utf-8
"""
sentry_riemann
"""
VERSION = '0.0.4'
|
class Solution(object):
def brokenCalc(self, X, Y):
res = 0
while Y > X:
res += Y % 2 + 1
Y = Y // 2 if Y % 2 == 0 else (Y + 1)//2
return res + X - Y
def main():
startValue = 2
target = 3
startValue = 5
target = 8
startValue = 3
target = 10
startValue ... |
x = 5
if x > 4:
print("¡La condición era verdadera!")
|
'''
Created on Nov 14, 2017
@author: jschm
'''
class Fraction(object):
'''Defines an immutable rational number with common arithmetic operations.
'''
def __init__(self, numerator=0, denominator=1):
#default values for fraction is 0
'''Constructs a rational number (fraction) initialized to ... |
#Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final mostre:
# - A média de idade do grupo. - Quantas mulheres tem menos de 20 anos.
# - Qual é nome do homem mais velho.
totidade = 0
i_velho = 0
nome_velho = ''
totm = 0
for c in range(1, 5):
print(5*'-', '{} pessoa'.format(... |
"""
The dictionaries are blocks and they the present by '{}' , inside every block is
represented by two elements, one key and one value, separated by ':' and with ','
separated every block
Example: name = {key1:value1, key2:value2,.......}
And inside the values you can have tuple, list, numbers, strings, all types of d... |
'''
Created on Nov 22, 2010
@author: johantenbroeke
'''
|
# First we'll start an undo action, then Ctrl-Z will undo the actions of the whole script
editor.beginUndoAction()
# Do a Python regular expression replace, full support of Python regular expressions
# This replaces any three uppercase letters that are repeated,
# so ABDABD, DEFDEF or DGBDGB etc. the first 3 char... |
"""Define function to sort and merge an unsorted array."""
def mergesort(arr):
"""Define merge sort."""
left = arr[:len(arr)//2]
right = arr[len(arr)//2:]
if len(left) > 1:
left = mergesort(left)
if len(right) > 1:
right = mergesort(right)
lst = []
i, j = 0, 0
while i ... |
class Product(object):
def __init__(self, product_name:str, global_id, price, description="") -> None:
self.product_id = global_id
self.product_name = product_name
self.description = description
self.price = price
print("created product {0.product_name}".format(se... |
# Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
num = int(input("Enter number: "))
def bubbles_sum(num):
sum = 0
for a in range(1, num + 1):
sum = sum + a
if (a % 3 == 0 or a % 5 == 0) :
sum = s... |
# The channel to send the log messages to
CHANNEL_NAME = "voice-log"
# The bot token
BOT_TOKEN = "NDI3NTIyNzMxNjgxsasdsagsadshvbn,.fgsfgjfkLHEGROoAxA"
|
"""Contains some global switches"""
# Master switches: turn them on (True) to immediately switch phase
master_proceed_to_day = False
master_proceed_to_dawn = False
master_proceed_to_night = False
master_proceed_to_nomination = False
def init_switches():
"""Initialize (reset) these global switches"""
global m... |
# use the function blackbox(lst) that is already defined
lst = ["a", "b", "c"]
blackbox_lst = blackbox(lst)
print("modifies" if id(lst) == id(blackbox_lst) else "new")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 22 17:46:31 2022
@author: victor
"""
bikes = []
bikes.append('trek')
bikes.append('giant')
bikes.append('redline')
print(bikes) |
expected_output = {
"instance": {
"default": {
"vrf": {
"EVPN-BGP-Table": {
"address_family": {
"l2vpn evpn": {
"prefixes": {
"[3][40.0.0.3:164][0][32][40.0.0.7]/17": {
... |
"""Generated config, with scaler.
Date: 2022-01-09
Change: f = 48, n = 128 with relative error constrain in 1e-3.
added zero_mask = 1e-10.
The scaler directly save the reciprocal, have some problems in the round of its reciprocal.
The error evaluation method changed for both plain-text and cipher-text.
"""
sigmoid_co... |
def get_colnames(score: str):
colnames = {
"charlson": {
"aids": "AIDS or HIV",
"ami": "acute myocardial infarction",
"canc": "cancer any malignancy",
"cevd": "cerebrovascular disease",
"chf": "congestive heart failure",
"copd": "chron... |
#!/usr/bin/env python
'''
Test Templates
'''
regList = ["A", "B", "C", "D", "E", "F", "H", "L", "HL", "PC", "SP"]
cpuTestFile = '''
namespace GameBoyEmulator.Desktop.Tests {
[TestFixture]
public class CPUTest {
private const int RUN_CYCLES = 10;
{TESTS}
}
}
'''
baseTestTemplate = '''
... |
#Start of code
x=['a','e','i','o','u','A','E','I','O','U']
y=input("Enter an Alphabet: ")
if y in x:
print(y,"is a vowel")
else:
print(y,"is not a vowel")
#End of code
|
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'utils.authenticate.GoogleBackend',
]
|
N, M = map(int, input().split())
A = []
B = []
for i in range(N):
A.append(list(map(int, input().split())))
for i in range(N):
B.append(list(map(int, input().split())))
C = []
for i in range(N):
tmp = []
for j in range(M):
a = A[i][j]
b = B[i][j]
tmp.append(a ^ b)
C.append(... |
def get_fisnar_commands(**kwargs):
"""
get a list of the fisnar commands with a specified filter
:param xyz: set to True to only return commands that take in x, y, and z coordinates
:type xyz: bool
"""
filters = [] # list to store filters
kwarg_keys = ["xyz"]
for key in kwargs: # tr... |
contacts = {}
running = True;
while running:
command = input('enter A(dd) D(elete) F(ind) Q(uit)')
if command == 'A' or command == 'a':
name = input('enter a new name');
print('enter a phone number for', name, end=':')
number=input()
contacts[name] = number
elif command == ... |
class Atom:
def __init__(self, symbol, atoms, neutr):
self.symbol = str(symbol)
self.atoms = int(atoms)
self.neutrons = int(neutr)
self.protons = int(0)
self.mass = int(0)
def proton_number(self):
self.protons = self.atoms - self.neutrons
return self.prot... |
#!/usr/bin/env python3
xList = [ int( x ) for x in input().split() ]
xList = sorted( xList )
medianIndex = len( xList ) // 2
if len( xList ) % 2 == 0:
print( ( xList[medianIndex-1] + xList[medianIndex] ) / 2. )
else:
print( float( xList[ medianIndex ] ) )
|
class Box(object):
def __init__(self, side, height):
self._side = side
self._height = height
def volume(self):
return self._side * self._side * self._height
def __lt__(self, other):
return self.volume() < other
def __eq__(self, other):
return self.volume() == o... |
ROCK, PAPER, SCISSORS = range(3)
class RpsCandidate:
"""
Abstract base class for candidates for the
Pi In The Sky: Rock Paper Scissors Competition
"""
def __init__(self):
pass
def getNextMove(self):
"""
Get the next move in the game
Returns:
the ne... |
class Card():
ranks = [str(n) for n in range(2, 10)] + list('TJQKA')
rank_tran = {rank: n for n, rank in enumerate(ranks, 2)}
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self._numrank = self.rank_tran[rank]
def __eq__(self, other):
return self._num... |
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
# def helper(countA, countB, idx, cur_cost):
# if idx == len(costs):
# return cur_cost
# if countA < len(costs) // 2 and countB < len(costs) // 2:
# return min(helper(countA + 1... |
enum_ = '''
[COMMENT_LINE_IMPORTS]
# System
from enum import Enum
[COMMENT_LINE]
[COMMENT_LINE_CLASS_NAME]
class [CLASS_NAME](Enum):
[TAB]Template = 0
[COMMENT_LINE]
'''.strip() |
phones = [
{"id": 6, "latitude": 40.1011685523957, "longitude": -88.2200390954902},
{"id": 7, "latitude": 40.0963186128832, "longitude": -88.2255865263258},
{"id": 8, "latitude": 40.1153308841568, "longitude": -88.223901994968},
]
def get_phones():
return phones
bad_data = [
{"id": 6, "longitude... |
ies = []
ies.append({ "iei" : "2C", "value" : "IMEISV", "type" : "5G mobile identity", "reference" : "9.10.3.4", "presence" : "O", "format" : "TLV", "length" : "11"})
ies.append({ "iei" : "7D", "value" : "NAS message container", "type" : "message container", "reference" : "9.10.3.31", "presence" : "O", "format" : "TLV-... |
# Write a program that reads an integer and displays, using asterisks, a filled and hol-
# low square, placed next to each other. For example if the side length is 5, the pro gram
# should display
# ***** *****
# ***** * *
# ***** * *
# ***** * *
# ***** *****
side = int(input("Ente... |
class Solution:
def countBits(self, num: int) -> List[int]:
result = [0] * (1 + num)
for i in range(1, 1 + num):
result[i] = result[i&(i - 1)] + 1
return result
|
# function to check if two strings are
# anagram or not
def anagram(s1, s2):
# the sorted strings are checked
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
#commonCharacterCount
def commonC... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 16 12:03:24 2020
@author: tsdj
"""
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Back of envelope calculations for a precious metals mining company
try:
oz_per_yr = int(input("How many ounces will be produced annually?: "))
price_per_oz = int(input("What is the estimated USD price per ounce for the year?: "))
aisc = int(input("What is t... |
class MergeSort:
def __init__(self,array):
self.array = array
def result(self):
self.sort(0,len(self.array)-1)
return self.array
def sort(self,front,rear):
if front>rear or front == rear:
return
mid = int((front+rear)/2)
self.sort(front,mid)
... |
# 栈
class Solution:
def decodeString(self, s: str) -> str:
cnt = ''
res = ''
stack = []
cnt_stack = []
for i in range(len(s)):
c = s[i]
if c.isdigit():
cnt += c
elif c == '[':
cnt_stack.append(int(cnt))
... |
# Вася интересуется тем, что о нем пишут в интернете. Поэтому он хочет проверить, упоминается ли подстрока Vasya (именно
# с большой буквы) в строке.
#
# Вводится строка. Выведите True если в ней есть хотя бы одна подстрока Vasya и False в противном случае.
s = input()
subs = "Vasya"
print(subs in s)
|
#!/usr/bin/python
def find_max_palindrome(min=100,max=999):
max_palindrome = 0
a = 999
while a > 99:
b = 999
while b >= a:
prod = a*b
if prod > max_palindrome and str(prod)==(str(prod)[::-1]):
max_palindrome = prod
b -= 1
a -= 1
... |
def write():
systemInfo_file = open("writeTest.txt", "a")
systemInfo_file.write("\nTEST DATA2")
systemInfo_file.close()
|
# Problem Statement: https://www.hackerrank.com/challenges/exceptions/problem
for _ in range(int(input())):
try:
a, b = map(int, input().split())
print(a // b)
except (ZeroDivisionError, ValueError) as e:
print(f'Error Code: {e}') |
"""
Support for local Luftdaten sensors.
Copyright (c) 2020 Mario Villavecchia
Licensed under MIT. All rights reserved.
https://github.com/lichtteil/local_luftdaten/
Support for Ecocity Airhome sensors. AQI sensor
Mykhailo G
"""
|
"""
7.重建二叉树
时间复杂度:O(n^2) 最坏情况下(左子节点相连的单链),遍历inorder切片,n + (n-1) + (n-2) ... 1 = n*(n+1)/2
空间复杂度:O(n)
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def reConstructBinaryTree(self, pre, tin):
if (not pre) or (not tin):
... |
class ApplicationException(Exception):
"""Base Exception class for all exceptions across the application"""
def __init__(self, err_code: int, err_msg: str) -> None:
super(ApplicationException, self).__init__(err_code, err_msg)
self.err_code = err_code
self.err_msg = err_msg
def __s... |
class BaseContext(dict):
"""
warning: This is a singletone object. Don't create a instance of this object directly
"""
context_obj: 'BaseContext' = None
initial_data: dict = {
}
def initialize(self):
""" Initializes the context with default data """
self.update(self.initia... |
def div(func):
# You have to code here!
def wrapper(*arg, **kwargs):
answer_1 = f'<div>{func(*arg, **kwargs)}</div>'
return answer_1
return wrapper
def article(func):
# You have to code here!
def wrapper(*arg, **kwargs):
answer_2 = f'<article>{func(*arg, **kwargs)}</a... |
class Location:
__slots__ = 'name', '_longitude', '_latitude'
def __init__(self, name, longitude, latitude):
self._longitude = longitude
self._latitude = latitude
self.name = name
@property
def longitude(self):
return self._longitude
@property
d... |
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if not nums:
return 0
nums.sort()
count = 1
longest_streak = []
for index, value in enumerate(nums):
if index + 1 >= len(nums):
break
if nums[index + 1]... |
jobs = {}
class JobInfo(object):
def __init__(self, jobId):
self.jobId = jobId
self.data = None
self.handlers = []
|
#!/usr/bin/env python3
# ----------------------------------------------------------------------------
# Copyright (c) 2020--, Qiyun Zhu.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------... |
print(list(enumerate([])))
print(list(enumerate([1, 2, 3])))
print(list(enumerate([1, 2, 3], 5)))
print(list(enumerate([1, 2, 3], -5)))
print(list(enumerate(range(10000))))
|
# -*- coding: utf-8 -*-
"""
@version: 1.0
@author: James
@license: Apache Licence
@contact: euler52201044@sina.com
@file: 13_daffodils_number.py
@time: 2019/5/3 下午4:13
@description: 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
3位水仙花数有4... |
class Latex:
def __init__(self, ssh):
"""
latex
"""
self.bash = ssh.bash
# https://github.com/James-Yu/LaTeX-Workshop/wiki/Compile#latex-recipe
#pdflatex -> bibtex -> pdflatex X 2
# Recipe step 1
#
def compile(self, path, src, params):
try:
... |
programming_dictonary = {
"Bug":"An error in program that prevents the program running as expected",
"Function":"A piece of code that you can call over and over again",
}
# Retreive
print(programming_dictonary["Bug"])
# Adding items
programming_dictonary["Loop"] = "The action of doing something again and again... |
# ========== base graph node class / generic knowledge representation (AST/ASG)
class Object():
# node constructor with scalar initializer
def __init__(self, V):
# node class/type tag
self.type = self.__class__.__name__.lower()
# node name / scalar value
self.value = V
... |
"""
Samples below are intended to get us started with Python.
Did you notice this is a multi-line comment :-) and yes being the first
one and before code, it qualifies to be documentation as well. How Cool!!!
In order to be a docstring it had to be multi-line
"""
# print hello world :-), Hey this is a single line com... |
'''Escreva a função primeiro_lex(lista) que recebe uma lista de strings
como parâmetro e devolve o primeiro string na ordem lexicográfica.
Neste exercício, considere letras maiúsculas e minúsculas. '''
def primeiro_lex(lista):
for pal in lista:
if lista[0] == pal:
menor = pal
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.