content stringlengths 7 1.05M |
|---|
with open('input.txt') as f:
lines = f.readlines()
ans = 0
for line in lines:
input, output = line.split(" | ")
for word in output.split():
length = len(word)
if length == 2 or length == 4 or length == 3 or length == 7:
ans += 1
print(ans)
|
def fibonacci_iterative(num):
a = 0
b = 1
total = 0
for _ in range(2, num + 1):
total = a + b
a = b
b = total
return total
def fibonacci_recursive(num):
if num < 2:
return num
return fibonacci_recursive(num-1) + fibonacci_recursive(num-2)
print(fibonacci_i... |
data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
def makedict(**kwargs):
return kwargs
data = makedict(red=1, green=2, blue=3)
print(data)
def dodict(*args, **kwds):
d = {}
for k, v in args: d[k] = v
d.update(kwds)
return d
tada = dodict(yellow=2, green=4, *data.items())
print(tada)
|
class CicloCompleto:
def run(self):
print('Lavando...')
print('Enjuagando...')
print('Centrifugando...')
print('Finalizado!')
class SoloCentrifugado:
def run(self):
print('Centrifugando...')
print('Finalizado!')
#Fachada que instancia código "complejo"
class Lav... |
"""69. Sqrt(x)"""
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
#####Practice
###############
l = 0
r = x
while l <= r:
mid = l + (r - l)//2
if mid*mid <= x < (mid+1)*(mid+1):
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2014 Tech Receptives (<http://techreceptives.com>)
{
'name': 'Singapore - Accounting',
'author': 'Tech Receptives',
'website': 'http://www.techreceptives.com',
'category': 'Localization',... |
# A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number
# of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
# For example, take 153 (3 digits):
# 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
# and 1634 (4 digits):
# 1^4 + 6... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Hello(object):
def hello(self, name='world'):
print('Hello, %s.' % name) |
class Solution:
"""
@param n: an integer
@param k: an integer
@return: how many problem can you accept
"""
def canAccept(self, n, k):
n = int(n / k)
start = 0
end = n
while start + 1 < end:
mid = start + int((end - start) / 2)
fact = ((1 + ... |
#!/usr/bin/env python3
# 2020暑期排位5K_生日谜题
# https://codeforces.com/group/H9K9zY8tcT/contest/286081/problem/K
# bit-operation? 不适合python? 也能做
# 还能用dfs来做!?
t = input()
l = list(map(int,input().split()))
nob = 20 #as ai<10^5
n = len(l)
counts = [sum([(1<<i)&x == 0 for x in l]) for i in range(nob)]... |
# Note that we can only test things here all implementations must support
valid_data = [
("acceptInsecureCerts", [
False, None,
]),
("browserName", [
None,
]),
("browserVersion", [
None,
]),
("platformName", [
None,
]),
("pageLoadStrategy", [
N... |
class CodesDict(object):
def __init__(self, codes):
self.__dict__.update(codes)
_codes = {
'waiting': 1,
'analysis': 2,
'paid': 3,
'available': 4,
'dispute': 5,
'returned': 6,
'canceled': 7,
}
codes = CodesDict(_codes)
|
class Monitor:
def __init__(self, controller, redis_address):
self.controller = controller
self.redis_address = redis_address
def _schedule(self, gid, nid, domain, name, args={}, cron='@every 1m'):
"""
Schedule the given jumpscript (domain/name) to run on the specified node ac... |
senseiraw = {
"name": "SteelSeries Sensei RAW (Experimental)",
"vendor_id": 0x1038,
"product_id": 0x1369,
"interface_number": 0,
"commands": {
"set_logo_light_effect": {
"description": "Set the logo light effect",
"cli": ["-e", "--logo-light-effect"],
"... |
def ordering_fries():
print("Can I have some fried potatoes please?")
def countries_papagias_preferes():
print("Albania-Bulgaria-Romania...!")
|
"""
Description: find the area of triangle, given breadth and height
"""
# function definition of areatriangle
def areatriangle(breadth,height):
return (breadth*height)/2;
# input breadth and height
b = int(input("Enter the breadth of triangle: "))
h = int(input("Enter teh height of triangle: "))
print("The area o... |
'''
Linked List has 2 parts : A node that stores the data and a pointer to the next Node.
So it is handled in 2 classes:
1. Node class with operations:
1. init function to get the data and next node value
2. get_data function to get the data of the node
3. set_data function to set the data of the node
... |
"""
create by hanxiao on
"""
__author__ = "hanxiao"
PRE_PAGE = 15
BEANS_UPLOAD_ONE_BOOK = 0.5
|
class Foo():
def __init__(self, msg):
self.msg = msg
def show(self):
print(self.msg)
@classmethod
def foo_class_method(cls):
print(f"我是{cls.__name__}类, 但是我在调用自己的静态方法哦~ ", end='')
cls.foo_static_method()
@staticmethod
def foo_static_method():
print("Foo... |
# This file was generated by wxPython's wscript.
VERSION_STRING = '4.0.7.post2'
MAJOR_VERSION = 4
MINOR_VERSION = 0
RELEASE_NUMBER = 7
BUILD_TYPE = 'release'
VERSION = (MAJOR_VERSION, MINOR_VERSION, RELEASE_NUMBER, '.post2')
|
## TASK 1 - here are the expected letter frequencies in the english language - convert them to a byte frequency table
expected_letter_frequencies = {'a': 8.167, 'b': 1.492, 'c': 2.782, 'd': 4.253, 'e': 12.702, 'f': 2.228, 'g': 2.015, 'h': 6.094, 'i': 6.966, 'j': 0.153, 'k': 0.772, 'l': 4.025, 'm': 2.406, 'n': 6.749, '... |
def bracket_check(brackets):
'''function for checking a string of brackets'''
o = [ '{', '[', '(' ]
c = [ '}', ']', ')' ]
l = []
check = 0
for i in brackets:
if i in o:
check += 1
if i in c:
check -= 1
if check == 0:
print('yep')
else... |
# 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 ... |
class Utils:
@staticmethod
def fastModuloPow(num: int, pow: int, modulo: int) -> int:
result = 1
while pow:
if pow % 2 == 0:
num = (num ** 2) % modulo
pow = pow // 2
else:
result = (num * result) % modulo
pow... |
# https://leetcode.com/problems/satisfiability-of-equality-equations
class UnionFind:
def __init__(self):
self.node2par = {chr(i + 97): chr(i + 97) for i in range(26)}
def find_par(self, x):
if self.node2par[x] == x:
return x
par = self.find_par(self.node2par[x])
r... |
#
# PySNMP MIB module A3COM-HUAWEI-DHCPSNOOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-DHCPSNOOP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:04:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
#Copyright (c) 2020 Jan Kiefer
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES... |
ast = int(input("Ingrese numero de asteroides"))
nom =input("Ingrese nombre de asteroides")
print("Los",ast,"asteroides",nom,"caen del cielo") |
#!/usr/bin/env python
compsys={
'Artisan':{
'db':'file-store',
'objects':['Artisan','Product','Order','Customer'],
},
'Central Office user':{
'db':'file-store',
'objects':['Artisan','Product','Order','Customer'],
},
}
|
def main():
my_integ_loop.getIntegrator( trick.Runge_Kutta_2, 4)
trick.stop(300.0)
if __name__ == "__main__":
main()
|
# Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento:
# - à vista dinheiro/cheque: 10% de desconto
# - à vista no cartão: 5% de desconto
# - em até 2x no cartão: preço normal
# - 3x ou mais no cartão: 20% de juros
print('-' * 100)
print('{: ^100}'... |
S_ASK_DOWNLOAD = 0
C_ANSWER_YES = 1
C_ANSWER_NO = 2
S_ASK_UPLOAD = 3
S_ASK_WAIT = 4
S_BEGIN = 5
|
#!/usr/bin/env python3
n = 4
A = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2],
[2, 0.00001, 1, 0.4]]
b = [0, 1, 2, 3]
# Gauss elim
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
... |
depends = ["unittest"]
description = """
Plug and play integration with the Jenkins Coninuous Integration server.
For more information, visit:
http://www.jenkins-ci.org/
""" |
def keyExtract(array, key):
"""Returns values of specific key from list of dicts.
Args:
array (list): List to be processed.
key (str): Key to extract.
Returns:
list: List of extracted values.
Example:
>>> keyExtract([
{'a': 0, ...}, {'a': 1, ...}, {'a': 2, ...}... |
#Pat McDonald - 8/2/2018
#Exercise 3: Collatz conjecture
#Week 3 of Programming and Scripting
#Inspired by Reddit!: https://www.reddit.com/r/Python/comments/57r6bf/collatz_conjecture_program/?st=jdhil1j5&sh=ba8fd995
n = int(input("Type an integer: "))
print(n)
while n != 1:
if (n % 2 == 0):
#(n / 2) outputs a floa... |
n = int(input())
lista = [int(x) for x in input().split()]
qtde = lista.count(0)
indice = []
for i in range(0,qtde):
indice.append(lista.index(0))
lista[indice[i]] = 2
for i in range(0,n):
menor = 100000
for j in range(0,len(indice)):
temp = abs(i - indice[j])
if(temp < menor):
... |
"""Codewars: Happy Numbers
6 kyu
URL:https://www.codewars.com/kata/59d53c3039c23b404200007e/train/python
Math geeks and computer nerds love to anthropomorphize numbers and
assign emotions and personalities to them. Thus there is defined the
concept of a "happy" number. A happy number is defined as an integer
in wh... |
N = int(input())
S = str(input())
flag = False
half = (N+1) // 2
if S[:half] == S[half:N]:
flag = True
if flag:
print("Yes")
else:
print("No") |
#!/usr/bin/env python
weight = input("your weight is? ")
height = input("your height is? ")
bmi = float(weight) / ( float(height) ** 2 )
print(f"your bmi: {bmi:.2f}")
if bmi <= 18.5:
print("you are so thin!")
elif bmi <= 25 and bmi > 18.5:
print("well, you are fit.")
elif bmi <= 28 and bmi > 25:
print("it l... |
#!/usr/bin/env conda-execute
# conda execute
# env:
# - python ==3.5
# - conda-build
# - pygithub >=1.29
# - pyyaml
# - requests
# - setuptools
# - tqdm
# channels:
# - conda-forge
# run_with: python
# TODO take package or list of packages
# TODO take github url or github urls
# TODO If user doesn't have a fo... |
class SvResponseBase:
def __init__(self, cl_request):
self.cl_request = cl_request
def payload():
""" OVERRIDE THIS TO IMPLEMENT """
raise
|
#! env\bin\python
# Ryan Simmons
# Coffee Machine Project
class CoffeeMachine:
# the values in supplies refers to 1-1 with this
supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
def __init__(self, supplies):
self.supplies = supplies
def supply_checker(self, drink)... |
"""
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of
favorite restaurants represented by strings. You need to help them find out their common interest
with the least list index sum. If there is a choice tie between answers, output all of them with
no order requirement. You ... |
# Write a program to print the pattern
def pattern(a):
print("Output :")
for i in range(1, a+1):
c = 1
for k in range(a, i, -1):
print(" ", end="")
for j in range(1, 2*i):
if j < i:
print(c, end="")
c += 1
els... |
# O(n ^ 4)
# class Solution:
# def countQuadruplets(self, nums: List[int]) -> int:
# n = len(nums)
# ans = 0
# for a in range(n - 3):
# for b in range(a + 1, n - 2):
# for c in range(b + 1, n -1):
# for d in range(c + 1, n):
# ... |
# Constants
#
# Device Variables
VAR_BILLINGPERIODDURATION = 'zigbee:BillingPeriodDuration'
VAR_BILLINGPERIODSTART = 'zigbee:BillingPeriodStart'
VAR_BLOCK1PRICE = 'zigbee:Block1Price'
VAR_BLOCK1THRESHOLD = 'zigbee:Block1Threshold'
VAR_BLOCK2PRICE = 'zigbee:Block2Price'
VAR_BLOCK2THRESHOLD = 'zigbee:Block2Threshold'
V... |
# Bit manipulation
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
for i in range(1 << len(nums)):
tmp = []
for j in range(len(nums)):
if i >> j & 1:
... |
"""Utility queries for create, drop tables and insert data."""
# DROP TABLES
songplay_table_drop = "drop table if exists songplays"
user_table_drop = "drop table if exists users"
song_table_drop = "drop table if exists songs"
artist_table_drop = "drop table if exists artists"
time_table_drop = "drop table if exists t... |
def load_file_list(f_list):
lines=[]
for fp in f_list:
with open(fp,'r',encoding='utf-8') as f:
for line in f:
strs=line.strip().split('\t')
lines.append([float(strs[0]),len(lines),strs[1]])
return lines
def build_id_dict(list):
dic={}
for l in l... |
# -------------
# netrecon info
# --------------
__name__ = 'netrecon'
__version__ = 0.19
__author__ = 'Avery Rozar: avery.rozar@trolleyesecurity.com'
|
def read_puzzle(path):
with open(path, 'r+') as file:
return file.read().split('\n')
class Submarine:
horizontal = 0
depth = 0
aim = 0
def forward(self, x):
self.horizontal = self.horizontal + x
self.depth = self.depth + self.aim * x
def down(self, y):
self.ai... |
class FieldDimension:
def __init__(self, dimension, indexes):
self.dimension = dimension
self.indexes = indexes
@classmethod
def to_index(cls, t):
"""
:param t: t look like "1" or "4-7"
:return: tuple either size of 1 or 2 (1) or (4, 7)
"""
... |
for t in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
counter = 0
flag = False
result = True
for i in A:
if i == 1 and not flag:
counter = 1
flag = True
elif i == 1 and counter < 6 :
result = False
br... |
"""
Topic modeling is a type of statistical modeling for discovering the abstract 'topics' that occur in
a collection of documents, Latent Dirichlet Allocation is an example of topic model and is used to
classify text in a document to a particular topic. It builds a topic per document model and words per
topic model, m... |
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
s = 0
while n > 0:
if n % 2 == 1:
s += 1
n = n // 2
return s
def test_0():
assert Solution().hammingWeight(11) == 3
assert So... |
"""
NAME : DIBANSA, RAHMANI P.
NAME : BELGA, EMJAY
COURSE : BSCPE 2-2
ACADEMIC YEAR : 2019-2020
PROGRAM'S SUMMARY: THIS PROGRAM WOULD MIMIC A STACK OF NOTEBOOKS THAT WOULD BE CHECKED. THIS PROGRAM RECORDS THE NAME
OF THE NOTEBOOK'S OWNER AND ADDS THE NOTEBOOK ON THE TOP OF THE STACK. AS ... |
# https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/
class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
dp = [0] * len(word)
dic = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
dp[0] = 1 if word[0] == 'a' else 0
for i in range(1, len(word)):
... |
# IF COM ESTRUTURA ANHINHADOS
idade = 18
if idade > 17:
print('Você pode dirigir ')
nome = 'Bob'
print()
print('Testando condição aninhada.....')
if idade > 13:
if nome == 'Bob':
print('Ok Bob, você esta autorizado a entrar ')
else:
print("Desculpe, mas você não pode entrar! ")
print()
... |
# flake8: noqa
def foo():
def inner():
x = __test_source()
__test_sink(x)
def inner_with_model():
return __test_source()
|
"""A collection of command-related exceptions."""
__all__ = ('CommandError', 'ArgumentError', 'MissingArgumentError', 'UnusedArgumentsError', 'AuthorizationError',
'ComplexityError')
class CommandError(Exception):
"""Raised on any command processing error."""
class ArgumentError(CommandError):
"... |
with open("3.txt") as f:
nums = [x for x in f.read().split("\n")]
totals = [0] * len(nums[0])
for n in nums:
for i, c in enumerate(n):
totals[i] += 1 if c == "1" else -1
gamma = int("".join(map(lambda x: "1" if x > 0 else "0", totals)), 2)
epsilon = int("".join(map(lambda x: "1" ... |
"""
This problem was asked by Lyft.
Given a list of integers and a number K, return which contiguous elements of the list sum to K.
For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9.
"""
# solved through caterpillar method
def get_contigous_sum(k, arr):
... |
# define variables
# dont change
fdd = 79
daynames = ['شنبه', 'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنج شنبه', 'جمعه']
monthname = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند']
grgdayofmonthleap = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366... |
e = int(input('Digite até que número você quer fazer a soma dos ímpares multiplos de 3: '))
s = 0
for c in range(0, e+1):
if c % 3 == 0 and c % 2 != 0:
s = s + c
print('A soma de todos é {}.'.format(s))
|
# define inception block layer
def InceptBlock(filters, strides):
"""InceptNet convolutional striding block.
filters: tuple: (f1,f2,f3)
filters1: for conv1x1
filters2: for conv1x1,conv3x3
filters3L for conv1x1,conv5x5"""
filters1, filters2, filters3 = filters
conv1x1 = stax.serial(... |
'''
In ChessLand there is a small but proud chess bishop with a recurring dream. In the dream the bishop finds itself on an n × m chessboard with mirrors along each edge, and it is not a bishop but a ray of light. This ray of light moves only along diagonals (the bishop can't imagine any other types of moves even in it... |
# Orden de ejecución de operaciones aritméticas
a = (3+1) + 4**2 * 2 # 36 => () => ** => * => +
a = 4 * 5 + 6 - 3 # 23 => * => + => -
a = 4 * 5 * 6 - 3 # 117 => * => * => -
a = 4 * 5 * (6 - 3) # 60 => (-) => * => *
a = 9 / (3 * 2 + 3) # 1 (* => +) => /
a = 9 / 3 * 2 + 3 # 9 / => * => +
print("Final... |
class PackageInstaller(object):
"""
Installs packages
"""
def __init__(self, connector, packages)-> None:
self.__packages_installed = 0
self.__packages = packages
self.__bash_connector = connector
for package in self.__packages:
self.__run_package_installer... |
count = 0
count2 = 0
while True:
questions = set()
# 2nd part
everyone = set()
fst = True
try:
person = input()
while person != "":
for x in person:
questions.add(x)
if fst:
for x in person:
everyone.add(... |
class SerializerError(Exception):
def __init__(self, message):
self._message = message
class ValidationError(SerializerError):
pass
class InvalidSerializer(SerializerError):
pass
|
n = int(input())
a = [['' for j in range(n)] for i in range(n)]
for i in range(n):
f = 0
for j in range(i, n):
a[i][j] = str(f)
f += 1
f = i
for j in range(i):
a[i][j] = str(f)
f -= 1
for row in a:
print(' '.join(row))
# For the record, I feel dumb because it coul... |
#!/usr/bin/env python3
# https://abc102.contest.atcoder.jp/tasks/abc102_b
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
print(a[-1] - a[0])
|
# Spiegelmann (9071005) | In Monster Park Maps
response = sm.sendAskYesNo("Do you want to leave?")
if response:
sm.warpInstanceOut(951000000)
|
#!/usr/local/bin/python3
def main():
# Test suite
tests = [
[None, None], # Should throw a TypeError
[-1, None], # Should throw a ValueError
[0, 0],
[9, 9],
[138, 3],
[65536, 7]
]
print('Testing add_digits')
for item in tests:
try:
... |
"""
Rules for representing package from package managers.
"""
_PACKAGE_JSON_TEMPLATE = "\"package\": \"{package}\", \"version\": \"{version}\", \"sum\": \"{sum}\""
def _package_json_impl(ctx):
ctx.actions.write(
output = ctx.outputs.manifest,
content = "{" + _PACKAGE_JSON_TEMPLATE.format(
... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Most digits
#Problem level: 7 kyu
def find_longest(arr):
return arr[[len(str(x)) for x in arr].index(max([len(str(x)) for x in arr]))]
|
#!/usr/bin/env python3
def main():
# initialize round counter to 0 and answer to blank
round = 0
answer = " "
# set up loop
while round < 3 and (answer.lower() != "brian" and answer.lower() != "shrubbery"):
# increment round
round += 1
answer = input("Finish the movie ti... |
def sentence_maker(phrase):
interrogatives = ("why","how","what")
capitalized = phrase.capitalize()
#startswith function checks whether the string starts with the given values
if phrase.startswith(interrogatives):
return f"{capitalized}?"
else:
return f"{capitalized}."
conversation... |
"""
For in Python
Iterando Strings com for
Função range(start=0, stop, step)
"""
texto = 'Python'
for letra in texto:
print(letra)
for n in range(0, 100, 8): # Acha os múltiplos de 8
print(n)
# continue - pula para o próximo laço.
# brake - termina o laço.
|
# https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix
# O(n + m) time | O(1) space
# where 'n' is the length of row and 'm' is the length on column
def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col]... |
def get_variables():
return {
'SPECIAL_FUNC': {'hoge': 'fuga'}
}
|
n=int(input())
numSwaps=0
a=list(map(int, input().strip().split()))
for i in range(n-1):
for j in range(n-i-1):
if (a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
numSwaps+=1
print(f"Array is Sorted in {numSwaps} swaps")
print(f"First Element: {a[j]}")
print(f"Last Element: {a[j... |
"""
https://leetcode.com/problems/roman-to-integer/
"""
def roman_to_integer(s):
"""
This implementation passed all tests on submission January 18, 2022.
There's not too much any other way of implementing this, am I right? You
really just have encode each of the rules that are stated.
"""
o ... |
# Has the same id
a = [1, 2, 3]
c = a
print(id(a), id(c))
# Has a different id
b = 42
print(id(b))
b = '42'
print(id(b))
|
class Score:
def __init__(self, name, loader):
self.name = name
self.metrics = ['F', 'M']
self.highers = [1, 0]
self.scores = [0. if higher else 1. for higher in self.highers]
self.best = self.scores
self.best_epoch = [0] * len(self.scores)
self.present = self... |
mysql = {
'user': 'scott',
'password': 'password',
'host': '127.0.0.1',
'database': 'employees',
'raise_on_warnings': True,
}
|
# Author: allannozomu
# Runtime: 544 ms
# Memory: 19.8 MB
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if (A[0] < A[-1]):
ordered = sorted(A)
else:
ordered = sorted(A, reverse = True)
return ordered == A
|
def szyfr(slowa):
wynik = []
for slowo in slowa:
wynik.append(slimak(slowo))
return wynik
def slimak(slowo):
ukl = [[" " for _ in range(len(slowo))] for _ in range(len(slowo))]
kon = [1,2,2,2] + [j for j in range(3, 20)] + [j for j in range(3, 20)]
kon.sort()
pivot = int(len(slowo) ... |
class Vessel:
def __init__(self, name: str):
"""
Initializing class instance with vessel name
:param name:
"""
self.name = name
self.fuel = 0.0
# list of dicts with passenger attributes
self.passengers = []
def __getattr__(self, item):
""... |
class Error(Exception):
pass
class InvalidTypeError(Error):
pass
class InvalidArgumentError(Error):
pass
|
# 重み付きUnion-Find
class WeightedUnionFind:
def __init__(self, n: int) -> None:
self.n = n
self.par = list(range(n))
self.rank = [0] * n
self.weight = [0] * n
def find(self, x: int) -> int:
if self.par[x] == x:
return x
else:
y = self.find(self.par[x])
self.weight[x] += self.weight[self.par[x]]
... |
# -*- coding: utf-8 -*-
"""
Created on May 4 - 2019
---Based on the 2-stage stochastic program structure
---Assumption: RHS is random
---read stoc file (.sto)
---save the distributoin of the random variables and return the
---random variables
@author: Siavash Tabrizian - stabrizian@smu.edu
"""
class readstoc:
d... |
#********************************************************************
# Filename: FibonacciSearch.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the fibonacci search algorithm.
#*******************************************************... |
class HostAssignedStorageVolumes(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_assigned_volumes(idx_name)
class HostAssignedStorageVolumesColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts()
|
class Input:
"""
Input prototype
"""
def __init__(self, mod_opts=None):
self.name = ""
self.pretty_name = ""
self.help = ""
self.image_large = ""
self.image_small = ""
self.opts = mod_opts
if mod_opts:
if 'name' in mod_opts:
... |
def checkBingo(c):
for x in range(5):
if c[(x * 5) + 0] == c[(x * 5) + 1] == c[(x * 5) + 2] == c[(x * 5) + 3] == c[(x * 5) + 4] == True:
return True
if c[x + 0] == c[x + 5] == c[x + 10] == c[x + 15] == c[x + 20] == True:
return True
return False
def part2(path):
p_in... |
# 207-course-schedule.py
#
# Copyright (C) 2019 Sang-Kil Park <likejazz@gmail.com>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) ->... |
def main():
n = int(input("Enter a number: "))
for i in range(3, n + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime: print(f"{i} ", end="")
print()
if __name__ == '__main__':
main()
|
class Registry(object):
def __init__(self, name):
super(Registry, self).__init__()
self._name = name
self._module_dict = dict()
@property
def name(self):
return self._name
@property
def module_dict(self):
return self._module_dict
def __len__(self):
return len(self.module_dict)
def get(self, ke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.