content stringlengths 7 1.05M |
|---|
#!/usr/bin/python
# height2.py
print ('Height: %.2f %s' % (172.3, 'cm'))
print ('Height: {0:.2f} {1:s}'.format(172.3, 'cm'))
|
"""
Crie um programa que Simule o funcionamento de um caixa eletrônico. No inicio, pergunte ao usuario qual será o valor a
ser sacado (numero inteiro) e o programa vai verificar quantas cédulas de cada valor serão entregues. Considere
que o caixa possui cédulas de 50, 20, 10 e 1.
"""
print('=' * 40)
print('BANCO FSR'.... |
#
# PySNMP MIB module EFM-CU-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/EFM-CU-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:11:39 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( OctetS... |
# (c) 2021 Leon Luithlen
# This code is licensed under MIT license
def strongly_typed(*args, **kwargs):
stargs = args
stkwargs = kwargs
def type_strongly(func):
def wrapper(*args, **kwargs):
for arg, type_ in zip(args, stargs):
assert isinstance(arg,type_), f"{arg} should be of type {type_}"
for kw, a... |
# ==== Start of helper classes to be used by TriggerExtractorResultCollection ====
class DocumentPrediction(object):
def __init__(self, docid):
self.docid = docid
self.sentences = dict()
""":type: dict[str, SentencePrediction]"""
def to_json(self):
d = dict()
d['docid'] ... |
"""
Task 1
FizzBuzz has been used as a common challenge during programmer interviews, it requires the
interviewee to write code that prints the numbers between 1 and 100 with the following rules:
•If a number is divisible by 3, print “Fizz”
•If a number is divisible by 5, print “Buzz”
•If a number is divisibl... |
"""
https://leetcode.com/problems/reshape-the-matrix/
566. Reshape the Matrix (Easy)
"""
class Solution:
def matrixReshape(self, mat, r, c):
m = len(mat)
n = len(mat[0])
if m*n != r*c:
return mat
rLoc = 0
cLoc = 0
result = []
row = []
... |
'''
A string with parentheses is well bracketed if all parentheses are matched: every opening bracket has a matching closing bracket and vice versa.
Write a Python function wellbracketed(s) that takes a string s containing parentheses and returns True if s is well bracketed and False otherwise.
Hint: Keep track of the ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 29 16:51:16 2019
@author: linyizi
"""
|
# Models are decision tree
# Batandwa Mgutsi
# 12/03/2020
class DecisionCase:
"""A Decision case has a sentence and a set of two other decision cases to execute on yes and on no"""
"""answers by the user in case the DecisonCase requires input"""
sentence = None
requiresAnswer = True
yesCase = No... |
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
length = len(cost)
dp = [0 for x in range(0, length)]
dp[0] = cost[0]
dp[1] = cost[1]
for i in range(2, length):
# Remember to divided ... |
print('\033[1;93m=-=-=-=- \033[1;94mAula de tuplas \033[1;93m=-=-=-=\033[m')
#Tuplas são imutáveis
lanche = ('hamburguer', 'suco', 'pizza', 'pudim')
print(lanche[2])
print(lanche[0:2])
print(lanche[1:])
print(lanche[-1])
print(len(lanche))
print(' ')
lanche = ('hamburguer', 'suco', 'pizza', 'pudim')
for c in lanche:... |
PLURAL_KEYS = (
"view",
"measure",
"dimension",
"dimension_group",
"filter",
"access_filter",
"bind_filters",
"map_layer",
"parameter",
"set",
"column",
"derived_column",
"include",
"explore",
"link",
"when",
"allowed_value",
"named_value_format",
... |
A = 26
MOD = 1_000_000_007
def shortPalindrome(s):
c1 = [0] * A
c2 = [[0] * A for _ in range(A)]
c3 = [0] * A
res = 0
for i in (ord(c) - 97 for c in s):
res = (res + c3[i]) % MOD
for j in range(A):
c3[j] += c2[j][i]
for j in range(A):
c2[... |
"""Exceptions for downtoearth.
These are helpers provided so that you can raise proper HTTP code errors from your API.
Usage:
from downtoearth.exceptions import NotFoundException
raise NotFoundException('your princess is in another castle')
"""
class BadRequestException(Exception):
def __init__(self, ms... |
class Solution:
def isPalindrome(self, x: int) -> bool:
i = 0
str_x = str(x)
n = len(str_x)
while i < n-i-1:
if str_x[i] != str_x[n-i-1]:
return False
i += 1
return True |
"""2017 Advent of Code, Day 2"""
with open("input", "r+") as file:
puzzle_input = file.readlines()
SPREADSHEET = []
CHECKSUM = 0
CHECKSUM_2 = 0
for row in puzzle_input:
SPREADSHEET.append([int(value) for value in row.strip().split()])
for row in SPREADSHEET:
row.sort()
CHECKSUM += row[-1] - row[0]
f... |
class Solution:
def getSkyline(self, buildings: [[int]]) -> [[int]]:
if not buildings:
return []
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
mid = len(buildings) // 2
left = self.getSkyline(buildings[:mid])
... |
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
def valid(sub):
nums = [item for item in sub if item.isdigit()]
return len(set(nums)) == len(nums)
def check_row():
return al... |
class Node (object):
def __init__(self, leaf, num_spaces=4):
self.name = leaf[0]
self.num_spaces = num_spaces
leaves = leaf[1:]
if len(leaves):
self.leaves = [Node(leaves, num_spaces)]
else:
self.leaves = None
# Returns true when the leaves are a... |
# isr1.py - Timer to activate units in a cycle
# The 7-segment units are controlled one-by one in a cycle, using a timer interrupt for consistent light output.
# Model 1: every timer interrupt, the control switches from one unit to the next.
# User configuration
framebuf = "ABCD" # User configuration: desir... |
letters = {}
for c in input():
if c in letters:
letters[c] += 1
else:
letters[c] = 1
max_double = max(letters.values())
if max_double == 1:
print(len(letters))
for l in letters:
print(l)
exit(0)
if list(letters.values()).count(max_double) == 1:
print(1)
for l, k in... |
#Generate Christmas Tree Pattern
# Generating Triangle Shape
def triangleShape(n):
for i in range(n):
for j in range(n-i):
print(' ', end=' ')
for k in range(2*i+1):
print('*',end=' ')
print()
# Generating Pole Shape
def poleShape(n):
for i in range(n):
... |
"""A set of function(s) that are used for estimating frame per second (fps).
These function(s) often receive an inference time, perform some calculation on it.
The function(s) do return a fps value.
"""
def convert_infr_time_to_fps(infr_time: float) -> int:
# Gets the time of inference (infr_time) and returns F... |
class Node():
"""Building Block of Linked List."""
def __init__(self, data):
"""Initialize Node.
Args:
data: The data to be stored.
"""
self.data = data
self.next = None
def __str__(self):
"""String representation of Node."""
return "(... |
# check if a number is odd or even
num = int(input("Enter a number: "))
if num%2: # note that it is not checked with ==; result of %2 is 0 or 1 which can be translated as False or True
print("The number is odd")
else:
print("The number is even") |
# zwei 06/16/2014
# inspired by sympy.utilities.iterables.kbins.partition()
def partition(lista, bins):
# EnricoGiampieri's partition generator from
# http://stackoverflow.com/questions/13131491/
# partition-n-items-into-k-bins-in-python-lazily
if len(lista) == 1 or bins == 1:
yield [lista]
... |
"""
Writing a Function that accepts 2 parameters.
Draws a playing board based on the rows and columns input
GitHub : @ChaitanyaJoshiX
"""
def DrawingBoard(rows, columns):
for i in range(rows):
if i%2 == 0:
for j in range(columns):
if j%2 == 0:
if j!=... |
class Solution:
def romanToInt(self, s: str) -> int:
roman = {'I': 1,'V': 5,'X': 10, 'L': 50,'C': 100,'D': 500,'M': 1000}
exception = {'IV': 4,'IX': 9,'XL': 40,'XC': 90,'CD': 400,'CM': 900}
intnum = 0
for exc in exception:
if exc in s:
intnum = intnum + e... |
class Simbolo:
def __init__(self,tipo,nombre,posicion,ambito,dimensiones=0):
self.tipo=tipo
self.nombre=nombre
self.posicion=posicion
self.ambito=ambito
self.dimensiones=dimensiones |
pytest_plugins = [
'aioclustermanager.tests.fixtures'
]
|
class Result(dict):
"""Result dict. Behaves 'immutable' to the Feature.process method.
Just a simple dict to hold the results from features.
"""
__slots__ = ()
def __setitem__(self, *args):
raise TypeError('`Result` object does not support item assignment.')
def _setitem(self, key, v... |
"""
Simple dependencies between tests.
"""
def test_no_skip(ctestdir):
"""One test is skipped, but no other test depends on it,
so all other tests pass.
"""
ctestdir.makepyfile("""
import pytest
@pytest.mark.dependency()
def test_a():
pytest.skip("explicit skip")
... |
# URI Online Judge 1117
nota1, nota2 = -1, -1
continuar = 1
while continuar == 1:
nota1, nota2 = -1, -1
while nota1 < 0 or nota1 > 10:
nota1 = float(input())
if nota1 < 0 or nota1 > 10:
print("nota invalida")
while nota2 < 0 or nota2 > 10:
nota2 = float(input())
... |
# -*- coding: utf-8 -*-
#
# Copyright © 2021–2022 martin f. krafft <tctools@pobox.madduck.net>
# Released under the MIT Licence
#
_PyBaseException = BaseException
class BaseException(_PyBaseException):
pass
class InvalidDataError(BaseException):
pass
|
result = set()
for *features, label in DATA[1:]:
species = label.pop()
if species.endswith(SUFFIXES):
result.add(species)
|
# Work out the first ten digits of the sum of
# the following one-hundred 50-digit numbers.
num_str = "37107287533902102798797998220837590246510135740250\
46376937677490009712648124896970078050417018260538\
74324986199524741059474233309513058123726617309629\
91942213363574161572522430563301811072406154908250\
23067588... |
class Out():
def __init__(self):
self.log_level = 0
def print(self, msg):
print(msg)
def log(self, level, msg):
if level >= self.log_level:
return
else:
output = ""
if level == 1:
output = "[VERBOSE] "
elif le... |
number_of_test_cases = int(input().strip())
for _ in range(number_of_test_cases):
try:
a, b = map(int, input().strip().split(" "))
print(a // b)
except Exception as e:
print("Error Code:", e)
|
def printArray(array):
print(" ")
for itemNum in range(0, len(array)):
print("#" + str(itemNum) + ": " + str(array[itemNum]))
def linearSearch(array, find):
foundInd = -1
found = False
time = 0
while time < len(array) and not found:
if array[time] == find:
print... |
# TODO
# Have not even started one bit but easy once get the other part done
# https://bsmg.wiki/mapping/map-format.html#events-2
# Get the Melograph
# Translate the graph to the events
# Write the results to the file
# Onset Can create a idea of where to put the beats
# https://librosa.org/doc/latest/generated/lib... |
class GroupHelper:
def __init__(self,app):
self.app = app
def return_to_group_page(self):
wd = self.app.wd
wd.find_element_by_link_text("group page").click()
def creator(self, group):
wd = self.app.wd
# open_gp
wd.find_element_by_link_text("groups").click()
# init_group_creator
wd.find_element_by_... |
'''
Faça um programa que leia as notas referentes às duas avaliações de um aluno. Calcule e imprima a média semestral.
Faça com que o algoritmo só aceite notas válidas (uma nota válida deve pertencer ao intervalo [0,10]). Cada nota deve
ser validada separadamente.
Entrada = A entrada contém vários valores reais, positi... |
class category(object):
def __init__(self, id=None, account=None, name=None,
description=None, parent=None,
selectable=True, active=True):
self.id = id
self.account = account
self.name = name
self.description = description
self.parent = parent
self.selectable = s... |
# Faça um programa que leia um número Inteiro e mostre na tela o seu sucessor e seu antecessor.
n1 = int(input('Digite um número: '))
ant = n1 - 1
suc = n1 + 1
print('O seu antecessor é {} e seu sucessor é {}'.format(ant, suc))
|
"""
Fixed and improved version based on "extracting from C++ doxygen documented file Author G.D." and py++ code.
Distributed under the Boost Software License, Version 1.0. (See
accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
"""
class doxygen_doc_extractor:
"""
Extracts Doxyg... |
#Project Euler Problem-52
#Author Tushar Gayan
def f(num_1,num_2): #Checks same digit
num_list_1 = [int(i) for i in str(num_1)]
num_list_2 = [int(i) for i in str(num_2)]
num_list_1.sort();num_list_2.sort()
if num_list_1 == num_list_2:
return True
else:
return False
n = 1
while f(n... |
"""
breadcrumbs.namedobject
~~~~~~~~~~~~~~~~~~~~~~~
Sentinels with good representation.
:copyright: 2021 by breadcrumbs Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
class NamedObject(object):
"""A class to construct named sentinels."""
def __in... |
# problem : https://leetcode.com/problems/coin-change-2/
# time complexity : O(NM)
# algorithm : DP
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
if amount == 0 and len(coins) == 0:
return 1
dp = [[0] * (amount + 1)] * (len(coins) + 1)
for coinInd in ra... |
def main():
with open("day1/input.dat") as f:
expenses = [int(n) for n in f.readlines()]
result = None
for a in expenses:
for b in expenses:
if a + b == 2020:
result = a*b
break
return result
if __name__ == "__main__":
print(main()) |
d = {
'name': 'setayesh',
'last_name': 'pasanadideh',
'age': 14,
'b_p': 'tehran',
'p': print,
'wear_glass': False
}
print(d)
print(d['last_name'])
d['p']( 'amirreza') |
COCO_PERSON_SKELETON = [[2, 3], [3,4], [4, 5], [2, 6], [6,7], [7,8], [2,1]]
COCO_KEYPOINTS = [
'nose', # 1
'left_eye', # 2
'right_eye', # 3
'left_ear', # 4
'right_ear', # 5
'left_shoulder', # 6
'right_shoulder', # 7
'left_elbow', # 8
... |
'''
Escopo Global e Local
não se pode alterar a variavel global dentro de uma função
para uma variavel local ser alterado use a palavra global => NÃO É UMA BOA PRÁTICA NÃO DEVE-SE FAZER
'''
variavel = 'valor'
def func():
print(variavel)
def func2():
# global variavel
variavel = 'Outro valor'
print(v... |
class StaticConnection():
def __init__(self, src, dst, bandwidth, delay, loss):
self.src = src
self.dst = dst
self.bandwidth = bandwidth
self.delay = delay
self.loss = loss |
{
'conditions' : [
[ 'skia_os != "ios"', {
'error': '<!(set GYP_DEFINES=\"skia_os=\'ios\'\")'
}],
],
'targets': [
{
'target_name': 'SimpleiOSApp',
'type': 'executable',
'mac_bundle' : 1,
'include_dirs' : [
'../experimental/iOSSampleApp/Shared',
],
'sou... |
vogais = {
'a': 0,
'e': 0,
'i': 0,
'o': 0,
'u': 0
}
texto = str(input('insira um texto: ')).strip().lower()
for letra in texto:
if letra in 'a':
vogais['a'] += 1
elif letra in 'e':
vogais['e'] += 1
elif letra in 'i':
vogais['i'] += 1
elif letra in 'o':
... |
# Copyright 2014 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
alien_0 = {'color': 'green', 'points': 5} #create a dictionary
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
print(alien_0)
alien_0['x_position'] = 0 # add to the dictionary
alien_0['y_position'] = 25 # add to the dictionary
... |
class SETTINGS:
__slots__ = ("TOKEN","DB_NAME")
def __init__(self):
self.TOKEN = '415193750:AAFNBxqmF5ow24TwzuJlzYKpYSPmt_K5p_A'
self.DB_NAME = 'vk2tl.db'
|
###############################################################################
#
# $Id$
#
###############################################################################
__all__ = ["client","constants","file_list","enq_message","messages","md_client","mw_client","pe_client"]
|
class Node(object):
def __init__(self, id):
self.id = id
self.vec = []
self.neighbours = []
def add_neighbour(self, node_id):
self.neighbours.append(node_id)
class Graph(object):
def __init__(self):
# id -> node
self.nodes = {}
self.edges = []
... |
n = int(input())
matrix = [[int(n) for n in input().split(", ")] for _ in range(n)]
flat_matrix = [number for row in matrix for number in row]
print(flat_matrix)
|
INTENT = "intent"
INTENTS = "intents"
ENTITIES = "entities"
UTTERANCES = "utterances"
USE_SYNONYMS = "use_synonyms"
SYNONYMS = "synonyms"
DATA = "data"
VALUE = "value"
TEXT = "text"
ENTITY = "entity"
SLOT_NAME = "slot_name"
TRUE_POSITIVE = "true_positive"
FALSE_POSITIVE = "false_positive"
FALSE_NEGATIVE = "false_negati... |
def to_hex(hh: bytes, for_c=False):
hex_values = ("{:02x}".format(c) for c in hh)
if for_c:
return "{" + ", ".join("0x{}".format(x) for x in hex_values) + "}"
else:
return " ".join(hex_values)
|
IP =input("enter your ip address ")
count_seg = 0
len_seg = 0
i = ''
for i in range(0,len(IP)):
if(IP[i] =='.'):
print("segment {} contain {} characters".format(count_seg+1,len_seg))
count_seg += 1
len_seg = 0
else:
len_seg +=1
if i != "." :
print("segment... |
"""Custom errors goes here"""
class Error(Exception):
"""Base error class"""
pass
class InvalidUserInput(Error):
"""Exception raised for invalid user input"""
pass
|
numero=int(input("Digite numero: "))
if(numero%2==0):
print("el numero es par")
else:
print("el numero es impar")
|
# could be set as random or defined by node num
def getdelay(source,destination,size):
return 1
def getdownloadspeed(id):
return 1000 |
def has_print_function(tokens):
p = 0
while p < len(tokens):
if tokens[p][0] != 'FROM':
p += 1
continue
if tokens[p + 1][0:2] != ('NAME', '__future__'):
p += 1
continue
if tokens[p + 2][0] != 'IMPORT':
p += 1
continu... |
#*--------------------------------------------------
#* decorator.py
#* excerpt from https://refactoring.guru/design-patterns/decorator/python/example
#* ejemplo obtenido desde el canal de youtube BettaTech: https://www.youtube.com/watch?v=Ab9HxiPLryg
#*--------------------------------------------------
# COMPONENTE
c... |
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 450
SCREEN_CENTER = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
BUTTON_COLOR = (0, 0, 0)
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 50
BALL_WIDTH = 10
BALL_HEIGHT = 10
AUDIO_ICON_WIDTH = 20
AUDIO_ICON_HEIGHT = 20
AUDIO_ICON_X = SCREEN_WIDTH - AUDIO_ICON_WIDTH
AUDIO_ICON_Y = SCREEN_HEIGHT - AUDI... |
# Source : https://leetcode.com/problems/longest-continuous-increasing-subsequence/
# Author : foxfromworld
# Date : 07/12/2021
# First attempt
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
start, ret = 0, 0
for i, num in enumerate(nums):
if i > 0 and nums[i-1] >=... |
def print_translation(args):
"""
Parses calls to print to convert to the C++ equivalent
Parameters
----------
args : list of str
List of arguments to add to the print statement
Returns
-------
str
The converted print statement
"""
return_str = "std::cout << "
... |
"""
protocolDefinitions.py
The following module consists of a list of commands or definitions to be used in the communication between devices and the control system
Michael Xynidis
Fluvio L Lobo Fenoglietto
09/26/2016
"""
# Definition Name Valu... |
"""
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right... |
"""
Copyright (R) @huawei.com, all rights reserved
-*- coding:utf-8 -*-
CREATED: 2020-6-04 20:12:13
MODIFIED: 2020-6-06 14:04:45
"""
SUCCESS = 0
FAILED = 1
ACL_DEVICE = 0
ACL_HOST = 1
MEMORY_NORMAL = 0
MEMORY_HOST = 1
MEMORY_DEVICE = 2
MEMORY_DVPP = 3
# error code
ACL_ERROR_NONE = 0
ACL_ERROR_INVALID_PARAM = 100000... |
# -*- coding: utf-8 -*-
########################################################################
#
# License: BSD
# Created: 2005-12-01
# Author: Ivan Vilata i Balaguer - ivan@selidor.net
#
# $Id$
#
########################################################################
"""Utility scripts for PyTables.
... |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"\n",
"from finnhub.exceptions import FinnhubAPIException\n",
"from finnhub.exceptions import FinnhubRequestException\n",
"\n",
"class Client:\n",
" ... |
class ObjectList(object):
""""""
def __init__(self):
self._items = []
def __getitem__(self, index):
if index >= 0 and index < len(self._items):
return self._items[index]
else:
raise IndexError()
def __len__(self):
return len(self._items)
de... |
# Comment1
class Module2(object):
command_name = 'module2'
targets = [r'products/module2_target.txt']
dependencies = [('module1_target.txt', True)]
configs = ['module2a.conf', 'module2b.conf']
|
'''
Created on 2016年2月16日
@author: Darren
'''
'''
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Your algorithm s... |
class ValidDate(object):
@classmethod
def special_char(self,char):
"""Check to see if char is in a list of special date chars
"""
if(char == '-'):
return True
else:
return False
@classmethod
def check_and_store(self,char):
"""Check to se... |
# pylint: disable=line-too-long
"""
Implement a compiler for the interpreter developed in Exercise 12, Problem 1.
The program should be compiled in a language based on operand stack.
The following operations are supported:
* ``CONST c``: push the value ``c`` on the stack,
* ``LOAD v``: load the value of the variable ... |
n = int(input())
arr = list(map(int, input().rstrip().split()))
arr.reverse()
for num in arr:
print(num , end=" ")
|
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def get_name(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, source, destination):
"""Assumes source and destinat... |
"""
You want to find people who have as much exposure to different cultures as yourself.
Complete the uncommon_cities helper that takes the cities you have visited (my_cities) and the cities the other person has visited (other_cities) and returns the number of cities that both sequences do NOT have in common.
So give... |
M = ContF = cont = 0
while True:
idade = int(input('Idade:'))
sexo = 't'
while sexo not in 'mf':
sexo = str(input('Sexo:[M/F] ')).lower().strip()[0]
if idade > 18:
cont+=1
if sexo in 'f' and idade < 20:
ContF+= 1
if sexo in 'm':
M += 1
escolha = 't'
... |
## Advent of Code 2018: Day 14
## https://adventofcode.com/2018/day/14
## Jesse Williams
## Answers: [Part 1]: 8176111038, [Part 2]: 20225578
INPUT = 890691
def createNewRecipes(recipes, elves):
newRcpSum = recipes[elves[0]] + recipes[elves[1]] # add current recipes together
newRcpDigits = list(map(int, lis... |
#!/usr/local/bin/python3.6
def is_ztest(m):
if int(m.author.id) == int(zigID):
return True
else:
return False
|
def read_matrix(c, r):
matrix = []
for _ in range(c):
row = input().split(' ')
matrix.append(row)
return matrix
c, r = [int(n) for n in input().split(' ')]
matrix = read_matrix(c, r)
matches = 0
for col in range(c - 1):
for row in range(r - 1):
if matrix[col][row] == matrix[... |
# Option for variable 'simulation_type':
# 1: cylindrical roller bearing
# 2:
# 3: cylindrical roller thrust bearing
# 4: ball on disk (currently not fully supported)
# 5: pin on disk
# 6: 4 ball
# 7: ball on three plates
# 8: ring on ring
# global simulation setup
simulation_type = 5 # one of the above types
simulat... |
BUSINESS_METRICS_VIEW_CONFIG = {
'Write HBase' : [['write operation', 'Write/HBase'],
['log length', 'Write/Log'],
['memory/thread', 'Write/MemoryThread'],
],
'Read HBase' : [['read operation', 'Read/HBase'],
['result size', 'Read/ResultSize'],
... |
n=int(input())
for i in range(1,n):
if i+sum(map(int,list(str(i))))==n:
print(i)
exit()
print(0) |
"""
Doctests
You have the option to write tests into your docstring in python.
"""
def add(a, b):
"""
>>> add(2, 3)
5
>>> add(100, 200)
300
"""
return a + b
# command line command to run the doctests:
# python -m doctest -v filename.py |
edge_array = [];
par =[0,0,0,0,0,0]
for par[0] in range(0,3):
for par[1] in range(0,3):
for par[2] in range(0,3):
for par[3] in range(0,3):
for par[4] in range(0,3):
for par[5] in range(0,3):
edge_array.append(str(par[0])+" "+str(par[1])+" "+str(par[2])+" "+str(par[3])+" "+str(par[4])+" "+str(par[5... |
""" Steinhaus-Johnson-Trotter algorithm """
def SJT_gen(n: int):
"""Generate the swaps for the Steinhaus-Johnson-Trotter algorithm.
Args:
n (int): [description]
Returns:
[type]: [description]
Yields:
[type]: [description]
"""
if n == 2:
yield 0
yield ... |
# -*- coding: utf-8 -*-
class Node(object):
def __init__(self, type_, value, children=None):
self.type = type_ # Options: 'operator', 'identifier', 'value'
self.value = value
self.children = children or []
def dump(self, recursive=False):
"""Return a formatted dump of the tr... |
levels = {
1: {
'ship': (80, 60),
'enemies': ((24, 24), (50, 24), (100, 24), (120, 24))
},
2: {
'ship': (80, 110),
'enemies': ((10, 10), (80, 10), (150, 10),
(10, 30), (80, 30), (150, 30))
},
3: {
'ship': (10, 60),
'enemies': ((90, ... |
class HttpRequest:
def __init__(self, path, method, headers, path_params, query_params, body):
self.path = path
self.method = method
self.headers = headers
self.path_params = path_params
self.query_params = query_params
self.body = body
|
"""
3.2 Stack Min: How would you design a stack which, in addition to push and pop, has a function min
which returns the minimum eiement? Push, pop and min should ail operate in 0 ( 1 ) time.
"""
"""
Solution --> keep track of what is min at each stage of opertaion
"""
class Stack:
def __init__(self):
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.