content stringlengths 7 1.05M |
|---|
#Cristian Chitiva
#cychitivav@unal.edu.co
#12/Sept/2018
myList = ['Hi', 5, 6 , 3.4, "i"] #Create the list
myList.append([4, 5]) #Add sublist [4, 5] to myList
myList.insert(2,"f") #Add "f" in the position 2
print(myList)
myList = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455]
myList.sort() #So... |
"""
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_larg... |
sample = ["abc", "xyz", "aba", "1221"]
def stringCounter(items):
amount = 0
for i in items:
if len(i) >= 2 and i[0] == i[-1]:
amount += 1
return amount
print("The amount of string that meet the criteria is:",stringCounter(sample)) |
# Uri Online Judge 1079
N = int(input())
for i in range(0,N):
Numbers = input()
num1 = float(Numbers.split()[0])
num2 = float(Numbers.split()[1])
num3 = float(Numbers.split()[2])
print(((2*num1+3*num2+5*num3)/10).__round__(1)) |
entity_id = data.get('entity_id')
command = data.get('command')
params = str(data.get('params'))
parsedParams = []
for z in params.replace(' ', '').replace('],[', '|').replace('[', '').replace(']', '').split('|'):
rect = []
for c in z.split(','):
rect.append(int(c))
parsedParams.append(rect)
if co... |
def rank_filter(func):
def func_filter(local_rank=-1, *args, **kwargs):
if local_rank < 1:
return func(*args, **kwargs)
else:
pass
return func_filter
|
tot=coe=rat=sap=0
for i in range(int(input())):
n,s=input().split()
n=int(n)
tot+=n
if s=='C':coe+=n
elif s=='R':rat+=n
elif s=='S':sap+=n
print(f"Total: {tot} cobaias\nTotal de coelhos: {coe}\nTotal de ratos: {rat}\nTotal de sapos: {sap}")
p=(coe/tot)*100
print("Percentual de coelhos: %.2f"%p,e... |
[ ## this file was manually modified by jt
{
'functor' : {
'description' : [ "The function always returns a value of the same type than the entry.",
"Take care that for integers the value returned can differ by one unit",
"from \c ceil((a+b)/2.0) o... |
"""
Exercício Python 5:
Faça um programa que leia um número Inteiro e
mostre na tela o seu sucessor e seu antecessor.
"""
n = int(input('digite um numero inteiro '))
#ant = n-1
#post = n+1
#print('O antecessor de {} é {} e posterior é {}' .format(n, ant, post))
print('{} o antercessor é {} o sucessor é {}'.format(n, (... |
def extract_to_m2(filename, annot_triples):
"""
Extracts error detection annotations in m2 file format
Args:
filename: the output m2 file
annot_triples: the annotations of form (sentence, indexes, selections)
"""
with open(filename, 'w+') as m2_file:
for triple in annot_tripl... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
start = list(map(int, inpu... |
#!/usr/bin/env python3
"""
Source Code of Pdiskuploaderbot
"""
|
'''
author : bcgg
可惜时间爆了
其实写的很好
中间很多可以改进
'''
ans = 0
def merge(arr, l, m, r):
global ans
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0, n1):
L[i] = arr[l + i]
for j in range(0, n2):
R[j] = arr[m + 1 + j]
i = 0
j = 0
k = l
while i < n... |
# Audit Event Outcomes
AUDIT_SUCCESS = "0"
AUDIT_MINOR_FAILURE = "4"
AUDIT_SERIOUS_FAILURE = "8"
AUDIT_MAJOR_FAILURE = "12"
|
"""All plugging called to check norm for a C file."""
__all__ = [
"columns",
"comma",
"function_line",
"indent",
"libc_func",
"nested_branches",
"number_function",
"parenthesis",
"preprocessor",
"snake_case",
"solo_space",
"statements",
"trailing_newline",
"two_sp... |
#771. Jewels and Stones
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
# count = 0
# jewl = {}
# for i in jewels:
# if i not in jewl:
# jewl[i] = 0
# for j in stones:
# if j in jewl:
# count += 1
... |
class MaxPQ:
def __init__(self):
self.pq = []
def insert(self, v):
self.pq.append(v)
self.swim(len(self.pq) - 1)
def max(self):
return self.pq[0]
def del_max(self, ):
m = self.pq[0]
self.pq[0], self.pq[-1] = self.pq[-1], self.pq[0]
self.pq = se... |
class Song:
"A class for representing a song"
def __init__(self, name, singer):
"""
Initialize a new song with it's name and singer
:param name: str
:param singer: str
"""
self.name = name
self.singer = singer
self.mood = self.mood()
def text... |
BOT_TOKEN: str = "ODg4MzAyMzkwNTMxNDg1Njk2.YUQuEQ.UO4oyY9Zk4u1W5f-VpPLkkQ70TM"
SPOTIFY_ID: str = ""
SPOTIFY_SECRET: str = ""
BOT_PREFIX = "$"
EMBED_COLOR = 0x4dd4d0 #replace after'0x' with desired hex code ex. '#ff0188' >> '0xff0188'
SUPPORTED_EXTENSIONS = ('.webm', '.mp4', '.mp3', '.avi', '.wav', '.m4v', '.ogg', '... |
"""
An edge is a bridge if, after removing it count of connected components in graph will
be increased by one. Bridges represent vulnerabilities in a connected network and are
useful for designing reliable networks. For example, in a wired computer network, an
articulation point indicates the critical computers and a b... |
class BRepBuilderGeometryId(object,IDisposable):
"""
This class is used by the BRepBuilder class to identify objects it creates (faces,edges,etc.).
BRepBuilderGeometryId(other: BRepBuilderGeometryId)
"""
def Dispose(self):
""" Dispose(self: BRepBuilderGeometryId) """
pass
@staticmethod
def Inva... |
class IncompatibleAttribute(Exception):
pass
class IncompatibleDataException(Exception):
pass
class UndefinedROI(Exception):
pass
class InvalidSubscriber(Exception):
pass
class InvalidMessage(Exception):
pass
|
def create_bag_of_centroids(wordlist, word_centroid_map):
"""
a function to create bags of centroids
"""
# The number of clusters is equal to the highest cluster index in the word / centroid map
num_centroids = max( word_centroid_map.values() ) + 1
# Pre-allocate the bag of centro... |
# Enter script code
message = "kubectl exec -it <cursor> -- bash"
keyboard.send_keys("kubectl exec -it ")
keyboard.send_keys("<shift>+<ctrl>+v")
time.sleep(0.1)
keyboard.send_keys(" -- bash")
|
'''
Topic : Algorithms
Subtopic : Diagonal Difference
Language : Python
Problem Statement : Given a square matrix, calculate the absolute difference between the sums of its diagonals.
Url : https://www.hackerrank.com/challenges/diagonal-difference/problem
'''
#!/bin/python3
# Complete the 'diagonalD... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/702/A
#严格来说不能算DP?
_ = input()
l = list(map(int,input().split())) #https://codeforces.com/blog/entry/71884
maxL = 1
curL = 1
for i in range(1,len(l)):
if l[i]<=l[i-1]:
curL = 1
continue
curL += 1
if curL > maxL: maxL = cur... |
'''
Quiz 1:
Hacer un programa que lea una temperatura en farenheit y la convierta en celsius y si es mayor
a 100°C imprima "caliente". Si es menor a 0°C imprima "frio"
'''
tempF = int(input("TempF: "))
#(tempF - 32/(5/9))
tempC = (((tempF - 32)*5)/9)
print("\nLa temperatura en Celsius es " + str(tempC))
... |
class ParsnipException(Exception):
def __init__(self, msg, webtexter=None):
self.args = (msg, webtexter)
self.msg = msg
self.webtexter = webtexter
def __str__(self):
return repr("[%s] %s - %s" % (self.webtexter.NETWORK_NAME, self.webtexter.phone_number, self.msg))
class LoginError(ParsnipException):pa... |
def soma(x,y):
return print(x + y)
def sub(x,y):
return print(x - y)
def mult(x,y):
return print(x * y)
def div(x,y):
return print(x / y)
soma(3,8)
sub(10,5)
mult(3,9)
div(15,7) |
class DeviceLog:
def __init__(self, deviceId, deviceName, temperature, location, recordDate):
self.deviceId = deviceId
self.deviceName = deviceName
self.temperature = temperature
self.location = location
self.recordDate = recordDate
def getStatus(self):
if self.t... |
class NeighborResult:
def __init__(self):
self.solutions = []
self.choose_path = []
self.current_num = 0
self.curr_solved_gates = []
|
'''
@brief this class reflect action decision regarding condition
'''
class EventAction():
'''
@brief build event action
@param cond the conditions to perform the action
@param to the target state if any
@param job the job to do if any
'''
def __init__(self, cond="", to=... |
quedex_public_key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1
mQENBFlPvjsBCACr/UfHzXAezskLqcq9NiiaNFDDT5A+biC8VrOglB0ZSQOYRira
NgQ2Cp8Jd+XU77F+J1012BjB5y87Z+hdnwBDsqF7CjkjeQzsE3PSvm9I+E3cneqx
UcinRaUD1wfwVytbg9Q9rpqQ7CTjVWY1UPYjs6dAo1WAp/ux/VTeOFbpO0R3D7if
ZGY1QeISRpLWiMpcG2YCOALnuazABVCNXLhVqa8Y7tt2I... |
age = int(input("How old are you ?"))
#if age >= 16 and age <= 65:
#if 16 <= age <= 65:
if age in range(16,66):
print ("Have a good day at work.")
elif age > 100 or age <= 0:
print ("Nice Try. This program is not dumb.")
endkey = input ("Press enter to exit")
else:
print (f"Enjoy your free time, ... |
"""Helpers to subset an extracted dataframe"""
readability_cols = [
"flesch_reading_ease",
"flesch_kincaid_grade",
"smog",
"gunning_fog",
"automated_readability_index",
"coleman_liau_index",
"lix",
"rix",
]
dependency_cols = [
"dependency_distance_mean",
"dependency_distance_st... |
class Solution:
def longestPalindrome(self, s: str) -> int:
d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
res = 0
for _, n in d.items():
res += n - (n & 1)
return res + 1 if res < len(s) e... |
"""GCP Storage Constant."""
locations_list = [
"US",
"EU",
"ASIA",
"ASIA1",
"EUR4",
"NAM4",
"NORTHAMERICA-NORTHEAST1",
"NORTHAMERICA-NORTHEAST2",
"US-CENTRAL1",
"US-EAST1",
"US-EAST4",
"US-WEST1",
"US-WEST2",
"US-WEST3",
"US-WEST4",
"SOUTHAMERICA-EAST1",
... |
class Articles:
def __init__(self,id,name,author, title, description, url, urlToImage,publishedAt):
self.id = id
self.name = name
self.author = author
self.title = title
self.description = description
self.url = url
self.urlToImage = urlToImage
... |
# OpenWeatherMap API Key
weather_api_key = "f4695ec49ac558195fc591f0d450c34c"
# Google API Key
g_key = "AIzaSyAyIq5hhFN-Y0M16Ltie3YuwpDiKWx8tCk"
|
'''
Faça um programa que leia o nome completo de uma pessoa,
mostrando em seguida o primeiro e o último nome separadamente.
'''
entrada = str(input('Digite um nome completo: ')).strip()
print('Olá {}'.format(entrada))
nome = entrada.split()
print('Seu primeiro nome é: {}'.format(nome[0]))
print('Seu último nom... |
class ArgumentError(Exception):
def __init__(self, argument_name: str, *args) -> None:
super().__init__(*args)
self.argument_name = argument_name
@property
def argument_name(self) -> str:
return self.__argument_name
@argument_name.setter
def argument_name(self, value: s... |
BOT_NAME = "placement"
SPIDER_MODULES = ["placement.spiders"]
NEWSPIDER_MODULE = "placement.spiders"
ROBOTSTXT_OBEY = True
CONCURRENT_REQUESTS = 16
DUPEFILTER_DEBUG = True
EXTENSIONS = {"spidermon.contrib.scrapy.extensions.Spidermon": 500}
SPIDERMON_ENABLED = True
ITEM_PIPELINES = {"spidermon.contrib.scrapy.pipeli... |
def star_pattern(n):
for i in range(n):
for j in range(i+1):
print("*",end=" ")
print()
star_pattern(5)
'''
star_pattern(5)
*
* *
* * *
* * * *
* * * * *
'''
|
listaNum = list()
contadorde5 = 0
while True:
num = int(input('Digite um número: '))
if num == 5:
contadorde5 += 1
listaNum.append(num)
continuar = str(input('Quer continuar? [ S / N ] ')).strip().upper()
print()
if continuar[0] == 'N':
break
while continuar[0] != 'S' and... |
# 1461. Check If a String Contains All Binary Codes of Size K
# User Accepted:2806
# User Tried:4007
# Total Accepted:2876
# Total Submissions:9725
# Difficulty:Medium
# Given a binary string s and an integer k.
# Return True if any binary code of length k is a substring of s. Otherwise, return False.
# Example 1:
# ... |
n = int(input())
v = []
for i in range(n): v.append(int(input()))
s = sorted(set(v))
for i in s: print(f'{i} aparece {v.count(i)} vez (es)')
|
#! /usr/bin/env python
# Copyright (C) 2012-2015, Alphan Ulusoy (alphan@bu.edu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any lat... |
expected_output = {
"vrf": {
"VRF1": {
"address_family": {
"ipv4": {
"instance": {
"1": {
"areas": {
"0.0.0.1": {
"sham_links": {
... |
pkgname = "cargo-bootstrap"
pkgver = "1.60.0"
pkgrel = 0
# satisfy runtime dependencies
hostmakedepends = ["curl"]
depends = ["!cargo"]
pkgdesc = "Bootstrap binaries of Rust package manager"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT OR Apache-2.0"
url = "https://rust-lang.org"
source = f"https://ftp.oct... |
# m=wrf_hydro_ens_sim.members[0]
# dir(m)
# Change restart frequency to hourly in hydro namelist
att_tuple = ('base_hydro_namelist', 'hydro_nlist', 'rst_dt')
# The values can be a scalar (uniform across the ensemble) or a list of length N (ensemble size).
values = 60
wrf_hydro_ens_sim.set_member_diffs(att_tuple, valu... |
def main () :
i = 1
fib = 1
target = 10
temp = 0
while (i < target) :
temp = fib
fib += temp
i+=1
print(fib)
return 0
if __name__ == '__main__':
main()
|
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
greed_p = 0
size_p = 0
count = 0
while greed_p < len(g) and size_p < len(s):
if g[greed_p] <= s[size_p]:
count += 1
greed_p ... |
"""
This is duplicated from Django 3.0 to avoid
starting an import chain that ends up with
ContentTypes which may not be installed in a
Djangae project.
"""
class BaseBackend:
def authenticate(self, request, **kwargs):
return None
@classmethod
def can_authenticate(cls, request):
... |
data = {
"publication-date": {
"year": {
"value": "2020"},
"month": {"value": "01"}},
"short-description": "With a central surface brightness of 29.3 mag arcsec, and half-light radius of r_half=3.1^{+0.9}_{-1.1} kpc, Andromeda XIX (And XIX) is an extremely diffuse satellite of Androm... |
"""
For an array, we can build a SegmentTree for it, each node stores an extra attribute count to denote the number of
elements in the the array which value is between interval start and end. (The array may not fully filled by elements)
Design a query method with three parameters root, start and end, find the number o... |
# This is a sample Python script.
def test_print_hi():
assert True
|
hours = input('Enter Hours \n')
rate = input('Enter Rate\n')
hours = int(hours)
rate = float(rate)
if (hours <= 40):
pay = rate*hours
else:
extra_time = hours - 40
pay = (rate*hours) + ((rate*extra_time)/2)
print('Pay: ', pay)
|
def get_schema():
return {
'type': 'object',
'properties': {
'connections': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
... |
def main():
mainFile = open("index.html", 'r', encoding='utf-8')
writeFile = open("index_pasted.html", 'w+', encoding='utf-8')
classId = 'class="internal"'
cssId = '<link rel='
for line in mainFile:
if (classId in line):
pasteScript(line, writeFile)
elif (cssId in line):... |
# 公众号:MarkerJava
# 开发时间:2020/10/5 17:25
scores = {'kobe': 100, 'lebron': 99, 'AD': 88}
# 获取所有key
keys = scores.keys()
print(keys)
print(type(keys))
print(list(keys)) # 将所有key组成的视图转换层列表
# 获取所有的值
value = scores.values()
print(value)
print(type(value)) # 将所有value组成的视图转换层列表
# 获取所有键值对
items = scores.items()
print(items... |
def main():
seed = 0x1234
e = [0x62d5, 0x7b27, 0xc5d4, 0x11c4, 0x5d67, 0xa356, 0x5f84,
0xbd67, 0xad04, 0x9a64, 0xefa6, 0x94d6, 0x2434, 0x0178]
flag = ""
for index in range(14):
for i in range(0x7f-0x20):
c = chr(0x20+i)
res = encode(c, index, seed)
if... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/2/2 10:08 上午
# @Author : xinming
# @File : ListNode.py
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class MyLinkedList:
def __init__(self):
self.size = 0
self.dummy_head = ListNode(0)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
file1=open('data/u_Lvoid_20.txt',encoding='utf-8')
file2=open('temp2/void.txt','w',encoding='utf-8')
count=0
for line in file1:
count=count+1
if(line[0]=='R'):# 'line' here is a string
line_list=line.split( ) # 'line_list' is a list of small strings=['R4... |
def climbingLeaderboard(scores, alice):
scores = list(reversed(sorted(set(scores))))
r, rank = len(scores), []
for a in alice:
while (r > 0) and (a >= scores[r - 1]):
r -= 1
rank.append(r + 1)
return rank |
screen = {
"bg": "blue",
"rows": 0,
"columns": 0,
"columnspan": 4,
"padx": 5,
"pady": 5,
}
input = {
"bg": "blue",
"fg": "red",
"fs": "20px",
}
button = {
"bg": "blue",
"fg": "red",
"fs": "20px",
}
|
# 3. Single layered 4 inputs and 3 outputs(Looping)
mInputs = [3, 4, 1, 2]
mWeights = [[0.2, -0.4, 0.6, 0.4],
[0.4, 0.3, -0.1, 0.8],
[0.7, 0.6, 0.3, -0.3]]
mBias1 = [3, 4, 2]
layer_output = []
for neuron_weights, neuron_bias in zip(mWeights, mBias1):
neuron_output = 0
for n_inputs, ... |
class FolhaDePagamento:
@staticmethod
def log():
return f'Isso é um log qualquer.'
#folha = FolhaDePagamento()
#print(folha.log())
print(FolhaDePagamento.log()) |
# reading 2 numbers from the keyboard and printing maximum value
r = int(input("Enter the first number: "))
s = int(input("Enter the second number: "))
x = r if r>s else s
print(x)
|
def main():
STRING = "aababbabbaaba"
compressed = compress(STRING)
print(compressed)
decompressed = decompress(compressed)
print(decompressed)
def compress(string):
encode = {} # string -> code
known = ""
count = 0
result = []
for letter in string:
if known + letter in... |
# When one class does the work of two, awkwardness results.
class Person:
def __init__(self, name, office_area_code, office_number):
self.name = name
self.office_area_code = office_area_code
self.office_number = office_number
def telephone_number(self):
return "%d-%d" % (s... |
class Solution(object):
def maxCount(self, m, n, ops):
"""
:type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int
"""
return reduce(operator.mul, map(min, zip(*ops + [[m,n]])))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
class OpenError(StandardError):
def __init__(self, error_code, error, error_info):
self.error_code = error_code
self.error = error
self.error_info = error_info
StandardError.__init__(self, error)
def __str__(self):
return 'Erro... |
#MaBe
matriz = [[0, 0, 0], [0, 0, 0,], [0, 0, 0]]
for l in range(0, 3):
for c in range(0,3):
matriz[l][c] = int(input(f'Digite o valor da posição {(c, l)}: '))
for obj in range(0, 3):
for i in range(0, 3):
print(f'[{matriz[obj][i]}]', end=' ')
print()
|
table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
tr = {}
for i in range(58):
tr[table[i]] = i
s = [11, 10, 3, 8, 4, 6]
xor = 177451812
add = 8728348608
def dec(x):
r = 0
for i in range(6):
r += tr[x[s[i]]] * 58**i
return (r - add) ^ xor
def enc(x):
x = (x ^ xor) + add... |
class ConfigException(Exception):
"""Configuration exception when an integration that is not available
is called in the `Config` object.
"""
pass
|
#079_Valores_unicos_em_uma_lista.py
lista = []
print("")
while True:
n = int(input("Adicione valor: "))
if n not in lista:
lista.append(n)
print(f"Valor {n} adicionado com sucesso")
else:
print(f"Valor {n} duplicado NÃO adicionado")
esc = " "
while esc not in "SN":
... |
#
# @lc app=leetcode id=838 lang=python3
#
# [838] Push Dominoes
#
# @lc code=start
class Solution:
def pushDominoes(self, dominoes: str) -> str:
l = 0
ans = []
dominoes = 'L' + dominoes + 'R'
for r in range(1, len(dominoes)):
if dominoes[r] == '.':
conti... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
if pRoot == None:
return []
queue1 = [pRoot]
queue2 = []
ret = []
while queue1 or q... |
# 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 w... |
# (c) Copyright [2017] Hewlett Packard Enterprise Development LP
#
# 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 appli... |
"""A tool for modeling composite beams and aircraft wings.
``Aerodynamics``
This module provides the aerodynamics models used within AeroComBAT
``AircraftParts``
This module provides a full-fledged wing object that can be used to
determine if a design is both statically adequate as well as stable.
``... |
# A Text to Morse Code Converter Project
# Notes:
# This Morse code make use of the basic morse code charts which contains 26 alphabets and 10 numerals
# No special characters are currently involved. But can be added in the '.txt ' file based on the requirement.
MORSE_CODE_CHART = "script_texts.txt"
def lo... |
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_univals(node):
if node.right is None and node.left is None:
return node.val, True, 1
l_val, l_is_unival, l_univals = count_univals(node.left)
r_val... |
def naive(a, b):
c = 0
while a > 0:
c = c + b
a = a - 1
return c
def russian(a, b):
"""
The Russian Peasant Algorithm:
Multiply one integer by the other integer.
Input: a, b: integers
Returns: a*b
"""
c = 0
while a > 0:
if a % 2 == 1:
... |
# Python Tuples
# Ordered, Immutable collection of items which allows Duplicate Members
# We can put the data, which will not change throughout the program, in a Tuple
# Tuples can be called as "Immutable Python Lists" or "Constant Python Lists"
employeeTuple = ("Sam", "Sam" "Mike", "John", "Harry", "Tom", "Sean", "Ju... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: tflite
class BuiltinOperator(object):
ADD = 0
AVERAGE_POOL_2D = 1
CONCATENATION = 2
CONV_2D = 3
DEPTHWISE_CONV_2D = 4
EMBEDDING_LOOKUP = 7
FULLY_CONNECTED = 9
HASHTABLE_LOOKUP = 10
L2_NORMALIZATION = ... |
class Table(object):
def __init__(self, name):
self.name = name
self.columns = []
def createColumn(self, column):
self.columns.append(column)
def readColumn(self, name):
for value in self.columns:
if value.name == name:
return value
... |
class Config:
api_host = "https://api.frame.io"
default_page_size = 50
default_concurrency = 5
|
"""
Profile ../profile-datasets-py/div83/073.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/073.py"
self["Q"] = numpy.array([ 1.956946, 2.801132, 4.230252, 5.419981, 6.087733,
6.419039, 6.547807, 6.548787, 6.504738, 6.4... |
# Introductory examples
name = 'Maurizio'
surname = 'Petrelli'
print('-------------------------------------------------')
print('My name is {}'.format(name))
print('-------------------------------------------------')
print('My name is {} and my surname is {}'.format(name, surname))
print('------------------------------... |
class PartialFailure(Exception):
"""
Error indicating either send_messages or delete_messages API call failed partially
"""
def __init__(self, result, *args):
self.success_count = len(result['Successful'])
self.failure_count = len(result['Failed'])
self.result = result
s... |
'''
Created on Dec 18, 2016
@author: rch
'''
|
#!/usr/bin/env python
# coding=utf-8
class BaseException(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return '<%s %s>' % (self.__class__.__name__, self.code)
|
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
'''
[3,5,2,1,6,4]
[3,5,1,6,2,4]
[4,3,2,1]
[3,4,2,1]
[6,6,5,6,3,8]
'''
def is_correct_order(x, ... |
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'test_cdecl',
'type': 'loadable_module',
'msvs_settings': {
'VCCLCompilerTool': {
'Calling... |
class BaseAgent(object):
"""
Class for the basic agent objects.
"""
def __init__(self,
env,
actor_critic,
storage,
device):
"""
env: (gym.Env) environment following the openAI Gym API
"""
self.env = en... |
#
# PySNMP MIB module RBT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:18:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... |
def solution(num):
if num < 0:
raise ValueError
if num == 1:
return 1
k = None
for k in range(num // 2 + 1):
if k ** 2 == num:
return k
elif k ** 2 > num:
return k - 1
return k
def best_solution(num):
if num < 0:
raise ValueEr... |
# Homework #6. Loops
print("--- Task #1. 10 monkeys")
# Task #1. Write a program that output the following string: "1 monkey 2 monkeys ... 10 monkeys".
for x in range(1, 11):
if x == 1:
monkey = f"{x} monkey "
else:
monkey = monkey + f"{x} monkeys "
print(monkey.strip())
print("\n--- Task #2. Countdow... |
# -*- coding: utf-8 -*-
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
mod = 10 ** 9 + 7
ans = 0
# See:
# https://www.youtube.com/watch?v=JTH27weC38k
# https://atcoder.jp/contests/jsc2019-qual/submissions/7107452
# Key Insight
# 2つの... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.