content stringlengths 7 1.05M |
|---|
#!/usr/bin/python3
"""
Define a Square class
"""
class Square:
"""
A class that defines a square.
"""
def __init__(self, size=0):
"""
Initializes the square.
Args:
size (int): The size of the square.
"""
self.size = size
@property
def ... |
'''Без использования библиотек, создать класс для представления информации о времени. Ваш класс должен иметь
возможности установки времени и изменения его отдельных полей (час, минута,
секунда) с проверкой допустимости вводимых значений. В случае недопустимых
значений полей нужно установить максимально допустимое значе... |
#
# PySNMP MIB module CISCOSB-TRAPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-TRAPS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
_base_ = [
'../../_base_/default_runtime.py',
'../../_base_/schedules/schedule_adam_600e.py',
'../../_base_/det_models/panet_r50_fpem_ffm.py',
'../../_base_/det_datasets/icdar2017.py',
'../../_base_/det_pipelines/panet_pipeline.py'
]
train_list = {{_base_.train_list}}
test_list = {{_base_.test_list... |
#Write a program that prompts for a file name, then opens that file and reads through the file,
#and print the contents of the file in upper case.
#Use the file words.txt to produce the output below.
#You can download the sample data at http://www.py4e.com/code3/words.txt
# Use words.txt as the file name
fname = input... |
class Player:
def __init__(self, name: str):
self.name = name
self.wins = 0
def add_win(self):
self.wins += 1
class Player_War(Player):
def __init__(self, name: str):
super().__init__(name)
self.card = None |
# The MIT License (MIT)
# Copyright (c) 2015 Yanzheng Li
# 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,... |
car_lot = ["Ford", "Dodge", "Toyota", "Ford", "Toyota", "Chevrolet", "Ford"]
print(car_lot.count("Ford"))
|
"""
Module containing Client and Clients class.
"""
class Client(object):
"""
Class representing single client connecting to the server.
"""
def __init__(self, *args):
"""Constructor.
Can be called with various amount of arguments.
There are two main options: either provide a ... |
class Board():
WINNERS = [
set([(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)]),
set([(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)]),
set([(2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]),
set([(3, 0), (3, 1), (3, 2), (3, 3), (3, 4)]),
set([(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]),
set([(... |
# Copyright 2018 The GamePad Authors. All Rights Reserved.
#
# 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... |
n = 0
pares = []
impares = []
geral = []
for c in range(0, 7):
n = int(input(f'Digite o {c+1}° valor: '))
if n % 2 == 0:
pares.append(n)
else:
impares.append(n)
pares.sort()
impares.sort()
geral = pares + impares
print(f'Lstas dos pares: {pares}')
print(f'Lista dos Ímpares: {impares}')
""" ... |
class Solution:
def nextGreaterElement(self, n: int) -> int:
num = list(str(n))
# Start from the right most digit and find the first
# digit that is smaller than the digit next to it
i = len(num)-1
while i-1 >= 0 and num[i] <= num[i-1]:
i -= 1
if... |
class Info(object):
# URLs:
data_live_url = "https://data-live.flightradar24.com"
flightradar_url = "https://www.flightradar24.com"
# Flights data URLs:
real_time_flight_tracker_data_url = data_live_url + "/zones/fcgi/feed.js"
flight_data_url = data_live_url + "/clickhandler/?flight={}"
... |
"""HTTP specific constants."""
KEY_AUTHENTICATED = "op_authenticated"
KEY_OPP = "opp"
KEY_OPP_USER = "opp_user"
KEY_REAL_IP = "op_real_ip"
|
# Base class
class SchemaError(Exception):
pass
class SchemaBaseError(SchemaError):
pass
class SchemaAttributeError(SchemaError):
pass
# Don't catch these exceptions
class SchemaBaseUnknownAttribute(SchemaBaseError):
pass
class SchemaBaseLinkTypeNotSupported(SchemaBaseError):
pass
class Sc... |
'''
Что покажет приведенная ниже программа?
x = 5
def add():
x = 3
x = x + 5
print(x)
add()
print(x)
'''
x = 5
def add():
x = 3
x = x + 5
print(x)
add() # результат выполнения функции - 8 (х+5)
print(x)
|
class FoxProgression:
def theCount(self, seq):
if len(seq) == 1:
return -1
a, m = seq[1]-seq[0], seq[1]/float(seq[0])
af, mf = True, m == int(m)
c = sum((af, mf))
for i, j in zip(seq[1:], seq[2:]):
if af and j-i != a:
af = False
... |
#
# PySNMP MIB module ARUBA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARUBA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:25:46 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:23... |
def session_hist_tex(f, session_data,threshold_requests_per_session):
"""
Write session caracteristics in latex file
Parameters
----------
f: file
session_data: pandas dataframe of sessions
threshold_requests_per_session: int for f... |
def YesNo(message=None):
if message:
print(message + ' [y/N]')
else:
print('[y/N]')
choice = input()
if choice != 'y' and choice != 'Y':
return False
return True
def YesNoTwice():
if YesNo():
return YesNo("Are you really really sure?")
return False
def YesNoTrice():
if YesNo():
i... |
for i in range(int(input())):
n=int(input())
a=[int(x) for x in input().split()]
m=int(input())
my=[]
pf,c=0,0
q=[]
for i in range(n):
z=a[i]
if z not in my:
if len(my)<m:
my.append(z)
else:
my[my.index(q.pop(0))]=z
... |
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
for i in range(k-1):
nums.remove(max(nums))
return max(nums)
|
# Garo9521
# https://codeforces.com/contest/1521/problem/B
# math
t = int(input())
for case in range(t):
n = int(input())
array = list(map(int, input().split()))
minpos = array.index(min(array))
print(n - 1)
for i in range(minpos):
print(i + 1, minpos + 1, array[minpos] + minpos - i, array[m... |
class Encoder(tf.keras.layers.Layer):
def __init__(self, intermediate_dim):
super(Encoder, self).__init__()
self.hidden_layer = tf.keras.layers.Dense(
units=intermediate_dim,
activation=tf.nn.relu,
kernel_initializer='he_uniform'
)
self.output_layer = tf.keras.layers.Dense(
un... |
def main():
# input
S = input()
T = input()
U = input()
# compute
# output
print(U + T + S)
if __name__ == '__main__':
main()
|
def chi_squared(k1, k2, xs, ys):
stats_x = [0 for _ in range(k1)]
stats_y = [0 for _ in range(k2)]
d = dict()
for x, y in zip(xs, ys):
if (x,y) in d:
d[(x, y)] += 1
else:
d[(x, y)] = 1
stats_x[x] += 1
stats_y[y] += 1
result = 0.
for ... |
class Solution:
def dfs(self, root):
if root is None:
return (float('inf'), float('-inf'), 0, 0) # min, max, largest, size
left, right = self.dfs(root.left), self.dfs(root.right)
new_min = min(root.val, left[0], right[0])
new_max = max(root.val, left[1], right[1])
... |
def count_substring(string, sub_string):
stringSequences = []
for i in range(len(string)):
stringSequences.append(string[i:i+len(sub_string)])
return stringSequences.count(sub_string)
|
'''
@jacksontenorio8
Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie
duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados,
respectivamente. Ao final, mostre o conteúdo das três listas geradas.
'''
lista = []
lista_par = []
lista_impar = []
whil... |
'''
Copyright 2019-2020 Secure Shed Project Dev Team
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... |
'''configuration variables for use throughout the global scope'''
session = None
# --------------- Static Variables ------------------
APPLICATION_ID = 'amzn1.echo-sdk-ams.app.1a291230-7f25-48ed-b8b7-747205d072db'
APPLICATION_NAME = 'The Cyberpunk Dictionary'
APPLICATION_INVOCATION_NAME = 'the cyberpunk dictionary'
APP... |
#!/usr/bin/env python3
# Print Welcome Message
print('Hello, World')
|
desafio = 'DESAFIO 008'
print('{:=^20}' .format(desafio))
'''
Fazer um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros
'''
metros = float(input('Informar um número em metros: '))
cm = metros * 100
mm = metros * 1000
print('Em centímetros: {} \n Em milímetros: {}' .format(cm, mm)) |
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack = []
result = [0] * len(T)
for idx, t in enumerate(T):
while stack and T[stack[-1]] < t:
prev_idx = stack.pop()
result[prev_idx] = idx - prev_idx
stack.appe... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 6 09:33:36 2021
@author: user15
"""
s = '出席番号1番の山田が5分間スピーチを行わせていただきます。私の気になるITニュースについてお話しさせていただきます。よろしくお願いいたします。〜中略〜データとして4月は100人、5月は150人とひと月で大きく成長しています。'
# ① 発表者の出席番号は何番か出力せよ(出席番号は上記文字列から抜き出すこと)
print('出席番号:',s[4 : 4 + 2])
# ② 発表者の名前を下記のように出力せよ(名前... |
class RevitLinkType(ElementType,IDisposable):
"""
This class represents another Revit Document ("link") brought into
the current one ("host").
"""
@staticmethod
def Create(document,*__args):
"""
Create(document: Document,path: ModelPath,options: RevitLinkOptions) -> RevitLinkLoadResult
C... |
'''Faça um programa para uma loja de tintas.
O programa deverá pedir o tamanho em metros quadrados da área a ser pintada.
Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta
é vendida em latas de 18 litros,
que custam R$ 80,00.
Informe ao usuário a quantidades de latas de tin... |
def how_many_visited_houses(instructions):
visited = {'0:0' : True}
x = 0
y = 0
# ^y
# |
# |
# --------+---------->x
#
#
for step in instructions:
if step == '>':
x += 1
elif step == '<':
x -= 1... |
for _ in range(int(input())):
a=input()
n=len(a)
if n%2==0 and a[0:n//2]==a[n//2:n]:
print("YES")
else:
print("NO")
|
#class SVNRepo:
# @classmethod
# def isBadVersion(cls, id)
# # Run unit tests to check whether verison `id` is a bad version
# # return true if unit tests passed else false.
# You can use SVNRepo.isBadVersion(10) to check whether version 10 is a
# bad version.
class Solution:
"""
@param n: ... |
config = {}
def process_logic_message(message):
type = message.get("type", None)
if type == "initialize":
return __initialize__()
if type == "enable":
return __enable__()
if type == "disable":
return __disable__()
else:
return wirehome.response_creator.not_supporte... |
"""
8 / 8 test cases passed.
Runtime: 28 ms
Memory Usage: 15.2 MB
"""
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return ["FizzBuzz" if i % 3 == 0 and i % 5 == 0 else \
"Fizz" if i % 3 == 0 else \
"Buzz" if i % 5 == 0 else \
str(i) for i in range(... |
class tooltips:
def __init__ (self, attr):
self.tips = dict()
self.ori_attr = attr
for i in attr:
self.tips[i] = True
if 'time_value' in self.tips:
self.tips['time_value'] = False
def set_attr(self, attr):
for i in self.tips:
self.tips[i] = False
for i in attr:
if i in self.tips:
self.... |
# -*- coding: utf-8 -*-
################################################
#
# URL:
# =====
# https://leetcode.com/problems/implement-trie-prefix-tree/
#
# DESC:
# =====
# Implement a trie with insert, search, and startsWith methods.
#
# Example:
# Trie trie = new Trie();
# trie.insert("apple");
# trie.search("apple"); ... |
def foo():
'''
>>> from mod import GoodFile as bad
'''
pass
|
print('program1.py')
a = 100000000
for x in range(1,9):
if (x>=1 and x<=2):
b=a*0
print('laba bulanan ke-',x,':',b)
if (x>=3 and x<=4):
c=a*0.1
print('laba bulanan ke-',x,':',c)
if (x>=5 and x<=7) :
d=a*0.5
print('laba bulanan ke-',x,':',d)
if (x==8) :
e=a*0.2
print('la... |
def return_dict(list):
dict = {}
for plate in list:
if(plate in dict):
dict[plate] = dict[plate] + 1
else:
dict[plate] = 1
return dict
def isNumber(character):
return True if(character<='9' and character>='0') else False
def isLetter(character):
return True i... |
try:
a = 4 / 0
except Exception as ex:
print(str(ex))
finally:
print('Thats all Folks')
|
class Torus(object,IEpsilonComparable[Torus]):
""" Torus(basePlane: Plane,majorRadius: float,minorRadius: float) """
def EpsilonEquals(self,other,epsilon):
""" EpsilonEquals(self: Torus,other: Torus,epsilon: float) -> bool """
pass
def ToNurbsSurface(self):
""" ToNurbsSurface(self: Torus) -> NurbsSurface... |
def bfs(graph, init):
visited = []
queue = [init]
while queue:
current = queue.pop(0)
if current not in visited:
visited.append(current)
adj = graph[current]
for neighbor in adj:
for k in neighbor.keys():
queue.append... |
#coding: utf-8
#---------------------------------------------------------------------------------
# Um programa que contém uma função que recebe dois parâmetros sendo o primeiro
# o número a ser calculado, e o outro sendo um valor lógico(opcional) que indica
# se o processo do cálculo da fatororial será exibido ou n... |
del_items(0x80118770)
SetType(0x80118770, "int NumOfMonsterListLevels")
del_items(0x800A7554)
SetType(0x800A7554, "struct MonstLevel AllLevels[16]")
del_items(0x8011846C)
SetType(0x8011846C, "unsigned char NumsLEV1M1A[4]")
del_items(0x80118470)
SetType(0x80118470, "unsigned char NumsLEV1M1B[4]")
del_items(0x80118474)
S... |
ls = []
with open('input.txt') as fh:
for line in fh.readlines():
if not line.strip():
continue
ls.append(int(line))
for i in range(len(ls)):
for j in range(i+1, len(ls)):
if ls[i] + ls[j] == 2020:
print("part1:")
print(ls[i], ls[j])
prin... |
# encoding=utf8
def banner_bash( bannerstring ):
length= len(bannerstring)
i=0
v_str=""
while ( i < 6 ):
j=0
while (j < length):
char = bannerstring[j].lower()
if ( i == 0 ):
if ( char == "0" ):v_str+=" ██████╗ "
el... |
"""
Command parsing. :py:class:`CommandParser` breaks up the input, and tosses out
:py:class:`ParsedCommand` instance.
"""
class ParsedCommand(object):
"""
A parsed command, broken up into something the command handler can
muddle through.
:attr str command_str: The command that was passed.
:attr ... |
# test practice of the the collatz sequence(the simplest impossible maths problem
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number/2;
print(int(number))
else:
number = (number*3) + 1
print(int(number))
def main():
print("Enter number: ")
number = int(input())
colla... |
class Solution:
def countAndSay__iterative(self, n: int) -> str:
if n <= 0: return "" # EMPTY
if n == 1: return "1"
say_prev = "1"
for i in range(2, n + 1): # n included
say_curr = self.convert(say_prev)
say_prev = say_curr
return say_prev
# ... |
maior = None
menor = None
cont = 0
while True:
entr = input('Digite algum número, ou fim para finalizar: ')
if entr == 'fim': break
try:
int(entr)
except:
print('Erro de entrada')
continue #retorna ao começo do input
if menor is None:
menor = entr
elif maior i... |
"""
Question 7
Write code to calculate fibonacci numbers, create lists containing first 20 fibonacci numbers.
(Fib numbers made by sum of proceeding two.Series start at 0 1 1 2 3 5 8 13...)
"""
a = 0
b = 1
fib_num = list()
count = 0
user_input = input('Enter a number: ')
while not user_input.isdigit():
user_input =... |
"""TensorFlow Lite Support Library Helper Rules for iOS"""
# When the static framework is built with bazel, the all header files are moved
# to the "Headers" directory with no header path prefixes. This auxiliary rule
# is used for stripping the path prefix to the C API header files included by
# other C API header fi... |
class Bills:
"""A class that is used to build the Bills"""
def __init__(self, digest):
self.title = digest.get("title")
self.short_title = digest.get("shortTitle")
self.collection_code = digest.get("collectionCode")
self.collection_name = digest.get("collectionName")
self... |
count = 10
print("Hello!")
while count > 0:
print(count)
count -= 2 |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# This is a sample controller
# this file is released under public domain and you can use without limitations
# -------------------------------------------------------------------------
# ---- example index page ----
de... |
# 初始参数
h=1/10
y0=1
t=0
step=10
# 定义初值问题的右端函数f
def f(t,y):
return 4*t*y**(1/2)
# 定义初值问题的真解
def y(t):
return (1+t**2)**2
# 定义使用runge-kutta方法求解初值问题的函数
def runge_kutta_4(y0,t,h,f,y,step):
un=[y0]
u=[y0]
e=[0]
c=[0,1/2*h,1/2*h,h]
for i in range(step):
k1=f(t,y0)
k2=f(t+c[1],y0+c[1... |
'''
3.1.2 见sym_table中的array_st实现
'''
'''
3.1.3 见sym_table中的link_st实现
'''
class time_object(object):
'''
@brief 3.1.4
'''
def __init__(self, h, m, s):
super().__init__()
self.time = [h, m, s]
def compare_to(self, item):
for i in range(len(self.time)):
... |
'''
Gui
___
Contains the Qt views and controllers.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
|
def make_text(x, y, z):
return '{}時の{}は{}'.format(x, y, z)
x = 12
y = '気温'
z = 22.4
print(make_text(x, y, z))
|
input = """
dir(e). dir(w). dir(n). dir(s).
inverse(e,w). inverse(w,e).
inverse(n,s). inverse(s,n).
row(X) :- field(X,Y).
col(Y) :- field(X,Y).
num_rows(X) :- row(X), not row(XX), XX = X+1.
num_cols(Y) :- col(Y), not col(YY), YY = Y+1.
goal(X,Y,0) :- goal_on(X,Y).
reach(X,Y,0) :- init_on(X,Y).
conn(X,Y,D,0) :- co... |
"""
44. How to select a specific column from a dataframe as a dataframe instead of a series?
"""
"""
Difficulty Level: L2
"""
"""
Get the first column (a) in df as a dataframe (rather than as a Series).
"""
"""
Input
"""
"""
df = pd.DataFrame(np.arange(20).reshape(-1, 5), columns=list('abcde'))
"""
# Input
df = pd.Dat... |
numCasoTeste = int(input())
membros = ['Rolien', 'Naej', 'Elehcim', 'Odranoel']
for casoTeste in range(numCasoTeste):
numInput = int(input())
for _ in range(numInput):
recebido = int(input())
print(membros[recebido - 1]) |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 8 13:44:47 2020
@author: celine.gross
"""
with open('input_day8.txt', 'r') as file:
puzzle = file.read().strip().split('\n')
# Part 1
def to_next(data, i=0, accumulator=0):
'''
Returns the next line index to look at (i) and the updated accumulator value
... |
#
# PySNMP MIB module HP-SN-SW-L4-SWITCH-GROUP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-SN-MIBS
# Produced by pysmi-0.3.4 at Mon Apr 29 19:23:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
#!/usr/bin/env python3
# [rights] Copyright 2020 brianddk at github https://github.com/brianddk
# [license] Apache 2.0 License https://www.apache.org/licenses/LICENSE-2.0
# [repo] github.com/brianddk/reddit/blob/master/python/mining.py
# [btc] BTC-b32: bc1qwc2203uym96u0nmq04pcgqfs9ldqz9l3mz8fpj
# [tipjar] gith... |
""" Supplies the internal functions for functools.py in the standard library """
# reduce() has moved to _functools in Python 2.6+.
reduce = reduce
class partial(object):
"""
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
"""
__slots_... |
# Copyright 2019 The Bazel Authors. All rights reserved.
#
# 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 la... |
# -*- coding: utf-8 -*-
_translations = {
"req_fine_reduction": {
"en": "###Request a Fine Reduction",
"es": "###Cómo solicitar una reducción de multa",
"zh-s": "###请求减少罚款",
"zh-t": "###請求減少罰款"
},
"landing_page_description": {
"en":
"""*This online system is an optional way to request a fine... |
data = b""
data += b"\x7F\x45\x4C\x46" # ELF
data += b"\x02\x02\x02" # ELF64
data += b"\x20\x00" # ABI
data += b"\x00\x00\x00\x00\x00\x00\x00" # Pad
data += b"\x00\x00\x00\x00\x00\x00\x00\x00" # Type Machine Version
data += b"\x00\x00\x00\x00\x00\x00\x00\x00" # Start Address
data += b"\x00\x00\x00\x00\x00\x00\x00\x40"... |
class User:
def __init__(self):
self.id = None
self.login = None
self.password = None
self.fullName = None
self.phone = None
self.email = None
self.imageUrl = ''
self.activated = False
self.langKey = 'en'
self.activationKey = None
... |
row = int(input("How many rows you want? "))
column = int(input("How many columns you want? "))
if row==column:
for i in range(1,row+1):
for j in range(1,row+1):
if i==j:
print("1", end = " ")
else:
print("0", end= " ")
print("")
else:
pri... |
def arithmetic_progression(el_1, el_2, n):
"""Finds the nth element of Given the first two elements of
an arithmetic progression.
NOTE: nth term for arithmetic progression is a sub n = (n-1)*d + a
where n is the nth term, d is difference, a is the first element of
the arithmetic progression.
"""... |
patches = [
{
"op": "remove",
"path": "/PropertyTypes/AWS::S3::StorageLens.S3BucketDestination/Properties/Encryption/Type",
},
{
"op": "add",
"path": "/PropertyTypes/AWS::S3::StorageLens.S3BucketDestination/Properties/Encryption/PrimitiveType",
"value": "Json",
},... |
#
# PySNMP MIB module CISCO-COMMON-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-MGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
with open("input_16.txt", "r") as f:
lines = f.readlines()
names = []
restrictions = []
for line in lines:
if len(line.strip()) == 0:
break
names.append(line.strip().split(": ")[0])
values = line.strip().split(": ")[1]
ranges = values.split(" or ")
restrictions.append([
[int(x)... |
#cigar_party
def cigar_party(cigars, is_weekend):
if 40<=cigars<=60:
return True
elif cigars>=60 and is_weekend:
return True
return False
#date_fashion
def date_fashion(you, date):
if you<=2 or date<=2:
return 0
elif you>=8 or date>=8:
return 2
elif 2<you<8 or 2<date<8:
r... |
def bucketSort(input):
'''简单的桶排序
时间复杂度可以,但是浪费空间'''
min=input[0]
max=input[0]
for temp1 in input:
if temp1>max:
max=temp1
if temp1<min:
min=temp1
tempArr=[0]*(max+1)
#print(tempArr)
for temp2 in input:
tempArr[temp2]+=1
print(tempArr)
... |
Listagem = ("Lápis", 1.75, "Borracha", 2.00, "Caderno", 15.90, "Estojo", 25.00, "Transferidor", 4.20,
"Compasso", 9.99, "Mochila", 120, "Canetas", 22.30, "Livro", 34.90)
print('--'*20)
print(f'{"LISTAGEM DE PREÇOS":^40}')
print('--'*20)
for i in Listagem:
if type(i) is str:
print(f... |
#
# first solution:
#
class sample(object):
class one(object):
def __get__(self, obj, type=None):
print("computing ...")
obj.one = 1
return 1
one = one()
x=sample()
print(x.one)
print(x.one)
#
# other solution:
#
# lazy attribute descriptor
class lazyattr(objec... |
"""Class Transaction"""
class Transaction:
"""Docs."""
def __init__(self):
# Crea una transacción
# hash
# de quien
# para quien
# timestamp
# monto en satoshis
# fee
pass
def read_transaction_config(config_file, node_file, dir):
"""Read th... |
"""About this package."""
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "jupyter-d3"
__summary__ = "Jupyter magic providing easy integration of d3 JavaScript visualization library."
__uri__ = "https://github.com/Cerma... |
class Ball(object):
color = str()
circumference = float()
brand = str()
|
NAME = 'converter.py'
ORIGINAL_AUTHORS = [
'Angelo Giacco'
]
ABOUT = '''
Converts currencies
'''
COMMANDS = '''
>>> .convert <<base currency code>> <<target currency code>> <<amount>>
returns the conversion: amount argument is optional with a default of 1
.convert help
shows a list of currencies supported
'''
W... |
class Bar:
x = 1
print(Bar.x)
|
def find_min(array, i):
if i == len(array) - 1:
return array[i]
else:
tmp_min = array[i]
i = i + 1
min_frm = find_min(array, i)
return min(tmp_min, min_frm)
a = [2, 1, 3, 10, 53, 23, -1, 2, 5, 0, 34, 8]
#a = [x for x in range(1000)]
print (find_min(a, 0))
|
def solve(input):
print(sum(list(map(int, input))))
with open('input.txt', 'r') as f:
input = f.read().splitlines()
solve(input)
|
# Given a linked list, determine if it has a cycle in it.
# Follow up:
# Can you solve it without using extra space?
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boo... |
#1
# Time: O(n)
# Space: O(n)
# Given an array of integers, return indices of
# the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution,
# and you may not use the same element twice.
#
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Bec... |
def get_length(dna):
''' (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
'''
return len(dna)
def is_longer(dna1, dna2):
''' (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
... |
"""
Workflow module
"""
class Workflow:
"""
Base class for all workflows.
"""
def __init__(self, tasks, batch=100):
"""
Creates a new workflow. Workflows are lists of tasks to execute.
Args:
tasks: list of workflow tasks
batch: how many items to proces... |
"""Utility variables and functions for the TS3 API"""
# FROM OLD API
"""
Don't change the order in this map, otherwise it might break
"""
_ESCAPE_MAP = [
("\\", r"\\"),
("/", r"\/"),
(" ", r"\s"),
("|", r"\p"),
("\a", r"\a"),
("\b", r"\b"),
("\f", r"\f"),
("\n", r"\n"),
("\r", r"\r"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.