content stringlengths 7 1.05M |
|---|
def is_in_interval(n):
return (-15 < n <= 12) or (14 < n < 17) or (19 <= n)
print(is_in_interval(int(input())))
|
class UniBrokerMessageManager:
def reject(self) -> None:
raise NotImplementedError(f'method reject must be specified for class "{type(self).__name__}"')
def ack(self) -> None:
raise NotImplementedError(f'method acknowledge must be specified for class "{type(self).__name__}"')
|
__all__ = (
"Node",
"DefinitionNode",
"ExecutableDefinitionNode",
"TypeSystemDefinitionNode",
"TypeSystemExtensionNode",
"TypeDefinitionNode",
"TypeExtensionNode",
"SelectionNode",
"ValueNode",
"TypeNode",
)
class Node:
__slots__ = ()
class DefinitionNode(Node):
__slo... |
class Sort:
col_id: str
sort: str
def __init__(self, col_id, sort):
self.col_id = col_id
self.sort = sort
@staticmethod
def from_json(json: dict):
if not json:
raise Exception('Error. Sort was not defined but should be.')
sort = Sort()
# colId... |
ANIMALS = [
"aardvark",
"aardwolf",
"albatross",
"alligator",
"alpaca",
"amphibian",
"anaconda",
"angelfish",
"anglerfish",
"ant",
"anteater",
"antelope",
"antlion",
"ape",
"aphid",
"armadillo",
"asp",
"baboon",
"badger",
"bandicoot",
"... |
# Name of the campaign
CampaignName = 'iview-campaign'
# Name of the parser module. The parser module must be
# in the chromosome/parsers directory.
Parser = 'PNG'
# The path of the initial corpus
InitialPopulation = 'C:\\tmp\\png'
# The fitness algorithms that will be used by Chronzon
# and the weight of each one. ... |
# https://www.acmicpc.net/problem/10872
def n_fac(n):
if n==1:
return 1
else:
return n * n_fac(n-1)
n = int(input())
if n == 0:
print(1)
else:
print(n_fac(n)) |
class TestRequest_certs():
def test_request_certs(self):
return
|
print('MAIOR E MENOR NÚMERO')
a = int(input('Digite um número inteiro: '))
b = int(input('Digite outro número inteiro: '))
c = int(input('Digite outro: '))
#VERIFICANDO O MENOR NÚMERO:
if a<c and a<b:
menor = a
if b<c and b<a:
menor = b
if c<b and c<a:
menor = c
#VERIFICANDO O MAIOR NÚMERO:
if a > c and a >... |
def complement(l):
"Compute the complement of the literal L."
if isinstance(l, str):
return ('¬', l)
else:
return l[1]
def extractVariable(l):
"Extract the propositional variable from the literal L."
if isinstance(l, str):
return l
else:
return l[1]
def arb(S):
... |
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
dic = {}
for char in s:
dic[char] = dic.get(char,0)+1
res = []
for char in s:
dic[char] -= 1
if char not in res:
while res and char<res[-1] and dic[res[-1]]>0:
... |
VERSION_NAME = "tmtccmd"
VERSION_MAJOR = 1
VERSION_MINOR = 10
VERSION_REVISION = 2
# I think this needs to be in string representation to be parsed so we can't
# use a formatted string here.
__version__ = "1.10.2"
|
def caesar_encrypt(word,n):
c = ''
for i in word:
if (not i.isalpha()):
c += i
elif (i.isupper()):
c += chr((ord(i) + n-65) % 26 + 65)
else:
c += chr((ord(i) + n - 97) % 26 + 97)
return c
def caesar_decrypt(word,n):
c = ''
for i in word:
... |
def parOuImpar(n=0):
if n % 2 ==0:
return True
else:
return False
num = int(input("Digite um numero: "))
if parOuImpar(num):
print("E par!")
else:
print("Nao e par!")
|
# coding=utf-8
def yes_no_input():
while True:
choice = raw_input("This will read open or close information 'Type anything': ").lower()
if choice in ['運行', '全面滑走可能', '平常運転','○','● ','open','OPEN','Open','◎','◯','一部滑走可能']:
return True
elif choice in ['運休','時間外','運転見合わせ','close',... |
# Subtract numbers module
class Calculate:
def sub(a, b):
"""Substract two numbers"""
return a - b
def add(a, b):
"""Add two numbers"""
return a + b
def mult(a, b):
"""Product of two numbers"""
return a * b
def div(a, b):
"""Divide two numbers"""
return a / b
|
inputs = [1, 2, 3, 2.5]
weights1 = [0.2, 0.8, -0.5, 1.0]
weights2 = [0.5, -0.91, 0.26, -0.5]
weights3 = [-0.26, -0.27, 0.17, 0.87]
bias1 = 2
bias2 = 3
bias3 = 0.5
output = [ inputs[0]*weights1[0] + inputs[1]*weights1[1] + inputs[2]*weights1[2] + inputs[3]*weights1[3] + bias1,
inputs[0]*weights... |
x=[]
for i in range(4):
x.append(int(input()))
x.sort()
ans=sum(x[1:])
x=[]
for i in range(2):
x.append(int(input()))
ans+=max(x)
print(ans) |
#https://codeforces.com/problemset/problem/588/A
n = int(input())
a, p = map(int, input().split(" "))
mm = a * p # minimum money
mp = p # minimum price
for i in range(n - 1):
a, p = map(int, input().split(" "))
if p < mp:
mp = p
mm += a * mp
print(mm)
|
#42) Coded triangle numbers
#The nth term of the sequence of triangle numbers is given by, tn = (1/2)*n*(n+1); so the first ten triangle numbers are:
#1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a wo... |
"""lista = []
lista.append('Guilherme')
lista.append(28)
#print(lista)
lista2 = []
lista2.append(lista[:])
lista[0] = 'Bryan'
lista[1] = 6
lista2.append(lista[:])
print(lista2)
"""
"""lista = [['João', 61], ['Guilherme', 28], ['Julia', 1], ['Bryan', 6]]
# [ [ 0 ],[ 1]], [ 0 ], [1], [ 0 ], [1], [ 0 ], [... |
class Solution:
def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
tokens.sort()
tokens, maxScore, currentScore = deque(tokens), 0, 0
while tokens and (P >= tokens[0] or currentScore):
while tokens and P >= tokens[0]:
P -= tokens.popleft()
... |
#Done by Carlos Amaral on 12/06/2020
"""
Start with the list you used in Exercise 3-1, but instead of just
printing each person’s name, print a message to them. The text of each mes-
sage should be the same, but each message should be personalized with the
person’s name.
"""
friends = ['Rita', 'Catarina', 'Emilia', '... |
#
# PySNMP MIB module CISCO-STACKWISE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-STACKWISE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:13:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
# _*_ coding: utf-8 _*_
#
# Package: src.core.repository.file
__all__ = [
"car_repository",
"customer_repository",
"employee_repository",
"file_db",
"file_repository",
"rental_repository"
]
|
# Write a function to find the longest common prefix string amongst an array of strings.
class Solution:
# @param {string[]} strs
# @return {string}
def longestCommonPrefix(self, strs):
if not strs:
return ""
lcp = ""
base = strs[0]
for i in range(len(base)):
... |
#
# @lc app=leetcode id=32 lang=python3
#
# [32] Longest Valid Parentheses
#
# @lc code=start
class Solution:
def longestValidParentheses(self, s):
if not s:
return 0
l = 0
r = len(s)
while s[r - 1] == '(' and r > 0:
r -= 1
while s[l] == ')' and l < r... |
'''
Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
'''
class Solu... |
#-*- coding:utf-8 -*-
#宏定义
#字体
FONT_COMMON = "Roboto"
FONT_HEI = "FontHei"
#界面
START_MENU = "startmenu"
PLAY_MENU = "playmenu"
|
"""
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Solution:
1. Recursion (in place)
Flatten the left subtree ... |
"""
A module storing strings used to display messages.
"""
INVALID_INTERNAL_RESAMPLING_OPTIMAL = "Invalid CAT12 configuration! Resampling type 'optimal' can only be set with an internal resampling value of 1. Valid configuration coerced."
INVALID_INTERNAL_RESAMPLING_FIXED = "Invalid CAT12 configuration! Resampling typ... |
command = input()
compare_string_lower = {"coding", "dog", "cat", "movie"}
compare_string_upper = {"CODING", "DOG", "CAT", "MOVIE"}
coffee = 0
get_sleep = False
while not command == "END":
if command.isupper() and command in compare_string_upper:
coffee += 2
if command.islower() and command in compare_s... |
"""Various useful string conversions utilities for XRPL."""
def str_to_hex(input: str) -> str:
"""
Convert a UTF-8-encoded string into hexadecimal encoding.
XRPL uses hex strings as inputs in fields like `domain`
in the `AccountSet` transaction.
Args:
input: UTF-8-encoded string to conver... |
print('nice' in 'nice to meet you')
a=1000000
b=1000000
c=a+b
print(c)
|
a = 1
b = 1
while 32 >= a:
print(a,-b)
b *= 2
a += 1
print("Year",b/365)
|
# Please contact the author(s) of this library if you have any questions.
# Authors: Kai-Chieh Hsu ( kaichieh@princeton.edu )
class _scheduler(object):
def __init__(self, last_epoch=-1, verbose=False):
self.cnt = last_epoch
self.verbose = verbose
self.variable = None
self.step()
... |
#!/usr/bin/env python3
inp = []
with open('03.txt') as fp:
for line in fp:
inp.append(line.strip())
def part1(arr):
acc = [0] * len(arr[0])
for x in arr:
for i in range(len(x)):
acc[i] += int(x[i])
gamma = list(map(lambda x: '1' if x >= len(arr)/2.0 else '0', acc))
eps... |
# ac
N = int(input())
A = list(map(int,input().split()))
mid = int(2**N/2)
left, right = A[:mid], A[mid:]
second = min(max(left), max(right))
print(A.index(second)+1) |
"""Exceptions for Unmanic."""
class UnmanicError(Exception):
"""Generic Unmanic Exception."""
pass
class UnmanicBadRequestRequestedEndpointNotFoundError(UnmanicError):
"""Unmanic bad request endpoint not found exception."""
pass
class UnmanicBadRequestRequestedMethodNotAllowedError(UnmanicError)... |
# eln:decorators
READERS = dict()
# Decorator for adding reader functions
def register_reader(function):
READERS[function.__name__] = function
return function
|
# -*- coding: utf-8 -*-
'''
File name: code\permuted_matrices\sol_559.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #559 :: Permuted Matrices
#
# For more information see:
# https://projecteuler.net/problem=559
# Problem Statement
'''... |
soma = 0
valor = 0
cont = -1
while valor != 999:
soma += valor
cont += 1
valor = int(input('Digite o valor: [999 para parar] '))
print('A soma de {} termos é igual a {}'.format(cont,soma)) |
# oci-utils
#
# Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown
# at http://oss.oracle.com/licenses/upl.
""" Module with oci migrate related exceptions.
"""
class OciMigrateException(Exception):
""" Exceptions for the Im... |
def assert_valid_git_hub_url(edit_on_github_url: str, page_path: str):
# Do you like to include yet another organization? Thing twice :)
url_lower = edit_on_github_url.lower()
assert \
url_lower.startswith('https://github.com/JetBrains/'.lower()) \
or \
url_lower.startswith('https:... |
class RigPacket:
def __init__(self, velocity=0, direction=0):
self.velocity = velocity
self.direction = direction
|
"""
This package represents Presentation layer.
Put your views for different API.
Your views should use services from Application layer,
without implementing logic and only preparing given
data from request for services and formatting it for
response.
All of sub-packages should use the same services
interfaces, diffe... |
"""
A direct child HAS TO define required class variables (pseudo "abstract").
"""
class ClassWithAbstractVariables(object):
@classmethod
def __init_subclass__(cls):
required_class_variables = [
'abstract_class_variables_0',
'abstract_class_variables_1',
'abstract_... |
#!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
command += testshade("-t 1 -g 256 256 -od uint8 -o Cout out_varying_index_float.tif test_varying_index_float")
command += tes... |
def fibonacci_element(n, computed = {0: 0, 1: 1}):
""" calculate N'th Fibonacci number. """
if n not in computed:
computed[n] = fibonacci_element(n-1, computed) + fibonacci_element(n-2, computed)
return computed[n]
def sequence_calc(nterms = 1):
""" Calculate Fibonacci sequence from start """... |
#--- Exercício 3 - Foreach
#--- Escreva programa que leia as notas (4) de 10 alunos
#--- Armazene as notas e os nomes em listas
#--- Imprima:
# 1- O nome dos alunos
# 2- Média do aluno
# 3- Resuldo (Aprovado>=7.0)
notas =[]
nomes = []
media = 0
a = 0
b = 1
c = 2
d = 3
for d in range(1,1... |
def task1(s):
"""
Function which receives a sequence of comma-separated numbers and generate a list and a tuple which contains
every number
Input: string with comma separated numbers
Output: list and tuple with all the numbers
"""
pass
def task2():
"""
Function which receives a se... |
NL_MATERIAL = {
"math": {
"title": "Didactiek van wiskundig denken",
"text": "Leermateriaal over wiskunde en didactiek op de universiteit.",
"url": "https://maken.wikiwijs.nl/91192/Wiskundedidactiek_en_ICT",
"files": [
[{
"mime_type": "application/x-zip",
... |
# Suppose the cover price of a book is $24.95, but bookstores get a 40% discount.
# Shipping costs $3 for the first copy and 75 cents for each additional copy.
# What is the total wholesale cost for 60 copies?
print(round((24.95 - (24.95 * (40 / 100))) * 60 + 3 + 0.75 * 59, 2))
|
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... |
'''
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
'''
#Example
#Create a variable outside of a function, and use it inside the function
x = "awesome"
... |
''' 5. b.
To get a string from a given string where
all occurrences of its first char have been
changed to '$', except the first char itself.
'''
word = input("Enter a long word: ") #arastratiosphecomyia
first_char = word[0] # set first character of our string to first_char variable
new_string = fi... |
points = [[0, 0]]
n = int(input())
for i in range(n):
x, y = map(int, input().split())
points.append([x, y])
distance_pairs = []
for i in range(n + 1):
for j in range(i, n + 1):
dx = points[i][0] - points[j][0]
dy = points[i][1] - points[j][1]
distance_pairs.append([dx ** 2 + dy ** 2, i, j])
distanc... |
'''
NetworkX betweenness centrality on a social network
Betweenness centrality is a node importance metric that uses information about the shortest paths in a network. It is defined as the fraction of all possible shortest paths between any pair of nodes that pass through the node.
NetworkX provides the nx.betweennes... |
#Desafio MDC
def mdc(numeros):
pass
if __name__ == '__main__':
print(mdc([21, 7])) #7
print(mdc([125, 40])) #5
print(mdc([9, 564, 66, 3])) #3
print(mdc([55, 22])) #11
print(mdc([15, 150])) #15
print(mdc([7, 9])) #1 |
N = int(input())
K = int(input())
print(K % N)
|
# Exercício 2.6 - Modifique o programa da listagem 2.11, de forma que ele calcule um
# aumento de 15% para um salário de R$ 750
salario = 750.00
taxa_aumento = 0.15
aumento = salario * taxa_aumento
novo_salario = salario + aumento
print('\nSálario de R$750.00 + aumento de 15' + '% = ' + 'R$%.2f\n' % (novo_salario)) |
"""
def
-> Used to define new functions
-> Binds a function object to a name
-> Executed at runtime
"""
|
'''Test file for file_path_operations.py.'''
master = FileMaster('/Users/person1/Pictures/house.png')
test.describe('Description Test Cases')
test.assert_equals(master.extension(), 'png')
test.assert_equals(master.filename(), 'house')
test.assert_equals(master.dirpath(), '/Users/person1/Pictures/') |
'''solved, super easy'''
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
else:
i += ... |
class Solution:
# @param {int[]} nums a set of distinct positive integers
# @return {int[]} the largest subset
def largestDivisibleSubset(self, nums):
# Write your code here
if not nums:
return 0
nums = sorted(nums)
# n = len(nums)
dp, prev =... |
"""
@Date: 2021/11/06
@description:
"""
|
def complicated_logic(first, second):
print(f"You passed: {first}, {second}")
# return first + second * 12 - 4 * 12
number1 = 10
number2 = 3
result = complicated_logic(number1, number2)
print(result)
|
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
ans = set()
for i in range(bound):
if pow(x,i) > bound or (x==1 and i>0):
break
for j in range(bound):
if pow(y,j) > bound or (y==1 and j>0):
... |
class Node():
def __init__(self, val):
self.val = val
self.right = None
self.left = None
def insert(root, val):
if root is None:
return Node(val)
elif val < root.val:
root.left = insert(root.left, val)
elif val > root.val:
root.right = insert(root.right,... |
class Fjs(object):
def __init__(self, name):
self.name = name
def hello(self):
print("said by : ", self.name)
def __getattr__(self, item):
print("访问了特性1:" + item)
return None
raise AttributeError
def __setattr__(self, key, value):
print("访问... |
soma = 0
for i in range(0,101):
if(i%2==0):
soma+=i
print("A soma de todos os pares é:", soma) |
input()
num = set(map(int,input().split()))
prime = set([i for i in range(3,max(num)+1,2)])
for i in range(3,max(num)+1,2):
if i in prime:
prime -= set([i for i in range(i*2,max(num)+1,i)])
prime.add(2)
print(len(num.intersection(prime))) |
class TestOptimizeO:
"""Test interaction of -O flag and optimize parameter of compile."""
def setup_method(self, method):
space = self.space
self._w_flags = space.sys.get('flags')
# imitate -O
space.appexec([], """():
import sys
flags = list(sys.flags)
... |
# draw a rectangle
# rect(x, y, width, height)
rect(20, 50, 100, 200)
rect(130, 50, 100, 200)
oval(240, 50, 100, 200)
oval(20, 250, 100, 100)
oval(130, 250, 100, 100)
rect(240, 250, 100, 100)
for x in range(20, 300, 50):
rect(x, 370, 40, 40)
for x in range(20, 300, 50):
if random() > 0.5:
rect(x,... |
# Desenvolva um programa que leia seis numeros inteiros e mostre a soma apenas daqueles que forem PARES.
# Se o valor digitado for IMPAR, desconsidere-o
soma = 0
cont = 0
for n in range(1, 7):
n = int(input('Digite um Valor inteiro: '))
if n % 2 == 0:
soma = soma + n
cont = cont + 1
print(f'A so... |
"""
Pagination support code.
"""
BUFFER = 5
def paginator(page_num, max_page, buffer_size=BUFFER):
"""
Pagination generator.
Generates a sequence of page numbers, giving the pages at the beginning
and end, and around the current page, with a number of buffer pages on
each side of both. Omitted ... |
scores = {
"John": 81.5,
"Fred": 100,
"Chad": 50,
"Wopper": 30,
"Katie": 73
}
def calc_grade(score):
if score >= 91:
return "Outstanding"
elif score >= 81:
return "Exceeds Expectations"
elif score >= 71:
return "Acceptable"
elif score >= 61:
return "... |
# eval utils
def statistics_degrees(A_in):
"""
Compute min, max, mean degree
Parameters
----------
A_in: sparse matrix or np.array
The input adjacency matrix.
Returns
-------
d_max. d_min, d_mean
"""
degrees = A_in.sum(axis=0)
return np.max(degrees), np.min(degree... |
# Exercício Python 39: Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre:
#A) qual é o total gasto na compra.
#B) quantos produtos custam mais de R$1000.
#C) qual é o nome do produto mais barato.
print('~'*30)
print('LISTA DE ... |
"""
A statement function set holds a set of statement functions that can be used in statements.
"""
class BaseStatementFuncSet(object):
"""
A statement function set holds a set of statement functions that can be used in statements.
"""
def __init__(self):
self.funcs = {}
self.at_creat... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 14:53:06 2019
@author: ISHA
"""
arr = [
[ 'XYZ', 1, 88, 56, 45],
[ 'ABC', 2, 45, 86, 52],
[ 'LMN', 3, 87, 39, 40],
[ 'QWS', 4, 96, 86, 85],
[ 'TRE', 5, 76, 56, 53],
[ 'UTH', 6, 35, 79, 48],
[ ... |
"""
*graphical color*
Spectral color measures.
"""
# from ._color import Color
# from ._rgb import Rgba
# from ._hsv import Hsba
__all__ = [
"Color",
"Rgba",
"Hsba",
]
|
#!/usr/bin/env python3
'''
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words.
You should return an array of all the anagrams or an empty array if there are none.
'''
def anagrams(word, words):
analis = []
for item in words:
... |
YEAR_CHOICES = (
(1,'First'),
(2,'Second'),
(3,'Third'),
(4,'Fourth'),
(5,'Fifth'),
)
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 31 10:11:51 2019
@author: Administrator
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
# if n == 1:
# return x
# if x!=0 and n == 0:
# return 1
# if x == 0 and n <= 0:
# return None
# if n>... |
# day 6...
# count distinct questions or whatever
# parse forms from input file. Split by group!
def parse_forms(file):
raw = file.read()
# Ths smushes each group's responses together, to better facilitate part 1.
# I'm sure I'll regret this in part 2.
# grouplist = ["".join(p.splitlines()) for p in r... |
#
# PySNMP MIB module DOCS-RPHY-PTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-RPHY-PTP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:53:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# -*- coding: utf-8 -*-
# @Author: ZwEin
# @Date: 2016-07-08 13:48:24
# @Last Modified by: ZwEin
# @Last Modified time: 2016-07-08 13:48:34
def attr_func_state(attr_vals):
pass |
# Domains list
DOMAINS = [
{ 'url': 'https://ifmo.su', 'message': '@guryn' }
]
# Notifications link from https://t.me/wbhkbot
WEBHOOK = ''
|
@state_trigger("sensor.power_meter != '9999'")
def load_optimizer(value=None):
pass
|
## Alphabet war
## 7 kyu
## https://www.codewars.com/kata/59377c53e66267c8f6000027
def alphabet_war(fight):
l = dict(zip('wpbs', range(4,0,-1)))
r = dict(zip('mqdz', range(4,0,-1)))
left, right = 0,0
for char in fight:
if char in l:
left += l[char]
elif char ... |
"""Define routes."""
def includeme(config):
"""App routes."""
config.add_static_view(
'static',
'pyramid_learning_journal:static',
cache_max_age=3600
)
config.add_route('home', '/')
config.add_route('detail', '/journal/{id:\d+}')
config.add_route('new', '/journal/new-en... |
class Solution:
# Codes (Accepted), O(n) time and space
def replaceDigits(self, s: str) -> str:
li, n = [], len(s)
for i in range(0, n, 2):
if i+1 < n:
code = ord(s[i]) + int(s[i+1])
li += [s[i], chr(code)]
else:
li.append(s... |
class SubmissionStatus(object):
SUBMITTED = -4
WAITING = -3
JUDGING = -2
WRONG_ANSWER = -1
ACCEPTED = 0
TIME_LIMIT_EXCEEDED = 1
IDLENESS_LIMIT_EXCEEDED = 2
MEMORY_LIMIT_EXCEEDED = 3
RUNTIME_ERROR = 4
SYSTEM_ERROR = 5
COMPILE_ERROR = 6
SCORED = 7
REJECTED = 10
JUDGE_ERROR = 11
PRETEST_PASSE... |
"""
Given a string str, we need to extract the symbols and words of the string in order.
Example 1:
input: str = "(hi (i am)bye)"
outut:["(","hi","(","i","am",")","bye",")"].
Explanation:Separate symbols and words.
Solution:
Go through the str, push the alphabetical into stack and append it to res list if we meet a... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 13:51:55 2019
@author: nehap
"""
"""
Input: 5
Output :
* * * * *
* * * *
* * *
* *
*
"""
if __name__=="__main__":
n = int(input("Input: "))
#Initial Spaces
k=n-1
print("Output :")
#Outer loop - controlling number of rows
for ... |
def main():
c = input()
if c != c[::-1]: # -1 шаг строки: от конца к началу
print("It's not palindrome")
else:
print("It's palindrome")
if __name__ == "__main__":
main() |
str1 = "Liu Kang "
str2 = "Johnny Cage "
str3 = "Scorpion "
str4 = "Sub-Zero "
str5 = "Sonya "
str6 = "Test yo might! "
print(str1 + str2 + str3 + str4 + str5 + str6)
print(str3 * 5)
print(str3 * (5 + 4))
print(str3 * 5 + "4")
today = "Tuesday"
# bool - in operator
print("day" in today)
print("scorpion" in today)
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Empresa: Funcao Coppetec
Desenvolvedor: Gustavo Daniel Soares Figueiredo
Data: 14/12/2014
Descricao: Classe criada para gerar os id dos objetos a serem adicionados no banco de dados, evitando assim mais requisições ao banco de dados.
'''
class GenerateID:
def __init... |
# pylint: disable=missing-docstring
def stupid_function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9): # [too-many-arguments]
return arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.