content stringlengths 7 1.05M |
|---|
# Problema 2
# Generar una arreglo invertido de n números y después buscar un elemento
def generateList(size):
return list(range(size,0,-1))
def searchInvertArray(array, element):
for i in range(0,len(array)):
if array[i] == element:
return True
return False
# Casos de pru... |
#ID of the project
project_id = ""
#List of paths where the folders to check are
project_paths = []
#Destination of the sync, trailing slash
destination_path = ""
##################################
#Postgres database and rw user
##################################
db_host = ""
db_db = ""
db_user = ""
... |
class Solution:
def summaryRanges(self, nums):
if not nums:
return nums
results = []
start = end = nums[0]
for i in nums:
if i != end:
rng = f"{start}->{end-1}" if start != (end - 1) else f"{start}"
results.append(rng)
... |
class Solution:
def totalNQueens(self, n: int) -> int:
def dfs(row):
if row == 0:
return 1
count = 0
for col in range(n):
if col not in col_blacklist and \
row - col not in major_blacklist and \
row + ... |
N = int(input())
R = []
for i in range(0, N*2) :
if i%2 == 0 : R.append("*")
else : R.append(" ")
for l in range(0, N) :
P1 = P2 = ""
for i in range(0, N) :
P1 += R[i]
print(P1)
for i in range(N*2-1, N-1, -1) :
P2 += R[i]
print(P2) |
#
# PySNMP MIB module SYMMCOMMONPTP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMCOMMONPTP
# Produced by pysmi-0.3.4 at Tue Jul 30 11:34:16 2019
# On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt
# Using Python version 3.7.4 (default, J... |
class Solution:
def search(self, nums, target):
if not nums:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target == nums[mid]:
return mid
if nums[mid] < nums[high]:
# 后半... |
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
non_zeros = [i for i in range(len(nums)) if nums[i] != 0] # List comprehension to keep only numbers that are non -zero
nz = len(non_zeros)
nums[:nz] = [nums[i] for i in non_zeros] # edit the list to add non zero num... |
DEFAULT_OCR_AUTO_OCR = True
DEFAULT_OCR_BACKEND = 'mayan.apps.ocr.backends.tesseract.Tesseract'
DEFAULT_OCR_BACKEND_ARGUMENTS = {'environment': {'OMP_THREAD_LIMIT': '1'}}
TASK_DOCUMENT_VERSION_PAGE_OCR_RETRY_DELAY = 10
TASK_DOCUMENT_VERSION_PAGE_OCR_TIMEOUT = 10 * 60 # 10 Minutes per page
|
input()
c = int(input())
a = sorted((map(int, input().split())))
a.sort(key= lambda x: x%c)
print(*a) |
"""
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Exam... |
def greet(name):
return "Hello {}".format(name)
print(greet("Alice"))
def greet2(name):
def greet_message():
return "Hello"
return "{} {}".format(greet_message(),name)
print(greet2("Alice"))
def change_name_greet(func):
name = "Alice"
return func(name)
print(change_name_greet(greet))
... |
class Helpers(object):
"""
Adds additional helper functions that aren't part of the core or extended
API.
"""
def __init__(self, api):
self.api = api
def is_promotable(self, tail):
# type: (TransactionHash) -> bool
"""
Determines if a tail transaction is promotable.
:param tail:
... |
class FormClosedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.Form.FormClosed event.
FormClosedEventArgs(closeReason: CloseReason)
"""
@staticmethod
def __new__(self, closeReason):
""" __new__(cls: type,closeReason: CloseReason) """
pass
Clos... |
s = b'abc'; print(s.islower(), s)
s = b'Abc'; print(s.islower(), s)
s = b'ABC'; print(s.islower(), s)
s = b'123'; print(s.islower(), s)
s = b'(_)'; print(s.islower(), s)
s = b'(abc)'; print(s.islower(), s)
s = b'(aBc)'; print(s.islower(), s)
s = bytearray(b'abc'); print(s.islower(), s)
s = bytearray(b'Abc'); print(s.i... |
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height)-1
res = 0
area = 0
while i < j:
area = min(height[i],height[j])*(j-i)
#print(area)
res = max(res,area)
if height[i]<height[j]:
i+... |
explanations = {
'gamma': '''
Proportion of tree modifications that should use mutrel-informed choice for
node to move, rather than uniform choice
''',
'zeta': '''
Proportion of tree modifications that should use mutrel-informed choice for
destination to move node to, rather than uniform choice
... |
def _impl(_ctx):
pass
bad_attrs = rule(implementation = _impl, attrs = {"1234isntvalid": attr.int()})
|
# Copyright (c) 2017 Hristo Iliev <github@hiliev.eu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of c... |
#!/usr/bin/env python3
def sleep_in(weekday, vacation):
"""
The parameter weekday is True if it is a weekday, and the parameter
vacation is True if we are on vacation. We sleep in if it is not a
weekday or we're on vacation. Return True if we sleep in.
sleep_in(False, False) → True
sleep_in(T... |
def caesar_encode(phrase, shift):
res=[]
for i,j in enumerate(phrase.split()):
res.append("".join(chr(ord("a")+(ord(k)-ord("a")+shift+i)%26) for k in j))
return " ".join(res) |
expected_output = {
'ints': {
'Ethernet 1/1/1': {
'ip_address': 'unassigned',
'ok': True,
'method': 'unset',
'status': 'up',
'protocol': 'up'
},
'Ethernet 1/1/2': {
'ip_address': 'unassigned',
'ok': True,
... |
""" Ex - 095 - Aprimore o desafio 93 para que ele funcione com vários jogadores, incluindo um sistema
de visualização de detalhes do aproveitamento de cada jogador."""
# Como eu fiz.
# T.L.D.:
cad_joga = dict()
gol_part = list()
dad_jgdr = list()
# Area de desenvolvimeno:
wh... |
class UnshortenerOld():
"""
Todo option selenium ?
"""
def __init__(self,
logger=None,
verbose=True,
maxItemCount=100000000,
maxDataSizeMo=10000,
dataDir=None,
seleniumBrowserCount=20,
... |
class Solution:
def removeElement(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
print(count)
return(count)
obj = Solution()
obj.removeElement([3,2,2,3], 3)
obj.removeEl... |
# -*- coding: utf-8 -*-
# 获取字符串中匹配子串的最后一个位置
def find_last(string, str):
last_position = -1
while True:
position = string.find(str, last_position+1)
if position == -1:
return last_position
last_position = position
# 将文件名改写成小文件名
def thumbFilePath(filepath):
... |
#!/usr/bin/env python3
class Solution:
def buddStrings(self, A, B):
la, lb = len(A), len(B)
if la != lb:
return False
diff = [i for i in range(la) if A[i] != B[i]]
if len(diff) > 2 or len(diff) == 1:
return False
elif len(diff) == 0 and len(set(A)) ==... |
print('this is the first line of second.py')
for x in range(20):
print(x)
print('this is the chunk of code added to the fourth branch')
print('Im editing this file in GitHub to see if fetch finds it')
print('adding this code to push to the main on the remote repository') |
def count_substring(string, sub_string):
k = len(sub_string)
ans = 0
for i in range(len(string)):
if i+k > len(string):
break
if sub_string == string[i:i+k]:
ans += 1
return ans
if __name__ == '__main__':
string = input().strip()
sub_string = input().stri... |
print("Hello World")
my_name = input("Whats your name? ")
print("Hello " + my_name)
print('Did you know that your name is ' + str(len(my_name)) + ' letters long!')
|
"""
37. How to get the nrows, ncolumns, datatype, summary stats of each column of a dataframe? Also get the array and list equivalent.
"""
"""
Difficulty Level: L2
"""
"""
Get the number of rows, columns, datatype and summary statistics of each column of the Cars93 dataset. Also get the numpy array and list equivalent ... |
#py_screener.py
def screener(user_inp=None):
"""A function to square only floating points.
Returns custom exceptions if an int or complex is encountered."""
#make sure something was input
if not user_inp:
print("Ummm...did you type in ANYTHING?")
return
#If it *might* be a floa... |
default_mapping = {
'Recipient Name': 'recipient_name',
'Recipient DUNS Number': 'recipient_unique_id',
'Awarding Agency': 'awarding_toptier_agency_name',
'Awarding Agency Code': 'awarding_toptier_agency_code',
'Awarding Sub Agency': 'awarding_subtier_agency_name',
'Awarding Sub Agency Code': 'a... |
class Reporting(object):
def __init__(self, verbose=False, debug=False):
self.verbose_flag = verbose
self.debug_flag = debug
def error(self, msg):
pass
def debug(self, msg):
pass
def verbose(self, msg):
pass
|
def iloc(records, rows=':', cols=':') -> list:
"""A Pandas .iloc-like function.
Args:
records (list): A 2-D list.
rows (str or int): The indices of rows. Default is ':'.
cols (str or int): The indices of columns. Default is ':'.
Returns:
list: The sliced records.
Examp... |
"""
30 - Crie um programa que leia um número inteiro qualquer e mostre na tela se
ele é par ou ímpar
"""
num = int(input('\033[35mDigite um número qualquer: \033[m'))
if num % 2 == 0:
print(f'O número {num} é \033[34mPAR\033[m')
else:
print(f'O número {num} é \033[34mÍMPAR\033[m.')
|
class Solution:
def isValid(self, s: str) -> bool:
if not s: return True
if len(s) % 2: return False
if s[0] in ']})': return False
maps = {'(':')', '{':'}', '[':']'}
stack = []
for char in s:
if char in '({[':
stack.appen... |
fruits = ['pineapple', 'lemon', 'pear', 'watermelon', 'tomato', 'apple']
first, second, *middle, firstlast, last = fruits
print(f'''Первый элемент: {first}
Второй: {second}
Посередине: {middle}
Предпоследний: {firstlast}
Последний: {last}''')
|
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/next-sparse-binary-number/0
def sol(num):
"""
By definition of sparse number two 1s cannot be adjacent but zeroes can be
If two 1s are adjacent and we want to make a bigger number we cannot
make the either of the bits 0, so only option le... |
'''
A função inverte strings e coloca todas as letras em maiúsculo:
'''
def fazAlgo(string):
pos = len(string)-1
string = string.upper()
while pos >= 0:
print(string[pos], end="")
pos = pos - 1
fazAlgo("amora")
|
command = input()
kids = 0
adults = 0
while command != "Christmas":
peoples_age = int(command)
if peoples_age <= 16:
kids += 1
elif peoples_age > 16:
adults += 1
command = input()
if command == "Christmas":
total_toys_price = kids * 5
total_sweater_price = adults * 15
pri... |
class Solution(object):
def findBestValue(self, arr, target):
arr.sort(reverse = True)
while arr and target >= arr[-1]*len(arr):
temp = arr[-1]
target -= arr.pop()
if not arr:
return temp
res = target / float(len(arr))
if res % 1 > 0.5:
... |
# Converts RGB to GRB which is needed by the lightstrip
def Color(red, green, blue, white = 0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (green <<... |
"""
Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
"""
class Solution:
"""
@param: head: a ListNode
@param: val: An integer
@return: a ListNode
"""
def removeElements(self, head, val):
if head is None:
... |
class MockRequests:
def __init__(self, ok=True, json_data=None):
self.ok = ok
self.json_data = json_data
self.get_method_called = False
def __call__(self, *args, **kwargs):
self.get_method_called = True
self.response = MockResponse(json_data=self.json_data)
retur... |
# -*- coding: utf-8 -*-
class Solution:
def minCostToMoveChips(self, chips):
count_even, count_odd = 0, 0
for chip in chips:
if chip % 2 == 0:
count_even += 1
else:
count_odd += 1
return min(count_even, count_odd)
if __name__ == '_... |
"""Module for user service exceptions"""
__all__ = [
'UserNotFoundException',
'UserIsExistsException',
]
class UserNotFoundException(Exception):
"""Indicates that user not found
Args:
message: Detailed message
"""
def __init__(self, message: str) -> None:
self.message = mess... |
def _copy_cmd(ctx, file_list, target_dir):
dest_list = []
if file_list == None or len(file_list) == 0:
return dest_list
shell_content = ""
batch_file_name = "%s-copy-files.bat" % (ctx.label.name)
bat = ctx.actions.declare_file(batch_file_name)
src_file_list = []
for (src_file, rela... |
class Enum(object):
@classmethod
def parse(cls, value):
options = cls.options()
result = []
for k, v in options.items():
if type(v) is not int or v == 0:
continue
if value == 0 or (value & v) == v:
result.append(v)
retur... |
class Model:
def __init__(self):
pass
class Optimizer:
def __init__(self):
pass
|
currency = {
'GDP' : 1.3,
'EUR' : 1.08,
'USD' : 1.0,
'AUD' : 0.66,
'JPY' : 0.0090
}
while True:
intialcur = str(input('Please Enter the currency you want to convert from\n: ')).upper()
while True:
if intialcur in currency:
break
else:
intialcur = str(... |
"""
Implementation of a specific learning rate scheduler for GANs.
"""
class DRS_LRScheduler:
"""
Learning rate scheduler for training GANs. Supports GAN specific LR scheduling
policies, such as the linear decay policy using in SN-GAN paper as based on the
original chainer implementation. However, one... |
n, a, b = map(int, input().split())
ans = 0
for i in range(1, n+1):
str_i = str(i)
sum = 0
for j in range(len(str_i)):
sum += int(str_i[j])
if a <= sum <= b:
ans +=i
print(ans)
|
VERSION = "0.0.2"
VERSION_GUI = "0.0.2"
VERSION_CUI = "0.0.0"
VERSION_AUDIOCABLE = "0.0.2"
VERSION_ROUTE = "0.0.2"
VERSION_SETINGS = "0.0.1"
CALLBACK_AUDIOCABLE_SELECTED = None
CALLBACK_ROUTE_SELECTED = None
SETTINGS = None
CONFIGURATION = None
PATH_ROOT = ""
PATH_SETTINGS = "" |
class ItemContainerGenerator(
object,
IRecyclingItemContainerGenerator,
IItemContainerGenerator,
IWeakEventListener,
):
""" Generates the user interface (UI) on behalf of its host,such as an�System.Windows.Controls.ItemsControl. """
def ContainerFromIndex(self, index):
"""
C... |
def xor_reverse(iterable):
lenght = len(iterable)
i = 0
while i < lenght // 2:
iterable[i] ^= iterable[lenght - i - 1]
iterable[lenght - i - 1] ^= iterable[i]
iterable[i] ^= iterable[lenght - i - 1]
i += 1
return iterable
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# Variables that contain the user credentials to access Twitter API.
ACCESS_TOKEN = "570634225-AnsM63tVCpI4yeFwpj6QfSJTwm3pUx6onf30fI2Z"
ACCESS_TOKEN_SECRET = "ykA5CW0lWpl3VDiIRqJ5rhJjsQc6fyt0pps22tLAywXUJ"
CONSUMER_KEY = "iRwp1I7vH0cBoWNIO5w0uxURN"
CONSUMER_SECRET = "5rA8XDisNbzwTueiCiZG7JXEZe5T4HRiwLbFjWMTWlyNoU35r4... |
def split_data(input, output, validation_percentage=0.1):
num_sets = output.shape[0]
num_validation = int(num_sets * validation_percentage)
return (input[:-num_validation], output[:-num_validation]), (input[-num_validation:], output[-num_validation:])
|
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 1st solution
# O(n) time | O(1) space
profit = 0
start = prices[0]
end = start
for i, price in enumerate(prices):
if price >= end and i < len(prices) - 1:
end = price
... |
class Stat:
def __init__(self):
self.sum = {}
self.sum_square = {}
self.count = {}
def add(self, key, value):
self.count[key] = self.count.get(key, 0) + 1
self.sum[key] = self.sum.get(key, 0.0) + value
self.sum_square[key] = self.sum_square.get(key, 0.0) + value... |
class Object:
"""
Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
object()
"""
def __delattr__(self,*args):
""" __delattr__(self: o... |
BUY = 1
SALE = 2
OrderType = [
(BUY, 'BUY'),
(SALE, 'SALE')
] |
# A function with Behavior That varies Over Time
# A function compound value have a body and a parent frame
# The parent frame contains the balance, the local state of the withdraw function
# Non-Local Assignment & Persistent Local State
# Work for python 3
def make_withdraw(balance):
""" Return a withdraw fun... |
num = 1
val = 2
val2 = 333333
val2 = 333
val3 = 55555
|
PROFILE = {
"reciepientsFullName": "Max Mustermann",
"lastName": "Mustermann",
"title": "Mr.",
"reciepientsAddress": "Musterstraße 11",
"zipCode": "123456",
"city": "Musterhausen",
"IBAN": "DE07123412341234123412"
}
NF_FORM = {
"proc_agency": "USAG Grafenwoehr,<br>HQUSAG Grafenwoer,<... |
print('-*-'*20)
print('Analisador de triângulos ')
print('-*-'*20)
r1=float(input('Primeiro segmento:'))
r2=float(input('Segundo segmento:'))
r3=float(input('Terceiro segmento:'))
if r1<r2+r3 and r2<r1+r3 and r3<r1+r2:
print('Os segmentos acima podem formar um triangulo')
else:
print('Os segmentos acima não pod... |
# Дано предложение. Удалить из него все буквы о, стоящие на нечетных местах.
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
n = str(input("Предложение - "))
m = len(n)
for i in range(1, m):
i = str(i)
if n.find(i) % 2 == 1:
n = n.replace('... |
#--- Exercício 2 - Dicionários
#--- Escreva um programa que leia os dados de 11 jogadores
#--- Jogador: Nome, Posicao, Numero, PernaBoa
#--- Crie um dicionario para armazenar os dados
#--- Imprima todos os jogadores e seus dados
#--- Resolução Nicole Gruber
lista_jogadores=[]
for i in range(1,3):
Nome=input('Digi... |
oa = ord('a')
def word_score(word):
return sum((ord(letter) - oa + 1) for letter in word)
def high(s):
print(s)
return max(s.split(), key=word_score)
|
""" 01
E os 10% do garçom?**
Defina uma variável para o valor de uma refeição que custou R$ 42,54;
Defina uma variável para o valor da taxa de serviço que é de 10%;
Defina uma variável que calcula o valor total da conta e exiba-o no console com essa
formatação: R$ XXXX.XX.
"""
valor = 42.5... |
# table definition
table = {
'table_name' : 'adm_tax_cats',
'module_id' : 'adm',
'short_descr' : 'Sales tax categories',
'long_descr' : 'Sales tax categories',
'sub_types' : None,
'sub_trans' : None,
'sequence' : ['seq', [], None],
'tree_params' : None,
'ro... |
li = []
nli = []
n = int(input())
for i in range(n):
li.append(input())
nli.append([i])
a=0
#print(nli)
for i in range(n-1):
a,b = map(int,input().split())
a-=1
b-=1
nli[a]+=nli[b]
nli[b] = []
res = ""
for i in range(n):
print(li[nli[a][i]],sep='',end='') |
"""nbgrader_schema
Revision ID: e43177bfe90b
Revises:
Create Date: 2021-09-11 04:07:31.804665+00:00
"""
# revision identifiers, used by Alembic.
revision = 'e43177bfe90b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
|
#!/usr/bin/env python
"""
trie.py: contains the definition and declaration of the trie class
"""
__author__ = "Shivchander Sudalairaj"
__email__ = "sudalasr@mail.uc.edu"
class Trie:
"""
Trie/Prefix Tree data structure to efficiently load the dictionary of all valid words
https://en.wikipedia.org/wiki/Tr... |
names = ['John', 'Mary']
print(names)
names[0], names[1] = names[1], names[0]
print(names) |
#utf-8
#Exercício 14 do curso em vídeo de Python
celsius = float((input('Informe a temperatura em °C: ')))
#transformando de celsius para fahrenheit
fahr = (celsius * 9/5) + 32
print('A temperatura de {}°C corresponde a {}°F!'.format(celsius, fahr))
|
number = int(input())
for numbers in range(1111, 9999):
is_Magic = True
number_as_string = str(numbers)
for digit in number_as_string:
if int(digit) == 0:
is_Magic = False
break
elif number % int(digit) != 0:
is_Magic = False
break
if is_Ma... |
total = contV = mv = 0
nomeMB = ' '
while True:
print('-'*20)
print('LOJA SUPER BARATÃO')
print('-'*20)
nome = str(input('Nome do produto: '))
valor = float(input('Preço: R$'))
total += valor
if valor >= 1000:
contV +=1
if mv == 0 or valor < mv:
mv = valor
... |
idvelho = 0
nmvelho = ''
idade = 0
media = 0
contM = 0
sexo = ''
for p in range(1, 5) :
print('---- {}° PESSOA ----'.format(p))
nome = str(input('Nome: '))
idade = int(input('Idade: '))
media += idade
sexo = str(input('Sexo [M/F]: '))
if p == 1 and sexo in 'Mm' :
idvelho = idade
... |
def myfnc(x):
print("inside myfnc", x)
x = 10
print("inside myfnc", x)
x = 20
myfnc(x)
print(x)
|
class PDL1netTester:
"""
class represents a PDL1 net Tester
"""
def __init__(self):
pass
def test(self):
pass
# TODO: add here function to show results and compare different settings result
|
class Solution:
def reverse(self, x: int) -> int:
self.setLimit(x)
result = 0
while x != 0:
tail: int = self.mod10(x)
if self.overflow(result, tail):
return 0
result = result * 10 + tail
x = self.divide10(x)
return resul... |
del_items(0x80114B24)
SetType(0x80114B24, "int NumOfMonsterListLevels")
del_items(0x800A49E4)
SetType(0x800A49E4, "struct MonstLevel AllLevels[16]")
del_items(0x80114820)
SetType(0x80114820, "unsigned char NumsLEV1M1A[4]")
del_items(0x80114824)
SetType(0x80114824, "unsigned char NumsLEV1M1B[4]")
del_items(0x80114828)
S... |
class MinStack(object):
def __init__(self):
"""
data structure .
"""
self.stack = []
self.minimum = None
def push(self, x):
"""
:type x: int
:rtype: None
"""
if len(self.stack) == 0:
self.stack.append(x)
... |
class Point:
"Classe Point géographique contenant une position"
def __init__(self,x,y):
self._x=x
self._y=y
def getx(self):
return self._x
def gety(self):
return self._y
def setx(self, x):
self._x = x
def sety(self, y):
self._y = y
... |
# python -m trace --count -C . somefile.py
# https://docs.python.org/zh-cn/3/library/trace.html
# python 用trace调试编译 python -m trace --trace 159_debug_trace.py
def main():
print("xxxxx")
main()
# import sys
# import trace
# # create a Trace object, telling it what to ignore, and whether to
# # do tracing or line... |
# -*- coding: utf-8 -*-
"""
Algoritmo de busqueda binaria usando el ciclo while
escrito en Python.
Este metodo funciona con cadenas y numeros por igual, ya
que el lenguaje trata a las cadenas lexicograficamente;
comparando sus valores en el codigo ASCII
"""
def binary_search(list_data, search_data):
left_index,... |
#81. 题目:809*??=800*??+9*??+1 其中??代表的两位数,8*??的结果为两位数,9*??的结果为3位数。求??代表的两位数,及809*??后的结果。
#
#82 题目:八进制转换为十进制
def convert8to10(n):
lenN = len(str(n))
sumN = 0
for i in range(lenN):
sumN += 8 ** i * int(str(n)[lenN-1-i])
print('this is the 8 to 10 : %d' % sumN)
convert8to10(122)
#83. 题目:求0—7... |
###########################################
# EXERCICIO 034 #
###########################################
'''ESCREVA UM PROGRAMA QUE PERGUNTE O SALARIO
DE UM FUNCIONARIO E CALCULE O VALOR DE SEU
AUMENTO: PARA SALARIO SUPERIORES A R$1250,00
CALCULE AUMENTO DE 10 %, PARA SALARIOS MENORES
OU IGUA... |
class Solution:
def partitionLabels(self, S: str) -> List[int]:
"""
A string S of lowercase English letters is given. We want to
partition this string into as many parts as possible so that
each letter appears in at most one part, and return a list of
integers repre... |
'''
a = qtd pistas 1
b = qtd pessoas por pistas 9
c = qtd alunos 4
'''
A, B, C = [int(x) for x in input().split()]
if (A*B) > C:
print("S")
else:
print("N")
|
value = 74.55
value2 = 74.3
value4 = -100
print(f"O valor 1 é {round(value)} e o valor 2 {round(value2)}")
print(f"O valor 1 também é {int(value)}")
print(f"O valor absoluto de {value4} é {abs(value4)}")
print(3//2) |
global file_object
global min_country
global max_country
def open_file():
global file_object
while True:
# repeatedly prompting for a file name until if its valid
file_name = input('Enter the file name: ')
# checking if file can be opened
try:
file_objec... |
""" Leetcode 1041 - Robot Bounded in Circle
https://leetcode.com/problems/robot-bounded-in-circle/
"""
class Solution1:
""" 1. MINE Straight-Forward """
def is_robot_bounded(self, instructions: str) -> bool:
nums = {'G': 0, 'R': 1, 'L': -1}
direction = [1, -1]
position = [0, 0]
... |
# DESCRIÇÃO
# Escreva um programa que calcule a circunferência C de um determinado
# planeta, com base na observação do ângulo A, entre duas localidades C1 e
# C2, e na distância D, em estádios, entre elas.
# Suponha que as localidades estejam no mesmo meridiano de um planeta
# esférico. O seu programa deverá imprimi... |
_base_ = [
'../_base_/models/flownet2/flownet2sd.py',
'../_base_/datasets/chairssdhom_384x448.py',
'../_base_/schedules/schedule_s_long.py', '../_base_/default_runtime.py'
]
|
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description: 包括gan图像生成、vae图像生成、艺术风格迁移、图像漫画化
"""
|
LOAD_CONTENT_CACHE = False
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
|
number = int(input())
word = input()
save = []
for i in range(number):
current_string = input()
save.append(current_string)
print(save)
for i in range(len(save) -1, -1, -1):
element = save[i]
if word not in element:
save.remove(element)
print(save)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.