content stringlengths 7 1.05M |
|---|
"""
Date: Jan 13 2022
Last Revision: N/A
General Notes:
- 2249ms runtime (10.57%) and 59MB (65.71%)
- Not a bad first attempt. I wonder if I could think of something that doesn't require sorting
- However, hard to think of a solution that is better than O(n) while mine is O(n*logn)... so is it worth considering the si... |
class doggy(object):
def __init__(self, name, age, color):
self.name = name
self.age = age
self.color = color
def myNameIs(self):
print ('%s, %s, %s' % (self.name, self.age, self.color))
def bark(self):
print ("Wang Wang !!")
wangcai = doggy("Wangcai Masa... |
# DFLOW LIBRARY:
# dflow utilities module
# with new range function
# and dictenumerate
def range(_from, _to, step=1):
out = []
aux = _from
while aux < _to:
out.append(aux)
aux += step
return out
def dictenumerate(d):
return {k: v for v, k in enumerate(d)}
def prod(x):
res = ... |
class TFException(Exception):
pass
class TFAPIUnavailable(Exception):
pass
class TFLogParsingException(Exception):
def __init__(self, type):
self.type = type |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubtree(self, s, t, match=False):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
#... |
"""
Some models such as
A model with high precision
"""
class Model_Regression():
def __init__(self):
self.name = 'a_good_model'
def predict(self,x):
y = x*2
return y
if __name__ == '__main__':
model = Model_Regression()
print(model.predict(1)) |
print("Hello Aline and Basti!")
print("What's up?")
# We need escaping: \" cancels its meaning.
print("Are you \"Monty\"?")
# Alternatively you can use ':
print('Are you "Monty"?')
# But you will need escaping for the last:
print("Can't you just pretend you were \"Monty\"?")
# or
print('Can\'t you just pretend you w... |
"""
Codemonk link: https://www.hackerearth.com/problem/algorithm/max-num-6fbf414b/
You are given an array A of n elements A1, A2, ..., An. Let us define a function F(x) = ΣAi&x. Here, & represents
bitwise AND operator. You are required to find the number of different values of x for which F(x) is maximized. There
... |
class Action:
"""A thing that is done.
The responsibility of action is to do something that is important in the game. Thus, it has one
method, execute(), which should be overridden by derived classes.
"""
def execute(self, cast, script, callback):
"""Executes something that is importan... |
"""
The core Becca code
This package contains all the learning algorithms and heuristics
implemented together in a functional learning agent. Most users
won't need to modify anything in this package. Only core developers,
those who want to experiment with and improve the underlying
learning algorithms and their implem... |
# Decision de inversiòn se encuentra las siguientes variables involucradas variable
# A que tiene 10,000
# B es menor de 30
# C Tiene educacion de nivel universitario
# D tiene inreso anual de almenos 40,000
# E Debe invertir en valores
# F Debe invertir en acciones de crecimiento
# G invertir en acciones de IBM
# Cada... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 1 10:42:25 2017
@author: wuyiming
"""
SR = 16000
H = 512
FFT_SIZE = 1024
BATCH_SIZE = 64
PATCH_LENGTH = 128
PATH_FFT = "/media/wuyiming/TOSHIBA EXT/UNetFFT/"
|
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.rows, self.cols = len(board), len(board[0])
for row in range(self.rows):
for col in range(self.cols):
liveNeighborsNum = self.calcLiveNeighborsNum... |
#
# PySNMP MIB module MIB-INTEL-IP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MIB-INTEL-IP
# Produced by pysmi-0.3.4 at Wed May 1 14:12:01 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,... |
#!/usr/bin/env python
while True:
pass
|
"""Mock turtle module.
"""
def goto(x, y):
pass
def up():
pass
def down():
pass
def color(name):
pass
def begin_fill():
pass
def end_fill():
pass
def forward(steps):
pass
def left(degrees):
pass
|
'''
Get various integer numbers. In the end, show the average between all values and the lowest and the highest.
Asks the user if they want to continue or not.
'''
number = int(input('Choose a number: '))
again = input('Do you want to continue? [S/N]').strip().upper()
total = 1
minimum = maximum = number
while... |
# -*- coding:utf-8 -*-
"""
"""
class Delegate:
daily_forge = 0.
gift = property(
lambda obj: obj.share*obj.daily_forge/(obj.vote+obj.cumul-obj.exclude),
None, None,
""
)
@staticmethod
def configure(blocktime=8, delegates=51, reward=2):
assert isinstance(blocktime, int)
assert isinstance(delegates, i... |
print(3 * 3 == 6)
print(50 % 5 == 0)
Name = "Sam"
print(Name == "SaM")
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
for fruit in fruits:
if fruit == "apple":
print("Apple is present")
elif "cherry" in fruit:
print("Cherry is also present") |
#!/usr/bin/python3
'''
helloworld.py
Simple Hello world program. This is considered to be the
first program that anyone would write when learing a new language.
Author: Rich Lynch
Created for merit badge college.
Released to the public under the MIT license.
'''
print ("Hello Wo... |
lista = []
for c in range(0, 5):
lista.append(int(input(f'Digite um valor para a posição {c}: ')))
print('+_' * 25)
print('Você digitou os valores: ', * lista, sep=',')
# print(f'O maior valor digitado foi {max(lista)} na posição {lista.index(max(lista))}')
# print(f'O menor valor digitado foi {min(lista)} na posi... |
# -*- coding: utf-8 -*-
'''
Configuration of Capsul and external software operated through capsul.
'''
|
version = "0.9.8"
_default_base_dir = "./archive"
class Options:
"""Holds Archiver options."""
def __init__(self, base_dir, use_ssl=False, silent=False, verbose=False, delay=2, thread_check_delay=90, dl_threads_per_site=5, dl_thread_wait=1, skip_thumbs=False, thumbs_only=False, skip_js=False, skip_css=False, follow_c... |
class StepsLoss:
def __init__(self, loss):
self.steps = None
self.loss = loss
def set_steps(self, steps):
self.steps = steps
def __call__(self, y_pred, y_true):
if self.steps is not None:
y_pred = y_pred[:, :, : self.steps]
y_true = y_true[:, :, : se... |
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
# O(n) time | O(n) space
lst = []
startRow, endRow = 0, len(matrix) - 1
startColumn, endColumn = 0, len(matrix[0]) - 1
place = (0, 0)
while startRow <= endRow and startColumn <= endColumn:
... |
"""
https://www.practicepython.org
Exercise 13: Fibonacci
2 chilis
Write a program that asks the user how many Fibonnaci numbers to generate
and then generates them. Take this opportunity to think about how you can
use functions. Make sure to ask the user to enter the number of numbers in
the sequence to generate.(Hi... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 14:15:56 2018
@author: Chris
"""
path = r'C:\Users\Chris\Desktop\Machine Learning Raw Data\air-quality-madrid\stations.csv'
stations = pd.read_csv(path)
stations.head()
geometry = [Point(xy) for xy in zip(stations['lon'], stations['lat'])]
crs = {'init': 'epsg:4326'}... |
def encode(keyword, message, normalize=False):
# True - отбрасывать пробелы при шифровании
if normalize:
message = ''.join(message.split())
rows = len(message) // len(keyword)
if len(message) % len(keyword) != 0:
rows += 1
indexes = sorted([(index, value) for index, value in enumer... |
# network image size
IMAGE_WIDTH = 128
IMAGE_HEIGHT = 64
# license number construction
DOWNSAMPLE_FACTOR = 2 ** 2 # <= pool size ** number of pool layers
MAX_TEXT_LEN = 10
|
#!/usr/bin/python
def readFile(fileName):
paramsFile = open(fileName)
paramFileLines = paramsFile.readlines()
return paramFileLines
#number of expected molecular lines
def getExpectedLineNum(fileName):
lines = readFile(fileName)
print(lines[0])
return lines[0]
#frequency ranges of all expected... |
#!/usr/bin/env python3
# https://abc051.contest.atcoder.jp/tasks/abc051_d
INF = 10 ** 9
n, m = map(int, input().split())
a = [[INF] * n for _ in range(n)]
e = [None] * m
for i in range(n): a[i][i] = 0
for i in range(m):
u, v, w = map(int, input().split())
u -= 1
v -= 1
e[i] = (u, v, w)
a[u][v] = w
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class ListNode:
def __init__(self, x, n):
self.val = x
self.next = n
class Solution:
def mergeTwoLists(self, l1, l2):
pre = tmp = None
cur = l1
... |
# -*- coding: utf-8 -*-
data_dublin_core = {'msg': 'Retrieved 22 abstracts, starting with number 1.', 'export': '<?xml version=\'1.0\' encoding=\'utf8\'?>\n<records xmlns="http://ads.harvard.edu/schema/abs/1.1/dc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dc="http://purl.org/dc/elements/1.1/" xsi:sch... |
class AsupDestination(basestring):
"""
smtp|http|noteto|retransmit
Possible values:
<ul>
<li> "smtp" ,
<li> "http" ,
<li> "noteto" ,
<li> "retransmit"
</ul>
"""
@staticmethod
def get_api_name():
return "asup-destination"
|
numero = float(input('Informe um número e descubra se é inteiro ou decimal: '))
if round(numero) == numero:
print(f'O número {round(numero)} é inteiro')
else:
print(f'O número {numero} é decimal') |
def parseRaspFile(filepath):
headerpassed = False
data = {
'motor name':None,
'motor diameter':None,
'motor length':None,
'motor delay': None,
'propellant weight': None,
'total weight': None,
'manufacturer': None,
'thrust data': {'time':[],'thrust... |
"""
Author: Kagaya john
Tutorial 9 : Dictionaries
"""
"""
Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly brackets, and they have keys and values.
Example
Using the len() method to return the number of items:"""... |
"""Guarde en lista `naturales` los primeros 100 números naturales (desde el 1)
usando el bucle while
"""
n=1
naturales=[]
while n<=100 :
naturales.append(n)
n+=1
"""Guarde en `acumulado` una lista con el siguiente patrón:
['1','1 2','1 2 3','1 2 3 4','1 2 3 4 5',...,'...47 48 49 50']
Hasta el número 50.
"""
ra... |
class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
ones = []
twos = []
ans = 0
for num in nums:
ans += num
if num % 3 == 1:
ones.append(num)
elif num % 3 == 2:
twos.append(num)
if ans % 3 == 0:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Problem 031
The Minion Game
Source : https://www.hackerrank.com/challenges/the-minion-game/problem
"""
def is_vowel(c):
return c in ("A","E","I","O","U")
def minion_game(word):
p1, p2 = 0, 0
nb = len(word)
for i in range(nb):
if is_vowel(word... |
def evaluate_shard(out_csv_name, pw_ji, labels_x, labels_y, d = 0.00, d_step = 0.005, d_max=1.0):
h.save_to_csv(data_rows=[[
"Distance Threshhold",
"True Positives",
"False Positives",
"True Negative",
"False Negative",
"Num True Same",
"Num True Dif... |
def kaprekar_10(n):
divider = 10
while True:
left, right = divmod(n**2, divider)
if left == 0:
return False
if right != 0 and left + right == n:
return True
divider *= 10
def convert(num, to_base=10, from_base=10):
alpha = ... |
__query_all = {
# DO NOT CHANGE THE FIRST KEY VALUE, IT HAS TO BE FIRST.
'question_select_all_desc_by_date':
'SELECT id, submission_time, view_number, vote_number, title, message, image FROM question ORDER BY submission_time DESC',
'question_select_all_asc_by_date':
'SELECT id, submission_ti... |
class EmptyRainfallError(ValueError):
pass
class EmptyWaterlevelError(ValueError):
pass
class NoMethodError(ValueError):
pass |
"""
TOTAL BUTTON COUNT: 26 Buttons
GROUP NAMES: Enumerates each of the groups of buttons on controller.
BUTTON NAMES: Enumerates each of the names for each button on the controller.
GROUP SIZES: Dictionary containing the total number of buttons in each group.
BUTTON GROUPS: Dictionary where keys are group names an... |
# O(n^2) time | O(1) Space
# def twoNumberSum(array, targetSum):
# for i in range(len(array)):
# firstNum = array[i]
# for j in range(i+1, array[j]):
# secondNum = array[j]
# if firstNum + secondNum == targetSum:
# return [firstNum,secondNum]
# return []
... |
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
# create a hash table for 180 degree rotation mapping
helper = {'0':'0','1':'1','6':'9','8':'8','9':'6'}
# flip the given string
num2 = ''
n = len(num)
i = n - 1
while i >= 0:
... |
"""You're a wizard, Harry."""
def register(bot):
bot.listen(r'^magic ?(.*)$', magic, require_mention=True)
bot.listen(r'\bmystery\b|'
r"\bwhy (do(es)?n't .+ work|(is|are)n't .+ working)\b|"
r'\bhow do(es)? .+ work\b', mystery)
def _magic(thing):
return '(ノ゚ο゚)ノミ★゜・。。・゜゜・。{}... |
## floating point
class Number(Primitive):
def __init__(self, V, prec=4):
Primitive.__init__(self, float(V))
## precision: digits after decimal `.`
self.prec = prec
|
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 19:30:21 2018
@author: lenovo
"""
def Bsearch(A, key):
length = len(A)
if length == 0:
return -1
A.sort()
left = 0
right = length - 1
while left <= right:
mid = int((left + right) / 2)
if key == A[mid]:
retur... |
#media sources
dataurl_src = "'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQQAAAAAAAAA'"
throttler = "'../resources/range-request.php?rate=100000&fileloc=";
mp4_src = throttler + "preload.mp4&nocache=' + Math.random()";
ogg_src = throttler + "preload.ogv&nocache=' + Math.random()";
webm... |
class SecureList(object):
def __init__(self, lst):
self.lst = list(lst)
def __getitem__(self, item):
return self.lst.pop(item)
def __len__(self):
return len(self.lst)
def __repr__(self):
tmp, self.lst = self.lst, []
return repr(tmp)
def __str__(self):
... |
first_card = input().strip().upper()
second_card = input().strip().upper()
third_card = input().strip().upper()
total_point = 0
if first_card == 'A':
total_point += 1
elif first_card in 'JQK':
total_point += 10
else:
total_point += int(first_card)
if second_card == 'A':
total_point += 1
elif second... |
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class List:
def __init__(self):
self.head = None
self.tail = None
self.this = None
def add_to_tail(self, val):
new_node = Node(val)
if self.empty():
self... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
# GN version: //ui/events/keycodes:xkb
'target_name': 'keycodes_xkb',
... |
# from typing import Any
class SensorCache(object):
# instance = None
soil_moisture: float = 0
temperature: float = 0
humidity: float = 0
# def __init__(self):
# if SensorCache.instance:
# return
# self.soil_moisture: float = 0
# self.temperature: int = 0
#... |
# Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada o programa deverá perguntar se
# o usuário quer ou não continuar. No final mostre:
# A) Quantas pessoas tem mais de 18 anos.
# B) Quantos homens foram cadastrados.
# C) Quantas mulheres tem menos de 20 anos.
separador = ('─' * 40... |
#
# PySNMP MIB module NMS-ERPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NMS-ERPS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:22:01 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,... |
"""
1. The larger the time-step $\Delta t$ the more the estimate $p_1$ deviates
from the exact $p(t_1)$.
2. There is a linear relationship between $\Delta t$ and $e_1$: double the time-step double the error.
3. Make more shorter time-steps
""" |
#!/usr/bin/env python
cptlet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
listtl = '¢—-=@#$%^*'
last = 'BoB'
lastcheck = '.!?~\n'
with open('/Users/bob/ocr.txt', 'r') as f:
for i in f.readlines()[:-1]:
if i != '\n':
i = i[-1:]+i[:-2]+i[-2:-1].replace('-','')
if (i[1] not in cptlet or la... |
def quote_info(text):
return f"<blockquote class=info>{text}</blockquote>"
def quote_warning(text):
return f"<blockquote class=warning>{text}</blockquote>"
def quote_danger(text):
return f"<blockquote class=danger>{text}</blockquote>"
def code(text):
return f"<code>{text}</code>"
def html_link(l... |
#!/usr/bin/env python
# encoding: utf-8
class postag(object):
# ref: http://universaldependencies.org/u/pos/index.html
# Open class words
ADJ = "ADJ"
ADV = "ADV"
INTJ = "INTJ"
NOUN = "NOUN"
PROPN = "PROPN"
VERB = "VERB"
# Closed class words
ADP = "ADP"
AUX ="AUX"
CCON... |
print("-----------\nOmzetten van lengte-eenheden - Kilometers naar miles.\n")
while True:
print ("Geef de kilometers in die naar miles moeten omgezet.\nGebruik alleen getallen!")
km = str(input("Kilometers: "))
try:
km = float(km.replace(",", ".")) # replace comma with dot, if user entered a co... |
#!/usr/bin/env python3
"""
implementation of recursive hilbert enumeration
"""
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def up(point):
point.y += 1
def down(point):
point.y -= 1
def left(point):
point.x -= 1
def right(point):
point.x += 1
def hilber... |
class Pair(object):
def __init__(self, individual1, individual2):
self.ind1 = individual1
self.ind2 = individual2
|
class atom(object):
def __init__(self,atno,x,y,z):
self.atno = atno
self.position = (x,y,z)
# this is constructor
def symbol(self): # a class method
return atno__to__Symbol[atno]
def __repr__(self): # a class method
return '%d %10.4f %10.4f %10.4f%'
(... |
class Data:
def __init__(self, startingArray):
self.dict = {
"Category" : 0,
"Month" : 1,
"Day" : 2,
"RepeatType" : 3,
"Time" : 4,
}
self.list = ["Category","Month", "Day", "RepeatMonth", "Time"]
... |
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if not trust and n == 1:
return 1
Trust = defaultdict(list)
Trusted = defaultdict(list)
for a, b in trust:
Trust[a].append(b)
Trusted[b].append(a)
for i, t in Trust... |
HOST = "irc.twitch.tv"
PORT = 6667
NICK = "simpleaibot"
PASS = "oauth:tldegtq435nf1dgdps8ik9opfw9pin"
CHAN = "simpleaibot"
OWNER = ["sinstr_syko", "aloeblinka"]
|
N,K=map(int,input().split())
L=[1]*(N+1)
for j in range(2,N+1):
if L[j]: key=j
for i in range(key,N+1,key):
if L[i]:
L[i]=0
K-=1
if K==0:
print(i)
exit() |
"""lists"""
#import json
class Lists:
"""lists"""
def __init__(self, twitter):
self.twitter = twitter
def list(self, params):
"""Hello"""
pass
def members(self, params):
"""Hello"""
pass
def memberships(self, params):
"""Hello"""
pass
def ... |
def fact(n = 5):
if n < 2:
return 1
else:
return n * fact(n-1)
num = input("Enter a number to get its factorial: ")
if num == 'None' or num == '' or num == ' ':
print("Factorial of default value is: ",fact())
else:
print("Factorial of number is: ",fact(int(num)))
|
SUCCESS_GENERAL = 2000
SUCCESS_USER_REGISTERED = 2001
SUCCESS_USER_LOGGED_IN = 2002
ERROR_USER_ALREADY_REGISTERED = 4000
ERROR_USER_LOGIN = 4001
ERROR_LOGIN_FAILED_SYSTEM_ERROR = 4002 |
"""
Ludolph: Monitoring Jabber Bot
Version: 1.0.1
Homepage: https://github.com/erigones/Ludolph
Copyright (C) 2012-2017 Erigones, s. r. o.
See the LICENSE file for copying permission.
"""
__version__ = '1.0.1'
__author__ = 'Erigones, s. r. o.'
__copyright__ = 'Copyright 2012-2017, Erigones, s. r. o.'
|
#
# PySNMP MIB module AVICI-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AVICI-SMI
# Produced by pysmi-0.3.4 at Wed May 1 11:32:28 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... |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
{
"uidPageJourney": {
W3Const.w3PropType: W3Const.w3TypePanel,
W3Const.w3PropSubUI: [
"uidJourneyTab"
]
},
"uidJourneyTab": {
W3Const.w3PropType: W3Const.w3TypeTab,
W3Const.w3PropSubUI: [
["uidJourneyTabJourneyLabel", "uidJourneyTabJourneyPanel... |
def custom_send(socket):
socket.send("message from mod.myfunc()")
def custom_recv(socket):
socket.recv()
def custom_measure(q):
return q.measure()
|
#This one is straight out the standard library.
def _default_mime_types():
types_map = {
'.cdf' : 'application/x-cdf',
'.cdf' : 'application/x-netcdf',
'.xls' : 'application/excel',
'.xls' : 'application/vnd.ms-excel',
}
|
s = input()
ret = 0
for i in range(len(s)//2):
if s[i] != s[-(i+1)]:
ret += 1
print(ret)
|
SBOX = (
(0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76),
(0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0),
(0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15),
(... |
my_list = ['в', '5', 'часов', '17', 'минут',
'температура', 'воздуха',
'была', '+5', 'градусов']
idx = 0
while idx < len(my_list):
if my_list[idx].isdigit():
my_list.insert(idx, '"')
my_list[idx + 1] = f'{int(my_list[idx + 1]):02}'
my_list.insert(idx + 2, '"')
i... |
poem = '''There was a young lady named Bright,
Whose speed was far faster than light;
She started one day In a relative way, And
returned on the previous night.'''
print(poem)
try:
fout = open('relativety', 'xt')
fout.write(poem)
fout.close()
except FileExistsError:
print('relativety already exists! ... |
try:
with open("input.txt", "r") as fileContent:
timers = [int(number) for number in fileContent.readline().split(",")]
frequencies = [0] * 9
for timer in timers:
frequencies[timer] = timers.count(timer)
except FileNotFoundError:
print("[!] The input file was not found. The p... |
ADMINS = (
('Admin', 'admin@tvoy_style.com'),
)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'dezigner20@gmail.com'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'dezigner20@gmail.com'
EMAIL_HOST_PASSWORD = 'SSDD24869317SSDD**'
SERVER_EMAIL = DEFAULT_FR... |
class Solution:
# @param {integer[]} nums
# @return {integer[]}
def productExceptSelf(self, nums):
before = []
after = []
product = 1
for num in nums:
before.append(product)
product = product * num
product = 1
for num in reversed(nums):... |
def f(a):
global n
if n == 0 and a == 0:
return True
if n == a%10:
return True
if n == a//10:
return True
H1,M1=list(map(int,input().split()))
H2,M2=list(map(int,input().split()))
n=int(input())
S=0
while H1 != H2 or M1 != M2:
if f(H1) or f(M1):
S+=1
... |
def add(x, y):
""" Add two number """
return x+y
def subtract(x,y):
return abs(x-y)
|
LOCATION_REPLACE = {
'USA': 'United States',
'KSA': 'Kingdom of Saudi Arabia',
'CA': 'Canada',
}
|
def count(index):
print(index)
if index < 2:
count(index + 1)
count(0)
|
class Chessboard:
square_not_allowed = ["A1", "C1", "E1", "G1",
"B2", "D2", "F2", "H2",
"A3", "C3", "E3", "G3",
"B4", "D4", "F4", "H4",
"A5", "C5", "E5", "G5",
"B6", "D6", "F6", "H6",... |
# Refaça o exercicio 9, mostrando a tabuada de um número que o usuário escolher, só que agora
# utilizando o laço for.
num = int(input('Digite um número: '))
for n in range(1, 11):
print(f'{num} x {n} = {num * n}')
|
sum = 0
for i in range(1,101):
if i%2==0:
sum+=i
print(i,end=' ')
else :
continue
print(f'\n1~100 사이의 짝수의 총합: {sum}') |
def elbow_method(data, clusterer, max_k):
"""Elbow method function.
Takes dataset, "Reason" clusterer class and returns the optimum number of
clusters in range of 1 to max_k.
Args:
data (pandas.DataFrame or list of dict): Data to cluster.
clusterer (class): "Reason" clusterer.
... |
def main():
def square(n):
return n * n
if __name__ == '__main__':
main()
|
class Response:
def __init__(self, content, private=False, file=False):
self.content = content
self.private = private
self.file = file |
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
if weight1 <= maxW and (weight2 > maxW or value1 >= value2):
return value1
if weight2 <= maxW and (weight1 > maxW or value2 >= value1):
return value2
return 0
|
#
# PySNMP MIB module A3COM0074-SMA-VLAN-SUPPORT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM0074-SMA-VLAN-SUPPORT
# Produced by pysmi-0.3.4 at Wed May 1 11:09:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
def countConstruct(target, word_bank, memo = None):
'''
input: target- String
word_bank- array of Strings
output: number of ways that the target can be constructed by
concatenating elements fo the word_bank array.
'''
if memo is None:
memo = {}
if target in memo:
return memo[target]
if target ==... |
# scenario of runs for MC covering 2012 with three eras, as proposed by ECAL/H2g for 2013 re-digi campaign
# for reference see: https://indico.cern.ch/conferenceDisplay.py?confId=243497
runProbabilityDistribution=[(194533,5.3),(200519,7.0),(206859,7.3)]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.