content stringlengths 7 1.05M |
|---|
class SqsWorkerBaseException(Exception):
"""
All worker exceptions should derived from this base exception
"""
class WorkerAbortSilently(SqsWorkerBaseException):
"""
Called when the worker finds a condition that requires
to abort the task, but without reporting as an actual code error
""... |
__author__ = 'matti'
class Config(object):
DEBUG = False
TESTING = False
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:testipassu@localhost/gachimuchio'
class DebugConfig(Config):
DEBUG = True |
phrase = "Awana Academy"
print("Awana\nAcademy")
print("Awana\"Academy")
print("Awana\Academy")
print(phrase + " is cool")
print(phrase.capitalize())
print(phrase.lower())
print(phrase.upper())
print(phrase.isupper())
print(phrase.upper().isupper())
print(len(phrase))
print(phrase[0])
print(phrase.index("A"... |
# Author: Luis Márquez
# Date: 2021/01/21
# Description:
# This is a simple program in which the "Bubble Sort" algorithm is implemented in Python.
#
# The user enters a number serie and then, this algorithm, is in charge of ordering in a
# increasing or decreasing way the numbers, dependi... |
#!/usr/bin/env python3
with open('AUTHORS', 'r') as authors_file:
authors = list(sorted([x.strip() for x in authors_file]))
with open('Qiskit.bib', 'w') as fd:
fd.write("@misc{ Qiskit,\n")
fd.write(' author = {%s},\n' % ' and '.join(authors))
fd.write(' title = {Qiskit: the Quantum Informa... |
# Copyright 2019, Oath Inc.
# Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms
"""
Screwdrivercd wrappers and utilities to perform code validation
"""
__all__ = ['validate_dependencies', 'validate_package_quality', 'validate_style', 'validate_type', 'validate_unitt... |
#while loop
temp = 0
while(temp < 20):
temp+=1
if(temp>10):
print(temp,"> 10")
print(temp)
# for loops
colors = ['yellow','white','blue','magenta','red']
for color in colors:
print(color)
print(range(10))
for index in range(10):
print(index) |
# alias to Bazel module `toolchains/cc`
load("@rules_nixpkgs_cc//:foreign_cc.bzl", _nixpkgs_foreign_cc_configure = "nixpkgs_foreign_cc_configure")
nixpkgs_foreign_cc_configure = _nixpkgs_foreign_cc_configure
|
def get_just_smaller(arr):
just_smaller_array = [-1] * len(arr)
stack = []
for i in range(len(arr) - 1, -1, -1):
elem = arr[i]
while len(stack) > 0 and elem < arr[stack[-1]]:
index = stack.pop()
just_smaller_array[index] = i
stack.append(i)
return just_s... |
'''
Blind Curated 75 - Problem 71
=============================
Longest Repeating Character Replacement
---------------------------------------
Given a string `s` that consists of only uppercase English letters, you can
perform at most `k` operations on that string.
In one operation, you may choose any character of ... |
### Alumnos agregados por funcion
def insert_alumno(list):
for i in list:
cursor.execute("""insert into
dim_alumno(MRUN, GEN_ALU, FEC_NAC_ALU, INT_ALU, COD_COM)
values(%s,%s,%s,%s,%s)""",(i[0],i[1],i[2],i[3],i[4]))
connection.commit()
# Establecimiento agregados por funcion
def insert_... |
'''
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
6689... |
"""
CONTAINER WITH MOST WATER
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container c... |
lanches = ('hambúrguer', 'suco', 'refri', 'pudim')
print(lanches[2])# VAI MOSTRAR O REFRI, POIS EM PYTHON SE COMEÇA COM 0
print(lanches[0])# VAI MOSTRAR O HAMBÚRGUER
print(lanches[::])# O PRIMEIRO TERMO É O ÍNDECE/ O SEGUNDO É ATÉ ONDE VAI/ O TERCEIRO É DE QUANTAS CASAS VAI PULAR
print(lanches[:2:2])# COMEÇA DO PRIMEIR... |
class CredentialsNotFound(Exception):
"""Credential files not found"""
class MultipleFilesError(Exception):
"""More than one file matching the name given"""
class NotFoundError(Exception):
"""Item not Found"""
class FileExists(Exception):
"""File already exists"""
class FolderExists(Exception):
... |
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def top(self):
if self.is_empty()... |
class WorklogError(ValueError):
pass
class CommandError(WorklogError):
pass
class GitError(WorklogError):
pass
|
# https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/time-calculator
# https://replit.com/@harmonify/time-calculator#time_calculator.py
def add_time(base: str, addon: str, dow: str = "") -> str:
DAYS_OF_WEEK = ("Monday", "Tuesday", "Wednesday",
... |
# 3.6 Excel Spreadsheet - Column Number to Column Name
def excel_column_number_to_name(column_number):
output = ''
index = column_number - 1
while index >= 0:
character = chr((index % 26) + ord('A'))
output = output + character
index = (index / 26) - 1
return output[::-1]
|
class collision():
def rectangle(x, y, target_x, target_y, width=32, height=32, target_width=32, target_height=32):
# Assuming width/height is *dangerous* since this library might give false-positives.
if x >= target_x and (x + width) <= (target_x + target_width):
if y >= target_y an... |
class resultados_raiz:
"""
clase para resultados de los métodos de búsqueda de raíces de
ecuaciones escalares.
"""
def __init__(self, x=None):
# Inicialización del objeto
self.x = x
self.xlist = []
self.convergencia = ''
def __str__(self):
# brinda la po... |
"""
Copyright (c) 2014, Anders S. Christensen,
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the ... |
# THIS FILE IS GENERATED FROM pytsrepr SETUP.PY
short_version = '0.0.1'
version = '0.0.1'
full_version = '0.0.1.dev0+Unknown'
git_revision = 'Unknown'
release = False
if not release:
version = full_version
|
#!/usr/bin/python
class Employee:
empCount = 0
def __init__(self, name, salary, age):
self.name = name
self.salary = salary
self.age = age
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print... |
class Solution(object):
def maxDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
N, M = len(grid), len(grid[0]) if grid else 0
def around(r,c, val):
"""return valid cells around (r, c) whose values are equal to val"""
for (r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Section 4: Region Borders
"""
def B23p_T(T):
"""function B23p_T = B23p_T(T)
Section 4.1 Boundary between region 2 and 3.
Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam 1997 Section 4 Auxiliary Equati... |
class minHeap:
harr=[]
def parent(self,i):
return (i-1)/2
def left(self,i):
return ((2*i)+1)
def right(self,i):
return ((2*i)*2)
def getMin(self):
return self.harr[0]
def replaceMax(self,x):
self.harr[0]=x
minHeapify(0)
def __init__(self,arr,... |
class Vet:
animals = []
space = 5
def __init__(self, name):
self.name = name
self.animals = []
def register_animal(self, animal):
if self.space <= len(self.animals):
return f"Not enough space"
self.animals.append(animal)
Vet.animals.append(animal)
... |
def solution(A):
return 1
if __name__ == '__main__':
print ('Start tests..')
assert solution([1, 5, 2, 1, 4, 0]) == 1
print ('passed!') |
def generate_key_table(key):
table=[]
all_chars=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for char in key:
if char not in table:
if char=='i':
if 'j' not in table and 'i' not in table:
table.append(char)
elif char=='j':
if 'i' not i... |
matriz = [[0, 0, 0], [0, 0, 0,], [0, 0, 0]]
somapar = maior = somacol = 0
for l in range (0, 3):
for c in range(0, 3):
matriz[l][c] = int(input(f'Digite um valor para [{l}, {c}]: '))
print('='*40)
for l in range(0,3):
for c in range(0,3):
print(f'[{matriz[l][c]:^5}]', end='')
if matriz[l... |
n, k, q = map(int, input().split())
correct = [0] * n
# 正解数をカウント
for _ in range(q):
a = int(input())
a -= 1
correct[a] += 1
# (問題数) - (正解数) = (下がる点数)
# これがkより大きければ良い
for i in range(n):
if (q - correct[i]) < k:
print("Yes")
else:
print("No")
|
# https://www.hackerrank.com/challenges/30-sorting/problem
# Inputs
standard_input = """3
3 2 1"""
num = int(input())
# 3
l = [int(s) for s in input().split()]
# 3 2 1
swap_count = 0
for i in range(num):
for j in range(num - i - 1):
if l[j] > l[j + 1]:
tmp = l[j]
l[j] = l[j + 1... |
# -*- coding: utf-8 -*-
def import_oauth_class(m):
m = m.split('.')
c = m.pop(-1)
module = __import__('.'.join(m), fromlist=[c])
return getattr(module, c)
|
"""GrayScale package initialization module.
The GrayScale package is designed to work with shades of gray, namely,
it checks whether a color is a shade of gray and how many values need
to be added to its components to make it so. The shades are taken from
the RGB palette, and the color codes are written in a 16-digit ... |
# coding=utf-8
"""Fixtures for testing gmusicapi_wrapper."""
TEST_SONGS_1 = [
{'artist': 'Muse', 'album': 'Black Holes and Revelations', 'year': 2006, 'track_number': 1, 'title': 'Take a Bow'},
{'artist': 'Muse', 'album': 'Black Holes and Revelations', 'year': 2006, 'track_number': 2, 'title': 'Starlight'}
]
TEST_... |
def init():
global white
global black
global red
global green
global fill
global blue
global yellow
white = [255, 255, 255]
black = [0, 0, 0]
red = [204, 0, 0]
green = [0, 153, 0]
fill = [48, 48, 48]
blue = [15, 176, 255]
yellow = [255, 241, 27]
|
"""
Source: Stack Abuse
Exponential search depends on binary search to perform the final comparison of values. The algorithm works by:
- Determining the range where the element we're looking for is likely to be
- Using binary search for the range to find the exact index of the item
"""
def ExponentialSearch(lys, val)... |
"""
Binary Tree Cameras
You are given the root of a binary tree. We install cameras on
the tree nodes where each camera at a node can monitor its parent,
itself, and its immediate children.
Return the minimum number of cameras needed to monitor all nodes
of the tree.
Example 1:
Input: root = [0,0,null,0,0]
Outp... |
class Main:
def __init__(self):
self.li = []
for i in range(0, 2):
self.li.append(int(input()))
self.salary = float(input())
def totalSalary(self):
return self.li[1] * self.salary
def output(self):
print("NUMBER = {num}".format(num=self.li[0]))
p... |
list('abcd')
list((10, 20, 30))
tuple('abcd')
str(100)
str((10, 20, 30))
max([10, 200, 30])
min([10, 200, 30])
max('hello')
users = ['bob', 'alice', 'john']
for i in range(len(users)): # [0, 1, 2]
print('#%s: %s' % (i, users[i]))
list(enumerate(users)) # 应用时不必转换
for item in enumerate(users):
print('#%s: %s'... |
# see https://www.codewars.com/kata/556196a6091a7e7f58000018/solutions/python
def largest_pair_sum(numbers):
return sorted(numbers)[-1] + sorted(numbers)[-2]
print(largest_pair_sum([10,14,2,23,19]) == 42)
print(largest_pair_sum([-100,-29,-24,-19,19]) == 0)
print(largest_pair_sum([1,2,3,4,6,-1,2]) == 10)
print(l... |
ckpt_path = '../ckpts'
data_path = '../../data'
graph_path = '../graphs'
num_trains = {
'mnist': 60000,
'cifar': 50000,
'fmnist': 60000
}
num_tests = {
'mnist': 10000,
'cifar': 10000,
'fmnist': 10000
}
input_sizes = {
'mnist': 28*28,
'cifar': 3*32*32,
'fmnist': 28*28
}
output_siz... |
"""Python3 Code to solve problem 1254: Number of closed islands.
https://leetcode.com/problems/number-of-closed-islands/
"""
def close_island(grid):
if not grid or len(grid) == 0:
return 0
height, width = len(grid), len(grid[0])
count = 0
for x in range(height):
for y in range(wi... |
#Y = Species("Y",U_Y)
class Species:
def __init__(self, name, U):
self.name = name
#Y.name = "Y"
self.U = U
#Y.U = U_Y
self.behaviour = None
def get_U(self):
return self.U
#Y.get_U returns U_Y
#Y.set_U(U)
def set_U(self, U):
self.U =... |
resposta = ''
vezes = 0
while resposta != 'M' and resposta != 'F':
if vezes > 0:
print('\n\033[31mResposta Inválida. Tente novamente.\033[m\n')
resposta = str(input('Responda:\n\nM - Para masculino\nF - Para feminino\n\n').upper())
vezes = 1
print('\033[32mObrigado! Tenha um bom dia.')
|
display = [[False for i in range(50)] for j in range(6)]
commands = []
while True:
try: line = input()
except: break
if not line: break
commands.append(line)
for command in commands:
if command[:4] == 'rect':
i, j = command.find(' '), command.find('x')
a = command[i+1 : j]
... |
'''
https://www.hackerrank.com/challenges/python-mutations/problem
'''
def mutate_string(s, p, ch):
if p < 0 or p >= len(s):
return s
return s[:p] + ch + s[p+1:]
'''
Reverse String
--------------
Problem:
Given a string, reverse the characters order so that the last at first,
... |
class ReskinPacket:
def __init__(self):
self.type = "RESKIN"
self.skinID = 0
def write(self, writer):
writer.writeInt32(self.skinID)
def read(self, reader):
self.skinID = reader.readerInt32()
|
class Stack:
# Construct an empty Stack object.
def __init__(self):
self._a = [] # Items
# Return True if self is empty, and False otherwise.
def is_empty(self):
return len(self._a) == 0
# Push object item onto the top of self.
def push(self, item):
self... |
"""
A library containing utilities for additive manufacturing.
"""
def dimension(dim: float, tol: int = 0, step: float = 0.4) -> float:
"""
Given a dimension, this function will round down to the
next multiple of the dimension. An additional parameter
`tol` can be specified to add `tol` additional ste... |
def rectangle_area(w, h):
return w * h
width = int(input())
height = int(input())
print(rectangle_area(width, height)) |
a = 1
b = 'abc'
# type -> int -> 1
# type -> str -> 'abc'
# type -> class -> obj
print(type(a))
print(type(int))
print(type(b))
print(type(str))
"""
<class 'int'>
<class 'type'>
<class 'str'>
<class 'type'>
"""
class Student:
pass
class MyStudent(Student):
pass
stu = Student()
print()
print(type(stu))
print... |
class IUserManager:
def logIn(self, userId, password):
raise NotImplementedError
def SignUp(self, userId, password):
raise NotImplementedError
|
display_name = "Myriad Worlds"
library_name = "myriad"
version = "0.5"
author = "Duncan McGreggor, Paul McGuire"
author_email = "oubiwann@twistedmatrix.com"
license = "MIT"
url = "http://github.com/oubiwann/myriad-worlds"
description = "Myriad Worlds Game Server"
long_description = ("An experiment in generating worlds,... |
print("AGENDA do ADS")
menu = "1"
while menu == "1" or menu == "2" or menu == "3":
menu = input("Digite a opção desejada: \n 1 - Cadastrar \n 2 - Consultar \n 3 - Sair \n")
while menu != "1" and menu != "2" and menu != "3":
print("Opção invalida!!! DIGITE NOVAMENTE!!")
... |
def setup_routes(app, handler):
app.router.add_get(
'/browsers/{version}',
handler.browsers,
name='browsers',
)
|
#dicionario chave - valor (arrey de diferentes tipos de dados)
pessoa = {'nome': 'Lea', 'idade': 21}
#print(pessoa['nome'])
#print(pessoa['idade'])
#add uma nova chave ao meu dicionario
pessoa['curso'] = 'computação'
#print(pessoa)
#for chave, valor in pessoa.items():
# print("Chave: " + str(chave))
# print(... |
# McrpType.py
def typedproperty(name, expected_type):
private_name = '_'+name
@property
def prop(self):
return getattr(self, private_name)
@prop.setter
def prop(self, value):
if not isinstance(value, expected_type):
raise TypeError('Expected type {}'.format(exp... |
#
# PySNMP MIB module TVD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TVD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:20:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... |
'''
* Colors for terminal
'''
class COLORS:
# Regular colors
Black = "\033[0;30m"
Red = "\033[0;31m"
Green = "\033[0;32m"
Yellow = "\033[0;33m"
Blue = "\033[0;34m"
Purple = "\033[0;35m"
Cyan = "\033[0;36m"
White = "\033[0;37m"
... |
# me - this DAT
# par - the Par object that has changed
# val - the current value
# prev - the previous value
#
# Make sure the corresponding toggle is enabled in the Parameter Execute DAT.
def onValueChange(par, prev):
# use par.eval() to get current value
parent.save.Par_functions(par)
return
# Called at end of... |
# Formatting configuration for locale sh_YU
languages={'el': u'Gr\u010dki', 'en': 'Engleski', 'co': 'Korzikanski', 'af': 'Afrikanerski', 'sw': 'Svahili', 'ca': 'Katalonski', 'it': 'Italijanski', 'cs': u'\u010ce\u0161ki', 'ar': 'Arapski', 'mk': 'Makedonski', 'ga': 'Irski', 'eu': 'Baskijski', 'et': 'Estonski', 'zh': 'Ki... |
"""
14614. Calculate!
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 68 ms
해결 날짜: 2020년 9월 24일
"""
def main():
A, B, C = map(int, input().split())
print(A^(B if C & 1 else 0))
if __name__ == '__main__':
main() |
print(f"{'='*12} BRANT'STORE {'='*12}")
price = float(input('How much the product costs? $'))
print('''Choose the form of payment:
[1] Cash/check
[2] Credit Card''')
payment = int(input('What is the payment method? '))
if payment == 1:
price -= price * 0.1
print(f'The price will be ${price:.2f}')
elif payment ... |
'''
1부터 100까지 수가 증가하면서
그 수가 3의 배수라면 "Fizz"
5의 배수라면 "Buzz"
15의 배수라면 "FizzBuzz"
나머지 경우는 그 수를 출력
'''
for i in range(1,100+1):
if i%15==0:
print("FizzBuzz")
elif i%3==0:
print("Fizz")
elif i%5==0:
print("Buzz")
else:
print(i)
|
class Solution:
def replaceSpaces(self, S: str, length: int) -> str:
cnt = 0
S = list(S)
cnt += sum((1 for c in S[:length] if c == ' '))
newLen = length + 2 * cnt
#print(length, newLen)
S = S[:newLen]
for i in range(length - 1, -1, -1):
if S[i] ==... |
n = int((input('Digite um número para calcular seu Fatorial: ')))
c = n
f = 1
print(f'Calculando {n}!')
while c > 0:
print(f'{c}', end='')
print(f' x ' if c > 1 else ' = ', end='')
f *= c
c -= 1
print(f'{f}')
|
# DFLOW LIBRARY:
# dflow matrices module
# with zeros and ones
# functions
def zeros(rows, columns):
return [[0]*columns]*rows
def ones(rows, columns):
return [[1]*columns]*rows |
def merge(L, R, arr):
nl = len(L)
nr = len(R)
i, j, k = 0, 0, 0
while i < nl and j < nr:
if L[i] <= R[j]:
arr[k] = L[i]
k += 1
i += 1
else:
arr[k] = R[j]
k += 1
j += 1
def exhaust(index, maxIndex, arrIndex, ar... |
"""
Created on Wed Jul 22 22:27:09 2020
@author: wallissoncarvalho
This file is based on https://github.com/mullenkamp/nasadap
"""
mission_product_dict = {
'gpm': {
'base_url': 'https://gpm1.gesdisc.eosdis.nasa.gov:443',
'process_level': 'GPM_L3',
'version': 6,
'products': {
... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"article_holder": "00_loadarticles.ipynb",
"CoverageTrendsLoader": "00_loadarticles.ipynb",
"dailysourcepermalinksLoader": "00_loadarticles.ipynb",
"describer": "01_descriptive_anal... |
# 请定义一个Book类,属性:name、author、isbn、publisher和price
class Book():
"""Define a Book class
"""
def __init__(self, name, author, isbn, price, publisher="ABC Press"):
"""Init the properties
Args:
name (string): [Book's name]
author (string): [Book's author]
is... |
class ShellException(Exception):
def __init__(self, msg):
self._msg = msg
def __str__(self):
return repr(self._msg)
class ParseException(Exception):
def __init__(self, msg):
self._msg = msg
def __str__(self):
return repr(self._msg)
class TreeException(Exception):
... |
#!/usr/bin/env python
# -*- coding : utf-8 -*-
message = "hello python"
def say():
print(message)
|
'''
Created on 18.05.2018
@author: yvo
'''
class DataReader(object):
'''
Generic main class of all data reader objects used for the GLAMOS data interface.
An inherited data reader object can be specialised for file, database or web-services ...
As main object common to all inherited objects ... |
class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
count = 1
for num in preorder.split(','):
if not count:
return False
elif num != '#':
count += 1
... |
def addBorder(picture):
pictureWithBorder = []
pictureWithBorder.append('*'*(len(picture[0])+2))
for i in range(len(picture)):
pictureWithBorder.append('*' + picture[i] + '*')
pictureWithBorder.append('*'*(len(picture[0])+2))
return pictureWithBorder |
x = 5
for i in range(1,10, 2):
for j in reversed(range(x, x+3)):
print("I={} J={}".format(i,j))
x = x + 2
|
key = 5
message = open("encrypted.txt", "r")
encrypted = message.read()
message.close()
print(encrypted)
print("DECRYPTED: ", " ")
decrypt = []
for i in range(0, len(encrypted)):
decrypt.append(ord(encrypted[i]) - key)
#decrypt[i] = decrypt[i] - key
for i in range(0, len(decrypt)):
decrypt[i] = chr(decry... |
#from enum import Enum
# Enum only in Python >= 3.4
#class Operator(Enum):
class Operator(object):
And = 0
Equal = 1
GreaterEqual = 2
Greater = 3
LessEqual = 4
Less = 5
NotEqual = 6
Or = 7
Between = 8
Contains = 9
EndsWith = 10
Is = 11
IsNot = 12
Like = 13
Ma... |
"""
Offer a significant performance boost; it is most effective in
situations where the cost of initializing a class instance is high, the
rate of instantiation of a class is high, and the number of
instantiations in use at any one time is low.
"""
class ReusablePool:
"""
Manage Reusable objects for use by Cl... |
__author__ = "IceArrow256"
__version__ = '4'
def union(first, second):
result = set()
for i in first:
result.add(i)
for i in second:
if i not in result:
result.add(i)
return result
def intersection(first, second):
result = set()
for i in first:
if i in sec... |
__all__ = ["InvalidUnrestrictedGrammarFormatException"]
class InvalidUnrestrictedGrammarFormatException(Exception):
pass
|
def greet(firstName='', middleName='', lastName=''):
print('Hello, ' + lastName + ', ' + middleName + ' ' + firstName)
greet('Michael', 'G', 'Bay') # supplying parameters in a specific sequence
greet('Michael', 'G') # skipping lastName parameter
greet() # skipping all parameters
# specifying the custom sequen... |
# Maze in a 85x85 grid
# Nodes: 1231
# Edges: 1280
adjList = [
[41, 1],
[27, 0],
[55, 3],
[57, 4, 2],
[87, 3],
[22, 6],
[59, 7, 5],
[60, 6],
[30, 9],
[32, 8],
[44, 11],
[46, 10],
[47, 13],
[34, 12],
[77, 15],
[36, 14],
[89, 17],
[67, 18, 16],
... |
global N
N = 4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j], end = " ")
print()
def isSafe(board, row, col):
# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1... |
"""
Pointers do not exist in Python.
If you want to know why i recommend reading this article:
https://realpython.com/pointers-in-python/
""" |
marks = int(input("What is you marks in Math: "))
def show_grade(grade):
print(f"You got: {grade}")
if marks >= 80:
show_grade("A+")
elif marks >= 70:
show_grade("A")
elif marks >= 60:
show_grade("A-")
elif marks >= 50:
show_grade("B")
elif marks >= 40:
show_grade("C")
else:
show_grade("... |
# we are given a 2d matrix of 0s and 1s where 0 represents water and 1 represents land.
# any chunk of land disconnected from the borders(edges) of matrix is considered an island.
# The task is to remove all the islands from the matrix.
# Example
# [1, 0, 0, 0, 0, 0] [1, 0, 0, 0, 0, 0]
# [0, 1, 0, 1, 1, 1] [0, 0, 0,... |
class Solution:
def isValid(self, s):
if not s: # empty string is valid
return True
stack = []
for ch in s:
if ch == '(' or ch == '[' or ch == '{': # push opening brackets onto stack
stack.append(ch)
elif not stack: # if stack is empty then cannot pop needed closing bracket
return False # st... |
frase = str(input ('Digite uma frase:\n')).strip()
frase = frase.upper()
qtsA = frase.count('A')
pA = frase.find('A') + 1
uA = frase.rfind('A') + 1
print(f'\nNa sua frase existe {qtsA} letras As')
print(f'A primeira letra A aparece na posição {pA}!')
print (f'A última letra A aparecer na posição {uA}!') |
class DenseNetConfig(object):
# number of groups for group normalization
numGroups = 8
compressionRate = .5
growthRate = 32
# number of conv blocks
numBlocks = [6, 12, 24, 16]
|
class WeAre():
fl = False
_count = 0
def __init__(self):
WeAre.fl = True
WeAre._count += 1
WeAre.fl = False
@property
def count(self):
return WeAre._count
@count.setter
def count(self, value):
if WeAre.fl:
print("SAS")
WeA... |
def prestamo(informacion: dict)-> dict:
id_prestamo = informacion['id_prestamo']
casado = informacion['casado']
dependientes = informacion['dependientes']
educacion = informacion['educacion']
independiente = informacion['independiente']
ingreso_deudor = informacion['ingreso_deudor']
ic... |
MAJOR = 0
MINOR = 5
MICRO = 2
__version__ = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
|
if __name__ == '__main__':
with open('input', 'r') as file:
outputs = []
for line in file.readlines():
vals = line.split('|')
outputs.extend(vals[1].split())
print(len([x for x in outputs if len(x) in [2, 3, 4, 7]]))
|
def get_credentials_from_vault(path):
# TODO
pass
|
def pangram(s):
a = "abcdefghijklmnopqrstuvwxyz"
for i in a:
if i not in s.lower():
return False
return True
pan_Str = input("Enter the String : ")
if(pangram(pan_Str) == True):
print("Pangram Exists")
else:
print("Pangram Not Exists")
|
class Solution:
def XXX(self, digits: List[int]) -> List[int]:
s = digits[::-1]
i = 0
if s[0]+1 < 10:
s[0] += 1
else:
while s[i]+1 >= 10:
s[i] = 0
i += 1
if i != len(s):
s[i] += 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.