content
stringlengths
7
1.05M
bash(''' echo "hello" ''') bash(''' for i in $(seq 1 10); do echo $i sleep 2 done ''')
class Noeud: '''Noeud d'un arbre binaire''' def __init__(self, valeur=None): '''Créé un nœud avec une valeur (None par défaut)''' # valeur (object) : valeur a stocker dans le nœud. On présume que valeur # implémente une méthode pour être comparée à elle-même self.valeur = va...
# This script generates a theorem for them Z3 SAT solver. The output of this program # is designed to be the input for http://rise4fun.com/z3 # The output of z3 is the coordinates of the queens for a solution to the N Queen problem :) #Prints an assert statement def zassert(x): print("( assert ( {} ) )".format(x)...
# cook your dish here try: t = int(input()) for _ in range(t): r, c, k = map(int, input().rstrip().split(' ')) if r <= k: start_row = 1 else: start_row = r-k if c <= k: start_col = 1 else: start_col = c-k if r+k >= 8...
""" 3047 : ABC URL : https://www.acmicpc.net/problem/3047 Input : 1 5 3 ABC Output : 1 3 5 """ a = list(sorted(map(int, input().split()))) order = input() b = [] for o in order: b.append(a[ord(o) - ord('A')]) print(' '.join(str(c) for c in b))
class Solution: def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ sums = [0] s = 0 for num in nums: s += num sums.append(s) for i in range(len(sums)): for j in range...
'''Defines data and parameters in an easily resuable format.''' # Common sequence alphabets. ALPHABETS = { 'dna': 'ATGCNatgcn-', 'rna': 'AUGCNaugcn', 'peptide': 'ACDEFGHIKLMNPQRSTVWYXacdefghiklmnpqrstvwyx'} COMPLEMENTS = { 'dna': {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'N': 'N', 'a': 't', ...
# Created by MechAviv # White Heaven Sun Damage Skin | (2433828) if sm.addDamageSkin(2433828): sm.chat("'White Heaven Sun Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
def expose(board, x, y): if not board[y][x].flagged: board[y][x].exposed = True #debug print(x, y, sep='\t') if x == 0 or x == len(board[0]) - 1 or y == 0 or y == len(board) - 1 or board[y][x].mine: return 0 if board[y][x].neighbours == 0: if board[y-1][x-1].exposed is Fals...
number = 5 numbers = [1,2,3,4,5] # if statement if number == 5: print(number) if len(numbers) == 5: print(numbers[3]) if number in numbers: # if 3 in [1,2,3,4,5] print("3 is here") # elif and else statement if number == 3: print("is 3") elif number == 5: print("is 5") else: print("not 3 & 5...
memo = { 0: 0, 1: 1, 2: 1, } def fib(n): if n in memo: return memo[n] val = fib(n-1) + fib(n-2) memo[n] = val return val print(fib(35))
class Screen(object): """ Represents a display device or multiple display devices on a single system. """ def Equals(self,obj): """ Equals(self: Screen,obj: object) -> bool Gets or sets a value indicating whether the specified object is equal to this Screen. obj: The object to compare ...
# Esto es un comentario # enteros - int my_int = 42 # reales - float my_float = 3.14 # strings - str my_str = 'string con comilla simple' my_str_2 = "string con comilla doble" my_str_3 = """string multilinea""" """Los strings multilinea pueden servir para poner comentarios de varias líneas""" # booleans - bool my...
num = int(input('\033[1;31mMe diga um número \033[m')) resultado = num % 2 par = (0) impar = (1) if resultado == impar: print('\033[1;32mO número\033[m \033[1;31m{}\033[m \033[1;34mé impar\033[m'.format(num)) else: print('\033[1;33mO número\033[m \033[1;31m{}\033[m \033[1;34mé par\033[m'.format(num))
# coding: utf-8 __version__ = '0.12.0'
# -*- coding: utf-8 -*- # Caching # https://docs.djangoproject.com/en/3.2/topics/cache/ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', }, 'staticfiles': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache...
x, a, b = map(int, input().split()) if b <= a: print('delicious') elif b - a <= x: print('safe') else: print('dangerous')
class EvaluatorTestCases: expressions = [ ("1 2 + 2.5 * 2 5 SUM", 14.5, float, 3), ("1 2 3 SUM 4 5 SUM 6 7 SUM", sum(range(8)), int, 3), ("1 2 3 SUM 4 5 SUM 6 7 SUM 8.5 *", sum(range(8)) * 8.5, float, 4), ] not_ok = [ """ void test(){ int a; int b...
class Args(object): def __init__(self): self.seed = 0 self.experiment = None self.network = None self.approach = None self.parameter = [] self.taskcla = None self.comment = None self.log_dir = None global args args = Args()
list1=[12,-7,5,64,-14] for num in list1: if num>=0: print(num,end=" ") list2=[12,14,-95,3] for num in list2: if num>=0: print(num,end=" ")
#Three character NHGIS codes to postal abbreviations state_codes = { '530':'WA', '100':'DE', '110':'DC', '550':'WI', '540':'WV', '150':'HI', '120':'FL', '560':'WY', '720':'PR', '340':'NJ', '350':'NM', '480':'TX', '220':'LA', '370':'NC', '380':'ND', '310':'NE', '470':'TN', '360':'NY', '420':'PA', '02...
# função usada abaixo 'print()' é usada para exibir ou imprimir mensagens no console. # Iteiros | Int print(10) # Será exibido no console o numero 10 # Ponto Flutuante | Float print(9.5) # Cadeia de caracteres | Strings cadeia_de_caracter = "Olá Mundo!" print(cadeia_de_caracter) # Boleano | Boolean valor_verdadeiro...
# Marcelo Campos de Medeiros # ADS UNIFIP # Exercicios Com Strings # https://wiki.python.org.br/ExerciciosComStrings ''' Leet spek generator. Leet é uma forma de se escrever o alfabeto latino usando outros símbolos em lugar das letras, como números por exemplo. A própria palavra leet admite muitas variações, como l33t...
def uniquePaths(m: int, n: int) -> int: dp = [[0 for _ in range(m)] for _ in range(n)] for i in range(m): dp[0][i] = 1 for j in range(n): dp[j][0] = 1 for i in range(1, n): for j in range(1, m): dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return...
# -*- coding: utf-8 -*- """ Python Flight Mechanics Engine (PyFME). Copyright (c) AeroPython Development Team. Distributed under the terms of the MIT License. Constant variables ------------------ Sources: [1] - COESA standard - U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, D.C., ...
a,b,c = input().split() #한번에 여러개의 입력을 받기 위해 .split() a = int(a) b = int(b) c = int(c) # 파이썬은 입력을 받을 때 문자열로 입력을 받기 때문에 int로 형변환 if a>b: print(">") elif a==b: print("==") else: print("<")
if __name__ == "__main__": base_path = "/data4/dheeraj/hashtag/all/Twitter/" f_tweets = open(base_path + "train_post.txt", "r") f_tags = open(base_path + "train_tag.txt", "r") tweets = f_tweets.readlines() tags = f_tags.readlines() f_tags.close() f_tweets.close() tweets = tweets[:100] ...
# -*- coding: utf-8 -*- """Bandit directory containing multi-armed bandit implementations of BLA policies in python. **Files in this package** * :mod:`moe.bandit.bla.bla`: :class:`~moe.bandit.bla.bla.BLA` object for allocating bandit arms and choosing the winning arm based on BLA policy. """
# # PySNMP MIB module IPMROUTE-STD-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/IPMROUTE-STD-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:18:06 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)...
class Solution: def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ words = str.split(' ') if len(pattern) != len(words) or len(set(pattern)) != len(set(words)): return False d = dict() for i...
# Problem 4: Dutch National Flag Problem def sort_zero_one_two(input_list): # We define 4 variables for the low, middle, high, and temporary values lo_end = 0 hi_end = len(input_list) - 1 mid = 0 tmp = None if len(input_list) <= 0 or input_list[mid] < 0: return "The list is either empty...
# -*- coding: utf-8 -*- """ equip.visitors.blocks ~~~~~~~~~~~~~~~~~~~~~ Callback the visit basic blocks in the program. :copyright: (c) 2014 by Romain Gaucher (@rgaucher) :license: Apache 2, see LICENSE for more details. """ class BlockVisitor(object): """ A basic block visitor. It first receives the...
# coding=utf-8 BTC_BASED_COINS = { 'PIVX': { 'ip': '', 'port': 3000, 'url': '' } } ETHEREUM_BASED_COINS = ['ETH', 'BNB', 'SENT'] ADDRESS = ''.lower() PRIVATE_KEY = '' FEE_PERCENTAGE = 0.01 TOKENS = [ { 'address': ADDRESS, 'decimals': 18, 'logo_url': 'https://...
def get_poisoned_worker_ids_from_log(log_path): # Unchanged from original work """ :param log_path: string """ with open(log_path, "r") as f: file_lines = [line.strip() for line in f.readlines() if "Poisoning data for workers:" in line] workers = file_lines[0].split("[")[1].split("]")[...
# It must be here to retrieve this information from the dummy core_universal_identifier = 'd9d94986-ea14-11e0-bd1d-00216a5807c8' core_universal_identifier_human = 'Consumer' db_database = "WebLabTests" weblab_db_username = 'weblab' weblab_db_password = 'weblab' debug_mode = True ######################### # G...
__author__ = "Shaban Hassan [shaban00]" """ Regiser all routes for flask socket io """ # SOCKET_EVENTS = [ # { # "event": "connect", # "func": "connect", # "namespace": "namespace" # } # ] SOCKET_EVENTS = []
if __name__ == '__main__': n, m = list(map(int, input().split(" "))) arr = list(map(int, input().split(" "))) set_a = set(map(int, input().split(" "))) set_b = set(map(int, input().split(' '))) print(sum([1 if e in set_a else -1 if e in set_b else 0 for e in arr]))
""" You are given an m x n 2D image matrix (List of Lists) where each integer represents a pixel. Flip it in-place along its horizontal axis. Example: Input image : 1 1 0 0 Modified to : 0 0 1 1 """ def flip_horizontal_axis(matrix): """ Returns a list...
# Given a binary tree, find a minimum path sum from root to a leaf. # For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15. # 10 # / \ # 5 5 # \ \ # 2 1 # / # -1 class Node: def __init__(self, value, left=None, right=None): self.value ...
expected_output = { "interface": { "GigabitEthernet3.90": { "interface": "GigabitEthernet3.90", "neighbors": { "FE80::5C00:40FF:FEFF:209": { "age": "22", "ip": "FE80::5C00:40FF:FEFF:209", "link_layer_address"...
class Solution: def rob(self, nums: List[int]) -> int: dp = [num for num in nums] for i in range(2, len(nums)): dp[i] += max(dp[:i-1]) return max(dp)
print("Statements") print("Statement does something, while expression is something") 2*2 # this is an expression, it will not do anything if not using interactive interpreter. print(2*2) #this is an statement, it does print x=3 #this is also an statement, it has no values to print out, but x is already assigned.
# This problem was recently asked by Google: # Given a sorted list, create a height balanced binary search tree, # meaning the height differences of each node can only differ by at most 1. class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left se...
# Copyright 2021 PaddleFSL Authors # # 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 wri...
#--------------------------------------------------------------------------------------------------- # Tiparoj #--------------------------------------------------------------------------------------------------- c.fonts.completion.category = "bold 8pt monospace" c.fonts.completion.entry = "8pt monospace" c.fonts.debug...
class Account: """An account has a balance and a holder. >>> a = Account('John') >>> a.holder 'John' >>> a.deposit(100) 100 >>> a.withdraw(90) 10 >>> a.withdraw(90) 'Insufficient funds' >>> a.balance 10 >>> a.interest 0.02 """ interest = 0.02 # A class ...
_base_ = 'ranksort_cascade_rcnn_r50_fpn_1x_coco.py' model = dict(roi_head=dict(stage_loss_weights=[1, 0.50, 0.25]))
{ "targets": [ { "target_name": "pcap_binding", 'win_delay_load_hook': 'true', "sources": [ "npcap_binding.cpp","npcap_session.cpp"], "include_dirs": ["npcap/Include","<!@(node -p \"require('node-addon-api').include\")"], "libraries": [ "<(module_root_dir)/npcap/Lib/x64/Packe...
class Config(object): # game setting row_size = 6 column_size = 6 piece_in_line = 4 black_first = True max_num_round = 36 # mcts temperature = 1.0 playout_times = 100 # num of simulations for each move c_puct = 5. # data num_games_per_generation = 10 ...
class TooLarge(Exception): """The input was too long.""" def __init__(self): super(TooLarge, self).__init__("That number was too large.") class ImproperFormat(Exception): """Invalid Format was given.""" def __init__(self): super(ImproperFormat, self).__init__("An Invalid Format was giv...
""" Description Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings. Please implement encode and decode Example Example1 Input: ["lint","code","love","you"] Output: ["lint","code","love","you"] Explanation: ...
# Demonstrate how to use dictionary comprehensions def main(): # define a list of temperature values ctemps = [0, 12, 34, 100] # Use a comprehension to build a dictionary tempDict = {t: (t * 9/5) + 32 for t in ctemps if t < 100} print(tempDict) print(tempDict[12]) # Merge two dictionarie...
# -*- coding: utf-8 -*- """Collection of exceptions raised by requests-toolbelt.""" class StreamingError(Exception): """Used in :mod:`requests_toolbelt.downloadutils.stream`.""" pass class VersionMismatchError(Exception): """Used to indicate a version mismatch in the version of requests requir...
class NaturalNumbers: def __init__(self): pass def get_first_n_for(self, n): # Ejemplo """ Obtener los primeros n naturales en una lista con for """ first_n = [] # Se declara una lista donde almacenaremos los numeros for i in range(n): # Se itera sobre range que ...
class Config(): def __init__(self): self.type = "a2c" self.gamma = 0.99 self.learning_rate = 0.001 self.entropy_beta = 0.01 self.batch_size = 128
width = const(7) height = const(12) data = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x10\x10\x10\x10\x00\x00\x10\x00\x00\x00\x00lHH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x14(|(|(PP\x00\x00\x00\x108@@8Hp\x10\x10\x00\x00\x00 P \x0cp\x08\x14\x08\x00\x00\x00\x00\x00\x00\x18 TH4\x00\x00\x00\x00\x10\x10\...
# 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 binaryTreePaths(self, root: TreeNode) -> List[str]: if not root: return [] result = [] ...
class Solution(object): def countComponents(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ V = [[] for _ in range(n)] for e in edges: V[e[0]].append(e[1]) V[e[1]].append(e[0]) visited = [False fo...
class Solution: def calculate(self, s: str) -> int: inner, outer, result, opt = 0, 0, 0, '+' for c in s+'+': if c == ' ': continue if c.isdigit(): inner = 10*inner + int(c) continue if opt == '+': result += outer ...
client_id="You need to fill this" client_secret="You need to fill this" user_agent="You need to fill this" username="You need to fill this" password="You need to fill this"
def by_independent_sets(independent_sets): """独立集合族Tにより与えられた集合が基拡大集合か否か判定する関数を返す関数 Args: independent_sets: 独立集合族T Returns: 与えられた集合Xが基拡大集合か否か判定する関数 True if |X| ≧ max{|I|: I ∈ T} False otherwise """ return lambda X: len(X) >= max(len(I) for I in independent_sets) def by_bases(bases): """基族Dにより与えられた集合が基...
targets = [int(target) for target in input().split()] command = input().split() while "End" not in command: index = int(command[1]) if "Shoot" in command: power = int(command[2]) if 0 <= index < len(targets): targets[index] -= power if targets[index] <= 0: ...
class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def ...
letter="Sai Teja"; for i in letter: print(i);
class Club: total = 140 start_address = 751472 size = 88 max_name_size = 48 max_tla_size = 3 def __init__(self, option_file, idx): self.option_file = option_file self.idx = idx self.set_addresses() self.set_name() self.set_tla() def set_addresses(se...
def add_one(num): return (-(~num)) print(add_one(3)) print(add_one(99))
#encode.py #ASCII print(ord('A')) print(ord('a')) print(chr(65)) #UTF-8 s = "世界,你好!" bs = s.encode("utf-8") print(bs) print(bs.decode("utf-8")) print(bs.encode("gbk"))
# Global constants that will be used all along the program # Port paths ODRIVE_USB_PORT_PATH = "" REHASTIM_USB_PORT_PATH = "" USB_DRIVE_PORT_PATH = ""
#!/usr/bin/env python3 class Solution: def xorOperation(self, n: int, start: int) -> int: res = start for i in range(1,n): res^=start+2*i return res ## Intuition: # # - As per the requirements of the problem, we don't need to return the array itself. # - So, we can free up any ...
"""Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada.""" n = int(input('Digite um número inteiro para ver sua tabuada: ')) #print(' {} \n {} \n {} \n {} \n {} \n {} \n {} \n {} \n {} \n {}'.format(n * 1, n * 2, n * 3, n * 4, n * 5, n * 6, n * 7, n * 8, n * 9, n * 10)) print('-'*12) pr...
# dude, this is a comment # some more hello def dude(): yes awesome; # Here we have a comment def realy_awesome(): # hi there in_more same_level def one_liner(): first; second # both inside one_liner back_down last_statement # dude, this is a comment # some more hello if 1:...
# https://open.kattis.com/problems/oddgnome n = int(input()) for _ in range(n): gnomes = list(map(int, input().split()))[1:] for i in range(1, len(gnomes) - 1): if gnomes[i + 1] > gnomes[i - 1]: if gnomes[i] < gnomes[i - 1] and gnomes[i] < gnomes[i + 1]: print(i + 1) ...
''' ## Questions ### 23. [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. **Example:** ``` Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 ''' ## Solutions # Definit...
# coding=utf-8 # # @lc app=leetcode id=144 lang=python # # [144] Binary Tree Preorder Traversal # # https://leetcode.com/problems/binary-tree-preorder-traversal/description/ # # algorithms # Medium (50.28%) # Total Accepted: 312.5K # Total Submissions: 618.9K # Testcase Example: '[1,null,2,3]' # # Given a binary tr...
# Palace Oasis (2103000) | Ariant Castle (260000300) ariantCulture = 3900 if sm.hasQuest(ariantCulture): sm.setQRValue(ariantCulture, "5", False) sm.sendSayOkay("You used two hands to drink the clean water of the Oasis. " "Delicious! It quenched your thirst right on the spot.")
class Dino: @staticmethod def exe1(): print("al carajo 1") def exe2(self): print("al carajo 2") class Car(Dino): wheels = 0 def __init__(self, color, x, func): self.color = color self.f = func Car.wheels = x while (True): print("yey") Dino.exe1() din = Dino() din.exe2() f = lambda x: x+1 #print(f(2...
#!/usr/bin/python # # Copyright 2007 Google Inc. All Rights Reserved. """CSS Lexical Grammar rules. CSS lexical grammar from http://www.w3.org/TR/CSS21/grammar.html """ __author__ = ['elsigh@google.com (Lindsey Simon)', 'msamuel@google.com (Mike Samuel)'] # public symbols __all__ = [ "NEW...
# Copyright (c) 2018 - 2020 Institute for High Voltage Technology and Institute for High Voltage Equipment and Grids, Digitalization and Power Economics # RWTH Aachen University # Contact: Thomas Offergeld (t.offergeld@iaew.rwth-aachen.de) # # # This module is part of CIMPyORM. # # # CIMPyORM is licensed un...
""" Backported error classes for twisted. """ __docformat__ = 'epytext en' class VerifyError(Exception): """Could not verify something that was supposed to be signed. """ class PeerVerifyError(VerifyError): """The peer rejected our verify error. """ class CertificateError(Exception): """ We d...
alunos = {'aluno':str(input('Digite o nome do aluno: ')),'media':float(input(f'Média do aluno: '))} print(f'Nome: {alunos["aluno"]}.') print(f'Média: {alunos["media"]}.') if alunos['media'] > 7: print(f'O aluno {alunos["aluno"]} foi aprovado.') else: print(f'O aluno {alunos["aluno"]} foi reprovado.') #PODERIA ...
def test(): assert len(TRAINING_DATA) == 4, "Los datos de entrenamiento no concuerdan – esperaba 4 ejemplos." assert all( len(entry) == 2 and isinstance(entry[1], dict) for entry in TRAINING_DATA ), "Formato incorrecto de los datos de entrenamiento. Esperaba una lista de tuples dónde el segundo elem...
with open('inputs/input24.txt') as fin: raw = fin.read() def parse(raw): x = [x for x in raw.splitlines()] return x a = parse(raw) def part_1(data): dictionary = {} for a in data: e = a.count('ne') + a.count('se') w = a.count('nw') + a.count('sw') x = e + 2 * (a.count('...
num = int(input('Digite um numero: ')) tot = 0 for c in range(1, num +1): if num% c == 0 : print('\033[33m', end='') tot += 1 else: print('\033[31m',end=' ') print('{}'.format(c) , end=' ') print('\n\033[mO numero {} foi divisivel {} vezes'.format(num, tot)) if tot == 2: print('E...
__version__ = '0.3.7' __title__ = 'iam-docker-run' __description__ = 'Run Docker containers within the context of an AWS IAM Role, and other development workflow helpers.' __url__ = 'https://github.com/billtrust/iam-docker-run' __author__ = 'Doug Kerwin' __author_email__ = 'dwkerwin@gmail.com' __license__ = 'MIT' __key...
#!/bin/python3 # # Copyright (c) 2019 Paulo Vital # # 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,...
""" Module: 'uasyncio.event' on esp32 1.13.0-103 """ # MCU: (sysname='esp32', nodename='esp32', release='1.13.0', version='v1.13-103-gb137d064e on 2020-10-09', machine='ESP32 module (spiram) with ESP32') # Stubber: 1.3.4 class Event: '' def clear(): pass def is_set(): pass def set(): ...
NumbersBelow19 = ["One", "Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Ninteen"] multiplesOf10 = ["Twenty" , "Thirty" , "Fourty" , "Fifty" , "Sixty" , "Seventy" ,"Eighty" , "Ninety"] singleDigits = ["One", "Two","Thr...
num = int(input()) first = [] second = [] for i in range(num): line = input().split(' ') name = line[0] t1 = float(line[1]) t2 = float(line[2]) first.append([name, t1]) second.append([name, t2]) first.sort(key=lambda x: x[1]) second.sort(key=lambda x: x[1]) total_time = 0 squad_list_of_lists =...
def remdup(a): return list(set(a)) l=[] for i in range(0,5): l.append(input()) print(l) rev = l[::-1] print(rev) print(remdup(l)) print([i for i in range(0,10) if i%2==0])
''' Created on 1.12.2016 @author: Darren '''''' Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no duplicate exists in the array." '''
# This is Pessimistic Error Pruning. def prune(t): # If the node is a leaf node, stop pruning. if t.label != None: return L = t.leaf_sum N = t.N p = (t.RT + 0.5*L)/N # When the following condition is satisfied, # replace the subtree with a leaf node. if t.RT + 0.5 - (N*p*(1-p))*...
__author__ = 'haukurk' def log_exception(sender, exception, **extra): """ Log an exception to our logging framework. @param sender: sender @param exception: exception triggered @**extra: other params. @return: void """ sender.logger.debug('Got exception during processing: %s', exceptio...
"""Top-level package for trailscraper.""" __author__ = """Florian Sellmayr""" __email__ = 'florian.sellmayr@gmail.com' __version__ = '0.6.5'
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isCousins(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool': m = {} def traverse(node, parent=None, depth=0): ...
class Singleton(type): instance = None def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instance # Taken from https://github.com/tomerghelber/singleton-factory class SingletonFactory(type): """ ...
# Utilizando a função type, escreva uma função recursiva que imprima os elementos de uma lista # Cada elemento deve ser impresso separadamente, um por linha # Considere o caso de listas dentro de listas, como L = [1, [2, 3, 4, [5, 6, 7]]] # A cada nível, imprima a lista mais à direita, como fazemos para indentar blocos...
#To find whether the number is +ve,-ve or 0 x=int(input("Enter a number")) def check_num(x): if x>0: print("The",x,"is positive") elif x<0: print("The",x,"is negative") else: print("The",x,"is zero") check_num(x)
"""Constants for propensity_matching library.""" MINIMUM_DF_COUNT = 4000 MINIMUM_POS_COUNT = 1000 UTIL_BOOST_THRESH_1 = MINIMUM_POS_COUNT UTIL_BOOST_THRESH_2 = MINIMUM_DF_COUNT UTIL_BOOST_THRESH_3 = 50000 SAMPLES_PER_FEATURE = 100 SMALL_MATCH_THRESHOLD = 3000**3
class RequestError(Exception): """The base class for all errors.""" def __init__(self, code, error, retry_after=None): pass class Unauthorized(RequestError): """Raised if your API Key is invalid or blocked.""" def __init__(self, url, code): self.code = code self.error = 'Your...
#!/usr/bin/python3 ################################ # File Name: DocTestExample.py # Author: Chadd Williams # Date: 10/17/2014 # Class: CS 360 # Assignment: Lecture Examples # Purpose: Demonstrate PyTest ################################ # Run these test cases via: # chadd@bart:~> python3 -m doctest -v DocTestE...