content
stringlengths
7
1.05M
#!/usr/bin/env python3 for _ in range(int(input())): input() # don't need n try: print(input().index('1') // 2) except ValueError: print(-1)
# basic features for lists: https://docs.python.org/3/tutorial/datastructures.html # List: mutable def main(): my_list = list() my_list = [1, 2, 3] print("----------Hinzufügen----------") # Option 1: Single Value my_list.append(-10) print(my_list) # Option 2: List Concatenation (Verkettu...
def assignments_yield_islice(n_clubs: int) -> Iterator[set]: # This is almost but not quite accurate # It's about 15% faster than non-islice, but I can't get the combinators to roll over right n_block_1 = n_clubs // 3 + ((n_clubs % 3) > 0) n_block_2 = n_clubs // 3 + ((n_clubs % 3) > 1) n1 = n_assi...
def reverse_vowel(s): vowels = "AEIOUaeiou" i, j = 0, len(s)-1 s = list(s) while i < j: while i < j and s[i] not in vowels: i += 1 while i < j and s[j] not in vowels: j -= 1 s[i], s[j] = s[j], s[i] i, j = i + 1, j - 1 return "".join(s)
print('Olá mundo!') print('Como estão vocês?') x = input('Como você está?\n').capitalize() if x == 'Bem': print('Quem bom que está bem!') print(x)
ips = ["127.0.0.1", "255.0.0.1", "137.44.1.20", "48.8.9.72", ".".join(str(x) for x in range(256))] z_a = ord("z") - ord("a") # apparently I find it hard to remember az is 26 letters for ip in ips: sip = [] for byte in ip.split("."): b, s = int(byte), [] if b < ord("a"): b += ord("a") if b > ord...
# -*- coding: utf-8 -*- """ Created on Wed Jan 29 09:50:55 2020 @author: Administrator """ """ 已知三个升序整数数组a[l],b[m],c[n],请在三个数组中各找一个元素,使得组成的三元组距离最小. 三元组距离的定义是:假设a[i],b[j],c[k]是一个三元组,那么距离为:Distance=max(|a[i]-b[j]|,|a[i]-c[k]|,|b[j]-c[k]|), 请设计一个求最小三元组距离的最优算法. """ def GetDist(a , b , c): # get the dis...
class AI(): def __init__(self, grid): self.grid = grid def solve(self): covered = self.grid.grid.get_covered() try: cell = covered[0] except IndexError: print("Nothing more to do") return self.grid.press(*cell) print("Press",...
def StringVersion( seq ): return '.'.join( ['%s'] * len( seq )) % tuple( seq ) def TupleVersion( str ): return map( int, str.split( '.' ))
# responder-brute configuration file # Path to Responder.db RESPONDERDB = '../Responder.db' # Current hash file CURRENTHASHFILE = 'current.txt' # Poll for new hashes every N seconds POLLTIME = 5 # Use 'john' for John The Ripper or 'hashcat' for Hashcat. MODE = 'john' if MODE == 'john': # Command to run. Use "{...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # CISCO-CDP-MIB # Compiled MIB # Do not modify this file directly # Run ./noc mib make_cmib instead # ---------------------------------------------------------------------- # Copyright (C) 2007-2018 The NOC Proj...
class Simple(object): def __init__(self, lines): self.lines = lines def __enter__(self): return self def __exit__(self, *args): pass def path(self): return None def get_doc_ids(self): return list(range(len(self.lines))) def get_doc_text(self, line): ...
''' igualad: a == b desigualad: a != b a menor que b: a < b a menor o igual b: a <= b a mayor que b: a > b a mayor o igual b: a >= b ''' # if basico en varias lineas a = 33 b = 200 if b > a: print("b es mayor a") # if anidado en varias lineas a = 33 b = 33 if b > a: print("b es mayor a") elif a == b: print(...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # class Solution: # def inorderTraversal(self, root: TreeNode) -> List[int]: # res = [] # if not root: # ...
class Fifo(list): def __init__(self): self.back = [] self.append = self.back.append def pop(self): if not self: self.back.reverse() self[:] = self.back del self.back[:] return super(Fifo, self).pop()
## Script (Python) "getPautasPautao" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=data='', ##title=Retorna a lista de pautas do pautao ret = { 'manha': [], 'tarde': [], 'noite': [], 'nota':[], 'programas': [], 'semturno': [] } if...
"""Hackerrank Problem: https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter/problem""" def fun(s): """Determine if the passed in email address is valid based on the following rules: It must have the username@websitename.extension format type. The username can only contain lett...
""" Dummy module to substitute missing dependencies, e.g.: >>> try: ... import termcolor ... except ImportError: ... import dummy as termcolor Now some functionality of missing modules can be used in form of dummy functions, i.e. it will make no real effect. E.g. `termcolor.colored` will return text without any ...
class BaseModule(object): def __init__(self, connector): self.connector = connector def setup(self): pass
''' Created on 09.03.2019 @author: Nicco ''' class plan_base(object): ''' plan base is providing alle the methods to connect to act, perception and the simulator ''' def __init__(self, params): ''' Constructor '''
even_set = set() odd_set = set() for row in range(int(input())): name = input() ascii_letters = [ord(letter) for letter in name] result = sum(ascii_letters) // (row+1) if result % 2 == 0: even_set.add(result) else: odd_set.add(result) if sum(even_set) == sum(odd_set):...
_base_ = [ '../_base_/models/ocrnet_r50-d8.py', '../_base_/datasets/cityscapes_sccqq.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101)) optimizer = dict(lr=0.02) lr_config = dict(min_lr=2e-4) data = dict( ...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ python类的内置属性 __dict__ : 类的属性(包含一个字典,由类的数据属性组成) __doc__ :类的文档字符串 __name__: 类名 __module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod) __bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组) __class__: 类返回其元类 __mro__: 返回类...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: 1.0 @author: xjl @file: file_transmission.py 将利用多线程实现文件的传输 @time: 2021/10/22 22:21 """ if __name__ == '__main__': pass
# # PySNMP MIB module BAY-STACK-PIM-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-PIM-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:36:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
#max() 方法返回给定参数的最小值,可比较字符.汉字和表达式 print(min(1, 2, 3, 45, 4)) print(min([1, 2, 3, 4, 5, 6])) print(min('a', 'b', 'c', 'd')) print(min('梁', '伟', '洋')) print(min(8+2, 1+1, 9+9))
# # PySNMP MIB module Nortel-Magellan-Passport-FrameRelayUniTraceMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-FrameRelayUniTraceMIB # Produced by pysmi-0.3.4 at Wed May 1 14:27:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ...
with open("input.txt") as f: lines = f.readlines() split_lines = [x.split() for x in lines] horiz = map(lambda x: int(x[1]) if x[0][0] == 'f' else -int(x[1]) if x[0][0] == 'b' else 0, split_lines) vert = map(lambda x: int(x[1]) if x[0][0] == 'd' else -int(x[1]) if x[0][0] == 'u' else 0, split_lines) print(su...
''' Use this folder for the development of any products. All data should be saved to S3. '''
nums = [12, 34, 5, 7, 8] iter_nums = iter(nums) # def sum_numbers(nums): # for n in nums: # n += sum_numbers(nums) # return n # print(sum_numbers(iter_nums)) def sum_list(list_to_sum, index): if len(list_to_sum) == 0: return 0 if index == 0: return list_to_...
def hello(): return "Hello, pobby!" def main(): s = hello() print(s) """hahahahahah sdjfkadsjflksdjfkldsajfklsda fjdaslkfjdsakl""" if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """Tests dict input objects for `cookiecutter.operator.aws.ec2_meta` module.""" # import os # from cookiecutter.main import cookiecutter # TODO: Need to be able test pyinquirer # def test_operator_terraform(monkeypatch, tmpdir): # """Verify the operator call works successfully.""" # m...
""" https://docs.python.org/3/tutorial/controlflow.html """ def parrot(voltage, state='a stiff', action='voom'): print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.", end=' ') print("E's", state, "!") d = {"voltage": "four million", "state": "bleedin' d...
def sell(goods, price): return goods*price goods = int(input('Goods...')) price = int(input('Price...')) r = sell(goods, price) print(f'Прибыль составит {r} $')
class SnapshotView(object): """ A view into some subset of a snapshot instance. The attributes of the view depend on the snapshot from which it was derived, and the kind of view requested. All available attributes from the snapshot are available via the fields property, which returns a tuple. ...
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if not matrix: return [] M = matrix[:] # duplicate matrix m = len(M) # get m n = len(M[0]) # get n i, j = 0, 0 # set coordinate ...
# Author: OMKAR PATHAK # A Python generator is a function which returns a generator iterator (just an object we can iterate over) # by calling yield def simpleGenerator(numbers): i = 0 while True: check = input('Wanna generate a number? (If yes, press y else n): ') if check in ('Y', 'y') and l...
def _configure_features( ctx, cuda_toolchain, requested_features=[], unsupported_features=[] ): features = cuda_toolchain.features enabled_features = {} # Enable compilation mode feature compilation_mode = ctx.var["COMPILATION_MODE"] if compilation_mode in features: enabled_...
"""Test mobile app device tracker.""" async def test_sending_location(hass, create_registrations, webhook_client): """Test sending a location via a webhook.""" resp = await webhook_client.post( "/api/webhook/{}".format(create_registrations[1]["webhook_id"]), json={ "type": "update_...
""" 347. Top K Frequent Elements ------------------------------ https://leetcode.com/problems/top-k-frequent-elements/ Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Note: You may ...
""" A row measuring seven units in length has red blocks with a minimum length of three units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one grey square. There are exactly seventeen ways of doing this. p114.png How many ways can a row measuring fift...
#!/usr/bin/env python3 #coding:utf-8 class LNode(object): def __init__(self, x): self.val = x self.next = None def reverse(head): """ 方法功能:对带头结点的单链表进行逆序 输入参数:head: 链表头结点 """ if head is None or head.next is None: return None cur = None # 当前结点 nxt = None # 后继结...
class Node: def __init__(self,data): self.left=None self.right=None self.data=data def PrintTree(self): if self.left: self.left.PrintTree() print(self.data) if self.right: self.right.PrintTree() def insert(self,data): i...
""" 11 Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua àrea e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta, cobre uma àrea de 2m²""" l = float(input('Digite o valor da largura da parede em metro(s): ')) a = float(input('Digite o valor da altura d...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
names = ['Simon', 'Sophie', 2] print (names[0] + ' loves ' + names[1] + ' for ' + str(names[2]) + ' years') for name in names : print (name)
''' Using sieve of Eratosthenes, primes(x) returns list of all primes less than x Modification: We don't need to check all even numbers, we can make the sieve excluding even numbers and adding 2 to the primes list by default. We are going to make an array of: x / 2 - 1 if number is even, else x / 2 (The -1 with even...
# Space: O(1) # Time: O(n) class Solution: def singleNumber(self, nums): res = [] length = len(nums) nums.sort() status = 0 for i in range(length): if i == 0: if nums[i] != nums[i + 1]: res.append(nums[i]) ...
numbers_list = input().split(', ') new_list = [] for digit in numbers_list: digits = digit.split(', ') current_digit = int(digits[0]) if current_digit == 0: numbers_list.remove('0') numbers_list.append('0') new_list = list(map(int, numbers_list)) print(new_list)
""" Funções com Parametro (de entrada) - Funções que recebem dados para serem processados dentro da mesma; Num programa qualquer geralmente temos: - Entrada -> Processamento -> Saída Se for uma função, sabemos que: - Não possuem entrada; - Não possuem saída; - Possuem entrada mas não possuem saída; ...
# Copyright 2018 The GraphNets Authors. 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 required by applicabl...
'''Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem: - o primeiro valor é maior; - o segundo valor é maior; - Não existe valor maior, os dois são iguais''' a = int(input('Digite um valor inteiro: ')) b = int(input('Digite outro valor inteiro: ')) if a > b: print('O pri...
class Error(Exception): """ Base exception for all exceptions that indicate a failed request """ class DecodeError(Error): """" Raised when the request cannot be decoded by the server. """ class NoFreeOTAAddresses(Error): """" Raised when the OTA request cannot be completed due to no ...
wt3_3_10 = {'192.168.122.110': [8.5425, 9.6589, 8.3878, 8.9764, 8.5553, 8.1619, 8.5832, 8.1742, 7.8747, 7.6304, 7.6131, 7.5381, 7.3988, 7.2547, 7.2352, 7.1954, 7.0925, 6.9968, 7.8112, 7.7524, 7.6389, 7.5302, 7.4983, 7.4729, 7.4327, 7.3494, 7.2848, 7.2741, 7.2099, 7.1539, 7.2822, 7.2477, 7.3613, 7.315, 7.2783, 7.1005, ...
def readFiel(path): file = open(path,"r",encoding="utf-8") print(file.read()) file.close() #关闭流 def readFiel02(path): # 使用with ....as的形式可以捕获异常,不用手动添加try except with open(path,"r",encoding="utf-8") as f: print(f.read()) def readFiel03(path): # 使用with ....as的形式可以捕获异常,不用手动添加try except ...
COUNTRIES = [ ("Россия", "Россия"), ("Украина", "Украина"), ("Беларусь", "Беларусь"), ("Казахстан", "Казахстан"), ("Абхазия", "Абхазия"), ("Австралия", "Австралия"), ("Австрия", "Австрия"), ("Азербайджан", "Азербайджан"), ("Албания", "Албания"), ("Алжир", "Алжир"), ("Американ...
""" ==CHANGELOG== * support UTF8 ==CHANGELOG== """ sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdf...
names = ['David','Herry','Army'] message1 = "hello " + names[0] print(message1) message1 = "hello " + names[1] print(message1) message1 = "hello " + names[2] print(message1)
hu = "haha" age = 22 name = "Cat"
def calculateStats(numbers): val = len(numbers) result = {"max": float('NaN'), "min": float('NaN'), "avg": float('NaN')} if val == 0: return result else: result["max"] = max(numbers) result["min"] = min(numbers) result["avg"] = sum(numbers) / val return result ...
lst = [ ["https://bit.ly/DataStructC", "9:00", "9:58"], ["https://bit.ly/AeroStructures", "11:10", "12:08"], ["https://zoom.us/j/8143311495?pwd=e-space", "12:10", "13:00"] ["https://bit.ly/engMaterials", "13:50", "14:50"] ]
host='localhost' user='root' password='wowilosttwosis$' db='fin_man_db' charset='utf8mb4'
cx, cy, cd = input().split() cx = float(cx); cy = float(cy); cd = float(cd); r = cd; n = int(input()); coef = input().split(); z = float(input()); for i in range(n+1): coef[i] = float(coef[i]) def f_eval(x): ans = 0 for i in range(0, n+1): ans += coef[i]*(x**(n-i)) return ans lo = cx - r - 10 hi = cx + r + 10 ...
"""Load dependencies needed to depend on the remote-apis-sdks repo.""" load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository") def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs) def remote_apis_sdks_go_deps(): """Load dep...
# Copyright 2016 The Closure Rules Authors. 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 required by appli...
class Process: def __init__(self, id, arrvl_time, exec_time): self.id = id self.arrvl_time = arrvl_time self.exec_time = exec_time self.compl_time = 0 self.timeLeft = exec_time def execute(self, quantum): #self.timeLeft = self.timeLeft - quantum if self.timeLeft ...
# DATABASE db_username = 'root' db_password = 'toor' db_name = 'fscaffold' db_hostname = 'localhost' DEBUG = True PORT = 5000 HOST = "0.0.0.0" SQLALCHEMY_ECHO = False SECRET_KEY = "SOME SECRET" # PostgreSQL # SQLALCHEMY_DATABASE_URI = "postgresql://{DB_USER}:{DB_PASS}@{DB_ADDR}/{DB_NAME}".format( # DB_USER=db_use...
# Time: O(n) ~ O(n^2) # Space: O(n) class Solution(object): def canCross(self, stones): """ :type stones: List[int] :rtype: bool """ if stones[1] != 1: return False last_jump_units = {s: set() for s in stones} last_jump_units[1].add(1) f...
""" * Assignment: Loop Dict Reverse * Required: no * Complexity: easy * Lines of code: 9 lines * Time: 13 min English: 1. Define: a. `features: list[tuple]` - measurements b. `labels: list[int]` - species c. `label_encoder: dict[int, str]` dictionary with encoded (as numbers) sp...
words = "Life is short" upper_word_list = ["LIFE", "IS", "SHORT", "USE", "PYTHON"] word_generator = ( lower_w for w in upper_word_list if (lower_w := w.lower()) in words.lower() ) for w in word_generator: print(w, end=" ") # word_generator is StopIteration now
# overall function that recursively splits an input array in half, and # uses the helper function "merge" to compare items in each half against each # other to sort them def mergeSort(list): # Determine whether the list is broken into # individual pieces. if len(list) < 2: return list # Find th...
class DockerComposeEntity: def __init__(self): self.sinks = list() def build_state(self): result = dict() services = dict() sink_count = 0 for sink in self.sinks: services[f"sink_{sink_count}"] = sink.__dict__ sink_count += 1 result["ver...
a = input() if len(a) == 1 and 'a' in a: ans = -1 else: ans = 'a' print(ans)
LocalValueDim = 18446744073709551613 dataTypes = { -1: 'unknown', 0: 'byte', 1: 'short', 2: 'integer', 4: 'long', 50: 'unsigned_byte', 51: 'unsigned_short', 52: 'unsigned_integer', 54: 'unsigned_long', 5: 'real', 6: 'double', 7: 'long_double', 9: 'string', 10...
list1 = [3, 4, 51, 90.1, False, 'Amresh', 7] # index = 0 # for i in list1: # print (f'index: {index}, Value: {i}') # index += 1 for index, item in enumerate(list1): print (f'index: {index}, Value: {item}')
class Params(object): def __init__(self , data_path='faces/dataset/' , artifacts_path='faces/artifacts/' , models_path='/User/mlrun/demos/faces/notebooks/functions/models.py' , frames_url='framesd:8081' , token='set_token' ...
''' Created on 15.02.2017 @author: emillokal ''' measure0=0 measure1=0
# Link to the problem: https://www.codechef.com/MARCH18B/problems/MIXCOLOR def main(): T = int(input()) while T: T -= 1 _ = int(input()) occr = {} colors = list(map(int, input().split())) for i in colors: occr[i] = 0 for val in colors: oc...
# File where I wrote functions that helped parse and make changes to multiple lines of code def read_source_file(name: str)->str: f = open(name) s = f.read() f.close() return s def save_as_new(text: str): f = open('./new.py', mode='w') f.write(text) f.close() def find_brace_close_posit...
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
class Immutable(type): def __new__(msc, name, bases, nmspc): new_class = type(name, bases, nmspc) original_initialization = new_class.__init__ def set_attribute(self, key, value): raise AttributeError("Attributes are immutable") def wrapper(self, *args, **kwargs): ...
""" Map Com map, fazemos mapeamento de valores para função. import math def area(r): # Calcula a área de um círculo com raio 'r'. return math.pi * (r ** 2) print(area(2)) print(area(5.3)) raios = [2, 5, 7.1, 0.3, 10, 44] # Forma comum areas = [] for r in raios: areas.append(area(r)) print(areas) #...
MAX_MEMBER_REPR_LENGTH = 1000 class Repr: """Convencience class to automatically add standard ``__repr__()`` and ``__str__()`` functions to class. Uses ``__dict__`` property. """ def __repr__(self): members = ', '.join(f'{k}={str(v)[:MAX_MEMBER_REPR_LENGTH]}' for k, v in self.__dict__.items...
class CleanPhoneNumber(object): def __init__(self, phone_number): self.phone_number = phone_number def sanitize_phone_number(self): phone_number = self.phone_number phone = list(phone_number) prefix = phone[0] length = len(phone_number) if prefix == '+' and leng...
""" Some convenience methods to manipulate sequence objects (ex: list, range, set, string) """ def chunks(l, n): """ Yield successive n-sized chunks from list l. Example: l = [1,2,3,4,5,6,7,8,9,10] c = list(chunks(l, 3)) # c will be equal "[ [1,2,3], [4,5,6], [7,8,9], [10]] """ f...
# List of guide files to search guides = ['analytics_guide.md','angular_guide.md','api_guide.md','authentication_guide.md','cache_guide.md','hub_guide.md','i18n_guide.md','interactions_guide.md','logger_guide.md','pub_sub_guide.md','push_notifications_setup.md','service_workers_guide.md','storage_guide.md'] # Start of...
x = 9 y = 3 # Arithmetic Operators print(x+y) #Addition print(x-y) #Subtraction print(x*y) #Multiplication print(x/y) #Division print(x%y) #Modulus print(x**y) #Exponantiation x = 9.191823 print(x//y) #Floor Division #Assignment Operators x = 9 # set x = 9 x += 3 # x = x + 3 print(x) x = 9 x -= 3 # x = x - 3 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # File Name: Problem_3.py # Project Name: WebLearn # Author: Benjamin Zhang # Created Time: 2019-01-12 21:45 # Version: 0.0.1.20190112 # # Copyright (c) Benjamin Zhang 2019 # All rights reserved. # name = ["Adam", "Seth", "Enosh", "Ke...
infile = open("./local_models/time-all.normalized","r") outfile = open("./clustering/initial.dat","w") listoflists = [] for line in infile: listoflists.append(line.strip().split()) numtopics = len(listoflists[0])-1 numwords = len(listoflists) for topic in range(1,numtopics+1): #fancy indexing because words are st...
#!/usr/bin/env python # coding: utf-8 # author: binux(17175297.hk@gmail.com) # https://github.com/binux/binux-tools/blob/master/python/chinese_digit.py dict ={u'零':0, u'一':1, u'二':2, u'三':3, u'四':4, u'五':5, u'六':6, u'七':7, u'八':8, u'九':9, u'十':10, u'百':100, u'千':1000, u'万':10000, u'0':0, u'1':1, u'2':2, u'3':3,...
print('-'*12, 'DESCONTO DE PRODUTOS', '-'*12) preco = float(input('Qual o preço do produto: ')) desc = preco - (preco * 5 / 100) print('O produto que custava R${:.2f}, na promoção com desconto de 5% vai custar R${:.2f}'.format(preco, desc))
class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=43): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Olá' # >>> julio.nome # 'Julio' # >>> julio.idade # 43 # >>> for filho in julio.filhos: # ... print...
def spam(): global eggs eggs = 'spam' def bacon(): eggs = 'bacon' def ham(): print(eggs) eggs = 12 spam() print(eggs) """ spam """
def check_ip_byte(string, i, chars_left, ip, dot='exist'): index, result = i + 1, 'fail' if len(string) - i >= chars_left: n = string[i] if n.isdigit(): i += 1 while n.isdigit(): if i < len(string): if string[i].isdigit(): ...
class Solution: def findJudge(self, N: int, trust) -> int: helper = [set() for i in range(N)] for i, n in enumerate(trust): helper[n[0] - 1].add(n[1]) for i in range(N): if len(helper[i]) != 0: continue is_major = True for j, n...
# 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. load("//antlir/bzl:oss_shim.bzl", "buck_genrule") def _get_build_info(): return struct( package_name = native.read_config("build_...
i = 0 for i in range(0, 100): if i % 2 == 0: print(i) i+= i
"""\ Front-to-back rapid web development =================================== TurboGears brings together four major pieces to create an easy to install, easy to use web mega-framework. It covers everything from front end (MochiKit JavaScript for the browser, Genshi / Kid / Mako / Cheetah for templates in Python) to the...
input = """jmp +336 jmp +593 jmp +121 acc -8 nop +459 jmp +451 acc -6 acc +23 acc +23 acc -2 jmp +113 acc -11 acc +25 jmp +529 acc +0 jmp +1 jmp +313 acc +30 nop +235 jmp +45 nop +195 acc -11 jmp +491 acc +6 nop +425 nop +68 acc +9 jmp -25 jmp +507 jmp +456 acc -1 acc +49 acc +5 jmp +31 acc +30 nop +513 jmp +499 nop +5...
class componente: def equip(self): pass class CharacterConcreteComponent(componente): def __init__(self, name: str): self.name = name self.p1 = '' def e2(x): def a2(self): return f"{self.name} equipment:"+ x(self) return a2 @e2 def equip(self): ...