content
stringlengths
7
1.05M
class Crc8(): """ Implements the 1-wire CRC8 checksum. (The polynomial should be X^8 + X^5 + X^4 + X^0) """ R1 = [0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41] R2 = [0x00, 0x9d, 0x23, 0xbe, 0x46, 0xdb, 0x65, 0xf8, ...
##################################################################################################### """ that one is too long tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo loooooong""" __revision__ = '' # The next line is exactly 80 characters long. A = '-----------------------------------------...
cores = {'verde': '\033[1;32m', 'vermelho': '\033[1;31m', 'azul': '\033[1;34m', 'violeta': '\033[1;35m', 'clear': '\033[m'} pessoa = dict() lista = list() lista_mulheres = list() lista_idade_maior_media = list() media = 0 while True: pessoa["Nome"] = str(input("Digite o nome: "))...
DEFAULT: int = 2 MINIMUM: int = 0 MAXIMUM: int = 9
def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") def print_one(arg1): print(f"arg1: {arg1}") def print_none(): print("I got nothing.") print_two("Kody", "Wilson") print_two_again("Kody", "Wilson") print_one("...
# Copyright 2015 Ufora Inc. # # 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 i...
# # PySNMP MIB module PDN-PPP-LCP-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-PPP-LCP-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:39:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
# Parse header file to generate Python wrapper around the rszvb DLL for the Rohde&Scwarz ZVA 40 Network Anlyzer fout = open("rszvb_v2.py",'w') # First load the DLL print >>fout , """import numpy as numpy from ctypes import * # Prerequisition: installed rszvb driver 32-bit # Reference to rszvb dll rszvbDL...
{ 'sr1_replace' : None, 'search_replace' : '[]', 'sr2_search' : None, 'sr2_replace' : None, 'sr1_search' : None, 'sr3_search' : None, 'sr3_replace' : None, }
# coding=utf-8 """This module, pre_process_constant.py, provides an abstraction for JS constants to pre-process.""" class PreProcessConstant(object): """Represents a constant to pre-process.""" def __init__(self, raw_line): self._raw = raw_line self._variable = None self._value = None self._initia...
# -*- coding: utf-8 -*- """ stashcli.errors ~~~~~~~~~~~~~~~~ stashcli exception definitions """ class DuplicatePullRequest(Exception): def __init__(self, msg): super(DuplicatePullRequest, self).__init__(msg) class EmptyPullRequest(Exception): def __init__(self, msg): super(EmptyPullRequest, ...
""" Escreva um algoritmo que leia 2 números e imprima o resultado da divisão do primeiro pelo segundo. Caso não for possível mostre a mensagem “divisao impossivel” para os valores em questão. Entrada A entrada contém um número inteiro N. Este N será a quantidade de pares de valores inteiros (X e Y) que serão lidos em ...
class Node: def __init__(self, data): self.data = data self.next = None self.arb=None class Solution: def cloneList(self, head): clone_head = clone_last = None current_node = head while current_node: if clone_head == None: clone_head...
x = int(input()) y = int(input()) soma = 0 if y < 0: for c in range(x, y, -1): if c % 2 != 0: soma += c print(soma) elif x > y: for c in range(y, x): if c % 2 != 0: soma += c print(soma) else: print('0')
class AtomClass: def __init__(self, Velocity, Element = 'C', Mass = 12.0): self.Velocity = Velocity self.Element = Element self.Mass = Mass def Momentum(self): return self.Velocity * self.Mass
N = int(input()) check = False for i in range(1, N): nums = list(map(int, str(i))) sum1 = i + sum(nums) if sum1 == N: print(i) check = True break if not check: print(0)
expected_output = { "interface": { "Loopback0": { "interface_status": "Up", "ip_address": "200.0.7.1", "protocol_status": "Up" }, "MgmtEth0/RSP0/CPU0/0": { "interface_status": "Up", "ip_address": "5.25.27.1", "protocol_s...
''' script de desconto de valor ''' valor = float(input('Qual o Valor? ')) porcentagem = float(input('Qual a Porcentagem? ')) redução = (valor / 100) * porcentagem valor_final = valor - redução print(f'{porcentagem}% de {valor} é {redução:.2f}') print(f'sobrará {valor_final:.2f}')
# Chino (2210013) | Colossus Road : Chino's Lift: The Road Up & Down sm.setPlayerAsSpeaker() sm.sendNext("Hey..") sm.setSpeakerID(parentID) sm.sendSayOkay("No.")
class FancyPrint(object): HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def echo(stuff_to_print, style): bash_color = getattr(FancyPrint, style, None) if no...
class ImageGroupData: def __init__(self, start_y, start_x, y_gear_offset, x_gear_offset): self.start_y = start_y self.start_x = start_x self.y_gear_offset = y_gear_offset self.x_gear_offset = x_gear_offset class ImageTypeData: def __init__(self, size, rel_start_offset, rows=None, columns=None, p...
# BEDIRHAN KARAKAYA file = open("veriler.txt", "r") veriler = [] # Değerleri veriler dizisine atiyorum for i in file: veriler.append(int(i)) # dizinin eleman sayisi elemanSayisi = len(veriler) toplam_y = 0 # dizideki elemanlarin toplamini buluyorum for i in range(elemanS...
text = input() save = [] for letter in text: o = ord(letter) + 3 ch = chr(o) save.append(ch) print("".join(save))
''' URL: https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/ Time complexity: O(n) Space complexity: O(n) ''' class Solution(object): def minDiffInBST(self, root): """ :type root: TreeNode :rtype: int """ sorted_lst = [] self.sort_vals(root...
''' ' Task #7.13 ' Created by Andrii Demchenko ' Computer Mathematics, 1st grade ' ' Скласти програми (свій пункт, я зробив 4) ' а) всі голосні літери, які входять до кожного слова; ' б) всі приголосні літери, які не входять до жодного слова; ' ж) всі дзвінки приголосні літери, які входять ' в кожне ...
# # PySNMP MIB module AISYSCFGTEMP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AISYSCFGTEMP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:01:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
cur_hedons = 0 cur_health = 0 last_hedons = 0 last_health = 0 cur_star = None cur_star_activity = None last_star_time = 0 bored_with_stars = False last_activity = None last_activity_duration = 0 cur_time = 0 last_finished = -1000 def initialize(): '''Initializes the global variables needed...
def get_cycle(n): results = [] remainders = [1] val = 1 while True: result = (val*10)//n remainder = (val*10)%n results.append(result) if remainder == 0 or remainder in remainders: break remainders.append(remainder) val = remainder return (...
# Databricks notebook source LWILIOBCIMDGCHFASADRRGZCLIILUWO RAZOIMPPJWANJOYLINMNWZBNP ZGJJDFPYWBFLTPDCBSYJNCJLHEJLZASADWKGDWRMJCBBBOCJBPWLLGBPKTLMNQTFQKMHEEICHICAMKGNLTSAYULKKXJFNPLKAALUFPSLDWIHHUGNWKEMGMXWBDG GSTFBJXBKRCGZHILZPJRUOFWRVWWKVAIDTEK NIKIMPVFKIFHNJSLWLJZOHICCULWGGJJSWLHQFHQQUCDPJRBGAS OBARCRYIKLKKEZ LTMF...
def palindromo(palabra): palabra =palabra.replace(' ','') palabra=palabra.lower() palabra_invertida = palabra[::-1] if palabra==palabra_invertida: return True else: return False def run(): palabra = input("Escribir una palabra: ") es_palindromo=palindromo(palabra) if e...
# # PySNMP MIB module CISCO-IETF-SCTP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IETF-SCTP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:43:56 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
supported_types = { 'removed', 'added', 'updated', 'nested', 'unchanged' } def stringify(value): if isinstance(value, dict): return '[complex value]' if isinstance(value, bool): return str(value).lower() if value is None: return 'null' if isinstance(value, s...
obj = pd.Series(np.arange(5.), index=list('abcde')) obj obj.drop(['c']) obj.drop(list('dc')) data = pd.DataFrame(np.arange(16).reshape((4,4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) data data.drop(['Colorado', 'Ohio']) data.drop('two', axis=1) data.drop('two', axis='col...
def chooseLargest(a, b): list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b))) l1 = [1, 2, 3, 4, 5] l2 = [2, 2, 9, 0, 9] return list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b)))
# https://www.hackerrank.com/challenges/string-validators/problem string = input() print(any(c.isalnum() for c in string)) print(any(c.isalpha() for c in string)) print(any(c.isdigit() for c in string)) print(any(c.islower() for c in string)) print(any(c.isupper() for c in string))
frase = "Curso em Video Python" print(len(frase))# para contar a quatidade de caracteres em frase. print(frase[3:12])#para separar letras de frase apartir da casa 3 (lembrando que começa de 0 então a posicao e 4) ate a numero 12 sendo que a 12 será excluída. print(frase[3::2])#Inicia o print da 3 casa da frase até a ...
# # PySNMP MIB module Nortel-Magellan-Passport-VnetMcdnSigMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-VnetMcdnSigMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:19:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan...
# Localizable strings extracted by LocalizationDemo.tscn tr("Space") tr("Exclam") tr("QuoteDbl") tr("NumberSign") tr("Dollar") tr("Percent") tr("Ampersand") tr("Apostrophe") tr("ParenLeft") tr("ParenRight") tr("Asterisk") tr("Plus") tr("Comma") tr("Minus") tr("Period") tr("Slash") tr("Colon") tr("Semicolon") tr("Less")...
""" This file stores API headers used by the samples. The samples call the dictionary in this script to retrieve them. You can store multiple header dictionaries here and call the one you want to use in your script. IN PRODUCTION: You may not want to store your keys in plaintext in a source code file. You can just re...
class FormataTexto(object): def __init__(self, texto, formatacao='Titulo'): self.__texto = texto self.__formatacao = formatacao def __str__(self): return self.__getFormatar() def __getFormatar(self): if self.__formatacao == 'Titulo': return self.__texto....
__title__ = 'app' __description__ = 'A Flask based microblog.' __url__ = 'https://github.com/Napchat/microblog' __version__ = '1.0' __author__ = 'Shang Nan' __author_email__ = 'shangnan543@163.com' __license__ = 'MIT License' __copyright__ = 'Copyright 2017 Shang Nan'
# 入力 S = input() ans = ( 'Bad' if S[0] == S[1] or S[1] == S[2] or S[2] == S[3] else 'Good' ) # 出力 print(ans)
info_modes = {'login': 'inurl:login | inurl:signin | intitle:Login | intitle:"sign in" | inurl:auth', 'signup': 'inurl:signup | inurl:register | intitle:Signup', 'phpinfo': 'ext:php intitle:phpinfo "published by the PHP Group"'} for info in info_modes: print(info_modes[info])
N1 = int(input("Digite o primeiro numero: ")) N2 = int(input("Digite o segundo numero:")) print(N1+N2)
OPEN_MS_SRC="/home/uschmitt/Release1.10pyopenms" OPEN_MS_BUILD_DIR="/home/uschmitt/Release1.10pyopenms" OPEN_MS_CONTRIB_BUILD_DIRS="/home/uschmitt/Release1.10pyopenms/contrib;/opt/local;/usr/local;" QT_HEADERS_DIR="/usr/include/qt4" QT_LIBRARY_DIR="/usr/lib/x86_64-linux-gnu" QT_QTCORE_INCLUDE_DIR="/usr/include/qt4/QtCo...
# Group the Numbers # Partitioning : quicksort !! # Time - O(n), Space- O(1) # Lomuto's partitioning O(n) time, in-place def solve(arr): even = -1 # index from the beginning (r -- red == even) i = 0 # current pointer while i < len(arr): # O(n) if arr[i] % 2 == 0: even += 1 ...
class Learner(object): """docstring for Learner""" def __init__(self, model, seed=None): super(Learner, self).__init__() self.model = model self.seed = seed def next(self, pool, step): raise Exception("Undefined next function") def fit(self, X, y): raise Ex...
# see https://www.codewars.com/kata/5a092d9e46d843b9db000064/solutions/python def solve(arr): arr = sorted(arr) i, j = 0, -1 while True: if arr[i] + arr[j] != 0: print(arr[i], arr[j], arr[i+1], arr[j-1]) if arr[i+1] + arr[j] == 0: return arr[i] el...
''' 1. A nota final de um estudante é calculada a partir de três notas atribuídas, respectivamente, a um trabalho de laboratório, a uma avaliação semestral e a um exame final. A média das três notas mencionadas obedece aos pesos a seguir: Nota Peso Trabalho de laboratório ...
''' Assigment No: 1 - Grading Logic Assigment Author's Name: Umaima Khurshid Ahmad Youtube Link: https://youtu.be/SY_c813y6H0 Date: 04/05/2020 'I have not given or received any unauthorized assistance on this assignment' ''' def computeFinalGrade(): '''returns total score and grade of the student ...
class ShootingProblem: def __init__(self, initialState, runningModels, terminalModel): """ Declare a shooting problem. :param initialState: initial state :param runningModels: running action models :param terminalModel: terminal action model """ self.T = len(runningM...
###exercicio 52 n = int(input('digite um numero: ')) if n == 2 or n == 3 or n == 5: print ('{} é um numero primo'.format(n)) elif n%2 == 0 or n%3 == 0 or n%5 == 0: print ('{} não é um numero primo'.format(n)) else: print ('{} é um numero primo'.format(n)) print ('Fim!!!')
class CRITsOperationalError(Exception): """ Critical error oh shiiiii""" pass class CRITsInvalidTypeError(Exception): """Raised when an invalid TLO type is specified""" pass
def parse_table(table): data = [] table_body = table.find('tbody') rows = table_body.find_all('tr') for row in rows: cols = row.find_all('td') cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols if ele]) # Get rid of empty values return data
# -*- coding: utf-8 -*- class ExecutionDisabled(Exception): """ Exception thrown if the manager cannot execute task because execution is disabled """ pass class NotFound(Exception): """ Exception thrown if a requested object is not found in a collection """ pass class ProcessNotFound(NotFound): "...
x = int(input()) _ = ((x) + (3)) _ = ((x) * (6)) _ = ((x) & (2)) _ = ((x) ^ (1)) _ = ((x) | (3)) _ = ((x) + (10))
def swap_case(s): t="" for i in s: if i.isalpha(): if i.isupper(): t=t+i.lower() else: t=t+i.upper() else: t=t+i return (t)
#!/usr/bin/env python EXPECTED_NUM_TESTS = 4 METRICS_FILE_PATH = "./svqc/tests/test_metrics.txt" CRITERIA_FILE_PATH = "./svqc/tests/test_criteria.txt" EXPECTED_OUT_FILE_PATH = "./svqc/tests/test_out.txt" OUT_FILE_PATH = "./svqc/tests/test.out"
class CacheVocabulary: def __init__(self, vocab_data, vocab_dict, cache_number, unknown_word, blank_word): self.word_value = {} self.word_value[unknown_word] = 0 self.word_value[blank_word] = 1 count = 0 for key in vocab_dict.keys(): word = vocab_data.vocab.itos[...
def lprint(msg,*tuple): print(msg) if len(tuple)>1: for obj in tuple: print(obj) print("结束")
def relax(): neopixel.setAnimation("Color Wipe", 0, 0, 20, 1) sleep(2) neopixel.setAnimation("Ironman", 0, 0, 255, 1) if (i01.eyesTracking.getOpenCV().capturing): global MoveBodyRandom MoveBodyRandom=0 global MoveHeadRandom MoveHeadRandom=0 i01.setHandSpeed("left", 0.85, 0.85, ...
TRAINING_DATA = [ ( "我去年去了西安,那里的城墙很壮观!", {"entities": [(4, 5, "TOURIST_DESTINATION")]}, ), ( "人一辈子一定要去一趟巴黎,但那里的埃菲尔铁塔有点无趣。", {"entities": [(5, 6, "TOURIST_DESTINATION")]}, ), ( "深圳也有个巴黎的埃菲尔铁塔,哈哈哈", {"entities": []} ), ( "北京很适合暑假去:长城、故宫,还...
class OdbAnalysisWarning: """The OdbAnalysisWarning object stores the description of different warnings encountered during the analysis. Notes ----- This object can be accessed by: .. code-block:: python import visualization session.odbData[name].diagnosticData.an...
""" 1. Clarification 2. Possible solutions - Brute force - sieve of Eratosthenes (κόσκινον Ἐρατοσθένους in Greek) - Sieve Of Euler 3. Coding 4. Tests """ # # T=O(n*sqrt(n)), S=O(1), Time Limit Exceeded # class Solution: # def countPrimes(self, n: int) -> int: # ans = 0 # for i in range...
class Director: __builder = None def setBuilder(self, builder): self.__builder = builder def getOrden(self): orden = Orden() pan = self.__builder.preparaPan() orden.setPan(pan) carne = self.__builder.agregaCarne() orden.setCarne(carne) verduras = self....
""" Classes for user pers. Classes Personality Conditional """ class Personality: """ Represents a user's decision making. The idea is to get all Conditional objects in goals to be true and false in limits. This allows a user to make decisions by mapping functions to changed output. :pa...
class Room: room_cost = 0 def __init__(self, name: str, budget: float, members_count: int): self.family_name = name self.budget = budget self.members_count = members_count self.children = [] self.expenses = 0 @property def total_monthly_cost(self): retur...
class Solution: def nthUglyNumber(self, n: int) -> int: if n < 0: return 0 dp = [1] * n index2 = index3 = index5 = 0 for i in range(1, n): dp[i] = min(2 * dp[index2], 3 * dp[index3], 5 * dp[index5]) if dp[i] == 2 * dp[index2]: index2 += 1 if dp[i] ...
#6-Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista. Em seguida, calcule a média anual das temperaturas e mostre a média calculada juntamente com todas as temperaturas acima da média anual, e em que mês elas ocorram (mostrar o mês por extenso: 1- janeiro, 2- fevereiro...). ...
# -*- coding: utf-8 -*- """ Created on Wed Jan 18 06:40:34 2018 @author: boele """ # 02, reading text files and converting from NED to XYZ # open xyz file f = open('test.xyz', 'r') data = f.read() xyz = data.split('\n') # print first 5 rows print(xyz[0:5]) # create empty ned list ned = [] # f...
##sequence = [1,1] ##length_expection = int(input("Please enter the length\ ## of Fibonacci to generate:")) ##i = 1 ##j = 2 ##while len(sequence) <= length_expection: ## sequence.append(i+j) ## i += 1 ## j += 1 ##print(element for element in sequence) a = 1 b = 1 while a < 1000: ...
def draw(): rows = int(pow(2, int(random(1, 6)))) u = int(height / (rows + 4)) thickness = int(pow(2, int(random(1, 4)))) uth1 = int(u / thickness) uth2 = u + uth1 startX = int(-u * .75) startY = int(height / 2 + rows / 2 * u) endX = width + u endY = height / 2 + rows / 2 * u fo...
__all__ = [ 'base_controller', 'cdrs_controller', 'numbers_controller', 'routes_controller', 'messages_controller', ]
#!/usr/bin/python3 """Meowth - A Discord helper bot for Pokemon Go communities. Meowth is a Discord bot written in Python 3.5 using version 0.16.12 of the discord.py library. It assists with the organisation of local Pokemon Go Discord servers and their members.""" __author__ = "FoglyOgly, Scragly and BrenenP" __copyr...
#!/usr/bin/env python3 """Zig Zag. Given an array A (distinct elements) of size N. Rearrange the elements of array in zig-zag fashion. The converted array should be in form a < b > c < d > e < f. The relative order of elements is same in the output i.e you have to iterate on the original array only. Source: https://p...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2019-11-04 10:22:34 # @Author : Racter Liu (racterub) # @Mail : racterub@gmail.com # @Link : https://racterub.io # @License : MIT """ 題目: 給定兩輸入 s1, s2 將 s1 最左平移至最右,可平移多次,檢查是否和 s2 相同 輸入 exit 來結束程式 Example1: s1 = 'abcde' s2 = 'cdeab' Answer: True Exa...
__author__ = 'Chintalagiri Shashank' __email__ = 'shashank@chintal.in' __version__ = '0.1.0'
def make_bold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def make_italic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped def make_underline(fn): def wrapped(): return "<u>" + fn() + "</u>" return wrapped @make_bold @ma...
# 000577_30_Dict_add_rem customer_29876 = {'first name': 'David', 'last name': 'Elliott', 'address': '4803 Wellesley St.', 'city': 'Toronto'} print("initial dict", customer_29876) # rem del customer_29876["address"] print('remove "address"',customer_29876) # add "street" print("add street") customer_29876["street"] = "...
# 字符串 str= 'reverse this string', 请使用三种方法翻转字符串。 # 方法1: str= 'reverse this string' print(str[::-1]) # 方法2: str= 'reverse this string' length=len(str) str1='' for i in range(length,0,-1): str1+=str[i-1] print(str1) # 方法3: str= 'reverse this string' str3=reversed(str) str4='' for i in str3: str4+=i print(str4)...
def user_selection(message, options): # taken from https://github.com/Asana/python-asana/blob/master/examples/example-create-task.py option_list = list(options) print(message) for i, option in enumerate(option_list): print(i, ": " + option["name"]) index = int(input("Enter choice (default 0)...
""" Name: exception.py Author: Charles Zhang <694556046@qq.com> Propose: PyGrading exceptions Coding: UTF-8 """ class DataTypeError(Exception): pass class FunctionsTypeError(Exception): pass class FieldMissingError(Exception): pass class ExecError(Exception): pass class Functio...
""" Miscellaneous utility classes and functions. """ class Location: @classmethod def location_from_pos(cls, src, pos, name=None, filename=None): loc = Location(src, name=name, filename=filename, ln=0, col=0, pos=0) for c in src: loc._inc_pos() if c == '\n': ...
class Object: """ Represents a detected object """ # (x, y) is the top left coordinate x = None y = None # (x2, y2) is the bottom right coordinate x2 = None y2 = None width = None height = None label = None score = None def to_string(self): return "x={}, ...
# coding=utf8 # Declaração vetor = [] for i in range (0, 10): vetor.append(i) vetor.reverse() # inverte a lista for i in vetor: print(i, end = " ")
# Exercício Python 040 # LEIA DUAS NOTAS E CALCULE A MEDIA # <5: REPROVADO; ENTRE 5 E 6.9: RECUPERACAO; >=7: APROVADO a = float(input('Digite a nota 1: ')) b = float(input('Digite a nota 2: ')) m = (a + b) / 2 if m >= 7: print('Parabéns, sua média é {:.2f} e você está aprovado!'.format(m)) elif 5 <= m < 7: prin...
""" 继承 - 行为 财产:钱不用孩子挣,但是可以直接花 皇位:江山不用太子打,但是可以直接坐 编程:代码不用子类写,但是可以直接用 """ # 在生活中,先有父再有子,存在"不劳而获的快感". # 在程序中,从设计角度讲,先有子类再有父类 # 多个类型,有代码的共性,且都属于一种概念. # 编码 ,先有父类再有子类 """ class Teacher: def say(self): print("说话") def teach(self): print("教学") class Student: ...
class MenuItem(object): def __init__(self, type: str, title: str, **kwargs): if not isinstance(type, str): raise TypeError('type must be an instance of str') if not isinstance(title, str): raise TypeError('title must be an instance of str') self.type = type se...
class dotUndoOperation_t(object): # no doc Operation=None
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE def indent_code(code, indent): finalcode = "" for line in code.splitlines(): finalcode += " " * indent + line + "\n" return finalcode
''' lec4 dict tuple ''' my_tuple = 'a','b','c','d','e' print(my_tuple) my_2nd_tuple= ('a','b','c','d','e') print (my_2nd_tuple) is_a_tuple= ('a',) print ( type(is_a_tuple) ) print (my_tuple[1]) my_car = { 'color' : 'red', 'maker': 'toyota', 'year': 2015 } print (my_car) print (my_car ['color'])...
class Credentials: def __init__(self, appkey, secretkey, accountkey=None): self.appkey = appkey self.secretkey = secretkey self.account_key = accountkey def __eq__(self, other: object) -> bool: if isinstance(other, Credentials): return self.appkey == other.appkey \ ...
print('Olá, seja bem vindo ao meu site!') print('Estarei lhe redirecionando para nosso sistema') nome = input('Qual seu nome ?') idade = input('Quantos anos você tem?') print('É um grande prazer te conhecer,{}! você está bem velhio hein?! HAHA'.format(nome)) print('Como eu posso lhe ajudar?')
i = 1 pool = 3 entFormat = open("play_script.txt", "w") while i == 1: readLine = input() if readLine == "stop": i = 0 entFormat.close() else: if readLine == "": wool = "{}".format(pool) entFormat.write(" elseif time < "+wool+" then\n") pool = p...
# Uses python3 def edit_distance(s, t, memo = {}): if len(s) == 0: return len(t) if len(t) == 0: return len(s) if (len(s), len(t)) in memo: return memo[(len(s), len(t))] delta = 1 if s[-1] != t[-1] else 0 diag = edit_distance(s[:-1], t[:-1], memo) + delta vert = edit_distance(s[:-1], t...
# # @lc app=leetcode id=280 lang=python3 # # [280] Wiggle Sort # # @lc code=start class Solution: def wiggleSort(self, nums): """ Do not return anything, modify nums in-place instead. """ if nums: nums.sort() for i in range(1, len(nums) - 1, 2): ...
# Examen Parcial 1 Algoritmos y Estructuras 2 Seccion 305C1 # ----- Programacion Modular ----- def factorial(numero): fact = 1 for i in range (1, numero + 1): fact *= i return (fact) def coseno(num, termino): bandera = True result = 1 if(termino % 2 == 0): ...
# -*- coding: utf-8 -*- """ mothpy - moth-inspired navigation models flying in `pompy` (Puff Odour-plume Model in Python) @author: Noam Benelli and Alex Liberzon """ name = "mothpy"
# HEAD # Classes - Metaclasses for class modification # DESCRIPTION # Describes how to use metaclasses dynamically to modify classes during instatiation # Describes how to add attributes to a metaclass # or re-implement the type __call__ methods # Public # RESOURCES # # /opt/pycharm/pycharm-community-2019.2....
# Challenge 036 - 04/21/2021 - Henrique Matheus Alves Pereira # Write a program to approve the bank loan for the purchase of a home. # Ask the price of the house, the buyer's salary and how many years he will pay. # The monthly installment cannot exceed 30% of the salary or the loan will be denied. print("Challenge 036...