content stringlengths 7 1.05M |
|---|
#Reverse the input array
# input : {5,4,3,2,1}
# output : {1,2,3,4,5}
arr = list(map(int,input().split()))
for i in range(len(arr)):
arr.push(a[-1])
arr.remove(a[-1])
print(arr) |
def mergesort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = items[:mid]
right = items[mid:]
left = mergesort(left)
right = mergesort(right)
return merge(left, right)
def merge(left, right):
merged = []
left_index = 0
right_index... |
#Se crean los inputs
rate = input("Enter Rate:")
hrs = input("Enter Hours:")
#Se toman los valores y se convierten en float ambos por que string y float no se pueden multiplicar directamente
pay = float(rate) * float(hrs)
#Se imprime el resultado de pay
print("Pay:",pay) |
class response():
def __init__(self) -> None:
self.num = 5
def call_result(self):
return(self.num) |
n = int(input())
if n == 7 or n == 5 or n== 3:
print("YES")
else:
print("NO") |
# SPDX-License-Identifier: MIT
# Copyright (C) 2018-present iced project and contributors
# ⚠️This file was generated by GENERATOR!🦹♂️
# pylint: disable=invalid-name
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
"""
x86 instruction code
"""
INVALID: int = 0
"""
It's an invalid instruction, eg. ... |
# Sample program illustrating programmer-defined functions
# along with code that calls the functions
#
# The 'cube_root' function uses a 'return' statement. Its
# only job is to calculate and "return" the cube root of a
# number. It does not print anything. Notice that statements
# that "call" the 'cube_root' func... |
class Wallet:
def __init__(self, stocks, initial_account=3000):
self.stocks_amount = 0
for stock in stocks:
self.stocks_amount += stock.getCostPrice()
self.available_cash = initial_account - \
self.stocks_amount # argent disponible en cash
self.virtual_acco... |
class Node:
def __init__(self, parent, rank=0, size=1):
self.parent = parent
self.rank = rank
self.size = size
def __repr__(self):
return '(parent=%s, rank=%s, size=%s)' % (self.parent, self.rank, self.size)
class Forest:
def __init__(self, num_nodes):
self.nodes = ... |
"""
Temperature Scale Converter
- Converts celsius sclae to fahrenheit and vice-versa
Author : (Niyoj Oli)[https://github.com/niyoj]
Date : 24/09/21
"""
temp = input("Input the temperature you would like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() =... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Irreversible Lock Date',
'version': '1.0',
'category': 'Accounting/Accounting',
'description': """
Make the lock date irreversible:
* You cannot set stricter restrictions on advisors th... |
"""Arquivo a ser enviado ao sistema"""
def desafio1(number):
"""Função que retorna o valor entrado"""
return 0
|
load("@rules_pmd//pmd:dependencies.bzl", "rules_pmd_dependencies")
load("@bazelrio//:defs.bzl", "setup_bazelrio")
load("@bazelrio//:deps.bzl", "setup_bazelrio_dependencies")
def setup_dependencies():
rules_pmd_dependencies()
setup_bazelrio_dependencies(
toolchain_versions = "2022-1",
wpilib_ver... |
"""
Classes example based on:
http://interactivepython.org/runestone/static/pythonds/Introduction/
ObjectOrientedProgramminginPythonDefiningClasses.html
@author Alex Sáez
"""
class LogicGate(object):
def __init__(self, name):
self.name = name
self._output = None
def connect_output_to(self, o... |
class Selectors(object):
def setup_bot(self, settings, spec, items, extractors, logger):
self.logger = logger
self.selectors = {} # { template_id: { field_name: {..} }
for template in spec['templates']:
template_id = template.get('page_id')
self.selectors[template_i... |
print('TABUADA')
n = int(input('Digite um numero: '))
n1 = n *1
n2 = n *2
n3 = n *3
n4 = n *4
n5 = n *5
n6 = n *6
n7 = n *7
n8 = n *8
n9 = n *9
n10= n *10
print('-----------\n{} x 1 = {}\n{} x 2 = {}\n{} x 3 = {}\n{} x 4 = {}\n{} x 5 = {}\n{} x 6 = {}\n{} x 7 = {}\n{} x 8 = {}\n{} x 9 = {}\n{} x 10 = {}\n-----... |
# -----------------------------------------------------------------------
print('\033[32;1mDESAFIO 030 - Par ou Ímpar\033[m')
print('\033[32;1mALUNO:\033[m \033[36;1mJoaquim Fernandes\033[m')
print('-' * 50)
# -----------------------------------------------------------------------
tipo = ['Par', 'Ímpar']
num = int(inpu... |
"""
Escribe un programa que haga cuente cuantas veces aparece un número en una tupla que añadiremos
de manera DINÁMICA, ya que puede cambiar el valor de entrada.
Guardarla en una tupla de este estilo:
((número-buscado, apariciones), (número-buscado, apariciones), (número-buscado, apariciones))
Usando un ejemplo real:
E... |
# Daniel Mc Callion
# function yo takes one parameter
def yo(a):
return a * 2
# here we are calling the function yo
# and are passingin an argument, 3
yo(3)
# a. nothing no print but returns 6
# b. print(yo(3))
|
result = [0, 0, 0]
diff = 22
for a in range(int(200/21.99) + 1):
for b in range(int((200 - 21.99*a)//18.05)+1):
c = int((200 - 21.99 * a - 18.05 * b)//15.99) + 1
if diff > (21.99 * a + 18.05 * b + 15.99 * c - 200):
diff = 21.99 * a + 18.05 * b + 15.99 * c - 200
result = [a, b... |
# question can be found on leetcode.com/problems/count-odd-numbers-in-an-interval-range/
class Solution:
def countOdds(self, low: int, high: int) -> int:
number = (high - low + 1) // 2
if low % 2 != 0 and high % 2 != 0:
return number + 1
else:
return number
|
# -*- coding: utf-8 -*-
__all__ = [
'BASE',
'LB',
'TOPOLOGY_MAP'
]
BASE = {
# can be overriden by a configuration file
'SHARED_MEM_HOSTNAME': '127.0.0.1',
'SHARED_MEM_STATE_TIMESTAMP_KEY': 'polaris_health:state_timestamp',
'SHARED_MEM_GENERIC_STATE_KEY': 'polaris_health:generic_state',
... |
def subtract(a,b):
c=a-b
return c
def summate(a,b):
c=a+b
return c
def sumKM(a,b):
c=(a+b)/1000.
return c
def minusX10(a,b):
c = (a-b)*10
return c
def divAdd5(a,b):
c = (a/b)+5
return c
if __name__ == "__main__":
print("Run from import") |
class Solution:
def smallestEqual(self, nums: List[int]) -> int:
smallest = -1
for i in range(0, len(nums)):
if i % 10 == nums[i]:
if smallest == -1:
smallest = i
else:
if i < smallest:
smalle... |
#!/usr/bin/env python
# coding: utf-8
"""
Implement a MyCalendar class to store your events. A new event can be added if
adding the event will not cause a double booking.
Your class will have the method, book(int start, int end). Formally, this
represents a booking on the half open interval [start, end), the range of... |
PROTO = {
'spaceone.monitoring.api.plugin.webhook': ['Webhook'],
'spaceone.monitoring.api.plugin.event': ['Event'],
}
|
"""
26. Numa eleição existem três candidatos. Faça um programa que peça o número
total de eleitores. Peça para cada eleitor votar e ao final mostrar o número
de votos de cada candidato.
"""
total_eleitores = int(input("Informe a quantidade de eleitores: "))
votos = []
cand_1 = 0
cand_2 = 0
cand_3 = 0
for x in rang... |
def do_twice_mod(func, value):
'''
Input
func: Un objeto funcion.
value: valor que se le pasa al objeto funcion.
'''
func(value)
func(value)
def print_twice(arg):
'''
Input
arg: argumento a imprimir.
'''
print(arg)
print(arg)
#do_twice_mod(print_twice, 'spam')
de... |
# The MIT License (MIT)
#
# Copyright (c) 2014-2016 Benedikt Schmitt <benedikt@benediktschmitt.de>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without lim... |
# pylint: disable=invalid-name,used-before-assignment,missing-docstring
if xeo > 5: # [cond-expr]
xeo = 5
else:
xeo = 6
if xeo > 5:
xeo = 5
else:
beo = 6
|
# Scrapy settings for sydney project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'sydney'
SPIDER_MODULES = ['sydney.spiders']
NEWSPIDER_MODULE = 'sydney.spide... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 这种写法是错的
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
# 使用递归的方法,中序遍历
if root.left:
# 不是空,才继续遍历
return self.kthSmallest(root.left, k... |
def addition():
a = 10
b = 45
print(a + b)
addition()
def addition():
a = int(input("Enter a number "))
b = int(input("Please enter another number "))
print(a + b)
addition()
def user_info(name, age, info):
'''This function print name age and city from an argument provided '''
p... |
a=[]
e=a
b=''
while True:
b=input('Enter Number(Use String To Break):')
if b.isalpha():
break
else:
a.append(int(b))
while len(a)>0:
c=a[0]
for x in a:
d=0
if c==x:
d+=1
a.remove(x)
else:
continue
print ("Number:",c)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
spinMultiplicity = 2
energy = {
'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('energy.out'),
#'CCSD(T)-F12/cc-pVTZ-F12':-382.9466871191517,
}
frequencies = GaussianLog('ts5-freq.log')
rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[1,2], top=[2,9,10,11... |
actionHandlers = { }
toolTipHandlers = { }
resultProvidersCached = { }
resultProvidersUncached = { }
# name : string
# getItemGroupsCached: () -> [itemGroup]
# getItemGroupsUncached: () -> [itemGroup]
def registerResultProvider(name, getItemGroupsCached, getItemGroupsUncached):
resultProvidersCached[name] = getItemG... |
"""
https://leetcode.com/problems/merge-two-sorted-lists/
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
@staticmethod
def to_list(node, result=[]):
"""
Recursive method to represent linked lis... |
"""
Link - https://leetcode.com/problems/valid-parentheses/
Problem Description :
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be... |
"""
Heap representation of priority queue as described in Section 2.4, pg 313
Python has its own implementation:
https://docs.python.org/3.6/library/heapq.html
https://github.com/python/cpython/blob/master/Lib/heapq.py
"""
class MaxHeap:
def __init__(self, keys=[]):
self._size = 0
self._heap = [N... |
class UserNotifyEvent:
ACCOUNT_CONFIRMATION = "account_confirmation"
ACCOUNT_PASSWORD_RESET = "account_password_reset"
ACCOUNT_CHANGE_EMAIL_REQUEST = "account_change_email_request"
ACCOUNT_CHANGE_EMAIL_CONFIRM = "account_change_email_confirm"
ACCOUNT_DELETE = "account_delete"
ACCOUNT_SET_CUSTOME... |
"""Constants for the kmtronic integration."""
DOMAIN = "kmtronic"
CONF_HOSTNAME = "host"
CONF_USERNAME = "username"
CONF_PASSWORD = "password"
DATA_HUB = "hub"
DATA_HOST = "host"
DATA_COORDINATOR = "coordinator"
MANUFACTURER = "KMtronic"
ATTR_MANUFACTURER = "manufacturer"
ATTR_IDENTIFIERS = "identifiers"
ATTR_NAME ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Super:
def method(self):
print('in Super.method')
def delegate(self):
self.action()
class Inheritor(Super):
pass
class Replacer(Super):
def method(self):
print('in Replacer.method')
class Extender(Super):
def method(sel... |
class MaxQueue(object):
def __init__(self):
self.queue = []
self.max_queue = []
def enqueue(self, num):
self.queue.append(num)
while self.max_queue and self.max_queue[-1] < num:
self.max_queue.pop()
self.max_queue.append(num)
def dequeue(self):
... |
def v(arr):
i = n - 2
while (i >= 0) and\
(arr[i] >= arr[i + 1]):
i -= 1
if i >= 0:
j = i + 2
while (j < n) and\
(arr[j] > arr[i]):
j += 1
arr[i], arr[j - 1] = \
arr[j - 1], arr[i]
return [*arr[:i + 1],
... |
print("-"*17)
print(" Meters to cm/mm ")
print("-"*17)
meters = float(input("Type a value: "))
cm = meters*100
mm = meters*1000
print("{} meters in centimeters is: {} centimeters \nIn millimeters is: {} millimeters".format(meters,cm,mm)) |
# Exercício 6.8 - Modifique o primeiro exemplo (Listagem 6.23) de forma a realizar
# a mesma tarefa, mas sem utilizar a variável achou. Dica: observe a condição de
# saída do while.
lista = [15, 7, 27, 39, 99, 33, 22, 55, 77, 28, 59]
print('\n')
print(lista)
valor = int(input("Informe o valor que deseja procurar na l... |
# encoding: utf-8
# module Autodesk.Gis.Map.Platform.Utils.Globalization calls itself Globalization
# from Autodesk.Map.Platform.Utils, Version=24.0.30.14, Culture=neutral, PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class EnumTypeConverter(EnumConverter):
""" EnumTypeC... |
init = int(input("Start index: "))
end = int(input("End index: "))
def sr(integer):
x = -1
while x < integer:
s = None
if x * x == integer:
s = str(x)
break
x += 1
return s
m = init
ps = []
while m <= end:
if sr(m) != None:
ps.... |
class temporal:
'''This is an abstract class'''
class MensajeOut:
tipo='normal'
mensaje=''
codigo=''
class MensajeTs:
instruccion=''
identificador=''
tipo=''
referencia=''
dimension=''
class Tabla_run:
def __init__(self, basepadre, nombre, atributos=[]):
self.basepadr... |
# Given a collection of intervals, merge all overlapping intervals.
# Example 1:
# Input: [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
# Example 2:
# Input: [[1,4],[4,5]]
# Output: [[1,5]]
# Explanation: Intervals [1,4] ... |
num = 10
while num:
print(num)
num = num - 1
|
a = int(input())
b = int(input())
if a < b:
for i in range(a, b + 1):
print(i, end=' ')
else:
for i in range(a, b - 1, -1):
print(i, end=' ')
|
#
# PySNMP MIB module ERI-DNX-APS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ERI-DNX-APS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:51:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
#!/usr/bin/python3
""" 5. Raise exception """
def raise_exception():
""" raise_exception """
raise TypeError
|
__all__ = [
'admins', 'aliases', 'alternatives', 'base', 'domains', 'fetches',
'managers', 'users', 'relays', 'tokens', 'api'
]
|
"""
Return the smallest possible int that is not already in the list
"""
def solution(A):
#print('---')
#print(A)
l = filter(lambda x: x>0, A)
l_st = set(l)
l = list(l_st)
#print (l)
if not l:
return 1
l.sort()
#if 1 not in l:
#return 1
if l[0] > 1:
... |
###############################################################################
#
# Copyright (c) 2016 Wi-Fi Alliance
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear... |
__author__ = 'davidl'
def set_status(execution_id, process_id, uut, test, verdict):
pass
def set_results(execution_id, process_id, uut, test, results):
pass
|
expressão = str(input('Digite uma expressão matemática: '))
lista = []
for c in expressão:
if c == '(':
lista.append('(')
elif c == ')':
if len(lista) > 0:
lista.pop()
else:
lista.append(')')
break
if len(lista) == 0:
print('A expressão é válida.')... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 17 12:50:48 2020
@author: Cliff
"""
#Generator/Filter
#-------------------------------------------------------
#Generator using the filter function
#The gererator prints a list of all numerical value and filters out the
#strings.
my_list = [1,"x",2,"y","3","z",3]
def my... |
primo = int(input('Digite um número: '))
vezes = 0
for c in range(1, primo + 1):
if primo % c == 0:
vezes = vezes + 1
if vezes == 2: #Aqui estamos limitando ao computador apresentar somente os números divisivel por 1 e ele mesmo.
print('Primo')
else: #Se a contagem do número analisado não maior que 2 n... |
# Given two strings, check if one is a permutation of the other
def check_permutation(str1, str2):
freq1 = {}
freq2 = {}
for char in str1:
if freq1.get(char):
freq1[char] += 1
else:
freq1[char] = 1
for char in str2:
if freq2.get(char):
freq2[char] += 1
else:
freq2[char... |
__example_payload__ = "SELECT FIELD FROM information_schema.tables"
__type__ = "changing specific payload characters into their Unicode equivalent"
def tamper(payload, **kwargs):
unicode_changes = {
'1': 'B9', '2': 'B2', '3': 'B3', 'D': 'D0',
'T': 'DE', 'Y': 'DD', 'a': 'AA', 'e': 'F0',
'o'... |
def calcAQI(cp, ih, il, bph, bpl):
a = (ih - il)
b = (bph - bpl)
c = (cp - bpl)
return int((a /b) * c + il)
def aqi_from_pm(pm):
if (pm > 350.5):
return calcAQI(pm, 500, 401, 500, 350.5)
elif (pm > 250.5):
return calcAQI(pm, 400, 301, 350.4, 250.5)
elif (pm > 150.5):
... |
def swap(a: int, b: int, arr: list):
"""swap elements of array
Args:\n
a (int): index 1
b (int): index 2
arr (list): list of elements
"""
if a != b:
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def partition(elements: list, start: int, end: int) -> int:
... |
#“ 4 ” +“ 5”不一定等于 “ 9 ”
a = 4
b = 5
print(a + b)
print("4"+"5")
|
class VocabDictionary:
def __init__(self, unk="<unk>", pad="<pad>"):
self.dictionary = {}
self.tokens = []
self.unk = unk
self.pad = pad
self.pad_index = self.add_symbol(self.pad)
self.unk_index = self.add_symbol(self.unk)
def __len__(self):
return len(se... |
'''
James Halladay
Copyright (c) 2021
Multi-Layer Grid (MLG) Neural Network
An improvement on the Feed-Forward Neural Network Multi-Layer Perceptron (MLP) model.
The MLP model is a simple feed-forward neural network that is trained to classify
the input data into a set of categories.
The MLG model... |
##
## ROOT Module
##
## This is a sample dynamic module for the system.
##
def do(n,b):
# Declare Keyword (important)
keyword = "root"
# Check if Keyword in Body (important)
if keyword in b:
return "Ok"
else:
# Returns a False if Keyword not in Body (important)
return False... |
N = int(input())
arr = []
for _ in range(N):
arr.append(int(input()))
arr.sort()
for attr in arr:
print(attr) |
# File: microsoftscom_consts.py
#
# Copyright (c) 2017-2022 Splunk 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 ... |
compra = []
#error linia 30
while True:
print("0. Salir")
print("1. Ver lista de la compra")
print("2. Agregar producto a la lista")
print("3. Modificar producto de la lista")
print("4. Quitar producto de la lista")
try:
elegir_opcion = input()
elegir_opcion= int(elegir_opcion)
... |
''' Master class for payments '''
class BasePayments(object):
''' Base class for payments and interfacing with external subscription systems '''
def __init__(self, user=None, config=None, rdb=None):
''' Initialize the Payments Class '''
self.user = user
self.config = config
sel... |
nome = input('Digite seu nome completo: ')
listaNomes = nome.split()
print("""Muito prazer em te conhecer!
Seu primeiro nome é {}
Seu último nome é {}""".format(listaNomes[0], listaNomes[len(listaNomes)-1]))
|
class Solution(object):
def firstMissingPositive(self, nums):
i = 0
while i < len(nums):
if 0 < nums[i] <= len(nums) and nums[nums[i] - 1] != nums[i]:
nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
else:
i += 1
for i in range(0, len(nums)):
if nums[i] != i + 1:
... |
class BYUJWTError(Exception):
"""Error handling BYU JWT"""
class JWTVerifyError(BYUJWTError):
"""Error Verifing JWT"""
class JWTHandlerError(BYUJWTError):
"""Error while handling JWT"""
|
def print_hi(name):
print(f'hi, {name}')
if __name__ =='__main__':
print_hi('PyCharm')
|
class Grafo:
def __init__(self, vertices):
self.vertices = vertices
self.grafo = [[0]*self.vertices for i in range(self.vertices)]
def adiciona_aresta(self, u, v, peso):
# estou pensando em grafos direcionados simples
self.grafo[u-1][v-1] = peso #trocar = por += ser for grafo ... |
"""
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must ... |
#!/usr/bin/python3
"""Create Terraform Modules."""
def create_vpc(region, pbsubnet, pvsubnet, source):
"""Create Terraform Module for AWS VPC."""
tf_module_vpc = {
"source": "%s/m-aws-vpc" % source,
"awsRegion": region,
"public_subnet_cidr": pbsubnet,
"private_subnet_... |
# Title : Print square of number, limit specified by the user.
# Author : Kiran raj R.
# Date : 24:10:2020
userInput = input(
"Enter the limit till you need to print the sqaure of numbers :")
square_list = []
for i in range(1, int(userInput)+1):
square_list.append(i**2)
print(square_list)
|
# -----------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -----------------------------------------------------------------------------
""... |
#!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple ... |
class Solution:
no_remove = True
def validPalindrome(self, s: str) -> bool:
lp = 0
rp = len(s)-1
no_remove = True
while lp < rp:
if s[lp] == s[rp]:
lp += 1
rp -= 1
elif self.no_remove:
self.no_remove = False... |
"""Exercício Python 48: Faça um programa que calcule a soma entre todos os números impares que são múltiplos de três
e que se encontram no intervalo de 1 até 500."""
soma = 0
cont = 0
for num in range(1, 501, 2):
if num % 3 == 0:
cont = cont + 1
soma = soma + num
print('\033[1;34mA soma de todos os... |
# 52
# Create a polygon class and a rectangle class
# that inherits from the polygon class and finds the square of rectangle.
# Создайте класс многоугольника и класс прямоугольника
# который наследуется от класса многоугольника и находит площадь прямоугольника.
class Polygon:
def __init__(self, no_of_sides):
... |
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
OneDec = False
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
if OneDec:
return False
OneDec = True
if i > 1 and nums[i - 2] > nums[i] and i <... |
text = input()
save_odd = []
save_even = []
receve = text.split("|")
while True:
command = input().split()
if command[0] == "Done":
final = "".join(map(str, receve))
print(f"You crafted {final}!")
break
if command[0] == "Move" and command[1] == "Left":
position = int(comm... |
while True:
print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'subtract' to subtract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input... |
# You are given a list containing letters of a name. Print them out
# as a string with these chars separated by hyphens and with an
# exclamation point in the end. Do so using arguments of the
# print() function!
# So, if the letters in the list name are ['K', 'A', 'T', 'E'], your
# program should print the string 'K-... |
cite = clipboard.get_selection().encode('ascii', 'ignore')
keyboard.send_key("<delete>")
try:
cite = "(" + cite.replace(" (", ", ")
cite = re.sub("[., ]*$", ".", cite)
keyboard.send_keys(cite)
except Exception as ex:
val = type(ex).__name__ + " " + ex.args[0]
keyboard.send_keys(val) |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 21:19:10 2022
@author: ACER
"""
#comentarios en linea
"""
comentarios en linea
Linea 1
Linea 2
"""
#crear una constante
"""
NAME = 'Adriana'
FULL_NAME = 'adriana muñoz rojas'
print (NAME)
print (FULL_NAME)
# tipos de datos
entero = 90
print (f'el entero tiene valo... |
class Solution:
def minIncrementForUnique(self, A: List[int]) -> int:
A.sort()
sum_ = sum(A)
for k in range(1, len(A)):
if A[k] <= A[k-1]:
A[k] = A[k-1] + 1
return sum(A) - sum_ |
#The classic
print("Hello World")
#Print more things
print("Hello New World") |
with open('input', 'r') as fh:
data = fh.readlines()
for i, line in enumerate(data):
data[i] = list(line.rstrip())
bits = list(zip(*data))
gamma_bits = list()
eps_bits = list()
for bit in bits:
if bit.count('1') > bit.count('0'):
gamma_bits.append('1')
eps_bits.append('0')
else:
... |
fname= 'romeo.txt'
fh = open(fname)
slist = []
for line in fh:
lsl = line.split()
for str in lsl:
if str not in slist:
slist.append(str)
slist.sort()
print(slist)
|
class Issues:
def __init__(self):
self.issue_types = {}
self.issues = {}
def add_issue_type(self, issue_type_id, issue_type_info):
self.issue_types[issue_type_id] = issue_type_info
def add_issue_obj(self, issue_type_id, obj_type, obj_id):
if issue_type_id not in self.issue_... |
#
# @lc app=leetcode.cn id=404 lang=python3
#
# [404] 左叶子之和
#
# https://leetcode-cn.com/problems/sum-of-left-leaves/description/
#
# algorithms
# Easy (48.04%)
# Total Accepted: 4.3K
# Total Submissions: 8.8K
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# 计算给定二叉树的所有左叶子之和。
#
# 示例:
#
#
# 3
# / \
# 9 20
#... |
# -*- coding: utf-8 -*-
def get_client_ip(request):
"""
Returns client ip from request.
Source: http://stackoverflow.com/a/4581997/821594
"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.... |
'''FAÇA UM PROGRAMA QUE TENHA UMA FUNÇÃO CHAMADA maior(), QUE RECEBA VÁRIOS
PARÂMETROS COM VALORES INTEIROS. SEU PROGRAMA TEM QUE ANALISAR TODOS OS VALORES E DIZER
QUAL DELES É O MAIOR.'''
def maior(* num):
cont = maior = 0
print('Analisando os valores passados ... ')
for valor in num:
print(f'{valo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.