content stringlengths 7 1.05M |
|---|
"""This problem was asked by Pinterest.
At a party, there is a single person who everyone knows, but who does not
know anyone in return (the "celebrity"). To help figure out who this is,
you have access to an O(1) method called knows(a, b), which returns True
if person a knows person b, else False.
Given a list of... |
class Item:
def __init__(self, name, price, rarity, typ):
self.__name = name
self.__price = price
self.__rarity = rarity
self.__typ = typ
def getName(self):
return self.__name
def setName(self, name):
self.__name = name
def getPrice(self):
r... |
general_value_test_cases = [( {'type': 'driving-licence', 'id': '4HpY_e2U_TUH', 'preferred_label': 'AM', 'deprecated_legacy_id': '16'},
'driving-license', {'legacy_ams_taxonomy_id': '16', 'type': 'driving-license', 'label': 'AM', 'concept_id': '4HpY_e2U_TUH', 'legacy_ams_taxonomy_num_id': 16}),
( {'type': 'driving-li... |
def hex2int(hex_str):
"""
Convert hex characters (e.g. "23" or "011a") to int (35 or 282)
:param hex_str: hex character string
:return: int integer
"""
return int(hex_str, 16)
def hex2value10(hex_str):
"""
Convert 2 hex characters (e.g. "23") to float (3.5)
:param hex_str: hex char... |
class Quantity(object):
def __get__(self, instance, owner):
return getattr(instance, self.target_name)
def __set__(self, instance, value):
if not hasattr(self, 'target_name'):
self.set_target_names(instance)
if value > 0:
setattr(instance, self.target_name, valu... |
def sort_012(inputList):
next0 = 0
next2 = len(inputList) - 1
frontIndex = 0
while frontIndex <= next2:
if inputList[frontIndex] is 0:
inputList[frontIndex] = inputList[next0]
inputList[next0] = 0
next0 += 1
frontIndex += 1
elif inputList[frontIndex] == 2: ... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
if type(self.data) != 'str':
return str(self.data)
return self.data
def inorder(root, is_last_node=False):
if root:
inorder(root.left)... |
class Credentials:
"""
Class that generates new instances of credentials.
"""
credentials_list = []
def __init__(self,account_name, username, password):
"""
__init__method to help us create new instances of the class credentials
"""
self.account_name = account_na... |
sum=0
for i in range(5):
a=int(input())
if a<40:
a=40
sum+=a
print(sum//5) |
# Some constants to work for https://github.com/Di-Ny/LoRaPacketForwarderDomoticzConfigurator
#
# Author: DiNy
###########
## Global
GW_UNIT_ID=10
###########
## LORA
DR_2_SFBW_EU868 = {
"0":["12","125.0","5"],
"1":["11","125.0","5"],
"2":["10","125.0","5"],
"3":["9","125.0","5"],
"4":["8","125.0","5"],
"5":["7"... |
# Login information for the 6.034 Automated Tester
USERNAME="lcchiang_MIT_EDU"
PASSWORD="yu7Q4nPJNRALMY3AJ6ze"
XMLRPC_URL="https://ai6034.mit.edu/labs/xmlrpc/"
|
# Autor: David Ferreira de Almeida
# Implementacao de uma Árvore Binária de Busca
#
# Exemplo de uma Árvore Binária de Busca que será usado durante o código.
# O elemento à esquerda são menores que o valor do pai, e os elementos à
# direita são maiores ou iguais ao valor do pai.
#
# 61
# ... |
class Solution:
def reverseBits(self, n):
res = 0
for _ in range(32):
res = (res<<1) + (n&1) # 右移动
n>>=1 # 左移
return res
s =Solution()
b = s.reverseBits(101010111)
print(b)
|
ENDPOINT = "https://en.wikipedia.org/w/api.php"
def make_url(id, is_expanded=False, is_html=False):
# TODO: isdigit is not robust enough, title could be number instead of string
return make_id_url(id, is_expanded, is_html) if str(id).isdigit() else make_title_url(id, is_expanded, is_html)
def make_title_ur... |
#!/usr/bin/python3
def main():
buffersize = 50000
infile = open('obama.png', 'rb')
outfile = open('obama-copy.png', 'wb')
buffer = infile.read(buffersize)
while len(buffer):
outfile.write(buffer)
print('.', end = '')
buffer = infile.read(buffersize)
print()
print('D... |
a, b, c = sorted(list(map(float, input().split())))
if(((a+b) > c)and((c-a) < b)):
print('It is a triangle.')
if(((a**2)+(b**2)) == (c**2)):
print('-> also a Right triangle.')
if(not(a-b)):
print('-> Wow it\'s a Isosceles right triangle!')
else:
print('not a triangle.') |
def alternating(list_of_ints):
pass
print(alternating([1, 2, 3, 4]))
print(alternating([10, 11, 1, 12]))
print(alternating([10, 21, 22, -5, 100, 101, 2]))
|
DEVICE_NAME = '00002a00-0000-1000-8000-00805f9b34fb'
MODEL_NUMBER = '00002a24-0000-1000-8000-00805f9b34fb'
SERIAL_NUMBER = '00002a25-0000-1000-8000-00805f9b34fb'
FIRMWARE_VERSION = '00002a26-0000-1000-8000-00805f9b34fb'
HARDWARE_VERSION = '00002a27-0000-1000-8000-00805f9b34fb'
MANUFACTURER_NAME = '00002a29-0000-1000-80... |
pkgname = "libusbmuxd"
pkgver = "2.0.2"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf", "automake", "libtool"]
makedepends = ["libusb-devel", "libplist-devel"]
pkgdesc = "Client library to multiplex connections to/from iOS devices"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.1-on... |
allowedAccess = ['Danilo', 'Lucio', 'Daiana', 'Vanessa']
requestName = input("Por gentileza informa seu nome para verificar nivel de permissão: ")
for name in allowedAccess:
if(name == requestName):
print("Acesso autorizado a " + requestName)
break
else:
print("Acesso negado a " + requ... |
def main():
return 'THIS_IS_MAIN_MAIN'
def func():
return 'THIS_IS_MAIN_FUNC'
|
"""
Boolean Data Type(bool):
- Only be True or False
- None is false
- All numbers are True, except 0.
- All strings are True, except Empty strings. ie ""
- All Collections(list, tuple, set, and dictionary) are True, except Empty ones.ie. (), [], {},
- Objects from a class with a __len__ function that returns 0 is alw... |
def get_msg_with_punctuations(old, new):
new_org_text = new
for i in range(len(old)):
if not str.isalpha(old[i]):
new_org_text = new_org_text[0:i] + old[i] + new_org_text[i:]
for i in range(len(old)):
if str.isupper(old[i]):
new_org_text = new_org_text[0:i] + str.uppe... |
class Solution:
def lowestCommonAncestor(self, root, p, q):
if root is None or p == root or q == root:
return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
if l is None:
return r
if r is None:
... |
def Logo():
print("""
____________________ ______________ ____________
| | | | | @
| ____________| | ______ | | _______. #
| | | | | | | | | #
| | __________ | | | | | | | #
| | | ... |
### This program subtracts ###
def minus(a, b):
sub = a - b
print(sub)
print("Welcome to subtracting your life version 1.0.0.0.0.0.0.1!")
x,y = input("Please input the digits of your life that you wish to subtract: ").split()
x = int(x)
y = int(y)
minus(x,y)
|
class XmlServiceTransport(object):
"""XMLSERVICE transport base class
Args:
ctl (str): XMLSERVICE control options, see
http://yips.idevcloud.com/wiki/index.php/XMLService/XMLSERVICEQuick#ctl
ipc (str): An XMLSERVICE ipc key for stateful conections, see
http://yips.idevcloud.com/wiki... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
next_node = head.next
head.next = None
while next_node:
... |
def Cel():
celsius = float(input("Enter the temperature in Celsius ")) # It will take user input
fahrenheit :float = (celsius * 9 / 5) + 32 # calculation part
print("Value in Fahrenheit ", fahrenheit)
def Far():
fahrenheit = float(input("Enter the temperature in Fahrenheit ")) # It will take user i... |
#CP2
#Thomas Franceschi
#Kyle Williams
#import sys
class baseParser:
def __init__(self, expression, length, counter):
self.expression = expression #String being parsed
self.length = length #Max range for token
self.counter = counter #Token
self.M = '' #Output
def parseRegexp(self):
... |
""" Problem Set 1 - Problem 3
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of t... |
"""Simple example test."""
def test_simple():
"""Simple example test."""
assert True
|
__all__ = [
'PrimaryStatus',
'InputStatus',
'OutputStatus',
'StopReason'
]
class PrimaryStatus:
QUEUING_CHECKS = "QUEUING_CHECKS"
# one of checks tasks has been started
CHECKING = "CHECKING"
# when all first level tasks has been finished
CHECKS_FINISHED = "CHECKS_FINISHED"
... |
# __getattr__ is not implemented by default
# __getattribute__ run for every attribute access (w/o looking at attributes on object)
# __getattr__ only run when attribute not found in normal ways
class Foo(object):
def __getattribute__(self, item):
print('Foo called __getattribute__ on {0}'.format(item))
... |
# palindrome_check.py
# recursion in strings
def isPalindrome(s):
# check if string is a palindrome
def toChars(s):
# convert string to characters
s = s.lower()
ans = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxy':
ans = ans + c
retur... |
f = open('./deu.txt','r')
fwde = open('./deu.de','w')
fwen = open('./deu.en','w')
lines = [line for line in f.read().split('\n') if line]
for line in lines:
items = line.split('\t')
assert len(items)==3
fwen.write(items[0] + '\n')
fwde.write(items[1] + '\n')
fwde.close()
fwen.close()
|
height_map = [int(e.strip()) for e in input().strip().split(',')]
count = 0
negative = False
for i in height_map:
if i < 0:
negative = True
else:
if negative:
count += 1
negative = False
print(count) |
# Find value that occurs in odd number of elements.
# Find the number in an non-empty array that does not have pair
# Array [9,3,9,3,9,7,9] pairs
# A[0] = 9 and A[2] = 9
# A[1] = 3 and A[3] = 3
# A[4] = 9 and A[6] = 9
# A[5] = 7 no pair
# the function should return 7, as explained in the example above.... |
# -*- coding: utf-8 -*-
{
'name': 'Gastos unidos a facturas',
'version': '1.0',
'category': 'Accounting/Expenses',
'sequence': 6,
'summary': 'Gastos unidos a facturas',
'description': """ Cambios a gastos para unirlas a facturas """,
'website': 'http://aquih.com',
'author': 'Rodrigo Fer... |
Data_File = open("Day2_Data.txt")
Data = Data_File.read()
Data = Data.split(',')
for i in range(len(Data)):
Data[i]=int(Data[i])
Data_Backup = Data.copy()
for noun in range (100):
for verb in range(100):
Data = Data_Backup.copy()
Data[1] = noun
Data[2] = verb
Ind... |
# https://www.facebook.com/roshan.philipines/posts/2769055946717382
# Subscribed by Roshaen
#Implementation of ISBN number
def isbn(n):
lst=[]
j=0
for i in range(len(n)):
lst.insert(j,n[i])
j+=1
i=0
sum=0
for i in range(len(lst)):
sum=sum+int(lst[i])*(10-i)
if(sum%1... |
def get_defaults():
return {
"acceptable_size": 100,
"acceptable_time": 3,
"get_pages": True,
"get_assets": True,
"get_images": True,
"get_scripts": True,
"get_stylesheets": True,
"give_second_chance": True,
"logfile_location": "gyroscope.log",... |
#PROBLEM LINK:- https://leetcode.com/problems/shuffle-the-array/
class Solution:
def shuffle(self, nums, n):
v = []
for i in range(n):
v.append(nums[i])
v.append(nums[i+n])
return v
|
# coding: utf-8
##############################################################################
# Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
#
# Subject to your compliance with these terms, you may use Microchip software
# and any derivatives exclusively with Microchip products. It is your
# resp... |
input_numbers = input('Enter numbers separated by a space : ').split()
max = int(input_numbers[0])
min = int(input_numbers[0])
avg = 0
sum = 0
for i in range(0, len(input_numbers)):
input_numbers[i] = int(input_numbers[i])
sum = sum + input_numbers[i]
if input_numbers[i] > max:
max = input_nu... |
'''3. Write a Python program to print the square and cube symbol in the
area of a rectangle and volume of a cylinder.
Sample output:
The area of the rectangle is 1256.66cm2
The volume of the cylinder is 1254.725cm3'''
area = 1256.66
volume = 1254.725
print(f"The area of the rectangle is {round(area, 2)}cm2")
print(f... |
#!/usr/bin/env python3
def clear_screen(lines=128):
if not isinstance(lines, int) or lines < 64:
lines = 64
print( '\n' * lines, end='' )
class Player:
def __init__(self, n):
self.score = 0
self.name = n
self.attack1 = ''
self.attack2 = ''
self.guard = ''
... |
# однострочный комментарий
'''
первая строка
вторая строка
'''
print('Hello!')
print('Hello!', 'student!', 123, sep='xxx')
print('Hello!', 'student!', 123, end='yyy')
print()
# Ввод
age = input('Input your age')
print(age, type(age))
print(int(age), type(int(age)))
'''
print(1+1, 'student', sep='yyy', end='!'... |
class Plugin(object):
"""
Plugin Base Class
Meant to be inherited for plugins
"""
def __init__(self):
self._commands = {}
def command(self, name, **kwargs):
"""
Decorator to register a coroutine to a plugin command
:param name: Command Name
:return:
... |
class Assert(object):
@staticmethod
def is_instance(instance, instances_class):
assert isinstance(instance, instances_class), '{0} should be an instance of class {1}'.format(
instance.__name__, instances_class.__name__
)
|
#Prime Number Checker
#Parker Dinkins
'''
This program asks for a number between 0 and 5000
If the number isn't in that range it asks for it again
When a proper number is entered it checks if it is prime
If the numbr is prime it prints the two factors
If the number is not prime it prints all the factors
Finally it ask... |
#!/usr/bin/env python3
# Write a program that computes the GC fraction of a DNA sequence in a window
# Window size is 11 nt
# Output with 4 significant figures using whichever method you prefer
# Use no nested loops. Instead, count only the first window
# Then 'move' the window by adding 1 letter on one side
# And subt... |
#!/usr/local/bin/python3
class Duet():
def __init__(self, instruction_list):
self.instruction_list = [ instruction.split() for instruction in instruction_list ]
self.program_counter = 0
self.registers = {}
self.played = None
self.nonZeroPlayed = False
self.__instr_se... |
n = int(2367363789863971985761)
#überprüfen welche länge n = 2367363789863971985761 hat
#print(n)
i = 1
while n != 1: #solange n noch nicht gleich 1 ist
if n%2 == 0: #wenn n durch 2 ganz teilbar ist
n = n//2
#print(n)
else: #ansonsten
n = n*3+1
#print(n)
i = i+1
... |
def check_flux_balance(data_dict: dict) -> bool:
"""
When all fluxes are specified in the measRates sheet, check if all metabolites are mass balanced (well, the ones
that are marked as balanced in the mets sheet).
If everything is fine flag is 0, otherwise it is set to 1.
Args:
data_dict: ... |
def sum_of_digits(number):
"""
Calculating sum of digits of number
"""
sum = 0
number = abs(number)
while number > 0:
sum += number % 10
number = number // 10
return sum
def to_digits(number):
"""
Calculating the digits of the number
"""
digits = []
whil... |
def consumer():
r = ''
while True:
n = yield r # 返回的是r, 通过send函数接收的是n, 通过next和send都可以唤醒执行
# if not n:
# return
print('[CONSUMER] consuming %s' % n)
r = '200 OK'
def produce(c):
n = 0
while n < 5:
n = n + 1
print('[PRODUCE] prod... |
NUM_ALLELES = 3
ALLELE_PRIOR = 1.0 / NUM_ALLELES
ALPHA = 1.5
MINUS_INFINITE = -1000000000
mBound = 6
jA = 10.0
jB = 0.5
pA = 0.1
pD = 0.1
pC = 1.0 - pD
pI = 0.1
if __name__ == '__main__':
print('This is a configuration file!')
|
# The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
#
# 73167176531330624919225119674426574742355349194934
# 96983520312774506326239578318016984801869478851843
# 85861560789112949495459501737958331952853208805511
# 125406987471585238630507156932909632952274430435... |
class A:
def feature1(self):
print("Feature 1 working")
def feature2(self):
print("Feature 2 working")
a1 = A()
a1.feature1()
class B(A):
def feature3(self):
print("feature 3 working")
def feature4(self):
print("feature 4 working")
b1 = B()
b1.feature2()
|
# Application Install Directory (Relative to Inside Container)
SNODAS_APP = '/app/cumulus/snodas/core'
# Archive of UNMASKED files downloaded from NSIDC
SNODAS_RAW_UNMASKED = '/app/data/snodas/raw_unmasked'
# Archive of MASKED files downloaded from NSIDC
SNODAS_RAW_MASKED = '/app/data/snodas/raw_masked'
|
expected_output = {
'vrf': {
'VRF501': {
'address_family': {
'ipv4': {
'routes': {
'192.168.111.1/32': {
'route': '192.168.111.1/32',
'active': True... |
class Node:
def __init__(self, name=None, terminal=False):
self._name = name
self._children = []
self._level = None
self._terminal = terminal
# ====================
# GETTERS E SETTERS
@property
def name(self):
return self._name
@name.setter
def name... |
def get_all_includes(comp_args, dst_includes):
i = 0
while i < len(comp_args):
curr_arg = comp_args[i].strip()
if curr_arg == "-isystem":
curr_arg1 = "-I" + comp_args[i+1].strip()
if curr_arg1 not in dst_includes:
dst_includes.append(curr_arg1)
if ... |
def push(data_json):
# A user pushes 1 or more commits to a repository.
repository = data_json['repository']
# repository_scm = repository['scm']
repository_name = repository['name']
repository_link = repository['links']['html']['href']
actor = data_json['actor']
actor_name = actor['display... |
"""
Messages for the :mod:`~django_dicom.models.managers` module.
"""
DATA_ELEMENT_CREATION_FAILURE = (
"Failed to create DataElement instance for:\n{data_element}\n{exception}"
)
HEADER_CREATION_FAILURE = "Failed to read header information!\n{exception}"
IMPORT_ERROR = (
"Failed to import {path}\nThe following... |
# Māras
text = input("ievadi teikumu")
texta = []
words = text.split()
textb = [w[::-1] for w in words]
# for item in words:
# texta.append(item[::-1])
# textb = " ".join(texta) # so we do not have " " after last item
print(" ".join(textb))
|
class LifeCycle:
def __init__(self, id, label, composed_of):
self.id = id
self.label = label
self.composed_of = composed_of
|
a = []
maximum = 0
for _ in range(6):
tmp = [int(x) for x in str(input()).split(" ")]
a.append(tmp)
for i in range(6):
for j in range(6):
if (j + 2 < 6) and (i + 2 < 6):
result = a[i][j] + a[i][j+1] + a[i][j+2] + a[i+1][j+1] + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2]
if(result > maximum):
maximum = result... |
def NumpyInList(array,l1):
for i in l1:
if i[0] == array[0] and i[1] == array[1]:
return True
return False
|
def create_matrix(size):
matrix = []
for _ in range(size):
matrix.append([int(x) for x in input().split()])
return matrix
def is_valid_cell(position, size):
row = position[0]
col = position[1]
return 0 <= row < size and 0 <= col < size
def print_matrix(matrix):
for row in matrix:... |
load(
"@io_bazel_rules_dotnet//dotnet/private:context.bzl",
"dotnet_context",
)
load(
"@io_bazel_rules_dotnet//dotnet/private:providers.bzl",
"DotnetLibrary",
)
load("@io_bazel_rules_dotnet//dotnet/private:rules/common.bzl", "collect_transitive_info")
def _libraryset_impl(ctx):
"""_libraryset_impl ... |
# Basic syntax
#T# Table of contents
#C# Blocks of code
#C# Variables, constants, literals
#C# - Type hints
#C# Escape sequences and escaped chars
#C# Expressions
#C# Function calls
#C# Statements
#C# Multiline statements
#C# Multistatement lines
#C# Metadata
#T# Beginning of content
# |-------------------------... |
"""
Given a number, return a string with dash `'-'` marks before and after each odd integer, but do not begin or end the string with a dash mark.
"""
def dashatize(num):
if not num and not (num == 0):
return 'None'
result = '-'.join(str(abs(num)))
copy_result = result[:]
occurrences = 0
f... |
(rows_count, columns_count) = map(int, input().split())
matrix = []
new_matrix = []
player_position = []
player_wins = False
for i in range(rows_count):
row = [x for x in input()]
if "P" in row:
player_position = [i, row.index("P")]
row[row.index("P")] = "."
row2 = row.copy()
matrix.app... |
"""django-dmarc-reporting"""
__author__ = "VirtualTam"
__title__ = "django-dmarc-reporting"
__version__ = '0.1'
default_app_config = 'dmarc_reporting.apps.DmarcReportingConfig'
|
coordinates_FFFFCC = ((149, 117),
(149, 118), (149, 119), (149, 120), (149, 121), (149, 122), (149, 123), (149, 124), (149, 125), (149, 126), (149, 127), (149, 128), (149, 129), (149, 130), (150, 111), (150, 112), (150, 113), (150, 114), (150, 115), (150, 116), (150, 131), (150, 133), (151, 107), (151, 108), (151, 10... |
class TrimapError(Exception):
"""
Error when creating matting trimap.
"""
def __init__(self, err):
super(TrimapError, self).__init__(err)
class AnnError(Exception):
"""
Error with Input annotation.
"""
def __init__(self, err):
super(AnnError, self).__init__(err)
|
class WiktionaryParaphrase:
def __init__(self, lexunit_id: str, wiktionary_id: str, wiktionary_sense_id: int, wiktionary_sense: str,
edited: bool):
"""
This class holds the Wictionary paraphrase object. A wictionary paraphrase can be part of lexical units. The
contain a def... |
class StockTrendPredictor:
def predict(self, headline: str) -> int:
r"""Predict stock trending from the given headline
Args:
headline: the news headline
Returns:
A prediction, 0 for not-changed or downward trend, 1 for upward trend
"""
pass
|
# Part 1: 187
# Part 2: 4723283400
class Slope():
def __init__(self, path):
"""
input path to text file
text file should contain map data consisting of "." for open spaces, "#" for trees
"""
# put file data into 2D array of characters "." and "#"
with open(path, "r"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Base class. Eventually all optimizers will be implemented as classes with this
as the base class.
"""
class BaseOptimizer(object):
'''
Placeholder for now. Will eventually convert all methods to
instances of this class.
'''
pass |
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
global_val = list()
global_num = 0
if root is None:
return global_val
def in_traverse(root, result):
if root is None:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google Inc. 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 ... |
class EmailAddress:
def __init__(self, email):
self.email = email
self._email_tpl = tuple(self._email.split('@'))
def __str__(self):
return self.email
def __repr__(self):
return f"{EmailAddress.__name__}('{self.email}')"
@property
def email(self):
return s... |
class Settings():
"""A class to store all settings for Allien Invation."""
def __init__(self):
"""Initialize the game's static settings"""
# Screen Settings
self.screen_width = 800
self.screen_height = 600
# self.bg_color = (0, 0, 0)
self.bg_color = (10, 10, 10)... |
x = int(input())
y = int(input())
ans = 0
if x > 0:
if y > 0:
ans = 1
else: ans = 4
else:
if y > 0:
ans = 2
else: ans = 3
print(ans) |
# filename : csc_checks.py
# description : check definitions (security best practices and CVEs)
# create date : 2018-05-07 14:07:33.569768
csc1_1 = {'check_name': 'csc1_1',
'check_type': 'check_in_simple',
'match1': 'banner motd',
'match2': 'n/a',
'required': 'yes',
'result_ok': 'Test successful.... |
print("What is yas?")
word = input()
def isYas(word):
Yasses = True
state=0
for i in range(len(word)):
if word[i].isalpha():
if state == 0:
if word[i] in ["Y","y"]:
state=1
else:
Yasses = False
elif state == 1:
if word[i] in ["Y","y"]:
state=1
elif word[i] in ["A","a"]:
st... |
class NGram:
# @param {int} n a integer
# @param {str} string a string
def mapper(self, _, n, string):
# Write your code here
# Please use 'yield key, value' here
for i in range(len(string) - n + 1):
yield string[i:i + n], 1
# @param key is from mapper
# @param... |
###################################################
## ##
## This file is part of the KinBot code v2.0 ##
## ##
## The contents are covered by the terms of the ##
## BSD 3-clause license included in the LICENSE ##
## file,... |
class Vector:
def __init__(self,x,y):
self.x=x
self.y=y
def __repr__(self):
return str(self.x) +"i, "+ str(self.y)+"j"
def dotProduct(v1,v2):
return v1.x*v2.x + v1.y*v2.y |
# -*- coding: utf-8 -*-
"""
Author: @heyao
Created On: 2019/6/24 下午1:57
"""
|
class CalculatorException(Exception):
pass
class Calculator:
"""
This is a simple Calculator that performs basic addition, subtraction,
division, multiplication and root calculation of numbers.
"""
def __init__(self):
self.__val = 0
def add(self, num:int or float or compl... |
#poly_limit=10
def poly_check(seq,poly_limit):
if 'A'*poly_limit not in seq and 'T'*poly_limit not in seq and 'G'*poly_limit not in seq and 'C'*poly_limit not in seq:
return True
else:
return False
def var_check(change_from, change_to, seq,var_limit):
ALL=['A','T','C','G']
tmp=[]
for one in ALL:
if on... |
x = input()
if x == ".helpf":
print(".help : to show help menu")
|
"""Hello world module"""
def hello_func():
"""return 'Hello!'"""
return "Hello!"
def main():
"""print 'Hello!'"""
print(hello_func())
if __name__ == '__main__':
main()
|
class Config(object):
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = '1234567890'
SQLALCHEMY_ECHO = False
FLASK_ADMIN_SWATCH = 'united'
if __name__ == '__main__':
for key in Config.__dict__:
print(key, Config.__dict__[key]) |
# https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts
def generate_the_string(n):
if n % 2 == 0:
return 'a' * (n - 1) + 'b'
return 'a' * n |
class Queue2Stacks:
def __init__(self):
self.stack1 = []
self.stack2 = []
def size(self):
return len(self.stack1)
def isEmpty(self):
return self.stack1 == []
def enqueue(self,item):
self.stack1.append(item)
def d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.