content stringlengths 7 1.05M |
|---|
'''
num = int(input('Informe um numero: '))
n = str(num)
print(f'Analisando seu numero {num}')
print(f'Unidade: {n[3]}')
print(f'Dezena: {n[2]}')
print(f'Centena: {n[1]}')
print(f'Milhar: {n[0]}')
# No exemplo acima exibirá um problema quando colocar numeros menores.
# Ex: 123 ou 12 ou 5
# Só funcionará quando o num... |
def primes(n):
out = list()
sieve = [True] * (n+1)
for p in range(2, n+1):
if sieve[p]:
out.append(p)
for i in range(p, n+1, p):
sieve[i] = False
return out
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n ... |
# coding=utf-8
class Legs(object):
def __init__(self):
# Código do aeroporto do ponto de destino da viagem.
self.destination = None
# Código do aeroporto do ponto de origem da viagem.
self.origin = None
|
class Solution:
def maxArea(self, height: List[int]) -> int:
area = 0
left_pivot = 0
right_pivot = len(height)-1
while left_pivot != right_pivot:
current_area = abs(right_pivot-left_pivot) * min(height[left_pivot], height[right_pivot])
# ... |
print("------------------")
print("------------------")
print("------------------")
print("------------------")
print("------------------")
num1 = 10
num2 = 20
|
#exceptions
def spam(divided_by):
try:
return 42 / divided_by
except:
print('Invalid argument.')
print(spam(2))
print(spam(0))
print(spam(1))
|
# Slackbot API Information
slack_bot_token = "xoxb-2650828670406-2670419769553-qxTzP6Sbh9tlqfYIA52wh1bZ"
bot_id = "xoxb-2650828670406-2670419769553-qxTzP6Sbh9tlqfYIA52wh1bZ"
# AIML FIles
directory = "/aiml"
learn_file = "std-startup.xml"
respond = "load aiml b" |
#-*- coding: UTF-8 -*-
def log_info(msg):
print ('bn info:'+msg);
return;
def log_error(msg):
print ('bn error:'+msg);
return;
def log_debug(msg):
print ('bn debug:'+msg);
return; |
def fighter():
i01.moveHead(160,87)
i01.moveArm("left",31,75,152,10)
i01.moveArm("right",3,94,33,16)
i01.moveHand("left",161,151,133,127,107,83)
i01.moveHand("right",99,130,152,154,145,180)
i01.moveTorso(90,90,90) |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self is None:
return "Nil"
else:
return "{} -> {}".format(self.val, repr(self.next))
class Solution:
def oddEvenList(sel... |
# -*- coding: utf-8 -*-
__name__ = "bayrell-common"
__version__ = "0.0.2"
__description__ = "Bayrell Common Library"
__license__ = "Apache License Version 2.0"
__author__ = "Ildar Bikmamatov"
__email__ = "support@bayrell.org"
__copyright__ = "Copyright 2016-2018"
__url__ = "https://github.com/bayrell/common_py3"
|
description = 'Verify the application shows the correct error message when creating a project without name'
pages = ['common',
'index']
def setup(data):
common.access_golem(data.env.url, data.env.admin)
def test(data):
click(index.create_project_button)
click(index.create_button)
index.veri... |
expected_output = {
'group':{
1:{
'state':'Ready',
'core_interfaces':{
'Bundle-Ether2':{
'state':'up'
},
'TenGigE0/1/0/6/1':{
'state':'up'
}
},
'access_in... |
"""
Configuration for Captain's Log.
"""
# The log file. Use an absolute path to be safe.
log_file = "/path/to/file"
|
class Band:
def __init__(self, musicians={}):
self._musicians = musicians
def add_musician(self, musician):
if musician is None:
raise ValueError("Missing required musician instance!")
if musician.get_email() in self._musicians.keys():
raise ValueError("Email a... |
def moving_shift(s, shift):
result=""
for char in list(s):
if char.isupper():
char=chr((ord("A")+(ord(char)-ord("A")+shift)%26))
elif char.islower():
char=chr((ord("a")+(ord(char)-ord("a")+shift)%26))
result+=char
shift+=1
temp=get_list(len(result)) ... |
"""
A pig-latinzer
"""
def pig_latinize(word_list):
"""
Pig-latinizes a list of words.
Args:
word_list: The list of words to pig-latinize.
Returns:
A generator containing the pig-latinized words.
"""
for word in word_list:
if word is None:
... |
'''
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be sho... |
class TestStackiPalletInfo:
def test_no_pallet_name(self, run_ansible_module):
result = run_ansible_module("stacki_pallet_info")
assert result.status == "SUCCESS"
assert result.data["changed"] is False
def test_pallet_name(self, run_ansible_module):
pallet_name = "stacki"
... |
'''(Record and Move on Technique [E]): Given a sorted array A and a target T,
find the target. If the target is not in the array, find the number closest to the target.
For example, if A = [2,3,5,8,9,11] and T = 7, return 8.'''
def record(arr, mid, res, T):
if res == -1 or abs(arr[mid] - T) < abs(arr[res] - T... |
f1 = open("../train_pre_1")
f2 = open("../test_pre_1")
out1 = open("../train_pre_1b","w")
out2 = open("../test_pre_1b","w")
t = open("../train_gbdt_out")
v = open("../test_gbdt_out")
add = []
for i in xrange(30,49):
add.append("C" + str(i))
line = f1.readline()
print >> out1, line[:-1] + "," + ",".join(add)
line = f2... |
class Solution:
def readBinaryWatch(self, num: int) -> List[str]:
return [str(h)+':'+'0'*(m<10)+str(m) for h in range(12) for m in range(60) if (bin(m)+bin(h)).count('1') ==
num]
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( a ) :
return ( 4 * a )
#TOFILL
if __name__ == '__main__':
param = [
(98,),
(9,),
(18,),
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def helper(start):
... |
selRoi = 0
top_left= [20,40]
bottom_right = [60,120]
#For cars2.avi
top_left= [40,50]
bottom_right = [60,80]
top_left2= [110,40]
bottom_right2 = [150,120]
first_time = 1
video_path = 'cars2.avi' |
class Animal:
def __init__(self):
self.age = 1
def eat(self):
print("eat")
class Mammal(Animal):
def walk(self):
print("walk")
m = Mammal()
print(isinstance(m, Mammal))
print(isinstance(m, Animal))
print(isinstance(Mammal, object))
o = object()
print(issubclass(Mammal, Animal))... |
def gen_calk():
''' Generuje dodatnie liczby calkowite zwiekszajac je o 1 '''
l = 1
while True:
yield l
l += 1
def kwadraty():
''' Generuje kwadraty dodatnich liczb calkowitych zwiekszanych o 1 '''
for c in gen_calk():
yield c ** 2
def select(iterowalny, n):
''' Twor... |
inventory_dict = {
"core": [
"PrettyName",
"Present",
"Functional"
],
"fan": [
"PrettyName",
"Present",
"MeetsMinimumShipLevel",
"Functional"
],
"fan_wc": [
"PrettyName",
"Present",
"MeetsMinimumShipLevel"
],
"fr... |
SEAL_CHECKER = 9300535
SEAL_OF_TIME = 2159367
if not sm.hasQuest(25672):
sm.createQuestWithQRValue(25672, "1")
sm.showFieldEffect("lightning/screenMsg/6", 0) |
# -*- coding: utf-8 -*-
class PayStatementReportData(object):
"""Implementation of the 'Pay Statement Report Data' model.
TODO: type model description here.
Attributes:
asset_ids (list of string): The list of pay statement asset IDs.
extract_earnings (bool): Field to indicate... |
class Solution:
def minJumps(self, arr: List[int]) -> int:
if len(arr) == 1:
return 0
d = collections.defaultdict(list)
for index, element in enumerate(arr):
d[element].append(index)
queue = collections.deque([(0, 0)])
s = set()
s.add... |
_base_ = './model_r3d18.py'
model = dict(
backbone=dict(type='R2Plus1D'),
)
|
def func(x):
"""
Parameters:
x(int): first line of the description
second line
third line
Example::
assert func(42) is None
""" |
"""
Uni project. Update literature.
Developer: Stanislav Alexandrovich Ermokhin
"""
dic = dict()
for item in ['_ru', '_en']:
with open('literature'+item+'.txt') as a:
lst = a.read().split(';')
dic[item] = lst
new_lst = list()
for key in dic:
dic[key] = sorted(['\t'+item.replace('\n', '') f... |
'''input
ABCD
No
BACD
Yes
'''
# -*- coding: utf-8 -*-
# CODE FESTIVAL 2017 qual C
# Problem A
if __name__ == '__main__':
s = input()
if 'AC' in s:
print('Yes')
else:
print('No')
|
ss = input()
out = ss[0]
for i in range(1, len(ss)):
if ss[i] != ss[i-1]: out += ss[i]
print(out)
|
def onStart():
parent().par.Showshortcut = True
def onCreate():
onStart()
|
#Edited by Joseph Hutchens
def test():
print("Sucessfully Complete")
return 1
test()
|
def pipe_commands(commands):
"""Pipe commands together"""
return ' | '.join(commands)
def build_and_pipe_commands(commands):
"""Command to build then pipe commands together"""
built_commands = [x.build_command() for x in commands]
return pipe_commands(built_commands)
|
__all__ = [
'ValidationError',
'MethodMissingError',
]
class ValidationError(Exception):
pass
class MethodMissingError(Exception):
pass
|
def main():
while True:
text = input("Enter a number: ")
if not text:
print("Later...")
break
num = int(text)
num_class = "small" if num < 100 else "huge!"
print(f"The number is {num_class}")
|
"""An Extensible Dependency Resolver
"""
__version__ = "0.0.0a3"
|
quadruple_operations = [
'+', # 0
'-',
'*',
'/',
'%',
'=', # 5
'==',
'>',
'<',
'<=',
'>=', # 10
'<>',
'and',
'or',
'goto',
'gotof', # 15
'gotot',
'ret',
'return',
... |
def main():
# problem1()
# problem2()
# problem3()
problem4()
# Create a function that has two variables.
# One called greeting and another called myName.
# Print out greeting and myName two different ways without using the following examples
def problem1():
greeting = "Hello world"
myNam... |
# 037
# Ask the user to enter their name and display each letter in
# their name on a separate line
name = input('Enter ya name: ')
for i in range(len(name)):
print(name[i])
|
# Dictionary Keys, Items and Values
mice = {'harold': 'tiny mouse', 'rose': 'nipple mouse', 'willy wonka': 'dead mouse'}
# Looping over a dictionary
for m in mice.values(): # All values of the dictionary
print(m)
print()
for m in mice.keys(): # All keys of the dictionary
print(m)
print()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 11:29:15 2019
@author: changsicjung
"""
'''
'''
def solution(location, s, e):
answer = -1
# [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print('Hello Python')
return answer |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Constantes para el Tetris con Pygame.
"""
__author__ = "Sébastien CHAZALLET"
__copyright__ = "Copyright 2012"
__credits__ = ["Sébastien CHAZALLET", "InsPyration.org", "Ediciones ENI"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Sébastien CHAZALLET"
__emai... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 09:47:40 2019
@author: Administrator
"""
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
elif num > 0:
ans = []
while num > 0:
tmp = num % 7
num ... |
def selection_sort(items):
"""Implementation of selection sort where a given list of items are sorted in ascending order and returned"""
for current_position in range(len(items)):
# assume the current position as the smallest values position
smallest_item_position = current_position
# ... |
def get_text():
print('Melyik fájlt elemezzük?')
filename = input()
if len(filename) > 0:
f = open(filename, 'r')
text = f.read()
f.close()
else:
text = 'Kutya macska.'
return text
def get_format():
print('Milyen formátumú legyen az elemzés? xml vagy ... |
def make_greeting(name, formality):
return (
"Greetings and felicitations, {}!".format(name)
if formality
else "Hello, {}!".format(name)
)
|
# Python modules
# 3rd party modules
# Our modules
class PulseDesignPreview(object):
"""A lightweight version of a pulse design that's good for populating
lists of designs (as in the design browser dialog).
"""
def __init__(self, attributes=None):
self.id = ""
self.uuid = ""... |
class MockMetaMachine(object):
def __init__(self, meta_business_unit_id_set, tag_id_set, platform, type, serial_number="YO"):
self.meta_business_unit_id_set = set(meta_business_unit_id_set)
self._tag_id_set = set(tag_id_set)
self.platform = platform
self.type = type
self.seri... |
male = [
'Luka',
'Jakob',
'Mark',
'Filip',
'Nik',
'Tim',
'Jaka',
'Žan',
'Jan',
'Lovro',
'Oskar',
'Vid',
'David',
'Gal',
'Liam',
'Žiga',
'Maks',
'Anže',
'Nejc',
'Lan',
'Miha',
'Anej',
'Maj',
'Matija',
'Izak',
'Leon',
... |
__all__ = ('CMD_STATUS', 'CMD_STATUS_NAME', 'CMD_BLOCKED', 'CMD_READY',
'CMD_ASSIGNED', 'CMD_RUNNING', 'CMD_FINISHING', 'CMD_DONE',
'CMD_ERROR', 'CMD_CANCELED', 'CMD_TIMEOUT',
'isFinalStatus', 'isRunningStatus')
CMD_STATUS = (CMD_BLOCKED,
CMD_READY,
C... |
def print_hello():
# 冒号结尾
print('hello')
print_hello()
def print_str(s):
print(s)
return s * 2
# return代表函数的返回值
print(print_str('fuck'))
def print_default(s='hello'):
# print(s)
# 如果不注释掉这一行,就会输出两个hello
return s
# 如果注释掉这一行,就会输出none
print(print_default())
print(print_default(... |
uri = "postgres://user:password@host/database" # Postgresql url connection string
token = "" # Discord bot token
POLL_ROLE_PING = None # Role ID to ping for polls, leave as None to not ping
THREAD_INACTIVE_HOURS = 12 # How many hours of inactivity are required for a
ADD_USERS_IDS = [] # List of user ids to add to... |
# copyright 2008-2009 WebDriver committers
# Copyright 2008-2009 Google Inc.
#
# Licensed under the Apache License Version 2.0 = uthe "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 requ... |
class Account:
""" A simple account class """
""" The constructor that initializes the objects fields """
def __init__(self, owner, amount=0.00):
self.owner = owner
self.amount = amount
self.transactions = []
def __repr__(self):
return f'Account {self.owner},{self.amoun... |
def my_cleaner(dryrun):
if dryrun:
print('dryrun, dont really execute')
return
print('execute cleaner...')
def task_sample():
return {
"actions" : None,
"clean" : [my_cleaner],
}
|
def NumFunc(myList1=[],myList2=[],*args):
list3 = list(set(myList1).intersection(myList2))
return list3
myList1 = [1,2,3,4,5,6]
myList2 = [3, 5, 7, 9]
NumFunc(myList1,myList2) |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/7/19 下午7:00
# @Author : Latent
# @Email : latentsky@gmail.com
# @File : sequence_num.py
# @Software: PyCharm
# @class : 对于库存的清洗
"""
字段说明:
1.inventory_id ---->数据库自增
2.num ---> 当前库存
3.num_level ---> 库存等级
"""
class Sequence_Num(object):
# 1. 库存等级换算 ------>... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
ans = list()
for node in lists:
val = node
while (v... |
"""
1-Recolectar los tipos del AST en diccionario
2-Recolectar Métodos de tipos
3-Verificar la semántica
"""
class battle_sim_typing:
def __init__(self, program, collector, builder, definer,checker, context):
self.program=program
self.collector=collector
self.builder=builder
... |
for i in range(10):
print('Привет', i)
# [перегрузка функции range()]
# Напишем программу, которая выводит те числа
# из промежутка [100;999], которые оканчиваются на 7.
for i in range(100, 1000): # перебираем числа от 100 до 999
if i % 10 == 7: # используем остаток от деления на 10, для получения последней ... |
'''Faça um programa que tenha uma função chamada escreva(), que recebe um texto qualquer
como parâmetro e mostre uma mensagem com o tamanho adaptável'''
def escreva(msg):
tam = len(msg)+4
print('~'*tam)
print(f' {msg}')
print('~'*tam)
#Programa principal
escreva('Gustavo Guanabara')
escreva('oi')
escr... |
# Copyright (C) 2021 <FacuFalcone - CaidevOficial>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is... |
"""
lab9
"""
#3.1
class my_stat():
def cal_sigma(self,m,n):
self.result=0
for i in range (n,m+1):
self.result=self.result+i
return self.result
def cal_p(self,m,n):
self.result=1
for i in range (n,m+1):
s... |
#Replace all ______ with rjust, ljust or center.
THICKNESS = int(input()) #This must be an odd number
c = 'H'
# Top Cone
for i in range(THICKNESS):
print((c*i).rjust(THICKNESS-1)+c+(c*i).ljust(THICKNESS-1))
# Top Pillars
for i in range(THICKNESS+1):
print((c*THICKNESS).center(THICKNESS*2)+(c*THICK... |
cellsize = 200
cells = {}
recording = False
class Cell:
def __init__(self, x, y, ix, iy):
self.x, self.y = x, y
self.ix, self.iy = ix, iy # positional indices
self.xdiv = 1.0
self.ydiv = 1.0
self.left = None
self.up = None
def left_inter(self):
if s... |
jogadores = list()
jogador = dict()
desempenho = list()
resp = 'S'
while resp not in 'N':
print('-=' * 20)
jogador['nome'] = str(input('Nome do jogador: '))
quant = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
soma = 0
for partida in range(0, quant):
gol = int(input(... |
HUOBI_URL_PRO = "https://api.huobi.sg"
HUOBI_URL_VN = "https://api.huobi.sg"
HUOBI_URL_SO = "https://api.huobi.sg"
HUOBI_WEBSOCKET_URI_PRO = "wss://api.huobi.sg"
HUOBI_WEBSOCKET_URI_VN = "wss://api.huobi.sg"
HUOBI_WEBSOCKET_URI_SO = "wss://api.huobi.sg"
class WebSocketDefine:
Uri = HUOBI_WEBSOCKET_URI_PRO
clas... |
"""
Tests using cards CLI (command line interface).
"""
def test_add(db_empty, cards_cli, cards_cli_list_items):
# GIVEN an empty database
# WHEN a new card is added
cards_cli("add something -o okken")
# THEN The listing returns just the new card
items = cards_cli_list_items("list")
assert le... |
class NeuroLangException(Exception):
"""Base class for NeuroLang Exceptions"""
pass
class UnexpectedExpressionError(NeuroLangException):
pass
class NeuroLangNotImplementedError(NeuroLangException):
pass
class ForbiddenExpressionError(NeuroLangException):
"""
Generic exception specifying a... |
def index(array,index):
try:
return array[index]
except:
return array
def append(array,value):
try:
array.append(value)
except:
pass
return array
def remove(array,index):
try:
del array[index]
except:
pass
return array
def dedupe(array):... |
class Entity():
def __init__(self, entityID, type, attributeMap):
self.__entityID = entityID
self.__type = type
self.__attributeMap = attributeMap
@property
def entityID(self):
return self.__entityID
@entityID.setter
def entityID(self, entityID):
self.__enti... |
""" Abstract Syntax Tree Nodes """
class AST: ...
class LetraNode(AST):
def __init__(self, token):
self.token = token
def __repr__(self):
return f'{self.token}'
class NumeroNode(AST):
def __init__(self, token):
self.token = token
def __repr__(self):
return f'{self.to... |
def funcao_numero(num = 0):
ultimo = num
primeiro = 1
while True:
for c in range(1,primeiro + 1):
print(f'{c} ',end=' ')
print()
primeiro += 1
if primeiro > ultimo:
break
num = int(input('Informe um número para ver uma tabela personaliada: '))
funcao_... |
#
# from src/3dgraph.c
#
# a part of main to tdGraph
#
_MAX_VALUE = float("inf")
class parametersTDGraph:
def __init__(self, m, n, t, u, minX, minY, minZ, maxX, maxY, maxZ):
self.m = m
self.n = n
self.t = t
self.u = u
self.minX = minX
self.minY = minY
self.... |
# -*- coding: utf-8 -*-
"""
fahrToCelsius is the function that converts the input temperature from degrees Fahrenheit
to degrees Celsius.
tempFahrenheit is input value of temperature in degrees Fahrenheit.
convertedTemp is returned value of the function that is value of temperature in degrees Celsius.
tempClass... |
class CreateSingleEventRequest:
def __init__(self, chart_key, event_key=None, table_booking_config=None, social_distancing_ruleset_key=None):
if chart_key:
self.chartKey = chart_key
if event_key:
self.eventKey = event_key
if table_booking_config is not None:
... |
#
# PySNMP MIB module PYSNMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PYSNMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:43:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
def uniform_cost_search(graph, start, goal):
path = []
explored_nodes = list()
if start == goal:
return path, explored_nodes
path.append(start)
path_cost = 0
frontier = [(path_cost, path)]
while len(frontier) > 0:
path_cost_t... |
def fibonacci(n):
seznam = []
(a, b) = (0, 1)
for i in range(n):
(a, b) = (b, a+b)
seznam.append(a)
return [a, seznam]
def stevke(stevilo):
n = 1
while n > 0: #nevem kako naj bolje napisem
if fibonacci(n)[0] > 10 ** (stevilo -1):
return fibonacci(n)[1].index(... |
spam = 42 # global variable
def printSpam():
print('Spam = ' + str(spam))
def eggs():
spam = 42 # local variable
return spam
print('example xyz')
def Spam():
eggs = 99
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
def assignSpam(var):
global spam
spam = var
Spam()
printSpam()
assignSp... |
"""
URL: https://codeforces.com/problemset/problem/1422/C
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: combinatorics, dp, math, *1700
---------------------In Progress---------------------
"""
mod = 10 ** 9 + 7
def a(s):
# s = input()
ll = len(s)
summ = 0
for i in range(ll):
current_d... |
def binarySearch(nums, target):
# 左右都闭合的区间 [l, r]
l, r = 0, len(nums) - 1
while l <= r:
mid = (left + right) >> 1
if nums[mid] == target:
return mid
# 搜索区间变为 [mid+1, right]
if nums[mid] < target:
l = mid + 1
# 搜索区间变为 [left, mid - 1]
if ... |
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
print (ar.count(max(ar)))
#https://www.hackerrank.com/challenges/birthday-cake-candles/problem |
class Project:
def __init__(self, id=None, name=None, description=None):
self.id = id
self.name = name
self.description = description
def __repr__(self):
return "%s: %s, %s" % (self.id, self.name, self.description)
def __eq__(self, other):
return self.id == other.id... |
class Service:
def __init__(self, name):
self.name = name
self.methods = {}
def rpc(self, func_name):
def decorator(func):
self._save_method(func_name, func)
return func
if isinstance(func_name, str):
return decorator
func = func_nam... |
'''
Дополните приведенный код, используя срезы, так чтобы он вывел строку s в обратном порядке.
'''
s = "In 2010, someone paid 10k Bitcoin for two pizzas."
print(s[::-1])
|
def prime_factors(strs):
result = []
float=2
while float:
if strs%float==0:
strs = strs / float
result.append(float)
else:
float = float+1
if float>strs:
break
return result
|
'''
Steven Kyritsis CS100
2021F Section 031 HW 10,
November 12, 2021
'''
#3
def shareoneletter(wordlist):
d={}
for w in wordlist:
d[w]=[]
for i in wordlist:
match=False
for c in w:
if c in i:
match=True
i... |
"""
Given a sequence, find the length of its longest repeating subsequence (LRS).
A repeating subsequence will be the one that appears at least twice in the original
sequence and is not overlapping (i.e. none of the corresponding characters in the
repeating subsequences have the same index).
Example 1:
Input: “... |
# A server used to store and retrieve arbitrary data.
# This is used by: ./dispatcher.js
def main(request, response):
response.headers.set(b'Access-Control-Allow-Origin', b'*')
response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST')
response.headers.set(b'Access-Control-Allow-Headers', ... |
clarify_boosted = {
'abita cove': ["cooked cod"],
'the red city': ["baked potatoes", "carrots", "iron ingot"],
'claybound': ["cooked salmon"]
}
aliases = {
'Quartz': 'Quartz Crystal',
'Potatoes': 'Baked Potatoes',
'Nether Wart': 'Nether Wart Block'
}
|
while True:
linha = input("Digite qualquer coisa ou \"fim\" para terminar: ")
if linha == "fim":
break
print(linha)
print("Fim!")
|
"""
What you will learn:
- How to add, subtract, multiply divide numbers
- Float division and integer division
- Modulus (finding the remainder)
- Dealing with exponents
- Python will crash on errors (like divide by 0)
Okay now lets do more cool things with variables. Like making python do math for us!
What you need ... |
phrase = input('Enter a phrase: ')
for c in phrase:
if c in 'aeoiuAEOIU':
print(c) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.