content
stringlengths
7
1.05M
'''A confederação nacional de natacao precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade até 9 anos> MIRIM até 14 anos: INFANTIL até 19 anos JUNIOR até 20 anos SENIOR acima: MASTER'''
# Q1 class Thing: pass example = Thing() print(Thing) print(example) # Q2 class Thing2: letters = 'abc' print(Thing2.letters) # Q3 class Thing3: def __init__(self): self.letters = 'xyz' thing3 = Thing3() print(thing3.letters) # Q4 class Element: def __init__(self, name, symbol, numb...
j = 7 for i in range(1,(10),2): for jump in range(0,3): print("I={0} J={1}".format(i,j)) j = j - 1 j = 7
# def welcome(): # return 'Welcome to the Python' # basic function # # def uppercase_decorator(function): # parameter function # def wrapper(): # function inside of uppercase # func = function() # variable == function() # make_uppercase = func.upper() # transforma o retorno da função chamada em ...
result = [ [0.6, 0.7], {'a': 'b'}, None, [ 'uu', 'ii', [None], [7, 8, 9, {}] ] ]
def DependsOn(pack, deps): return And([ Implies(pack, dep) for dep in deps ]) def Conflict(p1, p2): return Or(Not(p1), Not(p2)) a, b, c, d, e, f, g, z = Bools('a b c d e f g z') solve(DependsOn(a, [b, c, z]), DependsOn(b, [d]), DependsOn(c, [Or(d, e), Or(f, g)]), Conflict(d, e), a, z)...
# # PySNMP MIB module SW-LAYER2-PORT-MANAGEMENT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-LAYER2-PORT-MANAGEMENT-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:12:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ve...
# -*- coding: utf-8 -*- if 1 == 1: print ("1 é igual a 1") if not 1 == 2: print ("1 é diferente de 2") if True: print ("Bloco True executado") if False: print ("Bloco False não será executado")
'''Uma empresa decidiu fazer um levantamento em relação aos candidatos que se apresentarem para preenchi- mento de vagas em seu quadro de funcionários. Supondo que você seja o programador dessa empresa, faça um programa que leia, para cada candidato, a idade, o sexo (M ou F), e a experiência no serviço (S ou N). Para e...
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: sample_11.1 Description : date: 2022/2/18 ------------------------------------------------- """ class Vector2d: typecode = 'd' def __init__(self, x, y): self.x = float(x) self.y = fl...
class Queue: # Constructor to initiate queue def __init__(self, queue=None): if queue is None: queue = [] self.queue = queue # push to append an item into queue def push(self, value): self.queue.append(value) # front to return starting element from queue de...
class EnumType(object): # Internal data storage uses integer running from 0 to range_end # range_end is set to the number of possible values that the Enum can take on # External representation of Enum starts at 1 and goes to range_end + 1 def __init__(self, initial_value): self.set(initial_valu...
# -*- coding: utf-8 -*- # class LineLoop(object): _ID = 0 dimension = 1 def __init__(self, lines): self.lines = lines self.id = 'll{}'.format(LineLoop._ID) LineLoop._ID += 1 self.code = '\n'.join([ '{} = newll;'.format(self.id), 'Line Loop({}) = {...
# Binary search def binary_search(A: list, x: int): i = 0 j = len(A) while i < j: m = (i + j) // 2 if A[m] == x: return True elif A[m] > x: j = m else: i = m + 1 return False def recursive_binary_search(A: list, x: int, start: int, end: int): if end >= start: m = start...
class BaseDBDriver(): """ This will stub the most basic methods that a GraphDB driver must have. """ _connected = False _settings = {} def __init__(self, dbapi): self.dbapi = dbapi def _debug(self, *args): if self.debug: print ("[GraphDB #%x]:" % id(self)...
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: s = list(s); lines = 1; line = 0 while s: if line + widths[ord(s[0])-97] > 100: lines += 1; line = 0 else: line += widths[ord(s.pop(0))-97] return [lines, ...
Lakh = 100 * 1000 Crore = 100 * Lakh biggerNumbers = { 100 : "sau", 1000 : "hazaar", Lakh : "laakh", Crore : "karoD" }
class Match: def __init__(self): self.date = "" self.round = "" self.tournament = "" self.home = "" self.score = "" self.away = "" self.channels = ""
#پروژه بانک #نوشته شده توسط امیر حسین غرقی class Bank: def Create(self): self.first_name = input( 'Enter first name : ') self.last_name = input("Enter your last name : ") self.phone_number = input("Enter your phone number, sample : 0912*****54 :") self.value = float(input("Ent...
class Solution: def intToRoman(self, num): """ :type num: int :rtype: str """ res = "" while num: if num >= 1000: res += (num//1000) * 'M' num = num%1000 elif num >= 900: res += 'CM' ...
pairs = [] with open("dane/pary.txt") as f: for line in f: parsed_line = line.strip().split() num = int(parsed_line[0]) text = parsed_line[1] pairs.append(tuple([num, text])) def is_prime(num: int) -> bool: for i in range(2, num): if num % i == 0: return F...
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: prod = 1 prods = [1]*len(nums) for i in range(len(nums)): prods[i] = prod prod *= nums[i] prod = 1 for i in range(len(nums)-1, -1, -1): prods[i...
def all_index(array, num): indx = [] for i in range(0,len(array)): for j in range(0,array[i].count(num)): if j == 0: indx.append([i, array[i].index(num)]) else: indx.append([i, array[i].index(num,indx[j-1][1]+1)]) return indx tic = [[1,1,0]...
"""This problem was asked by Uber. You have N stones in a row, and would like to create from them a pyramid. This pyramid should be constructed such that the height of each stone increases by one until reaching the tallest stone, after which the heights decrease by one. In addition, the start and end stones of the p...
""" 给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1。 返回使 A 中的每个值都是唯一的最少操作次数。 示例 1: 输入:[1,2,2] 输出:1 解释:经过一次 move 操作,数组将变为 [1, 2, 3]。 示例 2: 输入:[3,2,1,2,1,7] 输出:6 解释:经过 6 次 move 操作,数组将变为 [3, 4, 1, 2, 5, 7]。 可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。 提示: 0 <= A.length <= 40000 0 <= A[i] < 40000 来源:力扣(LeetCode) 链接:https://leetcode...
"""Constants for the xbox integration.""" DOMAIN = "xbox" OAUTH2_AUTHORIZE = "https://login.live.com/oauth20_authorize.srf" OAUTH2_TOKEN = "https://login.live.com/oauth20_token.srf" EVENT_NEW_FAVORITE = "xbox/new_favorite"
def encrypt(message, key): encrypted_message = '' for char in message: if char.isalpha(): #ord() returns an integer representing the Unicode code point of the character unicode_num = ord(char) unicode_num += key if char.isupper(): ...
# In "and" operator if ONE is false the whole is false # in "or" operator if ONE is true the whole is true print("Welcome to the rollercoaster!") height = int(input("What is your height in cms? ")) bill = 0 if height >= 120: print("You can ride the rollercoaster") age = int(input("What is your age...
lista = [4,14,24,34,44] q4 = int(input("a soma dos dois dígitos é igual a?")) numero_final = [] for x in range(len(lista)): valor = str(lista[x]) dig_um = int(valor[0]) if lista[x]>9: dig_dois = int(valor[1]) if lista[x]<10: if dig_um== q4: numero_final.append(lista[...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Problem 021 Divisible Sum Pairs Source : https://www.hackerrank.com/challenges/divisible-sum-pairs/problem """ _, d = map(int, input().split()) numbers = list(map(int, input().split())) nb = len(numbers) count = 0 for i in range(nb-1): for j in range(i+1, nb): ...
class User: def __init__(self, username, name, email, bio, repositories): self.username = username self.name = name self.email = email self.bio = bio self.repositories = repositories def __str__(self): final = "Name: {} ({}):".format(self.name, self.username) ...
#------------------------------------------------------------------------------- def checkUser( username, passwd ): return False #------------------------------------------------------------------------------- def checkIfUserAvailable( username ): return False #------------------------------------------------...
# using modified merge function def compute_union(arr1, arr2): union = [] index1 = 0 index2 = 0 while (index1 < len(arr1)) and (index2 < len(arr2)): if arr1[index1] < arr2[index2]: union.append(arr1[index1]) index1 += 1 elif arr1[index1] > arr2[index2]: ...
levels = [ #{ # 'geometry': [ ' bbb ', # ' bbb ', # ' bbb ', # ' bbb ', # ' b ', # ' b ', # ' bbb ', # ...
while True: a, b, c = sorted(map(int, input().split())) if a == 0 and b == 0 and c == 0: break print("right" if a ** 2 + b ** 2 == c ** 2 else "wrong")
# EASY # count each element in array and store in dict{} # loop through the array check if exist nums[i]+1 in dict{} class Solution: def findLHS(self, nums: List[int]) -> int: n = len(nums) appear = {} for i in range(n): appear[nums[i]] = appear.get(nums[i],0) + 1 ...
class Clock(): # Set initial Clock state def __init__(self, hours, minutes): timeDic = self.calculateMinutes(minutes) self.minutes = timeDic['minutes'] self.hours = self.calculateHour(hours + timeDic['hours']) self.time = self.generateTimeString() # Add minutes to the cl...
class Order: __slots__ = ( 'id', 'order_number', 'customer_name', 'shipping_name', 'order_date', 'order_details_url', 'subtotal', 'shipping_fee', 'tax', 'status', 'retail_bonus', 'order_type', 'customer_url', ...
''' Find the largest continuous sum ''' def largest_cont_sum(arr): if len(arr) == 0: return 0 cur_sum = arr[0] max_sum = arr[0] for item in arr[1:]: cur_sum = max(cur_sum+item, item) if cur_sum >= max_sum: max_sum = cur_sum return max_sum
tupla = ( int(input('Digite um número: ')), int(input('Digite outro número: ')), int(input('Digite mais número: ')), int(input('Digite o último número: ')) ) print('Você digitou os valores: {}'.format(tupla)) print('O número 9 apareceu {} vezes.'.format(tupla.count(9))) if 3 in tupla: print('O núme...
class Solution: def matrixReshape(self, mat: List[List[int]], newRows: int, newCols: int) -> List[List[int]]: rows = len(mat) cols = len(mat[0]) if rows * cols != newRows * newCols: return mat newMat = [[0] * newCols for _ in range(newRows)] for x in range(rows...
input = """ c num blocks = 1 c num vars = 180 c minblockids[0] = 1 c maxblockids[0] = 180 p cnf 180 765 43 -70 -94 0 80 70 -20 0 34 -89 37 0 -99 -140 153 0 -30 131 14 0 136 20 17 0 -125 -172 -114 0 19 -13 -126 0 127 -138 -142 0 -127 -84 79 0 -63 -13 50 0 -15 -118 17 0 6 65 -116 0 -30 -167 157 0 -156 -143 -12 0 38 -60 1...
def multiplication_table(size): return [[ x * y for y in range(1, size + 1)] for x in range(1, size + 1)] print(multiplication_table(3)) # [[1,2,3],[2,4,6],[3,6,9]]
algo = input('Digite algo: ') print('Tipo do valor:', type(algo)) print('è um número ?:', algo.isnumeric()) print('é alfabeto', algo.isalpha()) print('é um alfanumerico ', algo.isalnum())
a=5 b=50 if a>=b: c=a-b else: c=a-b print(c)
# -*- coding: utf-8 -*- # Put here your production specific settings ADMINS = [ ('Francesca Alberti', 'francydark91@gmail.com'), ] EMAIL_SUBJECT_PREFIX = '[ALBERTIFRA]'
# autocord # package for simple automation with discord client # # m: error class ApiError(Exception): pass
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt copy("src", "out_encodings") run(""" coverage run utf8.py coverage annotate utf8.py """, rundir="out_encodings") compare("out_encodings", "gold_encoding...
""" 0604. Design Compressed String Iterator Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string. Implement the StringIter...
class HarmonyConfig(object): def __init__(self, config): self.json = config def get_activities(self): return self._build_kv_menu('activity') def get_devices(self): return self._build_kv_menu('device') def _build_kv_menu(self, key): menu = {} for d in self.json[...
# Copyright 2018 Databricks, Inc. VERSION = "1.12.1.dev0"
#!/usr/bin/env python # # Copyright (c) 2018 10X Genomics, Inc. All rights reserved. # __MRO__ = """ stage CHOOSE_DIMENSION_REDUCTION( in bool chemistry_batch_correction, out bool disable_run_pca, out bool disable_correct_chemistry_batch, src py "stages/analyzer/choose_dimension_reduction", ) """ ...
'''https://leetcode.com/problems/longest-common-subsequence/ 1143. Longest Common Subsequence Medium 4663 55 Add to List Share Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated f...
# Copyright 2021 BenchSci Analytics Inc. # Copyright 2021 Nate Gay # # 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 a...
class Program: language = 'Python' def say_hello(): print(f'Hello from {Program.language}') p = Program() print(type(p)) print(p.__dict__) print(Program.__dict__) print(p.__class__) # BEST PRACTICES print(isinstance(p, Program))
def assert_status_with_message(status_code=200, response=None, message=None): """ Check to see if a message is contained within a response. :param status_code: Status code that defaults to 200 :type status_code: int :param response: Flask response :type response: str :param message: String...
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-01-15 16:40:08 # @Last Modified by: 何睿 # @Last Modified time: 2019-01-15 17:49:45 class MinStack(object): # 栈中存储的是元组(当前位置的值,当前位置到栈底所有值的最小值) def __init__(self): """ initialize your data structure here. """ ...
class TreeLeaf( object ): """Base class for Tree Leaf objects. Supports a single parent. Cannot have children. """ def __init__( self ): """Creates a tree leaf object. """ super( TreeLeaf, self ).__init__() self._parent = None @pr...
def roman_to_int(s): s = s.upper() try: rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} int_val = 0 for i in range(len(s)): if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]: int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]] ...
#!/usr/bin/env python3 """ This module containes general-purpose chemical data (aka tables). Sources: 1. www.ccdc.cam.ac.uk/Lists/ResourceFileList/Elemental_Radii.xlsx, (access date: 13 Oct 2015) 2. C. W. Yong, 'DL_FIELD - A force field and model development tool for DL_POLY', R. Blake, Ed., CSE Fron...
class OuterClass(object): def outer_method(self): def nested_function(): class InnerClass(object): class InnermostClass(object): def innermost_method(self): print() InnerClass.InnermostClass().innermost_method() ...
# -*- coding: utf-8 -*- # # Copyright (c) 2015, ParaTools, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # (1) Redistributions of source code must retain the above copyright notice, # t...
# S-box Table # We have 8 different 4x16 matrices for each S box #It converts 48 bits to 32 bits # Each S box will get 6 bits and output will be 4 bits s_box = [ [[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [4, 1, 14, 8...
# Python INTRO for TD Users # Kike Ramírez # May, 2018 # Understanding Dictioinaries # Declaring a dictionary Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} # Print a chosen value print((Dict['Tiffany'])) # Copy a dictionary DictCopy = Dict.copy() print(DictCopy) # Update a dictionary Dict.update({"Sara...
# Split target image into an MxN grid def splitImage(image, size): W, H = image.size[0], image.size[1] m, n = size w, h = int(W/n), int(H/m) imgs = [] for j in range(m): for i in range(n): # append cropped image imgs.append(image.crop((i*w, j*h, (i+1)*w, (j+1)*h...
def is_vowel(s: str) -> bool: if len(s) == 0 or len(s) > 1: return False vowel = ["a", "e", "i", "o", "u"] for item in s: if item.lower() in vowel: return True return False
# content of test_sample.py def func(x): return x + 2 def test_answer(): assert func(3) == 5 def test_2(): assert func(10) == 12
''' Created on Aug 7, 2017 @author: duncan ''' class Subscriber(object): def __init__(self, subscriber_id, subscriber_email): self.subscriber_id = subscriber_id self.subscriber_email = subscriber_email class Site(object): def __init__(self, site_id, site_name): self.site_id...
''' Se um objeto anda como um pato e faz quack como um pato então ele é um pato Se o objeto responde a uma caracteristica ele pode ser considerado do mesmo tipo. Programa para interfaces e não para uma implementação ''' class Livro(): def __init__(self, titulo, lancamento, autor): self.titulo = titul...
# 2. Use the function to compute the square of all numbers of a given list def squares(a): squared = a*a return squared li = [1, 2, 3, 4, 5] lisq=[] for el in li: sq = squares(el) lisq.append(sq) print(lisq)
# coding: utf-8 __author__ = 'Keita Tomochika' __version__ = '0.0.1' __license__ = 'MIT'
name = "openjpeg" version = "2.3.1" authors = [ "Image and Signal Processing Group, UCL" ] description = \ """ OpenJPEG is an open-source JPEG 2000 codec written in C language. It has been developed in order to promote the use of JPEG 2000, a still-image compression standard from the Joint Photograph...
# Subject - the one to be observed # Observers - the one monitoring or observing the subject for changes class Subject: def __init__(self): self.__observers = [] def register(self, observer): self.__observers.append(observer) def notifyAll(self, *args, **kwargs): for observer in ...
# Seeing the greatest number def high(): print('-'*50) print('The numbers informed are: ', end='') for n in numbers: print(n, end= ' ') print('') print('-'*50) print(f'At all, were informed {len(numbers)} values.') print(f'The highest number informed was {max(numbers)}') print('-...
def galoisMult(a, b): ''' The parameter b will be either 1, 2 or 3. Multiplication by 3 is defined as multiplication by 2 then adding the original value. For example 3x6 is equivalent to 2x6+6. The multiplication by 2 is done with a left shift (a <<= 1) and dropping the MSB. If that bit had been a...
diff_counter = 0 A = input() B = input() for i in range(len(A)): if A[i] != B[i]: diff_counter += 1 if diff_counter > 1: print("LARRY IS DEAD!") elif diff_counter == 1: print("LARRY IS SAVED!") else: print("LARRY IS DEAD!")
""" dir([object]) Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. """ class A: name = "Derick" age = 30 class Shape: def __dir__(self): return ['area', 'location', 'shape',] def b(): c = 1 ...
class Method: CHAR = 'char' WORD = 'word' SPECTROGRAM = 'spectrogram' AUDIO = 'audio' FLOW = 'flow' @staticmethod def getall(): return [Method.CHAR, Method.WORD, Method.AUDIO, Method.SPECTROGRAM, Method.FLOW]
#!/usr/bin/env/python inp = open('top-1m.csv', 'r') out = open('top-1m__.csv', 'a+') out.write('"domain_id,"domain_name"') id = '' domain = '' while True: line = inp.readline() if len(line) > 0: cPos = line.find(',') id = line[:cPos] domain = line[cPos+1:] domain = '"'+dom...
TINY_TEST = False if TINY_TEST: MIN_BOUND = -2 MAX_BOUND = 2 else: MIN_BOUND = -200 MAX_BOUND = 200 WIDTH = (MAX_BOUND - MIN_BOUND) + 3 M = [["."] * WIDTH for i in range(WIDTH)] def setMap(p, v): x, y = p M[y - MIN_BOUND + 1][x - MIN_BOUND + 1] = v def getMap(p): x, y = p return M[...
def even_numbers(func): def wrapper(nums): numbers = func(nums) return [num for num in numbers if num % 2 == 0] return wrapper @even_numbers def get_numbers(numbers): return numbers print(get_numbers([1, 2, 3, 4, 5]))
SEASONS = { 1: { "TITLE" : "Destiny 2", "EXPANSION" : "Destiny 2", "ACTIVE" : False, "YEAR" : "1", "START" : '2017-09-06 17:00:00', "END" : '2017-12-05 17:00:00', }, 2: { "TITLE" : "Curse of Osiris", "EXPANSION" : "Destiny 2", ...
# Given a sorted integer array without duplicates, return the summary of its ranges. # Example 1: # Input: [0,1,2,4,5,7] # Output: ["0->2","4->5","7"] # Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range. # Example 2: # Input: [0,2,3,4,6,8,9] # Output: ["0","2->4","6","8->9"] # Explanation: 2,3...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019-04-10 16:23 # @Author : fgyong 简书:_兜兜转转_ https://www.jianshu.com/u/6d1254c1d145 # @Site : http://fgyong.cn 兜兜转转的技术博客 # @File : Int_sort.py # @Software: PyCharm #得出root为最大值 左右儿子为左右堆的最大值 def big_endian(arr:list,start:int,end:int): root = start ...
#Day 6 : Lets Review for i in range(int(input())): char = input() print("".join(char[::2]),"".join(char[1::2]))
# Copyright 2017 Therp BV, ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Client side message boxes", "version": "13.0.1.0.0", "author": "Therp BV, " "ACSONE SA/NV, " "Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Hidden/Dependency", ...
def linked_sort(a,b,kf=''): mapped = sorted([(i,j) for i,j in zip(a,b)], key=kf or standard) bsr=[j for i,j in mapped] a.sort(key=(kf or standard)) b.sort(key=lambda x: bsr.index(x)) return a standard = lambda x: str(x)
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education # {"feature": "Education", "instances": 34, "metric_value": 0.9597, "depth": 1} if obj[1]>1: # {"feature": "Coupon", "instances": 19, "metric_value": 0.998, "depth": 2} if obj[0]<=3: return 'True' elif obj[0]>3: return 'False' else: return 'False...
one = ['1'] two = ['3'] three = ['9'] a = '1' b = '3' c = '9' v = [0,0,0] for i in range(1000): v[0] = int(a) v[1] = int(b) v[2] = int(c) for i in range(len(a)) : v[0] += int(a[i]) for i in range(len(b)) : v[1] += int(b[i]) for i in range(len(a)) : v[2] += int(c[i]) one.app...
class MovieTrackingCamera: distortion_model = None division_k1 = None division_k2 = None focal_length = None focal_length_pixels = None k1 = None k2 = None k3 = None pixel_aspect = None principal = None sensor_width = None units = None
print("digite um numero para consultar seu intervalo") x = int(input()) if 0 <= x <= 25: print('Intervalo [0,25]') if 25 < x <= 50: print('Intervalo (25,50]') if 50 < x <= 75: print('Intervalo (50,75]') if 75 < x <= 100: print('Intervalo (75,100]') else: print('Fora de intervalo')
""" Implement pow(x, n), which calculates x raised to the power n (i.e., xn). source - https://leetcode.com/problems/powx-n """ """ Time Complexity - O(Logn) Space Complexity - 1 """ # Faster class Solution: def myPow(self, x: float, n: int) -> float: return pow(x, n) """ Time Complexity - O(Logn) Space...
""" Shape Vertices. How to iterate over the vertices of a shape. When loading an obj or SVG, getVertexCount() will typically return 0 since all the vertices are in the child shapes. You should iterate through the children and then iterate through their vertices. """ def setup(): size(640, 360) # Load the sha...
class HttpRequest(): def __init__(self, scope, body, receive, metadata=None, application=None): self._application = application self._scope = scope self._body = body self._cookies = None self._receive = receive self._subdomain, self._headers = metadata ...
""" Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], t...
# This dict is built through the metaclass applied to ExternalProvider. # It is intentionally empty here, and should remain empty. PROVIDER_LOOKUP = dict() def get_service(name): """Given a service name, return the provider class""" return PROVIDER_LOOKUP[name]()
dbodydict = dict() # dtitle, dbody fdbody = open("sample_alldoc_fake_body.dict") while 1: line = fdbody.readline() if not line: break tks = line.strip().split(' ') dbodydict[tks[0]]=tks[1] fclean = open("sample_valid_cqexp.cleaned") fexp = open("sample_valid_cqbody.cleaned",'w') while 1: ...
""" Complex Boolean Expressions if 18.5 <= weight / height**2 < 25: print("BMI is considered 'normal'") if is_raining and is_sunny: print("Is there a rainbow?") if (not unsubscribed) and (location == "USA" or location == "CAN"): print("send email") Good and Bad Examples 1. Don't use True or False...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def viterbi(obs, states, start_p, trans_p, emit_p): V = [{}] # list of dictionaries for st in states: V[0][st] = {"prob": start_p[st] * emit_p[st][obs[0]], "prev": None} # Run Viterbi when t > 0 for t in range(1, len(obs)): V.append({}) ...
# username and password # import sys # import msvcrt # passwor = '' # while True: # x = msvcrt.getch() # if x == '\r': # break # sys.stdout.write('*') # passwor +=x # print '\n'+pass username= input ("enter your username: \n") password = input ("enter your password: \n") print (" you complet...