content stringlengths 7 1.05M |
|---|
"""
SeparateChainingMap
Implement a Map with a hash table, using separate chaining.
"""
class SeparateChaining:
def __init__(self, length=10):
self.table = [[] for _ in range(length)]
self.size = 0
def __len__(self):
return self.size
def __setitem__(self, key, value):
pri... |
"""
Define a procedure, `deep_reverse`, that takes as input a list,
and returns a new list that is the deep reverse of the input list.
This means it reverses all the elements in the list,
and if any of those elements are lists themselves,
reverses all the elements in the inner list, all the way down.
>Not... |
def build_graph(projects, deps):
g = {}
for p in projects:
g[p] = (set(), set())
for d in deps:
g[d[0]][0].add(d[1])
g[d[1]][1].add(d[0])
return g
def build_order(projects, deps):
g = build_graph(projects, deps)
result = []
while g:
buff = []
for p i... |
class Solution:
# @param {integer[]} nums
# @return {boolean}
def containsDuplicate(self, nums):
tb = set()
for n in nums:
if n in tb:
return True
tb.add(n)
return False
|
#!/usr/bin/env python
# MIT License
#
# Copyright (c) 2019 iAchieved.it
#
# 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... |
html_tags = ['<!--...-->', '<!DOCTYPE>', '<a>', '<abbr>', '<acronym>', '<address>', '<applet>', '<area>', '<article>', '<aside>', '<audio>', '<b>', '<base>', '<basefont>', '<bdi>', '<bdo>', '<big>', '<blockquote>', '<body>', '<br>', '<button>', '<canvas>', '<caption>', '<center>', '<cite>', '<code>', '<col>', '<colgrou... |
class cacheFilesManager:
configFile = False
cacheRootPath = ''
cacheFileExtension = '.dat'
resourcesRootPath = ''
def createCacheFiles (self, fileInfo):
raise NotImplementedError
def deleteCacheFiles (self, fileInfo):
raise NotImplementedError
def getCacheFile (self... |
# Python - 3.4.3
def circleArea(r):
return (type(r) in [int, float]) and (r > 0) and round(r * r * 3.141592653589793, 2)
|
response = 'yes','no'
print(response)
('yes', 'no')
if input('control!') == response:
print('DESIST!')
|
# Description: Unpack into I(+) and I(-) for a specified Miller array.
# Source: NA
"""
Iobs = miller_arrays[${1:0}]
i_plus, i_minus = Iobs.hemispheres_acentrics()
ipd = i_plus.data()
ip=list(ipd)
imd = i_minus.data()
im = list(imd)
len(im)
Iobs.show_summary()
print(Iobs.info())
print(Iobs.observation_type())
"""
... |
def main():
char = ['zero','one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
num = list(input())
sum =0
for i in range(0,len(num)): sum=sum+int(num[i])
sum = str(sum)
for i in range(0,len(sum)):
print(char[int(sum[i])],end='')
if i!= len(sum)-1:
... |
# -*- coding: utf-8 -*-
nome = input()
salario = input()
vendas = input()
salario, vendas = float(salario), float(vendas)
print("TOTAL = R$ %.2f" % float(salario + (vendas*0.15)))
|
#coding=utf-8
def evaluate():
print('eval')
return 1
maxEvalScore = 0
a1, a2, a3, a, b = 1.0, 1.0, 1.0, 1.0, 1.0
for index, var in enumerate([a1, a2, a3, a, b]):
for k in range(10, 0, -1):
# m = var
var = k / 10
m = [a1, a2, a3, a, b][index]
[a1, a2, a3, a, b][index] =... |
playerage = 9
if playerage>10:
print("You are too old to play this game")
if playerage<8:
print("You are too young to play this game") |
"""
The MIT License (MIT)
Copyright (c) 2017 Johan Kanflo (github.com/kanflo)
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, ... |
class Token:
def __init__(self, token_type, text_position, byte_position, value=None):
self.type = token_type
self.text_position = text_position
self.byte_position = byte_position
self.value = value
|
""" Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero
até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso."""
#Tuplas por extensão de 0 a 20
extenso = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'N... |
"""
You are given an array arr having n integers. You have to find the maximum sum of contiguous subarray among all the
possible subarrays.
This problem is commonly called as Maximum Subarray Problem. Solve this problem in O(n logn) time, using Divide and
Conquer approach.
"""
def maxCrossingSum(arr, start, mid, stop)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__all__ = ["api_url"]
api_url = lambda e: "https://api.foursquare.com/v2/{0}".format(e)
|
p_types = {
"AD": "North West",
"AC": "North East",
"BD": "South West",
"BC": "South East"
}
p_type_descr = {
"AD": "\nAssertive, Decisive, Flexible, Creative, Adventurous.",
"AC": "\nAssertive, Decisive, Structured, Detailed, Organized.",
"BD": "\nFriendly, Caring, Flexible, Creative, Adve... |
#!/usr/bin/env python3
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
def _better_aspect(row1,row2,aspect):
if aspect[0] == '>':
return float(row1[aspect[1:]]) >= float(row2[aspect[1:]])
else:
return float(row1[aspect[1:]]) <= float(row2[aspect[1:]])
def paretoOptimize(data,aspects):
... |
def waitToTomorrow():
"""Wait to tommorow 00:00 am"""
tomorrow = datetime.datetime.replace(datetime.datetime.now() + datetime.timedelta(days=1),
hour=0, minute=0, second=0)
delta = tomorrow - datetime.datetime.now()
time.sleep(delta.seconds)
|
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
"""
1 2 3 2
[1,1,1,1,1]
2 2 2 2
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
... |
#!/usr/bin/env python
# encoding: utf-8
"""
sqrt.py
Created by Shengwei on 2014-07-15.
"""
# https://oj.leetcode.com/problems/sqrtx/
# tags: easy / medium, numbers, search
"""
Implement int sqrt(int x).
Compute and return the square root of x.
"""
class Solution:
# @param x, an integer
# @return an integer... |
# Complex prepositions of three words etc. в зависимости от
PREP_POSTAGS = ('ADP',)
def get_children(word_num, syntax_dep_tree):
return [child_number for child_number, child_syntax in enumerate(syntax_dep_tree)
if child_syntax.parent == word_num]
class IsComplexPreposition:
COMPLEX_PREPS = [
... |
class ExtrusionObject(RhinoObject):
# no doc
def DuplicateExtrusionGeometry(self):
""" DuplicateExtrusionGeometry(self: ExtrusionObject) -> Extrusion """
pass
ExtrusionGeometry = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Get: Extr... |
"""
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
The number of the nodes in the tree is in the range [0, 100].
-100 <= N... |
"""
The more input features the more parameter saving
4: 28 less params
64: 448 less params
"""; |
class GeorgeStrategyLevel3:
def __init__(self, player_num):
self.player_index = player_num
self.name = 'delayed_flank'
self.delayed_count = 0
self.flank_count = 0
self.flank_turn = None
self.flank_started = False
self.turn_count = 1
self.movement = 1
... |
mapping = {
"settings": {
"index": {
"max_result_window": 15000,
"number_of_replicas": 1,
"number_of_shards": 1,
"max_ngram_diff": 10
},
"analysis": {
"analyzer": {
"default": {
"type": "custom",
... |
""" Make a list of the numbers from one to one million,
and then use a for loop to print the numbers """
million = list(range(1000001))
for number in million:
print(number) |
# Inplace operator tests
# This originally from byterun was adapted from test_base.py
"""This program is self-checking!"""
x, y = 2, 3
x **= y
assert x == 8 and y == 3
x *= y
assert x == 24 and y == 3
x //= y
assert x == 8 and y == 3
x %= y
assert x == 2 and y == 3
x += y
assert x == 5 and y == 3
x -= y
assert x == 2 ... |
'''
You are given coins of different denominations and a total amount of money.
Write a function to compute the number of combinations that make up that amount.
You may assume that you have infinite number of each kind of coin.
Example 1:
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class UserInfo(object):
name = '两点水'
class UserInfo(object):
def __init__(self, name):
self.name = name
class UserInfo(object):
def __init__(self, name, age, account):
self.name = name
self._age = age
self.__account = account... |
variable_list = [
{"value": {"value": "var1_new_val"}, "context": "DefaultProfile", "name": "var1"},
{"value": {"value": "var2_new_val"}, "context": "DefaultProfile", "name": "var2"},
]
|
class Page:
def __init__(self, start: int, end: int, step: int):
self.last_start = start
self.start = start
self.end = end
self.step = step
def next(self):
self.start += self.step
if self.start < self.start + self.step > self.end:
self.start = self.e... |
# SPDX-License-Identifier: MIT
# This module exists to solve circular dependencies between xbstrap.vcs_util
# and xbstrap.base; however, moving all exceptions here casues a new circular
# dependency: ExecutionFailureError needs Action.strings, defined in
# xbstrap.base, but xbstrap.base needs xbstrap.exceptions (this ... |
class Node(object):
def __init__(self, val):
self.val = val
self.children = []
def f(root, deletions):
if not root:
return
q = [root]
ans = []
if root.val not in deletions:
ans.append(root.val)
while q:
node = q.pop()
children = node.children
... |
__docformat__ = 'epytext en'
__doc__='''
European river Information System messages
@see: NMEA strings at U{http://gpsd.berlios.de/NMEA.txt}
@see: Wikipedia at U{http://en.wikipedia.org/wiki/Automatic_Identification_System}
@license: Apache 2.0
@copyright: (C) 2006
'''
|
def min_distance(polygon, point):
"""
Return the minimum distance between a point and a polygon edge
"""
dist = polygon.exterior.distance(point)
for interior in polygon.interiors:
dist = min(dist, interior.distance(point))
return dist |
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
#
# Given a string, find the length of the longest substring without repeating characters.
# For example, the longest substring without repeating letters for "abcabcbb" is "abc",
# which the length is 3. For "bbbbb" the longest substring is... |
'''
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input:
3
Output:
3
Example 2:
Input:
11
Output:
0
Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9... |
# -*- coding: utf-8 -*-
{
'name': "Lycée",
'version': '1.0.0',
'depends': ['base'],
'author': "Lucas Ramos Paiva",
'website': "https://github.com/lucrp/lycee/",
'category': 'Inventory',
'description': "Ce module sert à gérer les classes, les étudiants et les professeurs d'un Lycée",
'lic... |
def merge_sorted(arr_1, arr_2):
merged_array = list()
ind_1, ind_2 = 0, 0
while ind_1 < len(arr_1) and ind_2 < len(arr_2):
if arr_1[ind_1] <= arr_2[ind_2]:
merged_array.append(arr_1[ind_1])
ind_1 += 1
else:
merged_array.append(arr_2[ind_2])
ind... |
#
# PySNMP MIB module APDD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APDD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:23:10 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:1... |
class FpolicyServerStatus(basestring):
"""
Status
Possible values:
<ul>
<li> "connected" - Server Connected,
<li> "disconnected" - Server Disconnected,
<li> "connecting" - Connecting Server,
<li> "disconnecting" - Disconnecting Server
</ul>
"""
@staticmethod
... |
class RemoveAmountController:
def __init__(self, remove_amount_use_case):
self.remove_amount_use_case = remove_amount_use_case
def route(self, body):
if body is not None:
product_id = body["id"] if "id" in body else None
amount_to_remove = body["amount_to_remove"] if "a... |
# Common configuration options
# Annotation categories for COCO output (TODO: move to different file)
COCO_CATEGORIES = [
{
"id": 0,
"name": "Paragraph",
"supercategory": None
},
{
"id": 1,
"name": "Title",
"supercategory": None
},
{
"id": 2,
"name":... |
'''
Example-related classes.
@author: anze.vavpetic@ijs.si
'''
class Example:
'''
Represents an example with its score, label, id and annotations.
'''
ClassLabeled = 'class'
Ranked = 'ranked'
def __init__(self, id, label, score, annotations=[], weights={}):
self.id = id
self.... |
#!/usr/local/bin/python3
"""Task
A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence.
Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, ... |
"""
Reach a Number
You are standing at position 0 on an infinite number line. There is a goal at position target.
On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps.
Return the minimum number of steps required to reach the destination.
Example 1:
Input: target =... |
class SparseVector:
def __init__(self, nums: List[int]):
# self.data = {}
# for idx, val in enumerate(nums):
# if val > 0:
# self.data[idx]=val
self.data = []
for idx, val in enumerate(nums):
if val > 0:
self.d... |
class FirstHundredGenerator():
def __init__(self):
self.number = 0
def __next__(self): #Permite hacer next(object)
if self.number < 100:
current = self.number
self.number += 1 # Incrementa pero devuelve el anterior
return current
else:
rai... |
class Colors():
"""
Colors which boil down to RGB tuples
"""
Black = (0, 0, 0)
Medium_Purple = (106, 90, 205)
Neon_Cyan = (8, 247, 254)
Neon_Green = (57, 255, 20)
Neon_Magenta = (255, 29, 206)
Neon_Orange = (252, 76, 2)
Neon_Yellow = (255, 239, 0)
Red = (255, 0, 0)
White... |
__author__ = 'kemi'
# Plugin globals
SERVICE_COMMANDS = 'service.commands.'
PACKAGE_COMMANDS = 'package.commands'
INSTALL = 'install '
REMOVE = 'remove '
# Install commands
APT_GET = 'sudo apt-get -y '
APT_GET_UPDATE = 'sudo apt-get update'
DPKG = 'sudo dpkg -i '
YUM = 'sudo yum -y '
APT_SOURCELIST_DIR = '/etc/apt/... |
def is_palindrome(text) :
""" Takes in a string and determines if palindrome. Returns true or false. """
if len(text) == 1 :
return True
elif len(text) == 2 and text[0] == text[-1] :
return True
elif text[0] != text[-1] :
return False
elif text[0] == text[-1] :
is_palindrome(text[1:-1])
return ... |
'''
Parse curry (lisp) code.
'''
def remove_comment(line):
if ';' not in line:
return line
else:
return line[:line.find(';')]
def typify(item):
'''
Error-free conversion of an abitrary AST element into typed versions
i.e. ['X', '1'] becomes ['X', 1] where the second element is conv... |
#!/usr/local/bin/python
class ParsingExpression(object):
def __repr__(self):
return self.__str__()
def __or__(self,right):
return Ore(self, pe(right))
def __and__(self,right):
return seq(self,pe(right))
def __xor__(self,right):
return seq(self,lfold("", pe(right)))
d... |
# last bit in the foreground map is 2**6
LMC_VAL = 2**7
HYPERLEDA_VAL = 2**9
GAIA_VAL = 2**10
DES_STARS_VAL = 2**11
NSIDE_COVERAGE = 32
NSIDE = 16384
FOOTPRINT_VAL = 2**0
# Hyperleda
HYPERLEDA_RADIUS_FAC = 1
# HYPERLEDA_RADIUS_FAC = 2
HYPERLEDA_MINRAD_ARCSEC = 0.0
# HYPERLEDA_MINRAD_ARCSEC = 10
# Gaia
GAIA_RADIUS... |
class Action:
def __init__(self, number, values):
self.number = number
self.values = values
|
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
visited, count, graph = [False for _ in range(n)], 0, defaultdict(set)
def dfs(i):
for j in graph[i]:
if not visited[j]:
visited[j] = True
dfs(j)
... |
#=========================
# Weapon List
#=========================
stick = {'name':'Stick','damage':1, 'description':'A wooden stick.... Maybe it will help'}
club = {'name':'Club', 'damage':2, 'description': 'It is a wooden club to swing around'}
woodenSword = {'name':'Wooden Sword', 'damage':3, 'description':'I... |
{
"targets": [
{
"variables": {
"cpp_base": "./src/cpp/"
},
"target_name": "uTicTacToe",
"sources": [
"<(cpp_base)node-driver.cpp",
"<(cpp_base)UltimateTicTacToe.cpp",
"<(cpp_base)UltimateTicTacTo... |
# coding=utf-8
# Copyright 2020 Heewon Jeon. All rights reserved.
#
# 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 app... |
#AUTHOR: Farrah Akram
#Python3 Concept: Simple ATM in Python
#GITHUB: https://github.com/krosskid12
while True:
balance=10000;
print(" <<-- Welcome to Github ATM -->> ")
print("""
1) Balance Check
2) Withdraw Balance
... |
class Restaurante():
"""Uma classe para descrever restauranes."""
def __init__(self, nome, cozinha):
self.nome = nome
self.cozinha = cozinha
self.num_atendimento = 0
def descricao(self):
print(f'\nNome do restaurante: {self.nome}')
print(f'Tipo de cozinha: {self.coz... |
#!/usr/bin/python
"""Const values"""
CONFIG_PATH_NAME = 'configs'
VERSIONS_FILENAME = 'app_version'
VERSIONS_FILENAME_EXT = ".json"
APPS_METADATE_FILENAME = 'meta_'
TMP_IGNORE_DIR = 'ignore_tmp'
APP_MANIFEST_HEADERS = ['commitid', 'application', 'whitelist', 'blacklist', 'method']
LOGPATH = '/var/appetite'
META_DIR ... |
class Node:
def __init__(self, data):
self.data = data
self.nxt = None
def add(self, data):
nxt = self
while nxt.nxt is not None:
nxt = nxt.nxt
nxt.nxt = Node(data)
return nxt.nxt
def join(self, node):
self.nxt = node
def get_size(n):
count = 1
while n.nxt is not No... |
# -*- coding: utf-8 -*-
"""
二叉树:填充每个节点的下一个右侧节点指针
https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
"""
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = righ... |
'''
Tuple - An ordered set of data
1. They are immutable, not changeable*.
2. Parenthesis are not necessary, it is there only for avoiding syntactic ambiguity(i.e x=1,2 is the same as x=(1,2s))
3. t = 'a', 'b', 'c' 3-ary tuple
print(t)
We need to make the things good.
4. We can access them like lists using... |
"""
In this exercise you are helping your younger sister edit her paper for school.
The teacher is looking for correct punctuation, grammar, and excellent word choice.
You have four tasks to clean up and modify strings.
"""
def capitalize_title(title: str) -> str:
"""
:param title: str title str... |
with open('./Gonduls/13/input.txt', 'r') as inputf:
lista= list(inputf.read().split('\n'))
lista[1] = lista[1].split(',')
buses =[]
for i, elem in enumerate(lista[1]):
if (elem != 'x'):
buses.append([int(elem), i, True])
times = 0
step = 1
i = 0
notfound= True
while(notfound):
# checks i... |
exit_list= [3602, 1174, 1194, 818, 878, 4296]
total_example = 0
for number in exit_list:
total_example += number
for index, number in enumerate(exit_list):
print("layer:", index+1, "exit %:", number/total_example*100) |
def multiply1(x,y):
n = len(x)
if (n==1):
return x[0]*y[0]
s = int(n/2)
xl = x[0:s]
xh = x[s:]
yl = y[0:s]
yh = y[s:]
p1 = multiply(xl,yl)
p2 = multiply(xh,yh)
xz = [x1 + x2 for x1, x2 in zip(xl, xh)]
yz = [y1 + y2 for y1, y2 in zip(yl, yh)]
p3 = mult... |
b = "this is file 'b'"
def b_func():
inside_b_func = 'inside b_func()'
print("b")
|
# Copyright 2021 Edoardo Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
'''
MIT License
Copyright (c) 2019 Keith Christopher Cronin
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, ... |
"""Dosya İşlemleri - Dosya Güncellemek"""
"""
with open('asd.txt', 'r+') as f:
# eski veri değişkeninde saklansın
eski_veri = f.read()
# Dosyanın imleci en başına gitsin
# Amacım yukarıya eklemek olduğu için en başa gönderdim.
f.seek(0)
# Şimdi verileri tekrardan yazma işlemi yapıyorum.
# Ye... |
msg1 = 'Digite um número inteiro: '
n1 = int(input(msg1))
msg2 = 'Digite outro número inteiro: '
n2 = int(input(msg2))
s = n1 + n2
print('A soma entre \033[1:34m{0}\033[m e \033[1:31m{1}\033[m vale \033[1:32m{2}\033[m.'.format(n1, n2, 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 sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
stack=[(root, 1)]
output=0
... |
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
i=0
t=0
if not nums:
return 0
res=None
for j,x in enumerate(nums):
t+=x
while t>=s:
... |
class DataTypeTemplate(object):
"""Defines a DataType template.
The template defines a name and all the paths to the "data" folders in a KiProject.
"""
_templates = []
def __init__(self, name, description, paths, is_default=False):
"""Instantiates a new instance.
Args:
... |
config = {}
def set_config(conf):
global config
config = conf
def get_config():
global config
return config
def get_full_url(relative_url):
return '%s/api/%s/%s' % (config['HOST'], config['API_VERSION'], relative_url)
def get_headers():
return {
'Accept': 'application/json',
# 'Authoriza... |
class UsiError(Exception):
def __init__(self, message, error_code):
self.message = message
self.error_code = error_code
|
# -*- coding: UTF-8 -*-
# Copyright 2017 Luc Saffre
# License: BSD (see file COPYING for details)
"""Extended and specific plugins for Lino Noi.
.. autosummary::
:toctree:
contacts
amici
"""
|
###
# range()
###
# 1. create a list of integers from 0 to n
# l = list(range(10))
# print(l)
# # 2. create a list of integers from 3 to 10
# l2 = list(range(3,10))
# print(l2)
# # 3. create a list of integers from 0, 10 with step size of 2
# # 0, 2, 4, ...
# l3 = list(range(0,10,2))
# print(l3)
# # 4. create ... |
class ZenHttpException(Exception):
"""Exception with HTTP status code."""
def __init__(self, status):
"""Creates an instance.
Args:
status (int): HTTP status code.
"""
self.status = status
|
# 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
# 1. Linear Time
class Solution:
def countNodes(self, root: TreeNode) -> int:
return 1 + self.countNodes(root.right) + self.c... |
class FeatureImportance(object):
def __init__(self, importance=0, importance_2=0, main_type='split'):
self.legal_type = ['split', 'gain']
assert main_type in self.legal_type, 'illegal importance type {}'.format(main_type)
self.importance = importance
self.importance_2 = importance_... |
"""
pygments.lexers._scheme_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Scheme builtins.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
# Autogenerated by external/scheme-builtins-generator.scm
# using Guile 3.0.5.130-5a1e7.
scheme_ke... |
# By default the LibriSpeech corpus is set.
path_to_corpus = '../audio_data/LibriSpeech/'
# By default librispeech file-name has been set. Please modify if you are using some other corpus
speaker_meta_info_file_name='SPEAKERS.TXT'
# Each of the subset will have deifferent output sub-folder identified by subset-typ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
ans = 0
while head:
ans = 2*ans + head.val
head = head.next
retu... |
def MySort(UnsortedArray):
n=len(UnsortedArray)
if n==1:
SortedArray=UnsortedArray
else:
midpoint=n//2
Array1=MySort(UnsortedArray[0:midpoint])
Array2=MySort(UnsortedArray[midpoint:n])
i=0;
j=0;
SortedArray=[]
while i<midpoint and j<n-midpoint:... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList1(self, head: Optional[ListNode]) -> Optional[ListNode]:
new_head = None
node = head
while n... |
class Var(object) :
def __init__(self, name) :
self.name = name
def __str__(self) :
return str(self.name)
class Data(object) :
def __init__(self, x) :
self.x = x
def __str__(self) :
return str(self.x)
class Fun(object) :
def __init__(self, var, body) :
... |
class Url:
"""
This module implements useful methods that manipulate urls, used in the
project.
"""
_github_main_page_url = 'https://github.com'
_googlecache_urlprefix = 'http://webcache.googleusercontent.com/search?q='
@staticmethod
def github_url(relative_url):
"""
... |
op = input()
ops = {}
for i in range(len(op)):
if op[i + 1] == ':':
ops[op[i]] = True
elif op[i + 1] != ':' and op != ':':
ops[op[i]] = False
n = int(input())
for idx in range(1, n + 1):
ans = ''
print("Case {0}: {1}".format(idx, ans))
|
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
tree = [[] for _ in range(n)]
# a --> b
for a, b in connections:
tree[a].append((b, 1))
tree[b].append((a, 0))
self.ans = 0
def dfs(u, parent):
for v, d in t... |
# Examples to see class inheritance
class Car:
""" A class that models a real life car in a oversimplified way."""
def __init__(self, make, model, year):
"""Function to store key attributes of the car."""
self.make = make
self.model = model
self.year = year
se... |
"""
Given an array of positive and negative numbers,
arrange them in an alternate fashion such that every
positive number is followed by negative and vice-versa
maintaining the order of appearance.
"""
def find_first_positive(lst):
j = 0
pivot = 0
for i in range(len(lst)):
if lst[i] < pivot:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.