content stringlengths 7 1.05M |
|---|
# Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress.
# Vasya even has a favorite coder and Vasya pays special attention to him.
# One day Vasya decided to collect the results of all contests where his favorite coder participated and track the
# progress of his coolnes... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.37
工具: python == 3.7.3
"""
"""
思路:
二分查找
结果:
执行用时 : 56 ms, 在所有 Python3 提交中击败了100%的用户
内存消耗 : 14.6 MB, 在所有 Python3 提交中击败了100%的用户
"""
class Solution:
def search(self, reader, target):
"""
:type rea... |
'''
Python program to remove two duplicate numbers from a given number of list.
Sample Input:
([1,2,3,2,3,4,5])
([1,2,3,2,4,5])
([1,2,3,4,5])
Sample Output:
[1, 4, 5]
[1, 3, 4, 5]
[1, 2, 3, 4, 5]
'''
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
... |
# optimal performance
def copy_random_list(head):
if not head: return head
# copy each node and insert right after itself
curr = head
while curr:
node_new = RandomListNode(curr.label)
node_next = curr.next
curr.next = node_new
node_new.next = node_next
curr = no... |
class CoinPaymentsProviderError(Exception):
pass
class TxInfoException(Exception):
pass
|
#!/usr/bin/env python
# vi: set ft=python sts=4 ts=4 sw=4 et:
######################################################################
#
# See COPYING file distributed along with the psignifit package for
# the copyright and license terms
#
######################################################################
__do... |
current_number=0
while current_number <=5:
current_number +=1
print(current_number)
|
#!/usr/bin/python3
def add_sub(shellcode: bytes, add_or_sub: bool=True, to_num: int=1, decode: bool=False) -> bytes:
"""Perform a add or sub encoding scheme on `shellcode`.
:return: bytes object
"""
shellcode = bytearray(shellcode)
encoded_payload = bytearray()
calculated_num = (int(add_or_s... |
def tree(length):
if length>5:
t.forward(length)
t.right(20)
tree(length-15)
t.left(40)
tree(length-15)
t.right(20)
t.backward(length)
t.left(90)
t.color("green")
t.speed(1)
tree(90)
|
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=36):
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
@staticmethod
#funciona como uma função da classe pessoa, não precisa recebe... |
#!/usr/bin/env python
'''
https://leetcode.com/problems/find-the-duplicate-number/
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Input: [1,3,4... |
cases = int(input())
for a in range(cases):
tracks = int(input().split(" ")[0])
requests = input().split(" ")
last = int(requests[0])
total = 0
for i in requests[1:]:
next = int(i)
total += min(tracks - ((next - last - 1) % tracks + tracks) % tracks, ((next - last - 1) % trac... |
def alternating_sums(a):
even, odd = [], []
for i in range(len(a)):
if i % 2 == 0:
even.append(a[i])
else:
odd.append(a[i])
return [sum(even), sum(odd)]
def alternating_sums_short(a):
return [
sum(a[::2]), sum(a[1::2])
]
if __name__ == '__main__':
... |
# [h] close all fonts
'''Close all open fonts.'''
all_fonts = AllFonts()
if len(all_fonts) > 0:
for font in all_fonts:
font.close() |
"""Implementation for directed graph."""
class GraphNode:
def __init__(self, node_id):
self.id = node_id
self.data = None
self.adj = set()
class DirectedGraph:
"""Implements a directed graph.
Nodes have unique ids.
Attributes:
nodes: A map of id to node object.... |
"""Top-level package for with-op script."""
__author__ = """Vince Broz"""
__email__ = 'vince@broz.cc'
__version__ = '1.1.1'
|
def adder(a:int, b:int) -> int:
while b:
_xor = a ^ b
_and = (a & b) << 1
a = _xor
b = _and
return a
if __name__ == "__main__":
bin_digits = 8
for i in range(2 ** bin_digits):
for ii in range(2 ** bin_digits):
true = i + ii
test = adder(i, ii)
if true != test:
print(f"Adding: {i:b} + {ii:b}"... |
# calculate 10!
@profile
def factorial(num):
if num == 1:
return 1
else:
print("Calculating " + str(num) + "!")
return factorial(num -1) * num
@profile
def profiling_factorial():
value = 10
result = factorial(value)
print("10!= " + str(result))
if __name__ == "__main__":
... |
""" Holds utilities related with Earth plotting """
EARTH_PALETTE = {
"land_color": "#9fc164",
"ocean_color": "#b2d9ff",
"lake_color": "#e9eff9",
"dessert_color": "d8c596",
}
""" A color palette based on Earth colors """
|
# Problem: Reverse a doubly linked list
# Url: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem
# Level: Easy
# Developer: Murillo Grübler
class DoublyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
self.prev = None
class Doub... |
BZX = Contract.from_abi("BZX", "0xc47812857a74425e2039b57891a3dfcf51602d5d", interface.IBZx.abi)
TOKEN_REGISTRY = Contract.from_abi("TOKEN_REGISTRY", "0x2fA30fB75E08f5533f0CF8EBcbb1445277684E85", TokenRegistry.abi)
list = TOKEN_REGISTRY.getTokens(0, 100)
for l in list:
iTokenTemp = Contract.from_abi("iTokenTemp", ... |
lowestPossible = 1
highestPossible = 999
num = 0
while True:
enemy = hero.findNearest(hero.findEnemies())
if enemy:
if enemy.type == "scout":
lowestPossible = num
elif enemy.type == "munchkin":
highestPossible = num
hero.attack(enemy)
else:
num = lowe... |
#!/usr/bin/env python
# coding: utf-8
# Utility functions
def get_image_size(model_prefix):
if 'caffenet' in model_prefix:
return 227
elif 'squeezenet' in model_prefix:
return 227
elif 'alexnet' in model_prefix:
return 227
elif 'googlenet' in model_prefix:
return 299
elif 'inception-v3' in m... |
# variable = a container for a value.
# Behaves as the value that it contains
first_name = "Bro"
last_name = "Code"
full_name = first_name +" "+ last_name
#name='Bro'
print("Hello "+full_name)
#print(type(name))
age = 21
age += 1
print("Your age is: "+str(age))
#print(age)
#print(type(age))
height = 250.5
print("Yo... |
#!/usr/bin/python
# Any system should have an sh capable of `command -v`
# REQUIRES: command -v sh
print("Oh, but it is!")
# CHECK: This should never be compared
|
__author__ = 'Liu'
__email__ = 'wisedoge@outlook.com'
# 一些惯用变量名的解释
|
#4. Faça um programa que peça dois números e imprima a soma deles.
print('VAMOS SOMAR')
#Informando numeros
num1 = int(input('Digite o 1º número: '))
num2 = int(input('Digite o 2º número: '))
#Declarando soma das variaveis
soma = num1 + num2
#imprimindo somas
print (f'A soma de {num1} + {num2} é igual a {soma}') |
# CloudShell L1 resource autoload XML helper
#
# It should not be necessary to edit this file.
#
# - Generates the autoload XML resource format to return to CloudShell
# - Subresources are also represented with nested instances of this class
# - See example usage in <project>_l1_handler.py
class L1DriverReso... |
class Solution:
def intToRoman(self, num):
symbols_list = [
["M", "M", "M"],
["C", "D", "M"],
["X", "L", "C"],
["I", "V", "X"]
]
pown_list = [1000, 100, 10, 1]
def digitToRoman(digit, symbols):
if digit < 4:
... |
class Solution:
def mySqrt(self, x: int) -> int:
if x < 2: return x
result, value = x, x // 2
while result > value:
result, value = value, (value + x // value) // 2
return result
test = Solution().mySqrt
print(2, test(4))
print(2, test(8))
print(0, test(0))
print(1, tes... |
# Copyright 2015 Ufora Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
CLUSTERS_DB = 'complete_clusters.db'
SAMPLE2PROTEIN_DB = 'sample2protein.db'
SAMPLE2PATH = 'sample2path.tsv'
|
def funny(x):
if (x%2 == 1):
return x+1
else:
return funny(x-1)
print(funny(7))
print(funny(6))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This package contains only the Brewery DB API key. It is necessary to provide
an alternate method for this key entry when using chalice so that secrets
aren't improperly shared.
"""
BREWERY_KEY = "<YOUR_BREWERY_DB_API_APP_KEY_HERE>"
S3_BUCKET = "<YOUR_S3_BUCKET>"
|
class TweetComplaint:
def __init__(self, complain_text, city, state, tweet_id, username, image_url):
self.complain_text = complain_text
self.tweet_id = tweet_id
self.username = username
self.city = city
self.state = state
self.image_url = image_url
self.statu... |
class Solution:
def rob(self, num):
ls = [[0, 0]]
for e in num:
ls.append([max(ls[-1][0], ls[-1][1]), ls[-1][0] + e])
return max(ls[-1])
|
# -*- coding: utf-8 -*-
__version__ = '0.16.1.dev0'
PROJECT_NAME = "planemo"
PROJECT_USERAME = "galaxyproject"
RAW_CONTENT_URL = "https://raw.github.com/%s/%s/master/" % (
PROJECT_USERAME, PROJECT_NAME
)
|
"""This is the entry point of the program."""
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)-1,0,-1):
for j in range(i):
if list_of_numbers[j] > list_of_numbers[j+1]:
placeholder = list_of_numbers[j]
list_of_numbers[j] = list_of_numbers[j+... |
spec = {
'name' : "ODL demo",
'external network name' : "exnet3",
'keypair' : "X220",
'controller' : "r720",
'dns' : "10.30.65.200",
'credentials' : { 'user' : "nic", 'password' : "nic", 'project' : "nic" },
# 'credentials' : { 'user' : "admin", 'password' : "admin", 'project' : "admin" },
... |
#encoding:utf-8
subreddit = 'kratom'
t_channel = '@r_kratom'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
n = 5
count = 0
total = 0
startCount = n - 3
while True:
if count == n:
break
elif count < n:
x = int(input())
if count > startCount:
total = total + x
count = count + 1
print('')
print('Sum is %d.' % total)
|
JPEG_10918 = (
'SOF0', 'SOF1', 'SOF2', 'SOF3', 'SOF5',
'SOF6', 'SOF7', 'SOF9', 'SOF10',
'SOF11', 'SOF13', 'SOF14', 'SOF15',
)
JPEG_14495 = ('SOF55', 'LSE', )
JPEG_15444 = ('SOC', )
PARSE_SUPPORTED = {
'10918' : [
'Process 1',
'Process 2',
'Process 4',
'Process 14',
... |
'''Crie um programa que tenha uma tupla com varias palavras (não usar acentos). Depois disso, voce deve mostrar, para cada palavra, quais são as suas vogais.'''
lista = ('Sao Paulo','Santos','Praia Grande','Peruibe','Cotia','Jundiai','Araraquara','Valinhos')
vogais = ('a','e','i','o','u')
for c in lista:
print(f'\... |
def converte_formato_hora(hora: str):
# Classifica em AM ou PM
if hora[-2:] == "AM":
# se 12, retorna 00:[minutos]
if hora[:2] == "12":
return "00" + hora[2:-3]
# senão, retorna a hora menos AM
else:
return hora[:-3]
elif hora [-2:] == "PM":
... |
# 递归
# Runtime: 32 ms, faster than 100.00% of Python3 online submissions for Invert Binary Tree.
# Memory Usage: 12.4 MB, less than 0.96% of Python3 online submissions for Invert Binary Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left =... |
class Solution:
def numberOfArithmeticSlices(self, A: List[int]) -> int:
count, currentSum = 0, 0
for i in range(2, len(A)):
if A[i] - A[i - 1] == A[i - 1] - A[i - 2]:
count += 1
else:
currentSum += ((count + 1) * count) // 2
co... |
#Add Key imports here!
TRAIN_URL = "https://raw.githubusercontent.com/karkir0003/DSGT-Bootcamp-Material/main/Udemy%20Material/Airline%20Satisfaction/train.csv"
def read_train_dataset():
"""
This function should read in the train.csv and return it
in whatever representation you like
"""
###YOU... |
#!/usr/bin/env python
# encoding: utf-8
"""
candy.py
Created by Shengwei on 2014-07-22.
"""
# https://oj.leetcode.com/problems/candy/
# tags: hard, array, greedy, logic
"""
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the follo... |
"""
Visualization styles.
"""
__author__ = "Alexander Urban"
__email__ = "aurban@atomistic.net"
__date__ = "2021-01-23"
__version__ = "0.1"
CPK = {
'H': 'white',
'C': 'black',
'N': 'blue',
'O': 'red',
'F': 'green',
'Cl': 'green',
'Br': '0x8b0000',
'I': '0x9400d3',
'He': 'cyan',
... |
app_name = 'tulius.profile'
urlpatterns = [
]
|
# 判断整数的位数(0、一位数或多位数)
n = int(input('整数:'))
if n == 0: # 0
print('该值为零。')
elif n >= -9 and n <= 9: # 一位数
print('该值为一位数。')
else: # 多位数
print('该值为多位数。')
|
#
# PySNMP MIB module CISCO-WBX-MEETING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WBX-MEETING-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:04:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
# Column/Label Types
NULL = 'null'
CATEGORICAL = 'categorical'
TEXT = 'text'
NUMERICAL = 'numerical'
ENTITY = 'entity'
# Feature Types
ARRAY = 'array'
# backend
PYTORCH = "pytorch"
MXNET = "mxnet"
|
def main():
a,b,c,k = map(int,input().split())
ans = 0
ans += min(a, k)
ans -= max(0, k-a-b)
print(ans)
if __name__ == "__main__":
main() |
def main():
# equilibrate then isolate cold finger
info('Equilibrate then isolate coldfinger')
close(name="C", description="Bone to Turbo")
sleep(1)
open(name="B", description="Bone to Diode Laser")
sleep(20)
close(name="B", description="Bone to Diode Laser")
|
#!/usr/bin/python3
""" Verifies which numbers from a list of postive integers are even,
using filter and lambda.
filter() constructs a list of elements which were successfully
evaluated, according with the lambda function, upon the elements
of an iterable (list, strings, etc.).
"""
__author__ = "@ivanleoncz"
numb... |
class AmrTypes:
dbpedia = {
"person": "dbo:Person",
"family": "dbo:Agent",
"animal": "dbo:Animal",
"language": "dbo:Language",
"nationality": "dbo:Country",
"ethnic-group": "dbo:EthnicGroup",
"regional-group": "dbo:EthnicGroup",
"religious-group": "db... |
students = []
def get_students_titlecase():
students_titlecase = []
for student in students:
students_titlecase.append(student['name'].title())
return students_titlecase
def print_students_titlecase():
print(get_students_titlecase())
def add_student(name, student_id = 332):
student = {'n... |
# author: @s.gholami
# -----------------------------------------------------------------------
# read_matrix_input.py
# -----------------------------------------------------------------------
# Accept inputs from console
# Populate the list with the inputs to form a matrix
def equations_to_matrix() -> list:
"""
... |
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
return num_islands(grid)
def num_islands(grid):
res = 0
R = len(grid)
C = len(grid[0])
def dfs(i, j):
if grid[i][j] == '1':
grid[i][j] = '0'
if i > 0:
dfs(i - 1, j)
... |
sample_rate = 16000
audio_duration = 10
audio_samples = sample_rate * audio_duration
audio_duration_flusense = 1
audio_samples_flusense = sample_rate * audio_duration_flusense
window_size = 512
overlap = 256
mel_bins = 64
device = 'cuda'
num_epochs = 30
gamma = 0.4
patience = 4
step = 10
random_seed = 36851234
split_... |
# 다음 큰 숫자
def solution(n):
cnt = bin(n).count('1')
while True:
n += 1
if bin(n).count('1') == cnt: return n
'''
정확성 테스트
테스트 1 〉 통과 (0.01ms, 10.2MB)
테스트 2 〉 통과 (0.00ms, 10.2MB)
테스트 3 〉 통과 (0.00ms, 10.2MB)
테스트 4 〉 통과 (0.00ms, 10.2MB)
테스트 5 〉 통과 (0.01ms, 10.2MB)
테스트 6 〉 통과 (0.00ms, 10.3MB)
테스트 7... |
def minion_game(string):
# your code goes here
vowels = frozenset('AEIOU')
length = len(string)
kev_sc = 0
stu_sc = 0
for i in range(length):
if string[i] in vowels:
kev_sc += length - i
else:
stu_sc += length - i
if kev_sc > stu_sc:
print('Kev... |
"""
1 - Faça um programa que receba dois números e mostre qual deles é o maior.
"""
numero1 = int(input("Digite o primeiro número: "))
numero2 = int(input("Digite o segundo número: "))
if numero1 > numero2:
print(f"Entre os números {numero1} e {numero2} .O número maior é: {numero1}")
elif numero1 == numero2:
... |
class Message:
def __init__(self, to_channel):
self.to_channel = to_channel
self.timestamp = ""
self.text = ""
self.blocks = []
self.is_completed = False
def get_message(self):
return {
"ts": self.timestamp,
"channel": self.to_channel,
... |
productions = {
(52, 1): [1,25,47,53,49 ],
(53, 2): [54, 57,59,62,64],
(53, 3): [54,57,59,62,64],
(53, 4): [54,57,59,62,64],
(53, 5): [54,57,59,62,64],
(53, 6): [54,57,59,62,64],
(54, 2): [2,55,47],
(54, 3): [0],
(54, 4): [0],
(54, 5): [0],
(54, 6): [0],
(55, 25): [25,56]... |
class CDI():
def __init__(self,v3,v2,v3SessionID,v3BaseURL,v2BaseURL,v2icSessionID):
print("Created CDI Class")
self._v3=v3
self._v2=v2
self._v3SessionID = v3SessionID
self._v3BaseURL = v3BaseURL
self._v2BaseURL = v2BaseURL
self._v2icSessionID = v2icSessionID
... |
# Média Aritmética
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 + n2) / 2
print('== DADOS OBTIDOS ==')
print('Primeira nota: {:.1f}'.format(n1))
print('Segunda nota: {:.1f}'.format(n2))
print('A média alcançada foi de {:.1f}'.format(m))
|
"""
스택 자료구조 구현
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, value):
new_head = Node(value)
new_head.next = self.head
self.head = new_head
def pop(self):
... |
# Função para Fatorial
def fatorial(n, show=False):
'''
=> Cálucula o Fatorial de um número.
:param n:O número a ser cálculado
:param show: Mostra o fatoramento do número
:return: Retorna com o valor solicitado o Fatorial (n)
'''
f = 1
for c in range(n, 0, -1):
if show:
... |
"""List all the extensions."""
names = [
"tourney",
"season",
"refresh",
"misc",
]
|
# ----------------------------------------------------------------------------
# MODES: serial
# CLASSES: nightly
#
# Test Case: multicolor.py
#
# Tests: Tests setting colors using the multiColor field in some of
# our plots.
# Plots - Boundary, Contour, FilledBoundary, Subset
# ... |
'''
Faça um programa que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas.
'''
nome = input('Qual seu nome: ')
print('Olá {}! Seja bem vindo!'.format(nome))
|
def run_tests_count_tokens(config):
scenario = sp.test_scenario()
admin, [alice, bob] = get_addresses()
scenario.h1("Tests count token")
#-----------------------------------------------------
scenario.h2("Nothing is minted")
contract = create_new_contract(config, admin, scenario, [])
cou... |
gal_sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1406',... |
# This is not for real use!
# This is normally generated by the build and install so should not be used for anything or filled in with real values.
# File generated from /opt/config
#
GLOBAL_INJECTED_AAI1_IP_ADDR = "10.0.1.1"
GLOBAL_INJECTED_AAI2_IP_ADDR = "10.0.1.2"
GLOBAL_INJECTED_APPC_IP_ADDR = "10.0.2.1"
GLOBAL_INJ... |
###############################################################################
# Copyright (c) 2017-2020 Koren Lev (Cisco Systems), #
# Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others #
# #
... |
class RedbotMotorActor(object):
# TODO(asydorchuk): load constants from the config file.
_MAXIMUM_FREQUENCY = 50
def __init__(self, gpio, power_pin, direction_pin_1, direction_pin_2):
self.gpio = gpio
self.power_pin = power_pin
self.direction_pin_1 = direction_pin_1
sel... |
#!/usr/bin/env python3
print("// addTable")
for a in range(0, 10):
print(" '{0}': {{".format(a))
for b in range(a, 10):
s = (a + b) % 10
c = (a + b) // 10
print(" '{0}': '{1}{2}',".format(b, s, c))
print(" },")
print()
print("// subTable")
for a in range(0, ... |
'''1) Um funcionário recebe um salário fixo mais 4% de comissão
sobre as vendas. Faça um programa que receba o salário fixo de um
funcionário e o valor de suas vendas, calcule e mostre a comissão e
o salário final do funcionário.'''
salario = float(input("Digite o valor do seu salario: "))
vendas = float(input("Dig... |
n, k = map(int, input().split())
dis = input().split()
m = n
while True:
m = str(m)
for d in dis:
if d in m:
break
else:
print(m)
exit()
m = int(m) + 1
|
def replay(adb):
adb.tap(1720, 1000)
def go_to_home(adb):
adb.tap(1961, 40)
def go_to_battle(adb):
adb.tap(1943, 928)
def go_to_event_battle(adb):
adb.tap(1900, 345)
def select_daily_event(adb):
adb.tap(313, 267)
def select_unit(adb):
adb.tap(1935, 935)
def sortie(adb):
adb.tap(1930, 947)
def stage_clear_ok(adb)... |
player_1_position = 7
player_2_position = 10
player_1_score = 0
player_2_score = 0
def roll_die():
i = 1
while 1:
yield i
i += 1
if i > 100:
i = 1
roll = roll_die()
number_of_die_rolls = 0
# while (player_1_score < 1000 and player_2_score < 1000):
# for i in range(6):
whi... |
class RevasCalculations:
'''Functions related to calculations go there
'''
pass
|
"""
write a first program in python3
How to run the program in terminal
python3 filename.py
"""
print("HelloWorld in Python !!")
|
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) ... |
# Crie um programa que leia duas notas de um aluno e calcule sua média,
# mostrando uma mensagem no final, de acordo coma média atingida.
# -Média abaixo de 5.0: REPROVADO.
# -Média entre 5.0 e 6.9: RECUPERAÇÃO
# -Média 7.0 ou superior: APROVADO
n1 = float(input('Nota 1: '))
n2 = float(input('Nota 2: '))
media = (n1 + ... |
class Node:
"""Node for bst."""
def __init__(self, val):
"""Instantiate node."""
self.val = val
self.right = None
self.left = None
def __repr__(self):
"""Represent node."""
return '<Node Val: {}'.format(self.val)
def __str__(self):
"""Node value.... |
"""Output the number of labs required for a certain number of students."""
SEATS = 24
students = input('Enter the number of students: ')
while not students.isnumeric():
students = input(
"Numbers are usually numeric. Let's try this again.\n"
'Enter the number of students: '
)
students = int(s... |
def solve(s):
word_list = s.split(' ')
name_capitalized = []
for word in word_list:
name_capitalized.append(word.capitalize())
word = ' '.join(name_capitalized)
return word
|
"""Subscribe to a specific queue
and consume the messages.
"""
class Subscriber:
def __init__(self, adapter):
"""Create a new subscriber with an Adapter instance.
:param BaseAdapter adapter: Connection Adapter
"""
self.adapter = adapter
def consume(self, worker):
"""... |
#
# Copyright (c) 2019 Jonathan McGee <broken.source@etherealwake.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS I... |
#!/usr/bin/python
print('Content-type: text/plain\n\n')
print('script cgi with GET')
|
#
# GeomProc: geometry processing library in python + numpy
#
# Copyright (c) 2008-2021 Oliver van Kaick <ovankaic@gmail.com>
# under the MIT License.
#
# See file LICENSE.txt for details on copyright licenses.
#
"""This module contains the write_options class of the GeomProc geometry
processing library.
"""
# Option... |
OLD_EXP_PER_HOUR = 10
OLD_TIME_TO_LVL_DELTA = 5
NEW_EXP_PER_HOUR = 10
NEW_TIME_TO_LVL_DELTA = 7
NEW_TIME_TO_LVL_MULTIPLIER = 1.02
def old_level_to_exp(level, exp):
total_exp = exp
for i in range(2, level + 1):
total_exp += i * OLD_TIME_TO_LVL_DELTA * OLD_EXP_PER_HOUR
return total_exp
def new_... |
#!/usr/bin/env python3
# probleme des 8 dames
def printGrid(grid):
for y in range(8):
print(8 - y, end=" |")
for x in range(8):
print(grid[x][y], "", end="")
print()
print("------------------")
print("X |A B C D E F G H")
grid = [[0] * 8 for _ in range(8)]
for j in ran... |
class Bicicleta:
def __init__(self, marca, aro, calibragem):
self.marca = marca;
self.aro = aro;
self.calibragem = calibragem;
def __str__(self):
string = "Marca: "+self.marca+"\nAro: "+str(self.aro)+"\nCalibragem: "+str(self.calibragem)
return string
def getMarca(... |
class Node(object):
def __init__(self, nm, name, capacity = 15):
self.nm = nm
self.name = name
self.capacity = capacity
self.values = []
def consume(self, from_name, value):
"""
All subclass need to override this function to do
acturlly calculation
"""
pass
def data_income(self, from_name, valu... |
class Encapsulation:
def __hide(self):
print("示例的隐藏方法")
def getname(self):
return self.__name
def setname(self,name):
if len(name)<3 or len(name)>8:
raise ValueError("长度不在范围内")
self.__name = name
name=property(getname,setname)
e = Encapsulation()
#e.name = "h... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: su jian
@contact: 121116111@qq.com
@file: __init__.py.py
@time: 2017/8/16 17:43
"""
def func():
pass
class Main():
def __init__(self):
pass
if __name__ == '__main__':
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.