content
stringlengths
7
1.05M
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2021 Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free...
""" Given a sequence of elements a_1, a_2, ... , a_n, you would like to check whether it contains an element (majority element) that appears more than n/2 times. """ def find_majority_element(values): """ Returns the majority element or None if no such element found """ def find_candidate(): ...
# Exercício Python 24: Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome “SANTO”. cidade = input("Digite o nome da cidade: ") cid = cidade.strip() cid = cid[:5] print(cid.lower() == "santo")
class MultiTable(object): """ Multiplication table for a given multiplicand """ def __init__(self, multiplicand): """ :param multiplicand: Initial value (int) """ if not isinstance(multiplicand, (int, float)): raise TypeError('Expected type(s): num <int, floa...
hour_exam = int(input()) min_exam = int(input()) hour_arrival = int(input()) min_arrival = int(input()) status = 0 exam_time = (hour_exam * 60) + min_exam arrival_time = (hour_arrival * 60) + min_arrival difference = arrival_time - exam_time if difference > 0: status = "Late" elif difference < -30: status =...
def foo(): ''' >>> from mod import good as bad ''' pass
# # PySNMP MIB module CISCO-ETHERNET-FABRIC-EXTENDER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ETHERNET-FABRIC-EXTENDER-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:57:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using...
# Write a function called “isOldEnoughToDrive”. # Given a number, in this case an age, “isOldEnoughToDrive” returns whether a person of this given age is old enough to legally drive in the United States. # Notes: # The legal driving age in the United States is 16. def is_old_enough_to_drive(age): if age >= 16: ...
JAZZMIN_SETTINGS = { # title of the window 'site_title': 'DIT Admin', # Title on the brand, and the login screen (19 chars max) 'site_header': 'DIT', # square logo to use for your site, must be present in static files, used for favicon and brand on top left 'site_logo': 'data_log_sheet/img/log...
numbers = [4, 400, 5000] print("Max Value Element: ", max(numbers)) animals = ["dogs", "crocodiles", "turtles"] print(max(animals)) animals.append(["zebras"]) #adds the the list with one element "zebras" to the existing list as one object. print(animals) animals.extend("zebras") #iterates through the string one...
def get_subarray_sum_1(s_array): #O(n**2) ''' Return max subarray and max subarray sum ''' #initialise variables max_sum = 0 max_sub_array = [] #get all items in array and go through them for item in range(len(s_array)): #get all possible sub arrays while maintaining their max...
#sort function def Binary_Insertion_Sort(lst): for i in range(1, len(lst)): x = lst[i] # here x is a temporary variable pos = BinarySearch(lst, x, 0, i) + 1 for j in range(i, pos, -1): lst[j] = lst[j - 1] lst[pos] = x #binary search func...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists: [ListNode]): nums = [] for node in lists: while node is not None: nums.append(node.val) node = node.next nums.so...
"""Code sample.""" def myfunc(s): """Convert strings to mixed caps.""" ret_val = '' index = 0 for letter in s: if index % 2 == 0: ret_val = ret_val + letter.upper() else: ret_val = ret_val + letter.lower() index = index+1 return ret_val
prog = ['H', 'Q', '9'] code = list(i for i in input()) run = False for i in code: if i in prog: run = True break if run: print('YES') else: print('NO')
def th_selector(over_area, altitude): if altitude <= 10: th_x = over_area // 2 # 40 th_y = over_area // 4 # 20 return th_x, th_y elif altitude <=20: th_x = over_area // 8 th_y = over_area // 20 return th_x, th_y else: th_x = over_area // 20 th_...
MAX_SIZE = 2000001 isprime = [True] * MAX_SIZE prime = [] SPF = [None] * (MAX_SIZE) def sieve(N): isprime[0] = isprime[1] = False for i in range(2, N): if isprime[i] == True: prime.append(i) SPF[i] = i j = 0 while j < len(prime) and i * prime[j] < N and prime[j]...
# # 01 solution line_nums = input().split() remove = int(input()) line_nums_list = [int(x) for x in line_nums] for i in range(remove): line_nums_list.remove(min(line_nums_list)) line_nums = ", ".join([str(x) for x in line_nums_list]) print(line_nums) # # INPUT 1 # 10 9 8 7 6 5 # 3 # # INPUT 2 # 1 10 2 9 3 8 # 2 # #...
def Owl(thoughts, eyes, eye, tongue): return f""" {thoughts} {thoughts} ___ (o o) ( V ) /--m-m- """
""" https://leetcode.com/problems/length-of-last-word/ Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. If the last word does not exist, return 0. Note: A word i...
langversion = 1 langname = "Italiano" ##updater # text construct: "Version "+version+available+changelog #example: Version 3 available, click here to download, or for changelog click here available = " disponibile, clicca qui per scaricare" changelog = ", o clicca qui per il changelog" ##world gen worldify = "Da Imm...
""" Using while loop for the first time. """ #Declaring variables x = 0 #initiating the loop while x >= 10: #Stuff that gets iterated when the condition above is true print("Dard to hai") x = x + 2 #The loop has finally ended print("The loop has finally ended")
''' Routines for generating dynamic files. ''' def file_with_dyn_area( file_path, content, first_guard='<!-- guard line: beginning -->', second_guard='<!-- guard line: end -->'): ''' The function reads a file, locates the guards, replaces the content. ''' full_content = '' g...
# @arnaud drop this file? # ---------------------------------------------------------------------- # # Misc constants # UA_MAXOP = 6 # ---------------------------------------------------------------------- # instruc_t related constants # # instruc_t.feature # CF_STOP = 0x00001 # Instruction doesn't pass execution...
input = """ n(x4000). n(x3999). n(x3998). n(x3997). n(x3996). n(x3995). n(x3994). n(x3993). n(x3992). n(x3991). n(x3990). n(x3989). n(x3988). n(x3987). n(x3986). n(x3985). n(x3984). n(x3983). n(x3982). n(x3981). n(x3980). n(x3979). n(x3978). n(x3977). n(x3976). n(x3975). n(x3974). n(x3973). ...
n = int(input()) if n == 1: print(101) exit() a = sum(map(int, input().split())) ans = 0 for i in range(101): if (a + i) % n == 0: ans += 1 print(ans)
class QuerioFileError(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, args, kwargs)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Possible roles of an agent during task NO_ROLE = 0 WIZARD = 1 APPRENTICE = 2 IN_TRAINING = 10 WIZARD_IN_TRAINING = WIZ...
def countWords(file): wordsCount = 0 with open(file, "r") as f: for line in f: words = line.split() wordsCount += len(words) print (wordsCount)
class SqlInsertError(Exception): def __init__(self, object, table: str) -> None: self.object = object self.table = table super().__init__(f'Could not insert {object.__repr__()} in {table}.') class SqlSelectError(Exception): def __init__(self, table: str, function: str, data=None) -> No...
# -*- coding: utf-8 -*- MONGO_CONFIG = { 'host': '47.93.9.48', 'port': 27017, 'user': 'root', 'pwd': 'Yunxi20191231' } chrome_driver_path = '/usr/local/bin/chromedriver' sogou_wechat_url = 'https://weixin.sogou.com'
# coding: utf-8 # Distributed under the terms of the MIT License. class AppModel(object): def __init__(self): pass def __run__(self): pass
def find_first_invalid(numbers): for k in range(25, len(numbers)): if not any( numbers[i] + numbers[j] == numbers[k] for i in range(k - 25, k) for j in range(i + 1, k) ): return numbers[k] with open("input.txt", 'r', encoding="utf-8") as file: in...
""" You are given the root node of a binary search tree (BST). You need to write a function that returns the sum of values of all the nodes with a value between lower and upper (inclusive). The BST is guaranteed to have unique values. """ # Binary trees are already defined with this interface: # class Tree(object)...
class Solution: def addStrings(self, num1: str, num2: str) -> str: res = '' add_on = 0 i, j = len(num1) - 1, len(num2) - 1 while i != -1 or j != -1: if i != -1 and j != -1: digit_sum = int(num1[i]) + int(num2[j]) + add_on i -= 1 ...
def sort_by_key(my_list=[], keys=[]): """ Reorder your list ASC/DESC based on multiple keys Parameters: :param (list) my_list: list of objects you want to order [{'code': 'beta', 'number': 3}, {'code': 'delta', 'number': 2}] :param (list) keys: list of dict keys and direction t...
# -*- mode: python; -*- # Copyright 2011 Google Inc. All Rights Reserved. # # 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 require...
class Matrix(object): def __init__(self, matrix_string): self.matrix = [] rows = matrix_string.splitlines() for row in rows: self.matrix.append([int(num) for num in row.split()]) def row(self, index): return self.matrix[index - 1] def column(self, index): ...
# coding ~utf-8 """ Author: Louai KB Binary tree classes to implement the Huffman Binary Tree for the compression process. """ class TreeNode: """This class implements the nodes of the tree""" def __init__(self, data : any, character:str=None) -> None: """Constructor of our TreeNode class ...
def mesclaListas(lista1, lista2): lista1.sort() lista2.sort() listaMesclada = [] i = 0 for i in lista2: if lista1[0] < i: listaMesclada.append(lista1.pop(0)) for i in lista1: if lista2[0] < i: listaMesclada.append(lista2.pop(0)) print(lista1, lista2)...
def multBy3(x): return x*3 def add5(y): return y+5 def applyfunc(f, g, p): return f(p), g(p) print(applyfunc(multBy3, add5, 3)) def returnArgsAsList(das, *lis): print(lis) print(das) returnArgsAsList(2, 1,2,3,5,6,'byn')
class Field: def __init__(self, name, encoder, decoder): assert name and isinstance(name, str) assert encoder and callable(encoder) assert decoder and callable(decoder) self.name = name self.encoder = encoder self.decoder = decoder
# # @lc app=leetcode.cn id=547 lang=python3 # # [547] 省份数量 # # https://leetcode-cn.com/problems/number-of-provinces/description/ # # algorithms # Medium (61.46%) # Likes: 503 # Dislikes: 0 # Total Accepted: 118.5K # Total Submissions: 192.9K # Testcase Example: '[[1,1,0],[1,1,0],[0,0,1]]' # # # # 有 n 个城市,其中一些彼...
class StickSymbolLocation(Enum, IComparable, IFormattable, IConvertible): """ Indicates the stick symbol location on the UI,which is used for the BuiltInParameter STRUCTURAL_STICK_SYMBOL_LOCATION. enum StickSymbolLocation,values: StickViewBottom (2),StickViewCenter (0),StickViewLocLine (3),StickViewTop ...
# Programa que calcule a integral simbólica de um polinômio dado nesta forma. poly = [0] const = 'c' def getIntegral(coefficients): return [const] + [coefficients[i] / (i + 1) for i in range(0, len(coefficients))] out = getIntegral(poly) print(out)
def valid(triangle): big = max(triangle) return big < sum(triangle) - big def part1(triangles): return sum(map(valid, triangles)) def group(n, it): return zip(*[iter(it)]*n) def transpose(it): return zip(*it) def part2(triangles): triangles = group(3, triangles) triangles = (t for gr...
# # This one does a little more then required and handles all types of brackets # def balancedParens(s): stack, opens, closes = [], ['(', '[', '{'], [')', ']', '}'] for c in s: if c in opens: stack.append(c) elif c in closes: try: if opens.index(stack.pop()) != closes.index(c): ...
"""Helper methods for Hijri conversion.""" def jdn_to_ordinal(jdn: int) -> int: """Convert Julian day number (JDN) to date ordinal number. :param jdn: Julian day number (JDN). :type jdn: int """ return jdn - 1721425 def ordinal_to_jdn(n: int) -> int: """Convert date ordinal number to Julia...
def f(): print('hello') print('calling f') f()
n, y = map(int, input().split()) y /= 1000 res10, res5, res1 = -1, -1, -1 for a in range(n + 1): if res1 != -1: break for b in range(n - a + 1): c = n - a - b total = 10000 * a + 5000 * b + 1000 * c if total == y: res10, res5, res1 = a, b, c if res1...
# Eingabe ist eine Liste mit Zahlen, es soll augegebenwerden, wie viele Zahlen # größer als ihre Vorgänger sind incr = 0 letzte = int(input()) while True: eingabe = input() if eingabe != '' and eingabe.isdigit(): zahl = int(eingabe) if zahl > letzte: incr += 1 letzte = zahl ...
class Finder: _finders = {} @classmethod def register(cls, finder_class): cls._finders[finder_class.name] = finder_class @classmethod def factory(cls, finder_name, deployment, **args): for name, finder in cls._finders.items(): if name == finder_name: re...
message = 'Hello World!' message2 = 'Hello World! \n' number = 32/35 display = message + repr(number) display2 = message + str(number) display3 = message2 + repr(number) print(display) print(display2) print(display3) print(repr(display3))
class Agent(object): def __init__(self): pass def act(self, obs): pass def train(self, replay_buffer, logger, step): pass
print('Welcome to tip calculator') bill = float(input('Enter Your total bill : $')) per_tip = int(input("Enter percentage of tip would you like to give (10,12 or 15): ")) num = int(input("No.of friends that would split the bill : ")) final_bill = round((bill + bill*0.01*per_tip)/num,2) print(f"Each person should pay ...
class RequiredFieldsError(Exception): def __init__(self, message, is_get=True, abnormal=False, title=None, error_fields=None): super(RequiredFieldsError, self).__init__() self.message = message self.is_get = is_get self.abnormal = abnormal self.title = title...
_perms_self_read_only = [ { "principal": "SELF", "action": "READ_ONLY" } ] _perms_self_read_write = [ { "principal": "SELF", "action": "READ_WRITE" } ] _perms_self_hide = [ { "principal": "SELF", "action": "HIDE" } ] # a dump of an okta...
n, m = map(int, input().split()) a = list(map(int, input().split())) a.insert(0, 0) for _ in range(m): op, x = map(int, input().split()) if op == 2: l = 2**(x - 1) r = min(n + 1, 2**x) print(' '.join(map(str, a[l:r]))) elif op == 1: t = [] t.append(a[x]...
#9. Juan, Raquel y Daniel aportan cantidades de dinero para formar un capital. # Juan y Raquel aportan en dólares y Daniel, en soles. Desarrolle el programa que # determine el capital total en dólares y que porcentaje de dicho capital aporta cada uno. Dólar = S/. 3.00 nuevos soles. j=float(input("Aporte de Juan sera $...
#!/usr/bin/env python3 """Extracting IDs from document""" def idExtractor(channelID, document): for key in document: try: if document[key][0] == channelID: return key, document[key][1] except TypeError: continue return
class BaseException(Exception): default_message = None def __init__(self, *args, **kwargs): if not (args or kwargs): args = (self.default_message,) super().__init__(*args, **kwargs) class NotEnoughBallotClaimTickets(BaseException): default_message = 'You do not have enough cl...
class APIException(Exception): pass class ADBException(Exception): pass
""" https://leetcode.com/problems/longest-palindromic-subsequence/ Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. Example 1: Input: "bbbab" Output: 4 One possible longest palindromic subsequence is "bbbb". Example 2: Input: "cbbd" Outpu...
MAJOR = 0 MINOR = 1 PATCH = 6 __version__ = '%d.%d.%d' % (MAJOR, MINOR, PATCH)
# # PySNMP MIB module TRAPEZE-NETWORKS-AP-IF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-AP-IF-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:19:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
def convex_hull_from_points(raw_v): hull = ConvexHull(raw_v) hull_eq = hull.equations # H representation v = raw_v[hull.vertices,:] num_vertices = len(v) g = np.hstack((np.ones((num_vertices,1)), v)) # zeros for vertex mat = cdd.Matrix(g, number_type='fraction') mat.rep_type = cdd.Re...
def valid_word(seq, word): check=set(seq) def helper(count, index): if index>=len(word): return True if count>=1 else False return any(helper(count+1, i) for i in range(index+1, len(word)+1) if word[index:i] in seq) return helper(0, 0)
# coding: utf-8 """***************************************************************************** * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * re...
class AbstractToken: name = 'token' def __init__(self, lexemes, form): self.lexemes = lexemes self.form = form self.source = self.get_source(lexemes) self.string = lexemes[0].string self.string_index = lexemes[0].string_index self.string_begin_index = lexemes...
numbers = input().split() for x in range(len(numbers)): numbers[x] = int(numbers[x]) for a in range(0, len(numbers)-2): for b in range(a+1, len(numbers)-1): for c in range(b+1, len(numbers)): A = numbers[a] B = numbers[b] C = numbers[c] if...
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the given BST @param k: the given k @return: the kth smallest element in BST """ def kthSmallest(self, root, k): ...
# 解説の C++ のコードを Python に移植 nmax = 8 graph = [[False] * nmax for _ in range(nmax)] def dfs(v, N, visited): all_visited = True for i in range(N): if not visited[i]: all_visited = False if all_visited: return 1 ret = 0 for i in range(N): if not graph[v][i]: ...
def calculate_triangles(max_p: int) -> int: max_value = -1 max_p_val = -1 for p in range(12, max_p + 1, 2): current_value = sum((p*p - 2*a*p) % (2*p - 2*a) == 0 for a in range(2, p // 3)) if current_value > max_value: max_value = current_value ...
app = Flask(__name__) class Model: def __init__(self, obj={}): """@param obj {dict}""" self._obj = obj def get_obj(self): return self._obj def set_property(self, name, value): self._obj[name] = value def set_properties(self, properties): """@param propert...
# Классы class Auth: def __init__(self, username, password): self.username = username self.password = password class Contactdate: def __init__(self, firstname, middlename, lastname, nickname, title, company, address, home, mobile, work, fax, email, email2, email3, ...
def partition(li, start, end): pivot = li[start] left = start + 1 right = end done = False while not done: while left <= right and li[left] <= pivot: left += 1 while right >= left and li[right] >= pivot: right -= 1 if right < left: done = ...
number = int(input()) previous = 1 current = 1 for i in range(number - 2): next = previous + current previous = current current = next print(current)
class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def _isValidBSTHelper(self, n, low, high): if not n: return True val = n.val if ((val > low and val < high)...
#For these problems, DON'T COMMENT OUT FUNCTION DEFINITIONS! You will need to use them. ####################################################################################### # 13.1 # Make a function which prints out a random string. Then call it. ###################################################################...
DEFAULT_KAFKA_PORT = 9092 #: Compression flag value denoting ``gzip`` was used GZIP = 1 #: Compression flag value denoting ``snappy`` was used SNAPPY = 2 #: This set denotes the compression schemes currently supported by Kiel SUPPORTED_COMPRESSION = (None, GZIP, SNAPPY) CLIENT_ID = "kiel" #: The "api version" value ...
css = [ 'about.css', 'button.css', 'frame.css', 'faq.css', 'index.css', 'map.css', 'ramanujan.css', 'rocket.css', 'shelf.css', 'snackbar.css', 'timeline.css', 'typewriter.css', 'mobile.css', 'info.css' ] concat = '' for i in css: with open(f'css/{i}') as f: ...
CONTROLLERS = {} def controller(code): def register_controller(func): CONTROLLERS[code] = func return func return register_controller def get_controller_func(controller): if controller in CONTROLLERS: return CONTROLLERS[controller] raise ValueError('Invalid request')
course = ' Python for Beginners ' print(len(course)) # Genereal perpous function print(course.upper()) print(course) print(course.lower()) print(course.title()) print(course.lstrip()) print(course.rstrip()) # Returns the index of the first occurrence of the character. print(course.find('P')) print(course.find('B'...
print("Hello World!") x = "Hello World" print(x) y = 42 print(y)
casa = float(input('Digite o Valor da Casa: R$')) sal = float(input('Qual é o Salario do Comprador?')) anos = int(input('Quantos anos de financiamento?')) prestação = casa / (anos * 12) minimo = sal * 30 /100 print('Para pagar uma casa de R${:.2f} em {} anos'.format(casa,anos),end = '') print('A prestação será de R${:...
# coding:utf8 """ 封装爬虫提取出来的数据 - 将来可以根据这个类型来判断爬虫提取的是数据还是请求 """ class Item(object): def __init__(self,data): # 这是为私有属性,为了保护Item中封装的数据 self.__data = data # 只能获取值,不能赋值 @property def data(self): return self.__data
class Policy(object): """ Base policy """ def __init__(self, action_low=None, action_high=None): self.action_low = action_low self.action_high = action_high def action(self, state, sim_time=0, desired=[], actual=[]): pass def reset(self): pass
def pyhelp(): while True: print('~' * 30) print('{:^30}'.format('SISTEMA DE AJUDA PYHELP')) print('~' * 30) comando = input('Função ou Biblioteca > ') if comando == 'FIM': break else: help(comando) pyhelp()
# Diccionarios de entrada: caballero = { "vida":2, "ataque":2, "defensa": 2, "alcance":2 } guerrero = { "vida":2, "ataque":2, "defensa": 2, "alcance":2 } arquero = { "vida":2, "ataque":2, "defensa": 2, "alcance":2 } names = ["caballero", "guerrero", "arquero"] dict_init = [caballero, guerrero, arquero] print("Las e...
class DefineRegion(object): def __init__(self): self.x = self.y = 10.0 self.depth = 1.0 self.subvolume_edge = 1.0 self.cytosol_depth = 10.0 self.num_chambers = (self.x / self.subvolume_edge) * (self.y / self.subvolume_edge) * ( self.depth / self.subvolume_...
#!/usr/bin/env python3 '''module that deals with functions''' def commandpush(devicecmd): #devicecmd=list ''' push commands to devices ''' for coffeetime in devicecmd.keys(): print("Handshaking......connecting with " + coffeetime) for mycmds in devicecmd[coffeetime]: print("Attempti...
for v in range(0, 3): print(v) for i, v in enumerate(range(10, 13)): print(i, v) for key, value in {'A': 0, 'B': 1}.items(): print(key, value)
n=22351 l=[] s=str(n) for ch in s: l= l + [int(ch)] highest=sorted (l,reverse=True) s="" for ch in highest: s=s+ str(ch) highest=int(s) n=9 for i in range(n +1,highest+1): print(i)
class Solution(object): def intersection(self, nums1, nums2): if len(nums1) > len(nums2): return self.intersection(nums2, nums1) lookup = set() for i in nums1: lookup.add(i) res = [] for i in nums2: if i in lookup: res += ...
def add(a, b): return a + b def multiply(a, b): return a * b assert add(10, 10) == 100, "confused addition" assert multiply(10, 10) == 20, "confused multiplication"
def linear_search(a, key): length = len(a) idx = 0 while idx < length: if a[idx] == key: return idx idx += 1 return -1 a = [1, 3, 5, 10, 13] key = 5 print(linear_search(a, key))
# increment.py """This increments (creates a new) serial number with every invocation of the class.""" # STATUS: Not working. See FIXME tag below. # from https://app.pluralsight.com/course-player?clipId=bf34ecab-aa3e-402b-961d-53efb624b957 class ShippingContainer: # Global scope # Class attributes here: n...
class Bar(): pass def t1(): raise Bar() def t2(): return Bar()
f = open("pb2.txt") n = int(f.readline()) P = [] for i in range(n): x, y = f.readline().split() P.append((float(x), float(y))) # citirea punctelor poligonului print("n=", n, " P=", P) # pentru x-monotonie, de exemplu, vreau sa iau cel mai din stanga punct si sa parcurg punctele pentru ca sunt...
def histogram(s): ''' Maps values of sequence to its frequency / occurrence. s: sequence ''' d = {} for c in s: d[c] = d.get(c, 0) + 1 return d def invert_dict(d): ''' Inverts a dictionary(d). Returns dictionary with values of d as keys and keys of d ...