content stringlengths 7 1.05M |
|---|
class ContentTransformer:
def transform(content):
raise NotImplementedError()
@classmethod
def from_siteinfo(cls, siteinfo, *args, **kwargs):
raise NotImplementedError()
|
ports_assignment = { "rs1_rs2" : 6004, "rs1_receive_bgp_messages" : 6000 , "rs1_send_mpc_output" : 6001 , "worker_port" : 7760, "rs2_receive_bgp_messages" : 6002, "rs2_send_mpc_output" : 6003, "rs1-preference-channel" : 6005, "rs2-preference-channel" : 6006}
#process_assignement = {"rs1" : '192.168.102.2',"rs2" : '192... |
# DAN KABAGAMBE
# TUMUSIIME FRANCIS
# NAKUYA SHAKIRAH HADIJJAH
total = 0
count = 0
smallest = None
largest = None
# Finding the largest and smallest
while True:
a = input('Enter a number:')
try:
a = int(a)
count = count + 1
total = total + a
if smallest is None:
... |
DASHBOARD = 'mydashboard'
DISABLED = False
ADD_INSTALLED_APPS = [
'openstack_dashboard.dashboards.mydashboard',
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 14:34:19 2021
@author: alef
"""
"""
Comentários funcionais
O caractere # marca o início de comentário. Qaulquer texto depois do # será ignorado
até o fim da linha, com exceção dos comentários funcionais.
Comentários funcionais são utilizados p... |
def test13(a, b):
"""Test for Docstring"""
a.b[1]
ziffern = "0123456789"
ziffern[a:b]
|
""""
Entradas
Valor_c--> float--> C
Salidas
Descuento --> float -->desc
"""
C=float(input("Digite el valor de la compra: "))
desc=(C*0.15)
#cajanegra
toaltal=(C-desc)
#Salida
print("El total a pagar es: "+str(toaltal)) |
class Status:
CANCELED = "CANCELED"
DECOMPRESSING = "DECOMPRESSING"
DELETED = "DELETED"
FAILED = "FAILED"
FREE = "FREE"
INITIAL_LOAD = "INITIAL_LOAD"
INVALID_FILE = "INVALID_FILE"
LOST = "LOST"
STAGE = "STAGE"
PROCESSING = "PROCESSING"
RUNNING = "RUNNING"
SUCCEEDED = "S... |
# -*- coding: utf-8 -*-
def test_del_first_contact(app):
app.session.login(username = "admin", password = "secret")
app.contact.delete_first_contact()
app.session.logout() |
# estrutura encadeada devemos usar o comando "elif", que é uma abreviação de else
codigo_compra = 5444
if codigo_compra == 5222:
print("compra a vista.")
elif codigo_compra == 5333:
print("compra a prazo no boleto.")
elif codigo_compra ==5444:
print("compra a prazo no cartao.")
else:
print("código não ca... |
class Person:
def __init__(self, params):
self.name = params.get('name')
self.birth_date = params.get('birth_date')
def params_str(self):
return "{{name: '{}', birth_date: '{}'}}".format(self.name, self.birth_date)
|
def add_native_methods(clazz):
def getAll____(a0):
raise NotImplementedError()
def getByName0__java_lang_String__(a0, a1):
raise NotImplementedError()
def getByIndex0__int__(a0, a1):
raise NotImplementedError()
def getByInetAddress0__java_net_InetAddress__(a0, a1):
rai... |
'''
Description: Exercise 3 (for loop)
Version: 1.0.0.20210117
Author: Arvin Zhao
Date: 2021-01-17 17:46:34
Last Editors: Arvin Zhao
LastEditTime: 2021-01-18 10:40:04
'''
direction = input('Which direction do you want to count? (up/down)').strip().lower()
if direction == 'up':
top = int(input('Enter the top numbe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def colorText(txt='', fgColor='', fgLine='', bgColor='', ):
txtColor = ''
if (fgLine != ''):
txtColor += '\033[4m'
if (fgColor == 'black'):
txtColor += '\033[30m'
elif (fgColor == 'red'):
txtColor += '\033[31m'
elif (fgCo... |
type_dict = {
"[INFO]": "info",
"[WARNING]": "warning",
"[ERROR]": "error",
"[DEBUG]": "debug",
"START": "start",
"REPORT": "report",
"END": "end",
"DEBUG": "debug",
}
style_dict = {
"error": "bold red",
"start": "green",
"report": "dim yellow",
"debug": "bold blue",
... |
class Connection:
def __init__(self, unique,ip, hostname):
self.ip = ip
self.hostname = hostname
self.unique = unique
def __str__(self):
return str({"ip":self.ip, "hostname": self.hostname, "unique": self.unique}) |
def external_service(name, datacenter, node, address, port, token=None):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if token is None:
token = __pillar__['consul']['acl']['tokens']['default']
# Determine if the cluster is ready
if not __salt__["consul.cluster_ready"]():... |
#
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. T... |
class DumbDriveForward(Autonomous):
nickname = "Dumb drive forward"
def __init__(self, robot):
super().__init__(robot)
self.addSequential(AutoDumbDrive(robot, time=3, speed=-0.4))
class DumbDriveForwardHighGear(CommandGroup):
nickname = "Dumb drive forward high gear"
def __init__(sel... |
#Write a function name kinetic_energy that accepts an object's mass (in kg) and
#velocity (in m/s) as arguments. The function should return the amount of kinetic
#energy that object has. Write a program that asks the user to enter values for
#mass and velocity, the calls kinetic_energy to get the object's kinetic en... |
def seg(s):
s2 = s[0]
for e in s[1:]:
if e == s2[-1]:
s2 += e
else:
s2 += '/'
s2 += e
print(s)
print(s2)
def seg2():
s2 = []
s = ['a', 'a', 'b', 'b', 'v', 'v', 'c', 'c', 'a', 's']
for e in enumerate(s):
s2.append(e)
s3 = s2[0... |
class Solution:
def subtractProductAndSum(self, n: int) -> int:
prod = 1
sum_ = 0
while n > 0:
last_digit = n % 10
prod *= last_digit
sum_ += last_digit
n //= 10
return prod - sum_
... |
def test(x):
try:
if x:
print(x)
else:
raise (Exception)
except:
print("wrong")
finally:
print("finally")
print("after finally")
if __name__ == "__main__":
test(None)
test("hello")
|
# The example function below keeps track of the opponent's history and plays whatever the opponent played two plays ago. It is not a very good player so you will need to change the code to pass the challenge.
def player(prev_play, opponent_history=[]):
opponent_history.append(prev_play)
guess = "R"
if len... |
"""Robot in a grid."""
def robot_path(grid):
"""Return a path for the robot."""
rows = len(grid)
cols = len(grid[0])
valid_paths = []
def traverse_grid(i=0, j=0, path=[]):
if i > rows - 1 or j > cols - 1:
return
if grid[i][j] == 1:
return
if i == ro... |
# print()
#
# print('NÚMEROS & MATEMÁTICA')
#
# print()
#
# n = str(input('Digite um número de 0 á 9999: '))
#
# print('Unidades:', n[3], '\nDezenas:', n[2], '\nCentenas:', n[1], '\nMilhar:', n[0])
n = int(input('\033[35mDigite um número de zero a 9999: '))
u = n // 1 % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // ... |
# Copyright 2021 NVIDIA CORPORATION
# SPDX-License-Identifier: Apache-2.0
#
# Script to generate the GLSL compute functions
#
# uint autogeneratedGetCaseNumber(float sample000, float sample001, float sample010, float sample011,
# float sample100, float sample101, float sample110, float s... |
def view(user, tool):
return True
def create(user, tool):
if user.is_superuser:
return True
return user.is_developer
def change(user, tool):
if user.is_superuser:
return True
return user.is_developer
def delete(user, tool):
if user.is_superuser:
return True
r... |
ingredient1 = "chicken"
ingredient2 = "rice"
Michsays = input ("What is inside this hawker chicken rice?")
if (Michsays == ingredient1 or Michsays == ingredient2):
print("correct!")
else:
print("look again!")
# == takes precedence over or
Michasks = input("How much is the hawker chicken rice?")
floatConvert... |
with open("input.txt") as f:
arr = [line.strip() for line in f.readlines()]
feesh = arr[0].split(",")
feesh = [int(num) for num in feesh]
days = 256
max_age = 8
birth_rates = [ [None] * (max_age + 1) for i in range(days + 1)]
#print(feesh)
#print(birth_rates)
def final_feesh(fish_age, day):
print("Age: "... |
class Solution:
def flipgame(self, fronts: 'List[int]', backs: 'List[int]') -> 'int':
same_sides = {}
for i in range(len(fronts)):
if fronts[i] == backs[i]:
if fronts[i] not in same_sides:
same_sides[fronts[i]] = 0
same_sides[fronts[i]]... |
# 张三修定义了一个变量
num = 1
num2 = 20
num3 = 30
# 经理定义了一个变量
args = [1,2,3,4]
num4 = (1,2,3,4)
|
"""
Given a set and a sum (m) findout whether
there is a subset whose sub is equal to m
Time complexity : O(n*m)
Space complexity : O(n*m)
"""
def solve():
n,m = map(int,input().split())
a = list(map(int,input().split()))
dp = [[0 for i in range(m+1)] for j in range(n+1)]
for i in range(m+1):
... |
UNSIGNED_CHAR_COLUMN = 251
UNSIGNED_CHAR_LENGTH = 1
UNSIGNED_INT24_COLUMN = 253
UNSIGNED_INT24_LENGTH = 3
UNSIGNED_INT64_COLUMN = 254
UNSIGNED_INT64_LENGTH = 8
UNSIGNED_SHORT_COLUMN = 252
UNSIGNED_SHORT_LENGTH = 2
|
"""PostgreSQL utilities"""
def pg_result_to_dict(columns, result, single_object=False):
"""Convert a PostgreSQL query result to a dict"""
resp = []
for row in result:
resp.append(dict(zip(columns, row)))
if single_object:
return resp[0]
return resp
|
info = {
"friendly_name": "Comment (Block)",
"example_template": "comment text",
"summary": "The text within the block is not interpreted or rendered in the final displayed page.",
}
def SublanguageHandler(args, doc, renderer):
pass
|
def digitize(n):
if n == 0:
return[0]
else:
digits = []
while n > 0:
digits.append(n % 10)
n = (n - n % 10) // 10
return(digits[::-1])
#def digitize(n):
#return list(map(int, str(n)))cc |
"""
try:
a = int(input("Numerador: "))
b = int(input("Denominador: "))
r = a / b
except Exception as erro:
print(f"Problema encontrado foi {erro.__class__}")
else:
print(f"O resultado é {r}")
finally:
print("Volte sempre! Muito obrigado!")
"""
"""-----------------------------------------------"... |
#
# PySNMP MIB module CERENT-GLOBAL-REGISTRY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CERENT-GLOBAL-REGISTRY
# Produced by pysmi-0.3.4 at Wed May 1 11:48:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
def metade(valor, formatar=False):
valor = valor / 2
if formatar:
valor = moeda(valor)
return valor
def dobro(valor, formatar=False):
valor *= 2
if formatar:
return moeda(valor)
return valor
def aumentar(valor, porcentagem, formatar=False):
aumenta = valor * (porcentagem ... |
print('Accessing private members in Class:')
print('-'*35)
class Human():
# Private var
__privateVar = "this is __private variable"
# Constructor method
def __init__(self):
self.className = "Human class constructor"
self.__privateVar = "this is redefined __private variable"... |
def CheckPairSum(Arr, Total):
n = len(Arr)
dict_of_numbers = [0] * 1000
# print("Start of loop")
for i in range (n):
difference = Total - Arr[i]
# print difference
if dict_of_numbers[difference] == 1:
print("The pair is"... |
# NOTE: # noinspection - prefixed comments are for pycharm editor only
# for ignoring PEP 8 style highlights
class PageTitleMixin:
"""Page title mixin class
- for class based views
:argument: -page_title
:methods: - get_page_title()
- get_context_data()
"""
page_title = ''
d... |
# Variant DBScan analysis item
# Set variants
vdbscan_variants = pd.DataFrame({'eps': [2,2,3,3], 'mp' : [4,4,5,5]})
# Set column names
vdbscan_column_names = ('ra', 'dec')
# Create Variant DBScan analysis item
ana_vdbscan = skdiscovery.data_structure.table.analysis.VDBScan('VDBScan',vdbscan_variants, vdbscan_column_na... |
n=int(input("enter number of elements: "))
l=[]
for i in range(n):
l.append(int(input(f"enter l[{i}]: ")))
print(l)
'''
output:
enter number of elements: 6
enter l[0]: 23
enter l[1]: 11
enter l[2]: 67
enter l[3]: 889
enter l[4]: 342
enter l[5]: 23
[23, 11, 67, 889, 342, 23]
'''
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 law or agreed ... |
# Merge Sort [합병 정렬]
# Complexities : Time O(N log N) | Space O(N)
def merge(array, left, mid, right):
leftLen, rightLen = mid - left + 1, right - mid
leftArr, rightArr = [0] * leftLen, [0] * rightLen
l, r, merge_idx = 0, 0, left
for i in range(leftLen):
leftArr[i] = array[left + i]
for i ... |
"""Top-level package for wyeusk."""
__author__ = """Steve Betts"""
__email__ = 'stevo.betts@gmail.com'
__version__ = '0.1.0'
|
nun = [[], []]
val = 0
for c in range(0, 8):
val = int(input('Digite um numero: '))
if val % 2 == 0:
num[0].append(val)
else:
num[1].append(val) |
class Hparams:
batch_size = 128
enc_maxlen = 20
dec_maxlen = 20
num_epochs = 20
hidden_units = 128
emb_units = 64
graphemes = ["<pad>", "<unk>", "</s>"] + list(" ًٌٍَُِآئابتثجحخدذرزسشصضطظعغفقلمنهوپچژکگی")
phonemes = ["<pad>", "<unk>", "<s>", "</s>"] + list("?ACSZ^_abdefghijklmnopqrstuvxy... |
total = caros = cont = 0
barato = ''
print('==' * 20)
print(' LOJAS CLA ')
print('==' * 20)
while True:
nome = str(input('Nome do Produto: ')).strip().title()
preco = float(input('Preço: R$ '))
op = ' '
while op not in 'SN':
op = str(input('Quer Continuar ? [S/N] ')).strip().upper()[0]
t... |
# 山灵M0播放器播放列表管理工具配置
# ver.11
# By Clok Much
class Default:
m0_prefix = "A:\\" # M0播放列表的驱动器映射
m0_folder = "_explaylist_data\\" # M0播放列表所在的文件夹,以 \\ 结尾
m0_playlist_type = ".m3u" # M0播放列表文件格式
m0_disabled_playlist = ".m0disabled" # M0禁用的播放列表格式
playlist_default_name = "Default" # 默认播放列表名称
su... |
# Spajanie reťazcov
# Na vstupe získate dve frázy. Na výstup vypíšte výhovorku vygenerovanú z týchto fráz.
str1 = input() # umyť riad
str2 = input() # musím chytať Pokémony
print(f'Bohužiaľ nemôžem {str1}, pretože {str2}.')
# Bohužiaľ nemôžem umyť riad, pretože musím chytať Pokémony. |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def prefix(A):
pref = [0] * (len(A)+1)
for i in range(1, len(A)+1):
pref[i] = pref[i-1] + A[i-1]
return pref
def countTotal(P, left, right):
return P[right] - P[left]
def solution(A):
pref = prefix(A)... |
numeros = []
c = 0
while True:
num = int(input('Digite um número: '))
c += 1
numeros.append(num)
print(f'O número que você digitou foi {num}.')
print('\tDigite "999" para parar.\n')
if num == 999:
c -= 1
del numeros[-1]
soma = sum(numeros)
break
if c > 1:
prin... |
# https://codeforces.com/problemset/problem/584/A
n, t = map(int, input().split())
if n == 1:
if t < 10:
print(t)
else:
print(-1)
else:
if t < 10:
print(str(t)+'0'*(n-1))
else:
print('1'+'0'*(n-1)) |
# Quick Sort
# Time Complexity: O(n^2)
# Space Complexity: O(log(n))
# In-place quick sort does not create subsequences
# its subsequence of the input is represented by a leftmost and rightmost index
def quick_Sort(lst, first, last):
print(lst)
if first >= last: # the lst is sorte... |
n = float(input('Qual a largura da pardede? :'))
n2 = float(input('Qual a altura da parede? :'))
print(f'A área da parede é igual a {n*n2}, e será necessário {(n*n2)/2} litros de tinta para pintar a parede.')
|
# 字典
alien = {'color': 'green', 'point': 5}
print(alien['color'])
print(alien['point'])
alien['x_position'] = 0
alien['y_position'] = 25
print(alien)
for k, v in alien.items():
print(k)
print(v)
for key in alien.keys():
print(key)
for key in alien:
print(key)
for value in alien.values():
print(... |
# Fibonacci numbers module
def greeting(name="stranger"):
print("Hi {}".format(name))
|
"""Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço
passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 para viagens mais longas."""
km = float(input('Quantos Km: '))
if km <= 200:
print('Preço a pagar:R${}{:.2f}{}'.format('\033[4;32m',km * 0.50,'\033[m'))
else:... |
#split function is used for creat string in to list of String's
# String="10 11 12 13 14 15 16"
#we have to give Raguler Expression as argument of split function
#Know split function will split over string with respact" "
#l=["10","11","12","13","14","15","16"]
# l=String.split(" ")
# String=" 10 12 13 "
#stri... |
def power(number, power=2):
return number ** power
print(power(2, 3)) # 2 * 2 * 2 = 8
print(power(3)) # 3 * 2 = 9
print("------------------")
def showFullName(first, last):
return f"{first} {last}"
print(showFullName(last="Golchinpour", first="Milad"))
|
data = {}
individual = {}
info = input().split(" -> ")
while "no more time" not in info:
name = info[0]
contest = info[1]
points = int(info[2])
already_in = False
if contest in data:
for i in range(len(data[contest])):
if name == data[contest][i][0]:
already_in ... |
# -*-coding: utf-8 -*-
cg_notexists = '15019'
cg_zip_failed = '15009'
vray_notmatch = '15020'
cginfo_failed = '15002'
conflict_multiscatter_vray = '15021'
cg_notmatch = '15013'
camera_duplicat = '15015'
element_duplicat = '15016'
vrmesh_ext_null = "15018"
proxy_enable = "15010"
renderer_notsupport = "15004"
# -------... |
"""Test's routes definition."""
routes = [
{'name': 'index', 'pattern': '/'},
{'name': 'secret', 'pattern': '/secret'},
{'name': 'very_secret', 'pattern': '/secret/very'},
]
|
#!/usr/bin/env python3
with open("input.txt", "r") as f:
all_groups = [x.strip().split("\n") for x in f.read().split("\n\n")]
anyone = 0
everyone = 0
for group in all_groups:
all = set(group[0])
any = set(group[0])
for person in group[1:]:
all = all.intersection(person)
any.update(*person)
everyone += len... |
class Solution:
def maxScore(self, arr, k):
dp = {'l':[0], 'r':[0]}
curr_sum_left = 0
curr_sum_right = 0
for index in range(0, k):
# for left
curr_sum_left += arr[index]
dp['l'].append(curr_sum_left)
# for right
j = len... |
"""
********************
Singleton Pattern
********************
Description from Wikipedia:
*"the singleton pattern is a software design pattern that
restricts the instantiation of a class to one 'single' instance.
This is useful when exactly one object is needed to coordinate
actions across the system."*
.. warning... |
# date: 18/06/2020
# Description:
# Given a 32-bit integer,
# swap the 1st and 2nd bit,
# 3rd and 4th bit, up til the 31st and 32nd bit.
# convert from decimal to binary
def convert_to_binary(num):
result=''
while num != 0:
remainder = num % 2 # gives the exact remainder
num = num // 2
... |
vectors = { 'NW': (-1, -1), 'N': (-1, 0), 'NE': (-1, 1),
'W' : ( 0, -1), '' : ( 0, 0), 'E' : ( 0, 1),
'SW': ( 1, -1), 'S': ( 1, 0), 'SE': ( 1, 1),
}
class Board:
def __init__(self,grid,directions):
self._nb_row,self._nb_col=(len(grid),len(grid[0]))
s... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... |
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def findPositions(i, j, attackedColumn = set(), attackedHill = set(), attackedDale = set()):
if i == n-1:
return [[j]]
i += 1
validPos_list = []
... |
"""Component for the Somfy MyLink device supporting the Synergy API."""
CONF_ENTITY_CONFIG = "entity_config"
CONF_SYSTEM_ID = "system_id"
CONF_REVERSE = "reverse"
CONF_DEFAULT_REVERSE = "default_reverse"
DEFAULT_CONF_DEFAULT_REVERSE = False
DATA_SOMFY_MYLINK = "somfy_mylink_data"
MYLINK_STATUS = "mylink_status"
MYLINK... |
#! /usr/bin/env python3
with open("input", "r") as fd :
instructions = [x.split(' ') for x in fd.read().split('\n')]
acc = 0
done = [False] * len(instructions)
i = 0
while 0 <= i < len(instructions) and not done[i] :
done[i] = True
instruction, value = instructions[i]
if instruction == "acc" :
... |
class Point3:
"""A point in three-dimensional space."""
def __init__(self, x=0, y=0, z=0):
self.x=x
self.y=y
self.z=z
def __repr__(self):
return f"({self.x},{self.y},{self.z})"
def __str__(self):
return self.__repr__()
def __add__(self, other... |
def ben_update():
return
def ben_random_tick():
return
|
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, n):
self.width = n
def set_height(self, n):
self.height = n
def get_area(self):
return self.height * self.width
def get_perimeter(self):
... |
'''
Duplicate the elements of a list.
Example:
* (dupli '(a b c c d))
(A A B B C C C C D D)
'''
#taking input of list elements at a single time seperating by space and splitting each by split() method
demo_list = input("Enter elements seperated by space: ").split()
duplicates_list = list()
list_length = l... |
# Бинго 75 + Результаты тиража + предыдущий тираж к примеру 2000
def test_bingo75_results_draw_previous_draw(app):
app.ResultAndPrizes.open_page_results_and_prizes()
app.ResultAndPrizes.click_game_bingo75()
app.ResultAndPrizes.click_the_results_of_the_draw()
app.ResultAndPrizes.select_draw_2000_in_dr... |
n = int(input())
max_num = -1000000000000
for i in range(n):
num = int(input())
if num > max_num:
max_num = num
print(max_num) |
'''Faça um programa que receba o salário de um funcionário
e o percentual de aumento, calcule e mostre o valor do aumento e o novo salário'''
sal = float(input('Informe seu salario: '))
aum = int(input('Informe o percentual de aumento: '))
print(f'Seu aumento foi de: {sal*aum/100}')
print(f'Seu novo salario é: {sal +... |
with open("day-08.txt") as f:
lines = f.read().rstrip().splitlines()
ans = 0
for line in lines:
_, output = line.split(" | ")
for digit in output.split(maxsplit=3):
ans += len(digit) in (2, 3, 4, 7)
print(ans)
|
valores = list()
for i in range(0, 5):
valores.append(int(input(f'Digite um valor para a posição {i}: ')))
print('-=' * 20)
print(f'Você digitou os valores {valores}')
print(f'O maior valor digitado foi {max(valores)} nas posições: ', end='')
for pos, v in enumerate(valores):
if v == max(valores):
print... |
"""
This file is included in all files
"""
# THIS FILE IS INCLUDED IN ALL FILES
RELEASE = 'Created by BFM v. 5.1'
PATH_MAX = 255
stderr = 0
stdout = 6
# HANDY FOR WRITING
def STDOUT(text):
print(text)
def STDERR(text):
print(text)
# STANDARD OUTPUT FOR PARALLEL COMPUTATION
def LEVEL0():
STDERR('')
de... |
'''MIT License
Copyright (c) 2022 Carlos M.C.G. Fernandes
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 limitation the rights
to use, copy, modify, merge,... |
row1 = ["⬛","⬛","⬛"]
row2 = ["⬛","⬛","⬛"]
row3 = ["⬛","⬛","⬛"]
maps = [row1,row2,row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where you want to put the treasure ? \n")
maps[int(position[0])-1][int(position[1])-1] = "🟥"
print(f"{row1}\n{row2}\n{row3}")
|
class ApplyMaskBase(object):
def __init__(self):
pass
def apply_mask(self, *arg, **kwargs):
raise NotImplementedError("Please implement in subclass")
|
#
# # Recursive + memo (top-down)
# class Solution(object):
# def rob(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# cache = [-1] * len(nums)
# return self.robHelper(nums, len(nums) - 1, cache)
#
# def robHelper(self, nums, currentHouse, cache):
... |
a == b
a != b
a < b
a <= b
a > b
a >= b
a is b
a is not b
a in b
a not in b
|
# Exercício Python 066
# Leia varios números inteiros. Só para quando digitar 999
# Mostre quantos números foram inseridos e a soma entre eles.
contador = soma = 0
while True:
n = int(input('Digite um número: '))
if n == 999:
break
soma = soma + n
contador = contador + 1
print(f'Foram digitados... |
# iterator_protocol.py
print("""
The iterator protocol specifies two special methods to be implemented for any object to allow iteration
1. For any object to be iterated over, it must implement the __iter__ method which returns an iterator object.
Any object that returns an iterator is an iterable.
2. An iterator m... |
def quickshort(a,start,end):
if start<end:
pindex = partition(a,start,end)
quickshort(a,start,pindex-1)
quickshort(a,pindex+1,end)
def partition(a,start,end):
middle = int(end/2)
pivot = a[middle]
pindex = start
for i in range(start,middle):
if a[i]>=pivot:
a[i],a[pindex]=a[pindex],a[i]
... |
"""
Crie uma função que receba uma lista e retorne uma nova lista com os elementos únicos da primeira lista.
Ex: [1, 1, 2, 2, 2, 3, 4, 4, 5, 5] Retorna: [1, 2, 3, 4, 5]
"""
def unica(lista):
cont = 0
saida = []
while cont < len(lista):
if not lista[cont] in saida:
saida.append(lista[con... |
"""Functions for creating `XcodeProjInfo` providers."""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:sets.bzl", "sets")
load(
"@build_bazel_rules_apple//apple:providers.bzl",
"AppleBundleInfo",
"AppleFrameworkImportInfo",
"IosXcTestBundleInfo",
)
load("@build_bazel_rules_swift... |
"""
A module to show off a long-running function.
This module reads a very large text file and counts the
number of times each word appears in that file
Author: Walker M. White
Date: November 2, 2020
"""
def add_word(word,counts):
"""
Adds a word to a word-count dictionary.
The keys of the dictionari... |
#
# Problem: Compare original text vs what was altered and return a dict of
# indexes match_index_mapping the matching elements from the original text
# array to the altered text array.
#
# Algorithm should maximize the number of matches in sequential order.
#
# TODO: consider using dicts/tree instead of arrays
#
cla... |
# -*- coding: utf-8 -*-
"""
Looping Examples
Intro to Python Workshop
"""
## Iteration 1 - Iconic lyrics
n = 5
while n > 0:
print ("Hello "*3)
print ("How low")
print ("Entertain us!")
## Iteration 2 - Iconic lyrics
n = 0
while n > 0:
print ("Hello"*3)
print ("How low")
print ("E... |
#!/usr/bin/python3
given_list = [['87', '90', '78', '94'], ['78', '98', '92', '67']]
students = ['Chris', 'Eva']
names_classes = ['Math', 'Chemistry', 'Physics', 'English']
def printing(given_list, name_classes):
"""Printing catalog pandas style but without pandas"""
maxi_names = max(len(str(students[i])) f... |
"""
Basic GLS Syntax
Version 0.0.1
Josh Goldberg
"""
# Function Definitions
def sayHello():
print("Hello world!")
def combineStrings(a, b):
return a + b
# Class Declarations
class Point:
x = None
y = None
def __init__(self, x, y):
self.x = x
self.y = y
def setX(self, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.