content
stringlengths
7
1.05M
"""A walrus pattern looks like d := datetime(year=2020, month=m). It matches only if its sub-pattern also matches. It binds whatever the sub-pattern match does, and also binds the named variable to the entire object. """ # TODO # match group_shapes(): # case [], [point := Point(x, y), *other]: # print(f"...
test_cases = int(input()) while test_cases > 0: burles = int(input()) optimal = 0 while True: # The main logic here is to divide the burles into small parts of burles, as, that would be optimal. If Mishka sell 10 burles, he'd get one back; if less, nothing, if higher than 10 and lower than 20 th...
def MathOp(): classic_division=3/2 floor_division=3//2 modulus=3%2 power=3**2 return [classic_division, floor_division, modulus, power] [classic_division, floor_division, modulus, power]=MathOp() print(classic_division) print(floor_division) print(modulus) print(power)
""" Python implementation of a linked list """ # TODO docstrings class Node(object): def __init__(self, data=None): self.data = data self.next_node = None class LinkedList(object): def __init__(self): self.head = None self.size = 0 def __getitem__(self, index): ...
# # PySNMP MIB module Juniper-Multicast-Router-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-Multicast-Router-CONF # Produced by pysmi-0.3.4 at Wed May 1 14:03:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ve...
#!/usr/bin/env python3 """Reading in and writing out files""" def main(): # old method for opening files # requires closing the file object when done myfile = open("vendor.txt", 'r') # new method for opening files # closes file when indentation ends with open('vendor-ips.txt', 'w') as myoutfil...
# Global Moderation ACCOUNT_BAN = "ACB" ACCOUNT_UNBAN = "UBN" ACCOUNT_TIMEOUT = "TMO" SERVER_KICK = "KIK" PROMOTE_GLOBAL_OP = "AOP" DEMOTE_GLOBAL_OP = "DOP" LIST_ALTS = "AWC" BROADCAST = "BRO" REWARD = "RWD" RELOAD_SERVER_CONFIG = "RLD" # Channels LIST_OFFICAL_CHANNELS = "CHA" LIST_PRIVATE_CHANNELS = "ORS" INITIAL_CHA...
# Suppose you have a multiplication table that is N by N. That is, a 2D array # where the value at the i-th row and j-th column is (i + 1) * (j + 1) # (if 0-indexed) or i * j (if 1-indexed). # Given integers N and X, write a function that returns the number of times X # appears as a value in an N by N multiplica...
class Solution(object): def minTotalDistance(self, grid): """ :type grid: List[List[int]] :rtype: int """ # basically try to solve for median for 1D array twice vertical_list = [] horizontal_list = [] for i in range(len(grid)): for j in ran...
#!/usr/bin/env python3 -tt def doNav(defaultxml): defaultxml.write("<collection label=\"MITRE\">\n ") defaultxml.write("<view name=\"mitre\" default=\"true\" />\n ") defaultxml.write("<a href=\"http://localhost/attack-navigator/index.html\" target=\"_blank\">ATT&amp;CK® Navigator Mapping</a>\n ") de...
""" Easy 1640. [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/) You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays...
def maxSubArray(X): # Store sum, start, end result = (X[0], 0, 0) for i in range(0, len(X)): for j in range(i, len(X)): subSum = 0 for k in range(i, j + 1): subSum += X[k] if result[0] < subSum: result = (subSum, i, j) return result
# -*- coding: utf-8 -*- a = [] b = a c = [] print("id(a) = ", id(a)) print("id(b) = ", id(b)) print("id(c) = ", id(c)) a.append(1) b.append(2) c.append(3) print("id(a) = ", id(a)) print("id(b) = ", id(b)) print("id(c) = ", id(c))
def areaTriangulo(b,h): a = 0 a = (b * h) / 2 return a b = float(input('Digite a base do triangulo: ')) h = float(input('Digite a altura do triangulo: ')) print(f'A area de triangulo {b} x {h} é {areaTriangulo(b,h)}')
# encoding: utf-8 tamil = { "அ ":True, "அ ":True, "அஃகம்":True, "அஃகரம்":True, "அஃகல்":True, "அஃகுல்லி":True, "அஃகு":True, "அஃகிப்":True, "அஃகிடூ":True, "அஃகுள்":True, "அஃகேனம்":True, "அஃது":True, "அஃதும":True, "அஃபோதம்":True, "அஃறீணை":True, "அகக்கண்":True, "அகக்கரணம்":True, "அகக்...
__all__ = ('ConnectionClosed',) class ConnectionClosed(Exception): """Exception indicating that the connection to Discord fully closed. This is raised when the connection cannot naturally reconnect and the program should exit - which happens if Discord unexpectedly closes the socket during the crucia...
""" .. module:: check_in_known_missions :synopsis: Given a string, checks if it's in a list of known mission values. .. moduleauthor:: Scott W. Fleming <fleming@stsci.edu> """ #-------------------- def check_in_known_missions(istring, known_missions, exclude_missions): """ Checks if mission string is in ...
# -*- coding: utf-8 -*- # Só um comentário sobre isso aqui: # Essa parte provavelmente a parte mais mal feita do projeto todo. # Ter que obrigatóriamente criar um tabela pra cada ficha é desnecessário # e utiliza recursos demais. # Uma possibilidade pra resolver isso seria utilização # de alguma base de dados não rel...
# read_stocks.py # Read the current data of the stock market and show them if need be def is_open(api): #Check if market is closed clock = api.get_clock() print('The market is {}'.format('open.' if clock.is_open else 'closed.')) ### Please check again here def read_market_data(api,input_stocks,intervals,ma_i...
with open('input.txt') as file: sum = 0 group = None for line in file: if line.strip(): if group is None: group = set(line.strip()) else: group = group.intersection(line.strip()) else: print("group:", ''.join(sorted(group))...
# # PySNMP MIB module CISCO-COMMON-MGMT-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-MGMT-CAPABILITY # Produced by pysmi-0.3.4 at Wed May 1 11:53:37 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
class Edge: pass class Loop(Edge): pass class ParallelEdge(Edge): pass
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar. din = float(input('Quanto voce tem quantos reais na sua carteira R$ ')) print('Seu dinheiro vale US$ {:.2f} dólares'.format(din/3.27))
# Division with int # Prompt user for x x = int(input("x: ")) # Prompt user for y y = int(input("y: ")) # Perform division print(x / y)
# Python - 2.7.6 Test.describe('combine names') Test.it('example tests') Test.assert_equals(combine_names('James', 'Stevens'), 'James Stevens') Test.assert_equals(combine_names('Davy', 'Back'), 'Davy Back') Test.assert_equals(combine_names('Arthur', 'Dent'), 'Arthur Dent')
""" Leetcode problem: https://leetcode.com/problems/super-egg-drop/ """ def solve_dp(K: int, N: int): def solve(k, moves): dp = [None] * (k + 1) for i in range(k + 1): dp[i] = [0] * (moves + 1) for i in range(1, k + 1): for j in range(1, moves + 1): ...
def suma(num1, num2): return num1 + num2 def resta(num1, num2): return num1 - num2 def multiplica(num1, num2): return num1 * num2 def divide(num1, num2): try: return num1 / num2 except ZeroDivisionError: print("No puedes dividir entre 0") return "Operacion erronea" de...
a,b = [int(i) for i in input().split()] def gcd(a,b): if b==0: print(a) quit() c = a%b gcd(b,c) if a>b: gcd(a,b) else: gcd(b,a)
DEFAULT_LOGGING_CONFIG = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(levelname)s][%(name)s]: %(reset)s%(message)s' } }, 'handlers': { ...
class Solution: def numberToWords(self, num: int) -> str: """ :type num: int :rtype: str """ if not num: return 'Zero' onedigit = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'} twodigits_10to19 = {1...
# 美胜丑,明胜暗,简胜繁 # print('Hello World!') # 字符串必须放到引号中 # print('Hello', 'World', '!', 123) # 数字不用放到引号中 # print('Hello', 'World', '!', 123, sep='***') # 各项间用***分开 # print('Hello' + 'World!') # 字符串拼接 # print('Hello', 'World', '!', 123, end='') # 不打印回车 user = input('username: ') print(user) a = input('number: ') # in...
name = ['shubham', 'raj', 'shantanu', 'deeksha', 'kanu', 'vishal','priya','kavita', 'jugal', 'kamalnath'] serial = [i for i in range(10)] height_cm = [168, 178, 170, 155, 172, 171, 165, 166, 173] """zip is lazy, so you have to do something li...
# Write an algorithm to determine if a number n is "happy". # A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cy...
def Mean_of_All_Digits(num): arr = [] n = num while n > 0: r = n % 10 n = n // 10 arr.append(r) return sum(arr)//len(arr) print(Mean_of_All_Digits(42)) print(Mean_of_All_Digits(12345)) print(Mean_of_All_Digits(666))
# coding:utf-8 # File Name: chart_test # Author : yifengyou # Date : 2021/07/18 s = "crazyit.org is very good" print(s[2]) print(s[-1]) print(s[0:]) print(s[-6:]) print("================") print(min(s)) print(max(s)) print("================") print(s.title()) print(s.upper()) print(s.lower())
#make a way to quickly make a new dictionary with the right properties def tool_dict(line): return {"name":line[0],"2015":line[1],"2016":line[2],"2017":line[3],"2018":line[4],"2019":line[5],"total":sum(line[1:])} #open file file=open("tools_dh_proceedings.csv") print("Opened tools_dh_proceedings.csv") #throw ...
numbers = [3, 5, 7, 9, 4, 8, 15, 16, 23, 42] is_there_any_odd_number = False is_odd = lambda num: num % 2 == 1 def fun(num): print(f"fun({num})") return num % 2 == 1 for num in numbers: if is_odd(num): is_there_any_odd_number = True break print(is_there_any_odd_number) # print(any(map(...
def bfs(graph, source, target): visited = {k: False for k in graph} distance = {k: 1000000 for k in graph} queue = [] visited[source] = True distance[source] = 0 queue.append(source) while queue: node = queue.pop(0) for n in graph[node]: if not visited[n]: ...
"""FILE HANDLING Text file's mode: w - write r -read a - append r+ - read and write x - creation mode Binary file's mode: wb - write rb -read ab - append rb+ - read and write """ """ WORK WITHOUT WITH/AS my_file = open("data.txt","r") print(my_file.read()) must close the source """ """ READ A TEX...
_base_ = [ # '../_base_/models/deeplabv3plus_r18-d8.py', '../_base_/models/deeplabv3plus_r50-d8.py', '../_base_/datasets/boulderset.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py' ] norm_cfg = dict(type='BN', requires_grad=True) num_classes = 3 model = dict( pretraine...
print(''' ,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba, a8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P' "Y8 8b ,adPPPPP88 8PP""""""" `"Y8ba, ,adPPPPP88 88 "8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88 `"Ybbd8"' `"8bbdP"Y8 `"Ybbd8"' `"Ybb...
PARAMETERS = { # Input params "training_data_patterns": [ "data/tfrecord_v2/20180101.gz" ], "evaluation_data_patterns":[ "data/tfrecord_v2/20180101.gz" ], # Training data loader properties "buffer_size": 10000, "num_parsing_threads": 16, "num_parallel_readers": 4, ...
# encoding: utf-8 """Dict of COMMANDS.""" # clArg: [function, help, args:{ # shortCommand, LongCommand, choices # store_true, help # }] COMMANDS = { # --------------------- # SERVICE_DEVICE_CONFIG # --------------------- 'login': ['login', 'Attempts to login to rou...
class Solution: def FindGreatestSumOfSubArray(self, array): if not array: return 0 cur_sum, max_sum = array[0], array[0] for i in range(1, len(array)): cur_sum = array[i] if cur_sum <= 0 else cur_sum + array[i] max_sum = cur_sum if cur_sum > max_sum else...
def main(): # get sales = get_sales() advanced_pay = get_advanced_pay() rate = determined_comm_rate(sales) # calc pay = sales * rate - advanced_pay # print print("The pay is $", format(pay, ",.2f"), sep='') return def get_sales(): return float(input("Sales: $")) def determined_...
Dataset_Path = dict( CULane = "/home/lion/Dataset/CULane/data/CULane", Tusimple = "/home/lion/Dataset/tusimple" )
for _ in range(int(input())): n, k = map(int, input().split()) p = [0] + list(map(int, input().split())) visited = [False] * (n + 1) cycles = [] for i in range(1, n + 1): cycle = [] while not visited[i]: visited[i] = True cycle += i, i = p[i] ...
def f(x = True): 'whether x is a correct word or not' if x: print('x is a correct word') print('OK') f() f(False) def g(x, y = True): "x and y both correct words or not" if y: print(x, 'and y both correct') print(x,'is OK') g(68) g(68, False)
print('\033[31m-=-\033[m' * 20) print('\033[31m*************** Comparador de números ***************\033[m') print('\033[31m-=-\033[m' * 20) v = int(input('Insira um valor: ')) v2 = int(input('Insira um segundo valor: ')) if v > v2: print('O {}primeiro{} valor é maior.' .format('\033[32m', '\033[m')) elif v2 > v: ...
user = "user_name_here" password = "password_here" host = "host_here" app_name = "discogs app name here" user_token = "discogs app token here"
#!/usr/bin/env python3 dictionary = { #defines dictionary data structure "class" : "Astr 119", "prof" : "Brant", "awesomeness" : 10 } print(type(dictionary)); #prints the data type of dictionary course = dictionary["class"]; #obtains a value from a key in dictionary print(course); #prints the val...
f = open("crime.csv", "r") print("beep") print(f.readline()) print(f.readline()) f.close()
#program to calculate the maximum profit from selling and buying values of stock.. def buy_and_sell(stock_price): max_profit_val, current_max_val = 0, 0 for price in reversed(stock_price): current_max_val = max(current_max_val, price) potential_profit = current_...
class Solution: def findMin(self, nums: List[int]) -> int: val = sys.maxsize for i in nums: if i < val: val = i return val
# @Author : Wang Xiaoqiang # @GitHub : https://github.com/rzjing # @Time : 2020-01-06 15:59 # @File : gun.py # gunicorn configuration file bind = '0.0.0.0:5000' loglevel = 'info' access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)s' reload = True if __name__ == '__main...
liste = [5, 12, 7, 54, 4, 19, 23] classeur = { 'positif':[], 'negatif': [] }
# -*- coding: utf-8 -*- """AccountHistory Definitions.""" definitions = { "InlineCountValue": { "AllPages": "The results will contain a total count of items in the " "queried dataset.", "None": "The results will not contain an inline count.", }, "AccountPerformanceStanda...
class AirtrackBaseError(Exception): """AirtrackBase error""" class AirtrackError(AirtrackBaseError): """Airtrack error""" class AirtrackSubjectError(AirtrackError): """AirtrackCamera error""" class AirtrackStateMachineError(AirtrackError): """AirtrackStateMachine error""" class AirtrackCameraErr...
def inputs(): a = int(input()) return a def body(a): if a <= 2: print("NO") elif a % 2 == 0: print("YES") else: print("NO") def main(): a = inputs() body(a) if __name__ == "__main__": main()
class ShippingCubes: def minimalCost(self, N): m = 600 for i in xrange(1, 200): for j in xrange(1, i + 1): for k in xrange(1, j + 1): if i * j * k == N: m = min(m, i + j + k) return m
def tem_match(origin_test, origin_template): test = [] for i in origin_test: tem_test = [] for index, j in enumerate(i[1]): j.insert(0, i[0][index]) tem_test.append(j) test.append([i[0], tem_test]) tem_template = {} for i in origin_template: tem_...
n = int(input()) for i in range(0,10000,1): if i % n == 2: print(i)
#Programa que leia um npumero e mostre seu sucessor e antecessor n = int(input('Digite um número: ')) print('{} é o antecessor de {}, e seu sucessor é {}'.format(n-1,n,n+1))
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, A...
""" slackd.common ~~~~~~~~~~~~~ Provides application level utility functions and classes :copyright: (c) 2016 Pinn :license: All rights reserved """
def get_config(): conf = { # Change it to necessary directory 'workdir': 'dataset/cr_data/', 'PAD': 0, 'BOS': 1, 'EOS': 2, 'UNK': 3, 'train_qt': 'sql.train.qt.pkl', 'train_code': 'sql.train.code.pkl', # parameters 'qt_len': 20, ...
def get_urls(*args, **kwargs): return { 'http://docutils.sourceforge.net/RELEASE-NOTES.txt' }, set()
# # PySNMP MIB module G6-FACTORY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/G6-FACTORY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:04:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
# 3 segmentos formam um triângulo? qual triângulo eles formam? seg1 = int(input('Valor do 1º segmento: ')) seg2 = int(input('Valor do 2ª segmento: ')) seg3 = int(input('Valor do 3ª segmento: ')) if seg1 < seg2 + seg3 and seg2 < seg1 + seg3 and seg3 < seg1 + seg2: if seg1 == seg2 == seg3: tipo = 'Equiláter...
t11 = [14.27,22.98,13.40,39.35,33.57,32.22,23.96,19.83,16.07] t12 = [60.90,89.70,59.55,39.32,33.54,32.26,79.00,59.65,51.54] t21 = [19.47,29.66,61.43,25.30,20.94,20.31,28.31,22.99,18.73] m1 = [213.19,212.84,210.35] m2 = [112.31,111.99,109.55] def energy(t, m): v = 1.03 * 10 / t energy = 0.5 * m * v ** 2...
#! /usr/bin/env python def is_num_palindrome(num): # Skip single-digit inputs if num // 10 == 0: return False temp = num reversed_num = 0 while temp != 0: reversed_num = (reversed_num * 10) + (temp % 10) print(f'Reverse number: {reversed_num}') temp = temp // 10 ...
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: May 5, 2015 # Question: 122-Best-Time-to-Buy-and-Sell-Stock-II # Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ # ==============================...
""" IF the name is less than 3 characters then the name is shorter than usual. If the name is of more than 50 characters it is longer than usual. """ #Taking name from the user name = str(input("Please enter your full name: ")) #Evaluating the name if len(name) < 3: print("The name that you have put is too sh...
n1 = input("Digite uma fruta ") n2 = input("Digite outra fruta ") n3 = input("Digite outra fruta ") lista = [n1,n2,n3] print(lista) n4 = input("Escolha uma fruta para verificar ") if n4 in lista: print("Sim, está na lista! ") else: print("Não está na lista ")
# Refer: https://codeforces.com/contest/1538/problem/B def distribute_candies(arr, n): s = sum(arr) if s % n != 0: return -1 avg = s // n cnt = 0 for c in arr: if c > avg: cnt += 1 return cnt if __name__ == "__main__": t = int(input()) i = 0 while i < ...
__all__ = ['RetryStrategy'] class RetryStrategy (object): """ Base class for retry strategies. """ def exhaust (self): """ Sets the retry strategy in such a state that it will always return a value that indicates that no further sleep attempts should be made. """ ...
# Copyright 2020 Microsoft Corporation # # 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...
# Scrapy settings for sephora project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware...
_base_ = './van_small_8xb128_fp16_ep300.py' # model settings model = dict( backbone=dict(arch='large', drop_path_rate=0.2), )
#!/usr/bin/python REGISTER_USER = "RegisterUser" CURRENT_MEDS = "CurrentRx" DOSAGE_REMINDER = "DosageReminder" REFILL_REMINDER = "RefillReminder"
""" Criar um carro pela composição a partir de duas classes 1)Motor 2)Direção O motor terá que controlar a velocidade. Ele oferece os seguintes atributos: 1) Atributo de dados Velocidade 2) Metodo Acelerar, que deverar incrementar 1 velocidade em 1 unidade 3) Método de frear que devera decrementar 2 velocidades A dir...
""" Conjuntos Conjunto em qualquer linguagem de programação faz referência a teoria dos conjuntos da matemática - No python, os conjuntos são chamados de sets # Sets (conjuntos) não possuem valores duplicados # Sets (conjuntos) não possuem valores ordenados # Elementos não são acessados via índice, ou seja, conjunto...
if __name__ == "__main__": s = 'Hello from Python!' words = s.split(' ') print(words) for w in words: print(w) for ch in s: print(ch)
def sequentialSearch(n, array, x): if x >= n: return None location = 0 while (location < n and array[location] != x): location += 1 return location
MICROBIT = "micro:bit" # string arguments for constructor BLANK_5X5 = "00000:00000:00000:00000:00000:" # pre-defined image patterns IMAGE_PATTERNS = { "HEART": "09090:99999:99999:09990:00900:", "HEART_SMALL": "00000:09090:09990:00900:00000:", "HAPPY": "00000:09090:00000:90009:09990:", "SMILE": "00000:...
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: result, currentSum, hashSet, start = 0, 0, set(), 0 for end in range(len(nums)): while nums[end] in hashSet: hashSet.remove(nums[start]) currentSum -= nums[start] star...
""" Instruction: - write a proper docstring that includes any exception conditions - add two more meaningful testcases to the doctests part of each function - write the body of the function where a marker "YOUR CODE HERE" appear To test these functions, use the following command: python3 -m doctest week5_inclass_ex.p...
""" TCF CLI VERSION """ __version__ = '0.1.1'
class Solution: def specialArray(self, nums): length = len(nums) rng = range(length) # Start from end. (todo, try starting from beginning) for i in range(1, length+1): # keep track of matches (>= i) match = 0 for idx in rng: n = num...
""" Batch processing exceptions """ class SQSBatchProcessingError(Exception): """When at least one message within a batch could not be processed"""
numbers = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55] result = [el for num, el in enumerate(numbers) if numbers[num - 1] < numbers[num]] print(result)
# Create a word-count method # Function that returns number of words in a string def count_words(string): # Split the string into words words = string.split() # Return the number of words return len(words) # Create a new feature word_count ted['word_count'] = ted['transcript'].apply(count_words) # ...
class DiskError(RuntimeError): pass class SaveError(DiskError): pass class LoadError(DiskError): pass class RenameError(DiskError): pass class PathDoesNotExistError(DiskError): pass class PathExistsError(DiskError): pass class NotAFileError(FileNotFoundError): pass class DirectoryNotFoundError(NotA...
RECOGNIZE = { " | | ": '1', " _ _||_ ": '2', " _ _| _| ": '3', " |_| | ": '4', " _ |_ _| ": '5', " _ |_ |_| ": '6', " _ | | ": '7', " _ |_||_| ": '8', " _ |_| _| ": '9', " _ | ||_| ": '0', } def convert(input_grid): if input_grid == [] or ...
class CianException(Exception): """Base class for exceptions""" class CianStatusException(CianException): """Incorrect status in response from cian server""" def __init__(self, status): super().__init__(f"Status in response from cian is not 'ok'. Status: {status}")
def cap_text(text): """ Input a String Output the capitalized String """ return text.title()
def foo(**args): pass a = {} b = {} foo(**a)
class Shield: def __init__(self): self.water_level = 0 self.switch_state = 0 def tick(self, water_level, switch_state, action): return action
# 1046. Last Stone Weight - LeetCode Contest # https://leetcode.com/contest/weekly-contest-137/problems/last-stone-weight/ class Solution: def lastStoneWeight(self, stones) -> int: stones = sorted(stones,reverse=True) while len(stones) > 1: first_stone = stones.pop(0) second...
class Node(object): def __init__(self, key, data=None, result=None): self.key = key self.data = data self.result = [] if result is not None: self.result.append(result) self.children = dict() class Trie(object): """ Trie Data Structure Data Structure...