content stringlengths 7 1.05M |
|---|
'''n = s = 0
while n != 999:
n = int(input('Digite um número: '))
s += n
s -= 999
print ('A soma vale {}'.format(s))'''
n = s = 0
while True:
n = int(input('Digite um número: '))
if n == 999:
break
s += n
print ('A soma vale {}'.format(s)) |
def setup():
size(600, 400)
def draw():
global theta
background(0);
frameRate(30);
stroke(255);
a = (mouseX / float(width)) * 90;
theta = radians(a);
translate(width/2,height);
line(0,0,0,-120);
translate(0,-120);
branch(120);
def branch(l):
l *= .66
... |
def f(x):
y = x**4 - 3*x
return y
#pythran export integrate_f6(float64, float64, int)
def integrate_f6(a, b, n):
dx = (b - a) / n
dx2 = dx / 2
s = f(a) * dx2
i = 0
for i in range(1, n):
s += f(a + i * dx) * dx
s += f(b) * dx2
return s
|
# O(n) time | O(1) space
def reverseLinkedList(head):
p1, p2 = None, head
while p2 is not None:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
return p1 |
"""
* Highe level classes should not depend on low level classes, it happens most of the time because
we write low level classes first and then make the high level classes dependent on them
* Abstractions (High Level Classes) should not depend on implementations (Low level class)
Solve it using Bridge pattern or ... |
# Make a config.py file filling in these constants. Note: This is only a template file!
clientID = 'CLIENT_ID'
secretID = 'SECRET_ID'
uName = 'USERNAME'
password = 'PASSWORD'
db_host = 'IP_ADDR_DB'
db_name = 'MockSalutes'
db_user = 'DB_USER'
db_pass = 'DB_PASSWORD'
|
# cook your dish here
for _ in range(int(input())):
N,MINX,MAXX = map(int,input().split())
num = MAXX-MINX+1
even = num//2
odd = num-even
for i in range(N):
w, b = map(int,input().split())
if w%2==0 and b%2==0:
even = even+odd
odd=0
elif w%2==1 and b%2... |
#!/usr/bin/env python3
'''
Create a function, that takes 3 numbers: a, b, c and returns True if the last digit
of (the last digit of a * the last digit of b) = the last digit of c.
'''
def last_dig(a, b, c):
a = list(str(a))
b = list(str(b))
c = list(str(c))
val = list(str(int(a[-1]) * int(b[-1])))
return int(val... |
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
# @param intervals, a list of Intervals
# @return a list of Interval
def merge(self, intervals):
newInterval = []
if len(intervals) == 0:
r... |
# Basic Fantasy RPG Dungeoneer Suite
# Copyright 2007-2018 Chris Gonnerman
# 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
# no... |
##########################################################################################
#
# Asteroid Version
#
# (c) University of Rhode Island
##########################################################################################
VERSION = "0.1.0"
|
# Criando nossa 1ª Classe em Python
# Sempre que você quiser criar uma classe, você vai fazer:
#
# class Nome_Classe:
#
# Dentro da classe, você vai criar a "função" (método) __init__
# Esse método é quem define o que acontece quando você cria uma instância da Classe
#
# Vamos ver um exemplo para ficar mais claro, com ... |
class User:
def __init__(self,account_name,card,pin):
self.account_name = account_name
self.card = card
self.pin = pin |
CFG = {
'in_ch': 3,
'out_ch': 24,
'kernel_size': 3,
'stride': 2,
'width_mult': 1,
'divisor': 8,
'actn_layer': None,
'layers': [
{'channels': 24, 'expansion': 1, 'kernel_size': 3, 'stride': 1,
'nums': 2, 'norm_layer': None, 'dropout_ratio': 0.1, 'dc_ratio': 0.2,
... |
# -*- coding: utf-8 -*-
def main():
n = int(input())
dp = [float('inf') for _ in range(n + 1)]
ng_numbers = list()
# See:
# https://www.slideshare.net/chokudai/abc011
for i in range(3):
ng_number = int(input())
if ng_number == n:
print('NO')
... |
READ_DOCSTRING = """
Read the input ``table`` and return the table. Most of
the default behavior for various parameters is determined by the Reader
class.
See also:
- http://docs.astropy.org/en/stable/io/ascii/
- http://docs.astropy.org/en/stable/io/ascii/read.html
Parameters
-------... |
# -*- coding: utf-8 -*-
"""
Internal exceptions
===================
"""
class NotRegisteredError(KeyError):
pass
class UnknowConfigError(KeyError):
pass
class UnknowModeError(KeyError):
pass
class UnknowThemeError(KeyError):
pass
class CodeMirrorFieldBundleError(KeyError):
pass
|
numero=('Zero','Um','Dois','Três','Quatro','Cinco','Seis','Sete','Oito','Nove','Dez','Onze','Doze','Treze','Quatorze','Quinze','Dezesseis','Dezessete','Dezoito','Dezenove','Vinte')
while True:
num= int(input('Digite um numero ente 0 e 20: '))
if 0<=num<=20:
break
print('tente nov... |
pod_examples = [
dict(
apiVersion='v1',
kind='Pod',
metadata=dict(
name='good',
namespace='default'
),
spec=dict(
serviceAccountName='default'
)
),
dict(
apiVersion='v1',
kind='Pod',
metadata=dict(
... |
######################################################################
#
# Copyright (C) 2013
# Associated Universities, Inc. Washington DC, USA,
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Fo... |
regularServingPancakes = 24
cupsOfFlourrPer24Pancakes = 4.5
noOfEggsPer24Pancakes = 4
litresOfMilkPer24Pancakes = 1
noOfPancakes = float(input("How many pancakes do you want to make: "))
expectedCupsOfFlour = ( noOfPancakes / regularServingPancakes ) * \
cupsOfFlourrPer24Pancakes
expect... |
def generated_per_next_split(max_day):
# generate a table saying how many lanternfish result from a lanternfish
# which next split is on a given day
table = {}
for i in range(max_day+10, 0, -1):
table[i] = 1 if i >= max_day else (table[i+7] + table[i+9])
return table
def solve(next_splits... |
n = int(input())
xs = []
ys = []
numToPosX = dict()
numToPosY = dict()
for i in range(n):
x, y = list(map(float, input().split()))
numToPosX.setdefault(x, i)
numToPosY.setdefault(y, i)
xs.append(x)
ys.append(y)
xs.sort()
ys.sort()
resX = [0] * n
resY = [0] * n
for i in range(n):
resX[numT... |
def setup():
size(400,400)
stroke(225)
background(192, 64, 0)
def draw():
line(200, 200, mouseX, mouseY)
def mousePressed():
saveFrame("Output.png")
|
class random:
def __init__(self, animaltype, name, canfly):
self.animaltype = animaltype
self.name = name
self.fly = canfly
def getanimaltype(self):
return self.animaltype
def getobjects(self):
print('{} {} {}'.format(self.animaltype, self.name, self.fly))
ok = random('bird', 'penguin',... |
class ValidationResult:
def __init__(self, is_success, error_message=None):
self.is_success = is_success
self.error_message = error_message
@classmethod
def success(cls):
return cls(True)
@classmethod
def error(cls, error_message):
return cls(False, error_message)
... |
def eval_chunk_size(rm):
chunks = []
chunk_size = 0
for row in range(rm.max_row):
for col in range(rm.max_col):
if (rm.seats[row][col] == None or rm.seats[row][col].sid == -1) and chunk_size > 0:
chunks.append(chunk_size)
chunk_size = 0
else:
... |
#
# @lc app=leetcode id=9 lang=python3
#
# [9] Palindrome Number
#
# https://leetcode.com/problems/palindrome-number/description/
#
# algorithms
# Easy (47.28%)
# Total Accepted: 943.6K
# Total Submissions: 2M
# Testcase Example: '121'
#
# Determine whether an integer is a palindrome. An integer is a palindrome whe... |
class Circle:
def __init__(self,d):
self.diameter=d
self.__pi=3.14
def calculate_circumference(self):
c=self.__pi*self.diameter
return c
def calculate_area(self):
r=self.diameter/2
return self.__pi*(r*r)
def calculate_area_of_sector(self,angle):
... |
# Aqui tu funcion
def palindromos(lista):
return [string for string in lista if ''.join(string.lower().split()) == ''.join(string.lower()[::-1].split())]
# Lo puedes probar con esta lista
lista = [
"Añora la Roña",
"Como que moc",
"Anita lava la tina",
"Eva ya hay ave",
"Yo no maldigo mi suert... |
# cxd
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
ret = nums[0] + nums[1] + nums[-1]
value = abs(nums[0] + nums[1] + nums[-1] - target)
i = 0
while i... |
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
amounts = [float('inf')] * (amount + 1)
amounts[0] = 0
for coin in coins:
for amt in range(coin, amount + 1):
amounts[amt] = min(amounts[amt], amounts[amt - coin] + 1)
if amounts... |
""" Lottery module """
class Astro:
""" Create an Astro ticket """
def __init__(self):
"""
Initialize Astro ticket
"""
self.name = "Astro"
|
"""
Tests if nose can see the test directory
"""
def test_true():
assert True
|
"""
This script contains some global variables that are used throughout this specific dataset.
"""
# Dataset file names
raw_input_file_all = '/home/travail/datasets/urban_tracker/sherbrooke/sherbrooke_annotations/sherbrooke_gt.sqlite'
input_raw_image_frame_path = '/home/travail/datasets/urban_tracker/sherbrooke/sherbr... |
if __name__ == "__main__":
s = 'A\tB\tC'
print(len(s))
print(ord('\n'))
s = 'A\0B\0C'
print(len(s))
print(s)
print('-' * 50)
msg = """
aaaaaaaaa
bbbbbb''''bbbbb
ccccccc
"""
print(msg)
|
def partial_async_gen(f, *args):
"""
Returns an async generator function which is equalivalent to the passed in function,
but only takes in one parameter (the first one).
"""
async def inner(first_param):
async for x in f(first_param, *args):
yield x
return inner
... |
names = ["Katya", "Max", "Oleksii", "Olesya", "Oleh", "Yaroslav", "Anastasiia"]
age = [25, 54, 18, 23, 45, 21, 21]
isPaid = [True, False, True, True, False, True, False]
namesFromDatabaseClear = names.index("Max")
ageMax = age[namesFromDatabaseClear]
print(ageMax)
|
# -*- coding: utf-8 -*-
SEXO = (
('F', 'Feminino'),
('M', 'Masculino'),
) |
"""Exports Standard Interface Template boundary conditions."""
# 1. Standard python modules
# 2. Third party modules
# 3. Aquaveo modules
# 4. Local modules
__copyright__ = "(C) Copyright Aquaveo 2020"
__license__ = "All rights reserved"
class BoundaryConditionsWriter:
"""A class for writing out boundary cond... |
"""This package contains modules for working with Fireplace devices."""
__all__ = (
"fireplace",
"fireplace_device",
"fireplace_light_exception",
"fireplace_pilot_light_event",
"fireplace_state",
"fireplace_state_change_event",
"fireplace_timeout_event"
)
|
"""
Instruction names
"""
POP_TOP = 'POP_TOP'
ROT_TWO = 'ROT_TWO'
ROT_THREE = 'ROT_THREE'
DUP_TOP = 'DUP_TOP'
DUP_TOP_TWO = 'DUP_TOP_TWO'
NOP = 'NOP'
UNARY_POSITIVE = 'UNARY_POSITIVE'
UNARY_NEGATIVE = 'UNARY_NEGATIVE'
UNARY_NOT = 'UNARY_NOT'
UNARY_INVERT = 'UNARY_INVERT'
BINARY_MATRIX_MULTIPLY = 'BINARY_MATRIX_MULTIPL... |
h = float(input("Entre com a altura da pessoa: "))
pH = (72.7 * h) - 58
pM = (62.1 * h) - 44.7
print(f"O peso ideal de uma pessoa de {h}m é {pH:.0f}kg se for homem e {pM:.0f}kg se for mulher") |
cats_path = "python_crash_course/exceptions/cats.txt"
dogs_path = "python_crash_course/exceptions/dogs.txt"
try:
with open(cats_path) as file_object:
cats = file_object.read()
print("Koty:")
print(cats)
except FileNotFoundError:
pass
try:
with open(dogs_path) as file_object:
dogs =... |
def has_unique_chars(string: str) -> bool:
if len(string) == 1:
return True
unique = []
for item in string:
if item not in unique:
unique.append(item)
else:
return False
return True |
#
# PySNMP MIB module ChrComPmSonetSNT-PFE-Interval-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrComPmSonetSNT-PFE-Interval-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:20:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... |
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'local_database.db',
'TEST_NAME': ':memory:',
}
}
SECRET_KEY = '9(-c^&tzdv(d-*x$cefm2pddz=0!_*8iu*i8fh+krpa!5ebk)+'
ROOT_URLCONF = 'test_project.urls'
TEMPLATE_DIRS = (
'templates',
)
INSTALL... |
class Course:
def __init__(self, link, code, title, credits, campus, dept, year, semester, semester_code, faculty, courselvl, description, prereq, coreq, exclusion, breadth, apsc, flags):
self.link = link.strip()
self.code = code.strip()
self.title = title.strip()
self.credits = credits.strip()
self.campus ... |
# Generates comments with the specified indentation and wrapping-length
def generateComment(comment, length=100, indentation=""):
out = ""
for commentChunk in [
comment[i : i + length] for i in range(0, len(comment), length)
]:
out += indentation + "// " + commentChunk + "\n"
return out
... |
"""Error definitions."""
class VictimsDBError(Exception):
"""Generic VictimsDB error."""
class ParseError(VictimsDBError):
"""Error parsing YAML files."""
|
# Copyright (c) 2021, NakaMetPy Develoers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# Original source lisence:
# Copyright (c) 2008,2015,2016,2018 MetPy Developers.
#
# kinematics
g0 = 9.81 # 重力加速度 m/s**2
g = g0
g_acceralation = g0 # 重力加速度 m/s**2
Re = 6371.2... |
# -*- coding: utf-8 -*-
class Solution:
def exist(self, board, word):
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
if self.startsHere(board, word, visited, 0, i, j):
return True
return False
def startsHere(s... |
"""
1. Clarification
2. Possible solutions
- Brute force
- HashSet
3. Coding
4. Tests
"""
# # T=O(mn), S=O(1)
# class Solution:
# def numJewelsInStones(self, jewels: str, stones: str) -> int:
# return sum(s in jewels for s in stones)
# T=O(m+n), S=O(m)
class Solution:
def numJewelsInStones(s... |
#-------------------------------------------------------------------------------
# Name: Removing duplicates
# Purpose:
#
# Author: Ben Jones
#
# Created: 03/02/2022
# Copyright: (c) Ben Jones 2022
#-------------------------------------------------------------------------------
new_menu = [... |
'''
Created on Aug 9, 2018
@author: david avalos
'''
boolean = True
while boolean:
operacion = input("Qué operación desea realizar?\n1.Suma\n2.Resta\n3.Multiplicación\n4.División\n5.Salir\n\n->")
if operacion == "5":
break
try:
if int(operacion) > 5:
print("La opción sele... |
word_size = 8
num_words = 256
num_banks = 1
tech_name = "freepdk45"
process_corners = ["TT"]
supply_voltages = [1.0]
temperatures = [25]
|
# Definition for a binary tree node.
# class Node(object):
# def __init__(self, val=" ", left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
def post_order(node):
... |
# Panel settings: /project/<default>/api_access
PANEL_DASHBOARD = 'project'
PANEL_GROUP = 'default'
PANEL = 'api_access'
# The default _was_ "overview", but that gives 403s.
# Make this the default in this dashboard.
DEFAULT_PANEL = 'api_access'
|
"""
Representing a single file in a commit
@name name of file
@loc lines of code in file
@authors all authors of the file
@nuc number of unique changes made to the file
"""
class CommitFile:
def __init__(self, name, loc, authors, lastchanged, owner,co_commited_files,adev):
self.name = name ... |
# python stack using list #
my_Stack = [10, 12, 13, 11, 33, 24, 56, 78, 13, 56, 31, 32, 33, 10, 15] # array #
print(my_Stack)
print(my_Stack.pop())
# think python simple just pop and push #
print(my_Stack.pop())
print(my_Stack.pop())
print(my_Stack.pop())
|
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School']) |
'''
URL: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
Difficulty: Easy
Description: Maximum Nesting Depth of the Parentheses
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
It is an empty string "", or a single character not equal to "(" or ")",
It c... |
# example of except/from exception usage
try:
1 / 0
except Exception as E:
raise NameError('bad') from E
"""
Traceback (most recent call last):
File "except_from.py", line 4, in <module>
1 / 0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Trac... |
#
# PySNMP MIB module CISCO-EVC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EVC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:57:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
"""
A module to show off dictionary comprehension.
Dictionary comprehension is similar to list comprehension
except that you put the generator expression inside of {}
instead of [].
Author: Walker M. White (wmw2)
Date: October 28, 2020
"""
GRADES = {'jrs1':80,'jrs2':92,'wmw2':50,'abc1':95}
def histogram(s):
"... |
""" Model a record """
class Record(object):
def __init__(self, gps_lat=None, gps_long=None, company_name=None, search_url=None,
xpath_pattern=None, company_email=None):
self.gps_lat = gps_lat
self.gps_long = gps_long
self.company_name = company_name
self.search_u... |
#
# PySNMP MIB module ALPHA-RECTIFIER-SYS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALPHA-RECTIFIER-SYS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:20:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
# O(n) time | O(1) space
def twoNumberSum(array, targetSum):
# Write your code here.
result = []
for num in array:
offset = targetSum - num
if offset in array:
result = [offset, num]
return result
# def twoNumberSum(array, targetSum):
# for i in range(len(array)-1):
# for k in range(i+1, len(array)... |
class MockMail:
def __init__(self):
self.inbox = []
def send_mail(self, recipient_list, **kwargs):
for recipient in recipient_list:
self.inbox.append({
'recipient': recipient,
'subject': kwargs['subject'],
'message': kwargs['message']
... |
string = input()
string_length = len(string)
print(string_length)
string = input()
if len(string) < 5:
print("Ошибка! Введите больше пяти символов!")
string = input()
if not string:
print("Ошибка! Введите хоть что-нибудь!")
string = input()
if len(string) == 0:
print("Ошибка! Введите хоть что-нибудь!")
|
class Text:
""" The Plot Text Text Template
"""
def __init__(self, text=""):
"""
Initializes the plot text Text
:param text: plot text text
:type text: str
"""
self.text = text
self.template = '\ttext = "{text}";\n'
def to_str(self):
"""
... |
for x in range(0, 11):
for c in range(0, 11):
print(x, 'x', c, '= {}'.format(x * c))
print('\t')
|
def escreverPratos():
for i in range(0, t):
op = int(input("\nEscolha o prato de sua preferência: "))
if op == 1:
vet.append("Bobó de Camarão")
vetPrecoPrato.append(25.90)
if op == 2:
vet.append("Moqueca de Camarão")
vetPrecoPrato.append(29.90)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 19 17:53:46 2017
@author: benjaminsmith
"""
#do the regression in the
#we need a design matrix
#with linear, square, cubic time point regressors
#plus intercept
#plus whatever Design_Matrix files we want to put in.
onsets_convolved.head()
onsets... |
# Main network and testnet3 definitions
params = {
'argentum_main': {
'pubkey_address': 23,
'script_address': 5,
'genesis_hash': '88c667bc63167685e4e4da058fffdfe8e007e5abffd6855de52ad59df7bb0bb2'
},
'argentum_test': {
'pubkey_address': 111,
'script_address': 196,
... |
""" Utilities for Cloud Backends """
def parse_remote_path(remote_path):
"""
Parses a remote pathname into its protocol, bucket, and key. These
are fields required by the current cloud backends
"""
# Simple, but should work
fields = remote_path.split("/")
assert len(fields) > 3, "Improper... |
#52 Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
contador = 0
numero = int(input('Digite um número: '))
x = numero
for x in range(1,numero+1):
if numero % x == 0:
contador += 1
print(f'O número {numero} foi divisível {contador} vezes')
if contador == 2:
print(f'E ... |
# Crie um programa que tenha uma Tupla unica com nomes de produtos e seus respectivos preços na sequencia.
# No final, mostre uma listagem de preços, organizando os dados em forma tabular.
'''Dá para fazer em 2 linhas...
for i in range(0, len(prod), 2):
print(f'{prod[i]:.<30}R${prod[i + 1]:7.2f}')'''
produtos = (... |
def add_time(start, duration, day=None):
hour, minutes = start.split(':')
minutes, am_pm = minutes.split()
add_hour, add_min = duration.split(":")
hour = int(hour)
minutes = int(minutes)
add_hour = int(add_hour)
add_min = int(add_min)
n = add_hour // 24
rem_hour = add_hour % 24
n... |
string = '<option value="1" >Malda</option><option value="2" >Hooghly</option><option value="3" >Calcutta</option><option value="4" >Jalpaiguri</option><option value="6" >Coochbehar</option><option value="7" >Paschim Medinpur</option><option value="8" >Birbhum</option><option value="9" >Purba Medinipur</option><option ... |
class Calls(object):
def __init__(self):
self.calls = []
def addCall(self, call):
self.calls.append(call)
def endCall(self, call):
for c in self.calls:
if call.ID == c.ID:
self.calls.remove(call)
def searchCall(self, call_id):
for c in self.... |
# Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite
# restaurants represented by strings.
# You need to help them find out their common interest with the least list index sum. If there is a
# choice tie between answers, output all of them with no order requirement. Yo... |
def gcd(a,b):
if a < b:
a, b = b, a
if b == 0:
return a
return gcd(b, a %b)
def gcdlist(l):
if len(l) == 2:
return gcd(l[0], l[1])
f = l.pop()
s = l.pop()
m = gcd(f, s)
l.append(m)
return gcdlist(l)
def main():
n, x = map(int, input().split())
a = [... |
#! /bin/env python3
''' Class that represents a bit mask.
It has methods representing all
the bitwise operations plus some
additional features. The methods
return a new BitMask object or
a boolean result. See the bits
module for more on the operations
provided.
'''
class BitMask(int):
def AND(self,bm):
r... |
n,reqsum=map(int,input().split())
a=list(map(int,input().split()))
arr=[]
for i in range(1,n+1):
arr.append([i,a[i-1]])
arr=sorted(arr,key=lambda x:x[1])
#print(arr)
i=0
j=n-1
while(i<=j and i!=j):
#print("{}+{}={}".format(arr[i][1],arr[j][1],arr[i][1]+arr[j][1]))
if(arr[i][1]+arr[j][1]==reqsum):
pr... |
'''
Leia 2 valores inteiros X e Y. A seguir, calcule e mostre a soma dos números impares entre eles.
Entrada
O arquivo de entrada contém dois valores inteiros.
Saída
O programa deve imprimir um valor inteiro. Este valor é a soma dos valores ímpares que estão entre os valores fornecidos na entrada que deverá caber em ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
preorderList = list()
def preorderTraversal(root... |
str = "Python Program"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
print(str[5])
print(str[0:8])
print(str[::-1]) #to reverse the string |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# 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 ... |
"""Persian alphabet"""
#Persian digits from 0 to 9
DIGITS = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']
#Diacritics
SHORT_VOWELS = ['َ', 'ِ', 'ُ', 'ْ']
#The Persian Alphabet
LONG_VOWELS = ['ا', 'و', 'ی']
CONSONANTS = ['ء', 'ب', 'پ', 'ت', 'ث', 'ج', 'چ', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'ژ', 'س', 'ش', 'ص', 'ض', ... |
class BaseContext(object):
"""
Base class for contexts.
Most views in this app will use a database connection. This class will
add an instance attribute for the database session and the request.
"""
def __init__(self, request):
self._request = request
self._db = self._request... |
class Solution:
def countOrders(self, n: int) -> int:
"""
n! * (1 * 2 * 3 * (2n - 1))
n == 3
==> (1 * 2 * 3) * (1 * 3 * 5)
==> 1 * 1 * 2 * 3 * 3 * 5
result = 1
for i: 1 to n
result *= i * (2*n - 1)
"""
result = 1
... |
"""
Mycroft Holmes core
"""
VERSION = '0.3'
|
impar = 0
par = 0
for i in range(200):
num = int(input())
if num % 2 == 0:
par += 1
else:
impar += 1
print(f'Você inseriu {impar} números ímpares e {par} números pares.')
|
celcius = float(input('Digite a temperatura em Celsius: '))
fahr = (celcius * 9 / 5) + 32
print(f'A temperatura {celcius}°C fica {fahr}°F')
|
vid_parttern = r''
class Video:
def __init__(self):
pass
|
expected_output = {
'Node number is ': '1',
'Node status is ': 'NODE_STATUS_UP',
'Tunnel status is ': 'NODE_TUNNEL_UP',
'Node Sudi is ': '11 FDO25390VQP',
'Node Name is ': '4 Node',
'Node type is ': 'CLUSTER_NODE_TYPE_MASTER',
'Node role is ': 'CLUSTER_NODE_ROLE_LEADER'
}
|
# def get_sql(cte, params, company, conn, gl_code):
#
# sql = cte + ("""
# SELECT
# a.op_date AS "[DATE]", a.cl_date AS "[DATE]"
# , SUM(COALESCE(b.tran_tot, 0)) AS "[REAL2]"
# , SUM(COALESCE(c.tran_tot, 0) - COALESCE(b.tran_tot, 0)) AS "[REAL2]"
# , SUM(COA... |
class Service:
def __init__(self):
self.base = 7
def set_val(self, val):
self.func_val = val
def get_val(self):
return self.func_val
class Service2(Service):
def __init__(self): # pragma: no cover
self.base = 8
|
__author__ = 'roeiherz'
"""
Write a method to return all subsets of a set
"""
def power_set(subset):
n = len(subset)
# Stop case
if n != 0:
print(subset)
for i in range(n):
new_lst = subset[:i] + subset[i + 1:]
power_set(new_lst)
def power_set_memo(subset, mem):
n = len... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.