content
stringlengths
7
1.05M
def solve_me_first(a,b): return a + b num1 = input() num2 = input() res = solve_me_first(num1, num2) print(res)
#!/usr/bin/env python3 """ usage: scp.py [-h] [-p] [-q] [-r] [FROM [TO]] copy files between hosts positional arguments: FROM a local path, else HOSTNAME:PATH, else USER@HOSTNAME:PATH options: -h, --help show this help message and exit dreams: clear error messages for TO already exists, vs has no Dir,...
class Solution: def findComplement(self, num: int) -> int: return int(f'{num:b}'.replace('0', 'a').replace('1', '0').replace('a', '1'), base=2) # return num ^ (2**num.bit_length() - 1) # return num ^ ((1<<num.bit_length()) - 1) c = Solution().findComplement print(f''' {c(5)} {c(1)}...
class vehicleStatus: def __init__(self): self.position = [0, 0] self.direction = 1 self.receptive_radius = 1 self.communication_dis = 5 ACTION_MAP = { 0: [0, 0], 1: [-1, 0], 2: [0, 1], 3: [1, 0], 4: [0, -1], } ACTION_SPACE = ACTION_MAP.__len__() ACTION_MAP_I...
class IllegalCountryCodeException(Exception): def __init__(self, message): super(IllegalCountryCodeException, self).__init__(message)
whitelist = ["МОРОКА", "МОРС", "МОРОЗ", "ПЛАХА", "ПЛАТЬЕ", "ПЛОМБА"] def analyze(s, pref): if s in whitelist: return False, [f"{pref:<6} {s} - LOSING"] results = [] for word in whitelist: if word.startswith(s): result = analyze(s + word[len(s)], f"{pref:<6} --{word:<6}-->") ...
"""705. Design HashSet https://leetcode.com/problems/design-hashset/ Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: void add(key) Inserts the value key into the HashSet. bool contains(key) Returns whether the value key exists in the HashSet or not. void remove(key) Remov...
class Cheat: def __init__(self, name: str): self.name = name self.is_running = False def set_is_running(self, is_running: bool): self.is_running = is_running
''' 08 - Simple scatter plot Scatter are a bi-variate visualization technique. They plot each record in the data as a point. The location of each point is determined by the value of two variables: the first variable determines the distance along the x-axis and the second variable determines the height along the...
class BaseReward(): def __init__(self): pass def compute(self, distance, done): return 1 def __repr__(self): return self.__str__() def __str__(self): return "(Reward function D->X)" class ConstantReward(BaseReward): def __init__(self): """ This functio...
list = ["boat", "Dadtrough", "dogpaddle", "r%ace /!@# ca%r", "H!i"] reflection = "" badchar = " !@#$%^&*()/~|" for examples in list: print("Input:", examples) for char in badchar: examples = examples.replace(char, "") cleanexamples = examples.replace(char, "") examples = examples.lower...
class DynamicResourceExtensionConverter(TypeConverter): """ Converts from parsed XAML to System.Windows.DynamicResourceExtension and supports dynamic resource references made from XAML. DynamicResourceExtensionConverter() """ def CanConvertTo(self,*__args): """ CanConvertTo(self: DynamicResourceExt...
""" input: a valid roman numeral between 1, 3999 output return its integer equivalent key words/phrases: every roman numeral contains the chars ('I', 'V', 'X', 'L', 'C', 'D', 'M') example: iii -> 3 key operation: Given an input string, parse the string and return its integer equivalent simplest version: s = 'I' -> 1...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class= class_1 + class_2 new_class.append("Peter Warden") new_class.remove("Carla Gentry") print(new_class) # Code ends here # --------...
""" # What is modules in python? break down the entire code in smaller packages or modules for easy understanding and debugging, that can reusable for the future projects without copy code from that, just use as package (import and use it) """ def hello(): print("Hello", __name__) print("How ar...
class TwoSum: def __init__(self): self.nums = {} def add(self, number): self.nums[number] = self.nums.get(number, 0) + 1 def find(self, value): for num in self.nums: if value - num in self.nums and (num != value - num or self.nums[num] > 1): return True...
segundos_str = input("Por favor, entre com o número de segundos que deseja converter:") total_segs = int(segundos_str) dias = total_segs // 86400 rest = total_segs % 86400 horas = rest // 3600 segs_restantes = rest % 3600 minutos = segs_restantes // 60 segs_restantes_final = segs_restantes % 60 #teste if total_segs ...
# Copyright 2021 The XLS Authors # # 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 writ...
class APIException(Exception): pass class KeyboardException(Exception): pass
""" 에라토스테네스의 체 """ def eratos(n): # 에라토스테네스의 체 초기화: n개 요소에 True 설정(소수로 간주) sieve = [True] * n # n의 최대 약수가 sqrt(n) 이하이므로 i=sqrt(n)까지 검사 m = int(n ** 0.5) for i in range(2, m + 1): if sieve[i]: # i가 소수인 경우 for j in range(i+i, n, i): # i이후 i의 배수들을 False 판정 ...
## ## # File auto-generated against equivalent DynamicSerialize Java class class ServerMsg(object): def __init__(self): self.message = None def getMessage(self): return self.message def setMessage(self, message): self.message = message
# Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. print('-' * 100) print('{: ^100}'.format('EXERCÍCIO 037 - CONVERSOR DE BASES NUMÉRICAS')) print('-' * 100) n = int(input('Digite um númer...
raw_data = nr.random.normal(10, 1, 100) with tf.session() as sess: for i in range(len(raw_data)): curr_avg = sess.run(update_avg, feed_dict = {curr_value:raw_data[i]} )
# Author: btjanaka (Bryon Tjanaka) # Problem: (HackerRank) string-construction # Title: String Construction # Link: https://www.hackerrank.com/challenges/string-construction/problem # Idea: Since you can copy any substring at no charge, you can just copy single # letters that you previously purchased. Thus, the cost is...
class Solution: def spiralOrder(self, matrix): if matrix == []: return [] startRow = startCol = 0 endRow = len(matrix) - 1 endCol = len(matrix[0]) - 1 final_array = [] while startRow <= endRow and startCol <= endCol: ...
class Message: def __init__(self, data_dict=None, msg_id=-1, sender_id=-1, sender_ip=-1, msg="", verbose=False): if data_dict == None: if verbose: print(f"Created message sent from id: {sender_id}, with id {msg_id}") self.message_id = msg_id self.sender_...
def visitor(visitor_class: object): def visited(self, obj: object): # call visitor obj.__getattribute__("visited_" + visitor_class.__name__)(self) setattr(visitor_class, "visit", visited) return visitor_class
# A closure in Python is said to occur # when a nested function references # a value in its enclosing scope. # The whole point here is that it remembers the value def A(x): def B(): print(x) return B A(7)()
class Solution: def accountsMerge(self, acconts: List[List[str]]) -> List[List[str]]: n = len(acconts) pos = 0 emailList = {} emailList2 = [] for accont in acconts: for email in accont[1:]: if email not in emailList: em...
#Language:python #ID:52542 #QLink:https://quera.org/problemset/52542/ #Author:Amirkhaksar groups = int(input()) members =input() member_list = member_list = members.split() for i in member_list: number =int(i) if number <= 3: print("*" * number) else: print("*")
f_txt = open("ori.txt", "r") f_srt = open("converted.srt", "w") cnt = 1 line = f_txt.readline() while True: next_line = f_txt.readline() start_time = line[0:8] if not next_line: start_time_sec = int(line[6:8]) start_time_mnt = int(line[3:5]) start_time_hr = int(line[0:2]) e...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"load_data": "00_utils.ipynb", "average_preds": "00_utils.ipynb", "get_averaged_preds": "00_utils.ipynb", "get_datablock": "01_dataset.ipynb", "get_dls": "01_dataset.ipynb"...
# vFabric Administration Server API # Copyright (c) 2012 VMware, 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 # # https://www.apache.org/licenses/LICENSE-2.0...
model_name:str = 'AutoEncoder' max_view_imgs:int = 8 view_interval:int = 10 view_point_num:int = 5 lr:float = 0.001 batch_size:int = 64 encoder_nlayers:int = 4 decoder_nlayers:int = 4 def get() ->dict: hparam:dict = { "model_name":model_name, "lr":lr, "batch_size":batch_size, "enc...
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if ((x1 + y1) % 2 == 0) and (x2 + y2) % 2 == 0: if (y2 > y1) and (x1 + y1 - y2 <= y1) and (x2 <= x1 + y2 - y1): print("YES") else: print("NO") else: print("NO")
# Projeto: VemPython/exe026 # Autor: rafael # Data: 14/03/18 - 16:55 # Objetivo: TODO Faça um programa que leia uam frase pelo teclado e mostre: # Quantas vezes aparece a letra "A" # Em que posição ela aparece a primeira vez # Em que posição ela aparece pela ultima vez frase = str(input('Escreve uma parada ai: ')).str...
# TwilioQuest version 3.1.26 # Works in: # 3.1.26 # why you no camelCase? # would be: # favoriteRobot = "Cedric" # meaningOfLife = 42 favorite_robot = "Cedric" meaning_of_life = 42
class Workspace(object): def __init__(self, ws_str): d_num, current, geom, vp_pos, working_geom, name = self.parse_ws_line(ws_str) self.number = d_num self.name = name self.is_current = current self.geometry = DesktopGeom(*geom) self.working_geometry = WorkareaGeom(*w...
#List Methods numbers = [5,2,1,7,4] numbers2 = numbers.copy() print(f"original: {numbers}") numbers.insert(0, 10) print(numbers) print("\n") numbers.pop() print(numbers) number = [2,2,4,6,3,4,6,1] uniques = [] for num in number: if num not in uniques: uniques.append(num) print(uniques)
# Datasets paths LIBRI_FS50K='/mnt/data/FedEnhance/' CHUNK_LIBRI_FS50K='/mnt/data/ChunkFedEnhance/' CHUNK_WHAM_ENH='/mnt/data/PreFedEnhance/' # Federated learning experiments log dir FED_LOG_DIR='/home/thymios/fedenhance_log/' # Cometml your key API_KEY = 'place_your_cometml_key_here'
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: l = len(strs) ## If there is one string if l == 1: return strs[0] ## Get the length of the first word in the list ## We will use this length to check maximum prefix lw...
# 1st solution # O(kn) time | O(kn) space # where k = 2 class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) <= 1: return 0 n, k = len(prices), 2 profits = [prices[i + 1] - prices[i] for i in range(len(prices) - 1)] if k > len(prices) // 2: ...
"""Some cool functions to show nothing but a test""" def my_sum(a: float, b: float) -> float: """Sum of two floats Parameters ---------- a : float First value to sum b : float Second value to sum Returns ------- float The sum of ``a`` and ``b`` See also ...
''' TODO Greeting Create commandline prompt for height Create commandline prompt for weight Run calculation Look up BMI chart Print results ''' def welcome(): print('Hi welcome to the BMI calculator.') def request_height(): height = 0 return height def request_weight(): '''Commandline user input fo...
OCTICON_PAINTBRUSH = """ <svg class="octicon octicon-paintbrush" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M11.134 1.535C9.722 2.562 8.16 4.057 6.889 5.312 5.8 6.387 5.041 7.401 4.575 8.294a3.745 3.745 0 00-3.227 1.054c-.43.431-.69 1.066-.86 1.657a11.982...
__author__ = 'Clement JACOB' __copyright__ = "Copyright 2013, The Python OpenGL Engine" __license__ = "Closed Source" __version__ = "0.0.1" __email__ = "clems71@gmail.com" __status__ = "Prototype" class Stats(object): drawcalls = 0 @staticmethod def clear(): Stats.drawcalls = 0 def __repr__(self)...
class TogglClientException(Exception): pass class ArquivoCOnfiguracaoNaoEncontrado(TogglClientException): pass class TarefaAtivaException(TogglClientException): pass
class Cart: def __init__(self): self.__list_of_items = [] def add_item_to_cart(self, item): self.__list_of_items.append(item) def get_items_in_cart(self): return self.__list_of_items
hours = int(input()) minutes = int(input()) add_minutes = minutes + 15 if add_minutes <= 59: hours += 0 minutes = add_minutes elif add_minutes >= 60: hours += 1 minutes = add_minutes - 60 if hours >= 24: hours = 0 if minutes < 10: print(f"{hours}:0{minutes}") else: print(f"{hours}:{minutes}...
#!/usr/bin/env python3 class DirectedEdge: def __init__(self, v, w, weight): self.v = v self.w = w self.weight = weight def fromv(self): return self.v def to(self): return self.w def getVertex(self): return (self.v, self.w) def getWeight(self): ...
#Link : https://leetcode.com/problems/implement-stack-using-queues/ """ For a list = [1,2,3,4] Stack = [1 , 2 , 3 , 4] -> Top = 4 Stack.pop = 4 Queue = [1 , 2 , 3 , 4 ] -> FIFO -> First ele = 1 In order to make queue perform stack operations , we need to pop 4 i.e the last element We will be using 2 queues he...
'''module that contains a plethora of agents and policies This module will contain a number of agents and policies that can be specified by easily in a uniform manner. This way different agents can be easily swapped out between each other. Agents ------- Agents take a state and return an action. Unfortunately, bo...
def prepare_data(df, split, split_valid=None, mode="train"): if mode == "train": df = split_train_test(df, split=split, split_valid=split_valid) df.rename(columns={"^BVSP": "IBOV"}, inplace=True) return df def split_train_test(df, split, split_valid=None, ascending=True): # Number of rows ...
#distinct powers if __name__ == '__main__': s = [] for i in range(2, 101): for j in range(2, 101): s.append(i ** j) print(len(set(s)))
RUN = 1 QUIT = 2 PRINT = 3 TEMPLATE = 4 LIST_SHEET = 5 BACK_TRACE=6 STEP = 7 NEXT = 8 TEST = 9 EVAL = 10 MATCH = 11 AVT = 12 LIST_TEMPLATE = 13 SET_BREAK = 14 LIST_BREAK = 15 DELETE_BREAK = 16 HELP = 100 g_runCommands = [RUN, TEMPLATE, STEP, NEXT, ...
""" Profile ../profile-datasets-py/div52_zen30deg/002.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div52_zen30deg/002.py" self["Q"] = numpy.array([ 1.60776800e+00, 3.57700700e+00, 5.25388800e+00, 6.60521100e+00, 5.98130300e+00, 6.68717500e+0...
class Msgs: cmd = 1 info = 5 namespace = 7 args = 3 kwargs = 4 class Commands: ping = 1 head = 2 get_state = 3 set_state = 4 exec_atomic_fn = 5 exec_dict_method = 6
# ====================================================================== # Amphipod # Advent of Code 2021 Day 23 -- Eric Wastl -- https://adventofcode.com # # Python implementation by Dr. Dean Earl Wright III # ====================================================================== # =================================...
""" 이진 탐색 """ finding_number = 14 seq_list = [i for i in range(1, 15)] def is_exist(target, array): # 방법 1 cur_min_idx = 0 cur_max_idx = len(array) - 1 cur_guess_idx = (cur_min_idx + cur_max_idx) // 2 while cur_min_idx <= cur_max_idx: if array[cur_guess_idx] == target: return ...
# Production SECRET_KEY = b'\xfe=Hzo\xd1\x9bY_hW1\n\x07\xc6\xff' SQLALCHEMY_DATABASE_URI = 'postgresql://ayman:ayman@localhost:5432/catalog' # Testing the connection # psql –-host=localhost --port=5432 --username=ayman --password --dbname=catalog
''' @author: l4zyc0d3r People who are happy makes other happy. I am gonna finish it slowly but definitely.cdt ''' class Solution: def summaryRanges(self, N: List[int]) -> List[str]: if not N: return N ans,i,l=[],0,len(N) while i<l: j=i+1 while j<l and N[j]-N[j-1]==1:...
""" Space : O(1) Time : O(n) """ class Solution: def judgeCircle(self, moves: str) -> bool: x, y = 0, 0 n = len(moves) if n == 0: return True for i in moves: if i == "L": x -= 1 elif i == "R": x += 1 ...
def _setup_codeblock_substitutions(app): for ext in [ 'sphinx-prompt', 'sphinx_substitution_extensions', ]: app.setup_extension(ext) # list of interpretable substitutions app.config.substitutions = [ ('|version|', app.config.version), ] def setup(app): _setup_co...
""" A mixin for classes all compared the same way. """ class CompareByDict(object): """A mixin for classes that should be compared by their attribute/value pairs. Useful for the Document classes. """ def __eq__(self, other): return self.__dict__ == other.__dict__ def __neq__(self, other):...
def test_export__ExportList__1(search_data, browser): """..export.ExportList() renders an advice if there are no exporters. The actual exporters are tested in their modules. """ browser.login('visitor') browser.open(browser.PERSONS_LIST_URL) browser.getLink('Hohmuth').click() browser.getCo...
uni = "Jacobs" #012345 #654321 Negative reverse_uni = uni[::-1] print(reverse_uni)
MAJOR_COLORS = ['White', 'Red', 'Black', 'Yellow', 'Violet'] MINOR_COLORS = ["Blue", "Orange", "Green", "Brown", "Slate"] def color_pair_to_string(major_color, minor_color): return f'{major_color} {minor_color}' def get_color_from_pair_number(pair_number): zero_based_pair_number = pair_number - 1 major_index...
#!/usr/bin/env python # coding=utf-8 print("Hello world") #变量 message = "my name is zy" print(message) #字符窜 ##对于字符串单引号和双引号都可以 name = 'zy' print(name) ##title()来修改字符串的每个单词的首字母的大小写 name = 'add lovelace' print(name.title()) ##upper()全部大些 print("upper() : " + name.upper()) ##lower()全部小写 print("lower() :" + name.lower(...
country = input('Enter the name of your country: ') if country.lower == 'Kenya': print('so you must love kipchoge!') else: print('Your not from kenya')
class Source: def check_ipv4(self, ipv4): raise NotImplementedError def check_domain(self, domain): raise NotImplementedError def check_md5(self, md5): raise NotImplementedError def check_sha1(self, sha1): raise NotImplementedError def check_sha256(self, sha256): ...
print('====== DESAFIO 51 ======') receive = int(input('Digite um número: ')) tot = 0 for c in range(1, receive+1): s = receive % c if s == 0: tot += 1 if tot > 2: print(receive,'Não é primo') else: print(receive,'É primo')
dist = float(input('Digite uma distância em metros: ')) mm = dist * 1000 cm = dist * 100 dm = dist * 10 dam = dist / 10 hm = dist / 100 km = dist / 1000 print('A distância de {}m, equivale há {:.0f}mm, {:.0f}cm, {:.0f}dm.\nQue é igual há {}dam, {}hm, {}km.'.format(dist, mm, cm, dm, dam,hm, km))
name2 = " \t\n Angela McAdoo " print (name2) name2 = name2.strip() print (name2)
x = {1, 2, 3} x = {i for i in range(0, 10)} x = {1: 2, 3: 4} x = {**dic} x = {**dic, 4:5} x = {*l, 2, 3} x = {key : value for (key, value) in zip(keys, values)}
def media(alunos): nome = str(input("\ndigite o nome do aluno: ")) flag = 0 for k in alunos.keys(): if(k == nome): M = (alunos[nome][0] + alunos[nome][1])/2 flag = 1 if flag == 0: print("aluno nao encontrado!") else: print(f"\nmedia do aluno {nome} : {...
a = [] while True: n1 = int(input('Digite um número:\n')) a.append(n1) if a.count(n1) > 1: print('Esse valor não será adicionado, pois já foi uma vez.') a.pop() conf = input('Deseja continuar? (S/N)\n') if conf in 'Ss' or conf in 'Nn': if conf in 'Nn': break e...
# Revision of some previous learning cars = ['Bugatti','Verna','BMW-M4'] for car in cars: print(car.title()+"these are my favourite cars.") print("sound of these cars are like a beast."+car.title()) print("\t list of my favourite cars.") # Finding prime numbers for prime in range(0,100,2): print(prime) #...
# -*- coding: utf-8 -*- def pre_save_title(instance, raw, **kwargs): """Save old state to instance and setup path """ if not instance.publisher_is_draft: return page = instance.page page_languages = page.get_languages() if not instance.language in page_languages: page_languag...
PRESETS_FILES = [ ( [ "GE63", "GE73", "GE75", "GS63", "GS73", "GS75", "GX63", "GT63", "GL63", "GP75", "GL73", ], "1.json", ), (["GS65"], "2.json"), ]
''' https://www.spoj.com/problems/ABCDEF/ **Description** You are given a set S of integers between -30000 and 30000 (inclusive). Find the total number of sextuples that satisfy: a*b+c = (e+f)*d **Input** The first line contains integer N (1 ≤ N ≤ 100), the size of a set S. Elements of S are given in the next N line...
peso = float(input("Digite seu peso: ")) altura = float(input("Digite sua altura: ")) imc = peso/(altura ** 2) print("Seu IMC é {:.1f}".format(imc)) if imc < 18.5 : print("Você está abaixo do peso.") elif imc <= 25 : print("Você está no peso ideal.") elif imc <= 30 : print("Você está com sobrepeso.") elif i...
nome = str(input('Digite seu nome completo: ')).strip() print(f'Nome com todas as letras maiúsculas: {nome.upper()}') print(f'Nome com todas as letras minúsculas: {nome.lower()}') n = nome.replace(' ', '') print(f'Quantidade de letras com espaços: {len(nome)}') print(f'Quantidade total de letras (sem espaços): {len(n)}...
DEFAULT_CREDENTIALS_CONFIG = "config/credentials.json" DEFAULT_AUTH_CONFIG = "config/auth.json" DEFAULT_WORKER_CONFIG = "config/worker.json" CONFIG_STORE_DEFAULT = "default" CONFIG_STORES = "stores" CONFIG_STORE_NAME = "name" CONFIG_ENDPOINT = "endpoint" CONFIG_ACCESS_KEY = "accessKey" CONFIG_SECRET_KEY = "secretKey" ...
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ def helper(start, end): if start >= end: return s[start], s[end] = s[end], s[start] start += 1 ...
pkgname = "libmikmod" pkgver = "3.3.11.1" pkgrel = 0 build_style = "gnu_configure" hostmakedepends = ["pkgconf"] pkgdesc = "Mikmod module player and library" maintainer = "q66 <q66@chimera-linux.org>" license = "LGPL-2.1-or-later" url = "http://mikmod.shlomifish.org" source = f"$(SOURCEFORGE_SITE)/mikmod/{pkgname}-{pkg...
def aumentar(valor=0, taxa=0, fmt=False): res = valor + (valor * taxa/100) return moeda(res) if fmt else res def diminuir(valor=0, taxa=0, fmt=False): res = valor - (valor * taxa / 100) return moeda(res) if fmt else res def dobro(valor=0, fmt=False): res = valor * 2 return moeda(res) if fmt ...
# # Codegenerator for Dagger IDL # #!/usr/bin/python TAB_SIZE = 4 class CodeGen: def __init__(self, tmpl_filename = ""): self.__code = "" self.__seek_ptr = 0 def append(self, line): self.__code = self.__code[:self.__seek_ptr] \ + line \ + self.__code[self.__seek_ptr:] self.__se...
num = int(input('digite um numero')) pi = num%2 if pi == 0: print ('{} é um numero par'.format(num)) else: print ('{} é um numero impar'.format(num))
""" This module contains the result sentences and intents for the French version of the Supervisor app. """ # Result sentences RESULT_BACK = "Bonjour, je suis de retour !" RESULT_CONFIRM_REBOOT = "Voulez vous vraiment redémarrer le système ?" RESULT_CONFIRM_SHUTDOWN = "Voulez vous vraiment arrêter le système ?" RESULT...
class ProgressManager: def __init__(self, request): self.request = request def get_progress(self, section): user = self.request.user if self.request.user.is_anonymous: read_article_ids = set(self.request.session.get('read_articles', [])) else: read_artic...
class Pessoa: def __init__(self, nome, idade): self.nome = nome self.idade = idade self.nome_classe = self.__class__.__name__ def falar(self): print(f'{self.nome_classe} falando ...') class Cliente(Pessoa): def comprar(self): print(f'{self.nome_classe} comprando .....
orders=[['34587', 'Learning Python', 'Mark Lutz', 4, 40.95], ['98762', 'Programming Python', 'Mark Lutz', 5, 56.80], ['77226', 'Head First Python', 'Paul Barry', 3, 32.95], ['88112', 'Einfuhrung in Python3', 'Bernd Klein', 3, 24.99]] output = [[0]*2]*4 for i in range (0, 4): output[i][0]=orders[i][0] outpu...
#第一题 tp1=(10,20,55,90,20,10,20) set1=set(tp1) list1=list(set1) list1.sort() tp1=tuple(list1) print(tp1) #第二题 dict1={'王洪':90,'刘芸':60,'张天青':100,'胡源':70,'卢果':100} maxvalues=max(dict1.values()) print('最高分数是'+str(maxvalues)) print('得到最高分的学生名是:',end='') for i in dict1.keys(): if dict1[i]==maxvalues: print(i,end='...
""" Some format recipies """ # INPUT DATA data = [ (1000, 10), (2000, 17), (2500, 170), (2500, -170), ] # Print the header for reference print('REVENUE | PROFIT | PERCENT') # This template aligns and displays the data in the proper format TEMPLATE = '{revenue:>7,} | {profit:>+6} | {percent:>7.2%}' # ...
""" diaper pattern example (This is how you should NOT build your try.. except clauses) """ def fibonacci(n): """Returns the n-th number from the Fibonacci series.""" try: a = 0 b = 1 while n > 0: temp = a+b a = b b = temp ...
# Definition for singly-linked list. class Node(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeKLists(self, lists): # find start node pendings = [] start = None for list in lists: show(list) ...
""" Warnings raised during database object interaction. """ class PlayerAlreadyJoinedWarning(Warning): """ Is raised when a player tries to join again. """
class Sale: def __init__(self, town, product, price, quantity): self.town = town self.product = product self.price = price self.quantity = quantity def read_sale(): inputData = input().split(' ') town = inputData[0] product = inputData[1] price = float(inputData[2]) ...
class _MemberlistUpdater(object): def add_or_updater(self): pass def _get_memberlist(self): pass
''' Author: Kris Gonzalez DateCreated: 190114 Objective: write tests that execute on a given set of code in order to test compatability and give an example of "continuous integration" General Steps: 1. make a few random functions 2. in another file, write tests for those functions 3. run "pytest" and output result...