content stringlengths 7 1.05M |
|---|
"""
Common functions for protocols.
Protocols define, how the communication with a backend service works. They
usually come with a FactoryFromService class, that adapts the backend service
interface, and implements a factory interface.
"""
|
def generate_state(state, desired_len):
while len(state) < desired_len:
b = "".join(str((int(s) + 1) % 2) for s in reversed(state))
state = state + "0" + b
return state[:desired_len]
def checksum(state):
res = []
f = True
while f or len(state) % 2 == 0:
f = False
r... |
SCHEDULE_NONE = None
SCHEDULE_HOURLY = '0 * * * *'
SCHEDULE_DAILY = '0 0 * * *'
SCHEDULE_WEEKLY = '0 0 * * 0'
SCHEDULE_MONTHLY = '0 0 1 * *'
SCHEDULE_YEARLY = '0 0 1 1 *'
|
l = [*map(int, input().split())]
r = 0
for i in l:
if i > 0:
r += 1
print(r)
|
class Carbure:
SUCCESS = "success"
ERROR = "error"
class CarbureError:
INVALID_REGISTRATION_FORM = "Invalid registration form"
INVALID_LOGIN_CREDENTIALS = "Invalid login or password"
ACCOUNT_NOT_ACTIVATED = "Account not activated"
OTP_EXPIRED_CODE = "OTP Code Expired"
OTP_INVALID_CODE = "OT... |
### Score - Linux
P1_Wins = 0
CPU_Wins = 0
Game_Draws = 0
|
# Merge Sort
'''
Divide and Conquer Algorithm
-> Divide: Divide equally until one element: each individual element is sorted
-> Conquer: Combine elements by comparing
'''
# Conquer
def merge(arr,low,mid,high):
# Create two arrays for two halves
n1 = mid - low + 1;
n2 = high - mid;
# Declaring empty arr... |
class Solution:
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
# iterative
visited = [0] * (len(s) + 1)
stack = [0]
while stack:
cur = stack.pop()
print(cur)
if... |
casa = float(input('Qual é o Valor do imóvel desejado? R$ '))
salário = float(input('Qual é seu Salário Mensal? R$'))
anos = int(input('Em quantos anos de financiamento? '))
prestação = casa / (anos * 12)
mínimo = salário * 30 / 100
print('Para pagar uma casa de R${:.2f} em {} anos'.format(casa, anos), end='')
print(' ... |
DEFAULT_EQUIPMENT = [
("Dumbbells","Generic dumbbells."),
("Barbell","Generic barbell with plate weights."),
("Squat Rack","Generic squat rack."),
("Leg Curl Machine","Generic machine to do leg curls on."),
("Leg Extension Machine","Generic machine to do leg extensions on."),
("Pull up bar","Generic horizontal bar to ... |
'''Crie um programa que leia o nome completo de uma pessoa e mostre:
A) O nome com todas as letras maiúsculas.
B) O nome com todas as letras minúsculas.
C) Quantas letras ao todo (sem considerar espaços).
D) Quantas letras tem o primeiro nome.'''
nome = str(input('Informe o seu nome completo: ')).strip()
print('O seu ... |
ranks = [
"siviilipalvelusmies",
"alokas",
"sotamies",
"aliupseerioppilas",
"korpraali",
"ylimatruusi",
"alikersantti",
"upseerioppilas",
"kersantti",
"upseerikokelas",
"ylikersantti",
"vääpeli",
"pursimies",
"ylivääpeli",
"sotilasmestari",
"vänrikki",
... |
d = {2:0, 3:0, 4:0, 5:0}
input()
v = [int(x) for x in input().split()]
for i in v:
if i % 2 == 0: d[2] += 1
if i % 3 == 0: d[3] += 1
if i % 4 == 0: d[4] += 1
if i % 5 == 0: d[5] += 1
print(d[2], 'Multiplo(s) de 2')
print(d[3], 'Multiplo(s) de 3')
print(d[4], 'Multiplo(s) de 4')
print(d[5], 'Multiplo(s) ... |
# Single line Comment
""" Multi line Comment 1
Multi line Comment 2 """
print("Hello")
print("Hello World")
# By default end is new line charcter \n
print("Hello", end=' & ')
print("Hello World")
print("Hello","Hello World", end=' ')
print('Bye')
print('Harry is \ngood boy ! Yes\t!') # \t for tab (6 spaces) , \' ... |
# Caio Beraldi Ribeiro
class Table:
def __init__(self, maxSize, decision):
self.maxSize = maxSize - 1
self.key = [0] * (maxSize)
self.value = [None] * (maxSize)
self.size = -1
self.auxI = 0
self.decision = decision
def __repr__(self):
string = ... |
#Nathan Li - 3/11/2021 - P7: 10,001st Prime
primeNums = [2, 3, 5]
index = 6
#The simplest primality test is trial division: given an input number, n, check whether
#it is evenly divisible between 2 and √n
while len(primeNums) < 10001:
for prime in primeNums:
if index % prime == 0:
index += 1
... |
"""
Space : O(1)
Time : O(n)
"""
class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
def update(self, i: int, val: int) -> None:
self.nums[i] = val
def sumRange(self, i: int, j: int) -> int:
return sum(self.nums[i:j+1])
# Your NumArray object will be ins... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Children, obj[8]: Education, obj[9]: Occupation, obj[10]: Income, obj[11]: Bar, obj[12]: Coffeehouse, obj[13]: Restaurant20to50, obj[14]: Direction_same, obj[15]: Dista... |
def test_limits(client):
"""Make sure that requesting resources with limits return a slice of the result."""
for i in range(100):
badge = client.post("/api/event/1/badge", json={
"legal_name": "Test User {}".format(i)
}).json
assert(badge['legal_name'] == "Test User {}"... |
# cook your dish here
try:
n = int(input())
print(n)
except:
pass
|
acum = menor = cont = cont1 = 0
barato = ''
while True:
produto = str(input('Nome do produto:')).strip()
preço = float(input('Preço do produto:R$ '))
cont+= 1
if cont == 1 or preço < menor:
menor = preço
barato = produto
acum += preço
if preço > 1000:
cont1 += 1
esco... |
a, b = map(int, input().split())
if a+b < 24:
print(a+b)
else:
print((a+b)-24)
|
class Dog:
"""A simple attempt to model a dog"""
def __init__(self, name, age):
"""Initialize name and age attributes"""
self.name=name
self.age=age
def sit(self):
"""Simulate a dog sitting in response to a command"""
print(f"{self.name} is now sitting")
def roll_over(self):
"""Simulate rolling over ... |
listao = [[], []]
for c in range(0, 7):
v = (int(input(f'Digite o {c+1}° valor: ')))
if v % 2 == 0:
listao[0].append(v)
else:
listao[1].append(v)
listao[0].sort()
listao[1].sort()
print('='*50)
print(f'Os valores pares digitados foram: {listao[0]}')
print(f'Os valores ímpares digitados foram... |
#
# PySNMP MIB module POLICY-DEVICE-AUX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/POLICY-DEVICE-AUX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:41:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
#Ask user to input 3 numbers - width, length, height
width = input("Enter the width of the room in meters, please:\n")
length = input("Enter the length of the room in meters, please:\n")
height = input("Enter the height of the room in meters, please:\n")
#Find the volume of the room
#PS Think about units and what is t... |
{
'targets': [
{
'target_name': 'binding',
'sources': [ './src/fb-bindings.cc', './src/fb-bindings-blob.cc',
'./src/fb-bindings-fbresult.cc',
'./src/fb-bindings-connection.cc','./src/fb-bindings-eventblock.cc',
'./src/fb-bindings-fbeventemitter.... |
# Still waiting on what Neutral should be!
ALIGNMENT_CHOICES = (
(0, 'Neutral'),
(-1000, 'Evil'),
(1000, 'Good'),
)
SEX_CHOICES = (
(0, 'None'),
(1, 'Male'),
(2, 'Female'),
)
WEAPON_TYPE_CHOICES = (
('B', 'Blunt'),
('S', 'Sharp'),
)
DIRECTION_CHOICES = (
(0, 'North'),
... |
# -*- coding: UTF-8 -*-
labels = {
0 : '苹果',
1 : '香蕉',
2 : '橙子',
3 : '火龙果',
4 : '圣女果',
5 : '梨子',
6 : '空盘'
}
prices = {
0 : 4.2,
1 : 8.9,
2 : 10.2,
3 : 3.9,
4 : 8.77,
5 : 8.6,
6 : 0
} |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 09:23:08 2018
@author: misskeisha
"""
s = input()
def palindrome(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and palindrome(s[1:-1])
print(palindrome(s)) |
# break
# for i in range(1, 10):
# print(i)
# if i == 3:
# break
# continue
for i in range(1, 10):
if i == 4 or i == 7:
continue
print(i)
|
#Cambio , remplazo de cadena de Letras
print("=================================================================")
archivo_texto = open("archivo.txt","r+") # Archivo de Lectura y escritura
lista_texto=archivo_texto.readlines()
lista_texto[1]= " Estas linea ha sido incluioda desde el exterior 2 \n"
archivo_texto.seek(0... |
# 07/01/2019
def upc(n):
digits = [int(x) for x in f'{n:011}']
M = (sum(digits[0::2]) * 3 + sum(digits[1::2])) % 10
return 0 if M == 0 else 10 - M
assert upc(4210000526) == 4
assert upc(3600029145) == 2
assert upc(12345678910) == 4
assert upc(1234567) == 0
|
# -*- coding: utf-8 -*-
#
# dependencies documentation build configuration file, created by Quark
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon'
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'dependencies'
copyright = u'2015, dependencies authors'
author = ... |
while True:
try:
number = input('Please input hex number: ')
print(int(number, 16))
except:
break;
|
print('-'* 23)
print('\033[:31mCALCULADOR DE DESCONTOS\033[m')
print('-'* 23)
p = float(input('Valor do produto: '))
desc = (p / 100) * 95 # -> p - (p * 5 / 100)
print(f'O produto que custava {p:.2f} com desconto de 5% sae por: {desc:.2f}'.replace('.', ',')) |
limak, bob = map(int, input().split())
years = 0
while limak <= bob:
limak *= 3
bob *= 2
years += 1
print(years) |
##Find the nth term of the series.
##
##1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243,64, 729, 128, 2187 ….
##
##This series is a mixture of 2 series – all the odd terms in this series form
##a geometric series and all the even terms form yet another geometric series.
##Write a program to find the Nth term in the seri... |
"""Top-level package for ascii-art."""
__author__ = """Zero to Mastery"""
__version__ = '0.1.0'
|
#Settings for running headless_tests
DEVELOPMENT_SERVER_HOST='localhost'
DEVELOPMENT_SERVER_PORT=8004
PHANTOMJS_GHOSTDRIVER_PORT=8150
|
# -*- coding: utf-8 -*-
MINIMUM_PULSE_CYCLE = 0.5
MAXIMUM_PULSE_CYCLE = 1.2
PPG_SAMPLE_RATE = 200
PPG_FIR_FILTER_TAP_NUM = 200
PPG_FILTER_CUTOFF = [0.5, 5.0]
PPG_SYSTOLIC_PEAK_DETECTION_THRESHOLD_COEFFICIENT = 0.5
TRAINING_DATA_RATIO = 0.75 |
# Turns on debugging features in Flask
DEBUG = True
# secret key:
SECRET_KEY = "MySuperSecretKey"
# Database connection parameters
DB_HOST = "127.0.0.1"
DB_PORT = 27017
DB_NAME = "cgbeacon2-test"
DB_URI = f"mongodb://{DB_HOST}:{DB_PORT}/{DB_NAME}" # standalone MongoDB instance
# DB_URI = "mongodb://localhost:27011,l... |
string_input = input()
num = int(input())
# def string(str, n):
# new_string = ""
# for i in range(0, n):
# new_string += str
# return new_string
# def string(str, n):
# return str*n
# Recursion
def string(str, n):
if n < 1:
return ""
return str + string(str, n=n - 1)
prin... |
def add_node(v):
if v in graph:
print(v,"already present")
else:
graph[v]=[]
def add_edge(v1,v2):
if v1 not in graph:
print(v1," not present in graph")
elif v2 not in graph:
print(v2,"not present in graph")
else:
graph[v1].append(v2)
graph[v2].append(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Prince Prigio
chart = ["accept", "allow", "apologise", "appeal", "appear", "approve", "await", "bear", "beat", "behave", "behold", "better", "brawl", "breed", "build", "christen", "claim", "complain", "correct", "count", "cover", "creep", "curl", "decline", "deserve", "de... |
# -*- coding: utf-8 -*-
class Graph():
def __init__(self, v):
self.__adj = [[] for i in range(v)]
self.__pilha = []
self.__paths = []
self.__visit = [-1 for i in range(v)]
def __str__(self):
count = 0
stringR = "LISTA DE ADJACÊNCIA\n"
for v in self.__ad... |
#! python
# Problem # : 236A
# Created on : 2019-01-14 23:41:28
def Main():
cnt = len(set(input()))
print('IGNORE HIM!' if cnt & 1 else 'CHAT WITH HER!')
if __name__ == '__main__':
Main()
|
anjoValue = "o Gilberto e o Fiuk"
liderValue = "o Caio"
monstroArray = ["Caio", "Rodolffo"]
paredaoArray = ["Arthur", "Fiuk", "Thaís"]
elenco = [
['o Arthur', 'https://uploads.metropoles.com/wp-content/uploads/2021/03/02145955/arthur_bbb21-600x400.jpg'],
['a Karol Conká', 'https://files.nsctotal.com.br/s3fs... |
class Node:
def __init__(self, index):
self.index = index
self.visited = False
self._neighbors = []
def __repr__(self):
return str(self.index)
@property
def neighbors(self):
return self._neighbors
@neighbors.setter
def neighbors(self, neighbor):... |
"""
dummy tests
"""
#============================ helpers =========================================
#============================ tests ===========================================
def test_dummy():
pass
|
# https://leetcode.com/problems/maximum-product-difference-between-two-pairs
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums = sorted(nums)
return (nums[-1] * nums[-2]) - (nums[0] * nums[1])
|
"""
Contains functions implementing the Levenshtein distance algorithm.
"""
def relative(a, b):
"""Returns the relative distance between two strings, in the range
[0-1] where 1 means total equality.
"""
d = distance(a,b)
longer = float(max((len(a), len(b))))
shorter = float(min((len(a... |
# Space: O(n)
# Time: O(n)
class Solution:
def plusOne(self, digits):
temp = ''.join(map(lambda x: str(x), digits))
temp = int(temp) + 1
temp = list(str(temp))
return list(map(lambda x: int(x), temp))
|
#Explain your work
#Question 1
for x in range(a):
print(a) |
#!/usr/bin/python3
words = """art
hue
ink
oil
pen
wax
clay
draw
film
form
kiln
line
tone
tube
wood
batik
brush
carve
chalk
color
craft
easel
erase
frame
gesso
glass
glaze
image
latex
liner
media
mixed
model
mural
paint
paper
photo
print
quill
quilt
ruler
scale
shade
stone
style
tools
video
wheel
artist
bridge
canvas
ch... |
__version__ = "0.3.9"
__author__ = "Guinsly Mondésir"
sp_ask_school_dict = [
{
"school": {
"id": 1,
"queues": [
"toronto",
"toronto-mississauga",
"toronto-scarborough",
"toronto-st-george",
"toronto-st-g... |
# Licensed under an MIT open source license - see LICENSE
def generate_saa_list(scouseobject):
"""
Returns a list constaining all spectral averaging areas.
Parameters
----------
scouseobject : Instance of the scousepy class
"""
saa_list=[]
for i in range(len(scouseobject.wsaa)):
... |
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n = len(nums)
tmp = [0]*n
dup = 0
# 先进行桶排序
for i in range(n):
ind = nums[i]-1
value = nums[i]
if tmp[ind] != 0:
dup = value
else:
... |
class Sentence:
def __init__(self):
self._tokens = []
self._metadata = []
def append_metadata(self, data):
self._metadata.append(data)
def append_token(self, token):
self._tokens.append(token)
def __bool__(self):
return len(self._tokens) > 0
def __len__(se... |
class AppSettings:
allow_extra_fields = True
types = {
# Slack
'domain': str,
# come on, Okta, be consistent...
# T-Sheets
'subDomain': str,
# Engagedly
'acsUrl': str, # ACS URL
'audRestriction': str, # Entity ID
# JIRA
'baseURL... |
N, K = map(int, input().split())
S = list(input())
Y = 0
if N == 1:
print(0)
exit(0)
if S[0] == 'L':
Y += 1
if S[N-1] == 'R':
Y += 1
count = 0
X = 0
for i in range(N-1):
if S[i] == 'R' and S[i+1] == 'L':
X += 1
if S[i] == S[i+1]:
count += 1
count += K*2
print(min(N-1, count))
... |
#
# PySNMP MIB module CTRON-ROUTERS-INTERNAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-ROUTERS-INTERNAL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:15:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
# -*- coding: utf-8 -*-
class Solution:
def distributeCandies(self, candies):
return min(len(candies) / 2, len(set(candies)))
if __name__ == '__main__':
solution = Solution()
assert 3 == solution.distributeCandies([1, 1, 2, 2, 3, 3])
assert 2 == solution.distributeCandies([1, 1, 2, 3])
|
#author: n01
"""
Useful termcolor attributes (attrs for short)
@Usage: colored("stringa", COLOR, attrs=ATTRIBUTE)
These attributes are list with a single element
to create longer list just add the attributes together
e.g. BLINK + BOLD gives you ['blink', 'bold']
"""
BLINK = ["blink"]
BOLD = ["bold"]
DARK = ["dark"]
UN... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
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, merge, p... |
"""
Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that
occur more than once in the input string. The input string can be assumed to contain only alphabets
(both uppercase and lowercase) and numeric digits.
Example
"abcde" -> 0 # no characters repeats ... |
#
# PySNMP MIB module ELTEX-MES-IP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-IP
# Produced by pysmi-0.3.4 at Wed May 1 13:00:06 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,... |
def print_full_name(a, b):
first_name = a
last_name = b
print("Hello", first_name, last_name + "!", "You just delved into python.") |
#-*- coding:utf-8 _*-
"""
@author:charlesXu
@file: cws_rest_view.py
@desc: 分词和词性标注接口
@time: 2019/05/10
"""
|
opt = {
# LRC1000.0
'a9a.LRC1000.0': 1.05049605396498e+07, # from TRON
'a9a.bias.LRC1000.0': 1.05049602719930e+07, # from TRON
'covtype.libsvm.binary.LRC1000.0': 2.98341912891832e+08, # from nheavy
'covtype.libsvm.binary.bias.LRC1000.0': 2.98341823726758e+08, # fro... |
# encoding=utf-8
def my_coroutine():
while True:
received = yield
print('Received:',received)
it = my_coroutine()
next(it)
it.send('First')
it.send('Second')
def minimize():
current = yield
while True:
value = yield current
current = min(value,current)
it = minimize()
next(it)
print(it.send(10))
prin... |
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
anagram = {}
for i in strs:
count = [0]*26
for c in i:
count[ord(c) - ord('a')] += 1
count = tuple(count)
... |
'''
File name: p1_utils.py
Author:
Date:
'''
|
""" Implementation of Merge Sort algorithm
"""
def merge(data):
""" MergeSort is a Divide and Conquer algorithm. It divides input array
in two halves, calls itself for the two halves and then merges the
two sorted halves.
:param array: list of elements that needs to be sorted
:type array: list
... |
#Faça um algoritmo para converter valores de fahrenheit celsius
F=float(input("digite quantos graus fahrenheit "))
C= (F-32)/1.8
print ("Celsius", C)
|
DAILY='DAILY'
WEEKLY='WEEKLY'
MONTHLY='MONTHLY'
ANNUALLY='ANNUALLY'
MONTHLY_MEAN='MONTHLY_MEAN'
ANNUAL_MEAN='ANNUAL_MEAN'
MONTHLY_SUM='MONTHLY_SUM'
ANNUAL_SUM='ANNUAL_SUM'
MONTHLY_SNAPSHOT='MONTHLY_SNAPSHOT'
ANNUAL_SNAPSHOT='ANNUAL_SNAPSHOT' |
"""Top-level package for Ansible Events."""
__author__ = """Ben Thomasson"""
__email__ = 'ben.thomasson@gmail.com'
__version__ = '0.4.0'
|
# Using names.txt (right click and 'Save Link/Target As...'),
# a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order.
# Then working out the alphabetical value for each name, multiply this value by
# its alphabetical position in the list to obtain a name score.
# For... |
"""x = 1 # int
x = "CBF Cursos" # string
x = 15.6 # float
x = False # bool
n1 = 5; n2 = 2; x = complex(n1, n2)
#Coleções
x = ["Carro","Avião", "Navio", 1,58.3, True] #List / Array pode ser alterado
x = ("Carro", "Aviao", "Navio", 1, 58.3, True) #Tupla é fechada
x = range(0,100,1)#List de 0 á 100 de 1 em 1
"""
x = ... |
#
# PySNMP MIB module RFC1406Ext-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1406Ext-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:56:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
MAPPING = [
{
'sid': 'Adult age binary (yes)',
'symptom': 'age',
'module': 'adult',
'gen_5_4a': 55,
'endorsed': True,
},
{
'sid': 'Adult age binary (no)',
'symptom': 'age',
'module': 'adult',
'gen_5_4a': 45,
'endorsed': False,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# let's create several lists
alist1 = [1, 2, 3, 4, 5]
alist2 = ['a', 'b', 'c', 'd', 'e']
alist3 = [] # empty list
alist4 = list() # Also creates an empty list. As an argument, anything iterable can be used and a list is created from it.
print(len(alist1)) # The buil... |
__all__ = [
'feature_audio_adpcm', \
'feature_audio_adpcm_sync', \
'bv_audio_sync_manager'
]
|
x = int(input())
a = list(map(int,input().split()))
y = int(input())
b = list(map(int,input().split()))
f=[]
for i in b:
for j in a:
if i%j==0:
f.append(i/j)
print(f.count(max(f))) |
class mystery(object):
def __init__(this, length, values):
this.values = [0]*length
for value in values:
this.values[value] += 1
def __str__(this):
return "length {:d}: {}".format(len(this.values), this.values)
def __add__(this, value):
myst = mystery(len(this.v... |
# coding: utf-8
# file generated by setuptools_scm
# don't change, don't track in version control
class Version:
def __init__(self, version):
self._p = version.split('.')
self._v = version
def __getitem__(self, key):
return self._p[key]
def __str__(self):
return self._v
d... |
def get_pair_number(list_pairs, item_left, item_right):
# Retrieve pair number
found = False
ct_pair = 0
iter_pair = 0
while not found:
if list_pairs[iter_pair, 0] == item_left and list_pairs[iter_pair, 1] == item_right:
ct_pair = iter_pair
found = True
else:
... |
"""
Collatz Conjecture exercise
"""
def steps(number):
"""
Count the number of steps
"""
if number <= 0:
raise ValueError("Only positive integers are allowed")
step = 0
while number != 1:
number = 3 * number + 1 if number % 2 else number // 2
step += 1
retur... |
def f1():
print("b f1")
def f2():
print("b f2")
def f3():
print("b f3")
# 这样就不会在导入模块时自动执行了
'''
__name__ 模块名
需要说明的是,如果我们导入的模块除了定义函数之外还中有可以执行代码,
那么Python解释器在导入这个模块时就会执行这些代码,
事实上我们可能并不希望如此,
因此如果我们在模块中编写了执行代码,
最好是将这些执行代码放入如下所示的条件中,
这样的话除非直接运行该模块,
if条件下的这些代码是不会执行的,
因为只有直接执行的模块的名字才是“__main__”
'''
if __n... |
HDL_PORT = 6000
EMAIL_ADDRESS_FROM = 'sender@example.com'
EMAIL_ADDRESS_TO = 'receiver@example.com'
SMTP_HOST = 'smtp.example.com'
SMTP_PORT = 587
SMTP_USERNAME = 'sender'
SMTP_PASSWORD = 'topsecret'
|
######################################### BeatDetector #############################################
# Author: Dan Boehm
#
# Copyright: 2011
#
# Description: The MusicFrameData class contains all of the information necessary for the
# LightSelector to make its decisions. It provides an easily accessible format f... |
# -*- coding: utf-8 -*-
"""
[Python 2.7 (Mayavi is not yet compatible with Python 3+)]
Created on Wed Apr 6 13:51:02 2016
@author: Ryan Stauffer
https://github.com/ryanpstauffer/market-vis
Market Visualization Prototype
__init__.py
"""
__version__ = "0.0.1"
|
class StringValidator(object):
def __init__(self, max_length=-1):
self.max_length = max_length
self.value = None |
#
# PySNMP MIB module ALTIGA-PPTP-STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTIGA-PPTP-STATS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:05:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
"""
Given two strings containing backspaces (identified by the character ‘#’), check if the two strings are equal.
Example 1:
Input: str1="xy#z", str2="xzz#"
Output: true
Explanation: After applying backspaces the strings become "xz" and "xz" respectively.
"""
# Time: O(M + N) Space: O(1)
def backspace_compare(s... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
l=[]
self.inorder(root,l)
t = ... |
sum = 1
nnn = 2
mmm = 666666666
|
def build_report_table(extra_queries):
table = []
column_names = ["Serializer", "Field", "Function", "Max queries"]
rows = [query.to_row() for query in extra_queries]
max_width = max(len(item) for row in rows for item in row)
table.append(
" | ".join(column_name.ljust(max_width) for column... |
SAMPLE_TEXT = """title: FH Technikum Wien
subline: Elektronische Informationsdienste
externalurl: http://technikum-wien.at
duration: "abgeschlossen: 2006"
date: 2006-12-30 12:00
---
* Leistungsstipendium mehrmals erhalten: wird pro Studiengang (ca. 240 Studenten) an 6 Studenten pro Jahr vergeben.
* Teammitglied der [Au... |
"""
68. How to get the n’th largest value of a column when grouped by another column?
"""
"""
Difficulty Level: L2
"""
"""
In df, find the second largest value of 'taste' for 'banana'
"""
"""
Input
"""
"""
df = pd.DataFrame({'fruit': ['apple', 'banana', 'orange'] * 3,
'rating': np.random.rand(9),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.