content
stringlengths
7
1.05M
class PaymentAPIError(Exception): """ Raised when a payment related action fails. """ pass
class Meta(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): self[name] = value def bind(self, name, func): setattr(self.__class__, name, func)
# Rain_Water_Trapping def trappedWater(a, size) : # left[i] stores height of tallest bar to the to left of it including itself left = [0] * size # Right [i] stores height of tallest bar to the to right of it including itself right = [0] * size # Initialize result waterVolume = 0 ...
# -*- coding: utf-8 -*- BOT_NAME = 'spider' SPIDER_MODULES = ['spiders'] NEWSPIDER_MODULE = 'spiders' ROBOTSTXT_OBEY = False # change cookie to yours #DEFAULT_REQUEST_HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36', # '...
# -*- coding: utf-8 -*- def consumer(): status = True while True: n = yield status print("ๆˆ‘ๆ‹ฟๅˆฐไบ†{}!".format(n)) if n == 3: status = False def producer(consumer): n = 5 while n > 0: # yield็ป™ไธป็จ‹ๅบ่ฟ”ๅ›žๆถˆ่ดน่€…็š„็Šถๆ€ yield consumer.send(n) n -= 1 if __name...
# -*- coding: utf-8 -*- # Copyright (2018) 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...
#Function to remove a given word from a list and strip it at the same time. def remove_and_split(string, word): newStr = string.replace(word, "") return newStr.strip() this = " Root is a Computer " n = remove_and_split(this, "Root") print(n)
tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(table): colWidth = [0] * len(table) #List of rjust values to be used for i in range(len(table)): #iterates through the 3 lists ...
N = int(input()) M = int(input()) S = int(input()) for num in range(M, N - 1, - 1): if num % 2 == 0 and num % 3 == 0: if num == S: break print(num, end=" ")
# ่ฟ™ๆ˜ฏๅฐ†MNISTไธญ็š„ๆ•ฐๆฎ้›†่ฝฌๆขไธบcsvๆ ผๅผ็š„่„šๆœฌ # ๅŽ็ปญไปฃ็ ้ƒฝไผšๅœจcsvๆ–‡ไปถ็š„ๅŸบ็ก€ไธŠ่ฟ›่กŒ็ผ–ๅ†™, ่ฟ™ๆ ทๅคงๅฎถ็œ‹ไปฃ็ ไนŸ่ƒฝๆธ…้™คๅพˆๅคš # ไปฃ็ ็”ฑไปฅไธ‹็ฝ‘ๅ€ๆไพ›๏ผŒ่กจ็คบๆ„Ÿ่ฐขใ€‚ # https://pjreddie.com/projects/mnist-in-csv/ # ่ฏฅpyๆ–‡ไปถๅฑžไบŽไธ€ไธช่กฅๅ……๏ผŒไธไฝฟ็”จไนŸไธๅฝฑๅ“ๅŽ็ปญ็ฎ—ๆณ•็š„ๅฎž่ทตใ€‚ # ่ฝฌๆขๅŽ็š„CVSๆ–‡ไปถๅœจMnistๆ–‡ไปถๅคนไธญ def convert(imgf, labelf, outf, n): f = open(imgf, "rb") o = open(outf, "w") l = open(labelf, "rb") f.read(16) l.read(...
f=open('demo1.txt','a') a=int(input('enter number ')) f.write('hello hi\n') f.write('world') f.write(str(a)) f.close()
# -*- coding: UTF-8 -*- # ๅˆ ้™คๅญ—ๅ…ธไธญvalueไธบ็ฉบ็š„้”ฎๅ€ผๅฏนๆ–นๆณ• def deldictNULL(mydict): for key in list(mydict.keys()): if not mydict.get(key): del mydict[key] return mydict
ALIEN = {'.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0'} def morse_converter(s): return int(''.join(ALIEN[s[a:a + 5]] for a in xrange(0, len(s), 5)))
def calculateAverageAge(students): add_age = 0 for thing in students.values(): age = thing['age'] add_age = add_age + age return(add_age / len(students.keys())) students = { "Peter": {"age": 10, "address": "Lisbon"}, "Isabel": {"age": 11, "address": "Sesimbra"}, "Ann...
# very old file that isn't very useful but it works with things so I'm keeping it for now class Rectangle: current_id = 0 tolerable_distance_to_combine_rectangles = 0.00005 # buildings need to be this (lat/long degrees) away to merge def __init__(self, init_points, to_id=True): self.points = init_...
class Solution: def restoreString(self, s: str, indices: List[int]) -> str: res = [0] * len(indices) for i, j in zip(s, indices) : res[j] = i return "".join(res)
class Move: def __init__(self, dest_rank_id, from_rank_id): self.dest_rank_id = dest_rank_id self.from_rank_id = from_rank_id def output(self): out_str = '' out_str += str(self.from_rank_id) out_str += ' -> ' out_str += str(self.dest_rank_id) print(out_str)
# MatchJoin takes a list of matchers and joins them, to essentially # make a conjunctive matcher class MatchJoin: # @matchers A list of matchers to join into a single match for example # [ # LiteralMatch("hello ") # LiteralMatch("world") # ] def __init__(self, matchers : list): self....
# Finds the optmial cost def find_opt_cost(data): min_cost = data[data.A == -1]['cost'].values[0] return min_cost # Finds the energy corresponding to optimal route def find_opt_energy(data): opt_energy = data[data.A == -1]['energy'].values[0] return opt_energy # Returns true if optimal route is obs...
# -*- coding: utf-8 -*- """Constant values. """ __version__ = '2021.03.27' # image sizes RES_TINY = 'TINY' RES_SMALL = 'SMALL' RES_MEAN = 'MEAN' RES_BIG = 'BIG' RES_HUGE = 'HUGE' IMAGE_SIZES = {RES_TINY, RES_SMALL, RES_MEAN, RES_BIG, RES_HUGE} # threshold for sizes THRESHOLD_TINY = 0.1 THRESHOLD_SMALL = 1.0 THRESHO...
def jogo(): x = 0 while x != 1 and x != 2: print('1 - para jogar uma partida isolada') x = int(input('2 - para jogar um campeonato ')) print() if x == 1: print('Vocรช escolheu uma partida!') print() partida() else: print('Vocรช escolheu um campeonato!') ...
class LayeredStreamReaderBase: __slots__ = {'upstream'} def __init__(self, upstream): self.upstream = upstream async def read(self, n): return await self.upstream.read(n) async def readexactly(self, n): return await self.upstream.readexactly(n)
# class class_name: # def __init__(self): # # def function_name(self): # return class Athlete: def __init__(self, value='Jane'): self.inner_value = value print(self.inner_value) def getInnerValue(self): return self.inner_value class InheritanceClass(Athlete): def _...
Import("env") # # Add -m32 to the linker (since PlatformIo is not capable directly!) # (and since we are at it, make everyting statically linked ;-) # env.Append( LINKFLAGS=[ "-m32", "-static-libgcc", "-static-libstdc++" ] )
class Programa: def __init__(self, nome, ano): self._nome = nome.title() self.ano = ano self._likes = 0 @property def likes(self): return self._likes def dar_like(self): self._likes += 1 @property def nome(self): return self._nome ...
# -*- coding: utf-8 -*- { 'name': 'Customer Rating', 'version': '1.0', 'category': 'Productivity', 'description': """ This module allows a customer to give rating. """, 'depends': [ 'mail', ], 'data': [ 'views/rating_view.xml', 'views/rating_template.xml', 'se...
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: # Check edge case if not intervals: return [] # Sort the list to make it ascending with respect to the sub-list's first element and then in second element intervals = sorted(interv...
__source__ = 'https://leetcode.com/problems/next-greater-element-iii/description/' # Time: O(n) # Space: O(n) # # Description: same as 556. Next Greater Element III # //xinzyang@tesla.com # // Next closest bigger number with the same digits # // You have to create a function that takes a positive integer number and re...
def es_vocal(letra): """ Decide si una letra es vocal >>> es_vocal('A') True >>> es_vocal('ae') False >>> es_vocal('Z') False >>> es_vocal('o') True :param letra: :return: """ return len(letra) == 1 and letra in 'aeiouAEIOU' def contar_vocales(texto): """ ...
"Ejemplo de implementaciรณn con Programaciรณn Estructurada" clientes=[{'Nombre': 'Hector', 'Apellidos':'Costa Guzman', 'dni':'11111111A'}, {'Nombre': 'Juan', 'Apellidos':'Gonzรกlez Mรกrquez', 'dni':'22222222B'}] def mostrar_cliente(clientes, dni): for cliente in clientes: if (dni == cliente['dni']):...
# detector de palindromo frase = str(input('Digite uma frase: ')).upper().strip() separado = frase.split() junto = ''.join(separado) inverte ='' for letra in range(len(junto)-1,-1,-1): inverte += junto[letra] print('O inverso de {} รฉ {}'.format(junto, inverte)) if junto == inverte: print('A frase รฉ um palรญndro...
# Portal & Effect for Evan Intro | Dream World: Dream Forest Entrance (900010000) # Author: Tiger # "You who are seeking a Pact..." sm.showEffect("Map/Effect.img/evan/dragonTalk01", 3000)
#implement STACK/LIFO using LIST stack=[] while True: choice=int(input("1 push, 2 pop, 3 peek, 4 display, 5 exit ")) if choice == 1: ele=int(input("enter element to push ")) stack.append(ele) elif choice == 2: if len(stack)>0: pele=stack.pop() print("poped elemnt ",pele) else: print("sta...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE ่“้ฒธๅŸบ็ก€ๅนณๅฐ available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE ่“้ฒธๅŸบ็ก€ๅนณๅฐ is licensed under the MIT License. License for BK-BASE ่“้ฒธๅŸบ็ก€ๅนณๅฐ: ---------------------------------------------...
#!/bin/python3 nombre = 3 nombres_premiers = [1, 2] print(2) try: while True: diviseurs = [] for diviseur in nombres_premiers: division = nombre / diviseur if division == int(division): diviseurs.append(diviseur) if len(diviseurs) == 1: pri...
DIGS = {1: 'F1D', 2: 'F2D', 3: 'F3D', 22: 'SD', -2: 'L2D'} SEC_ORDER_DIGS = {key: f'{val}_sec' for key, val in DIGS.items()} REV_DIGS = {'F1D': 1, 'F2D': 2, 'F3D': 3, 'SD': 22, 'L2D': -2} LEN_TEST = {1: 9, 2: 90, 3: 900, 22: 10, -2: 100} TEST_NAMES = {'F1D': 'First Digit Test', 'F2D': 'First Two Digits Test', ...
# model settings model = dict( type='NPID', neg_num=65536, backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(3,), # no conv-1, x-1: stage-x norm_cfg=dict(type='SyncBN'), style='pytorch'), neck=dict( type='LinearNeck', in_c...
#!/usr/bin/env python3 # coding:utf-8 def estimate_area_from_stock(stock) : return 10000000000;
algo: str = input('Digite algo:') print('O tipo de primitivo da variรกvel รฉ ', type(algo)) print('ร‰ um nรบmero? ', algo.isnumeric()) print('ร‰ alfabรฉtico?', algo.isalpha()) print('ร‰ decimal?', algo.isdecimal()) print('Esta em minusculas?',algo.islower())
# CFG-RATE (0x06,0x08) packet (without header 0xB5,0x62) # payload length - 6 (little endian format), update rate 200ms, cycles - 1, reference - UTC (0) packet = [] packet = input('What is the payload? ') CK_A,CK_B = 0, 0 for i in range(len(packet)): CK_A = CK_A + packet[i] CK_B = CK_B + CK_A # ensure unsigned ...
class Course: def __init__(self, **kw): self.name = kw.pop('name') #def full_name(self): # return self.first_name + " " + self.last_name
'''Extracts the data from the json content. Outputs results in a dataframe''' def get_play_df(content): events = {} event_num = 0 home = content['gameData']['teams']['home']['id'] away = content['gameData']['teams']['away']['id'] for i in range(len(content['liveData']['plays']['allPlays'])...
#APROVANDO EMPRESTIMO casa = float(input('Valor da casa: R$')) salario = float(input('Salario do comprador: R$')) anos = int(input('Quantos anos de financiamento: ')) meses = anos * 12 prestaรงรฃo = casa / meses print('Para pagar uma casa de R${:.2f} em {} anos a prestaรงรฃo sera de R${:.2f}'.format(casa, anos, prestaรงรฃ...
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n=int(input()) a,b=map(int,input().split()) c,d=map(int,input().split()) e,f=map(int,input().split()) m=n-a-c-e x=max(0,min(m,b-a));m-=x y=max(0,min(m,d-c));m-=y z=max(0,min(m,f-e));m-=z print(a+x,c+y,e+z)
""" models/__init__.py ------------------------------------------------------------------- """ def init_app(app): """ :param app: :return: """ pass
""" Discussion: As we increase the input firing rate, more synapses move to the extreme values, either go to zero or to maximal conductance. Using 15Hz, the distribution of the weights at the end of the simulation is more like a bell-shaped, skewed, with more synapses to be potentiated. However, increasing the fir...
# coding: utf8 { '!langcode!': 'af', '!langname!': 'Afrikaanse', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s %%{row} deleted': '%s rows deleted', '%s %%{row} updated': '%s rows updated', '(requires internet access)': '(vereis internet toegang)', '(something like "it-it")': '(iets soos "it-it")...
#!/usr/bin/env python #-*- coding:utf8 -*- # @Author: lisnb # @Date: 2016-04-27T11:05:16+08:00 # @Email: lisnb.h@hotmail.com # @Last modified by: lisnb # @Last modified time: 2016-06-18T22:20:18+08:00 class UnknownError(Exception): pass class ImproperlyConfigured(Exception): """Wiesler is somehow imprope...
def raio_simplificado(lista_composta): for elemento in lista_composta: yield from elemento lista_composta = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
#trying something new uridine_mods_paths = {'U_to_DDusA' : {'upstream_rxns' : ['U'], 'enzymes' : {20:['DusA_mono'], '20A':['DusA_mono'], 17:['DusA_mono'], ...
#The casefold() method is an aggressive lower() method which convert strings to casefolded strings for caseless matching. string = "PYTHON IS AWESOME" # print lowercase string print("Lowercase string:", string.casefold()) firstString = "der FluรŸ" secondString = "der Fluss" # รŸ is equivalent to ss in ger...
class Pessoa: olhos = 2 # atributo Default ou atributo de classe def __init__(self, *filhos, nome=None, idade=59): self.idade = idade self.nome = nome self.filhos = list(filhos) @staticmethod def metodo_estatico(): return 59 @classmethod def nome_e_atributos_de...
def run(): # Range can receive a first value that defines start value of range: range(1, 1000) for i in range(1000): print('Value ' + str(i)) if __name__ == '__main__': run()
def biggerIsGreater(w): w = list(w) x = len(w)-1 while x > 0 and w[x-1] >= w[x]: x -= 1 if x <= 0: return 'no answer' j = len(w) - 1 while w[j] <= w[x - 1]: j -= 1 w[x-1], w[j] = w[j], w[x-1] w[x:] = w[len(w)-1:x-1:-1] return ''.join(w)
# Add support for multiple event queues def upgrader(cpt): cpt.set('Globals', 'numMainEventQueues', '1') legacy_version = 12
class Solution(object): def moveZeroes(self, nums): totalZeros = 0 for i in range(len(nums)): if nums[i] == 0 : totalZeros += 1 continue nums[i - totalZeros] = nums[i] if(totalZeros) : nums[i] = 0
# This file is created by generate_build_files.py. Do not edit manually. ssl_headers = [ "src/include/openssl/dtls1.h", "src/include/openssl/srtp.h", "src/include/openssl/ssl.h", "src/include/openssl/ssl3.h", "src/include/openssl/tls1.h", ] fips_fragments = [ "src/crypto/fipsmodule/aes/aes.c",...
def possible_combination(string): n = len(string) count = [0] * (n + 1); count[0] = 1; count[1] = 1; for i in range(2, n + 1): count[i] = 0; if (string[i - 1] > '0'): count[i] = count[i - 1]; if (string[i - 2] == '1' or (string[i - 2] == '2' and ...
''' Description: Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 ''' # Definition for a binary tree node. cla...
"""Constants for the Template Platform Components.""" CONF_AVAILABILITY_TEMPLATE = "availability_template" DOMAIN = "template" PLATFORM_STORAGE_KEY = "template_platforms" PLATFORMS = [ "alarm_control_panel", "binary_sensor", "cover", "fan", "light", "lock", "sensor", "switch", "v...
############################################################################### # Copyright (c) 2019, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory # Written by the Merlin dev team, listed in the CONTRIBUTORS file. # <merlin@llnl.gov> # # LLNL-CODE-797170 # All righ...
# -*- coding: utf-8 -*- """ Created on Tue Oct 20 20:20:20 2020 @authors: Amal Htait and Leif Azzopardi For license information, see LICENSE.TXT """ class SentimentIntensityAggregator: """ Apply an aggregation to a list of similarity scores. """ def __init__(self): pass def agg_score(sel...
# Metadata Create Tests def test0_metadata_create(): return # Metadata Getters Tests def test0_metadata_name(): return def test0_metadata_ename(): return def test0_metadata_season(): return def test0_metadata_episode(): return def test0_metadata_quality(): return def test0_metadata_ex...
# # @lc app=leetcode.cn id=374 lang=python3 # # [374] ็Œœๆ•ฐๅญ—ๅคงๅฐ # # https://leetcode-cn.com/problems/guess-number-higher-or-lower/description/ # # algorithms # Easy (50.55%) # Likes: 145 # Dislikes: 0 # Total Accepted: 65.9K # Total Submissions: 130.4K # Testcase Example: '10\n6' # # ็Œœๆ•ฐๅญ—ๆธธๆˆ็š„่ง„ๅˆ™ๅฆ‚ไธ‹๏ผš # # # ๆฏ่ฝฎๆธธๆˆ๏ผŒๆˆ‘้ƒฝไผšไปŽย 1ย ๅˆฐย ...
# coding: utf-8 # Author: zhao-zh10 # The function localize takes the following arguments: # # colors: # 2D list, each entry either 'R' (for red cell) or 'G' (for green cell). The environment is cyclic. # # measurements: # list of measurements taken by the robot, each entry either 'R' or 'G' # # motions:...
def foo(): print("In utility.py ==> foo()") if __name__=='__main__': foo()
count=0 def permute(s,l,pos,n): if pos>=n: global count count+=1 print(l) for k in l: print(s[k],end="") print() return for i in range(n): if i not in l[:pos]: l[pos] = i permute(s,l,pos+1,n) s="shivank" n=len(s) l=[]...
# https://leetcode.com/problems/divide-two-integers/ # class Solution: def divide(self, dividend: int, divisor: int) -> int: if dividend == divisor: return 1 isPositive = (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) dividend = dividend if d...
class DataClassFile(): def functionName1(self, parameter1): """ One Function (takes a parameter) with one test function (with single line comments) where outdated documentation exists. ************************************************************ ####UnitTest Specific...
#!/usr/bin/env python3 def linearSearch(lst,item): isFound = False for x in range(0,len(lst)): if item == lst[x]: isFound = True return "Item found at index " + str(x) elif (x == len(lst)-1) and (isFound == False): return "Item not found" if __name__ == '__main_...
line = input() if line == 's3cr3t!P@ssw0rd': print("Welcome") else: print("Wrong password!")
# ฮ— ฮตฯฮณฮฑฯƒฮฏฮฑ ฯ€ฮฟฯ… ฮตฮฏฯ‡ฮต ฮผฯ€ฮตฮฏ ฯƒฯ„ฮฟ ฯ„ฮญฮปฮฟฯ‚, ฮณฮนฮฑ ฯ„ฮฟ ฯ€ฯฯŽฯ„ฮฟ ฯ„ฮผฮฎฮผฮฑ my_list = [] # ฮ›ฮฏฯƒฯ„ฮฑ ฮผฮต ฯƒฯ„ฮฟฮนฯ‡ฮตฮฏฮฑ ฮฑฯ€ฯŒ ฯ„ฮฟ 1 ฮผฮญฯ‡ฯฮน ฯ„ฮฟ 25 for i in range(25): my_list.append(i) # ฮ‘ฯ†ฮฑฮฏฯฮตฯƒฮท ฮถฯ…ฮณฯŽฮฝ ฮฑฯฮนฮธฮผฯŽฮฝ for i in range(25): if i % 2 == 0: my_list.remove(i) print(my_list)
#%% def generate_range(min: int, max: int, step: int) -> None: for i in range(min, max + 1, step): print(i) generate_range(2, 10, 2) # %% # %% def generate_range(min: int, max: int, step: int) -> None: i = min while i <= max: print(i) i = i + step generate_range(2, 10, 2)
begin_unit comment|'# Copyright 2015 Red Hat Inc' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comm...
while True: entrada = input() if entrada == '0': break entrada = input() joao = entrada.count('1') maria = entrada.count('0') print(f'Mary won {maria} times and John won {joao} times')
# Age avergage with floating points # Var declarations # Code age1 = 10.0 age2 = 11.0 age3 = 13.0 age4 = 9.0 age5 = 12.0 result = (age1+age2+age3+age4+age5)/5.0 # Result print(result)
''' ็ผ–่พ‘่ท็ฆป ็ป™ไฝ ไธคไธชๅ•่ฏย word1 ๅ’Œย word2๏ผŒ่ฏทไฝ ่ฎก็ฎ—ๅ‡บๅฐ†ย word1ย ่ฝฌๆขๆˆย word2 ๆ‰€ไฝฟ็”จ็š„ๆœ€ๅฐ‘ๆ“ไฝœๆ•ฐย ใ€‚ ไฝ ๅฏไปฅๅฏนไธ€ไธชๅ•่ฏ่ฟ›่กŒๅฆ‚ไธ‹ไธ‰็งๆ“ไฝœ๏ผš ๆ’ๅ…ฅไธ€ไธชๅญ—็ฌฆ ๅˆ ้™คไธ€ไธชๅญ—็ฌฆ ๆ›ฟๆขไธ€ไธชๅญ—็ฌฆ ็คบไพ‹ย 1๏ผš ่พ“ๅ…ฅ๏ผšword1 = "horse", word2 = "ros" ่พ“ๅ‡บ๏ผš3 ่งฃ้‡Š๏ผš horse -> rorse (ๅฐ† 'h' ๆ›ฟๆขไธบ 'r') rorse -> rose (ๅˆ ้™ค 'r') rose -> ros (ๅˆ ้™ค 'e') ็คบไพ‹ย 2๏ผš ่พ“ๅ…ฅ๏ผšword1 = "intention", word2 = "execution" ่พ“ๅ‡บ๏ผš5 ่งฃ้‡Š๏ผš intention -> inention (ๅˆ ้™ค 't...
class Word: def __init__(self, cells): if not cells: raise ValueError("word cannot contain 0 cells") self.cell = cells[0] self.rest = Word(cells[1:]) if cells[1:] else None def _clear(self): self.cell |= 0 if self.rest: self.rest.clear() def ...
'''6. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. Sample String : 'abc' Expected Result : 'abcing' Sample Strin...
# basic tuple functionality x = (1, 2, 3 * 4) print(x) try: x[0] = 4 except TypeError: print("TypeError") print(x) try: x.append(5) except AttributeError: print("AttributeError") print(x[1:]) print(x[:-1]) print(x[2:3]) print(x + (10, 100, 10000))
# from util.stack import Stack """ Given a array of number find the next greater no in the right of each element Example- Input 12 15 22 09 07 02 18 23 27 Output 15 22 23 18 18 18 23 27 -1 """ '''prints element and NGE pair for all elements of arr[] ''' def find_next_greater_ele_in_array(array)...
N = int(input()) list = [] for _ in range(N): command = input().rstrip().split() if "insert" in command: i = int(command[1]) e = int(command[2]) list.insert(i, e) elif "print" in command: print(list) elif "remove" in command: i = int(command[1]) list.remo...
# Store all kinds of lookup table. # # generate rsPoly lookup table. # from qrcode import base # def create_bytes(rs_blocks): # for r in range(len(rs_blocks)): # dcCount = rs_blocks[r].data_count # ecCount = rs_blocks[r].total_count - dcCount # rsPoly = base.Polynomial([1], 0) # ...
#!/bin/python3 # coding: utf-8 print ('input name: ') name = input() print ('input passwd: ') passwd = input() if name == 'A': print('A') if passwd == 'BB': print('BB') else: print('Other!')
# Created by MechAviv # Map ID :: 940001050 # Hidden Street : East Pantheon sm.curNodeEventEnd(True) sm.setTemporarySkillSet(0) sm.setInGameDirectionMode(True, True, False, False) OBJECT_1 = sm.sendNpcController(3000107, -2000, 20) sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0) sm.setSpeakerID(3000107) sm.re...
subreddit = "quackers987" #CHANGE THIS #Multiple subreddits can be specified by joining them with pluses, for example AskReddit+NoStupidQuestions. fileLog = "imageRemoveLog.txt" neededModPermissions = ['posts', 'flair'] removeSubmission = False logFullInfo = False checkResolution = True minHeight = 800 minWidth = 800...
# In Islandora 8 maps to Repository Item Content Type -> field_resource_type field # The field_resource_type field is a pointer to the Resource Types taxonomy # class Genre: def __init__(self): self.drupal_fieldname = 'field_genre' self.islandora_taxonomy = ['tags','genre'] self.mods_xpa...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -----------------------------------------------------------------------...
# ๋„์–ด์“ฐ๊ธฐ, ๋“ค์—ฌ์“ฐ๊ธฐ ๊ผญ ํ™•์ธํ•˜์„ธ์š”! list1 = ["๊ฐˆ๋น„ํƒ•", "๋น„๋น”๋ฐฅ", "๋ƒ‰๋ฉด"] list2 = ["์งœ์žฅ", "์งฌ๋ฝ•", "๊ฟ”๋ฐ”๋กœ์šฐ", "๊นํ’๊ธฐ"] list3 = ["ํŒŒ์Šคํƒ€", "์Šคํ…Œ์ดํฌ", "๊ฐ๋ฐ”์Šค"] food = input("์Œ์‹์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”: ") # ์—ฌ๊ธฐ์„œ๋ถ€ํ„ฐ ์Œ์‹์ด ํ•œ์‹, ์ค‘์‹, ์–‘์‹ ์ค‘ ์–ด๋А ๊ณณ์— ์†ํ•˜๋Š”์ง€ ํŒ๋‹จํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”. # ๋‹จ, ์กฐ๊ฑด์‹์œผ๋กœ list1, list2, list3์— ํฌํ•จ๋˜๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ์ด์šฉํ•˜์…”์•ผ ํ•ฉ๋‹ˆ๋‹ค! if food in list1: print("ํ•œ์‹์ž…๋‹ˆ๋‹ค.") elif food in list2: p...
# Problem: Missing Number # Difficulty: Easy # Category: Array # Leetcode 268:https://leetcode.com/problems/missing-number/#/description # Description: """ Given an sorted array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] re...
'''Crie um programa que vai ler vรกrios nรบmeros e colocar em uma lista. Depois disso, mostre: A) Quantos nรบmeros foram digitados B) A lista de valores, ordenada de forma decrescente C) Se o valor 5 foi digitado e estรก ou nรฃo na lista.''' lista = [] print('\033[1;33m-=\033[m' * 20) while True: lista.append(int(input(...
while True: num = int(input("Enter an even number: ")) if num % 2 == 0: break print("Thanks for following directions.")
#Tuple is a collection of ordered items. A tuple is immutable in nature. #Refer https://docs.python.org/3/library/stdtypes.html?#tuples for more information person= ("Susan","Christopher","Bill","Susan") print(person) print(person[1]) x= person.count("Susan") print("Occurrence of 'Susan' in tuple is:" + str(x)) l=['a...
def get_sdm_query(query,lambda_t=0.8,lambda_o=0.1,lambda_u=0.1): words = query.split() if len(words)==1: return f"#combine( {query} )" terms = " ".join(words) ordered = "".join([" #1({}) ".format(" ".join(bigram)) for bigram in zip(words,words[1:])]) unordered = "".jo...
"""Define common constants""" JOB_COMMAND_START = "start" JOB_COMMAND_CANCEL = "cancel" JOB_COMMAND_RESTART = "restart" JOB_COMMAND_PAUSE = "pause" JOB_COMMAND_PAUSE_PAUSE = "pause" JOB_COMMAND_PAUSE_RESUME = "resume" JOB_COMMAND_PAUSE_TOGGLE = "toggle" JOB_STATE_OPERATIONAL="Operational" JOB_STATE_PRINTING="Printing...
def encode_structure_fold(fold, tree): def encode_node(node): if node.is_leaf(): return fold.add('boxEncoder', node.box) elif node.is_adj(): left = encode_node(node.left) right = encode_node(node.right) return fold.add('adjEncoder', left, right) ...
# -*- coding: utf-8 -*- class TrieNode: def __init__(self): self.children = {} self.leaf = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): current = self.root for char in word: if char not in current.children: ...
# Introduction to Computation and Programming Using Python (2021) # Chapter 2, Finger Exercise 1 # Finger exercise: Write a program that examines three variablesโ€” # x, y, and zโ€”and prints the largest odd number among them. If none # of them are odd, it should print the smallest value of the three. x = 10 # largest, no...
class PID: """PID controller.""" def __init__(self, Kp, Ti, Td, Imax): self.Kp = Kp self.Ti = Ti self.Td = Td self.Imax = Imax self.clear() def clear(self): self.Cp = 0.0 self.Ci = 0.0 self.Cd = 0.0 self.previous_error = 0.0 def ...
class DecimalPointFloatConverter: """ Custom Django converter for URLs. Parses floats with a decimal point (not with a comma!) Allows for integers too, parses values in this or similar form: - 100.0 - 100 Will NOT work for these forms: - 100.000.000 - 100,0 """ regex = "[0...