content
stringlengths
7
1.05M
# python3.5/win10 # -*- coding:utf-8 -*- ''' 元音字母 有:a,e,i,o,u五个, 写一个函数,交换字符串的元音字符位置。 假设,一个字符串中只有二个不同的元音字符。 二个测试用例: 输入 apple 输出 eppla 输入machin 输出 michan 不符合要求的字符串,输出None,比如: 输入 abca (两个元音相同) 输出 None 输入 abicod (有三个元音) 输入None ''' ''' 分析题目: 1.字符串有3个以上元音就None 2.字符串有2个相同元音就None 3.字符串没有元音输出None 4.元音数为2且是不同的元音才交换 ''' def interchange(str): vowels = ['a','e','i','o','u'] first_position = 0 second_position = 0 vowel_num = 0 for position in range(len(str)): if str[position] in vowels: vowel_num += 1 if vowel_num == 3: str = "None" elif vowel_num == 1: first_vowel = str[position] first_position = position elif vowel_num == 2: if str[position] == first_vowel: str = "None" else: second_position = position if vowel_num == 2: str = str[:first_position] + str[second_position] + str[first_position+1:second_position] + str[first_position] + str[second_position+1:] else: str = "None" print(str) if __name__ == '__main__': str = '' while str != '0': str = input("输入英文字符串(退出输入0):") interchange(str.lower())
##rotational constant in ground state in wavenumbers B_dict = {'O2': 1.4297, 'N2': 1.99, 'N2O': 0.4190, 'CO2': 0.3902, 'D2': 30.442, 'OCS': .2039} ##Centrifugal Distortion in ground state in wavenumbers D_dict = {'O2': 4.839e-6, 'N2': 5.7e-6, 'N2O': 0.176e-6, 'CO2': 0.135e-6, 'D2': 0, 'OCS': 0} ##anisotropy of the polarizability in m^3 - but cgs units d_alpha_dict = {'O2': 1.1e-30, 'N2': 0.93e-30, 'N2O': 2.8e-30, 'CO2': 2.109e-30, 'D2': .282e-30, 'OCS': 4.1e-30} ## Jmax for various molecules and laser < 10**13 W cm**-2 Jmax_dict = {'O2': 20, 'N2': 20, 'N2O': 60, 'CO2': 60, 'D2': 35, 'OCS': 70}
with open("haiku.txt", "a") as file: file.write("APPENDING LATER!") with open("haiku.txt") as file: data = file.read() print(data) with open("haiku.txt", "r+") as file: file.write("\nADDED USING r+") file.seek(20) file.write(":)") data = file.read() print(data)
GOOD_MORNING="Good Morning, %s" GOOD_AFTERNOON="Good Afternoon, %s" GOOD_EVENING="Good Evening, %s" DEFAULT_MESSAGE="Hello, World! %s" MESSAGE_REFRESH_RATE = 3600000 # 1 hour MESSAGE_TEXT_SIZE = 70
#!/usr/bin/env python # -*- coding=utf-8 -*- count = 0 while(count < 9): print('the index is :', count) count += 1 """输出结果 the index is : 0 the index is : 1 the index is : 2 the index is : 3 the index is : 4 the index is : 5 the index is : 6 the index is : 7 the index is : 8 """
# This is created from Notebook++ print("Hello, I am SKL") print("Welcome to my learning space")
#Reading lines from file and putting in a list contents = [] for line in open('rosalind_ini5.txt', 'r').readlines(): contents.append(line.strip('\n')) #Printing the even numbered lines, starting by one for i in range(1, len(contents), 2): print(contents[i])
class BaseUrlNotDefined(Exception): pass class InvalidCurrencyCode(Exception): pass class InvalidDate(Exception): pass class InvalidAmount(Exception): pass class APICallError(Exception): pass class HelperNotDefined(Exception): pass
## Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.## c = float(input('Informe a temperatura em C:')) f = 9 * c / 5 +32 print('A temperatura em {}C corresponde a {}F!'.format(c,f))
# Copyright (c) 2018, EPFL/Human Brain Project PCO # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Pagination(object): def __init__(self, start_from: int = 0, size: int = 50): self.start_from = start_from self.size = size class Stage(str): IN_PROGRESS = "IN_PROGRESS" RELEASED = "RELEASED" class ResponseConfiguration(object): def __init__(self, return_payload=True, return_permissions=False, return_alternatives=False, return_embedded=False, return_incoming_links=False, sort_by_label=False): self.return_payload = return_payload self.return_permissions = return_permissions self.return_alternatives = return_alternatives self.return_embedded = return_embedded self.return_incoming_links = return_incoming_links self.sort_by_label = sort_by_label class KGResult(object): def __init__(self, json: dict, request_args: dict, payload): self.payload = json self.request_args = request_args self.request_payload = payload def data(self): return self.payload["data"] if "data" in self.payload else None def message(self): return self.payload["message"] if "message" in self.payload else None def start_time(self): return self.payload["startTime"] if "startTime" in self.payload else None def duration_in_ms(self): return self.payload["durationInMs"] if "durationInMs" in self.payload else None def total(self): return self.payload["total"] if "total" in self.payload else 0 def size(self): return self.payload["size"] if "size" in self.payload else 0 def start_from(self): return self.payload["from"] if "from" in self.payload else 0
#Άσκηση 6.2: Έλεγχος αρχείου εικόνας checkType = [] try : with open('imag', 'rb') as binfile: data = binfile.read() bdata = bytearray(data) for i in range(3): print(i+1, 'byte||', 'hexadecimal:', hex(bdata[i]), 'decimal:', int(str(hex(bdata[i])), 16) ) checkType.append(int(str(hex(bdata[i])),16)) if (checkType[0] == 255 and checkType[1] == 216 and checkType[2] == 255) : print('Το αρχείο ΔΕΝ ειναι τύπου .jpg') except FileNotFoundError : print('Σφάλμα: Δεν υπάρχει το αρχείο σε αυτή τη θέση')
def iguais (l1,l2): same=0 for i in range (len(l1)): if l1[i]==l2[i]: same += 1 return same testea=[1,5,6,3,2,4,8,9,6,5,3,7,5,6,4,8,3,2,5,6,4,5,4,8,9,9] testeb=[5,4,6,9,8,7,5,5,3,2,1,4,6,5,7,8,9,6,3,2,1,4,5,6,9,8] print(iguais(testea,testeb))
# Conversor de temperaturas c = float(input('Digite um valor em °C :')) f = 9 * c / 5 + 32 print('A temperatura em {}ºC corresponde a {}ºF'.format(c, f))
# coding:utf-8 note = ["螽斯羽,诜诜兮。宜尔子孙,振振兮", "天接云涛连晓雾,星河欲转千帆舞", "噫吁戏,危乎高哉", "人成各,今非昨,病魂常似秋千索", "枯藤老树昏鸦,小桥流水人家", "山一程,水一程,身向榆关那畔行。故园无此声", "说什么黄泉无店宿忠魂,争道这青山有幸埋芳洁" ] class NoteModel: def get_note(self, n): try: v = note[n] except IndexError: v = "没有找到" return v class View: def show(self, n): print(f"句子是:{n}") def error(self, msg): print(f"Error:{msg}") def select(self): return input("请输入索引:") class Controller: def __init__(self): self.model = NoteModel() self.view = View() def run(self): tag = False while not tag: try: n = self.view.select() n = int(n) tag = True except ValueError: self.view.error("错误的索引") user_note = self.model.get_note(n) self.view.show(user_note) if __name__ == '__main__': c = Controller() while 1: c.run()
name = 'TaskKit' version = ('X', 'Y', 0) docs = [ {'name': "Quick Start", 'file': 'QuickStart.html'}, {'name': "User's Guide", 'file': 'UsersGuide.html'}, {'name': 'To Do', 'file': 'TODO.text'}, ] status = 'stable' requiredPyVersion = (2, 6, 0) synopsis = """TaskKit provides a framework for the scheduling and management of tasks which can be triggered periodically or at specific times."""
#!/usr/bin/env python3 a = int(input()) b = int(input()) if a // 2 == b or (3 * a) + 1 == b: print("yes") else: print("no")
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class DeviceTreePartitionSlice(object): """Implementation of the 'DeviceTree_PartitionSlice' model. TODO: type model description here. Attributes: disk_file_name (string): The disk to use. length (long|int): The length of data for the LVM volume (for which this device tree is being built) in bytes. It does not include size of the LVM meta data. lvm_data_offset (long|int): Each LVM partition starts with LVM meta data. After the meta data there can be data for one or more LVM volumes. This field indicates the offset in bytes (relative to partition) where data for various LVM volumes starts on the partition. NOTE: If this device tree represents first LVM volume on the partition, 'lvm_data_offset' is equal to 'offset'. offset (long|int): This is the offset (in bytes) where data for the LVM volume (for which this device tree is being build) starts relative to the start of the partition above. partition_number (int): The partition to use in the disk above. """ # Create a mapping from Model property names to API property names _names = { "disk_file_name":'diskFileName', "length":'length', "lvm_data_offset":'lvmDataOffset', "offset":'offset', "partition_number":'partitionNumber' } def __init__(self, disk_file_name=None, length=None, lvm_data_offset=None, offset=None, partition_number=None): """Constructor for the DeviceTreePartitionSlice class""" # Initialize members of the class self.disk_file_name = disk_file_name self.length = length self.lvm_data_offset = lvm_data_offset self.offset = offset self.partition_number = partition_number @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary disk_file_name = dictionary.get('diskFileName') length = dictionary.get('length') lvm_data_offset = dictionary.get('lvmDataOffset') offset = dictionary.get('offset') partition_number = dictionary.get('partitionNumber') # Return an object of this model return cls(disk_file_name, length, lvm_data_offset, offset, partition_number)
class Cell(): def __init__(self): self.touched = False self.has_mine = False self.marked = False self.value = 0 def _place_mine(self): self.has_mine = True def touch(self): if not self.marked: self.touched = True return self.has_mine def mark_as_safe(self): if not self.touched: self.marked = True def unmark(self): if self.marked: self.marked = False
# # PySNMP MIB module RUCKUS-VF2825-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RUCKUS-VF2825-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:50:56 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, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") ruckusVF2825, = mibBuilder.importSymbols("RUCKUS-PRODUCTS-MIB", "ruckusVF2825") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ModuleIdentity, Bits, Counter64, Unsigned32, Integer32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, iso, MibIdentifier, Gauge32, NotificationType, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Bits", "Counter64", "Unsigned32", "Integer32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "iso", "MibIdentifier", "Gauge32", "NotificationType", "Counter32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ruckusVF2825MIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1)) if mibBuilder.loadTexts: ruckusVF2825MIB.setLastUpdated('201010150800Z') if mibBuilder.loadTexts: ruckusVF2825MIB.setOrganization('Ruckus Wireless, Inc.') ruckusVF2825Objects = MibIdentifier((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 1)) ruckusVF2825Info = MibIdentifier((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 1, 1)) ruckusVF2825NetworkTable = MibTable((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 1, 1, 1), ) if mibBuilder.loadTexts: ruckusVF2825NetworkTable.setStatus('current') ruckusVF2825NetworkEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 1, 1, 1, 1), ).setIndexNames((0, "RUCKUS-VF2825-MIB", "ruckusVF2825NetworkName"), (0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: ruckusVF2825NetworkEntry.setStatus('current') ruckusVF2825NetworkName = MibTableColumn((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))) if mibBuilder.loadTexts: ruckusVF2825NetworkName.setStatus('current') ruckusVF2825NetworkIfName = MibTableColumn((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 1, 1, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: ruckusVF2825NetworkIfName.setStatus('current') ruckusVF2825Events = MibIdentifier((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 2)) ruckusVF2825Conf = MibIdentifier((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 3)) ruckusVF2825Groups = MibIdentifier((1, 3, 6, 1, 4, 1, 25053, 3, 1, 1, 1, 1, 3, 1)) mibBuilder.exportSymbols("RUCKUS-VF2825-MIB", ruckusVF2825Info=ruckusVF2825Info, ruckusVF2825NetworkIfName=ruckusVF2825NetworkIfName, PYSNMP_MODULE_ID=ruckusVF2825MIB, ruckusVF2825NetworkTable=ruckusVF2825NetworkTable, ruckusVF2825MIB=ruckusVF2825MIB, ruckusVF2825Events=ruckusVF2825Events, ruckusVF2825Conf=ruckusVF2825Conf, ruckusVF2825NetworkEntry=ruckusVF2825NetworkEntry, ruckusVF2825NetworkName=ruckusVF2825NetworkName, ruckusVF2825Groups=ruckusVF2825Groups, ruckusVF2825Objects=ruckusVF2825Objects)
# Created by MechAviv # ID :: [865090001] # Commerci Republic : Berry if sm.hasQuest(17613): # [Commerci Republic] The Minister's Son sm.curNodeEventEnd(True) sm.setTemporarySkillSet(0) sm.setInGameDirectionMode(True, True, False, False) sm.setStandAloneMode(True) sm.setSpeakerID(9390241) sm.removeEscapeButton() sm.flipDialogue() sm.setSpeakerType(3) sm.sendNext("Hey! Keep your paws away from my pants!") sm.setSpeakerID(9390242) sm.removeEscapeButton() sm.flipDialogue() sm.setSpeakerType(3) sm.sendSay("All your fish are belong to us!") sm.setSpeakerID(9390241) sm.removeEscapeButton() sm.flipDialogue() sm.setSpeakerType(3) sm.sendSay("I am the great #e#bLeon Daniella#k#n! These fish are mine! See? I wrote my name on them.") sm.setSpeakerID(9390242) sm.removeEscapeButton() sm.flipDialogue() sm.setSpeakerType(3) sm.sendSay("Your permanent marker won't dissuade us. WE WANT YOUR FISH!") sm.showNpcSpecialActionByTemplateId(9390241, "q17613", 0) sm.setSpeakerID(9390241) sm.removeEscapeButton() sm.flipDialogue() sm.setSpeakerType(3) sm.sendSay("It's not fair if you attack me as a pack. Do it one by one, like a real man, er, cat. Hey! Are you listening? Ouch!") sm.setSpeakerID(0) sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay("#b(Uh oh, that guy's in real trouble. I should help him.#k\r\nHey! Coastal Cats! Over here.") sm.setTemporarySkillSet(0) sm.setInGameDirectionMode(False, True, False, False) i = 0 while i < 12: sm.spawnMob(9390847, 996, 132, False) i += 1
class Solution: def totalMoney(self, n: int) -> int: s, m, p, t = 0, 0, 0, 0 while t < n: if t % 7 == 0: m += 1 s += m p = m else: p += 1 s += p t += 1 return s
SIG_START_DEFAULT = 0 SIG_UNDEF = 'undefined' class Signal(object): def __init__(self, name, start_state=None): self.name = name if start_state is not None: self.state = start_state else: self.state = SIG_START_DEFAULT self.previous = self.state self.conns = list() def __str__(self): msg = 'Sig<{}={}>' return msg.format( self.name, self.state) def set(self, time, state): self.previous = self.state self.state = state for conn in self.conns: # TODO: should really send only the state, not itself ?? # current form for access to .state and .previous (?.name? : not really) # NEEDED for trace, in current form. But device tracing is nicer ... conn(time, self) def add_connection(self, call, index=-1): self.conns[index:index] = [call] def remove_connection(self, call): while call in conns: self.conns.remove(call) def trace(self): self.add_connection(signal_trace, 0) def untrace(self): self.conns.remove(signal_trace) def signal_trace(time, sig): msg = '@{}: Sig<{}> {} ==> {}' msg = msg.format( time, sig.name, sig.previous, sig.state) print(msg) def trace(signal, on=True): if on: signal.add_connection(signal_trace) else: signal.conns.remove(signal_trace) def untrace(signal): trace(signal, False)
class Solution: def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ s = set(dict) sentence = sentence.split() for j, w in enumerate(sentence): for i in range(1, len(w)): if w[:i] in s: sentence[j] = w[:i] break return " ".join(sentence)
a = float(input('Quantos km é sua viagem?')) print('Sua viagem é de {} km' .format(a)) if a > 200: print('O preço de sua viagem é R${}'.format((a) * 0.45)) else: print('O preço de sua viagem é R${}'.format((a)* 0.50))
# # PySNMP MIB module DE-OPT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DE-OPT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:21:56 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) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") IpAddress, enterprises, Bits, iso, TimeTicks, ModuleIdentity, Gauge32, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, NotificationType, MibIdentifier, Counter32, Unsigned32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "enterprises", "Bits", "iso", "TimeTicks", "ModuleIdentity", "Gauge32", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "NotificationType", "MibIdentifier", "Counter32", "Unsigned32", "Counter64") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") codex = MibIdentifier((1, 3, 6, 1, 4, 1, 449)) cdxProductSpecific = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2)) cdx6500 = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1)) cdx6500Configuration = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 2)) cdx6500CfgGeneralGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 2, 2)) cdx6500Statistics = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 3)) cdx6500StatOtherStatsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2)) cdx6500Controls = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 4)) class DisplayString(OctetString): pass cdx6500StatEncryption = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12)) statEncryptionGeneral = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1)) deDataEncryptionHardwareStatus = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: deDataEncryptionHardwareStatus.setStatus('mandatory') deMaxChannelAvailable = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 500))).setMaxAccess("readonly") if mibBuilder.loadTexts: deMaxChannelAvailable.setStatus('mandatory') deMaxChannelConfigured = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 500))).setMaxAccess("readonly") if mibBuilder.loadTexts: deMaxChannelConfigured.setStatus('mandatory') deChannelsInUse = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 500))).setMaxAccess("readonly") if mibBuilder.loadTexts: deChannelsInUse.setStatus('mandatory') deMaxSimultaneousChannelsUsed = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 500))).setMaxAccess("readonly") if mibBuilder.loadTexts: deMaxSimultaneousChannelsUsed.setStatus('mandatory') deCurrentEncryptionQueueLength = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: deCurrentEncryptionQueueLength.setStatus('mandatory') deMaxEncryptionQueueDepth = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: deMaxEncryptionQueueDepth.setStatus('mandatory') deTimeLastStatisticsReset = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: deTimeLastStatisticsReset.setStatus('mandatory') deAlgorithmSupportedByHardwareStatus = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("no-simm", 1), ("des-40", 2), ("des-64", 3), ("des-128", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: deAlgorithmSupportedByHardwareStatus.setStatus('mandatory') statEncryptionChannelTable = MibTable((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 2), ) if mibBuilder.loadTexts: statEncryptionChannelTable.setStatus('mandatory') statEncryptionChannelEntry = MibTableRow((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 2, 1), ).setIndexNames((0, "DE-OPT-MIB", "deStatChannelNumber")) if mibBuilder.loadTexts: statEncryptionChannelEntry.setStatus('mandatory') deStatChannelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: deStatChannelNumber.setStatus('mandatory') deLastStatisticsReset = MibTableColumn((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: deLastStatisticsReset.setStatus('mandatory') deChannelState = MibTableColumn((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("nonData", 1), ("data", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: deChannelState.setStatus('mandatory') deSourceChannel = MibTableColumn((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 2, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: deSourceChannel.setStatus('mandatory') deDestinationChannel = MibTableColumn((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 2, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: deDestinationChannel.setStatus('mandatory') deCorruptedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 449, 2, 1, 3, 2, 12, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: deCorruptedPackets.setStatus('mandatory') cdx6500ControlsEncryption = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 4, 18)) ctrlEncryptionGeneral = MibIdentifier((1, 3, 6, 1, 4, 1, 449, 2, 1, 4, 18, 1)) deCtrlEncryptionGeneral = MibScalar((1, 3, 6, 1, 4, 1, 449, 2, 1, 4, 18, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("resetStatistics", 1)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: deCtrlEncryptionGeneral.setStatus('mandatory') ctrlEncryptionChannelTable = MibTable((1, 3, 6, 1, 4, 1, 449, 2, 1, 4, 18, 2), ) if mibBuilder.loadTexts: ctrlEncryptionChannelTable.setStatus('mandatory') ctrlEncryptionChannelEntry = MibTableRow((1, 3, 6, 1, 4, 1, 449, 2, 1, 4, 18, 2, 1), ).setIndexNames((0, "DE-OPT-MIB", "deCtrlChannelNumber")) if mibBuilder.loadTexts: ctrlEncryptionChannelEntry.setStatus('mandatory') deCtrlChannelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 449, 2, 1, 4, 18, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: deCtrlChannelNumber.setStatus('mandatory') deCtrlEncryptionChannel = MibTableColumn((1, 3, 6, 1, 4, 1, 449, 2, 1, 4, 18, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("resetStatistics", 1)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: deCtrlEncryptionChannel.setStatus('mandatory') mibBuilder.exportSymbols("DE-OPT-MIB", statEncryptionChannelEntry=statEncryptionChannelEntry, cdx6500StatOtherStatsGroup=cdx6500StatOtherStatsGroup, deChannelsInUse=deChannelsInUse, deCorruptedPackets=deCorruptedPackets, statEncryptionGeneral=statEncryptionGeneral, deStatChannelNumber=deStatChannelNumber, ctrlEncryptionChannelTable=ctrlEncryptionChannelTable, statEncryptionChannelTable=statEncryptionChannelTable, deDataEncryptionHardwareStatus=deDataEncryptionHardwareStatus, deCtrlChannelNumber=deCtrlChannelNumber, cdx6500Configuration=cdx6500Configuration, deDestinationChannel=deDestinationChannel, cdx6500StatEncryption=cdx6500StatEncryption, codex=codex, ctrlEncryptionGeneral=ctrlEncryptionGeneral, cdx6500Statistics=cdx6500Statistics, ctrlEncryptionChannelEntry=ctrlEncryptionChannelEntry, cdx6500CfgGeneralGroup=cdx6500CfgGeneralGroup, cdx6500Controls=cdx6500Controls, cdx6500=cdx6500, deMaxChannelAvailable=deMaxChannelAvailable, deMaxChannelConfigured=deMaxChannelConfigured, deSourceChannel=deSourceChannel, DisplayString=DisplayString, deMaxSimultaneousChannelsUsed=deMaxSimultaneousChannelsUsed, deCurrentEncryptionQueueLength=deCurrentEncryptionQueueLength, deLastStatisticsReset=deLastStatisticsReset, deMaxEncryptionQueueDepth=deMaxEncryptionQueueDepth, cdx6500ControlsEncryption=cdx6500ControlsEncryption, deCtrlEncryptionChannel=deCtrlEncryptionChannel, deAlgorithmSupportedByHardwareStatus=deAlgorithmSupportedByHardwareStatus, deCtrlEncryptionGeneral=deCtrlEncryptionGeneral, cdxProductSpecific=cdxProductSpecific, deTimeLastStatisticsReset=deTimeLastStatisticsReset, deChannelState=deChannelState)
# Ingredient Adjuster # Ask user how many cookies he or she wants cookie = int(input("Enter the amount of cookies you want: ")) sugar = 1.5 oil = 1 pounder = 2.75 print(sugar * cookie, ' gr. sugar.\n', oil * cookie, ' gr. butter.\n', pounder * cookie, ' gr. flour.', sep="")
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:60 ms, 在所有 Python3 提交中击败了86.96% 的用户 内存消耗:15.2 MB, 在所有 Python3 提交中击败了85.68% 的用户 解题思路: 递归 """ """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def preorder(self, root: 'Node') -> List[int]: result =[] def find(root): if root: result.append(root.val) childrens = root.children for children in childrens: find(children) find(root) return result
""" EXAMPLE USAGE: opts = Opts(environ, opt('q', default=''), opt('pages', default=2), opt('split', default=0), opt('simple', default=0), opt('max_topics', default=40), opt('ncol', default=3), opt('save', default=False), opt('load', default=False), opt('smoothing', default='lidstone'), opt('single_query', default=0), opt('format', default='dev'), ) ... then opts is a hash. """ #### first, from anyall.org/util.py def safehtml(x): return cgi.escape(str(x),quote=True) def unicodify(s, encoding='utf8', *args): """ because {str,unicode}.{encode,decode} is anti-polymorphic, but sometimes you can't control which you have. """ if isinstance(s,unicode): return s if isinstance(s,str): return s.decode(encoding, *args) return unicode(s) class Struct(dict): def __getattr__(self, a): if a.startswith('__'): raise AttributeError return self[a] def __setattr__(self, a, v): self[a] = v #### main code type_builtin = type def opt(name, type=None, default=None): o = Struct(name=name, type=type, default=default) if type is None: if default is not None: o.type = type_builtin(default) else: o.type = str #raise Exception("need type for %s" % name) #if o.type==bool: o.type=int return o def type_clean(val,type): if type==bool: if val in (False,0,'0','f','false','False','no','n'): return False if val in (True,1,'1','t','true','True','yes','y'): return True raise Exception("bad bool value %s" % repr(val)) if type==str or type==unicode: # nope no strings, you're gonna get unicode instead! return unicodify(val) return type(val) class Opts(Struct): " modelled on trollop.rubyforge.org and gist.github.com/5682 " def __init__(self, environ, *optlist): vars = cgi.parse_qs(environ['QUERY_STRING']) for opt in optlist: val = vars.get(opt.name) val = val[0] if val else None if val is None and opt.default is not None: val = copy(opt.default) elif val is None: raise Exception("option not given: %s" % opt.name) val = type_clean(val, opt.type) self[opt.name] = val def input(self, name, **kwargs): val = self[name] h = '''<input id=%s name=%s value="%s"''' % (name, name, safehtml(val)) more = {} if type(val)==int: more['size'] = 2 elif type(val)==float: more['size'] = 4 more.update(kwargs) for k,v in more.iteritems(): h += ''' %s="%s"''' % (k,v) h += ">" return h
# Advent of Code 2021, Day 17 # # Simple projectile simulation, with search for # velocities that achieve highest position, and total # number of possible velocity values that reach target # area; just used a simple grid search. # # AK, 17/12/2021 # Target area (x range and y range) T = ((20,30), (-10, -5)) # Sample data T = ((192, 251), (-89, -59)) # Real data # Determine whether coordinates are within target area def withinTarget(x, y): return x >= T[0][0] and x <= T[0][1] and y >= T[1][0] and y <= T[1][1] # Returns the highest position achieved def simulate(xv, yv): # Start at 0,0 #print(f'Simulating {xv}, {yv}') x = y = 0 highest = -99999 # Highest y reached, for Part 1 hitTarget = False # Whether or not hit target area # Simulate steps iter = 0 while iter < 300: # Stop after lots of iterations # Position changes according to velocity iter += 1 x += xv y += yv # Record highest position if iter == 0 or y > highest: highest = y # Adjust velocity if xv > 0: xv -= 1 elif xv < 0: xv += 1 yv -= 1 #print(f' Position = {x},{y}, velocity = {xv},{yv}') # Stop if reached target area if withinTarget(x, y): #print(' Within target!') hitTarget = True break # If hit target, return highest position reached, otherwise # return None #print(' Highest y =', highest) return highest if hitTarget else None # Simple pseudo-optimization, just a grid search, finds # the highest position reached (for Part 1) and also counts # up the number of solutions that hit target (for Part 2) def optimize(): best = count = 0 for xv in range(0, 300): # Set bounds range of problem for yv in range(-100, 100): ypos = simulate(xv, yv) if ypos != None: # Only count if hit target if ypos > best: best = ypos count += 1 print('Best found =', best) print('Solutions found =', count) # Test examples #for xv, yv in [(7, 2), (6, 3), (9, 0), (17, -4), (6, 9)]: # print(xv, yv, simulate(xv, yv)) # Run the solution optimize()
# Criação de Classe pai Pessoa com atributos nome e sobrenome. class Pessoa: # Metodo construtor vazio para criação de instancias vazias. def __init__(self): super().__init__() pass # GetNome para retornar o valor de nome. def getNome(self): return self._nome # SetNome para Inserir o valor de nome def setNome(self,nome): self._nome = nome # GetSobrenome para retornar o valor de sobrenome def getSobrenome(self): return self._sobrenome # SetSobrenome para Inserir o valor de sobrenome def setSobrenome(self,sobrenome): self._sobrenome = sobrenome
class Person(object): def __init__(self, name, age): self.name=name self.age=age def get_person(self,): return "Hi" print("hi")
class Book: def __init__(self, title, price, author): self.title = title self.author = author self.price = price def __eq__(self, other): if not isinstance(other,Book): raise ValueError("Couldn't compare book to non-book") return (self.title == other.title and self.price == other.price and self.author == other.author) def __ge__(self, other): if not isinstance(other,Book): raise ValueError("Couldn't compare book to non-book") return self.price >= other.price def __lt__(self, other): if not isinstance(other,Book): raise ValueError("Couldn't compare book to non-book") return self.price < other.price obj1 = Book("Ramayan", 9999,"Valmiki") obj2 = Book("MahaBharat", 7777, "Vyasa") obj3 = Book("Ramayan", 9999,"Valmiki") obj4 = Book("Bhagavatam", 5789, "Vyasa") print(obj1==obj3) print(obj1 >= obj2) print(obj1 < obj2) books = [obj4,obj3,obj2,obj1] books.sort() print([book.title for book in books])
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Piston Cloud Computing, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def validate(filter, value): return FILTER_FUNCTIONS.get(filter, lambda v: True)(value) def validate_int_in_range(min=0, max=None): def _validator(v): try: if max is None: return min <= int(v) return min <= int(v) <= max except ValueError: return False return _validator def validate_boolean(v): return v.lower() in ('none', 'true', 'false', '1', '0') FILTER_FUNCTIONS = {'size_max': validate_int_in_range(), # build validator 'size_min': validate_int_in_range(), # build validator 'min_ram': validate_int_in_range(), # build validator 'protected': validate_boolean, 'is_public': validate_boolean, }
''' Example 1: Input: N = 5, arr = {1, 2, 3, 2, 1} Output: 3 Explaination: Only the number 3 is single. Example 2: Input: N = 11, arr = {1, 2, 3, 5, 3, 2, 1, 4, 5, 6, 6} Output: 4 Explaination: 4 is the only single. ''' class Solution: def findSingle(self, N, arr): # code here m = 0 for i in arr: m ^= i return m
class RecordNotFound(Exception): pass class InvalidLEI(Exception): pass class InvalidISIN(Exception): pass class NotFound(Exception): pass
N=int(input("Ingresa un numero base pls:")) M=int(input("Ingresa una potencia pls:")) print("LOS RESULTADOS SON:") for i in range(0,M+1): print(f"{N}^{i} = " + str(N**i))
def main(): print("Please enter filename:") filename = input() f = open('..\\src\\main\\resources\\assets\\forbidden\\models\\item\\' + filename + '.json', mode='xt') f.write('{\n') f.write(' "parent": "forbidden:item/base_item",\n') f.write(' "textures": {\n') f.write(' "layer0": "forbidden:items/' + filename + '"\n') f.write(' }\n') f.write('}') f.close() main()
#show function logs all attempts on console and in out.txt file out = open("out.txt", 'w+') def show(line): li = "" for i in line: for j in i: li += str(j) + " " li += "\n" print(li) out.write(li) out.write("\n")
print() print("-- RELATIONS ------------------------------") print() print("GRAPH 1:\n0 0 0\n0 0 0\n0 0 0") g1 = Graph(3) print("REFLEXIVITA: " + str(is_reflexive(g1)) + " -> spravna odpoved: False") print("SYMETRIE: " + str(is_symmetric(g1)) + " -> spravna odpoved: True") print("ANTISYMETRIE: " + str(is_antisymmetric(g1)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g1)) + " -> spravna odpoved: True") print("-------------------------------------------") print("GRAPH 2:\n1 0 0\n0 1 0\n0 0 1") g2 = Graph(3) g2.matrix[0][0] = True g2.matrix[1][1] = True g2.matrix[2][2] = True print("REFLEXIVITA: " + str(is_reflexive(g2)) + " -> spravna odpoved: True") print("SYMETRIE: " + str(is_symmetric(g2)) + " -> spravna odpoved: True") print("ANTISYMETRIE: " + str(is_antisymmetric(g2)) + " -> spravna odpoved: False") print("TRANZITIVITA: " + str(is_transitive(g2)) + " -> spravna odpoved: True") print("- GOOD GRAPHS -----------------------------") print("GRAPH 3:\n0 0 0\n0 1 0\n0 1 1") g3 = Graph(3) g3.matrix[1][1] = True g3.matrix[2][1] = True g3.matrix[2][2] = True print("REFLEXIVITA: " + str(is_reflexive(g3)) + " -> spravna odpoved: False") print("SYMETRIE: " + str(is_symmetric(g3)) + " -> spravna odpoved: False") print("ANTISYMETRIE: " + str(is_antisymmetric(g3)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g3)) + " -> spravna odpoved: True") print("-------------------------------------------") print("GRAPH 4:\n0 1 1\n0 1 1\n0 0 1") g4 = Graph(3) g4.matrix[0][1] = True g4.matrix[0][2] = True g4.matrix[1][1] = True g4.matrix[1][2] = True g4.matrix[2][2] = True print("REFLEXIVITA: " + str(is_reflexive(g4)) + " -> spravna odpoved: False") print("SYMETRIE: " + str(is_symmetric(g4)) + " -> spravna odpoved: False") print("ANTISYMETRIE: " + str(is_antisymmetric(g4)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g4)) + " -> spravna odpoved: True") print("-------------------------------------------") print("GRAPH 5:\n1 0 0\n0 0 0\n1 0 0") g5 = Graph(3) g5.matrix[0][0] = True g5.matrix[2][0] = True print("REFLEXIVITA: " + str(is_reflexive(g5)) + " -> spravna odpoved: False") print("SYMETRIE: " + str(is_symmetric(g5)) + " -> spravna odpoved: False") print("ANTISYMETRIE: " + str(is_antisymmetric(g5)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g5)) + " -> spravna odpoved: True") print("-------------------------------------------") print("GRAPH 6:\n1 0 0\n1 1 0\n0 1 1") g6 = Graph(3) g6.matrix[0][0] = True g6.matrix[1][0] = True g6.matrix[1][1] = True g6.matrix[2][1] = True g6.matrix[2][2] = True print("REFLEXIVITA: " + str(is_reflexive(g6)) + " -> spravna odpoved: True") print("SYMETRIE: " + str(is_symmetric(g6)) + " -> spravna odpoved: False") print("ANTISYMETRIE: " + str(is_antisymmetric(g6)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g6)) + " -> spravna odpoved: False") print() print("- TRANSITIVE CLOSURE -------------------------") print() print("GRAPH 7:\n1 0 0\n1 1 0\n0 1 1") g7 = Graph(3) g7.matrix[0][0] = True g7.matrix[1][0] = True g7.matrix[1][1] = True g7.matrix[2][1] = True g7.matrix[2][2] = True print("TRANZITIVITA: " + str(is_transitive(g7)) + " -> spravna odpoved: False") transitive_closure(g7) print(str(g7.matrix)) print("TRANZITIVITA: " + str(is_transitive(g7)) + " -> spravna odpoved: True")
# Some utility classes to represent a PDB structure class Atom: """ A simple class for an amino acid residue """ def __init__(self, type): self.type = type self.coords = (0.0, 0.0, 0.0) # Overload the __repr__ operator to make printing simpler. def __repr__(self): return self.type class Residue: """ A simple class for an amino acid residue """ def __init__(self, type, number): self.type = type self.number = number self.atoms = [] # Overload the __repr__ operator to make printing simpler. def __repr__(self): return "{0} {1}".format(self.type, self.number) @property def alpha_carbon(self): """ Lookup the atom representing the alpha carbon """ for atom in self.atoms: if atom.type in ('CA', 'CA A', 'C A'): return atom # Le sad: no alpha carbon found print(self.atoms) return None class ActiveSite: """ A simple class for an active site """ def __init__(self, name): self.name = name self.residues = [] # Overload the __repr__ operator to make printing simpler. def __repr__(self): return self.name
class _elastica_numpy: """The purpose is to throw deprecation error to people previously using _elastica_numpy module. Please remove this exception after v0.3.""" raise ImportError("The module _elastica_numpy is now deprecated.")
# Task 03. Statistics def add_to_dict(product: str, quantity: int): if product not in stock: stock[product] = quantity else: stock[product] += quantity cmd = input() stock = {} while not cmd == "statistics": key = cmd.split(': ')[0] value = cmd.split(': ')[1] add_to_dict(key, int(value)) cmd = input() print("Products in stock:") for product in stock: print(f"- {product}: {stock[product]}") print(f"Total Products: {len(stock)}") print(f"Total Quantity: {sum(stock.values())}")
''' This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. You can modify the input array in-place. ''' def findLowestPositiveInteger(array): array.sort() nextNumber = 1 for x in array: if x > nextNumber and x > 0: break elif x > 0: nextNumber += 1 print(nextNumber) findLowestPositiveInteger([3,4,-1,-1]) findLowestPositiveInteger([1, 2, 0])
#Main class class Characters: def __init__(self, name, lastname, age, hp, title, language, race, weakness ): # instance variable unique to each instance self.__name = name self.__lastname = lastname self.__age = age self.__hp = hp self.__title = title self.__race = race self.__weakness = weakness self.__language = language def character_info(self): return f"ID:{self.__name} {self.__lastname}\n" \ f"age:{self.__age}\n" \ f"Hp:{self.__hp} \n" \ f"race:{self.__race}\n" \ f"title:{self.__title}\n" \ f"weakness:{self.__weakness}\n" \ f"language:{self.__language}\n" \ f"that's all buddy" def attributeone(self): return f"{self.__name}" def attributetwo(self): return F"{self.__hp}" #These classes are inheritors of the main class class WarriorPerson(Characters): def __init__(self, name="none", lastname="none", age="none", hp="150", title="none", language="none", race="human or unknown", weakness="none"): super().__init__(name, lastname, age, hp, title, language, race, weakness) class RegularHumanPerson(Characters): def __init__(self, name="none", lastname="", age="none", hp="50", title="The man who be normal", language="English", race="human or unknown", weakness="nearly everything"): super().__init__(name, lastname, age, hp, title, language, race, weakness) class WitchPerson(Characters): def __init__(self, name="none", lastname="none", age="none", hp="896", title="none", language="none", race="human or unknown", weakness="none"): super().__init__(name, lastname, age, hp, title, language, race, weakness) class VampirePerson(Characters): def __init__(self, name="none", lastname="", age="none", hp="500", title="none", language="none", race="human or unknown", weakness="none"): super().__init__(name, lastname, age, hp, title, language, race, weakness) regular_human = RegularHumanPerson( name="john", lastname="smith", age="45", hp="50", ) regular_humans_sidekick = RegularHumanPerson( name="robin", age="20", hp="32", ) old_warrior = WarriorPerson( name="Berserker", lastname="", age="345", hp="500", title="old warrior", language="English and old vikings language", race="Human", weakness="Science" ) old_which = WitchPerson( name="Sarah", lastname="", age="600", hp="659", title="Girl of beast", language="She knows little bit old english and witch language", race="Human", weakness="Science and light of angel" ) young_Vampire = VampirePerson( name="Deacon", lastname="", age="783", hp="800", language="She knows little bit old english and new english", race="vampire", weakness="stake" )
n = int(input()) b = list(map(int, input().split(' '))) x = [0] a = [] a.append(b[0]) x.append(a[0]) i = 1 while i < n: a.append(b[i]+x[i]) if a[i] > x[i]: x.append(a[i]) else: x.append(x[i]) i += 1 str_a = [str(ele) for ele in a] print(' '.join(str_a))
class Production(object): def analyze(self, world): """Implement your analyzer here.""" def interpret(self, world): """Implement your interpreter here.""" class FuncCall(Production): def __init__(self, token, params): self.name = token[1] self.params = params self.token = token def analyze(self, world): self.params.analyze(world) def interpret(self, world): funcdef = world.functions[self.name] funcdef.call(world, self.params) def __repr__(self): return f"FuncCall({self.name}: {self.params})" class Parameters(Production): def __init__(self, expressions): self.expressions = expressions def analyze(self, world): for expr in self.expressions: expr.analyze(world) def interpret(self, world): return [x.interpret(world) for x in self.expressions] def __repr__(self): return f"Parameters({self.expressions})" class Expr(Production): pass class NameExpr(Expr): def __init__(self, token): self.name = token[1] self.token = token def interpret(self, world): # This should point at an IntExpr for now ref = world.variables.get(self.name) return ref.interpret(world) def __repr__(self): return f"NameExpr({self.name})" class IntExpr(Expr): def __init__(self, token): self.integer = int(token[1]) self.token = token def __repr__(self): return f"IntExpr({self.integer})" def interpret(self, world): return self.integer class AddExpr(Expr): def __init__(self, left, right): self.left = left self.right = right def analyze(self, world): self.left.analyze(world) self.right.analyze(world) def interpret(self, world): return self.left.interpret(world) + self.right.interpret(world) def __repr__(self): return f"AddExpr({self.left}, {self.right})" class FuncDef(Production): def __init__(self, token, params, body): self.name = token[1] self.params = params self.body = body self.token = token def analyze(self, world): world.functions[self.name] = self def __repr__(self): return f"FuncDef({self.name}({self.params}): {self.body}" def call(self, world, params): params = params or Parameters() scope = world.clone() for i, p in enumerate(self.params.expressions): scope.variables[p.name] = params.expressions[i] for line in self.body: line.interpret(scope) class PrintFuncDef(Production): def call(self, world, params): print(*params.interpret(world))
""" A name to avoid typosquating pytest-foward-compatibility """ __version__ = "0.1.0"
class Config: DEBUG = False SQLURI = 'postgres://tarek:xxx@localhost/db' """ >>> from flask import Flask >>> app = Flask(__name__) >>> app.config.from_object('prod_settings.Config') >>> print(app.config) <Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCE PTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, ' SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_ COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, ' SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(second s=43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED _URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIM ETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'SQLURI': 'postgres://tarek:xxx@loc alhost/db'}> """
'''Try It Yourself''' '''6-1. Person: Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name, last_name, age, and city. Print each piece of information stored in your dictionary.''' person = {'nombre': 'Pablo', 'apellido': 'Rojas', 'edad': 22, 'ciudad': 'zacatecas'} print(person['nombre'].title()) print(person['apellido'].title()) print(person['edad']) print(person['ciudad'].title()) '''6-2. Favorite Numbers: Use a dictionary to store people’s favorite numbers. Think of five names, and use them as keys in your dictionary. Think of a favorite number for each person, and store each as a value in your dictionary. Print each person’s name and their favorite number. For even more fun, poll a few friends and get some actual data for your program.''' favorite_number = {'Luis': 14, 'Alex': 25, 'Jhona': 7, 'Pablo': 13, 'Vela': 4} print(f"Luis tu numero favorito es: {favorite_number['Luis']}") print(f"Alex tu numero favorito es: {favorite_number['Alex']}") print(f"Jhona tu numero favorito es: {favorite_number['Jhona']}") print(f"Pablo tu numero favorito es: {favorite_number['Pablo']}") print(f"Vela tu numero favorito es: {favorite_number['Vela']}") '''6-3. Glossary: A Python dictionary can be used to model an actual dictionary. However, to avoid confusion, let’s call it a glossary. • Think of five programming words you’ve learned about in the previous chapters. Use these words as the keys in your glossary, and store their meanings as values. • Print each word and its meaning as neatly formatted output. You might print the word followed by a colon and then its meaning, or print the word on one line and then print its meaning indented on a second line. Use the newline character (\n) to insert a blank line between each word-meaning pair in your output.''' words = {'if': 'Sirve para hacer una condicion simple', 'else': 'Sirve para dar resultado a una condicion if que no se cumple', 'elif': 'Sirve para agregar otra condicon si la condicion inicial if no es correcta y se agrega entre un if y else', 'upper': 'Es un metodo de las listas con el cual podemos hacer que todas las letras mayusculas', 'lower': 'Es un metodo de las listas con el cual podemos hacer que todas las letras sean minusculas'} print("El significado de if es:" + f"\n{words['if'].title()}") print("El significado de else es:" + f"\n{words['else'].title()}") print("El significado de elif es:" + f"\n{words['elif'].title()}") print("El significado de upper() es:" + f"\n{words['upper'].title()}") print("El significado de lower() es:" + f"\n{words['lower'].title()}")
#Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N. """"Problem Solution 1. Take in the number of terms to find the sum of the series for. 2. Initialize the sum variable to 0. 3. Use a for loop ranging from 1 to the number and find the sum of the series. 4. Print the sum of the series after rounding it off to two decimal places. 5. Exit. """ n=int(input("Enter the number of terms in the series: ")) sum=0 print("the sum of series: ", end = " ") for i in range(1,n+1): print(f"1/{i}",sep=" ",end=" ") if i<n: print("+ ",sep=" ",end=" ") sum=sum+(1/i) print(f" = {round(sum,3)}") print()
class Solution: """ @param s: A string @return: the length of last word """ def lengthOfLastWord(self, s): return len(s.strip().split(" ")[-1])
""" This shows that Lists and Dictionaries are different """ listfootball=['messi','inesta','pique','sanchez','suarez','neymar'] listbuzzfeed=['eugene','ashley','keith','ella','sara','chris'] """ This will return false """ print(listbuzzfeed==listfootball) dictfootball={'name':'lionel','age':'26','country':'argentina','club':'fc-barcelona'} dictfootball2={'country-name':'argentina','capital':'bueones-aires','sports':'football','icon':'maradona'} """ This will return true """ print(dictfootball2==dictfootball)
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' The MIT License (MIT) Copyright (c) 2016 Yuma.M 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. ''' INITIALIZE_CODES = [ 0x01, # clear display 0x38, # function set: 8bit, 2lines, 5x8 0x0c, # display on, no cursor 0x06, # カーソルの動き ] LINEBREAK_CODE = [0xc0] CHAR_TABLE = { u'!': [0x21], u'"': [0x22], u'#': [0x23], u'$': [0x24], u'%': [0x25], u'&': [0x26], u"'": [0x27], u'(': [0x28], u')': [0x29], u'*': [0x2a], u'+': [0x2b], u',': [0x2c], u'-': [0x2d], u'.': [0x2e], u'/': [0x2f], u'0': [0x30], u'1': [0x31], u'2': [0x32], u'3': [0x33], u'4': [0x34], u'5': [0x35], u'6': [0x36], u'7': [0x37], u'8': [0x38], u'9': [0x39], u':': [0x3a], u';': [0x3b], u'<': [0x3c], u'=': [0x3d], u'>': [0x3e], u'?': [0x3f], u'@': [0x40], u'A': [0x41], u'B': [0x42], u'C': [0x43], u'D': [0x44], u'E': [0x45], u'F': [0x46], u'G': [0x47], u'H': [0x48], u'I': [0x49], u'J': [0x4a], u'K': [0x4b], u'L': [0x4c], u'M': [0x4d], u'N': [0x4e], u'O': [0x4f], u'P': [0x50], u'Q': [0x51], u'R': [0x52], u'S': [0x53], u'T': [0x54], u'U': [0x55], u'V': [0x56], u'W': [0x57], u'X': [0x58], u'Y': [0x59], u'Z': [0x5a], u'[[': [0x5b], u'¥': [0x5c], u']]': [0x5d], u'^': [0x5e], u'_': [0x5f], u'`': [0x60], u'a': [0x61], u'b': [0x62], u'c': [0x63], u'd': [0x64], u'e': [0x65], u'f': [0x66], u'g': [0x67], u'h': [0x68], u'i': [0x69], u'j': [0x6a], u'k': [0x6b], u'l': [0x6c], u'm': [0x6d], u'n': [0x6e], u'o': [0x6f], u'p': [0x70], u'q': [0x71], u'r': [0x72], u's': [0x73], u't': [0x74], u'u': [0x75], u'v': [0x76], u'w': [0x77], u'x': [0x78], u'y': [0x79], u'z': [0x7a], u'(': [0x7b], u'|': [0x7c], u')': [0x7d], u'→': [0x7e], u'←': [0x7f], u'。': [0xa1], u'「': [0xa2], u'」': [0xa3], u'、': [0xa4], u'・': [0xa5], u'ヲ': [0xa6], u"ァ": [0xa7], u'ィ': [0xa8], u'ゥ': [0xa9], u'ェ': [0xaa], u'ォ': [0xab], u'ャ': [0xac], u'ュ': [0xad], u'ョ': [0xae], u'ッ': [0xaf], u'ー': [0xb0], u'ア': [0xb1], u'イ': [0xb2], u'ウ': [0xb3], u'エ': [0xb4], u'オ': [0xb5], u'カ': [0xb6], u'キ': [0xb7], u'ク': [0xb8], u'ケ': [0xb9], u'コ': [0xba], u'サ': [0xbb], u'シ': [0xbc], u'ス': [0xbd], u'セ': [0xbe], u'ソ': [0xbf], u'タ': [0xc0], u'チ': [0xc1], u'ツ': [0xc2], u'テ': [0xc3], u'ト': [0xc4], u'ナ': [0xc5], u'ニ': [0xc6], u'ヌ': [0xc7], u'ネ': [0xc8], u'ノ': [0xc9], u'ハ': [0xca], u'ヒ': [0xcb], u'フ': [0xcc], u'ヘ': [0xcd], u'ホ': [0xce], u'マ': [0xcf], u'ミ': [0xd0], u'ム': [0xd1], u'メ': [0xd2], u'モ': [0xd3], u'ヤ': [0xd4], u'ユ': [0xd5], u'ヨ': [0xd6], u'ラ': [0xd7], u'リ': [0xd8], u'ル': [0xd9], u'レ': [0xda], u'ロ': [0xdb], u'ワ': [0xdc], u'ン': [0xdd], u'゛': [0xde], u'゜': [0xdf], u'α': [0xe0], u'β': [0xe2], u'ε': [0xe3], u'μ': [0xe4], u'δ': [0xe5], u'ρ': [0xe6], u'√': [0xe8], u'∞': [0xf3], u'Ω': [0xf4], u'Σ': [0xf6], u'π': [0xf7], u'千': [0xfa], u'万': [0xfb], u'円': [0xfc], u'÷': [0xfd], u' ': [0xfe], u' ': [0xfe], u'■': [0xff], u'ガ': [0xb6, 0xde], u'ギ': [0xb7, 0xde], u'グ': [0xb8, 0xde], u'ゲ': [0xb9, 0xde], u'ゴ': [0xba, 0xde], u'ザ': [0xbb, 0xde], u'ジ': [0xbc, 0xde], u'ズ': [0xbd, 0xde], u'ゼ': [0xbe, 0xde], u'ゾ': [0xbf, 0xde], u'ダ': [0xc0, 0xde], u'ヂ': [0xc1, 0xde], u'ヅ': [0xc2, 0xde], u'デ': [0xc3, 0xde], u'ド': [0xc4, 0xde], u'バ': [0xca, 0xde], u'ビ': [0xcb, 0xde], u'ブ': [0xcc, 0xde], u'ベ': [0xcd, 0xde], u'ボ': [0xce, 0xde], u'パ': [0xca, 0xdf], u'ピ': [0xcb, 0xdf], u'プ': [0xcc, 0xdf], u'ペ': [0xcd, 0xdf], u'ポ': [0xce, 0xdf], }
""" ......................Static................................... class Bank(): @staticmethod def Banking(Attr): print("Welcome to Banking") print("It is Static Method") print("Pass Attribute :",Attr) BB=Bank() BB.Banking("Citi") BB.Banking("BOA") .........................GarbageCollection.................. """ class Dog(): def Sound(self): print("Bark") class Cat(): def Sound(self): print("Mew") def __del__(self): print("Destructor") d=Dog() d.Sound() c=Cat() c.Sound() del c
""" # The data in these tables were mostly sourced from Free60 and various forums and tools. # In particular the tool Le Fluffie was helpful # Some data has been verified, some changed and some has yet to be used. """ class STFSHashInfo(object): """ Whether the block represented by the BlockHashRecord is used, free, old or current """ types = { 0x00: "Unused", 0x40: "Freed", 0x80: "Old", 0xC0: "Current" } types_list = ["Unused", "Allocated Free", "Allocated In Use Old", "Allocated In Use Current"] class GamerTagConstants(object): """ GamerZone and Region mappings """ GamerZone = { 0: "Xbox", 1: "Recreation", 2: "Pro", 3: "Family", 4: "Underground", 5: "Cheater" } Region = { 0: "None", 1: "United Arab Emirates", 2: "Albania", 3: "Armenia", 4: "Argentina", 5: "Austria", 6: "Australia", 7: "Azerbaijan", 8: "Belgium", 9: "Bahrain", 10: "Brunei Darussalam", 11: "Bolivia", 12: "Brazil", 13: "Belarus", 14: "Belize", 15: "Canada", 16: "Unknown1", 17: "Switzerland", 18: "Chile", 19: "China", 20: "Colombia", 21: "Costa Rica", 22: "Czech Republic", 23: "Germany", 24: "Denmark", 25: "Dominican Republic", 26: "Algeria", 27: "Ecuador", 28: "Estonia", 29: "Egypt", 30: "Spain", 31: "Finland", 32: "Faroe Islands", 33: "France", 34: "Great Britain", 35: "Georgia", 36: "Greece", 37: "Guatemala", 38: "Hong Kong", 39: "Honduras", 40: "Croatia", 41: "Hungary", 42: "Indonesia", 43: "Ireland", 44: "Israel", 45: "India", 46: "Iraq", 47: "Iran", 48: "Iceland", 49: "Italy", 50: "Jamaica", 51: "Jordan", 52: "Japan", 53: "Kenya", 54: "Kyrgyzstan", 55: "Korea", 56: "Kuwait", 57: "Kazakhstan", 58: "Lebanon", 59: "Liechtenstein", 60: "Luxembourg", 61: "Latvia", 62: "Libya", 63: "Morocco", 64: "Monaco", 65: "Macodonia", 66: "Mongolia", 67: "Macao", 68: "Maldives", 69: "Mexico", 70: "Malaysia", 71: "Nicaragua", 72: "Netherlands", 73: "Norway", 74: "New Zealand", 75: "Oman", 76: "Panama", 77: "Peru", 78: "Philippines", 79: "Pakistan", 80: "Poland", 81: "Puerto Rico", 82: "Portugal", 83: "Paraguay", 84: "Qatar", 85: "Romania", 86: "Russian Federation", 87: "Saudi Arabia", 88: "Sweden", 89: "Singapore", 90: "Slovenia", 91: "Slovak Republic", 92: "Unknown 2", 93: "El Salvador", 94: "Syria", 95: "Thailand", 96: "Tunisia", 97: "Turkey", 98: "Trinidad Tobago", 99: "Taiwan", 100: "Ukraine", 101: "United States", 102: "Urugay", 103: "Uzbekistan", 104: "Venezuela", 105: "Viet Nam", 106: "Yemen", 107: "SouthAfrica", 108: "Zimbabwe" } class GPDID(object): """GPID descriptions""" types = { 0x8000: "This Title", 0x10040000: "Permissions", 0x10040002: "Y Axis Inversion", 0x10040003: "Controller Vibration Settings", 0x63E80044: "Avatar Information", 0x63E83FFF: "Title Specific Setting 1", 0x63E83FFE: "Title Specific Setting 2", 0x63E83FFD: "Title Specific Setting 3", 0x10040004: "GamerZone", 0x10040005: "Region", 0x10040006: "Gamerscore", 0x10040007: "Presence State (Unknown)", 0x10040008: "Camera", 0x5004000B: "Reputation", 0x1004000C: "Mute Setting", 0x1004000D: "Voice Output Speakers", 0x1004000E: "Voice Volume Setting", 0x4064000F: "Gamer Picture Reference", 0x40640010: "Personal Picture Reference", 0x402C0011: "Motto", 0x10040012: "Titles Played", 0x10040013: "Achievements Unlocked", 0x10040015: "Difficulty Setting", 0x10040018: "Control Sensitivity", 0x1004001D: "Preferred Color 1", 0x1004001E: "Preferred Color 2", 0x10040022: "Auto Aim", 0x10040024: "Auto Center", 0x10040024: "Action Movement Control", 0x10040038: "Gamerscore Earned On Title", 0x10040039: "Achievements Unlocked on Title", 0x1004003A: "User Tier (Unknown)", 0x1004003B: "Has Messanger Account", 0x1004003C: "Messanger Auto Signin", 0x1004003D: "Save Live Password", 0x1004003E: "Public Friends List", 0x1004003F: "Service Type (Unknown)", 0x41040040: "Account Name", 0x40520041: "Account Location", 0x41900042: "Gamercard URL", 0x43E80043: "Account Bio", 0x10000000: "Sync ID Table", 0x20000000: "Sync Record", 0x10042004: "Xbox.com Favorite Game (1)", 0x10042005: "Xbox.com Favorite Game (2)", 0x10042006: "Xbox.com Favorite Game (3)", 0x10042007: "Xbox.com Favorite Game (4)", 0x10042008: "Xbox.com Favorite Game (5)", 0x10042009: "Xbox.com Favorite Game (6)", 0x1004200A: "Xbox.com Platforms Owned", 0x1004200B: "Xbox.com Connection Speed", 0x700803F4: "User Crux Last Change Time (Unknown)" } class ContentTypes: """ STFS Content Types mapping """ types = { 0xD0000: "Arcade Title", 0x9000: "Avatar Item", 0x40000: "Cache File", 0x2000000: "Community Game", 0x80000: "Game Demo", 0x20000: "Gamer Picture", 0xA0000: "Game Title", 0xC0000: "Game Trailer", 0x400000: "Game Video", 0x4000: "Installed Game", 0xB0000: "Installer", 0x2000: "IPTV Pause Buffer", 0xF0000: "License Store", 0x2: "Marketplace Content", 0x100000: "Movie", 0x300000: "Music Video", 0x500000: "Podcast Video", 0x10000: "Profile", 0x3: "Publisher", 0x1: "Saved Game", 0x50000: "Storage Download", 0x30000: "Theme", 0x200000: "TV", 0x90000: "Video", 0x600000: "Viral Video", 0x70000: "Xbox Download", 0x5000: "Xbox Original Game", 0x60000: "Xbox Saved Game", 0x1000: "Xbox 360 Title", 0x5000: "Xbox Title", 0xE0000: "XNA" }
def valida(digitos): # digitos = [4,5,7,5,0,8,0,0,0] # digitos = [11] * 9 i = 1 soma = 0 for x in digitos: soma = soma +(i * x) i += 1 return bool( soma % 11 == 0) print(valida(1))
{ "targets": [{ "target_name": "OpenSSL_EVP_BytesToKey", "sources": [ "./test/main.cc", ], "cflags": [ "-Wall", "-Wno-maybe-uninitialized", "-Wno-uninitialized", "-Wno-unused-function", "-Wextra" ], "cflags_cc+": [ "-std=c++0x" ], "include_dirs": [ "/usr/local/include", "<!(node -e \"require('nan')\")" ], "conditions": [ [ "OS=='mac'", { "libraries": [ "-L/usr/local/lib" ], "xcode_settings": { "MACOSX_DEPLOYMENT_TARGET": "10.7", "OTHER_CPLUSPLUSFLAGS": [ "-stdlib=libc++" ] } } ] ] }] }
class Car: """Unit under test.""" def __init__(self, speed): self.speed = speed def getSpeed(self): return self.speed def brake(self): self.speed = 0
def catalan_number(n): nm = dm = 1 for k in range(2, n+1): nm, dm = ( nm*(n+k), dm*k ) return nm/dm print([catalan_number(n) for n in range(1, 16)]) [1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]
"""Shows options""" def show_options(): options = ["\nYour options are below.", "\nEnter: '<rooms>' to show a list of rooms", "\nEnter: '<create> room_name' to create a room and assign it a name.", "\nEnter: '<join> room_name' to join an existing chat room.", "\nEnter: '<users>' to list the users' names in your current room.", "\nEnter: '<leave>' to leave your current room." ] return options
prato = 5 pilha = list(range(1,prato + 1)) while True: print(' existem %d pratos na pilha '%len(pilha)) print('''pilha atual = {} digite E para adicionar um novo prato a pilha, ou D para lavar um prato. S para sair''') op = str(input('qual operaçao você deseja :'.format(pilha))).upper() if op == 'E': prato+= 1 pilha.append(prato) if op == 'D': if (len(pilha))>0: lavado = pilha.pop(-1) print('prato {} lavados'.format(lavado)) elif op == 'S': print('obrigado por ultlzar nossos serviços') break
def test(): assert ( "doc1.similarity(doc2)" or "doc2.similarity(doc1)" in __solution__ ), "Você está comparando a similaridade entre os dois documentos?" assert ( 0 <= float(similarity) <= 1 ), "O valor da similaridade deve ser um número de ponto flutuante. Você fez este cálculo corretamente?" __msg__.good("Muito bem!")
""" link: https://leetcode-cn.com/problems/design-snake-game problem: 模拟贪吃蛇游戏。 solution: 模拟。双端队列 + 哈希表,维护当前贪吃蛇所占的位置。 """ class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): self.foods = food self.score = 0 self.w = width self.h = height self.body = collections.deque() self.body.append((0, 0)) self.visit = set() self.visit.add((0, 0)) def move(self, direction: str) -> int: m = { "U": (-1, 0), "D": (1, 0), "L": (0, -1), "R": (0, 1), } ii, jj = m[direction] next_p = (self.body[-1][0] + ii, self.body[-1][1] + jj) if (not (0 <= next_p[0] < self.h and 0 <= next_p[1] < self.w)) or ( next_p != tuple(self.body[0]) and next_p in self.visit): return -1 self.body.append(next_p) self.visit.add(next_p) if self.score < len(self.foods) and next_p == tuple(self.foods[self.score]): self.score += 1 else: if next_p != self.body[0]: self.visit.remove(self.body[0]) self.body.popleft() return self.score
"""Constants for pyskyqremote- DE.""" SCHEDULE_URL = "https://www.sky.de/sgtvg/service/getBroadcasts" LIVE_IMAGE_URL = "https://www.sky.de{0}" PVR_IMAGE_URL = "https://www.sky.de{0}" CHANNEL_IMAGE_URL = "https://www.sky.de{0}" TIMEZONE = "Europe/Berlin" CHANNEL_URL = "https://raw.githubusercontent.com/RogerSelwyn/skyq_remote/master/pyskyqremote/country/channels-de.json" # pylint: disable=line-too-long
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. load("@com_google_api_codegen//rules_gapic:gapic.bzl", "gapic_srcjar", "unzipped_srcjar") def _cc_gapic_postprocessed_srcjar_impl(ctx): gapic_zip = ctx.file.gapic_zip output_main = ctx.outputs.main output_main_h = ctx.outputs.main_h output_dir_name = ctx.label.name output_dir_path = "%s/%s" % (output_main.dirname, output_dir_name) script = """ unzip -q {gapic_zip} -d {output_dir_path} # TODO: Call formatter here pushd {output_dir_path} zip -q -r {output_dir_name}-h.srcjar . -i ./*.gapic.h find . -name "*.gapic.h" -delete zip -q -r {output_dir_name}.srcjar . -i ./*.cc -i ./*.h popd mv {output_dir_path}/{output_dir_name}-h.srcjar {output_main_h} mv {output_dir_path}/{output_dir_name}.srcjar {output_main} rm -rf {output_dir_path} """.format( gapic_zip = gapic_zip.path, output_dir_name = output_dir_name, output_dir_path = output_dir_path, output_main = output_main.path, output_main_h = output_main_h.path, ) ctx.actions.run_shell( inputs = [gapic_zip], command = script, outputs = [output_main, output_main_h], ) _cc_gapic_postprocessed_srcjar = rule( _cc_gapic_postprocessed_srcjar_impl, attrs = { "gapic_zip": attr.label(mandatory = True, allow_single_file = True), }, outputs = { "main": "%{name}.srcjar", "main_h": "%{name}-h.srcjar", }, ) def cc_gapic_srcjar(name, src, package, **kwargs): raw_srcjar_name = "%s_raw" % name gapic_srcjar( name = raw_srcjar_name, src = src, package = package, output_suffix = ".zip", gapic_generator = Label("//generator:protoc-gen-cpp_gapic"), **kwargs ) _cc_gapic_postprocessed_srcjar( name = name, gapic_zip = ":%s" % raw_srcjar_name, **kwargs ) def cc_gapic_library(name, src, package, deps = [], **kwargs): srcjar_name = "%s_srcjar" % name cc_gapic_srcjar( name = srcjar_name, src = src, package = package, **kwargs ) actual_deps = deps + [ "@com_google_gapic_generator_cpp//gax:gax", ] main_file = ":%s.srcjar" % srcjar_name main_dir = "%s_main" % srcjar_name unzipped_srcjar( name = main_dir, srcjar = main_file, extension = "", **kwargs ) main_h_file = ":%s-h.srcjar" % srcjar_name main_h_dir = "%s_h_main" % srcjar_name unzipped_srcjar( name = main_h_dir, srcjar = main_h_file, extension = "", **kwargs ) native.cc_library( name = name, srcs = [":%s" % main_dir], deps = actual_deps, hdrs = [":%s" % main_h_dir], includes = [main_h_dir], # cc_library generates an empty .so file, making dynamic linking # impossible. This may be caused by us using a directory (instead of # exact files) as srcs input. linkstatic = True, **kwargs )
NAME = 'weather.py' ORIGINAL_AUTHORS = [ 'Gabriele Ron' ] ABOUT = ''' A plugin to get the weather of a location ''' COMMANDS = ''' >>> .weather <city> <country code> returns the weather ''' WEBSITE = ''
class Node: def __init__(self, value): self.value = value self.next = None class LinkList: def __init__(self, value): node = Node(value) self.head = node self.tail = node self.length = 1 def append(self, value): node = Node(value) if self.length == 0: self.head = node self.tail = node else: self.tail.next = node self.tail = node self.length += 1 return True def prepend(self, value): node = Node(value) if self.length == 0: self.head = node self.tail = node else: node.next = self.head self.head = node self.length += 1 return True def pop(self): if self.length == 0: return None if self.length == 1: temp = self.head self.head = None self.tail = None self.length -= 1 return temp temp = self.head while temp.next != self.tail: temp = temp.next pop = self.tail self.tail = temp self.tail.next = None self.length -= 1 return pop def pop_first(self): if self.length == 0: return None if self.length == 1: temp = self.head self.head = None self.tail = None self.length -= 1 return temp temp = self.head self.head = temp.next temp.next = None self.length -= 1 return temp def get(self, index): if index < 0 or index >= self.length: return None temp = self.head for _ in range(index): temp = temp.next return temp def set_value(self, value, index): temp = self.get(index) if temp: temp.value = value return True return False def insert(self, value, index): if index < 0 or index > self.length: return False if index == 0: return self.prepend(value) node = Node(value) temp = self.get(index - 1) node.next = temp.next temp.next = node self.length += 1 return True def remove(self, index): if index < 0 or index >= self.length: return None if index == 0: return self.pop_first() temp = self.get(index - 1) node = temp.next temp.next = node.next node.next = None self.length -= 1 return node def reverse(self): temp = self.head self.head = self.tail self.tail = temp before = None after = temp.next for _ in range(self.length): after = temp.next temp.next = before before = temp temp = after return True def __str__(self): answer = str() temp = self.head while temp: answer += str(temp.value) + " " temp = temp.next return answer
class node: def __init__(self,val): self.val = val self.next = None self.prev = None class mylinkedlist: def __init__(self): self.head = None self.tail = None self.size = 0 def get(self,index): if index < 0 or index >= self.size: return -1 cur = self.head while index != 0: cur = cur.next index = index -1 return cur.val def addathead(self,val): new_node = node(val) if self.head is None: self.head = new_node self.tail = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node self.size = self.size + 1 def addatTail(self,val): new_node = node(val) if self.tail is None: self.head = new_node self.tail = new_node else: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node self.size = self.size + 1 def addatIndex(self,index,val): if index < 0 or index >= self.size: return -1 elif index ==0: self.addathead(val) elif index == self.size: self.addatTail(val) else: cur = self.head while index-1 != 0: cur = cur.next index -= 1 new_node = node(val) new_node.next = cur.next cur.next.prev = new_node cur.next = new_node new_node.prev = cur self.size = self.size +1 def deleteatIndex(self,index,val): if index < 0 or index >= self.size: return -1 elif index == 0: cur = self.head.next if cur: cur.prev = None self.head = self.head.next self.size -= 1 if self.size == 0: self.tail = None elif index == self.size-1: cur = self.tail.prev if cur: cur.next = None self.tail = self.tail.prev size -= 1 if self.size == 0: self.head = None else: cur = self.head while index-1 != 0: cur = cur.next index -= 1 cur.next = cur.next.next cur.next.prev = cur self.size -=1
#declaring variable as string phrase = str(input('Type a phrase: ')) #saving the phrase in lowercase phrase = phrase.lower() #presenting amount of lettters 'a' print('Amount of letters "a": ', phrase.count('a')) #presenting the position of firt 'a' print('Firt "A" in position: ', phrase.find('a')) #presenting the position of last 'a' whith 'right find' print('Last "A" in postion: ',phrase.rfind('a'))
# listas ficam entre [] # listas podem ser MUTÁVEIS # lista.append(x) -- inclui o elemento 'x' ao final da lista previamente preenchida # lista.insert(0, x) -- o elemento 'x' é incluído na posição indicada '0' (e não ao final da lista), empurrando os demais elementos para frente. Sempre recebe DOIS VALORES. # del lista[x] -- elimina o item da lista na posição indicada 'x' # lista.pop(x) -- elimina o item da lista na posição indicada 'x' -- se nada for indicado no índice '()', o último elemento é eliminado # lista.remove('x') -- elimina a primeira ocorrência do item indicado no índice, 'x' # lista[x] = y -- o elemento 'x' da lista é substituído pelo elemento 'y' # if item in lista: -- condiciona uma operação à certeza do item na lista. p. ex: if item in lista: / lista.remove[item] # lista = list(range(1, 11)) -- o comando 'list' cria uma lista com o uso do 'range' # lista.sort() -- ordena os elementos de uma lista # lista.sort(reverse=True) -- ordena os elementos de uma lista em ordem inversa # len(lista) -- mostra quantos elementos existem na lista # for item in lista: / print(item) -- executa a operação para cada item da lista # for item in enumerate(lista): / print(item) -- mostra a posição do item na lista e o valor do item (em forma de tupla). # CONT... 'for posição, item in enumerate(lista):' / print(posição, item) -- retorna a posição do item e o valor do item da lista. # lista = list() / for c in range(0, 5): / lista.append(int(input('Digite um valor: '))) -- a lista é formada com 'range' via teclado # listaA = [1, 2, 3, 4] / listaB = listaA -- listaB == [1, 2, 3, 4] # CONT... listaB[0] = 9 / print(listaA, listaB) / resultado = [9, 2, 3, 4] / [9, 2, 3, 4] -- OU SEJA, as duas listas mudam juntas, pois estão 'LIGADAS'! # CONT... listaB = listaA[:] -- todos os elementos de listaA são COPIADOS para listaB # CONT... listaB[0] = 9 / print(listA, listaB) / resultado = [1, 2, 3, 4] / [9, 2, 3, 4] expre = input('Digite a expressão: ') abre = 0 fecha = 0 while True: if expre[0] == ')': print('ERRADO') break else: for simb in expre: if simb == '(': abre += 1 elif simb == ')': fecha += 1 if abre == fecha: print('CORRETO') else: print('INCORRETO') break
{ "targets": [ { "target_name": "json", "product_name": "json", "variables": { "json_dir%": "../" }, 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ], 'conditions': [ ['OS=="mac"', { 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' } }] ], "type": "static_library", "include_dirs": [ "<(json_dir)/", "<(json_dir)/JSON", "<(json_dir)/JSON/src" ], "sources": [ "<(json_dir)/JSON/json.h", "<(json_dir)/JSON/src/autolink.h", "<(json_dir)/JSON/src/config.h", "<(json_dir)/JSON/src/features.h", "<(json_dir)/JSON/src/forwards.h", "<(json_dir)/JSON/src/json_batchallocator.h", "<(json_dir)/JSON/src/json_tool.h", "<(json_dir)/JSON/src/reader.h", "<(json_dir)/JSON/src/value.h", "<(json_dir)/JSON/src/writer.h", "<(json_dir)/JSON/src/json_internalarray.inl", "<(json_dir)/JSON/src/json_internalmap.inl", "<(json_dir)/JSON/src/json_valueiterator.inl", "<(json_dir)/JSON/src/json_reader.cpp", "<(json_dir)/JSON/src/json_value.cpp", "<(json_dir)/JSON/src/json_writer.cpp" ], "all_dependent_settings": { "include_dirs": [ "<(json_dir)/JSON" ] } } ], "variables": { "conditions": [ [ "OS == 'mac'", { "target_arch%": "x64" }, { "target_arch%": "ia32" } ] ] }, "target_defaults": { "default_configuration": "Release", "defines": [ ], "conditions": [ [ "OS == 'mac'", { "defines": [ "DARWIN" ] }, { "defines": [ "LINUX" ] } ], [ "OS == 'mac' and target_arch == 'x64'", { "xcode_settings": { "ARCHS": [ "x86_64" ] } } ] ], "configurations": { "Debug": { "cflags": [ "-g", "-O0" ], "xcode_settings": { "OTHER_CFLAGS": [ "-g", "-O0" ], "OTHER_CPLUSPLUSFLAGS": [ "-g", "-O0" ] } }, "Release": { "cflags": [ "-O3" ], "defines": [ "NDEBUG" ], "xcode_settings": { "OTHER_CFLAGS": [ "-O3" ], "OTHER_CPLUSPLUSFLAGS": [ "-O3", "-DNDEBUG" ] } } } } }
todos = [] impar = [] par = [] while True: todos.append(int(input('Digite um valor: '))) soun = str(input('Quer adicionar mais ? [S/N] ')).strip()[0] if soun in 'Nn': break for n in todos: if n % 2 == 0: par.append(n) for v in todos: if v % 2 != 0: impar.append(v) print('=' * 40) print(f'Os numeros digitados sao estes {todos}') print(f'Os pares sao {par}.\nE os impares sao {impar}.')
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ num = "1" for _ in range(1, n): digit = num[0] count = 1 newNum = "" for j in range(1, len(num)): if num[j] == digit: count += 1 else: newNum += str(count) + digit digit = num[j] count = 1 newNum += str(count) + digit num = newNum return num
def print_formatted(N): width = len(bin(N)[2:]) for i in range(1, N + 1): print(' '.join(map(lambda x: x.rjust(width), [str(i), oct(i)[2:], hex(i)[2:].upper(), bin(i)[2:]]))) if __name__ == '__main__': n = int(input()) print_formatted(n)
class File: def __init__(self, hash, realName, extension, url): self.hash = hash self.realName = realName self.extension = extension self.url = url @staticmethod def from_DB(record): return File(record[0], record[1], record[2], record[3])
""" This module contains the utility functions for the main module. """ def request_type(request): """ If the request is for multiple addresses, build a str with separator """ if isinstance(request, list): # If the list is ints convert to string. to_string = ''.join(str(e) for e in request) # Finally build one string of the list. request = ",".join(to_string) return request # def have_confs(confirmations): # """ If the request has URI params we add them to the request string """ # confs = {'confirmations': confirmations} # if confs['confirmations'] > 0: # return True # else: # return False
class TicTacToe: def __init__(self) -> None: """ Create TicTacToe Game logic """ self.tic_board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] self.turn = True def play(self, x: int, y: int) -> bool: """ Playes one move for each player Args: x (int): x coords for place to play y (int): y coords for place to play Returns: bool: True if you can play the move else False """ if self.tic_board[x][y] != " ": return False if self.turn: self.tic_board[x][y] = "X" else: self.tic_board[x][y] = "O" self.turn = not self.turn return True def isMovesLeft(self) -> bool: """ Checks if any moves is left Returns: bool: True if there are any left moves """ for i in range(len(self.tic_board)): for j in range(len(self.tic_board[0])): if (self.tic_board[i][j] == " "): return True return False def movesLeft(self) -> int: """ Gets the number of moves left Returns: int: The number of empty cells """ sum = 0 for i in range(len(self.tic_board)): for j in range(len(self.tic_board[0])): if (self.tic_board[i][j] == " "): sum += 1 return sum def win(self) -> str: """ Function for when the player wins Returns: str: player X wins or player O wins """ check_x = ["X", "X", "X"] check_o = ["O", "O", "O"] win_x = "X wins" win_o = "O wins" for i in range(3): # check for horizontal wins if self.tic_board[i] == check_x: return win_x if self.tic_board[i] == check_o: return win_o # check for vertical wins if [row[i] for row in self.tic_board] == check_x: return win_x if [row[i] for row in self.tic_board] == check_o: return win_o # check for diagonals if [self.tic_board[i1][i1] for i1 in range(len(self.tic_board))] == check_x: return win_x if [self.tic_board[i1][i1] for i1 in range(len(self.tic_board))] == check_o: return win_o if [self.tic_board[i][len(self.tic_board[0])-i-1] for i in range(len(self.tic_board))] == check_x: return win_x if [self.tic_board[i][len(self.tic_board[0])-i-1] for i in range(len(self.tic_board))] == check_o: return win_o if not self.isMovesLeft(): return "Draw" return "" def __str__(self) -> str: """ToString method to print the class Returns: str: board in format ['', '', ''] ['', '', ''] ['', '', ''] """ return f"{self.tic_board[0]}\n{self.tic_board[1]}\n{self.tic_board[2]}" # Testing the TicTacToe class for bugs if __name__ == "__main__": game = TicTacToe() game.tic_board = [ ['X', 'O', 'O'], ['X', 'O', 'O'], ['X', 'X', 'X']] print(game) print(game.win())
class Node(object): def __init__(self, value, parent=None): self.value = value self.parent = parent def __eq__(self, other): if isinstance(other, Node): return self.value == other.value return NotImplemented def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.value) def __str__(self): return str(self.value) def lca(node1, node2): """ Return a least common ancestor. Memory and time complexity: O(s), where s is the distance between the two nodes. """ if not isinstance(node1, Node) or not isinstance(node2, Node): raise TypeError("Inputs should be a Node.") ancestors = set() while node1 or node2: if node1: if node1 in ancestors: return node1 else: ancestors.add(node1) node1 = node1.parent if node2: if node2 in ancestors: return node2 else: ancestors.add(node2) node2 = node2.parent raise Exception("Least common ancestor not found.") def main(): node1 = Node(1, None) node2 = Node(2, node1) node3 = Node(3, node1) node4 = Node(4, node2) node5 = Node(5, node2) node6 = Node(6, node3) node7 = Node(7, node3) node8 = Node(8, node4) node9 = Node(9, node4) print(lca(node1, node1)) # 1 print(lca(node7, node7)) # 7 print(lca(node1, node2)) # 1 print(lca(node8, node9)) # 4 print(lca(node8, node6)) # 1 print(lca(node5, node9)) # 2 if __name__ == '__main__': main()
''' 调用三个函数一个用来计算Y列表中最大的数最小的数第二个用来计算x列表中最大的数字和最小的数字第三个用来将y和x列表中的最大最小的数字打印出来 ''' def my_max(a): maxa = 3 for b in a: if b > maxa: maxa = b return maxa def my_min(a): mina = 100 for s in a: if s < mina: mina = s return mina def my_print(maxa, mina): print('最大值是:',maxa) print('最小值是:',mina) y = (3,69,52,8,5,4,9,7) maxyyy = my_max(y) minyyy = my_min(y) my_print(maxyyy, minyyy) x = (3,3,80,8,5,1,9,7) maxxx = my_max(x) minxx = my_min(x) my_print(maxxx, minxx)
class Vertex: def __init__(self, id): self.id = id self.edges = set() def outgoing_edges(self): for edge in self.edges: successor = edge.get_successor(self) if successor is not None: yield edge
''' Autor: Pedro Augusto Fatec Ferraz Objetivo: Estrutura de ifs encadeados para encontrar o mês a partir de um número ''' nmr_mes = int(input("Digite um número entre 1 e 12: ")) # deve se entrar com um valor entre 1 e 12 if nmr_mes > 0 and nmr_mes <= 12: # Com o operador end, podemos concatenar o valor do próximo print # de forma com que mostre dois dados com 1 linha. print('Valor válido, o mês escolhido foi:', end=' ') if nmr_mes == 1: print('Janeiro') elif nmr_mes == 2: print('Fevereiro') elif nmr_mes == 3: print('Março') elif nmr_mes == 4: print('Abril') elif nmr_mes == 5: print('Maio') elif nmr_mes == 6: print('Junho') elif nmr_mes == 7: print('Julho') elif nmr_mes == 8: print('Agosto') elif nmr_mes == 9: print('Setembro') elif nmr_mes == 10: print('Outubro') elif nmr_mes == 11: print('Novembro') elif nmr_mes == 12: print('Dezembro') else: print('Valor inválido...')
num = (int(input('Digite um numero: '))) tot = 0 for c in range(0, num): if num % (c + 1) == 0: print('\033[33m', end= ' ') tot = tot + 1 else: print('\033[31m', end= ' ') print(c + 1, end ='') print('', end= '\n') print('\033[mO numero {} foi divisivel {} vezes\033[m'.format(num, tot)) if tot == 2: print('\033[32mÉ um numero primo !\033[m') else: print('\033[31mNão é um numero primo !\033[m')
""" Test cases for micro-grid systems The following systems are considered 1. AC micro-grid 2. DC micro-grid 3. Hybrid AC/DC micro-grid """
# -*- coding: UTF-8 -*- light = input('input a light') if light == 'red': print('GoGoGO') elif light == 'green': print('stop')
# # LogicalDOCServer.py # # Copyright 2021 Yuichi Yoshii # 吉井雄一 @ 吉井産業 you.65535.kir@gmail.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def get_logicaldoc_server_addr() -> str: return '' def get_logicaldoc_server_port() -> str: return '' def get_logicaldoc_server_tenant() -> str: return 'logicaldoc' def get_logicaldoc_server_name() -> str: return get_logicaldoc_server_addr() \ + ':' + get_logicaldoc_server_port() \ + '/' + get_logicaldoc_server_tenant() + '/' def get_logicaldoc_url() -> str: return 'http://' + get_logicaldoc_server_name() def get_logicaldoc_auth_params() -> dict: return { 'u': '', 'pw': '', }
''' Resources/other/contact _______________________ Contact information for XL Discoverer. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. ''' __all__ = [ 'AUTHOR', 'AUTHOR_EMAIL', 'MAINTAINER', 'MAINTAINER_EMAIL' ] # EMAIL # ----- AUTHOR_EMAIL = 'ahuszagh@gmail.com' MAINTAINER_EMAIL = 'crosslinkdiscoverer@gmail.com' # PEOPLE # ------ AUTHOR = 'Alex Huszagh' MAINTAINER = 'Alex Huszagh'
# -* coding: utf-8 -*- """Numerical polynomial and multivariate polynomial library.""" __version__ = '0.0.1.dev0'
# Binary Tree Level Order Traversal - Breadth First Search 1 # Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelTraverse(self, node, level): if (level == len(self.levels)): self.levels.append([]) self.levels[level].append(node.val) if (node.left): self.levelTraverse(node.left, level + 1) if (node.right): self.levelTraverse(node.right, level + 1) def levelOrder(self, root): if not root: return [] self.levels = [] self.levelTraverse(root, 0) return self.levels # Time Complexity: O(N) # Space Complexity: O(N)
# ---------- Model Setting ---------- # model = dict( type='ImageClassifier', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(3, ), style='pytorch', # frozen_stages=2, # 冻结前两层参数 init_cfg=dict( type='Pretrained', checkpoint='torchvision://resnet50', ) ), neck=dict(type='GlobalAveragePooling'), head=dict( type='LinearClsHead', num_classes=2, in_channels=2048, loss=dict(type='CrossEntropyLoss', loss_weight=1.0), topk=(1,),)) # ---------- Training Setting ---------- # optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='step', step=[10, 20]) runner = dict(type='EpochBasedRunner', max_epochs=30) # checkpoint saving checkpoint_config = dict(interval=5,) # yapf:disable log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook') ]) # yapf:enable dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None resume_from = None workflow = [('train', 1)] # ---------- Schedules Setting ---------- # # optimizer optimizer_config = dict(grad_clip=None) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) # ---------- Dataset Setting ---------- # dataset_type = 'Gender_Dataset' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='RandomCrop', size=(128, 64), padding=4), dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'), dict(type='Resize', size=(256, 128)), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='ToTensor', keys=['gt_label']), dict(type='Collect', keys=['img', 'gt_label']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict(type='Resize', size=(256, 128)), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ] data = dict( samples_per_gpu=64, workers_per_gpu=2, train=dict( type=dataset_type, data_prefix='/data/workspace_robert/par_dataset/Market-1501-v15.09.15/v1/mm/gender/train', ann_file='/data/workspace_robert/par_dataset/Market-1501-v15.09.15/v1/mm/gender/meta/train.txt', pipeline=train_pipeline), val=dict( type=dataset_type, data_prefix='/data/workspace_robert/par_dataset/Market-1501-v15.09.15/v1/mm/gender/val', ann_file='/data/workspace_robert/par_dataset/Market-1501-v15.09.15/v1/mm/gender/meta/val.txt', pipeline=test_pipeline), test=dict( type=dataset_type, data_prefix='/data/workspace_robert/par_dataset/Market-1501-v15.09.15/v1/mm/gender/val', ann_file='/data/workspace_robert/par_dataset/Market-1501-v15.09.15/v1/mm/gender/meta/val.txt', pipeline=test_pipeline)) evaluation = dict( interval=5, metric=['accuracy', 'recall', 'precision'], save_best='accuracy_top-1', metric_options={'topk': (1,)} )
# Seasons.py -- Hass helper python_script to turn a Climate entity into a smart # thermostat, with support for multiple thermostats each having their own # schedule. # # INPUTS: # * climate_unit (required): The Climate entity to be controlled # * global_mode (required): an entity whose state is the desired global climate # mode (usually an input_select) # * state_entity (required): an input_text entity, unique to this climate_unit, # where the script can store some information between runs. # * at_home_sensor (optional): an entity that represents whether anyone is home # (usually a binary_sensor) # * from_timer (optional): whether the script was triggered by timer. If true, # only changes that modify the last-set operation mode or setpoint take # effect. This is done so that manual changes are left alone until the next # schedule switch. # # The last input is the 'seasons' dictionary as defined below, which defines the # scheduled behavior for each global mode / climate unit combination. It's a # dictionary keyed by a tuple of global mode and climate unit. Each entry is a # list of schedules, where each schedule has the following fields: # * title: Used only for logging and to help you find the right entry for edits # * time_on / time_off (optional): Start and stop of this schedule, 24-hour # hours:minutes. If not given, this schedule is always active (though see # window and if_away/if_home below) # * days: (optional): String defining days of week this schedule is active, matched # on the schedule's start time. Seven characters, dash or dot if not active, any # other character if active. You can use 0123456 or MTWTFSS or whatever you like. # Monday is first, following Python datetime convention. # * operation (required): The operating mode for this schedule, one of the modes # supported by your climate entity. # * setpoint (optional): The desired temperature for this schedule. Some modes # (e.g. 'dry' dehumidifaction) don't require a setpoint so it's optional # * window (optional): If given, if this entity's state is 'on' (i.e. the given # window is open), the schedule will act as if its operation mode is 'off'. # This is so you don't attempt to heat/cool the great outdoors if you left the # window open for some fresh air. # * if_away / if_home (optional): If present, this schedule will only apply if # the at_home_sensor state matches (true meaning someone is home). If no # at_home_sensor is given, these are both always false. # * humidity_sensor (optional): See if_humid. Note: could also be some other # type of sensor, like dewpoint. # * if_humid (optional): Percentage. If present, this schedule will only apply # if the humidity reported by the humidity_sensor is above this value at the # beginning of the period. # # Put this script in <config>/python_scripts (create the directory if needed) # and activate it as described at # https://www.home-assistant.io/components/python_script/ . # You should set up automations to call service python_script.seasons for each # relevant climate unit for the each of the following events: # * your global_mode entity changes (all climate units) # * your at_home_sensor changes (all climate units) # * your window sensor(s) change(s) (relevant climate units) # * on a time_interval, suggested every 15 minutes. (all climate units). This # interval is the resolution of your scheduled changes, so make it more or # less frequent as required. SEASONS = { ('Cold Winter', 'climate.first_floor_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Cold Winter', 'climate.second_floor'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Cold Winter', 'climate.loft_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Winter', 'climate.first_floor_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Winter', 'climate.second_floor'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Winter', 'climate.master_br'): [ { 'title': 'Winter Sleeping', 'time_on': '21:29', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 64 } ], ('Winter', 'climate.loft_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Cold Shoulder', 'climate.first_floor_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Cold Shoulder', 'climate.master_br'): [ { 'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 67 }, { 'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68 }, { 'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 64 }, { 'title': 'Day (Away)', 'time_on': '07:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 62 }, { 'title': 'Day (Home)', 'time_on': '07:59', 'time_off': '17:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68 }, { 'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'if_away': True, 'setpoint': 62 }, { 'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68 } ], ('Cold Shoulder', 'climate.loft_heat'): [ { 'title': 'Morning Boost', 'operation': 'heat', 'time_on': '06:59', 'time_off': '07:44', 'window': 'binary_sensor.skylight', 'setpoint': 68 } ], ('Cold Shoulder', 'climate.loft'): [ { 'title': 'Night', 'operation': 'heat', 'time_on': '00:04', 'time_off': '07:14', 'window': 'binary_sensor.skylight', 'setpoint': 61 }, { 'title': 'Day (Weekday)', 'days': 'MTWTF..', 'operation': 'heat', 'time_on': '07:14', 'time_off': '16:59', 'window': 'binary_sensor.skylight', 'setpoint': 68 }, { 'title': 'Day (Weekend)', 'days': '.....SS', 'operation': 'heat', 'time_on': '08:59', 'time_off': '16:59', 'window': 'binary_sensor.skylight', 'setpoint': 62 }, { 'title': 'Evening', 'operation': 'heat', 'time_on': '16:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 63 } ], ('Warm Shoulder', 'climate.first_floor'): [ { 'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Pre-Sleeping', 'time_on': '21:44', 'time_off': '21:59', 'operation': 'heat', 'setpoint': 62 }, { 'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 62 }, { 'title': 'Day (Away)', 'time_on': '08:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'setpoint': 62 }, { 'title': 'Day (Home)', 'time_on': '08:59', 'time_off': '17:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'if_away': True, 'setpoint': 62 }, { 'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'setpoint': 69 } ], ('Warm Shoulder', 'climate.master_br'): [ { 'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 67 }, { 'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Pre-Sleeping', 'time_on': '21:44', 'time_off': '21:59', 'operation': 'heat', 'setpoint': 64 }, { 'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 64 }, { 'title': 'Day (Away)', 'time_on': '08:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'setpoint': 62 }, { 'title': 'Day (Home)', 'time_on': '08:59', 'time_off': '17:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'if_away': True, 'setpoint': 62 }, { 'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'setpoint': 68 } ], ('Warm Shoulder', 'climate.loft'): [ { 'title': 'Night', 'operation': 'heat', 'time_on': '00:04', 'time_off': '07:29', 'window': 'binary_sensor.skylight', 'setpoint': 61 }, { 'title': 'Day (Weekday)', 'days': 'MTWTF..', 'operation': 'heat', 'time_on': '07:29', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 68 }, { 'title': 'Day (Weekend)', 'days': '.....SS', 'operation': 'heat', 'time_on': '08:59', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 62 }, { 'title': 'Evening', 'operation': 'heat', 'time_on': '17:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 63 } ], ('Normal Summer', 'climate.master_br'): [ { 'title': 'Dehumidify', 'time_on': '19:59', 'time_off': '20:59', 'operation': 'dry', 'humidity_sensor': 'sensor.dewpoint_mbr', 'if_humid': 63, 'window': 'binary_sensor.bedroom_window', }, { 'title': 'Sleeping-early', 'time_on': '20:59', 'time_off': '02:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 73 }, { 'title': 'Sleeping-late', 'time_on': '02:59', 'time_off': '07:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 74 }, ], ('Hot Summer', 'climate.master_br'): [ { 'title': 'Dehumidify', 'time_on': '19:59', 'time_off': '20:59', 'operation': 'dry', 'humidity_sensor': 'sensor.dewpoint_mbr', 'if_humid': 63, 'window': 'binary_sensor.bedroom_window', }, { 'title': 'Sleeping-early', 'time_on': '20:59', 'time_off': '02:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 73 }, { 'title': 'Sleeping-late', 'time_on': '02:59', 'time_off': '07:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 74 }, { 'title': 'Day (Away)', 'time_on': '08:29', 'time_off': '19:44', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'if_away': True, 'setpoint': 78 }, { 'title': 'Day (Home)', 'time_on': '08:29', 'time_off': '19:44', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 76 }, ], ('Hot Summer', 'climate.loft'): [ { 'title': 'Night', 'operation': 'cool', 'time_on': '00:04', 'time_off': '08:59', 'window': 'binary_sensor.skylight', 'setpoint': 83 }, { 'title': 'Day (away)', 'operation': 'cool', 'time_on': '08:59', 'time_off': '17:59', 'if_away': True, 'window': 'binary_sensor.skylight', 'setpoint': 85 }, { 'title': 'Day', 'operation': 'cool', 'time_on': '08:59', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 80 }, { 'title': 'Evening', 'operation': 'cool', 'time_on': '17:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 81 } ], ('Hot Summer', 'climate.first_floor'): [ { 'title': 'Sleeping', 'time_on': '21:59', 'time_off': '05:59', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 78 }, { 'title': 'Day (Away)', 'time_on': '07:59', 'time_off': '15:59', 'operation': 'cool', 'window': 'binary_sensor.first_floor_windows', 'if_away': True, 'setpoint': 78 }, { 'title': 'Day (Home)', 'time_on': '05:59', 'time_off': '15:59', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 75 }, { 'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'cool', 'window': 'binary_sensor.first_floor_windows', 'if_away': True, 'setpoint': 78 }, { 'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 75 } ] } def is_time_between(begin_time, end_time, check_time): if begin_time < end_time: return begin_time <= check_time <= end_time # crosses midnight return check_time >= begin_time or check_time <= end_time def time_offset(orig_time, offset): hour = orig_time.hour minute = orig_time.minute minute = minute + offset if minute < 0: hour = hour - 1 minute = minute + 60 if minute > 60: hour = hour + 1 minute = minute - 60 if hour < 0: hour = hour + 24 if hour > 24: hour = hour - 24 return datetime.time(hour=hour, minute=minute) def day_of_start(start_time, end_time, check_time): today = datetime.datetime.now().weekday() # today if doesn't cross midnight or no actual times given if (not start_time) or (not end_time) or start_time <= end_time: return today # today if we're between start and midnight if start_time <= check_time: return today # Otherwise, yesterday return 6 if today == 0 else today - 1 saved_state = hass.states.get(data.get('state_entity')).state climate_unit = data.get('climate_unit', 'climate.master_br') current_mode = hass.states.get(data.get('global_mode')).state from_timer = data.get('from_timer', False) at_home_sensor = data.get('at_home_sensor') is_home = False is_away = False if at_home_sensor: is_home = hass.states.get(at_home_sensor).state == 'on' is_away = not is_home now = datetime.datetime.now().time() key = (current_mode, climate_unit) schedules = SEASONS.get(key) matched = False setpoint = None turn_on = False turn_off = False desired_operation = None title = None next_state = None if not schedules: logger.info("No schedules for {}".format(key)) else: for schedule in schedules: time_on_str = schedule.get('time_on') time_off_str = schedule.get('time_off') time_on = None time_off = None if time_on_str: time_on = datetime.datetime.strptime(time_on_str, '%H:%M').time() if time_off_str: time_off = datetime.datetime.strptime(time_off_str, '%H:%M').time() start_day = day_of_start(time_on, time_off, now) day_match = True days = schedule.get('days') if days and len(days) == 7: day_match = days[start_day] != '-' and days[start_day] != '.' in_interval = day_match and (((not time_on) or (not time_off) or is_time_between(time_on, time_off, now))) home_away_match = True if schedule.get('if_home'): home_away_match = is_home if schedule.get('if_away'): home_away_match = not is_home dry_exclude = False hs = schedule.get('humidity_sensor') if hs and schedule.get('if_humid'): dry_exclude = float(hass.states.get(hs).state) < float(schedule['if_humid']) if in_interval and home_away_match and not dry_exclude: # When we get here, we have schedules for this unit and # global mode and we're in this schedule's interval. # We will obey this schedule and ignore subsequent matches if not time_on: time_on = datetime.datetime.strptime('00:00', '%H:%M').time() window_open = False if schedule.get('window'): window_open = hass.states.get(schedule['window']).state == 'on' else: window_open = False decided = False matched = True next_state = "%s-%s" % (str(schedule.get('operation')), str(schedule.get('setpoint'))) same_next_state = (next_state == saved_state) if window_open: # Off if window is open turn_off = True title = schedule.get('title') + ' (Window open)' decided = True if (not decided) and from_timer and (not same_next_state): desired_operation = schedule.get('operation') if desired_operation == 'off': turn_off = True else: turn_on = True setpoint = schedule.get('setpoint') title = schedule.get('title') decided = True if not decided and (not from_timer): desired_operation = schedule.get('operation') if desired_operation == 'off': turn_off = True else: turn_on = True setpoint = schedule.get('setpoint') title = schedule.get('title') decided = True break if not matched and current_mode != "Manual": # If no schedules matched, turn off except in Manual next_state = "off-None" same_next_state = (next_state == saved_state) if (not from_timer) or (not same_next_state): turn_off = True title = 'Default (Off)' if turn_off: desired_operation = 'off' if desired_operation: logger.info("Setting {} to mode {} target {} from schedule {}".format( climate_unit, desired_operation, setpoint, title)) service_data = { "entity_id": climate_unit, "hvac_mode": desired_operation } hass.services.call('climate', 'set_hvac_mode', service_data, False) if setpoint: time.sleep(2.0) if '.' in str(setpoint): setpoint_num = float(setpoint) else: setpoint_num = int(setpoint) service_data = { "entity_id": climate_unit, "temperature": setpoint_num, "hvac_mode": desired_operation } hass.services.call('climate', 'set_temperature', service_data, False) if next_state: hass.states.set(data.get('state_entity'), next_state)
# -------------- # Code starts here class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2=['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class= class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses= {'Math':65,'English':70,'History':80,'French':70,'Science':60} total= 65+70+80+70+60 print(total) percentage= ((total)/500)*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics={'Geoffrey Hinton':78,'Andrew Ng':95,'Sebastian Raschka':65,'Yoshua Benjio':50, 'Hilary Mason':70,'Corinna Cortes':66,'Peter Warden':75} topper= max(mathematics,key=mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here first_name=(topper.split( )[0]) print(first_name) last_name=(topper.split( )[1]) print(last_name) #first_name=print(topper[0:6]) #last_name=print(topper[7:9]) full_name ='ng' +' '+ 'andrew' certificate_name=full_name.upper() print(certificate_name) #print(full_name) # Code ends here
a = 3 b = 5 print('Os valores são \033[32;44m{}\033[m e \033[31;44m{}\033[m!!!'.format(a, b))
# Init conventions for input generation ROT_DIR_REF = -1 CURRENT_DIR_REF = -1 PHASE_DIR_REF = -1 class InputError(Exception): """Raised when the input data are incomplete or incorrect""" pass
def join_bash_scripts(scripts): """ have the option of creating a wrapper script for every group of bash files to be run, or just join them on the fly. """ if len(scripts) < 2: raise NotImplementedError output_script = scripts[0] for script in scripts[1:]: output_script = output_script + ''.join(script.splitlines(True)[1:]) return output_script def open_files(filenames): """open files and return contents.""" return list(map(lambda file: open(file, 'r').read(), filenames))
def cria(linhas, colunas): return {'linhas': linhas, 'colunas': colunas, 'dados': {}} #[[0,3],[1,2]] def criaLst(matriz_lst): linhas = len(matriz_lst) #2 colunas = len(matriz_lst[0]) #2 dados = {} #{(0,1): 3, (1,0):1, (1,1):2} for i in range(linhas): for j in range(colunas): if matriz_lst[i][j] != 0: #Cast to int before dados[i,j] = matriz_lst[i][j] return {'linhas': linhas, 'colunas': colunas, 'dados': dados} def carrega(nome_arquivo): matriz_file = open(nome_arquivo, 'rt', encoding='utf8') linha_matriz = matriz_file.readline() matriz_lst = [] while linha_matriz != "": temp = '' linha_mat = [] for i in range(len(linha_matriz)): if linha_matriz[i] != ' ': temp += linha_matriz[i] elif len(temp) > 0: striped_temp = temp.strip() striped_temp = float(striped_temp) linha_mat.append(striped_temp) temp = '' if len(temp) > 0: striped_temp = temp.strip() striped_temp = float(striped_temp) linha_mat.append(striped_temp) matriz_lst.append(linha_mat) linha_matriz = matriz_file.readline() matriz_file.close() return criaLst(matriz_lst) def salva(tadMat, nome_arquivo): matriz_file = open(nome_arquivo, 'wt', encoding='utf8') linhas = tadMat['linhas'] colunas = tadMat['colunas'] linha_lst = [] for l in range(linhas): for c in range(colunas): linha_lst.append("{:.1f}".format(getElem(tadMat,l,c))) matriz_file.write(" ".join(linha_lst)+"\n") linha_lst.clear() matriz_file.close() return tadMat def destroi(): return None def getElem(tadMat, linha, coluna): chave = (linha,coluna) if linha < tadMat['linhas'] and coluna < tadMat['colunas']: if chave in tadMat['dados'].keys(): return tadMat['dados'][chave] else: return 0 else: return None def setElem(tadMat, linha, coluna, valor): chave = (linha,coluna) if linha < tadMat['linhas'] and coluna < tadMat['colunas']: if chave in tadMat['dados'].keys(): existente = tadMat['dados'][chave] else: existente = 0 if valor == 0 and existente == 0: return elif valor == 0 and existente != 0: del tadMat['dados'][linha, coluna] elif valor != 0 and existente == 0: tadMat['dados'][linha, coluna] = valor elif valor != 0 and existente != 0: tadMat['dados'][linha, coluna] = valor else: return None def subtracao(tadMatA, tadMatB): #User o getElem e o setElem vai facilitar linhasA = tadMatA['linhas'] colunasA = tadMatA['colunas'] if (linhasA == tadMatB['linhas']) and (colunasA == tadMatB['colunas']): tadMatC = cria(linhasA, colunasA) for l in range(linhasA): for c in range(colunasA): setElem(tadMatC,l,c,getElem(tadMatA,l,c) - getElem(tadMatB,l,c)) return tadMatC else: return None def soma(tadMatA, tadMatB): #User o getElem e o setElem vai facilitar linhasA = tadMatA['linhas'] colunasA = tadMatA['colunas'] if (linhasA == tadMatB['linhas']) and (colunasA == tadMatB['colunas']): tadMatC = cria(linhasA, colunasA) for l in range(linhasA): for c in range(colunasA): setElem(tadMatC,l,c,getElem(tadMatA,l,c) + getElem(tadMatB,l,c)) return tadMatC else: return None def vezesK(tadMat, k): linhas = tadMat['linhas'] colunas = tadMat['colunas'] for l in range(linhas): for c in range(colunas): setElem(tadMat,l,c,getElem(tadMat,l,c) * k) return tadMat def multi(tadMatA, tadMatB): colunasA = tadMatA['colunas'] linhasB = tadMatB['linhas'] if colunasA == linhasB: linhasA = tadMatA['linhas'] colunasB = tadMatB['colunas'] tadMatC_lst = [] for l in range(linhasA): tadMatC_lst.append([]) for c in range(colunasB): tadMatC_lst[l].append(0) for k in range(colunasA): tadMatC_lst[l][c] += getElem(tadMatA, l, k) * getElem(tadMatB, k, c) return criaLst(tadMatC_lst) else: return None def clona(tadMat): linhas = tadMat['linhas'] colunas = tadMat['colunas'] dados = tadMat['dados'] return {'linhas': linhas, 'colunas': colunas, 'dados': dados } def quantLinhas(tadMat): return tadMat['linhas'] def quantColunas(tadMat): return tadMat['colunas'] def diagP(tadMat): diagP_lst = [] linhas = tadMat['linhas'] colunas = tadMat['colunas'] if linhas == colunas: for l in range(linhas): for c in range(colunas): if l == c: diagP_lst.append(getElem(tadMat,l,c)) return diagP_lst else: return None def diagS(tadMat): diagS_lst = [] linhas = tadMat['linhas'] colunas = tadMat['colunas'] if linhas == colunas: for l in range(linhas): for c in range(colunas): if (colunas - 1) == (l + c): diagS_lst.append(getElem(tadMat,l,c)) return diagS_lst else: return None def transposta(tadMat): linhas = tadMat['linhas'] colunas = tadMat['colunas'] dados = tadMat['dados'] dados_t = {} for key in dados: dados_t[key[1],key[0]] = dados[key] tadMat['linhas'] = colunas tadMat['colunas'] = linhas tadMat['dados'] = dados_t
# -*- coding: utf-8 -*- def main(): n, l = list(map(int, input().split())) s = input() tab_count = 1 crash_count = 0 for si in s: if si == '+': tab_count += 1 else: tab_count -= 1 if tab_count > l: crash_count += 1 tab_count = 1 print(crash_count) if __name__ == '__main__': main()
#Autor Manuela Garcia Monsalve # 28 septiembre 2018 #Esta es la super clase Vehiculo donde se encuentran los atributos de marca, modelo y color que seran #heredados para las subclases class Vehiculo(): def __init__(self,marca,color, modelo): #Se generan los atributos para poder ser heredados self.marca = marca self.color = color self.modelo = modelo def Prender(self): #Metodo prender vehiculo pass def Arrancar(self):#Metodo arrancar vehiculo pass def Apagar(self):#Metodo apagar vehiculo pass
widget_types = [ "textinput", # Editable text input box "textupdate", # Read only text update "led", # On/Off LED indicator "combo", # Select from a number of choice values "icon", # This field gives the URL for an icon for the whole Block "group", # Group node in a TreeView that other fields can attach to "table", # Table of rows. A list is a single column table "checkbox", # A box that can be checked or not "flowgraph", # Boxes with lines representing child blocks and connections ] def widget(widget_type): """Associates a widget with this field""" assert widget_type in widget_types, \ "Got %r, expected one of %s" % (widget_type, widget_types) tag = "widget:%s" % widget_type return tag port_types = [ "bool", # Boolean "int32", # 32-bit signed integer "NDArray", # areaDetector NDArray port "CS", # Motor co-ordinate system ] def inport(port_type, disconnected_value): """Marks this field as an inport""" assert port_type in port_types, \ "Got %r, expected one of %s" % (port_type, port_types) tag = "inport:%s:%s" % (port_type, disconnected_value) return tag def outport(port_type, connected_value): """Marks this field as an outport""" assert port_type in port_types, \ "Got %r, expected one of %s" % (port_type, port_types) tag = "outport:%s:%s" % (port_type, connected_value) return tag def group(group_name): """Marks this field as belonging to a group""" tag = "group:%s" % group_name return tag def config(): """Marks this field as a value that should be saved and loaded at config""" tag = "config" return tag
""" 17 Cupboards - https://codeforces.com/problemset/problem/248/A """ n = int(input()) nL, nR = 0, 0 for _ in range(n): x, y = map(int, input().split()) nL += x nR += y print(min(nL, n - nL) + min(nR, n - nR))
def cookie(x): if isinstance(x, str): cookie_eater = "Zach" elif isinstance(x, int) or isinstance(x, float): cookie_eater = "Monica" else: cookie_eater = "the dog" if x == True or x == False: cookie_eater = "the dog" return "Who ate the last cookie? It was %s!" % cookie_eater print(cookie("Ryan")) print(cookie(2.3)) print(cookie(True)) print(isinstance(True, float)) ## More common use: x = 200 print(type(x) == int)