content
stringlengths
7
1.05M
word1 = input() word2 = input() # How many letters does the longest word contain? len_word1 = len(word1) len_word2 = len(word2) max_len = 0 if len_word1 >= len_word2: max_len = len_word1 else: max_len = len_word2 print(max_len)
def _(line): new_indent = 0 for section in line: if (section != ''): break new_indent = new_indent + 1 return new_indent
class Something: def __eq__(self, other: object) -> bool: pass class Reference: pass __book_url__ = "dummy" __book_version__ = "dummy" associate_ref_with(Reference)
""" # COURSE SCHEDULE II There are a total of n courses you have to take labelled from 0 to n - 1. Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai. Given the total number of courses numCourses and a list of the prerequisite...
class RSI(object): def __init__(self, OHLC, period): self.OHLC = OHLC self.period = period self.gain_loss = self.gain_loss_calc() def gain_loss_calc(self): data = self.OHLC["close"] gain_loss = [] for i in range(1, len(data)): change = f...
class Recipe(object): """ This class provides a Recipe for an Order. It is a list (or dictionary) of tuples (str machineName, int timeAtMachine). """ def __init__(self): """ recipe is a list (or dictionary) that contains the tuples of time information for the Recipe. """ self.recipe = [] def indexO...
# -*- coding: utf8 -*- __author__ = 'D. Belavin' class NodeTree: __slots__ = ['key', 'payload', 'parent', 'left', 'right', 'height'] def __init__(self, key, payload, parent=None, left=None, right=None): self.key = key self.payload = payload self.parent = parent self.left = le...
class Member(object): def __init__(self, interval, membership): self.interval = interval self.membership = membership def is_max(self): return self.membership == 1.0 def __str__(self): return str(self.membership) + "/" + str(self.interval) def __hash__(self): ...
class SparkConstants: SIMPLE_CRED = 'org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider' TEMP_CRED = 'org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider' CRED_PROVIDER_KEY = 'spark.hadoop.fs.s3a.aws.credentials.provider' CRED_ACCESS_KEY = 'spark.hadoop.fs.s3a.access.key' CRED_SECRET_KEY = ...
"""Check if string is blank. Set boolean _blank to _true if string _s is empty, or null, or contains only whitespace ; _false otherwise. Source: programming-idioms.org """ # Implementation author: TinyFawks # Created on 2016-02-18T16:58:03.22685Z # Last modified on 2019-09-26T20:40:16.940019Z # Version 6 blank = s....
""" Test no choices given .. ignored: """
#!/usr/bin/env python """ _JobSplitting_ A set of algorithms to allocate work to a set of jobs split along lines like event, run, lumi, file. """ __all__ = []
load(":providers.bzl", "PrismaDataModel") def _prisma_datamodel_impl(ctx): return [ PrismaDataModel(datamodels = ctx.files.srcs), DefaultInfo( files = depset(ctx.files.srcs), runfiles = ctx.runfiles(files = ctx.files.srcs), ), ] prisma_datamodel = rule( impl...
instr = input() deviate = int(input()) for x in instr: if x.isalpha(): uni = ord(x) if x.islower(): x = chr(97 + ((uni + deviate) - 97) % 26) elif x.isupper(): x = chr(65 + ((uni + deviate) - 65) % 26) print(x, end="") print()
def centered_average(nums): """ take out 1 value of the smallest and largst compute and return the mean of the rest int div --> truncate the floating part? ASSUME: +3 ints pos/neg unsorted dupes possible Intutition: - computing an average (sum / # of points) Approac...
dd, mm, aa = input().split('/') print(f'{dd}-{mm}-{aa}') print(f'{mm}-{dd}-{aa}') print(f'{aa}/{mm}/{dd}')
''' Instructions Write a program that switches the values stored in the variables a and b. Warning. Do not change the code on lines 1-4 and 12-18. Your program should work for different inputs. e.g. any value of a and b. Example Input a: 3 b: 5 Example Output a: 5 b: 3 ''' # 🚨 Don't change the code below 👇 a = ...
#Programa que pede 10 números à escolha do usuário e mostra o somatório dos números pedidos" n = 1 soma = 0 while n<=10: x = int (input(f'{n} número: ')) soma = soma+x n = n+1 print('A soma dos números digitados é: ',soma)
MODULUS_NUM = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787 MODULUS_BITS = 381 LIMB_SIZES = [55, 55, 51, 55, 55, 55, 55] WORD_SIZE = 64 # Check that MODULUS_BITS is correct assert(2**MODULUS_BITS > MODULUS_NUM) assert(2**(MODULUS_BITS - 1) < MODULUS...
DICTIONARY = {'A': 'awesome', 'C': 'confident', 'B': 'beautiful', 'E': 'eager', 'D': 'disturbing', 'G': 'gregarious', 'F': 'fantastic', 'I': 'ingestable', 'H': 'hippy', 'K': 'klingon', 'J': 'joke', 'M': 'mustache', 'L': 'literal', 'O': 'oscillating', 'N': 'newtoni...
# 钻石继承搜索模式 """ 这是Python的新式类,也就是有一个以上的超类会通往同一个跟高级的超类 python的经典类继承搜索绝对是深度优先,然后是才左向右。一路向上搜索,深入树的左侧,返回后,才开始右侧 在新式类中,相对于说是宽度优先的,Python现寻找第一个搜索的右侧的所有超类,然后才一路往上搜索至顶端的共同的超类 当从多个子类访问超类的时候,新式搜索规则避免重复访问同一个超类 """ class A: attr = 1 class B(A): pass class C(A): attr = 2 class D(B, C): pass # attr = C.attr...
_ALLOWED_VOLUME_KEYS = ["claim_name", "mount_path"] def parse(volume_str): """Parse combined k8s volume string into a dict. Args: volume_str: The string representation for k8s volume, e.g. "claim_name=c1,mount_path=/path1". Return: A Python dictionary parsed from the given vo...
print('====== DESAFIO 02 ======') dia = int(input('Dia = ')) mes = input('Mês = ') ano = int(input('Ano = ')) print('Você nasceu no dia ',dia,' de ',mes,'de',ano,'. Correto?' )
# find the non-repeating integer in an array # set operations (including 'in' operation) are O(1) on average, and one loop that runs n times makes O(n) def single(array): repeated = set() not_repeated = set() for i in array: if i in repeated: continue elif i in not_repeated: ...
def lstrip0(iterable, obj): i = 0 iterable_list = list(iterable) while i < len(iterable_list): if iterable_list[i] != obj: break i += 1 for k in range(i, len(iterable_list)): yield iterable_list[k] def lstrip(iterable, obj, key_func=None): if not key_func: ...
def extendList(val, lst=[]): lst.append(val) return lst list1 = extendList(10) list2 = extendList(123,[]) list3 = extendList('a') print("list1 = %s" % list1) print("list2 = %s" % list2) print("list3 = %s" % list3)
# Given an array nums of integers, # return how many of them contain an even number of digits. def find_numbers_easy(nums): even_number_count = 0 for num in nums: if len(str(num)) % 2 == 0: even_number_count += 1 return even_number_count def find_numbers_hard(nums): even_numb...
# GENERATED VERSION FILE # TIME: Tue Sep 28 14:27:47 2021 __version__ = '1.0rc1+c42460f' short_version = '1.0rc1'
#!/usr/bin/env python3 bag_of_words = __import__('0-bag_of_words').bag_of_words sentences = ["Holberton school is Awesome!", "Machine learning is awesome", "NLP is the future!", "The children are our future", "Our children's children are our grandchildren", ...
x=4 itersLeft=x Sum=0 while(itersLeft!=0): Sum=Sum+x itersLeft=itersLeft-1 print(Sum) print(itersLeft) print(str(x)+"**"+" 2 = "+str(Sum))
class Solution: def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ i, j, size, sum, min_len = 0, 0, len(nums), 0, len(nums) if size == 0: return 0 while j < size: sum += nums[j] ...
QUIP_ACCESS_TOKEN = "1ee2demdo33=|03e39j94r4|komes234mfmf+wapdmeodmemdfg2y6hMfAHko=" # This is a fake token :D QUIP_BASE_URL = "https://platform.quip.com" ENV = "DEBUG" LOGS_PREFIX = ":quip.quip:" USER_JSON = { "name": "John Doe", "id": "1234", "is_robot": False, "affinity": 0.0, "desktop_folder_id"...
#!/usr/bin/env python # -*- coding: utf-8 -*- class InvalidTemplateError(Exception): """ Raised when a CloudFormation template fails the Validate Template call """ pass
class BinarySearch: def __init__(self, arr, target): self.arr = arr self.target = target def binary_search(self): lo, hi = 0, len(self.arr) while lo<hi: mid = lo + (hi-lo)//2 # dont use (lo+hi)//2. Integer overflow. # https://en.wikipedia.or...
class Solution(object): # def validPalindrome(self, s): # """ # :type s: str # :rtype: bool # """ # def is_pali_range(i, j): # return all(s[k] == s[j - k + i] for k in range(i, j)) # for i in xrange(len(s) / 2): # if s[i] != s[~i]: # ...
class connectionFinder: def __init__(self, length): self.id = [0] * length self.size = [0] * length for i in range(length): self.id[i] = i self.size[i] = i # Id2 will become a root of Id1 : def union(self, id1, id2): rootA = self.find(id1) ro...
# Delicka # Napíšte funkciu Delicka, ktorá bude prijímať parameter text a voliteľný parameter separator (defaultný separátor = ';'). Rozdeľuje text podľa parametra separator, prevedie prvé dva prvky na reálne čísla a vráti ich podiel. # Sample Input 1: # delicka('1;2;haha') # Sample Output 1: # 0.5 # Sample Input 2...
expected_output = { "vrf": { "vrf1": { "lib_entry": { "10.11.0.0/24": { "rev": "7", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.132.0.1": {"...
nmr = int(input("Digite um numero: ")) if nmr %2 == 0: print("Numero par") else: print("Numero impar")
class DefaultConfig(object): # Flask Settings # ------------------------------ # There is a whole bunch of more settings available here: # http://flask.pocoo.org/docs/0.11/config/#builtin-configuration-values DEBUG = False TESTING = False
n = int(input()) ss = input().split() s = int(ss[0]) a = [] for i in range(n): ss = input().split() a.append((int(ss[0]), int(ss[1]))) a.sort(key=lambda x: x[0] * x[1]) ans = 0 for i in range(n): if (s // (a[i])[1] > ans): ans = s // (a[i])[1] s *= (a[i])[0] print(ans)
def city_formatter(city, country): formatted = f"{city.title()}, {country.title()}" return formatted print(city_formatter('hello', 'world'))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' with open('1.txt', 'a', encoding='cp1251') as f: f.write('фотки\n') with open('1.txt', 'a', encoding='utf-8') as f: f.write('фотки\n') # OR... with open('2.txt', 'ab') as f: f.write('фотки\n'.encode('cp1251')) with open('2.txt', '...
''' Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Example: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Constraints: - 1 <= arr.length <= 10^4 - 0 <= arr[i] ...
class json_to_csv(): def __init__(self): self.stri='' self.st='' self.a=[] self.b=[] self.p='' def read_js(self,path): self.p=path l=open(path,'r').readlines() for i in l: i=i.replace('\t','') i=i.replace('...
def es5(tree): # inserisci qui il tuo codice d={} for x in tree.f: d1=es5(x) for x in d1: if x in d: d[x]=d[x] | d1[x] else: d[x]=d1[x] y=len(tree.f) if y in d: d[y]=d[y]| {tree.id} else: d[y]= {tree.id} ...
#!/home/jepoy/anaconda3/bin/python def main(): x = dict(Buffy = 'meow', Zilla = 'grrr', Angel = 'purr') kitten(**x) def kitten(**kwargs): if len(kwargs): for k in kwargs: print('Kitten {} says {}'.format(k, kwargs[k])) else: print('Meow.') if __name__ == '__main__': ma...
def resolve(): ''' code here ''' x, y = [int(item) for item in input().split()] res = 0 if x < 0 and abs(y) - abs(x) >= 0: res += 1 elif x > 0 and abs(y) - abs(x) <= 0: res += 1 res += abs(abs(x) - abs(y)) if y > 0 and abs(y) - abs(x) < 0: res += 1 eli...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : 1410.py @Contact : huanghoward@foxmail.com @Modify Time : 2022/4/12 16:18 ------------ """ class Solution: def entityParser(self, text: str) -> str: l = 0 r = 0 reading = False result = "" con...
def asm2(param_1, param_2): # push ebp # mov ebp,esp # sub esp,0x10 eax = param_2 # mov eax,DWORD PTR [ebp+0xc] local_1 = eax # mov DWORD PTR [ebp-0x4],eax eax = param_1 # mov eax,DWORD PTR [ebp+...
class _SpeechOperation(): def add_done_callback(callback): pass
class BaseHyperParameter: """ This is a base class for all hyper-parameters. It should not be instantiated. Use concrete implementations instead. """ def __init__(self, name): self.name = name
def main(): a = 1 if True else 2 print(a) if __name__ == '__main__': main()
# Birth should occur before death of an individual def userStory03(listOfPeople): flag = True def changeDateToNum(date): # date format must be like "2018-10-06" if date == "NA": return 0 # 0 will not larger than any date, for later comparison else: tempDate = dat...
name = input("Enter your name: ") age = input("Enter your age: ") print("Hello " + name + " ! Your are " + age + " Years old now.") num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = num1 + num2 print(result) # We need int casting number num1 and num2 result = int(num1) + int(num2) print(...
# -*- coding: utf-8 -*- def find_message(message: str) -> str: result: str = "" for i in list(message): if i.isupper(): result += i return result # another pattern return ''.join(i for i in message if i.isupper()) if __name__ == '__main__': print("Example:") print(fin...
# # Copyright 2019 Delphix # # 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, so...
# Copyright 2020 The Bazel 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 applicable la...
class Vector(object): SHORTHAND = 'V' def __init__(self, **kwargs): super(Vector, self).__init__() self.vector = kwargs def dot(self, other): product = 0 for member, value in self.vector.items(): product += value * other.member(member) return product ...
#!/usr/bin/env python3 def first(iterable, default=None, key=None): if key is None: for el in iterable: if el is not None: return el else: for el in iterable: if key(el) is not None: return el return default
class Foo: def qux2(self): z = 12 x = z * 3 self.baz = x for q in range(10): x += q lst = ["foo", "bar", "baz"] lst = lst[1:2] assert len(lst) == 2, 201 def qux(self): self.baz = self.bar self.blah = "hello" self._priv = 1 self._prot = self.baz def _prot2(self): ...
class Pessoa: olhos=2 def __init__(self, *filhos, nome=None,idade=28): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Olá{id(self)}' if __name__ == '__main__': andrew = Pessoa(nome='Andrew') waschington = Pessoa(and...
pattern_zero=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] pattern_odd=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667,...
class Solution(object): def isReflected(self, points): """ :type points: List[List[int]] :rtype: bool """ if not points: return True positions=set() sumk=0 for p in points: positions.add((p[0],p[1])) ...
Pathogen = { 'name': 'pathogen', 'fields': [ {'name': 'reported_name'}, {'name': 'drug_resistance'}, {'name': 'authority'}, {'name': 'tax_order'}, {'name': 'class'}, {'name': 'family'}, {'name': 'genus'}, {'name': 'species'}, {'name': 'sub_...
def merge(di1, di2, fu=None): di3 = {} for ke in sorted(di1.keys() | di2.keys()): if ke in di1 and ke in di2: if fu is None: va1 = di1[ke] va2 = di2[ke] if isinstance(va1, dict) and isinstance(va2, dict): di3[ke] = m...
def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] N, Q = read_list(int) array = read_list(int) C = [[0, 0, 0]] for a in array: c = C[-1][:] c[a % 3] += 1 C.append(c) for _ in range(Q): l, r = read_li...
arr=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] n=4#col m=4#row #print matrix in spiral form loop=0 while(loop<n/2): for i in range(loop,n-loop-1): print(arr[loop][i],end=" ") for i in range(loop,m-loop-1): print(arr[i][m-loop-1],end=" ") for i in range(n-1-loop,loop-1+1,-...
class Color: red = None green = None blue = None white = None bit_color = None def __init__(self, red, green, blue, white=0): self.red = red self.green = green self.blue = blue self.white = white def get_rgb(self): return 'rgb(%d,%d,%d)' % (self.re...
N = int(input()) ano = N // 365 resto = N % 365 mes = resto // 30 dia = resto % 30 print(str(ano) + " ano(s)") print(str(mes) + " mes(es)") print(str(dia) + " dia(s)")
r, c = (map(int, input().split(' '))) for row in range(r): for col in range(c): print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ') print()
'''Colocando cores no terminal do python''' # \033[0;033;44m codigo para colocar as cores # tipo de texto em cod (estilo do texto) # 0 - sem estilo nenhum # 1 - negrito # 4 - sublinhado # 7 - inverter as confgs # cores em cod (cores do texto) # 30 - branco # 31 - vermelho # 32 - verde # 33 - amarelo # 34 - azul # 35...
""" An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic. Example 1: Input: [1,2,2,3] Outpu...
valid_passport = 0 invalid_passport = 0 def get_key(p_line): keys = [] for i in p_line.split(): keys.append(i.split(':')[0]) return keys def check_validation(keys): for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])) # CID is optional if 'cid' in keys: ...
# Copyright 2017 The Forseti Security 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 ap...
class Security: def __init__(self, name, ticker, country, ir_website, currency): self.name = name.strip() self.ticker = ticker.strip() self.country = country.strip() self.currency = currency.strip() self.ir_website = ir_website.strip() @staticmethod def summary(name,...
def plot_frames(motion, ax, times=1, fps=0.01): joints = [j for j in motion.joint_names() if not j.startswith('ignore_')] x, ys = [], [] for t, frame in motion.frames(fps): x.append(t) ys.append(frame.positions) if t > motion.length() * times: break for joint in join...
# Copyright 2016 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 required by applicable law or ag...
default_vimrc = "\ set fileencoding=utf-8 fileformat=unix\n\ call plug#begin('~/.vim/plugged')\n\ Plug 'prabirshrestha/async.vim'\n\ Plug 'prabirshrestha/vim-lsp'\n\ Plug 'prabirshrestha/asyncomplete.vim'\n\ Plug 'prabirshrestha/asyncomplete-lsp.vim'\n\ Plug 'mattn/vim-lsp-settings'\n\ Plug 'prabirshrestha/asyncomplete...
extensions = ["myst_parser"] exclude_patterns = ["_build"] copyright = "2020, Executable Book Project" myst_enable_extensions = ["deflist"]
# encoding: utf-8 """ Configuration file. Please prefix application specific config values with the application name. """ # Slack settings SLACKBACK_CHANNEL = '#feedback' SLACKBACK_EMOJI = ':goberserk:' SLACKBACK_USERNAME = 'TownCrier' # These values are necessary only if the app needs to be a client of the API FEEDB...
# Given a list and a num. Write a function to return boolean if that element is not in the list. def check_num_in_list(alist, num): for i in alist: if num in alist and num%2 != 0: return True else: return False sample = check_num_in_list([2,7,3,1,6,9], 6) print(sample)
z = 10 y = 0 x = y < z and z > y or y > z and z < y print(x) # X = True
# 输入:[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]] # 目标是找到上下左右相连的1,即为连续岛屿 # 第一遍 class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 row = len(grid) col = len(grid[0]) cnt = 0 # 自顶向...
""" Global constants. """ # Instrument message fields INSTRUMENTS = 'instruments' INSTRUMENT_ID = 'instrumentID' EXCHANGE_ID = 'exchangeID' INSTRUMENT_SYMBOL = 'symbol' INSTRUMENT_TRADING_HOURS = 'instrument_trading_hours' UNIT_SIZE = 'unit_size' # future's contract unit size TICK_SIZE = 'tick_size' MARGIN_TYPE = 'm...
# Merge Sort: D&C Algo, Breaks data into individual pieces and merges them, uses recursion to operate on datasets. Key is to understand how to merge 2 sorted arrays. items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53] def mergesort(dataset): if len(dataset) > 1: mid = len(dataset) // 2 leftarr = da...
def nameCreator(playerName): firstLetter = playerName.split(" ")[1][0] try: lastName = playerName.split(" ")[1][0:5] except: lastNameSize = len(playerName.split(" ")[1]) lastName = playerName.split(" ")[1][len(lastNameSize)] firstName = playerName[0:2] return lastName + fi...
# Copyright: 2005-2008 Brian Harring <ferringb@gmail.com> # License: GPL2/BSD """ exceptions thrown by repository classes. Need to extend the usage a bit further still. """ __all__ = ("TreeCorruption", "InitializationError") class TreeCorruption(Exception): def __init__(self, err): Exception.__init__(se...
class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ ret = [[0 for j in range(len(B[0]))] for i in range(len(A))] for i, row in enumerate(A): for k, a in enum...
# Author : Aniruddha Krishna Jha # Date : 22/10/2021 '''********************************************************************************** Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this pref...
def truthTable(n): # 主函數 p = [] # p 代表已經排下去的,一開始還沒排,所以是空的 return tableNext(n, p) # 呼叫 tableNext 遞迴下去排出所有可能 def tableNext(n, p):# n : n個變數的真值表, p :代表已經排下去的 i = len(p) if i == n: # 全部排好了 print(p) # 印出排列 return binary=[0,1] for x in binary: p.append(x) # 把 x 放進表 #print("append:",p) tableNext(n, p) #...
#!/usr/bin/env python3 """ Write a function called sed that takes as arguments a pattern string, a replacement string, and two filenames; it should read the first file and write the contents into the second file (creating it if necessary). If the pattern string appears anywhere in the file, it should be re...
# invertFontSelection.py """ Inverts selection in the current font """ for glyph in CurrentFont(): if glyph.selected: glyph.selected = False else: glyph.selected = True
class BTNode: '''Binary Tree Node class - do not modify''' def __init__(self, value, left, right): '''Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None.''' self.value = value self.left = left self.right =...
checksum = 0 with open("Day 2 - input", "r") as file: for line in file: row = [int(i) for i in line.split()] result = max(row) - min(row) checksum += result print(f"The checksum is {checksum}")
def bytes_to(bytes_value, to_unit, bytes_size=1024): units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6} return round(float(bytes_value) / (bytes_size ** units[to_unit]), 2) def convert_to_human(value): if value < 1024: return str(value) + 'b' if value < 1048576: return str(bytes_...
TLDS = [ "ABB", "ABBOTT", "ABOGADO", "AC", "ACADEMY", "ACCENTURE", "ACCOUNTANT", "ACCOUNTANTS", "ACTIVE", "ACTOR", "AD", "ADS", "ADULT", "AE", "AEG", "AERO", "AF", "AFL", "AG", "AGENCY", "AI", "AIG", "AIRFORCE", "AL", "ALLFINANZ", "ALSACE", "AM", "AMSTERDAM", "AN", "ANDROID", "AO", "APARTMENTS", "AQ", "AQUARELLE", "AR"...
class Bank: def __init__(self): self.inf = 0 self._observers = [] def register_observer(self, observer): self._observers.append(observer) def notify_observers(self): print("Inflacja na poziomie: ", format(self.inf, '.2f')) for observer in self._observers: ...
fruta = 'kiwi' if fruta == 'kiwi': print("El valor es kiwi") elif fruta == 'manzana': print("Es una manzana") elif fruta == 'manzana2': pass #si no sabemos que poner y no marque error else: print("No son iguales") mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False print(mensaje)
# Status code API_HANDLER_OK_CODE = 200 API_HANDLER_ERROR_CODE = 400 # REST parameters SERVICE_HANDLER_POST_ARG_KEY = "key" SERVICE_HANDLER_POST_BODY_KEY = "body_key"