content
stringlengths
7
1.05M
# This module implements the public interface to the "counter" package. def reset(): """ Reset our counter. This should be called before we start counting. """ global _counts _counts = {} # Maps value to number of occurrences. def add(value): """ Add the given value to our counter. "...
class Solution: def recoverTree(self, root: Optional[TreeNode]) -> None: def swap(x: Optional[TreeNode], y: Optional[TreeNode]) -> None: temp = x.val x.val = y.val y.val = temp def inorder(root: Optional[TreeNode]) -> None: if not root: return inorder(root.left) ...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class VersionUpdateItem: def __init__(self, id, new_version): self.id = id self.new_version = new_version def __str__(self): return '[id: {}; new_version: {}]'.format(self.id, self.new_versio...
# -*- coding: utf-8 -*- """ Created on Wed Jan 27 21:02:58 2016 @author: amylo #""" print("HELLO WORLD!") print('HELLO MAYAN!') print('''this is the first line jfklds fjkdlsjfl''') age = 3 name = "Dou Dou" print("{0} was {1} years old".format(name,age)) print(name + " was " + str(age) + " years old ")
#crie um programa que mostre na tela todos os número pares que estão no intervalo entre 1 e 50 for n in range(2, 51, 2): #para n de 2 ate 51 pulando de dois em dois print(f'{n} ->', end=' ') #print n e nao quebre a linha print('FIM') #fim
""" This package is a place for your business logic. Please, do not create any other files inside your app package. Place all files here, including: logic, forms, serializers. Decoupling is a good thing. We need more of that. """
class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: arr = [0x7fffffff] * len(triangle) arr[0] = triangle[0][0] for i in range(1, len(triangle)): arr[i] = arr[i - 1] + triangle[i][i] for j in range(i - 1, 0, -1): arr[j] = min(arr[j...
def invert_dict(d): """more concise version of invert_dict with setdefault""" inverse = dict() for key in d: val = d[key] inverse.setdefault(val, []) inverse[val].append(key) return inverse inverse = invert_dict({'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}) print(inverse)
prn_out = { 1: [2, 6], 2: [3, 7], 3: [4, 8], 4: [6, 9], 5: [1, 9], 6: [2, 10], 7: [1, 8], 8: [2, 9], 9: [3, 10], 10: [2, 3], 11: [3, 4], 12: [5, 6], 13: [6, 7], 14: [7, 8], 15: [8, 9], 16: [9, 10], 17: [1, 4], 18: [2, 5], 19: [3, 6], ...
''' 1. def a(b): num=0 for i in b: if i=='-': num+=1 if num==2: if b[3] and b[6] is'-': b=b.replace('-','') if b.isdigit() is True: print('Valid SSN') else: print('Invalid SSN') else: print('...
""" Class representing Nodes of a tree data structure """ class Node: latest_move: list[dict] def __init__(self, latest_move: dict, evaluation): self.latest_move = [latest_move] if latest_move else list() self.child_nodes = list() self.board_evaluation: float = evaluation def add...
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") def berty_go_repositories(): # utils maybe( git_repository, name = "bazel_skylib", re...
y: Tuple[int, ...] x: Tuple[int] z: Tuple[Union[int, str]] for ([y, (x, (z))]) in \ undefined(): pass
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: words = set(wordList) if endWord not in words: return [] frontier = collections.deque([(beginWord)]) mn_cost = math.inf costs = {w : math.inf for w in word...
if __name__ == '__main__': stlist = [] marks = set() lower_name = [] for _ in range(int(input())): name = input() score = float(input()) stlist.append([name, score]) marks.add(score) # Increasing order sec = sorted(marks)[1] # print(sec) for name, scor...
#printing fibonacci number until 'n' using python n=int(input("enter the value of 'n': ")) a=0 b=1 sum=0 count=1 print("fibonacci:",end = " ") while(count<=n): print(sum,end=" ") count +=1 a=b b=sum sum=a+b
DEBUG = True PORT = 8080 SECRET_KEY = "secret" WTF_CSRF_ENABLED = True baseUrl = "https://hp8xm3yzr0.execute-api.us-east-2.amazonaws.com/prod/"
class DigestConfig: def __init__(self): self.digest_AAs = "KR" self.Nterm = False self.min_len = 9 self.max_len = 30 self.max_miss_cleave = 2 self.cleave_type = "full" def digest(protein, pepset, conf): if conf.cleave_type == "full": return digest_full(...
def split(str): splitted=str.split(" ") return splitted def join(str): joined="-".join(str) return joined str="Geeks For Geeks" splitted=split(str) print(splitted) print(join(splitted))
def normalise_total_cozie(dataframe, group, threshold): cluster_df = dataframe.copy(deep=True) # remapping cluster_df['prefer_cooler'] = cluster_df['thermal_cozie'][cluster_df.thermal_cozie == 11.0] #Too Hot cluster_df['prefer_warmer'] = cluster_df['thermal_cozie'][cluster_df.thermal_cozie == 9.0] # To...
"""Programa 5_11.py Descrição: Escrever um programa que pergunte o depósito inicial e a taxa de juros de uma poupança. Exibir os ganhos mensais para os 24 primeiros meses. Exiba o total de ganhos para o período Autor:Cláudio Schefer Data: Versão: 001 """ # Declaração de variáveis depósito = float() taxa = float() n...
def stage(hub, name): ''' Take the highdata and reconcoile the extend keyword ''' high, errors = hub.idem.extend.reconcile(hub.idem.RUNS[name]['high']) hub.idem.RUNS[name]['high'] = high hub.idem.RUNS[name]['errors'] = errors
# Formatting configuration for locale sv_SE languages={'gv': 'manx gaeliska', 'gu': 'gujarati', 'rom': 'romani', 'ale': 'aleutiska', 'sco': 'skotska', 'mni': 'manipuri', 'gd': 'skotsk gaeliska', 'ga': u'irl\xe4ndsk gaeliska', 'osa': 'osage', 'gn': u'guaran\xed', 'gl': 'galiciska', 'mwr': 'marwari', 'ty': 'tahitiska', ...
N = int(input()) count = 0 for i in range(1, N+1, 2): yakusuu = 0 for j in range(1, i+1, 2): if i % j == 0: yakusuu += 1 if yakusuu == 8: count += 1 print(count)
""" Data Structures :: LRU Cache """ class ListNode: def __init__(self, key, value, prev=None, next=None): """A node in a doubly-linked list-based LRU cache. :param key : Key by which to access nodes. :param value : Value accessed by key. :param pre...
# @Time : 2019/6/24 23:21 # @Author : shakespere # @FileName: Implement Trie (Prefix Tree).py ''' 208. Implement Trie (Prefix Tree) Medium Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true tri...
""" 44. Wildcard Matching Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "*" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = "cb" p = "?a" Output: false Explanation: '?' matches ...
"""P7E8 VICTORIA PEÑAS Escribe un programa que pida una frase, y pase la frase como parámetro a una función que debe eliminar los espacios en blanco (compactar la frase). El programa principal imprimirá por pantalla el resultado final. + info en https://stackoverrun.com/es/q/2136639""" def eliminarEspacios(seq): re...
class reverse_iter: def __init__(self, elements): self.elements = elements self.start = len(self.elements) - 1 def __iter__(self): return self def __next__(self): if self.start < 0: raise StopIteration index = self.start self.start -= 1 ...
N,K=map(int, input().split()) A=list(map(int, input().split())) # sort用 l = [[] for _ in range(K)] # 分配 for i in range(len(A)): ii = i%K l[ii].append(A[i]) # sort for i in range(len(l)): l[i].sort() # 元に戻す ll=[] for i in range(len(A)): ii = i%K jj = i//K val = l[ii][jj] ll.append(val) for...
# -*- coding: UTF-8 -*- # 숫자 포멧팅 def filter_number_format(value): return "{:,}".format(int(value))
# syms =['["2_x00"]', '["2_0y0"]', '["2_00z"]', # '["2_xx0"]', '["2_x0x"]', '["2_0yy"]', # '["2_xmx0"]', '["2_mx0x"]', '["2_0myy"]', # # '["3_xxx"]', '["3_xmxmx"]', # '["3_mxxmx"]', '["3_mxmxx"]', # # '["m3_xxx"]', '["m3_xmxmx"]', # '["m3_mxxmx"]', '["m3_mxmxx"]', # # '["4_x00"]', '["4_0y0"]', '["4_00z"]', # # '["-4_x0...
class NetstorageError(Exception): def __init__(self, response, *args, **kwargs): super(NetstorageError, self).__init__(response) self.msg = kwargs.get('message') class NotFoundError(NetstorageError): def __init__(self, response, *args, **kwargs): message = ('Can occur if the targeted ...
""" Rinzler's exceptions module :author: Rinzler<github.com/feliphebueno> :date: 14/07/2018 """ __author__ = "Rinzler<github.com/feliphebueno>" class RinzlerHttpException(BaseException): """ Rinzler's base HTTP Exception, all other HTTP Exceptions must subclass this class as well as override it's properti...
# numbers to letters small = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'] tens = ['mistake0','mistake1','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety'] # simple algori...
ALPHABET = 'abcdefghijklmnopqrstuvwxyz' def increment(word: str) -> str: last_index = len(word) - 1 if word[last_index] != 'z': return word[:last_index] + ALPHABET[ALPHABET.find(word[last_index]) + 1] elif len(word) == 1: return "aa" else: return increment(word[:last_index]) + ...
DB_CONFIG_DEV = {'host': 'host', 'usuario':'usr_pesquisabr', 'senha':'senhapesquisabr', 'database': 'pesquisabr' } DB_CONFIG_PROD = {'host': 'host', 'usuario':'usr_pesquisabr', 'senha':'senhapesquisabr', 'database': 'pesquisabr' } ...
def diag_diff(matr): sum1 = 0 sum2 = 0 length = len(matr[0]) for i in range(length): for j in range(length): if i == j: sum1 = sum1 + matr[i][j] if i == length - j - 1: sum2 = sum2 + matr[i][j] return sum1 - sum2
# # PySNMP MIB module HH3C-DOT11-RRM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-DOT11-RRM-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:26:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
# Aula 07 - Desafio 14: Conversor de temperatura entre °C e °F c = float(input('Informe a temperatura em graus Celsius: ')) f = (1.8 * c) + 32 print(f'A temperatura de {c:.2f}ºC equivale a {f:.2f}ºF')
class Solution: """ @param source: @param target: @return: return the index """ def strStr(self, source, target): l = len(target) for i in range(len(source) - l + 1): if source[i:i+l] == target: return i return -1
change = 91 coin = 25 print('how many quarters in 91 cents? 3') print('how much change is left after 3 quarters taken out of 91cents? 16') print(91 / 25, 'is not the awnser to either question') print(91//25) print(91%25)
"""from django.contrib import admin from .models import Status @admin.register(Status) class StatusAdmin(admin.ModelAdmin): list_display = ('shape', 'created_at') admin.site.register(Status, StatusAdmin) """
# binary search def binarySearchRec(sort: list, target: int, start: int, stop: int, value: bool): """binary search with recursion""" if start > stop: if value: return None # not found value else: return -1 # not found index else: mid = (start + stop) // 2 ...
a = input("Enter a number: ") prev = None flag = True if len(a)==1: flag = False for elm in a: if prev == None: prev = int(elm) else: if prev > int(elm): prev = int(elm) else: flag = False break print(flag)
BATTERY_UUID = "0000ec08-0000-1000-8000-00805f9b34fb" DEVICE_USER_NAME_UUID = "0000ec01-0000-1000-8000-00805f9b34fb" UPDATED_AT_UUID = "0000ec09-0000-1000-8000-00805f9b34fb" MODEL_NUMBER_UUID = "00002a24-0000-1000-8000-00805f9b34fb" MANUFACTURER_UUID = "00002a29-0000-1000-8000-00805f9b34fb" VALVE_MANUAL_SETTINGS_UUID ...
""" Quetion 29 : Define a function that can accept two string as input and then print it in console. Hints : Ues + to concatenate the strings. """ # Solution : def print_value(s1, s2): print(s1 + s2) print_value("3", "4") """ Output : 34 """
""" PSET-7 Part 3: Filtering At this point, you can run ps7.py, and it will fetch and display Google and Yahoo news items for you in little pop-up windows. How many news items? All of them. Right now, the code we've given you in ps7.py gets all of the feeds every minute, and displays the result. This is nice, but,...
GIT_ACTION_RESULT = 'result' GIT_ACTION_ADVERTISEMENT = 'advertisement' GIT_ACTIONS = [GIT_ACTION_ADVERTISEMENT, GIT_ACTION_RESULT] def is_valid_git_action(action): """ Returns true if the given action is one of git valid actions. """ return action in GIT_ACTIONS
# CSC 110 - Practice Activity #2 # Tip Calculator # Section 03 # Justin Clark # 1/14/2020 # input billAmountEntered = float(input('Enter bill amount $: ')) tipPercentEntered = float(input('Enter tip %: ')) # processing tipCalculated = billAmountEntered * (tipPercentEntered / 100) amountToPay = billAmountEntered + tip...
# -*- coding: utf-8 -*- __version__ = (1, 0, 0) default_app_config = "taiga_contrib_fan.apps.TaigaContribFanAppConfig"
i = 0 n = int(input()) while (n > 0): i += n n -= 1 print('Sum is',i)
# SPDX-License-Identifier: Apache-2.0 # Copyright © 2019-2022 Tensil AI Company class Slice: def __init__(self, address, buf): self.address = address self.buffer = buf def __iter__(self): return self.buffer def __len__(self): return len(self.buffer) def __getitem__(se...
EDIT_COLS = ['H', 'L'] HEADER_ROWS = 2 HIDE_COLS = ['A', 'B', 'C', 'D', 'F', 'K'] CHAR_LIMIT_VAL_COL = 'I' CHAR_LIMIT_APPLY_COL = 'H' CHAR_LIMIT_REGEX = r'(\d+)\s*文字'
class Point: def __init__(self, x, y): self._cluster = 0 # Not classified yet self._visited = False self._x = x self._y = y def get_cluster(self): return self._cluster def set_cluster(self, cluster): self._cluster = cluster def get_values(...
#! /usr/bin/env python3 def add_verticle(a, b) : global verticles if a in verticles : verticles[a].append(b) else : verticles[a] = [b] return verticles def all_paths_util(u, path = []) : global verticles if u in path and not u.upper() == u : return [] path.append(u) if u == 'end...
class SingleLed(object): """Represents a single LED that is connected to the ESP32""" def __init__(self, pin): self.pin = pin def write_on(self, is_on): print("Setting LED on pin {} to {}".format(self.pin, is_on)) # TODO: Actually call MicroPython code to set the output
class Solution: def totalHammingDistance(self, nums: List[int]) -> int: total = 0 for b in zip(*map('{:030b}'.format, nums)): zeros = b.count('0') total += zeros * (len(b) - zeros) return total
# # PySNMP MIB module HUAWEI-VO-GENERAL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-VO-GENERAL-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:49:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
class Solution: def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ # DP problem if not grid or not grid[0]: return 0 dp = [grid[0][0]] for num in grid[0][1:]: dp.append(dp[-1] + num) m, n = len(g...
#!/usr/bin/env python3 # Day 22: Subarray Sum Equals K # # Given an array of integers and an integer k, you need to find the total # number of continuous subarrays whose sum equals to k. class Solution: def subarraySum(self, nums: [int], k: int) -> int: count = 0 ways_to_sum = {} current_s...
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. """ if not head: ret...
gamemat = [0] * 4 for i in range(4): gamemat[i] = [0] * 4 player = 1 gameEnd = False gameResult = None def readInput(currentPlayer): print("Player " + str(currentPlayer) + " (input x and y, seperated with a space): ", end = "") try: x,y = input().split() x = int(x) y = int(y) ex...
## # check_if_correct: # def check_if_correct(): ''' @summary reusable while loop to check if alarm time is correct @desc Infinitely loops as long as the user does not input a "Y" or "N" @author Brandon Benefield @since v1.0.0 @param {void} @return {void} ...
# python3: CircuitPython 3.0 # Author: Gregory P. Smith (@gpshead) <greg@krypto.org> # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache....
class Suggestion: """ Object containing the data to suggest """ def __init__( self, email_address, name, content, ): self.email_address = email_address self.name = name self.content = content def __hash__(self): return hash((self.email_address, self.name...
# coding: utf-8 __author__ = 'deff' # Andoid-afl.https://github.com/ele7enxxh/android-afl # Fuzzing with libFuzzer. # Droid: Android application fuzzing framework.https://github.com/ajinabraham/Droid-Application-Fuzz-Framework # Writing the worlds worst Android fuzzer, and then improving it, by Gamozo 2018. # Fuzzing...
# Задача 10 # Напишите программу "Генератор персонажей" для игры. Пользователю должно #быть предоставлено 30 пунктов, которые можно распределить между четырьмя #характеристиками: Сила, Здоровье, Мудрость и Ловкость. Надо сделать так, чтобы #пользователь мог не только брать эти пункты из общего "пула", но и возвраща...
def pig_latin(text_input): final = "" # create final string, couples, and split text_input couples = ['bl', 'br', 'ch', 'cl', 'cr', 'dr', 'fl', 'fr', 'gh', 'gl', 'gr', 'ph', 'pl', 'pr', 'qu', 'sh', 'sk', 'sl', 'sm', 'sn', 'sp', 'st', 'sw', 'th', 'tr', 'tw', 'wh', 'wr'] split_t...
# ДЗ 2 Про # 1. Выведем на экран циклом пять пронумерованных строк из нулей for i in range(5): print(i+1, '0') # 2. Пользователь в цикле вводит 10 цифр. Находим количество введенных пользователем цифр 5. summ = 0 for i in range(10): answer = int(input('Please enter a number: ')) if answer == 5: su...
lista = [1, 3, 5, 7] lista_animal = ['cachorro', 'gato', 'elefante'] print(lista) print(lista_animal[1]) #Resultado: gato for x in lista_animal: print(x)
def add(x, y): '''Add two given numbers together ''' return x+y def subtract(x, y): ''' function to substrct x from y and return the remaining value''' return y - x
# https://leetcode.com/problems/verifying-an-alien-dictionary/ class Solution: def isAlienSorted(self, words: [str], order: str) -> bool: m = {} for i, o in enumerate(order): m[o] = i def is_sorted(w1, w2): for c1, c2 in zip(w1, w2): if ...
# Character Picture Grid Practice Project # Chapter 4 - Lists (Automate the Boring Stuff with Python) # Developer: Valeriy B. def picture_grid(grid): # Creating result list resulted_list = [] # Looping through grid columns for column in range(len(grid[0])): # Creating row string ...
# @Author: allen # @Date: May 08 18:01 2020 class Genre: genres = { 0: 'Blues', 1: 'Classic rock', 2: 'Country', 3: 'Dance', 4: 'Disco', 5: 'Funk', 6: 'Grunge', 7: 'Hip-Hop', 8: 'Jazz', 9: 'Metal', 10: 'New Age', 11: 'O...
def index(query): query = query.strip("/") fd = open("css/" + query, "r") return fd.read()
""" Implementation of Array from the ground up. We have lists in python that compares to an array data structure and should be used instead of building an array data structure from scratch. """ class Array: # __init__ is a special method called whenever you try to make # an instance of a class. As you heard, ...
class Symptom(object): def __init__(self,name): self.name = name self.weight = 0.0 self.talks = "" # 症狀的口語描述 self.diseases = None # 一個症狀對應的可能疾病集 self.toggle = False # 標記症狀是否已被詢問過 def __str__(self): res = self.name + " with weight: " + str(self.weight) + "\ndesc...
""" Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: - 0 <= i <= s.length - 2 - s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # file:filetemplate.py # author:Nathan # datetime:2021/8/27 13:19 # software: PyCharm """ this is function description """ class FileTemplate(object): app_setting = """#!/usr/bin/env python # -*- coding:utf-8 -*- \"\"\" 应用的配置加载项 \"\"\" im...
"""A number of dictionaries that map IDs to a label. """ # Maps Device EUI to a Label dev_lbls = dict( A81758FFFE0523DB = 'Tyler ELT-Lite 23DB', A81758FFFE05368E = '122 N Bliss', A81758FFFE05368F = '122 N Bliss Unit', A81758FFFE05569F = '3414 E 16th', A81758FFFE0556A0 = '3424 E 18th', A81758FFF...
# To Enable Custom Rich Presence, Please Make Sure "RPC_BOOL" is True in env file. # Custom Rich Presence (Edit as you like.) ENABLE_CUSTOM_RICH_PRESENCE=False # ⚠ RP_Prority_Order Number should not be same for other RPs. SHOW_RECO_RP=(True,15,2) # (True/False, Interval=15, RP_...
def outer (): def inner(): print(x ) x = 12 inner() outer()
print ("--------------------------------------------------") cad1 = "separar" print (cad1) nuevo_string1 = ",".join(cad1) print (nuevo_string1) print ("--------------------------------------------------") cad2 = "mi archivo de texto.txt" print (cad2) nuevo_string2 = cad2.split() nuevo_string2 = "_".join(nuevo_...
def is_even(n): if n % 2 == 0: return True def is_positive(n): if n >= 0: return True def get_result(collection): result = [str(x) for x in collection] return ", ".join(result) numbers = [int(x) for x in input().split(", ")] positive_nums = [] negative_nums = [] even_nums = [] odd_nu...
# -*- coding: utf-8 -*- """ Natural Convection heat transfer calculation based on Churchill and Chu correlation """ def Churchill_Chu(D, rhof, Prf, kf, betaf, alphaf, muf, Ts, Tinf): """ Natural Convection heat transfer calculation based on Churchill and Chu correlation :param D: [m] Pipe inside di...
def multi_print(number = 3, word = "Hallo"): for i in range(0, number): print(str(i) + " " + word) multi_print(1, "Hallo") print("--") multi_print() print("--") multi_print(2) print("--") multi_print(word = "Welt") print("--") multi_print(word = "Welt", number = 5) print("--")
""" The structure of a blockchain, Which is accessed like JSON or a dict. """ block = { "index": 1, "timestamp": 1506057125.900785, "transactions": [ { "sender": "8527147fe1f5426f9dd545de4b27ee00", "recipient": "a77f5cdfa2934df3954a5c7c7da5df1f", "amount": 5, ...
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. _blank_symbol_ctc = '_' _pad_symbol = '#' _characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ\' ' # Export all symbols: symbols = [_blank_symbol_ctc] + list(_characters) + [_pad_symbol] # Mappings from symbol to numeric ID and vice versa # (remember - ID zero ...
PEER_DID_NUMALGO_0 = "did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V" DID_DOC_NUMALGO_O_BASE58 = """ { "id": "did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V", "authentication": [ { "id": "did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv2...
a={"nome":"Pedro","idade":18,"sexo":"M"} print(a.values()) print(a.keys()) print(a.items()) for k,v in a.items(): print(f"{k} é {v}.")
idade = int(input('Digite a sua idade: ')) if idade <= 14: print('Não faz parte da tabela') else: if idade <= 20: print('Geração Z') elif idade <= 34: print('Geração Y') elif idade <= 49: print('Geração X') elif idade < 65: print('Geração Baby Boomers') ...
class Solution: def longestSubsequence(self, arr: List[int], diff: int) -> int: dp = {} for num in arr: if num - diff in dp: cnt = dp.pop(num - diff) dp[num] = max(dp.get(num, 0), cnt + 1) else: dp[num] = max(dp.get(num, 0), 1) ...
numbers = [1, 45, 31, 12, 60] for number in numbers: if number % 8 == 0: print ("THe numbers are unacccepetble") break else: print ("The Numbers are good")
''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false ''' class...
class rational: def __init__(self, x, y): gcd = self.__gcd(x, y) self.d = x // gcd # denominator self.n = y // gcd # numerator def __gcd(self, x, y): while y > 0: x, y = y, x % y return x def __add__(self, other): return rational( ...
#module for data updating def update_data_set(text_file_name:str, data:{'Time':int, "Mood":int, "Age":int}, class_res:int): '''Given a text file name and data, it will open the text file and update the file with new data in format "int,int,int" ''' file = open(text_file_name, "a") elements_for_dat...
# https://www.codementor.io/moyosore/a-dive-into-python-closures-and-decorators-part-1-9mpr98pgr def add_all_arguments(*args): result = 0 for i in args: result += i return result print(add_all_arguments(1, 5, 7, 9, 10)) # 32 print(add_all_arguments(1, 9)) # 10 print(add_all_arguments(1, 2, 3, ...
""" POO - Classes Em POO, Classes nada mais são do que modelos dos objetos do mundo real sendo representados computacionalmente. Imagine que você queira fazer um sistema para automatizar o controle das lâmpadas da sua casa. Classes podem conter: - Atributos -> Representam as características do objeto. Ou seja, ...
# Do DFS on input. Maintin a set of keys_collected. Do not push a room if it's there in the keys_collected set. class Solution(object): def canVisitAllRooms(self, rooms): """ :type rooms: List[List[int]] :rtype: bool """ S = [rooms[0]] keys_collected = set([...