content
stringlengths
7
1.05M
_YES_ANSWERS_ = ["y","yes"] _NO_ANSWERS_ = ["n", "no"] def getInput(_string): val = raw_input(_string) return val def getYesNoAnswer(_string): while True: val = raw_input(_string).lower() if val in _YES_ANSWERS_: return True if val in _NO_ANSWERS_: return False
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 elif len(nums) == 1: return nums[0] # get all sum first all_sum = sum(nums)
#!/usr/bin/env python3 # File: xRpcFaker.py def SayHello(token): return f"Hello {token}!"
class EventInstance(object): """ Represents language-neutral information for an event log entry. EventInstance(instanceId: Int64,categoryId: int) EventInstance(instanceId: Int64,categoryId: int,entryType: EventLogEntryType) """ @staticmethod def __new__(self, instanceId, categoryId, entryType=None): """ __new__(cls: type,instanceId: Int64,categoryId: int) __new__(cls: type,instanceId: Int64,categoryId: int,entryType: EventLogEntryType) """ pass CategoryId = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Gets or sets the resource identifier that specifies the application-defined category of the event entry. Get: CategoryId(self: EventInstance) -> int Set: CategoryId(self: EventInstance)=value """ EntryType = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the event type of the event log entry. Get: EntryType(self: EventInstance) -> EventLogEntryType Set: EntryType(self: EventInstance)=value """ InstanceId = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Gets or sets the resource identifier that designates the message text of the event entry. Get: InstanceId(self: EventInstance) -> Int64 Set: InstanceId(self: EventInstance)=value """
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [even for even in a if even % 2 == 0] print(b) c = [even*3 for even in a] print(c)
n = int(input("Digite um número: ")) n1 = n-1 n2 = n+1 print("O antecessor e sucessor de {} são, respectivamente {} e {}".format(n, n1, n2))
""" Loop for Loop -> Estrutura de repetição. for -> Uma dessas estrututras. for item in interavel : //execução do loop Utilizamos loops para iterar sobre sequências ou sobre valores iteráveis (Pode ser escrito uma parte de cada vez) Exemplos de interáveis: - String nome = 'Geek University' - Lista lista = [1, 3, 5, 7, 9] - Range numeros = range(1, 10) """ nome = 'Geek University' lista = [1, 3, 5, 7, 9] numeros = range(1, 10) # Temos que transformar em uma lista # Exemplo de for 1 (Interando sobre um string) for letra in nome: print(letra) print('------------') # Exemplo de for 2 (Interando sobre uma lista) for numero in lista: print(numero) print('------------') # Exemplo de for 3 (Interando sobre uma range) """ range(valor_inicial, valor_final) OBS: O valor final não é inclusive. 1 2 3 4 5 6 7 8 9 10 - Não """ for numero in range(1, 10): print(numero) print('------------') """ Enumerate ((0, 'G'), (1, 'e'), (2, 'e'), (3, 'k'), (4, ' ')...) """ for i, v in enumerate(nome): # i -> indice, v -> letra print(nome[i]) print('------------') for _, v in enumerate(nome): # _ descarta algum valor, que no caso é o indice print(v) print('------------') for i, v in enumerate(nome): print(v) for valor in enumerate(nome): print(valor) # adicionado o [0] imprime o indice e o [1] imprime a letra
cont = 0 somidade = 0 mulheres = list() todos = list() while True: todos.append(dict()) todos[cont]['nome'] = str(input('Nome: ')) todos[cont]['sexo'] = str(input('Sexo: [M/F] '))[0] while todos[cont]['sexo'] not in 'mMfF': print('ERRO! Digite um valor válido!') todos[cont]['sexo'] = str(input('Sexo: [M/F] '))[0] if todos[cont]['sexo'] in 'fF': mulheres.append(todos[cont]['nome']) todos[cont]['idade'] = int(input('Idade: ')) somidade += todos[cont]['idade'] cont += 1 mais = str(input('Quer continuar? [S/N] '))[0] while mais not in 'sSnN': print('ERRO! Digite um valor válido!') mais = str(input('Quer continuar? [S/N] '))[0] if mais in 'nN': break print('-' * 30) print(f'- O grupo tem {cont} pessoas') media = somidade / cont print(f'- A média de idade é de {media:.2f}') print('- As mulheres cadastradas foram: ', end='') for i, mulher in enumerate(mulheres): if i + 1 == len(mulheres): print(mulher) else: print(mulher, '/', end=' ') print('\n- Quem está a cima da média:') for k, acima in enumerate(todos): if todos[k]['idade'] > media: for i, v in todos[k].items(): print(f'{i} = {v} ', end='') print() print('<< ENCERRADO >>')
class Fenwick_Tree: def __init__(self, size): self.size = size + 1 self.array = [0 for _ in range(self.size)] def __len__(self): ''' Called when len is called on object ''' return self.size def lsb(self, index:int) -> int: ''' Returns integer value of least significant bit which is 1 If index is 352(101100000), then return value is 32(100000) ''' return index & -index def prev(self, index:int) -> int: ''' Returns last index whose element is added to element at given index ''' return index - self.lsb(index) def next(self, index:int) -> int: ''' Returns next index where element of current index is added ''' return index + self.lsb(index) def check_index(self, index:int) -> None: ''' Index bound checking Throws an exception if index is out of bounds ''' if index < 0 or index >= self.size: raise ValueError("Index out of bounds") def array_to_fenwick(self, array:list) -> None: ''' Converts the given array into a Fenwick array Writes over the data present in the object before calling this function ''' self.size = len(array) + 1 self.array = [0] for i in array: self.array.append(i) for i in range(1, self.size): next_index = self.next(i) if next_index < self.size: self.array[next_index] += self.array[i] def add(self, index:int, value:int) -> None: ''' Adds value to element at index and updates the Fenwick tree accordingly ''' index += 1 self.check_index(index) while index < self.size: self.array[index] += value index = self.next(index) def insert(self, index:int, value:int) -> None: ''' Replaces old value at index with given value ''' self.add(index, value - self.get_value_at(index)) def range_sum(self, left:int, right:int) -> int: ''' Gets the sum of all elements between left index (inclusive) and right index( exclusive) ''' if left > right: left, right = right, left self.check_index(left) self.check_index(right) s = 0 while right > left: s += self.array[right] right = self.prev(right) while left > right: s -= self.array[left] left = self.prev(left) return s def prefix_sum(self, index:int): ''' Gets the sum of all elements between first element and (index - 1)th element ''' self.check_index(index) s = 0 while index > 0: s += self.array[index] index = self.prev(index) return s def get_value_at(self, index:int) -> int: ''' Gets the value at the given index ''' return self.range_sum(index, index + 1) def get_array(self) -> list: ''' Returns the orginal values of array ''' array = self.array.copy() for i in range(self.size - 1, 0, -1): next_index = self.next(i) if next_index < self.size: array[next_index] -= array[i] array.pop(0) return array
class NofieldnameField(object): pass class FieldnameField(object): fieldname = 'hello' class RepeatedFieldnameField(FieldnameField): pass
def for_one(): """ We are creating a user defined function for numerical pattern of One with "*" symbol """ row=7 col=5 for i in range(row): for j in range(col): if i==1 and j<3 or j==2 or i==6 and j<5: print("*",end=" ") else: print(" ",end=" ") print() def while_one(): row=0 while row<6: col=0 while col<4: if col==2 or row==5 or row==1 and col<3: print("*",end=" ") else: print(" ",end=" ") col+=1 row+=1 print()
# ## ADD THIS TO YOUR .gitignore FILE ## # APPLICATION_TITLE = 'WikiGenomes' # DJango Secret key secret_key = '<django secret key>' # OAUTH Consumer Credentials---you must register a consumer at consumer_key = '<wikimedia oauth consumer key>' consumer_secret = '<wikimedia oauth consumer secret>' # Configurations for django settings.py # ALLOWED_HOSTS add IP or domain name to list. allowed_hosts = ['wikigenomes.org'] # TIME_ZONE wg_timezone = 'America/Los_Angeles' # ## Application customization ## # ## Taxids of the organisms that will included in the instance # ## If left blank, the 120 bacterial reference genomes https://www.ncbi.nlm.nih.gov/genome/browse/reference/ that currently populate WikiGenomes # ## You may also provide a list of taxids from the list of representative species at NCBI RefSeq at the same url # ## - to get the desired taxids into Wikidata for use in your WikiGenomes instance, create an issue at https://github.com/SuLab/scheduled-bots # ## providing the list of taxids, the name and a brief description of your application. You will then be notified through GitHub when the issue is resolved # ## when the genomes, thier genes an proteins have been loaded to Wikidata taxids = []
"""Constants.""" CACHE_NAME = 'news_lk_si' CACHE_TIMEOUT = 3600
'''Escrever um programa que permita ao usuário digitar o dia e mês de seu aniversário e a data de hoje (dia e mês); em seguida, o programa deve calcular quantos dias faltam entre a data de hoje e a data do próximo aniversário. Suponha todos os meses com 30 dias.''' dia = int(input('Digite a data de hoje:')) mes = int(input('Digite o mes atual (em número):')) diaNiver = int(input('Digite o dia do seu aniversário:')) mesNiver = int(input('Digite o mês do seu aniversário:')) if mesNiver>=mes and diaNiver > dia: dataDia = (30-dia)+diaNiver dataMes = (mesNiver-(mes+1))*30 print('Seu aniversário é daqui {} dias'.format(dataDia + dataMes)) elif mesNiver<=mes and diaNiver < dia: dataDia = (30 - dia) + diaNiver dataMes = (mesNiver + (12 - mes)) * 30 print('Seu aniversário é daqui {} dias'.format(dataDia + dataMes)) elif mesNiver == mes and diaNiver == dia: print('Parabéns pelo seu aniversário.')
name = 'AL_USDMaya' version = '0.0.1' uuid = 'c1c2376f-3640-4046-b55e-f11461431f34' authors = ['AnimalLogic'] description = 'USD to Maya translator. This rez package is purely an example and should be modifyed to your own needs' private_build_requires = [ 'cmake-2.8+', 'gcc-4.8', 'gdb-7.10' ] requires = [ 'usd-0.7', 'usdImaging-0.7', 'glew-2.0', 'python-2.7+<3', 'doubleConversion-1', 'stdlib-4.8', 'zlib-1.2', 'googletest', ] variants = [ ['CentOS-6.2+<7'] ] def commands(): prependenv('PATH', '{root}/src') prependenv('PYTHONPATH', '{root}/lib/python') prependenv('LD_LIBRARY_PATH', '{root}/lib') prependenv('MAYA_PLUG_IN_PATH', '{root}/plugin') prependenv('MAYA_SCRIPT_PATH', '{root}/lib:{root}/share/usd/plugins/usdMaya/resources') prependenv('PXR_PLUGINPATH', '{root}/share/usd/plugins') prependenv('CMAKE_MODULE_PATH', '{root}/cmake')
def findMatching(numbers, value): for number1 in numbers: for number2 in numbers: variables = [number1, number2] if (len(set(variables)) != len(variables)): continue if number1 + number2 == value: print("{} + {} = {}, {} * {} = {}".format(number1,number2,value,number1,number2,number1*number2)) return numbers = [] with open("./1/input.txt") as inputFile: for line in inputFile: numbers.append(int(line)) findMatching(numbers, 2020)
def triangle_reduce(triangle): last = triangle.pop() for i, n in enumerate(triangle[-1]): if last[i] > last[i+1]: triangle[-1][i] = triangle[-1][i] + last[i] else: triangle[-1][i] = triangle[-1][i] + last[i+1] return triangle def solve(triangle): while len(triangle) > 1: triangle = triangle_reduce(triangle) return triangle[0][0]
class URL: """ URL config strings """ GPPRO = "https://github.com/martinpaljak/GlobalPlatformPro/releases/" \ "download/v20.01.23/gp.jar" JCALGTEST = "https://github.com/crocs-muni/JCAlgTest/releases/" \ "download/v1.8.0/AlgTest_dist_1.8.0.zip" SMARTCARD_LIST = "http://ludovic.rousseau.free.fr/softwares/pcsc-tools/" \ "smartcard_list.txt" class Paths: """ Path config strings """ GPPRO = "data/bin/gp.jar" JCALGTEST = "data/bin/AlgTestJClient.jar" JCALGTEST_305 = "data/cap/AlgTest_v1.8.0_jc305.cap" JCALGTEST_304 = "data/cap/AlgTest_v1.8.0_jc304.cap" JCALGTEST_222 = "data/cap/AlgTest_v1.8.0_jc222.cap" JCALGTEST_CAPS = [JCALGTEST_305, JCALGTEST_304, JCALGTEST_222] SMARTCARD_LIST = "data/smartcard_list.txt" class MeasureJavaCard: """ Measure Java Card script config strings """ CFG_FILE = "config/measure_javacard/configurations.json" SPEED = { "instant": " You can blink once in the meantime\n", "fast": " Few minutes to fef hours.\n" " You can go make a coffee.\n", "medium": " Up to a few hours.\n" " You can compile Firefox in the meantime.\n", "slow": " Up to tens of hours.\n" " You can compile Gentoo in the meantime.\n" } RISK = { "low": " The test uses standard JCAPI calls\n", "medium": " The tests cause lot of API calls or allocations.\n" " The tests may damage the card.\n", "high": " The tests try to cause undefined behavior.\n" " There is a high possibility of bricking the card.\n" }
class GoogleCredentialsException(Exception): def __init__(self): message = "GCP_JSON or GCP_B64 env variable not set properly" super().__init__(message) class TaskNotFound(Exception): def __init__(self, name: str): message = f"Task {name} not registered." super().__init__(message)
s = "kBNCR9joiFtdAv19AhJ0mHVKassinaPSifCT5bnIrindoudUarwnZxwclalDWjgYudhVD5Sf3Z7looEZCuKQaBIAYTEKn0kQnm2rbwp3KLYsemipalmatusENYyIr6BvCNbuYXeDPFh49tBZQg2Hhw7QrPrAVpyo4RMRRIulZUMBhVNnK1kHFdFM3wxVsvBo3Kq6." a = 23 b = 29 c = 107 d = 118 print (s[a:b + 1] + " " + s[c:d + 1])
def rotate(list, n): return list[n:] + list[:n] def filter_equal_values(lhs, rhs): return [a for a, b in zip(lhs, rhs) if a == b] def sum_as_integers(list_of_strings): return sum(map(int, list_of_strings)) def part_one(input): lhs = list(input) rhs = rotate(lhs, 1) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) def part_two(input): lhs = list(input) rhs = rotate(lhs, len(lhs) // 2) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) if __name__ == "__main__": input = '9513446799636685297929646689682997114316733445451534532351778534251427172168183621874641711534917291674333857423799375512628489423332297538215855176592633692631974822259161766238385922277893623911332569448978771948316155868781496698895492971356383996932885518732997624253678694279666572149831616312497994856288871586777793459926952491318336997159553714584541897294117487641872629796825583725975692264125865827534677223541484795877371955124463989228886498682421539667224963783616245646832154384756663251487668681425754536722827563651327524674183443696227523828832466473538347472991998913211857749878157579176457395375632995576569388455888156465451723693767887681392547189273391948632726499868313747261828186732986628365773728583387184112323696592536446536231376615949825166773536471531487969852535699774113163667286537193767515119362865141925612849443983484245268194842563154567638354645735331855896155142741664246715666899824364722914296492444672653852387389477634257768229772399416521198625393426443499223611843766134883441223328256883497423324753229392393974622181429913535973327323952241674979677481518733692544535323219895684629719868384266425386835539719237716339198485163916562434854579365958111931354576991558771236977242668756782139961638347251644828724786827751748399123668854393894787851872256667336215726674348886747128237416273154988619267824361227888751562445622387695218161341884756795223464751862965655559143779425283154533252573949165492138175581615176611845489857169132936848668646319955661492488428427435269169173654812114842568381636982389224236455633316898178163297452453296667661849622174541778669494388167451186352488555379581934999276412919598411422973399319799937518713422398874326665375216437246445791623283898584648278989674418242112957668397484671119761553847275799873495363759266296477844157237423239163559391553961176475377151369399646747881452252547741718734949967752564774161341784833521492494243662658471121369649641815562327698395293573991648351369767162642763475561544795982183714447737149239846151871434656618825566387329765118727515699213962477996399781652131918996434125559698427945714572488376342126989157872118279163127742349' print(part_one(input)) print(part_two(input))
"""551. Student Attendance Record I https://leetcode.com/problems/student-attendance-record-i/ """ class Solution: def check_record(self, s: str) -> bool: l_cnt, a_cnt = 0, 0 pre = '' for c in s: if c == 'L': l_cnt += 1 if l_cnt == 3: return False elif pre == 'L': l_cnt = 0 if c == 'A': a_cnt += 1 if a_cnt == 2: return False pre = c return True
# 读取5个人的分数并输出总分以及平均分 print('计算5个人分数的总分以及平均分。') tensu1 = int(input('第1名分数:')) tensu2 = int(input('第2名分数:')) tensu3 = int(input('第3名分数:')) tensu4 = int(input('第4名分数:')) tensu5 = int(input('第5名分数:')) total = 0 total += tensu1 total += tensu2 total += tensu3 total += tensu4 total += tensu5 print('总分是{}分。'.format(total)) print('平均分是{}分。'.format(total / 5))
def KSA(key): S = bytearray(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % len(key)]) % 256 S[i], S[j] = S[j], S[i] return S def PRGA(S): i = 0 j = 0 while True: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] K = S[(S[i] + S[j]) % 256] yield K def RC4(key): S = KSA(key) return PRGA(S)
#------------------------------------------------------------------------------- # Part of tweedledum. This file is distributed under the MIT License. # See accompanying file /LICENSE for details. #------------------------------------------------------------------------------- """Tests."""
# 对整数1~12进行循环但跳过8(其一) for i in range(1, 13): if i == 8: continue print(i, end=' ') print()
class LRUCache: def __init__(self, limit): self.limit = limit self.hash = {} self.head = None self.end = None def get(self, key): node = self.hash.get(key) if node is None: return None self.refresh_node(node) return node.value def put(self, key, value): node = self.hash.get(key) if node is None: # 如果key不存在,插入key-value if len(self.hash) >= self.limit: old_key = self.remove_node(self.head) self.hash.pop(old_key) node = Node(key, value) self.add_node(node) self.hash[key] = node else: # 如果key存在,刷新key-value node.value = value self.refresh_node(node) def remove(self, key): node = self.hash.get(key) if node is None: return self.remove_node(node) self.hash.remove(key) def refresh_node(self, node): # 如果访问的是尾节点,无需移动节点 if node == self.end: return # 移除节点 self.remove_node(node) # 重新插入节点 self.add_node(node) def remove_node(self, node): if node == self.head and node == self.end: # 移除唯一的节点 self.head = None self.end = None elif node == self.end: # 移除节点 self.end = self.end.pre self.end.next = None elif node == self.head: # 移除头节点 self.head = self.head.next self.head.pre = None else: # 移除中间节点 node.pre.next = node.pre node.next.pre = node.pre return node.key def add_node(self, node): if self.end is not None: self.end.next = node node.pre = self.end node.next = None self.end = node if self.head is None: self.head = node class Node: def __init__(self, key, value): self.key = key self.value = value self.pre = None self.next = None lruCache = LRUCache(5) lruCache.put("001", "用户1信息") lruCache.put("002", "用户2信息") lruCache.put("003", "用户3信息") lruCache.put("004", "用户4信息") lruCache.put("005", "用户5信息") print(lruCache.get("002")) lruCache.put("004", "用户4信息更新") lruCache.put("006", "用户6信息") print(lruCache.get("001")) print(lruCache.get("006"))
# # PySNMP MIB module ARP-Spoofing-Prevent-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARP-Spoofing-Prevent-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:09:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection") dlink_common_mgmt, = mibBuilder.importSymbols("DLINK-ID-REC-MIB", "dlink-common-mgmt") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Unsigned32, Counter64, NotificationType, Bits, TimeTicks, ModuleIdentity, Integer32, Counter32, ObjectIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Gauge32, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Counter64", "NotificationType", "Bits", "TimeTicks", "ModuleIdentity", "Integer32", "Counter32", "ObjectIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Gauge32", "iso") RowStatus, MacAddress, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "MacAddress", "DisplayString", "TextualConvention") swARPSpoofingPreventMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 12, 62)) if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setLastUpdated('0805120000Z') if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setOrganization('D-Link Corp.') class PortList(OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 127) swARPSpoofingPreventCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 1)) swARPSpoofingPreventInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 2)) swARPSpoofingPreventMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 3)) swARPSpoofingPreventMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1), ) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtTable.setStatus('current') swARPSpoofingPreventMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1), ).setIndexNames((0, "ARP-Spoofing-Prevent-MIB", "swARPSpoofingPreventMgmtGatewayIP"), (0, "ARP-Spoofing-Prevent-MIB", "swARPSpoofingPreventMgmtGatewayMAC")) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtEntry.setStatus('current') swARPSpoofingPreventMgmtGatewayIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayIP.setStatus('current') swARPSpoofingPreventMgmtGatewayMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 2), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayMAC.setStatus('current') swARPSpoofingPreventMgmtPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 3), PortList()).setMaxAccess("readcreate") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtPorts.setStatus('current') swARPSpoofingPreventMgmtStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtStatus.setStatus('current') mibBuilder.exportSymbols("ARP-Spoofing-Prevent-MIB", swARPSpoofingPreventMgmtGatewayIP=swARPSpoofingPreventMgmtGatewayIP, swARPSpoofingPreventCtrl=swARPSpoofingPreventCtrl, swARPSpoofingPreventMgmtStatus=swARPSpoofingPreventMgmtStatus, swARPSpoofingPreventMgmtTable=swARPSpoofingPreventMgmtTable, swARPSpoofingPreventMgmt=swARPSpoofingPreventMgmt, PYSNMP_MODULE_ID=swARPSpoofingPreventMIB, swARPSpoofingPreventMgmtEntry=swARPSpoofingPreventMgmtEntry, PortList=PortList, swARPSpoofingPreventMgmtPorts=swARPSpoofingPreventMgmtPorts, swARPSpoofingPreventMIB=swARPSpoofingPreventMIB, swARPSpoofingPreventInfo=swARPSpoofingPreventInfo, swARPSpoofingPreventMgmtGatewayMAC=swARPSpoofingPreventMgmtGatewayMAC)
def regras(x): if x < 100: if x % 2 == 0: return x else: return (x + x) lista = [100, 200, 1000, 3000, 2, 3, 4, 5, 6, 7, 8] print(list(filter(regras,lista))) #https://pt.stackoverflow.com/q/321682/101
class WarmUpScheduler(): def __init__(self,optimizer, init_lr, d_model, n_warmup_steps): self._optimizer=optimizer self.init_lr=init_lr self.d_model=d_model self.n_warmup_steps=n_warmup_steps self._steps = 0 def step(self): r"""Update parameters""" self._update_learning_rate() self._optimizer.step() def _update_learning_rate(self): r"""Learning rate scheduling per step""" self._steps += 1 lr = self.init_lr * self._get_lr_scale() for param_group in self._optimizer.param_groups: param_group['lr'] = lr def _get_lr_scale(self): d_model = self.d_model n_steps, n_warmup_steps = self._steps, self.n_warmup_steps return (d_model ** -0.5) * min(n_steps ** (-0.5), n_steps * n_warmup_steps ** (-1.5)) def zero_grad(self): self._optimizer.zero_grad() def state_dict(self): return self._optimizer.state_dict() def load_state_dict(self,state_dict): self._optimizer.load_state_dict(state_dict) def get_lr(self): lr = self.init_lr * self._get_lr_scale() return [lr]
def merge(a1, a2): ma = [] i1, i2 = 0, 0 while i1 < len(a1) and i2 < len(a2): if a1[i1] < a2[i2]: ma.append(a1[i1]) i1 += 1 else: ma.append(a2[i2]) i2 += 1 while i1 < len(a1): ma.append(a1[i1]) i1 += 1 while i2 < len(a2): ma.append(a2[i2]) i2 += 1 return ma
def wrap(string, max_width): wrapper = textwrap.TextWrapper(width=max_width) word_list = wrapper.wrap(text=string) lastWrap = word_list[-1] for element in word_list: if element != lastWrap: print(element) return lastWrap
def flatten(some_list): """ Flatten a list of lists. Usage: flatten([[list a], [list b], ...]) Output: [elements of list a, elements of list b] """ new_list = [] for sub_list in some_list: new_list += sub_list return new_list def recursive_radix_sort(some_list, idex=None, size=None): """ Recursive radix sort Usage: radix([unsorted list]) Output: [sorted list] """ # Initialize variables not set in the initial call if size == None: largest_num = max(some_list) largest_num_str = str(largest_num) largest_num_len = len(largest_num_str) size = largest_num_len if idex == None: idex = size # Translate the index we're looking at into an array index. # e.g., looking at the 10's place for 100: # size: 3 # idex: 2 # i: (3-2) == 1 # str(123)[i] -> 2 i = size - idex # The recursive base case. # Hint: out of range indexing errors if i >= size: return some_list # Initialize the bins we will place numbers into bins = [[] for _ in range(10)] # Iterate over the list of numbers we are given for e in some_list: # The destination bin; e.g.,: # size: 5 # e: 29 # num_s: '00029' # i: 3 # dest_c: '2' # dest_i: 2 num_s = str(e).zfill(size) dest_c = num_s[i] dest_i = int(dest_c) bins[dest_i] += [e] result = [] for b in bins: # Make the recursive call # Sort each of the sub-lists in our bins result.append(recursive_radix_sort(b, idex-1, size)) # Flatten our list # This is also called in our recursive call, # so we don't need flatten to be recursive. flattened_result = flatten(result) return flattened_result def iterative_radix_sort(alist, base=10): if alist == []: return def key_factory(digit, base): def key(alist, index): return ((alist[index]//(base**digit)) % base) return key largest = max(alist) exp = 0 while base**exp <= largest: alist = counting_sort(alist, base - 1, key_factory(exp, base)) exp = exp + 1 return alist def counting_sort(alist, largest, key): c = [0]*(largest + 1) for i in range(len(alist)): c[key(alist, i)] = c[key(alist, i)] + 1 # Find the last index for each element c[0] = c[0] - 1 # to decrement each element for zero-based indexing for i in range(1, largest + 1): c[i] = c[i] + c[i - 1] result = [None]*len(alist) for i in range(len(alist) - 1, -1, -1): result[c[key(alist, i)]] = alist[i] c[key(alist, i)] = c[key(alist, i)] - 1 return result
needed_money = float(input()) owned_money = float(input()) days_counter = 0 spending_counter = 0 while True: action = input() amount = float(input()) days_counter += 1 if action == "spend": owned_money -= amount spending_counter += 1 if owned_money < 0: owned_money = 0 if spending_counter >= 5: print("You can\'t save the money.") print(f"{days_counter}") break else: owned_money += amount spending_counter = 0 if owned_money >= needed_money: print(f"You saved the money for {days_counter} days.") break
# Tanner Bornemann # Lab00 - Python Programming - Section 001 # 2017-01-13 def twenty_seventeen(): """Come up with the most creative expression that evaluates to 2017, using only numbers and the +, *, and - operators. >>> twenty_seventeen() 2017 >>> twenty_seventeen() + twenty_seventeen() 4034 >>> twenty_seventeen() * 3 6051 >>> twenty_seventeen() / 2 1008.5 """ return (9 * 9) + ((22 * 2) * 44)
DESCRIBE_GATEWAYS = [ { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-1234XXX", "OwnerId": "012345678912", "Tags": [ { "Key": "Name", "Value": "InternetGateway", }, ], }, { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-7e3a7c18", "OwnerId": "012345678912", "Tags": [ { "Key": "AWSServiceAccount", "Value": "697148468905", }, ], }, { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-f1c81494", "OwnerId": "012345678912", "Tags": [], }, ]
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' def can_paginate(operation_name=None): """ Check if an operation can be paginated. :type operation_name: string :param operation_name: The operation name. This is the same name\nas the method name on the client. For example, if the\nmethod name is create_foo, and you\'d normally invoke the\noperation as client.create_foo(**kwargs), if the\ncreate_foo operation can be paginated, you can use the\ncall client.get_paginator('create_foo'). """ pass def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None, HttpMethod=None): """ Generate a presigned url given a client, its method, and arguments :type ClientMethod: string :param ClientMethod: The client method to presign for :type Params: dict :param Params: The parameters normally passed to\nClientMethod. :type ExpiresIn: int :param ExpiresIn: The number of seconds the presigned url is valid\nfor. By default it expires in an hour (3600 seconds) :type HttpMethod: string :param HttpMethod: The http method to use on the generated url. By\ndefault, the http method is whatever is used in the method\'s model. """ pass def get_paginator(operation_name=None): """ Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name\nas the method name on the client. For example, if the\nmethod name is create_foo, and you\'d normally invoke the\noperation as client.create_foo(**kwargs), if the\ncreate_foo operation can be paginated, you can use the\ncall client.get_paginator('create_foo'). :rtype: L{botocore.paginate.Paginator} ReturnsA paginator object. """ pass def get_waiter(waiter_name=None): """ Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters\nsection of the service docs for a list of available waiters. :rtype: botocore.waiter.Waiter """ pass def send_ssh_public_key(InstanceId=None, InstanceOSUser=None, SSHPublicKey=None, AvailabilityZone=None): """ Pushes an SSH public key to a particular OS user on a given EC2 instance for 60 seconds. See also: AWS API Documentation Exceptions :example: response = client.send_ssh_public_key( InstanceId='string', InstanceOSUser='string', SSHPublicKey='string', AvailabilityZone='string' ) :type InstanceId: string :param InstanceId: [REQUIRED]\nThe EC2 instance you wish to publish the SSH key to.\n :type InstanceOSUser: string :param InstanceOSUser: [REQUIRED]\nThe OS user on the EC2 instance whom the key may be used to authenticate as.\n :type SSHPublicKey: string :param SSHPublicKey: [REQUIRED]\nThe public key to be published to the instance. To use it after publication you must have the matching private key.\n :type AvailabilityZone: string :param AvailabilityZone: [REQUIRED]\nThe availability zone the EC2 instance was launched in.\n :rtype: dict ReturnsResponse Syntax { 'RequestId': 'string', 'Success': True|False } Response Structure (dict) -- RequestId (string) -- The request ID as logged by EC2 Connect. Please provide this when contacting AWS Support. Success (boolean) -- Indicates request success. Exceptions EC2InstanceConnect.Client.exceptions.AuthException EC2InstanceConnect.Client.exceptions.InvalidArgsException EC2InstanceConnect.Client.exceptions.ServiceException EC2InstanceConnect.Client.exceptions.ThrottlingException EC2InstanceConnect.Client.exceptions.EC2InstanceNotFoundException :return: { 'RequestId': 'string', 'Success': True|False } :returns: EC2InstanceConnect.Client.exceptions.AuthException EC2InstanceConnect.Client.exceptions.InvalidArgsException EC2InstanceConnect.Client.exceptions.ServiceException EC2InstanceConnect.Client.exceptions.ThrottlingException EC2InstanceConnect.Client.exceptions.EC2InstanceNotFoundException """ pass
""" Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards. """ fruit = 'banana' i = len(fruit) - 1 while i >= 0: print(fruit[i]) i -= 1 # for ch in fruit[::-1]: # print(ch)
# Time: O(n^2); Space: O(1) def time_required_to_buy(tickets, k): time = 0 while tickets[k] > 0: for i, t in enumerate(tickets): if t > 0: time += 1 tickets[i] -= 1 if tickets[k] == 0: break return time # Time: O(n); Space: O(1) def time_required_to_buy2(tickets, k): time = tickets[k] # it has to buy all at kth position for i in range(len(tickets)): if i < k: time += min(tickets[i], tickets[k]) # for all pos before k it will exhaust all tickets or get till number till kth place elif i > k: time += min(tickets[i], tickets[k] - 1) # for all pos after k it can exhaust all tickets or get 1 less than the kth gets finished return time # Test cases: print(time_required_to_buy(tickets=[2, 3, 2], k=2)) print(time_required_to_buy(tickets=[5, 1, 1, 1], k=0))
# -*- coding: utf-8 -*- proxies = ( # '115.229.93.123:9000', # '114.249.116.183:9000', # '14.118.252.68:6666', # '115.229.93.123:9000', )
# Django settings for yawf_sample project. DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } SITE_ID = 1 # Make this unique, and don't share it with anybody. SECRET_KEY = 'ufq^a%n=9#nbs(_p09c5gvqt(f-7td3$h8tmfbl)(1o9p)226u' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'yawf_sample.urls' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'yawf', 'yawf.message_log', 'yawf_sample.simple', 'reversion', 'django.contrib.admin', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.CallbackFilter', 'callback': lambda r: not DEBUG } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'yawf': { 'handlers': ['console'], 'level': 'WARNING', 'propagate': True, } } } YAWF_CONFIG = { 'DYNAMIC_WORKFLOW_ENABLED': True, 'MESSAGE_LOG_ENABLED': True, 'USE_SELECT_FOR_UPDATE': False, } SOUTH_TESTS_MIGRATE = False
# DAY 4- ACTIVITY 3 # Program Description: This is a simple word bank program. It takes in the user's input and turns it into a string # which will then be stored into the word bank list. After the user is done inputting his desired words, the program # will print out the elements inside the word bank list. # The list that will act as the word bank. bankList = [] continueRunning = True while continueRunning: # will use try-except method just in case something is wrong with the inputs that the user had entered. try: # the program will convert the user's input into a string. # Then, it will append the word into the bankList. print ( "\n-------------------- ENTER DETAILS --------------------" ) word = str ( input ( " Enter a word ( string ) : " ) ) print ( "-------------------------------------------------------\n" ) bankList.append( word ) print ( " {} has been stored in the word bank. \n".format( word ) ) print ( "-------------------------------------------------------\n" ) # Here, the program will ask the user if he would like to continue using the program. # If yes, the user will be able to continue adding more words into the bank list. # If not, the program will print out the elements inside the bankList. hasChosen = False while hasChosen == False: try: userChoice = str ( input ( " Would you like to try again? Y/y if Yes and N/n if No. " ) ) if userChoice.lower() == "y" or userChoice.lower() == "yes" : hasChosen = True elif userChoice.lower() == "n" or userChoice.lower() == "no" : print ( "\n-------------------------------------------------------\n" ) print ( " The word bank contains: " ) for x in bankList: print ( " - {}.".format( x ) ) print ( "\n-------------------------------------------------------\n" ) continueRunning = False hasChosen = True else: print ( " Invalid Input. " ) except: print ( " Invalid Input. " ) except: print ( " Invalid Input. " )
############################################################################### # Monitor plot arrays # ############################################################################### tag = "monitor" varpos = { 'time': 0, 'x': 1, 'y': 2, 'z': 3, 'uindex': 4, 'i': 5, 'j': 6, 'k': 7, 'head': 8, 'temp': 9, 'pres': 10, 'satn': 11, 'epot': 12, 'conc0001': 13, # 'vx': 13, # 'vy': 14, # 'vz': 15, # 'bhpr': 16, # 'kz' : 17, }
""" Description: A demo of the different forms of string Literals available. SEE: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals """ # Raw strings; These are strings that will completely ignore special characters such as \n or \t my_string = "Hello \n\tWorld" print(my_string) """Would print: Hello World""" my_string = r"Hello \n\tWorld" # Also works with R"Hello \n\tWorld" print(my_string) # Would print: Hello \n\tWorld # Byte strings; These take the string provided and build a bytes object. # SEE: https://www.python.org/dev/peps/pep-3112/ For reference about byte string literals # SEE: https://docs.python.org/3/library/stdtypes.html#bytes For referenec about byte objects my_string = "Hello" print(type(my_string)) my_string = b"Hello" print(type(my_string)) """Unicode Literals; Unicode literals are no longer necessary, but some legacy code may contain them. It creates a unicode object with the string as the argument SEE: https://docs.python.org/3/c-api/unicode.html""" my_string = "Hello" print(type(my_string)) my_string = u"Hello" print(type(my_string)) """FStrings; Format strings can be seen in more detail in string_formatting.py. But the basics are it allows you to construct strings using variables""" name = "John Doe" greeting = f"Hello, {name}" print(greeting)
def greeting_user(fname,lname): print(f"Hi {fname} {lname} !") print("How are you?") print("start") greeting_user("Lois") # we can add positional argument, this means position of the argument can shifted around # greeting_user(lname= "tracy", fname="Andrew") print("end")
# -*- coding: utf-8 -*- """ Created on Sat Aug 28 10:00:47 2021 @author: qizhe """ class Solution: def findMin(self, nums) -> int: """ 二分查找找旋转数组的最小值,关键点是允许存在重复元素。 Parameters ---------- nums : TYPE DESCRIPTION. Returns ------- int DESCRIPTION. """ pl = 0 pr = len(nums)-1 minVal = min(nums[pl],nums[pr]) # 最大值是5000 while(pl<pr - 1): # 找中间元素,大于还是小于 pm = int((pl+pr)/2) if nums[pm] < minVal: minVal = nums[pm] if nums[pl] + nums[pr] < 2 * nums[pm]: pl = int((pl+pr)/2) elif nums[pl] + nums[pr] < 2 * nums[pm]: pr = int((pl+pr)/2) else: pr -= 1 if nums[pr] < minVal: minVal = nums[pr] return minVal if __name__ == '__main__': solu = Solution() input_Str = str('hello') # input_list = input_List = [3,3,1,3] result = solu.findMin(input_List) # output_Str = 'result = ' + solu.intToRoman(input_int) output_Str = ' result = ' + str(result) print(output_Str)
DEFAULT_REGION = 'us-west-1' AMAZON_LINUX_AMI_US_WEST_2 = "ami-04534c96466647bfb" # installs and starts ngnix, nothing else USER_DATA = """ #!/bin/bash sudo amazon-linux-extras install nginx1.12 -y sudo chkconfig nginx on sudo service nginx start # to generate CPU load on start up for autoscaling debugging #cat /dev/zero > /dev/null """ SCALING_DEFAULT_TARGET_VALUE_PERCENT = 70 ASSOCIATE_PUBLIC_IP_BY_DEFAULT = True DEFAULT_COOLDOWN_SECONDS = 300 HEATHCHECK_GRACE_PERIOD_SECONDS = 120 LOGGING_STR_SIZE = 60
# !/usr/bin/env python # -*-coding:utf-8 -*- # Warning :The Hard Way Is Easier """ ================================================================================= 【模拟工作队列】 ================================================================================= """ class JobQueue: def __init__(self, limit): self.items = [] self.items_deleted = [] self.length_limit = limit def add(self, item): if len(self.items) >= self.length_limit: self.items_deleted.append(self.items.pop(0)) self.items.append(item) def pop(self): return self.items.pop(0) def isEmpty(self): return len(self.items) == 0 def length(self): return len(self.items) class Task: def __init__(self, start_time, during): self.start = start_time self.during = during class Worker: def __init__(self, n: int): self.sign = n self.current_task = None self.end_time = 0 def start_work(self, task, time): self.current_task = task self.end_time = time + self.current_task.during def isBusy(self): return self.current_task is not None def done(self, time): if time == self.end_time: self.current_task = None def __str__(self): return f"<Worker {self.sign}, isBusy:{self.isBusy()}, end_time:{self.end_time}>" # def __repr__(self): # return f"<Worker {self.sign}, isBusy:{self.isBusy()}>" def Solution(task_info: str, limit: int, worker_num: int): job_queue = JobQueue(limit) workers = [Worker(i) for i in range(worker_num)] task_info_list = [int(item.strip()) for item in task_info.split()] task_str_length = len(task_info_list) task_dict = {} for i in range(0, task_str_length, 2): start_time = task_info_list[i] spend_time = task_info_list[i + 1] task_dict[start_time] = Task(start_time, spend_time) _startTime = 0 # 终止时间: 任务列表清空,队列为空,执行者全部空闲 while True: # 优先处理执行者 for worker in workers: if worker.current_task is None and not job_queue.isEmpty(): task = job_queue.pop() worker.start_work(task) print("[执行任务]:", _startTime, worker) elif worker.current_task is not None: worker.done(_startTime) # 添加任务 if task_dict.get(_startTime): todo_task = task_dict.get(_startTime) job_queue.add(todo_task) del task_dict[_startTime] # 每次添加完任务后,还需要再次检查是否有空闲的执行者 for worker in workers: if worker.current_task is None and not job_queue.isEmpty(): task = job_queue.pop() worker.start_work(task, _startTime) print("[执行任务]:", _startTime, worker) if len(task_dict) == 0 and job_queue.isEmpty() and \ all(not worker.isBusy() for worker in workers): break _startTime += 1 print(_startTime) # print("worker", workers) return _startTime, len(job_queue.items_deleted) if __name__ == '__main__': l = "1 3 2 2 3 3" limit = 3 workers = 2 print(Solution(l, limit, workers))
class Repository(object): def __init__(self, pkgs=None): """ A Repository object stores and manages packages this way, we can use multiple package indices at once. """ if pkgs is None: pkgs = {} self.pkgs = pkgs def add(self, pkg): """ Add a single package to this Repository, if it already exists, then overwrite it. """ if pkg.name in self.pkgs: if ( pkg.version.upstream_version < self.pkgs[pkg.name].version.upstream_version ): return self.pkgs[pkg.name] = pkg def update(self, pkgs): """ Update this repository with dictionary of packages if this repository has already been populated with packages, then merge this repository with the packages. """ if pkgs: return self.merge(Repository(pkgs)) self.pkgs = pkgs return self def merge(self, other): """ Merge this repository with another repository, for now let's overwrite the packages in this repository with the packages in the other repository if they alreadu exist. """ if not other.is_empty(): for pkg in other.pkgs.values(): self.add(pkg) return self def is_empty(self): """ Return true if this repository has no packages. """ return not bool(self.pkgs) def __getitem__(self, key): return self.pkgs.get(key, None) def __contains__(self, key): return key in self.pkgs
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): if not root: return while root: if root.left: node = root.left while node.right: node = node.right node.right = root.right root.right = root.left root.left = None root = root.right
print('Irei fazer algumas perguntas!') nome = input('Digite seu nome: ') print('Olá ',nome,', é um prazer te receber!') print('Digite sua data de nascimento!') dia = input('Qual o dia? ') mes = input('Qual o mês? ') ano = input('Qual o ano? ') print(nome,', você nasceu em ',dia,' de ',mes,' de ', ano,'.') numero1 = int(input('Digite um numero: ')) numero2 = int(input('Digite outro numero: ')) soma = numero1 + numero2 print('A soma de ',numero1,' e ', numero2,' é ',soma)
#Nesting Loops in Loops outer = ['Li','Na','K'] inner = ['F', 'Cl', 'Br'] for metal in outer: for halogen in inner: print(metal + halogen)
# https://codeforces.com/contest/1327/problem/A for _ in range(int(input())): n, k = map(int, input().split()) print("YES" if n % 2 == k % 2 and n >= k * k else "NO")
__all__ = [ 'box.py', 'servers.py', 'network.py' ]
def main(): while True: text = input("Text: ") if len(text) > 0: break letter = 0 word = 1 sentence = 0 for c in text: c = c.upper() if c >= "A" and c <= "Z": letter += 1 if c == " ": word += 1 if c == "." or c == "!" or c == "?": sentence += 1 # print(f"letter: {letter} word: {word} sentence: {sentence}") index = coleman_liau_index(letter, word, sentence) if index > 16: print("Grade 16+") elif index < 1: print("Before Grade 1") else: print(f"Grade {index}") def coleman_liau_index(letter, word, sentence): return round(0.0588 * (letter * 100.0 / word) - 0.296 * (sentence * 100.0 / word) - 15.8) if __name__ == "__main__": main()
print(""" 049) refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for. """) print('-' * 18) n = int(input('Digite um número: ')) print('Tabuada do {}'.format(n)) for valor in range(1, 11): print('{} x {} = {}' .format(n, valor, n*valor )) print('-' * 18)
class ComposeScript: def __init__(self, name, deploy=None, ready_check=None, output_extraction=None, cleanup_on=None, unique_by=None): self.name = name self.deploy = deploy if deploy is not None else [] self.cleanup_on = cleanup_on self.unique_by = unique_by self.ready_check = ready_check self.output_extraction = output_extraction
BASE_62_CHAR_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def base62_to_int(part: str) -> int: """ Simple base 62 to integer computation """ t = 0 for c in part: t = t * 62 + BASE_62_CHAR_SET.index(c) return t def get_partition(url_token: str): """ Extract partition from url token. (Based on JS code) """ partition = 0 if 'A' == url_token[0]: partition = base62_to_int([url_token[1]]) else: partition = base62_to_int(url_token[1:3]) return partition
# Типы переменных # Марка name = 'Ford' # строка print(name, type(name)) # Возраст age = 3 print(age, type(age)) # Объём двигателя engine_volume = 1.6 print(engine_volume, type(engine_volume)) # Есть ли люк? see_sky = False print((see_sky, type(see_sky)))
# Name : BrowserCookie.py # Author : Harshavardhan (HK) # Time : 03/12/2020 12:45 pm # Desc: BrowserCookie holds all the methods to manipulate cookies class BrowserCookie: def __init__(self, context): self.context = context def delete_all_cookies(self): """ Delete all cookies in the scope of the session. """ try: self.context.driver.delete_all_cookies() self.context.logger.info( 'Successfully deleted all cookies of all windows.') except Exception as ex: self.context.logger.error('Unable to delete all cookies of all windows.') self.context.logger.exception(ex) raise Exception( f'Unable to delete all cookies of all windows. Error: {ex}') def delete_a_cookie(self, cookie_name: str): """ Deletes a single cookie with the given name. :param cookie_name: name of the cookie to be deleted :return: none Usage driver.delete_cookie(‘my_cookie’) """ try: self.context.driver.delete_cookie(cookie_name) self.context.logger.info( f'Successfully deleted a cookie. Cookie:{cookie_name}') except Exception as ex: self.context.logger.error('Unable to deleted a cookie. Cookie:{cookie_name}') self.context.logger.exception(ex) raise Exception( f'Unable to deleted a cookie. Cookie:{cookie_name} Error: {ex}') def add_a_cookie(self, cookie_dict: dict): """ Adds a cookie to your current session. :param cookie_dict: A dictionary object, with required keys - “name” and “value”; optional keys - “path”, “domain”, “secure”, “expiry” :return: none Usage: driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’}) driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’}) driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’, ‘secure’:True}) """ try: self.context.driver.add_cookie(cookie_dict) self.context.logger.info( f'Successfully added a cookie {cookie_dict["name"]}:{cookie_dict["value"]}.') except Exception as ex: self.context.logger.error(f'Unable to add a cookie {cookie_dict["name"]}:{cookie_dict["value"]}.') self.context.logger.exception(ex) raise Exception( f'Unable to deleted a cookie{cookie_dict["name"]}:{cookie_dict["value"]}. Error: {ex}') def get_a_cookie(self, name: str): """ Get a single cookie by name. Returns the cookie if found, None if not. :param name: :return: cookie if found, None if not Usage: driver.get_a_cookie(‘my_cookie’) """ try: cookie = self.context.driver.get_cookie(name) self.context.logger.info( f'Successfully retrieved a cookie {name}.') return cookie except Exception as ex: self.context.logger.error(f'Unable to retrieve a cookie {name}.') self.context.logger.exception(ex) raise Exception( f'Unable to retrieve a cookie {name}. Error: {ex}') def get_all_cookies(self)->dict: """ Returns a set of dictionaries, corresponding to cookies visible in the current session. :return: set of dictionaries Usage: driver.get_all_cookie() """ try: cookies = self.context.driver.get_cookies() self.context.logger.info( f'Successfully retrieved all the cookies.') self.context.logger.info(cookies) return cookies except Exception as ex: self.context.logger.error(f'Unable to retrieve all the cookies.') self.context.logger.exception(ex) raise Exception( f'Unable to retrieve all cookies. Error: {ex}')
class EmptyChildProxy: """ Bad because does not extends dalec.proxy.Proxy """ app = "empty_child" def _fetch(self, *args, **kwargs): print("Are you my mummy?")
class Luhn: """ Given a number determine whether or not it is valid per the Luhn formula. """ def __init__(self, card_num: str): self.card_num = card_num.replace(' ', '') self.__card_num_list = \ [int(char) for char in self.card_num if char.isdigit()] self.__digits_processor() # Declaring private method def __digits_processor(self): """ The first step of the Luhn algorithm is to double every second digit, starting from the right. If doubling the number results in a number greater than 9 then subtract 9 from the product. :return: """ for i in range(len(self.__card_num_list) - 2, -1, -2): self.__card_num_list[i] = self.__card_num_list[i] * 2 if self.__card_num_list[i] > 9: self.__card_num_list[i] = self.__card_num_list[i] - 9 def valid(self) -> bool: """ Sum all of the digits. If the sum is evenly divisible by 10, then the number is valid. :return: """ for char in self.card_num: if not char.isdigit(): return False if len(self.card_num) < 2: return False return sum(self.__card_num_list) % 10 == 0
while True: try: S = input() count = 0 for k in input(): if k in S: count += 1 print(count) except: break
# def main(): # x, y, z = (int(x) for x in input().strip().split()) # result = 0 # if 1 <= x <= 31 and 1 <= y <= 12: # result += 1 # if 1 <= y <= 31 and 1 <= x <= 12: # result += 1 # print(result % 2) # # # main() def main(): a, b, c = map(int, input().split()) if a == b: print(1) elif b <= 12 and a <= 12: print(0) else: print(1) main()
buy_schema = { 'items': [ { 'itemKey': { 'inventoryType': 'CHAMPION', 'itemId': -1 }, 'purchaseCurrencyInfo': { 'currencyType': 'IP', 'price': -1, 'purchasable': True }, 'quantity': 1, 'source': 'cdp' } ] }
#class Solution(object): # def isNumber(self, s): # """ # :type s: str # :rtype: bool # """ # if s == '': return False # if s.strip() == '.': return False # # define the Deterministic Finite Automata # dfa = [ # DFA init: q0, valid: q2,q4,q7,q8 # {'blank':0, 'sign':1, 'digit':2, 'dot':3}, # q0 # {'digit':2, 'dot':3}, # q1 # {'digit':2, 'dot':3, 'e':5, 'blank':8}, # q2 # {'digit':4, 'e':5, 'blank':8}, # q3 # {'digit':4, 'e':5, 'blank':8}, # q4 # {'digit':7, 'sign':6}, # q5 # {'digit':7}, # q6 # {'blank':8, 'digit':7}, # q7 # {'blank':8}, # q8 # ] # state = 0 # # run the automata # for char in s: # #print(' * cursor char ', char, 'state', state) # # determine the type # if char.isnumeric(): # char_t = 'digit' # elif char == '.': # char_t = 'dot' # elif char.isspace(): # char_t = 'blank' # elif char == '+' or char == '-': # char_t = 'sign' # elif char == 'e': # char_t = 'e' # else: # return False # #print(' * cursor char is', char_t) # # is the type valid at current state? # if char_t not in dfa[state].keys(): # #print(' * invalid convertion') # return False # # go to next state # state = dfa[state][char_t] # #print(' * goto', state) # # is the final state of automata valid? # if state not in [2,3,4,7,8]: # return False # return True # Wrong answer class Solution(object): def isNumber(self, s): """ :type s: str :rtype: bool """ #define a DFA state = [{}, {'blank': 1, 'sign': 2, 'digit':3, '.':4}, {'digit':3, '.':4}, {'digit':3, '.':5, 'e':6, 'blank':9}, {'digit':5}, {'digit':5, 'e':6, 'blank':9}, {'sign':7, 'digit':8}, {'digit':8}, {'digit':8, 'blank':9}, {'blank':9}] currentState = 1 for c in s: if c >= '0' and c <= '9': c = 'digit' if c == ' ': c = 'blank' if c in ['+', '-']: c = 'sign' if c not in state[currentState].keys(): return False currentState = state[currentState][c] if currentState not in [3,5,8,9]: return False return True if __name__ == '__main__': s = Solution() tests = [ ('', False), ('3', True), ('-3', True), ('3.0', True), ('3.', True), ('3e1', True), ('3.0e1', True), ('3e+1', True), ('3e', False), ('+3.0e-1', True), ] for pair in tests: print(s.isNumber(pair[0]), pair[1])
# -*- coding: UTF-8 -*- URL = 'http://booking.bettersoftware.it/conference/getinfo.py/empty_attendees' SUBJECT = "[Better Software 2009] dati mancanti per il tuo badge di ingresso" BODY = u"""Ciao, questa mail è inviata automaticamente dal nostro gestionale a tutti gli utenti che hanno acquistato un biglietto per Better Software 2009. Ci risulta che uno o più biglietti associati al tuo account "%(username)s" non sono stati ancora compilati con i dati personali del partecipante. E' molto importante che compili il biglietto oggi inserendo il nome e cognome della persona che parteciperà e i giorni di presenza in conferenza. Puoi farlo entrando direttamente sul gestionale della conferenza usando il tuo username "%(username)s": http://www.bettersoftware.it/2009/booking/ e andando nella sezione acquisti cliccate sul biglietto ancora da compilare. Grazie! Better Software team """ SERVER = 'trinity.trilan' REPLYTO = 'info@bettersoftware.it' FROM = 'francesco@bettersoftware.it'
''' Функция get_sum() определена следующим образом: def get_sum(x, y, z): return x + y + z print('Сумма равна', x + y + z) Что будет выведено в результате выполнения следующего программного кода? print(get_sum(1, 2, 3)) ''' def get_sum(x, y, z): return x + y + z print('Сумма равна', x + y + z) # не выведется, т.к. return прерывает выполнение функции print(get_sum(1, 2, 3))
#!/usr/bin/python3 # 文件名:class.py class MyClass: """一个简单类实例""" i = 12345 def f(self): return 'hello world' # 实例化类 x = MyClass() # 访问类属性、方法 print("MyClass 类属性i为:",x.i) print("MyClass 类方法f输出为:",x.f())
class Tabs: MEMBERS = "Members" SITES = "Sites" ROLES = "Roles" DETAILS = "Details" class Details: NAME = "Name" EORI_NUMBER = "EORI number" SIC_NUMBER = "SIC code" VAT_NUMBER = "VAT number" REGISTRATION_NUMBER = "Registration number" CREATED_AT = "Created at" PRIMARY_SITE = "Primary site" TYPE = "Type"
def scope_test(): def do_local(): spam = 'local spam' def do_nonLocal(): nonlocal spam spam = 'non local spam' def do_global(): global spam spam = 'global spam' spam = 'test spam' do_local() print('after local assignment: ', spam) do_nonLocal() print('after non-local assignment: ', spam) do_global() print('after global assignment: ', spam) scope_test() print('in global scope: ', spam)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ SER-347 - João Felipe lista-03 Exercício 05. Faça um programa em Python que pergunte ao usuário qual a série que ele deseja calcular e em seguida imprima o nome da série escolhida. """ # Definindo as series numero = list(range(0, 5, 1)) nomes = ['Lucas', 'Pell', 'Triangular', 'Square', 'Pentagonal'] # Informando as series disponíveis ao usuário print('Veja as séries abaixo:\n0 Lucas\n1 Pell\n2 Triangular\n3 Square\n4 Pentagonal') x = int(input('Digite o número correspondente à série você deseja computar: ')) if x not in numero: print(f'{x} não está na lista de series.') else: serie = nomes[x] print(f"Você escolheu computar a série '{serie}'!") # END
#!/usr/bin/env python # -*- coding: utf-8 -*- class InvalidTokenTypeError(Exception): pass class InvalidNodeTypeError(Exception): pass class InvalidTargetNodeTypeError(Exception): pass
a,b,c = input().split() a,b,c = [float(a),float(b),float(c)] if a+b <= c or b+c <= a or c+a <= b: print("NAO FORMA TRIANGULO") else: if a*a == b*b+c*c or b*b == a*a+c*c or c*c == b*b+a*a: print("TRIANGULO RETANGULO") elif a*a > b*b+c*c or b*b > a*a+c*c or c*c > b*b+a*a: print("TRIANGULO OBTUSANGULO") else: print("TRIANGULO ACUTANGULO") if a == b == c: print("TRIANGULO EQUILATERO") elif a == b != c or a == c != b or c == b != a: print("TRIANGULO ISOSCELES")
""" @author: magician @date: 2019/12/13 @file: exception_demo.py """ def divide(a, b): """ divide :param a: :param b: :return: """ try: return a / b except ZeroDivisionError: return None def divide1(a, b): """ divide1 :param a: :param b: :return: """ try: return True, a / b except ZeroDivisionError: return False, None def divide2(a, b): """ divide2 :param a: :param b: :return: """ try: return a / b except ZeroDivisionError as e: raise ValueError('Invalid inputs') from e if __name__ == '__main__': x, y = 0, 5 result = divide(x, y) if not result: print('Invalid inputs') success, result = divide1(x, y) if not success: print('Invalid inputs') _, result = divide1(x, y) if not result: print('Invalid inputs') x, y = 5, 2 try: result = divide(x, y) except ValueError: print('Invalid inputs') else: print('Result is %.1f' % result)
def print_without_vowels(s): ''' s: the string to convert Finds a version of s without vowels and whose characters appear in the same order they appear in s. Prints this version of s. Does not return anything ''' # Your code here newString = "" for item in s: if item not in "aeiouAEIOU": newString += item print(newString) # print(print_without_vowels("a")) print_without_vowels("a")
expected_1 = ({ '__feature_4': [ 42., 67., 6., 92., 80., 10., 90., 5., 100., 40., 23., 44., 81., 53., 37., 7., 79., 45., 87.], '__feature_2': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., 4., 83., 70., 33.], '__feature_3': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29., 94., 66., 84., 55., 12., 43., 1., 16.], '__feature_0': [ 63., 89., 49., 24., 41., 48., 58., 47., 61., 14., 59., 96., 88., 65., 19., 74., 97., 50., 57.], '__feature_1': [ 27., 52., 18., 76., 60., 62., 30., 8., 86., 78., 31., 39., 93., 2., 28., 46., 85., 3., 73.]}, 19) expected_2 = ({ 'cuatro': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29., 94., 66., 84., 55., 12., 43., 1., 16.], 'dos': [ 27., 52., 18., 76., 60., 62., 30., 8., 86., 78., 31., 39., 93., 2., 28., 46., 85., 3., 73.], 'tres': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., 4., 83., 70., 33.], 'cinco': [ 42., 67., 6., 92., 80., 10., 90., 5., 100., 40., 23., 44., 81., 53., 37., 7., 79., 45., 87.], 'uno': [ 63., 89., 49., 24., 41., 48., 58., 47., 61., 14., 59., 96., 88., 65., 19., 74., 97., 50., 57.]}, 19) expected_3 = ({ 'cuatro': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29., 94., 66., 84., 55., 12., 43., 1., 16.], 'tres': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., 4., 83., 70., 33.]}, 19) expected_single_row = { 'single': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., 4., 83., 70., 33.]}
""" Physical and mathematical constants and conversion functions. """ __all__ = 'deg rad eV meV keV nanometer angstrom micrometer millimeter ' \ 'meter nm mm energy2wavelength wavelength2energy rad2deg deg2rad'.split() deg: float = 1. rad: float = 3.1415926535897932 / 180 # Energy eV: float = 1. meV: float = 1.e-3 keV: float = 1.e3 # Lengths nanometer: float = 1. nm: float = nanometer angstrom: float = 1.e-1 * nm micrometer: float = 1.e+3 * nm millimeter: float = 1.e+6 * nm meter: float = 1.e+9 * nm mm: float = millimeter # Conversions def energy2wavelength(energy: float): return 1239.84193 / energy def wavelength2energy(wavelength: float): return 1239.84193 / wavelength def rad2deg(radian: float): return radian / rad def deg2rad(degree: float): return degree * rad
""" Class hierarchy for types of people in college campus """ class College: def __init__(self, college): self.college = college def __str__(self): return f"College: {self.college}" class Department(College): def __init__(self, college, department, **kwargs): self.department = department super().__init__(college, **kwargs) def __str__(self): return f"Department of {self.department}" def current_department(self): return f"Department of {self.department}" class Professor(Department): def __init__(self, college, department, name, age, **kwargs): super().__init__(college, department) self.name = name self.age = age def __str__(self): return f"{self.name} in {self.department} department" def age(self): return f"{self.age}" class Student(Department): def __init__(self, college, department, student_name, student_age, **kwargs): super().__init__(college, department) self.student_name = student_name self.student_age = student_age def __str__(self): return f"{self.student_name} from {super().current_department()}" def main(): professor = Professor('Rice University', 'Arts', 'Ana Mathew', 36) print(professor) print(professor.current_department()) student = ('Rice University', 'Computer Science', 'Jane Doe', 22) print(student) if __name__ == '__main__': main()
def choise_sort(seq): """Функция производит сортировку методом вставки""" for pos in range(0, len(seq)-1): for i in range(pos+1, len(seq)): if seq[i] < seq[pos]: seq[i], seq[pos] = seq[pos], seq[i] return seq ################################################################ def find_smallest(seq): """Функция находит минимум в последовательности""" smallest = seq[0] smallest_index = 0 for i, v in enumerate(seq): if v < smallest: smallest = v smallest_index = i return smallest_index def selection_sort(seq): """Функция производит сортировку методом вставки""" res = [] for i in range(len(seq)): smallest = find_smallest(seq) res.append(seq.pop(smallest)) return res
# inteiros idade = 22 ano = 2021 # reais altura = 1.63 saldo = 10.50 # palavras (strings) nome = 'Luisa' sobrenome = 'Moura'
def example_filter1(string): return "Example1: " + string def get_template_filter(): return example_filter1 def returns_string_passed(string): return string def title_string(string): return string.title()
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class BotFrameworkSkill: """ Registration for a BotFrameworkHttpProtocol based Skill endpoint. """ # pylint: disable=invalid-name def __init__(self, id: str = None, app_id: str = None, skill_endpoint: str = None): self.id = id self.app_id = app_id self.skill_endpoint = skill_endpoint
#Programming Part variables #kinect_add = "./x64/Release/AzureKinectDK.exe" kinect_add = "C:/Users/User/Desktop/EVCIDNet-master/x64/Release/AzureKinectDK.exe" result_add = "./AzureKinectDK/output/result.txt" flag1_add = "./AzureKinectDK/output/flag1.txt" #image capture start flag flag2_add = "./AzureKinectDK/output/flag2.txt" #image capture finish flag flag3_add = "./AzureKinectDK/output/flag3.txt" #camera turn off and program terminate flag flag = [flag1_add, flag2_add, flag3_add] color_addr = "./AzureKinectDK/output/color.png" point_addr = "./AzureKinectDK/output/point.png" json_addr = "./AzureKinectDK/output/demo.json" json_dict = {"licenses": [{"name": "", "id": 0, "url": ""}], "info": {"contributor": "", "date_created": "", "description": "", "url": "", "version": "", "year": ""}, "categories": [{"id": 1, "name": "HolePairLeft", "supercategory": ""}, {"id": 2, "name": "HolePairRight", "supercategory": ""}, {"id": 3, "name": "ACHole", "supercategory": ""}], "images": [], "annotations": []} Error_coordinate = [[77777 for i in range(3)] for i in range(3)] #Communication Part variables regiaddrX1 = 8 regiaddrY1 = 9 regiaddrZ1 = 10 regiaddrX2 = 11 regiaddrY2 = 12 regiaddrZ2 = 13 regiaddrX3 = 14 regiaddrY3 = 15 regiaddrZ3 = 18 regiaddrC = 19 regiaddr = [regiaddrX1,regiaddrY1,regiaddrZ1,regiaddrX2,regiaddrY2,regiaddrZ2,regiaddrX3,regiaddrY3,regiaddrZ3,regiaddrC] robot_addr = "192.168.137.100" port_num = 502 offset = 32768 #int 16 max range flag1_signal = 1 flag3_signal = 0 #confirm_signal = "C" #terminate_signal = "D"
film = input('Введите название фильма: ') name = input('Введите название кинотеатра: ') time = input('Введите, во сколько начнётся фильм: ') yay = lambda film, name, time: 'Билет на " ' + film + ' " в "' + name + '" на' + time + 'забронирован' print(yay(film, name, time))
#!/usr/bin/env python ########################################################################################## ########################################################################################## ########################################################################################## # IF YOU ARE DOING THE NEW STARTER TRAINING # # DO NOT COPY THIS CODE, DO NOT "TAKE INSPIRATION FROM THIS CODE" # # YOU SHOULD WRITE YOUR OWN CODE AND DEVELOP YOUR OWN ALGORITHM FOR THE CONVERTERS ########################################################################################## ########################################################################################## ########################################################################################## def to_arabic_number(roman_numeral: str) -> int: src_roman_numeral = roman_numeral # print(f"convert to_arabic_number {roman_numeral} into arabic number") arabic_number = 0 numerals = { "M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1 } # print(f"1) Check numerals in order of size {numerals}") for numeral in numerals: numeral_value = numerals[numeral] # print(f" 2) Check for repeated {numeral} ({numeral_value})") while roman_numeral.startswith(numeral): # print(f" 3) When found {numeral}, add {numeral_value}, remove {numeral} from current str {roman_numeral}") arabic_number += numeral_value roman_numeral = roman_numeral[len(numeral):] # print(f" 4) Current arabic number is {arabic_number}, numeral left to parse is {roman_numeral}") # print(f"to_arabic_number({src_roman_numeral}) is {arabic_number}") return arabic_number def to_roman_numeral(arabic_number: int) -> str: src_arabic_number = arabic_number # print(f"convert to_roman_numeral {arabic_number} into roman numeral") roman_numeral = "" numerals = { "M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1 } # print(f"1) Check numerals in order of size {numerals}") for numeral in numerals: numeral_value = numerals[numeral] # print(f" 2) Check for repeated {numeral} ({numeral_value})") while arabic_number >= numeral_value: # print(f" 3) When found {numeral}, remove {numeral_value}, add {numeral} to {roman_numeral} from current number {arabic_number}") roman_numeral += numeral arabic_number -= numeral_value # print(f" 4) Current numeral is {roman_numeral}, arabic number left to parse is {arabic_number}") # print(f"to_roman_numeral({src_arabic_number}) is {roman_numeral}") return roman_numeral # # print("""generating pseudo code for training # ===================== # # """) # # print(""" # Roman to Arabic Pseudo Code # =====================================""") # output = to_arabic_number('MCDIV') # print(output) # # print(""" # Arabic to Roman Pseudo Code # =====================================""") # output = to_roman_numeral(2456) # # print(output)
#!/usr/bin/env python # -*- coding: utf-8 -*- '''conftest.py for cpac. Read more about conftest.py under: https://pytest.org/latest/plugins.html ''' # import pytest def pytest_addoption(parser): parser.addoption('--platform', action='store', nargs=1, default=[]) parser.addoption('--tag', action='store', nargs=1, default=[]) def pytest_generate_tests(metafunc): # This is called for every test. Only get/set command line arguments # if the argument is specified in the list of test 'fixturenames'. platform = metafunc.config.option.platform tag = metafunc.config.option.tag if 'platform' in metafunc.fixturenames: metafunc.parametrize('platform', platform) if 'tag' in metafunc.fixturenames: metafunc.parametrize('tag', tag)
# last data structure # Sets are unorded collection of unique objects my_set = {1, 2, 4, 4, 5, 5, 5, 4, 3, 3} print(my_set) # useful methods new_set = my_set.copy() print(new_set) my_set.add(100) print(my_set)
text = "PER" s = input() n = 0 d = 0 for i in s: if n > 2: n = 0 if i != text[n]: d += 1 n += 1 print(d)
nome = str(input('Digite o seu nome: ')) cores = {'branco':'\033[30m', 'vermelho':'\033[31m', 'verde':'\033[32m', 'amarelo':'\033[33m', 'azul':'\033[34m', 'roxo':'\033[35m', 'ciano':'\033[36m', 'cinza':'\033[37m', 'limpa':'\033[m'} if nome == 'Gabriel': print(cores['verde'], 'Que nome bonito!', cores['limpa']) elif nome == 'Leonardo' or nome == 'matheus' or nome == 'Camila': print(cores['ciano'], 'Seu nome é muito popular no Brasil!', cores['limpa']) else: print(cores['vermelho'], 'Seu nome é bem normal.', cores['limpa']) print(cores['roxo'], 'Tenha um bom dia, {}{}!'.format(nome, cores['limpa']))
def sum_list(lst): my_list = lst if len(my_list) == 1: return my_list[0] return my_list[0] + sum_list(my_list[1:]) lst = [1,2,3,4] print(sum_list(lst))
# path to folder with data BASEPATH = '/home/michal/Develop/oshiftdata/' # name of the Elasticsearch index INDEX_NAME = 'pagesbtext' # type of the Elasticsearch index INDEX_TYPE = 'page' # host address of MongoDB MONGODB_HOST = "127.0.1.1" # port of MongoDB MONGODB_PORT = 27017 # name of MongoDB database MONGODB_DB = "skool" # name of collection, where bodytexts are saved MONGODB_COLLECTION = "page" # username for accessing database MONGODB_USER = None # password for accessing database MONGODB_PASS = None # ELASTIC_HOST # ELASTIC_PORT # url on which classification server will listen URL = "localhost" # port on which classification server will listen PORT = 8001 # connection string to classification server CSTRING = "http://localhost:8001" # filenames of files with serialized model DEFAULT_FILENAMES = { 'CountVectorizer': 'cv', 'TfIdf': 'tfidf', 'Classifier': 'cls', 'MultiLabelBinarizer': 'mlb' }
""" 8.12 – Sanduíches: Escreva uma função que aceite uma lista de itens que uma pessoa quer em um sanduíche. A função deve ter um parâmetro que agrupe tantos itens quantos forem fornecidos pela chamada da função e deve apresentar um resumo do sanduíche pedido. Chame a função três vezes usando um número diferente de argumentos a cada vez. """ def items_sandwich(*items): if items: print('\nItens pedidos para o sanduíche: ') for item in items: print(item.capitalize()) else: print('\nNenhum item foi pedido para o sanduíche') items_sandwich('Queijo', 'Tomate', 'Bacon') items_sandwich('alface', 'batata') items_sandwich()
num1 = int(input("Please input your num1:")) num2 = int(input("Please input your num2:")) s = num1 + num2 print(s)
class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ res = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: if i == 0: res += 1 if i == len(grid) - 1: res += 1 if i > 0 and grid[i - 1][j] == 0: res += 1 if i < len(grid) - 1 and grid[i + 1][j] == 0: res += 1 if j == 0: res += 1 if j == len(grid[i]) - 1: res += 1 if j > 0 and grid[i][j - 1] == 0: res += 1 if j < len(grid[i]) - 1 and grid[i][j + 1] == 0: res += 1 return res def test_island_perimeter(): assert 16 == Solution().islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]]) assert 4 == Solution().islandPerimeter([[1]]) assert 4 == Solution().islandPerimeter([[1, 0]])
class Solution: def uniquePaths(self, m: int, n: int) -> int: if m <= 0 or n <= 0: raise Exception("Invalid Matrix Size") dp = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if i == 0 and j == 0: dp[i][j] = 1 elif i == 0 and j != 0: dp[i][j] = dp[i][j - 1] elif i != 0 and j == 0: dp[i][j] = dp[i - 1][j] else: dp[i][j] = dp[i][j - 1] + dp[i - 1][j] return dp[-1][-1]
# -*- coding: utf-8 -*- """ crie um programa que tenha uma tupla com várias palavras( não usar acentos). Depois disso. você deve mostrar, para cada palavra, quais são as suas vogais. """ palavras = ('dicionario', 'abobado', 'putrefato', 'pai') print(len(palavras)) print(len(palavras[0])) i = j = 0 for i in range(0 , len(palavras)): # percorre os elementos da tupla print(f'na palavra {palavras[i]} temos as vogais:') for j in range(0, len(palavras[i])): #percorre as letras do elemento letra = palavras[i][j] if letra in 'aeiou': print(palavras[i][j], end=' - ') print('\n')
honored_guest = ['YULIU', 'Jim', 'Shi'] print(honored_guest[0] + ' and ' + honored_guest[1] + ' and ' + honored_guest[2] + ' ' + "eat dinner") print("Shi cannot come here to eat dinner") honored_guest.sort() print(honored_guest) honored_guest.remove('Shi') print(honored_guest)
n=[5,6,7] # Atomic valences nc=[5,6,7] # Atomic valences l=2 # Orbital angular momentum of the shel J=0.79 # Slatter integrals F2=J*11.9219653179191 from the atomic physics program, must check this for Fe as I just used Haule's value for Mn here cx=0.0 # 0.052 # spin-orbit coupling from the atomic physics program qOCA=1 # OCA diagrams are computes in addition to NCA diagrams Eoca=1. # If the atomi energy of any state, involved in the diagram, is higher that Eoca from the ground state, the diagram ms is neglected mOCA=1e-3 # If maxtrix element of OCA diagram is smaller, it is neglected Ncentral=[6] # OCA diagrams are selected such that central occupancy is in Ncentral Ex=[0.5,0.5,0.5] # Energy window treated exactly - relevant only in magnetic state Ep=[3.0,3.0,3.0] # Energy window treated approximately qatom=0
count_sum_1 = 0 count_sum_2 = 0 with open('input', 'r') as f: groups = f.read().split('\n\n') # Part One for group in groups: yes_set = set(group.strip()) if '\n' in yes_set: yes_set.remove('\n') yes_count = len(yes_set) # print(f'yes_count = {yes_count}, yes_set = {yes_set}') count_sum_1 += yes_count print(f'count_sum_1 = {count_sum_1}') # Part Two for group in groups: group = group.strip().split('\n') ques_set = set(group[0]) if len(group) == 1: ques_count = len(ques_set) else: for g in group: ques_set = ques_set.intersection(set(g)) ques_count = len(ques_set) # print(f'ques_count = {ques_count}, ques_set = {ques_set}') count_sum_2 += ques_count print(f'count_sum_2 = {count_sum_2}')