content stringlengths 7 1.05M |
|---|
class SeparadorDeSilabas:
def __init__(self):
self.vocales_con_dieresis = ('ü',)
self.vocales_cerradas_sin_tilde = ('i', 'u')
self.vocales_cerradas_con_tilde = ('í', 'ú')
self.vocales_cerradas = self.vocales_cerradas_con_tilde + self.vocales_cerradas_sin_tilde
self.vocales_a... |
def iterPower(base,exp):
ans=1
while exp>0:
ans=ans*base
exp-=1
return ans
|
# Requer num e tipo = {"num": int, "tipo": int}
select_atributos_criatura = lambda dados = {} : """
Select atributo1, atributo 2
FROM criaturas
WHERE Num = :num
AND tipo = :tipo ;
"""
select_all_ref_atributos = lambda dados = {} : """
SELECT Distinct ref
FROM atributos
"""
# Requer tipo e r... |
"""
G2_RIGHTS.
Module to parse traffic configuration file.
"""
class TraceParser:
"""Class definition for traffic config file parsing.
Args:
path (str): Path to input traffic config file.
Attributes:
jobs (list): List of jobs obtained from traffic config file. Each job corresponds to a ... |
#Environment related constants
ENV_PRODUCTION = 'PRODUCTION'
#Staging is used for testing by replicating the same production remote env
ENV_STAGING = 'STAGING'
#Development local env
ENV_DEVELOPMENT = 'DEV'
#Automated tests local env
ENV_TESTING = 'TEST'
ENVIRONMENT_CHOICES = [
ENV_PRODUCTION,
ENV_STAGING,
... |
"""
Given an array of integers A, return the largest integer that only occurs once.
If no integer occurs once, return -1.
Example 1:
Input: [5,7,3,9,4,9,8,3,1]
Output: 8
Explanation:
The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it's the answer.
Example 2:
Input: [9,9,... |
# coding: utf-8
"""
API config settings
"""
PRODUCTION = True
DATABASES = {
'docker': {
'ENGINE': 'mongodb',
'NAME': 'leadbook',
'HOST': 'leadbookdb',
'PORT': 27017,
'TABLE': 'company'
},
'local': {
'ENGINE': 'mongodb',
'NAME': 'leadbook',
'H... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
... |
name = input("Please enter your name:")
age = int(input("Please enter your age:"))
if type(name) == str:
if type(age) == int:
print(f"{name} you are {age} years old and you will be 100 after {100 - age} years")
else:
print("Please enter a valid number")
else:
print("please enter your name")... |
"""
Test cases
TODO.
"""
|
seq = [0, 1]
def create_sequence(n):
global seq
if n == 0:
return []
elif n == 1:
return [0]
else:
seq = [0, 1]
for i in range(2, n):
seq.append(seq[-1] + seq[-2])
return seq
def locate(x):
if x in seq:
return f"The number - {x} is at in... |
d1 = dict()
print(d1) # DI1
print(type(d1))
d2 = dict({1:'a',2:'b',3:'c'})
print(d2) # DI2
d3 = dict([(1,"python"),(2,"is"),(3,"awesome")])
print(d3) # DI3
d4 = dict(((1,"python"),(2,"is"),(3,"awesome")))
print(d4) # DI4
d5 = dict({(1,"python"),(2,"is"),(3,"awesome")})
print(d5) # DI5
d6 = dict({[1,"python"],[2,"... |
def parse_array(tokenstream):
_ = tokenstream.pop_next()
assert _ == "["
result = []
while True:
token = tokenstream.pop_next()
if token == "]": break
result.append(token)
return result
def parse_varfunction(tokenstream, identifier, scene):
identifier_type = tokenstream.pop_next()[1:-1]
params... |
class Solution:
def lengthoflongestsubstring(self, s):
sls = len(set(s))
slen = len(s)
if slen < 1:
return 0
else:
max_len = 1
for i in range(slen):
for j in range(i+max_len+1, i+sls+1):
curr = s[i:j]
curr_l... |
"""
tuple 元组
列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网
站的用户列表或游戏中的角色列表至关重要。然而,有时候你需要创建一系列不可修改的元素,
元组可以满足这种需求。 Python将不能修改的值称为不可变的,而不可变的列表被称为元组。
元组看起来犹如列表,但使用圆括号而不是方括号来标识。
"""
#定义元组
dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])
#print(dimensions[2])
#python不能给元组的元素赋值
#dimensions[0]=250
for dimensi... |
print("Input: ",end="")
str = input()
def rev(str):
str = str.split(" ")
stack = []
for i in str:
stack.append(i)
while len(stack) > 0:
print(stack[-1], end = " ")
del stack[-1]
print("Output: ",end="")
rev(str)
|
class Solution(object):
def isScramble(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
return True
def test_is_scramble():
s = Solution()
assert s.isScramble("great", "rgeat") is True
assert s.isScramble("abcde", "caebd") is False
|
def compare_reverse_number(A, B):
rev_A, rev_B = '', ''
for i in range(len(A) - 1, -1, -1):
rev_A += A[i]
for j in range(len(B) - 1, -1, -1):
rev_B += B[j]
if rev_A > rev_B:
return rev_A
else:
return rev_B
def main():
A, B = input().split()
answer = compare_r... |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
# return linear_search_iterative(array... |
TASK = "task"
TASK_INSTANCE = "task_instance"
X = "X"
Y = "Y"
MAHOZ = "MAHOZ"
XY = f"{X}/{Y}"
|
class FlyweightMeta(type):
"""
Flyweight meta class as part of the Flyweight design pattern.
- External Usage Documentation: U{https://github.com/tylerlaberge/PyPattyrn#flyweight-pattern}
- External Flyweight Pattern documentation: U{https://en.wikipedia.org/wiki/Flyweight_pattern}
"""
def __ne... |
#
# PySNMP MIB module RDN-CABLE-SPECTRUM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RDN-CABLE-SPECTRUM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:54:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
t=int(input(""))
for i in range(0,t):
a,b=tuple(map(int,input("").split(" ")))
d=abs(a-b)
print((int(d/10))if(d%10==0)else(int((d+9)/10))) |
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(4)
def say_hi():
print("Hello")
say_hi() |
if __name__ == "__main__":
my_tuple = (1, 2, 3)
print('my_tuple:', my_tuple)
a, b, c = my_tuple
print('a', a)
print('b', b)
print('c', c)
print('my_tuple[0]:', my_tuple[0])
print('my_tuple[1]:', my_tuple[1])
print('my_tuple[1:3]:', my_tuple[1:3])
# my_tuple[0] = 1 # error , tup... |
"""
Datos de entrada
valor_normal-->van-->int
Datos de salida
valor_final-->vaf-->float
"""
#Entrada
van=int(input("digite el valor normal de la compra: "))
#Caja negra
vaf=((van-(van*0.15)))
#Salidas
print("El valor final de la compra es: ", vaf) |
#Bitonic sequence Dynamic programming
# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/dynamic/BitonicSequence.java
def bitonic_sequence( input ):
lis = [1]*len(input)
lds = [1]*len(input)
for i in range(1, len(input)):
for j in range(0, i):
if input[... |
# Exercício 084
pessoa = list()
dado = list()
maior = menor = 0
while True:
dado.append(str(input('Nome: ')))
dado.append(int(input('Peso: ')))
if len(pessoa) == 0:
maior = menor = dado[1]
else:
if dado[1] > maior:
maior = dado[1]
if dado[1] < menor:
meno... |
# Faça um programa que leia um ano qualquer e mostre se ele é BISSEXTO.
ano = int(input('Qual é o ano? '))
b = ano % 4
if b == 0:
print('\033[1;36mO ano de {} é bissexto. '.format(ano))
else:
print('\033[1;31mO ano de {} não é bissexto. '.format(ano))
|
# Bu Bir Basit Hesap Makinesidir
# Bu Fonksiyon iki sayıyı birbirine ekler
def toplama(x, y):
return x + y
# Bu fonksiyon iki sayıyı birbirinden çıkartır
def cikarma(x, y):
return x - y
# Bu fonksiyon iki sayıyı çarpar
def carpma(x, y):
return x * y
# Bu fonksiyon 2 sayıyı böler
def bölme... |
class API_Slack_Dialog():
def __init__(self):
self.title = ""
self.callback_id = ""
self.submit_label = "Submit"
self.state = "#3AA3E3"
self.elements = []
self.notify_on_cancel = True
# def add_button(self, name, text, value... |
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# Space complexity O(amount)
# Time complexity O(amount * the number of coins)
# Using Dynamic programinig with bottom-up strategy
# First, allocate the storage
dp = [amount + 1] * (amount + 1)
... |
i = float(input('Digite a primeira nota do aluno: '))
ii = float(input('Digite a segunda nota do aluno: '))
riv = ('{}{}{}'.format('\033[31m', i, '\033[m'))
ria = ('{}{}{}'.format('\033[34m', i, '\033[m'))
riiv = ('{}{}{}'.format('\033[31m', ii, '\033[m'))
riia = ('{}{}{}'.format('\033[34m', ii, '\033[m'))
riiiv = ('{}... |
class Solution:
def myPow(self, x: float, n: int) -> float:
return self.binary_exp_recursive(x, n)
def binary_exp_recursive(self, x: float, n: int) -> float:
exp = abs(n)
ans = self.recurse(x, exp)
return ans if n > 0 else 1 / ans
def recurse(self, x: float, n: int) -> floa... |
"""
Problem: https://www.hackerrank.com/challenges/any-or-all/problem
Max Score: 20
Difficulty: Easy
Author: Ric
Date: Nov 14, 2019
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
num_of_int = int(input())
list_of_int = list(map(int, input().split(" ")))
print(all(i > 0 for i in list_of_int)... |
lis = [1, 3, 15, 26, 30, 37, 45, 56, ]
divisibles = list(filter(lambda x: (x % 15 == 0), lis))
print(divisibles)
|
# A single line comment
""" A multiline comment can be
written by using three quotes
in sequence, and then by ending
with the same.
""" |
# 2. Number Definer
# Write a program that reads a floating-point number and prints "zero" if the number is zero.
# Otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1,
# or "large" if it exceeds 1 000 000.
number = float(input())
if number == 0:
print('zero')... |
# -*- coding: utf-8 -*-
DATE = 'Data'
TEMPERATURE = 'Temperatura do Ar Media (degC)'
MAX_TEMP = 'Temperatura do Ar Maxima (degC)'
MIN_TEMP = 'Temperatura do Ar Minima (degC)'
VARIATION_TEMP = 'Variacao da Temperatura do Ar (degC)'
HUMIDITY = 'Umidade relativa Media (%)'
MAX_HUMIDITY = 'Umidade relativa Maxima (%)'
MIN_... |
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
def selectionSort(A):
for i in range(len(A) - 1):
min = i
for j in range(i + 1, len(A)):
if A[j] < A[min]:
min = j
swap(A, min, i)
if __name__ == '__main__':
A = [3, 5, 8, 4, 1, ... |
# should_error
# skip-if: '-x' in EXTRA_JIT_ARGS
# Syntax error to have a continue outside a loop.
def foo():
try: continue
finally: pass
|
"""Advanced example of a complex flow.
TODO: copy our ETL example that we're currently using, simplify a bit.
"""
|
TWOUVO_SEQ = 'ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQCCSQYGYCGFGAEYCGAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCGKDAGGRVCTNNYCCSKWGSCGIGPGYCGAGCQSGGCDG'
FIVEHXG_SEQ = 'MRYFFMAEPIRAMEGDLLGVEIITHFASSPARPLHPEFVISSWDNSQKRRFLLDLLRTIAAKHGWFLRHGLFCIVNIDRGMAQLVLQDKDIRALLHAMLFVELQVAEHFSCQDNVLVD... |
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
n = len(words)
res = []
row = [words[0]]
length = len(words[0]) # length including necessary space
lenwd = len(words[0]) # length of words in this row
numwd = 1 # number of words in t... |
# Dungeon problem statement
# the dungeon has a size of R x C and you start at cell 'S' and there's an exit at cell 'E'.
# a cell full of rock is indicated by a '#' and empty cells are represented by a '.'
# ------------C-------------
# | S . . # . . . |
# | . # . . . # . |
# R . # . . . ... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self) -> None:
self.root = None
def push(self, value) -> None:
if self.root is None:
self.root = Node(value)
else:
root_node = self.root
... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
n = 0
if len(nums) == 0: return 0
for i in range(1,len(nums)):
if nums[n] < nums[i]:
n += 1
nums[n] = nums[i]
return n+1
|
"""
Integration tests of this component running live
on an integration server
"""
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( str ) :
n = len ( str ) - 1
i = n
while ( i > 0 and str [ i - 1 ] <= str [ i ] ) :
i -= 1
i... |
class CaseChangingStream():
def __init__(self, stream, upper):
self._stream = stream
self._upper = upper
def __getattr__(self, name):
return self._stream.__getattribute__(name)
def LA(self, offset):
c = self._stream.LA(offset)
if c <= 0:
return c
return ord(chr(c).upper() if self._upper else chr(c).... |
fp = open("1.in", "r")
drift = 0
for line in iter(fp.readline, ''):
drift += int(line)
print(drift)
def findDup():
drift = 0
seen = set([0])
for _ in range(1000):
fp = open("input1.txt", "r")
for line in iter(fp.readline, ''):
drift += int(line)
if drift in s... |
class CryptoNews:
"""
class that represents a single piece of crypto news
"""
def __init__(
self,
url="",
title="",
text="",
html="",
year=0,
author="",
source="",
):
self.url = url
self.title = title
self.text ... |
class Location:
"""
Location is an abstraction for representing a location in the World. An instance of the World can have multiple Event(s). Each event has a single Location.
Public Variables:
* x - x coordinate of the location
* y - y coordinate of the location
"""
def __... |
l1=[]
##Input number of elements in list
n=int(input())
##Input the elements in the list
l1=list(map(int,input().split()))
## Create a new list l2 to store the index(from 1 to number of elements in list1) of elements of list 1
l2=[i for i in range(1,n+1)]
##Run a for loop from 1 till the length of list 1(l1)
for i in ... |
# Original version was a simple for loop incrementing counts. Refactored to a generic function using list comprehension.
def main(filepath):
depths = [int(x) for x in open(filepath,'r').read().split('\n')]
increases = lambda x,y: len([d for i,d in enumerate(x[1:]) if len(x[i+1:]) >= y and sum(x[i+1:i+y+1])... |
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack, indicesToRemove, result = [], set(), []
for i, c in enumerate(s):
if c not in ['(', ')']:
continue
if c == '(':
stack.append(i)
elif not stack:
in... |
MFCSAM = {'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0,
'vizslas': 0, 'goldfish': 5, 'trees': 3, 'cars': 2, 'perfumes': 1}
GREATER = ('cats', 'trees')
FEWER = ('pomeranians', 'goldfish')
sues = []
for row in open('input').read().splitlines():
sue_properties = {}
for info in ... |
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
dp = [ [0] * (len(word2)+1) for _ in range(len(word1)+1) ]
for k in range(1, len(word2)+1):
dp[0][k] = k
for k in range(1, len(word1)+1):
dp[k][0] = k
for p in range(1, len(word1)+1):
... |
def sample(a: int, b: float, c: str) -> str:
"""
This is a sample
:param a: this is a
with two lines
:param b: this is b
:param c: this is c
:return: this is a string conatining that
"""
pass
|
class Runner:
def __init__(self, graph):
self.graph = graph
self.cache = {}
def findValues(self, inputs):
self.cache = {}
for inputIndex in range(len(inputs)):
self.cache[(inputIndex + 1, 0)] = inputs[inputIndex]
if not self.__calculateValues(self.graph.nod... |
print('\033[7;30m',21*'#','\033[m')
print('\033[1;31;40m','COMPARADOR DE NÚMEROS','\033[m')
print('\033[7;30m',21*'#','\033[m')
n1 = int(input('Digite um número inteiro: '))
n2 = int(input('Digite outro número inteiro: '))
if n1>n2:
print(f'O primeiro valor, {n1}, é maior!')
elif n2>n1:
print(f'O segundo valor,... |
# Copyright (c) Moshe Zadka
# See LICENSE for details.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
]
master_doc = 'index'
project = 'Symplectic'
copyright = '2017, Moshe Zadka'
author = 'Moshe Zadka'
version = '17.10'
release = '17.10'
|
'''
Created on 20 Jul 2015
@author: njohn
'''
if __name__ == '__main__':
pass |
# coding:utf-8
class Error(Exception):
def __str__(self):
return self.message
class SessionExpiredError(Error):
def __init__(self, message="Session has expired."):
super(SessionExpiredError, self).__init__()
self.message = message
class SessionInvalidError(Error):
def __init__(... |
# 1. Complete the function by filling in the missing parts. The color_translator
# function receives the name of a color, then prints its hexadecimal value.
# Currently, it only supports the three addictive primary colors (red, green,
# blue), so it returns "unknown" for all other colors.
def color_translator... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
元类介绍
- https://www.cnblogs.com/ellisonzhang/p/10513238.html
- 元类就是创建类这种对象的东西,type就是Python的内建元类,当然了,你也可以创建自己的元类
- 元类的主要目的就是为了当创建类时能够自动地改变类
"""
def main():
pass
if __name__ == "__main__":
main()
|
"""
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no mor... |
# Joshua Nelson Gomes (Joshua)
# CIS 41A Spring 2020
# Take-Home Assignment I
class Square:
def __init__(self, side):
self.side = side
def getArea(self):
return self.side * self.side
class Cube(Square):
def __init__(self, side):
Square.__init__(self, side)
def getVolume(self):
return self.side * self.si... |
# The subroutine inserts the vector passed as the secondargument into row j of the matrix.
# It also inserts this vector into column j of the matrix.
# Insertion involves copying the vector into the corresponding row and column.
# If the value of j is out of range, the subroutine returns -1 and does not perform any ins... |
class HooksIter:
def __init__(self, items=None):
self.hooks = {}
if items:
for item in items:
self.hooks[item] = item.hooks
def __iter__(self):
for hooks in self.hooks.values():
for event in hooks:
for hook in event:
... |
#
# Copyright (C) 2010-2017 Samuel Abels
# The MIT License (MIT)
#
# 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,... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Micah Hunsberger (@mhunsber)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: win_file_compression
short_description: Alters the compression of files and directories on NTFS pa... |
class PopulationIsNotEvaluatedException(RuntimeError):
pass
class StopEvolution(Exception):
pass
|
class Rule:
"""Represents a single production rule of a grammar.
Rules are usually written using some sort of BNF-like notation,
for example, 'list ::= list item' would be a valid rule. A rule
always has a single non-terminal symbol on the left and a list
(possibly empty) of arbitrary symbols o... |
#121
# Time: O(n)
# Space: O(1)
# Say you have an array for which the ith element is
# the price of a given stock on day i.
# If you were only permitted to complete at most one transaction
# (ie, buy one and sell one share of the stock),
# design an algorithm to find the maximum profit.
#
# Example 1:
# Input: [... |
def partition(nums, low, high):
pivot = nums[(low + high) // 2]
i = low - 1
j = high + 1
while True:
i += 1
while nums[i] < pivot:
i += 1
j -= 1
while nums[j] > pivot:
j -= 1
if i >= j:
return j
nums[i], nums[j] = nums... |
h, w = map(int, input().split())
ans = 0
if h == 1 or w == 1:
ans = 1
else:
if w % 2 == 0:
ans += (w//2)*h
else:
if h % 2 == 0:
ans += (h//2)*(w//2*2+1)
else:
ans += (h//2)*(w//2*2+1)+(w//2+1)
print(max(1, ans))
|
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
idx1, idx2 = 0, len(numbers)-1
while idx1 < idx2:
if numbers[idx1] + numbers[idx2] == target:
return [idx1+1, id... |
class User:
""" Contains additional user data """
def __init__(self, sid: str, nickname: str):
self._sid = sid
self._nickname = nickname
self._rooms = []
def get_sid(self) -> str:
""" Returns the user's unique SID """
return self._sid
@property
def nickname(... |
### test examples for the rast_client.py file
def test_somefunction():
pass
|
include("common.py")
beta_decarboxylation = ruleGMLString("""rule [
ruleID "Beta Decarboxylation"
labelType "term"
left [
edge [ source 4 target 7 label "-" ]
edge [ source 7 target 9 label "-" ]
edge [ source 9 target 10 label "-" ]
]
context [
node [ id 1 label "*" ]
edge [ source 1 target 2 label "-"... |
def main():
#with open(filename, (open for reading 'r', #writing 'w' or reading and writing 'rw'))
word = input("What's your word? Enter it here: ")
print("Scrabble score: " + (str)(scrabble_value(word)));
#everything past here the file is closed
# scrabble_value("potato")
#three options:
# 1) write a program ... |
ALL_DRIVERS = ['chromedriver', 'geckodriver']
DEFAULT_DRIVERS = ['chromedriver', 'geckodriver']
CHROMEDRIVER_STORAGE_URL = 'https://chromedriver.storage.googleapis.com'
CHROMEDRIVER_LATEST_FILE = 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE'
GECKODRIVER_LASTEST_URL = 'https://api.github.com/repos/mozi... |
"""State testing.
TODO: Create more comprehensive testing
"""
# from cadcad.space import Space
def test_class_creation() -> None:
"""Test class creation."""
|
#!/usr/local/bin/python3
"""This program takes a user's input on Name and Breed of a dog, then prints a list of the dogs."""
class Dog:
def __init__(self,name,breed):
self.name = name
self.breed = breed
def __str__(self):
return "{0}:{1}".format(self.name, self.breed)
... |
class restaurant:
def __init__(self,restaurant_name,cuisine_type):
"""initialize restaurant name and cusine"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0 #setting default value for an attribute
def describe_restaurant(self):
print(se... |
# Ordering
# Create a program that allows entry of 10 numbers and then sorts them into ascending or descending order, based on user input.
def main():
isNumber = input('Do you want to enter numbers or a string: [N/S] ').upper()
if isNumber == 'N':
nums = [int(input('Enter a number: ')) for _ in range(10)]
... |
# This problem was recently asked by Twitter:
# Implement a class for a stack that supports all the regular functions (push, pop) and
# an additional function of max() which returns the maximum element in the stack (return None if the stack is empty)
# Each method should run in constant time.
class MaxStack:
def ... |
coins = {
"Khan's Concentrated Magic": 80000,
"Luminous Cobalt Ingot": 800,
"Bright Reef Piece": 140,
"Great Ocean Dark Iron": 160,
"Cobalt Ingot": 150,
"Brilliant Rock Salt Ingot": 1600,
"Seaweed Stalk": 600,
"Enhanced Island Tree Coated Plywood": 80,
"Pure Pearl Crystal": 550,
"Cox Pirates' Artifact (Parley... |
class Command:
def execute(self):
raise NotImplementedError
|
# Use a Q to keep recent timestamps. Whenever ping is called, add t to Q and remove all the expired ones. Return len(Q)
class RecentCounter:
def __init__(self):
self.Q = []
def ping(self, t: int) -> int:
self.Q.append(t)
while self.Q[0]<t-3000:
self.Q.pop(0)
... |
class Html_Maker:
@classmethod
def read_text_file(cls, path: str):
ret = ''
with open(path, 'r') as f:
while True:
line = f.readline()
if not line:
break
line = line.replace(
'\t', '<span style="... |
a = list(range(10))
print(a)
b = list("Pablo Fajardo")
print(b)
empty = []
print(empty)
nine = [0,1,2,3,4,5,6,7,8,9]
print(nine)
mixed = ['a',1,'b',2,'c',3,"Pablo",empty,True]
print(mixed)
#Add a single item to a list
mixed.append("Fajardo")
print(mixed)
#Add item with index
mixed.insert(2,"PALABRA")
print(mixed... |
# 堀哲也 2016/11/05
# Copyright (c) 2016 Tetsuya Hori
# Released under the MIT license
# https://opensource.org/licenses/mit-license.php
# pos 完了した作業工程の数
# full 全作業工程の数
#
# 入力されるposは常に 0 <= pos <= full を満たす
# 表示成功で0、失敗で1を返す
#
#
# 表示例 (全工程1000個中、334個完了の状態)
#
# |******--------------| 33.4% NUM:[ 334 / 1000 ]
... |
# This is a useful data structure for implementing
# a counter that counts the time.
class DFSTimeCounter:
def __init__(self):
self.count = 0
def reset(self):
self.count = 0
def increment(self):
self.count = self.count + 1
def get(self):
return self.count
class Undir... |
class Obj(object):
def __init__(self, filename):
with open(filename) as f:
self.lines = f.read().splitlines()
self.vertices = []
self.vfaces = []
self.read()
def read(self):
for line in self.lines:
if line:
prefix, value = line.spl... |
# Consider a row of n coins of values v1 . . . vn, where n is even.
# We play a game against an opponent by alternating turns. In each turn,
# a player selects either the first or last coin from the row, removes it
# from the row permanently, and receives the value of the coin. Determine the
# maximum possible amount o... |
'''
Example: Given an array of distinct integer values, count the number of pairs of integers that
have difference k. For example, given the array { 1, 7, 5, 9, 2, 12, 3 } and the difference
k = 2,there are four pairs with difference2: (1, 3), (3, 5), (5, 7), (7, 9).
'''
def pairs_of_difference(array, diff):
hash... |
numbers_count = int(input())
sum_number = 0
for counter in range(numbers_count):
current_number = int(input())
sum_number += current_number
print(sum_number)
|
# coding=utf-8
def test_common_stats_insert(session):
raise NotImplementedError
def test_duplicate_common_stats_error(session):
raise NotImplementedError
def test_common_stats_default_values(session):
raise NotImplementedError
def test_common_stats_negative_value_error(session):
raise NotImpleme... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.