content stringlengths 7 1.05M |
|---|
n1 = float(input('Redação:'))
n2 = float(input('Ciências da Natureza e suas Tecnologias:'))
n3 = float(input('Ciências Humanas e suas Tecnologias:'))
n4 = float(input('Linguagens, Códigos e suas Tecnologias:'))
n5 = float(input('Matemática e suas Tecnologias:'))
x = (n1 + n2 + n3 + n4 + n5) / 5
print('Sua média no Enem... |
def factorial(n):
if n == 0:
return 1
return factorial(n-1) * n
|
def getalpha(schedule, step):
alpha = 0.0
for (point, alpha_) in schedule:
if step >= point:
alpha = alpha_
else:
break
return alpha
step_stage_0 = 0
step_stage_1 = 5e4
step_stage_2 = 7e4
step_stage_3 = 1e5
step_stage_4 = 2.5e5
step_stages = [step_stage_0, step_sta... |
def nome_no_formulario():
nome = input()
tamanho_de_caracteres = len(nome)
if tamanho_de_caracteres > 80:
print('NO')
else:
print('YES')
nome_no_formulario()
|
class Fib:
def __init__(self,nn):
print("inicjujemy")
self.__n=nn
self.__i=0
self.__p1=self.__p2=1
def __iter__(self):
print('iter')
return self
def __next__(self):
print('next')
self.__i+=1
if self.__i>self.__n:
... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
CORE_GAUGES = {
'system.disk.total': 5,
'system.disk.used': 4,
'system.disk.free': 1,
'system.disk.in_use': .80,
}
CORE_RATES = {
'system.disk.write_time_pct': 9.0,
'system.disk.read_time_p... |
# by Kami Bigdely
# Replace magic numbers with named constanst
def calculation(charge1, charge2, distance):
constant = 8.9875517923*1e9
return constant * charge1 * charge2 / (distance**2)
# First Section
# Given two point charges, calcualte the electric force exerted on them.
q1 = int(input('Enter ... |
class IDataset(object):
def __init__(self):
pass
def train(self):
raise RuntimeError("No implementation found!")
def val(self):
raise RuntimeError("No implementation found!")
def test(self):
raise RuntimeError("No implementation found!")
|
class A:
def z(self):
return self
def y(self, t):
return len(t)
#Funcion que abriremos desde el archivo main.py
def main_puzzle():
a = A
y = a.z
print(y(a)) #Muestra por pantalla <class '__main__.A'> ya que la funcion z devuelve self
aa = a()
print(aa is a()) #Impri... |
#define MAX(x,y) (((x) > (y)) ? (x) : (y))
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
class solution:
def maxProfit(prices:list[int])->int:
pricesSize = len(prices)
dp_sell_out = []
dp_sell_with = []
dp_buy = []
#current action is not selling, next step cou... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
curr_node = head
curr_new = new_head = ListNode(0)
prev = None
wh... |
# This program subtracts one number from another
# Author: Isabella Doyle
first = int(input("Enter the first number:")) # requests input of integer from user
second = int(input("Enter the second number:")) # requests input of integer from user
# prints sum below
print(first - second) |
#b. Un alumno desea saber cuál será su calificación final en la materia de Lógica Computacional.
# Dicha calificación se compone de tres exámenes parciales cuya ponderación es de 30%, 30% y 40%.
print("¡Calculo de calificacion Final de un alumno!")
examen01=float(input("Ingrese nota de examen N° 1 = "))
examen02=floa... |
def test_get_uptimez(client):
response = client.get("/uptimez/")
assert response.status_code == 200
def test_get_healthz(client):
response = client.get("/healthz/")
assert response.status_code == 200
|
print("Hello world")
print("Adios")
def suma(a,b):
return a+b
print(suma(2,3))
print("Esto es una feature") |
t = int(input())
for _ in range(t) :
n, k = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
if(k > arr[0]) :
print(abs(k-arr[0]))
else :
print(0) |
'''
Você deve fazer um programa que apresente a sequencia conforme o exemplo abaixo.
Entrada
Não há nenhuma entrada neste problema.
Saída
Imprima a sequencia conforme exemplo abaixo.
'''
I = [1,1,1,3,3,3,5,5,5,7,7,7,9,9,9]
J = [7,6,5,9,8,7,11,10,9,13,12,11,15,14,13]
for i,j in zip(I,J):
print('I={} J={}'.format... |
# -*- coding: utf-8 -*-
"""
stocks_correlation.providers.quandl
This module define the normalized columns
of the DataFrame the providers return
"""
DATAFRAME_COLUMNS = ['date', 'open', 'high', 'low', 'close']
CORREL_COMPUTE_COLUMNS = DATAFRAME_COLUMNS[1:]
def filter_dates(df, start_date, end_date):
"""Filters ... |
a = int(input("Enter the First Number: "))# Inputing the first number
b = int(input("Enter the seconf Number: "))#inputing the second number
if(a>=b):#cheking if the first
print(a, "is greater")
else:
print(b, "is greater")
|
__name__ = "pairwisedist"
__author__ = """Guy Teichman"""
__email__ = "guyteichman@gmail.com"
__version__ = "1.1.0"
__license__ = "Apache"
|
"""
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers
as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, ... |
#! python3
# __author__ = "YangJiaHao"
# date: 2018/3/2
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
时间复杂度 O(m + n)
"""
if not matrix:
return False
row = 0
... |
MAJOR = 1
MINOR = 11
RELEASE = 10
VERSION = '%d.%d.%d' % (MAJOR, MINOR, RELEASE)
def num(versionstring=VERSION):
"""Convert the version string of the form 'X.Y.Z' to an integer 100000*X + 100*Y + Z for version comparison"""
(major, minor, release) = versionstring.split('.')
return 100*100*int(major) +... |
"""
Standardize Mobile Number Using Decorators
https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem
"""
def wrapper(f):
def fun(l):
# complete the function
for i, n in enumerate(l):
if len(n) == 10: n= "+91" + n
elif len(n) == 11 and n.st... |
# -*- coding: utf-8 -*-
# Author : Jin Kim
# e-mail : jinkim@seculayer.com
# Powered by Seculayer © 2021 Service Model Team, R&D Center.
class StringUtil(object):
@staticmethod
def get_int(data) -> int:
try:
return int(data)
except ValueError:
return -1
@staticmet... |
file = open('list_de_note.csv', mode = "r", encoding = "utf-8-sig")
file_new = open('list_de_note_new.csv', mode = "w", encoding = "utf-8-sig")
header = file.readline() ##lire la premiere ligne
#file_new.write(header)
file_new.write(header.strip() + ", Điểm trung bình,Học lực\n")
row = file.readline() ##lire la de... |
#returns the set of reachable vertices assuming G is represented via adjacency lists.
# Assumes that the graph is a dictionary and each adjacency list is a set.
def reachable(G,v):
rset = set()
def dfs(w):
rset.add(w)
for ngh in G[w]:
if not (ngh in rset):
dfs(ngh)
return
dfs(v)
return(rset)
G = {}
G... |
class Script(object):
START_MSG = """<b>Hy {},
I'm an advanced filter bot with many capabilities!
There is no practical limits for my filtering capacity :)
See <i>/help</i> for commands and more details.</b>
"""
HELP_MSG = """
<b><i>Add me as admin in your group and start filtering :)</i></b>
<b>Filter C... |
#
# PySNMP MIB module ADSL-LINE-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADSL-LINE-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
def fahrenheit_to_celsius(F):
C = 0
# Your code goes here: calculate the temperature in Celsius,
# store in a variable (we called it C), and return it.
return C
|
'''
https://www.hackerrank.com/challenges/30-class-vs-instance/problem
Crear una clase persona con una variable de instancia de
age.
El constructor debe asignar initialAge a la age despues de corfimar el argumento pasado como initailAge no es negativo,
Sies negativo initialAge el constructor deberá mostrar... |
base_datapath = '/Work19/2020/lijunjie/LRS3/AV_model_database/'
with open(base_datapath+'pretrain_dataset.txt', 'r') as tr:
lines = tr.readlines()
for line in lines:
info = line.strip().split('.')
num1 = info[0].strip().split('-')[1]
num2 = info[0].strip().split('-')[2]
new_lin... |
"""Our first program in Python"""
#print is the function to show to the user all we want
print('Welcome to Python')
#input is the functions that we use to recive data from the user
name = input('Give me your name')
#We can print the data we recive
print('Hello ', name)
|
# Copyright (c) 2021 by Don Deel. All rights reserved.
"""
Shared data for fishem and its modules.
All Redfish and Swordfish objects are shared as JSON objects in a
dictionary named "fish". Redfish resource path names are used as
keys to access objects in this dictionary, and these objects can
contain nested elements... |
def entry(**kwargs):
return '\n'.join([
"Welcome to SAMi",
"What would you like? REPLY",
"1 = Resources",
"2 = Talk to a friend",
"3 = Charge your phone",
])
def resources_1(**kwargs):
return '\n'.join([
"Welcome to resources: TEXT",
"1 = Food",
... |
def aumentar(preco=0, taxa=0, formatado=False):
res = preco + (preco * taxa / 100)
return res if formatado is False else moeda(res)
def diminuir(preco=0, taxa=0, formatado=False):
res = preco - (preco * taxa / 100)
return res if formatado is False else moeda(res)
def dobro(preco=0, formatado=False):... |
class Queue:
def __init__(self, initial_size = 10):
self.arr = [0 for _ in range(initial_size)]
self.next_index = 0;
self.front_index = -1;
self.queue_size = 0;
def enqueue(self, value):
if(self.queue_size) == len(self.arr):
self.handle_queue_capacity_full();
self.arr[self.next_index... |
# clean city and sector columns ar & eng
def cities(df):
df['English_City'] = df["City"].copy()
df['English_City'][df.English_City.str.contains('TABOUK')] = 'TABOUK'
df['English_City'][df.English_City.str.contains('HAIL')] = 'HAIL'
df['English_City'][df.English_City.str.contains('ABHA')] = 'ABHA'
d... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
node = self
output = ""
while node != None:
output += str(node.val)
output += " "
node = node.next
return output
|
#Unicode characters and strings
#1960s/1970s ---> we assumed one byte is one character and went it with
# a byte and character were assumed to be the same thing
#ASCII goes up to 127
print(ord('H'))
print(ord('e'))
print(ord('\n'))
print(ord('G'))
#UTF-16 - fixed length, two byes
#UTF-32 - fixed length, four... |
a = ("Ты можеш входить один на вечеринку.")
b = ("На вечеринку входи с мамой.")
c = ("Тебе нельзя входить на вечеринку.")
d = ("Сколько тебе лет?")
age = int(input(d))
if (age>=25) :
print (a)
elif (age>18) and (age<25) :
print (b)
elif (age>много) :
print ('Ну так вали отсюда со своим много')
else:
p... |
"""
Various constants used
Unit abreviations are appended to the name, but powers are not
specified. For instance, the gravitational constant has units "Mpc^3
msun^-1 s^-2", but is called "G_const_Mpc_Msun_s".
Most of these numbers are from google calculator.
SHOULD MOVE TO ASTROPY.UNITS AT S... |
description = 'MIRA2 monochromator'
group = 'lowlevel'
includes = ['base', 'mslit2', 'sample', 'alias_mono']
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(
co_m2tt = device('nicos.devices.entangle.Sensor',
visibility = (),
tangodevice = tango_base + 'mono2/m2tt_enc',
... |
# Divided OF two number
while True:
a = int(input("Enter The Dividend Number : "))
b = int(input("Enter The Divisor Number : "))
if a > b:
quotient = int(a / b)
print("Quotirnt Number Of :", quotient)
else:
Quotient = int(b / a)
print("Quotirnt Number Of : 0.",... |
IMPAR = []
PAR = []
for i in range(15):
X = int(input())
if X % 2 == 0:
PAR.append(X)
elif X % 2 != 0:
IMPAR.append(X)
if len(PAR) == 5:
Y = 0
for j in PAR:
print('par[{}] = {}'.format(Y,j))
Y += 1
PAR = []
if len(IMPAR) == 5:
Y... |
# The MIT License
# Copyright (c) 2015 Tom Pollard
# 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... |
class UserRepositoryDependencyMarker: # pragma: no cover
pass
class ProductRepositoryDependencyMarker: # pragma: no cover
pass
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Option:
def __init__(self, name, number, y):
self.name=name
self.number=number
self.y=y
|
# $Id: module_index.py 2790 2008-02-29 08:33:14Z cpbotha $
class emp_test:
kits = ['vtk_kit']
cats = ['Tests']
keywords = ['test', 'tests', 'testing']
help = \
"""Module to test DeVIDE extra-module-paths functionality.
"""
|
a = input('Digite algo ')
print(' O tipo primitivo desse valor é:',type(a))
print('Só tem espaços?',a.isspace())
print('É um número?', a.isnumeric())
print('É alfabético?',a.isalpha())
print('é alfanumérico?',a.isalnum())
print('Está em maiúscula?',a.isupper())
print('Está em minúsculo?',a.islower())
print('Está captal... |
'''
N = int(input())
notas100 = N//100
notas50 = (N-(notas100*100))//50
notas20 = (N-(notas100*100+notas50*50))//20
notas10 = (N-(notas100*100+notas50*50+notas20*20))//10
notas5 = (N-(notas100*100+notas50*50+notas20*20+notas10*10))//5
notas2 = (N-(notas100*100+notas50*50+notas20*20+notas10*10+notas5*5))//2
notas1 = (N-... |
n1 = float(input('Primeira reta: '))
n2 = float(input('Segunda reta: '))
n3 = float(input('Terceira reta: '))
if n1 < n2 + n3 and n2 < n1 + n3 and n3 < n1 + n2:
print('Essas retas forrmam um triângulo ', end='')
if n1 == n2 == n3:
print('EQUILÁTERO!')
elif n1 != n2 != n3:
print('ESCALENO!')
... |
# https://binarysearch.com/problems/Longest-Anagram-Subsequence
class Solution:
def solve(self, a, b):
letters = set(list(a)).intersection(set(list(b)))
length = 0
for i in letters:
length += min(a.count(i),b.count(i))
return length
|
"""
Formatando valores:
:s -> Texto (string)
:d -> Inteiro (int)
:f -> Números de ponto flutuante (float)
:.(NUMERO)f -> Quantidade de casas decimais (float)
:(CARACTERE)(> ou < ou ^)(QUANTIDADE)(TIPO - s, d ou f)
> -> Esquerda
< -> Direita
^ -> Centro
"""
num_1 = 10
num_2... |
t = int(input())
while t > 0:
t -= 1
n,m,s = map(int, input().strip().split(' '))
k = (s+m-1)%n
if(k==0):
print (n)
else:
print (k) |
'''
Description : Input In Function By .format Method
Function Date : 14 Feb 2021
Function Author : Prasad Dangare
Input : Int
Output : Int
'''
# defination of function, use of .format method
def Addition(no1, no2):
ans = no1 + no2
return ans
def main():
... |
#cameraCoords syntax: [x1 (oben links),y1,x2 (unten rechts),y2,zoomLevel]
def moveCamera(cameraCoords, move,worldSize):
if cameraCoords[0]+move[0] <= 1 and move[0] < 0:
cameraCoords[0] -= cameraCoords[0]%1
cameraCoords[2] -= cameraCoords[2]%1
while cameraCoords[0] > 1:
ca... |
def display_board( state ):
print("-------------")
print("| %i | %i | %i |" % (state[0], state[1], state[2]))
print("-------------")
print("| %i | %i | %i |" % (state[3], state[4], state[5]))
print("-------------")
print("| %i | %i | %i |" % (state[6], state[7], state[8]))
print("-------------")
def move_up(sta... |
a = input ("Digite algo")
print(a.isalpha())
print(a.isalnum())
print(a.isascii())
print(a.isdecimal())
print(a.isdigit())
print(a.isidentifier())
print(a.islower())
|
class Node:
def __init__(self, val=0):
self.value = val
self.next = None
class LinkList:
c = 10
def __init__(self, *args):
self.val = (*args,)
self.head = self.__constructLinklist()
#self.printLinklist(self.head)
# self.pre = self.revserlinklist()
#... |
"""
Question 59 :
Print a unicode string "hello world".
Hints : Use u'string format to define unicode string
"""
# Solution :
unicode_string = u"hello world!"
print(unicode_string)
"""
Output :
hello world
""" |
"""
PASSENGERS
"""
numPassengers = 4084
passenger_arriving = (
(4, 8, 15, 6, 6, 0, 9, 7, 7, 4, 1, 0), # 0
(4, 11, 5, 5, 2, 0, 7, 10, 6, 8, 2, 0), # 1
(11, 10, 4, 1, 1, 0, 5, 9, 13, 5, 1, 0), # 2
(5, 5, 9, 5, 1, 0, 6, 8, 7, 3, 2, 0), # 3
(5, 10, 8, 7, 1, 0, 8, 16, 10, 3, 3, 0), # 4
(6, 12, 7, 1, 4, 0, 10, ... |
'''
__program__: Taking user input from the user
__author__: Abhinav Anil
__submittedTo__: dataSciTech
__email__: dataascii@gmail.com
__instagram__: @data.sci_
'''
#Taking the user name, PAN card number to validate the information for the user details.
while(1):
name = input("\n Enter your name : ")
if name.... |
peoples = {
'first_name': 'le',
'last_name': 'xiaoyuan',
'age': 21,
'city': 'dawu'
}
print(peoples['first_name'])
print(peoples['last_name'])
print(peoples['age'])
print(peoples['city'])
for people in peoples.values():
print(people)
lucky_number = {
'lexiaoyuan': 6,
'benjamin': 66,
'l... |
# Problem! you teach children about how to calculate the area and perimeter of the square
# and you will solve 20 questions about the way to find area and perimeter. to teach them.
# but that will consume the time, so you want to write a program to reduce the time
# when calculating all 20 quests.
# Now try to solve it... |
class PullRequest:
"""
This class models a pull-request.
"""
@staticmethod
def __initialize_files(files_string):
return files_string.split("|")
def __init__(self, data):
self.pr_id = data[0]
self.pull_number = data[1]
self.requester_login = data[2]
self.... |
# *** these filters do NOT see ping messages, nor do routers see them ***
# *** global imports are NOT accessible, do imports in __init__ and bind them to an attribute ***
class Filters(Base):
def __init__(self, logger):
# init parent class
super().__init__(logger)
# some... |
# functions for creating model and selection of hyperparameters
def objective_lgb(space, X, Y, cat_feats, NFALG_PRINT_HIST, NUM_FOLDS):
#global iteration, best_auc_so_far, best_ntrees
global iteration, best_auc_val_so_far, best_auc_val_std_so_far, best_ntrees, best_auc_train_so_far, best_auc_train_std_so_far
... |
class HwndSourceParameters(object):
"""
Contains the parameters that are used to create an System.Windows.Interop.HwndSource object using the System.Windows.Interop.HwndSource.#ctor(System.Windows.Interop.HwndSourceParameters) constructor.
HwndSourceParameters(name: str)
HwndSourceParameters(name: str,wid... |
#-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... |
number = input("Enter a series of number, using separator you like: ")
separator = ""
for char in number:
if not char.isnumeric():
separator = separator + char
print(separator)
str = 0;
sum = 0
for char in number:
if char not in separator:
str = str * 10 + int(char)
if char == number[... |
{
"includes": [
"../common.gypi"
],
"targets": [
{
"target_name": "libgdal_ogr_pgdump_frmt",
"type": "static_library",
"sources": [
"../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumplayer.cpp",
"../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumpdatasource.cpp",
"../gdal/ogr/ogrsf_frmts/pgdump/ogrpgdumpdriver.c... |
class Human(object):
def __init__(self, mark, io):
self.mark = mark
self.io = io
def sanitize_user_input(self, user_input):
try:
sanitized_input = int(user_input)
except TypeError:
sanitized_input = 0
except ValueError:
sanitized_inpu... |
def razbi_stevilo(n, st):
s = []
st = str(st)
while len(st) > n:
stevilo = st[:n]
s.append(stevilo)
st = st[1:]
return s #seznam 13 mestnih steil podanih v nizu
def razbi_stevke(n):
sez_stevk = []
for stevka in n:
sez_stevk.append(int(stevka))
sez_stevk.sort... |
class Solution:
def longestMountain(self, A: List[int]) -> int:
'''
T: O(n) and S: O(1)
'''
if len(A) < 3: return 0
maxLen = 0
for i in range(1, len(A)-1):
left, right = i - 1, i + 1
if (A[left] < A[i]) and (A[i] > A[right]):
... |
# Loan repayment calculation service
# This is the program calculating the loan repayment amount for clients.
#
# Input parameters:
# principal(p) : Only integers equal or greater than one million are allowed
# years(y) : Only integers equal or greater than one are allowed
# annual interest rate(r) : Only floating poin... |
# -*- coding: utf-8 -*-
# .-. .-. .-. . . .-. .-. .-. .-.
# |( |- |.| | | |- `-. | `-.
# ' ' `-' `-`.`-' `-' `-' ' `-'
__title__ = 'requests2'
__description__ = 'Python HTTP for Humans.'
__url__ = 'http://python-requests.org'
__version__ = '2.16.0'
__build__ = 0x021600
__author__ = 'Kenneth Reitz'
__author_ema... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 12:58:44 2020
@author: SELICLO1
"""
def HammingDistance(a,b):
mm = 0
for i,s in enumerate(a):
if s != b[i]: mm+= 1
return mm
a = 'GTCTGGGCCGTGCGGACTTGTTGCGGATGATACAAGGGCTTCACTACGTCGAAGTAAGTTACCAATTATACAAGCTACCGGTGTAGAATGGTGAGTAGGTCCGCTTATAGCCCGCGC... |
a = int(input("Enter the first no : "))
b = int(input("Enter the second no : "))
c = a+b
print("sum of",a,'+',b,'=',c)
print("The first no is: %d and second number is: %d and the sum is: %d"%(a,b,c))
print("%d + %d = %d"%(a,b,c))
print("%-10d + %-10d = %-10d"%(a,b,c))
print("%-10f + %-10f = %-10f"%(a,b,c))
prin... |
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def kth_to_last(k, linked_list):
pointer1, pointer2 = linked_list, linked_list
for _ in range(k):
if not pointer1:
return None
pointer1 = pointer1.next
while pointer1:... |
print("-- Strings -- ")
print()
mystring = "hello"
myfloat = 10.0
myint = 20
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)
print()
nome = 'Teste... |
def General(project):
feature_vectors = get_featrures(projects)
h_clusters = BIRCH(projects,feature_vectors)
for level in h_clusters.levels:
if level.depth == h_clusters.max_depth:
for cluster in level.clusters:
level.cluster.bell = bellwether(cluster.projects)
el... |
"""
LC89. Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation... |
# Sudoku Solver: https://leetcode.com/problems/sudoku-solver/
# Write a program to solve a Sudoku puzzle by filling the empty cells.
# A sudoku solution must satisfy all of the following rules:
# Each of the digits 1-9 must occur exactly once in each row.
# Each of the digits 1-9 must occur exactly once in e... |
abi = """[
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "_hashSender",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "_hashId",
"type": "uint256"
},
{
"indexed": false,
... |
# import contact: click on chart to draw a contact that gets pinged by sonar
colors = {'GRN':color(51, 255, 0), 'RED':color(193, 49, 36), 'BLK':color(10)}
def setup():
size(480, 480)
background(colors['BLK'])
fill(colors['RED'])
ellipse(240, 240, 430, 430)
fill(10)
ellipse(240, 240, 420, 420)
... |
def debug_policy_plot():
qq_right = []
x_vec = np.arange(vagent.max_q[0])
for xx in x_vec:
vagent.q[0] = xx
vsensor.update(vscene,vagent)
vobservation = local_observer(vsensor,vagent) #todo: generalize
qq_right.append(RL.compute_q_eval(vobservation.reshape([1... |
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
sum = 0
for i in shift:
if i[0] == 0:
sum += i[1]
else:
sum -= i[1]
sum = sum % len(s)
return s[sum:]+s[:sum]
|
# Copyright © 2014 Bart Massey
# [This program is licensed under the "MIT License"]
# Please see the file COPYING in the source
# distribution of this software for license terms.
# The += operator on lists appends the a copy of the
# right-hand operand to the left-hand operand. This
# makes z += y different from z = z... |
"""
netparse.table
This module provides the necessary abstraction to take a TABLE pattern
output and generate an accurate datastructure based off it.
For further reading, please check out this article:
https://pyability.com/the-curse-of-the-cli/
"""
class ParseTable:
def __init__(self, unstructured_data, patte... |
# Based on MicroPython config option, comparison of str and bytes
# or vice versa may issue a runtime warning. On CPython, if run as
# "python3 -b", only comparison of str to bytes issues a warning,
# not the other way around (while exactly comparison of bytes to
# str would be the most common error, as in sock.recv(3)... |
class Solution:
def toGoatLatin(self, S: str) -> str:
words = S.split()
res = []
for i, w in enumerate(words):
if w[0].lower() not in "aeiou":
w = w[1:] + w[0]
w += "ma" + ("a" * (i + 1))
res.append(w)
return ' '.join(res)
if __n... |
# the interface
# class, or the interface
# data type
# interface data types
# are inspired from
# the typescript language
# example
# f = Interface(types)
# f.create(data)
class InterfaceObject():
def __init__(self, object_info):
# the passed in values
# to create a new object
... |
"""
Standard disk mounted on a CIM_ComputerSystem.
"""
def EntityOntology():
return (["Name"],)
|
def rotflip():
yield "rot1"
yield "rot2"
yield "rot3"
yield "rot4"
yield "flip"
yield "rot1"
yield "rot2"
yield "rot3"
yield "rot4"
raise ValueError("aaaaa")
i = 0
#for i,a in enumerate(rotflip()):
a_gen = rotflip()
while True:
a = a_gen.__next__()
print(a)
i += 1
... |
marks = {}
for _ in range(int(input())):
line = input().split()
marks[line[0]] = sum(map(float, line[1:])) / 3
print('%.2f' % marks[input()]) |
"""
Count the number of ways to tile the floor of size n x m using 1 x m size tiles
Given a floor of size n x m and tiles of size 1 x m. The problem is to count the number of ways to tile the
given floor using 1 x m tiles. A tile can either be placed horizontally or vertically.
Both n and m are positive integers and 2... |
# A script to recursively find the greatest common divisor of two numbers
def greatest_divisor(first, second):
assert first == int(first) and second == int(second) and first != 0 and second != 0, 'Numbers provided must be nonzero integers'
if first < 0:
first = -first
if second < 0:
secon... |
def main():
card_number = input("Enter credit card number: ")
print_card_value(card_number)
def print_card_value(card_number):
if check_for_sum(card_number) == False:
print("INVALID")
elif check_for_amex(card_number) == True:
print("AMEX")
elif check_for_master(card_number) == T... |
# Write a program to create a stack called Product to perform
# the basic operations on stack using list. The list contains
# two data fields: ProductId and ProductName. Write the following functions:
# InsertProd() – To push the data values into the list Docinfo
# DeleteProd() – To remove the data value from the list... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.