content
stringlengths
7
1.05M
""" coding: utf-8 Created on 13/11/2020 @author: github.com/edrmonteiro From: Hackerrank challenges Language: Python Title: Count Triplets You are given an array and you need to find number of tripets of indices such that the elements at those indices are in geometric progression for a given common ratio and . For example, . If , we have and at indices and . Function Description Complete the countTriplets function in the editor below. It should return the number of triplets forming a geometric progression for a given as an integer. countTriplets has the following parameter(s): arr: an array of integers r: an integer, the common ratio Input Format The first line contains two space-separated integers and , the size of and the common ratio. The next line contains space-seperated integers . Constraints Output Format Return the count of triplets that form a geometric progression. Sample Input 0 4 2 1 2 2 4 Sample Output 0 2 Explanation 0 There are triplets in satisfying our criteria, whose indices are and Sample Input 1 6 3 1 3 9 9 27 81 Sample Output 1 6 Explanation 1 The triplets satisfying are index , , , , and . Sample Input 2 5 5 1 5 5 25 125 Sample Output 2 4 Explanation 2 The triplets satisfying are index , , , . """ # Complete the countTriplets function below. def countTriplets(arr, r): triplets = 0 mult2 = {} mult1 = {} for item in reversed(arr): if item * r in mult1: triplets += mult1[item * r] if item * r in mult2: mult1[item] = mult1.get(item, 0) + mult2[item * r] mult2[item] = mult2.get(item, 0) + 1 return triplets arr = [1, 2, 2, 4] #2 r = 2 print(countTriplets(arr, r)) arr = [1,3,9,9,27,81] #6 r = 3 print(countTriplets(arr, r)) arr = [1, 5, 5, 25, 125] #4 r = 5 print(countTriplets(arr, r)) stop = True
def get_list(file_name: str): with open(file_name) as f: array = [x for x in f.read()[1:-1].split('","')] return(array) def is_triangle(triangle: int): """any tn in triangle sequence is t = ½n(n+1): Solving with quadratic formula reveals n is only an integer if (1+8t) ** 0.5 is an integer and odd""" if int((1+8*triangle)**0.5) == (1+8*triangle)**0.5 and ((1+8*triangle)**0.5)%2 == 1: return True return False def count_triangles(possible_triangles: list): count = 0 for number in possible_triangles: if is_triangle(number): count += 1 return count def letter_sum(name_list: list): #Converts a list of words to a list of the sums of their numbers for index in range(len(name_list)): name_list[index] = sum(map(lambda x: ord(x) - 64, name_list[index])) return name_list if __name__ == "__main__": print("There are", count_triangles(letter_sum(get_list("42_words.txt"))), "encoded triangles.")
class ProfileError(Exception): def __init__(self, code: str): self.code = code class ProfileNotFoundError(ProfileError): def __init__(self, code: str): super().__init__(code) def __str__(self): return f"Profile {self.code} not found" class ProfileAlreadyExistsError(ProfileError): def __init__(self, code: str, owner: str): super().__init__(code) self.owner = owner def __str__(self): return f"Profile with code {self.code} and owner: {self.owner} has already exists"
class GotoAckPacket: def __init__(self): self.type = "GOTOACK" self.time = 0 def write(self, writer): writer.writeInt32(self.time) def read(self, reader): self.time = reader.readInt32()
# # PySNMP MIB module EXTREME-OSPF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-BASE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:53:03 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, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection") extremeAgent, = mibBuilder.importSymbols("EXTREME-BASE-MIB", "extremeAgent") extremeVlanIfIndex, = mibBuilder.importSymbols("EXTREME-VLAN-MIB", "extremeVlanIfIndex") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Unsigned32, iso, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ObjectIdentity, Bits, MibIdentifier, ModuleIdentity, Counter64, Counter32, NotificationType, Integer32, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "iso", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "ObjectIdentity", "Bits", "MibIdentifier", "ModuleIdentity", "Counter64", "Counter32", "NotificationType", "Integer32", "IpAddress") RowStatus, TruthValue, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TruthValue", "TextualConvention", "DisplayString") extremeOspf = ModuleIdentity((1, 3, 6, 1, 4, 1, 1916, 1, 15)) if mibBuilder.loadTexts: extremeOspf.setLastUpdated('0006280000Z') if mibBuilder.loadTexts: extremeOspf.setOrganization('Extreme Networks, Inc.') extremeOspfInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 1916, 1, 15, 1), ) if mibBuilder.loadTexts: extremeOspfInterfaceTable.setStatus('current') extremeOspfInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1916, 1, 15, 1, 1), ).setIndexNames((0, "EXTREME-VLAN-MIB", "extremeVlanIfIndex")) if mibBuilder.loadTexts: extremeOspfInterfaceEntry.setStatus('current') extremeOspfAreaId = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 15, 1, 1, 1), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: extremeOspfAreaId.setStatus('current') extremeOspfInterfacePassive = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 15, 1, 1, 2), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: extremeOspfInterfacePassive.setStatus('current') extremeOspfInterfaceStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 15, 1, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: extremeOspfInterfaceStatus.setStatus('current') mibBuilder.exportSymbols("EXTREME-OSPF-MIB", extremeOspfInterfacePassive=extremeOspfInterfacePassive, PYSNMP_MODULE_ID=extremeOspf, extremeOspf=extremeOspf, extremeOspfAreaId=extremeOspfAreaId, extremeOspfInterfaceEntry=extremeOspfInterfaceEntry, extremeOspfInterfaceStatus=extremeOspfInterfaceStatus, extremeOspfInterfaceTable=extremeOspfInterfaceTable)
# -*- coding: utf-8 -*- """ Created on Mon May 29 17:31:17 2017 @author: Prosimio """
class IndigoDevice: def __init__(self, id, name): self.id = id self.name = name self.states = {} self.states_meta = {} self.pluginProps = {} self.image = None self.brightness = 0 def updateStateOnServer(self, key, value, uiValue=None, decimalPlaces=0): self.states[key] = value self.states_meta[key] = {'value': value, 'uiValue': uiValue, 'decimalPlaces': decimalPlaces} # update the brightness "helper" if key == "brightnessLevel": self.brightness = value def replacePluginPropsOnServer(self, pluginProps): self.pluginProps = pluginProps def updateStateImageOnServer(self, image): self.image = image def refreshFromServer(self): pass
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ ## quick solution # find l1, l2 f=s=dummy=ListNode(0) dummy.next=head while f and f.next: f=f.next.next s=s.next l2=s.next s.next=None l1=dummy.next # reverse l2 dummy.next=None x=l2 while x: x.next,dummy.next, x = dummy.next, x, x.next l2=dummy.next # combine l1, l2 cur=dummy while l1 or l2: if l1: cur.next, l1.next, l1 = l1, None, l1.next cur=cur.next if l2: cur.next, l2.next, l2 = l2, None, l2.next cur=cur.next return ## normal solution (TLE) cur=head while cur and cur.next: l1=cur.next l2=cur while l1.next: l1=l1.next l2=l2.next l2.next=None l1.next=cur.next cur.next=l1 cur=cur.next.next
# callbacks.py # Authors: Jacob Schreiber <jmschreiber91@gmail.com> class Callback(object): """An object that adds functionality during training. A callback is a function or group of functions that can be executed during the training process for any of pomegranate's models that have iterative training procedures. A callback can be called at three stages-- the beginning of training, at the end of each epoch (or iteration), and at the end of training. Users can define any functions that they wish in the corresponding functions. """ def __init__(self): self.model = None self.params = None def on_training_begin(self): """Functionality to add to the beginning of training. This method will be called at the beginning of each model's training procedure. """ pass def on_training_end(self, logs): """Functionality to add to the end of training. This method will be called at the end of each model's training procedure. """ pass def on_epoch_end(self, logs): """Functionality to add to the end of each epoch. This method will be called at the end of each epoch during the model's iterative training procedure. """ pass class ModelCheckpoint(Callback): """This will save the model to disk after each epoch.""" def __init__(self, name=None, verbose=True): self.model = None self.params = None self.name = None self.verbose = verbose def on_epoch_end(self, logs): """Save the model to disk at the end of each epoch.""" model = self.model.to_json() epoch = logs['epoch'] name = self.name if self.name is not None else self.model.name if self.verbose: print("[{}] Saving checkpoint to {}.{}.json".format(epoch, name, epoch)) with open('{}.{}.json'.format(name, epoch), 'w') as outfile: outfile.write(model) class History(Callback): """Keeps a history of the loss during training.""" def on_training_begin(self): self.total_improvement = [] self.improvements = [] self.log_probabilities = [] self.epoch_start_times = [] self.epoch_end_times = [] self.epoch_durations = [] self.epochs = [] self.learning_rates = [] self.n_seen_batches = [] self.initial_log_probablity = None self.test_log_probability = [] def on_epoch_end(self, logs): """Save the files to the appropriate lists.""" self.total_improvement.append(logs['total_improvement']) self.improvements.append(logs['improvement']) self.log_probabilities.append(logs['log_probability']) self.epoch_start_times.append(logs['epoch_start_time']) self.epoch_end_times.append(logs['epoch_end_time']) self.epoch_durations.append(logs['duration']) self.epochs.append(logs['epoch']) self.learning_rates.append(logs['learning_rate']) self.n_seen_batches.append(logs['n_seen_batches']) self.initial_log_probability = logs['initial_log_probability'] self.test_log_probability.append(logs['test_log_probability']) class CSVLogger(Callback): """Logs results of training to a CSV file during training.""" def __init__(self, filename, separator=',', append=False): self.filename = filename self.separator = separator self.append = append self.file = None self.columns = ['epoch', 'duration', 'total_improvement', 'improvement', 'log_probability', 'last_log_probability', 'test_log_probability', 'epoch_start_time', 'epoch_end_time', 'n_seen_batches', 'learning_rate'] def on_training_begin(self): if self.append == False: self.file = open(self.filename, 'w') self.file.write(self.separator.join(self.columns) + "\n") else: self.file = open(self.filename, 'a') def on_training_end(self, logs): self.file.close() def on_epoch_end(self, logs): self.file.write(self.separator.join(str(logs[col]) for col in self.columns) + "\n") class LambdaCallback(Callback): """A callback that takes in anonymous functions for any of the methods, for convenience.""" def __init__(self, on_training_begin=None, on_training_end=None, on_epoch_end=None): self.on_training_begin_ = on_training_begin self.on_training_end_ = on_training_end self.on_epoch_end_ = on_epoch_end def on_training_begin(self): if self.on_training_begin_ is not None: self.on_training_begin_() def on_training_end(self, logs): if self.on_training_end_ is not None: self.on_training_end_(logs) def on_epoch_end(self, logs): if self.on_epoch_end_ is not None: self.on_epoch_end_(logs)
word_filter_set = ['육변기', '워마드', '응디', '니기미', '맘충', '씹창', '거렁뱅이', '갈보', '미친놈', '빠구리', '김치년', '개씨발', '메갈', '메갈리아', '섹스', '시발새끼', '보전꺠', '씨방새', '니미씨발', '씹', 'ㅆㅂ', '불알', '쎅스', '핑두', '보지년', '오피누', '놈딱', '잠지', '섻스', '간나새끼', '개돼지', '씹쌔끼', '꼬추걸레', '조팔', '한남', '짭새', '걸레년', '개좆', '미친년', '옘병', '닭대가리', '느그앰', '4카시', '후빨', '개년', '미친새끼', '개새끼', '북딱', '빙신', '빨통', '시발롬', '니미럴', "니기럴",'닥쳐', '저능아', '사카시', '씨방년', '보빨', '썅년', '이기야', 'ㅆ발', '보전깨', '똘추', '씹쌔', '노슬아치', '썅놈', '시발', '병신', '느금', '씹썌', '등신', 'ㅅㅂ', '느금마', "느거매",'돌대가리', '십색갸', '니미', '씨팔', '놈현', '지잡', '빠9리', '셋스', '십색꺄', '니애미', '시부랄', '씹치녀', '개간년', '씨발', '급식충', '오피녀', '개지랄', '씨방놈', '엄창', '보슬아치', '십색기', "보지보지", '뻐큐', '한남충', '걸레련', '냄져', '느그미', '봊', '김치녀', '나가디지라', '시브랄', '빡대가리', '붕알', '씨부랄', '노무혐', '딸딸이', '좆', 'ㅈㄹ' , '개씹', '부엉이바위', '따까리', '부랄', '씹치남', '염병', '페미', '시발련', '보빨러', '사까시', '자댕이', '니앰', '싸가지', '니엄', '틀딱', '노알라', '엠창', '느개비', '돼지새끼', '씨브랄', '꼬걸', '틀딱충', '개씹할', '창녀', '창년', '시발년', '씝뽈', '개자석', '호로새끼'] def check_word_filter(str_temp): for word in word_filter_set: if word in str_temp: return True return False
# Nama : Eraraya Morenzo Muten # NIM : 16520002 # Tanggal : 26 Maret 2021 # Program EmpatInteger # Input: 4 integer: A, B, C, D # Output: Sifat integer dari A, B, C, D (positif/negatif/nol) # Jika semua integer positif, tampilkan: # nilai maksimum, minimum, dan mean olympic # KAMUS # variabel # A, B, C, D : int # mo : real # PROCEDURE DAN FUNCTION def CekInteger (x): # I.S.: x terdefinisi, bertype int # F.S.: Jika x positif, maka tertulis di layar: POSITIF # Jika x negatif, maka tertulis di layar: NEGATIF # Jika x nol, maka tertulis di layar: NOL if x>0: print("POSITIF") elif x<0: print("NEGATIF") elif x==0: print("NOL") def Max (a, b, c, d): # menghasilkan nilai terbesar di antara a, b, c, d (integer) return max(a,b,c,d) def Min (a, b, c, d): # menghasilkan nilai terkecil di antara a, b, c, d (integer) return min(a,b,c,d) def IsAllPositif (a, b, c, d): # menghasilkan True jika a, b, c, d seluruhnya positif # False jika tidak return (a>0) and (b>0) and (c>0) and (d>0) # PROGRAM UTAMA A = int(input()) B = int(input()) C = int(input()) D = int(input()) # Menuliskan sifat integer CekInteger(A) CekInteger(B) CekInteger(C) CekInteger(D) # Penulisan maksimum, minimum, dan mean olympic if (IsAllPositif(A,B,C,D)): print(Max(A,B,C,D)) print(Min(A,B,C,D)) mo = (A + B + C + D - Max(A,B,C,D) - Min(A,B,C,D)) / 2 print("%.2f" % mo) # 2 desimal
username = 'ENTER YOUR E-MAIL ID HERE' password = 'ENTER YOUR PASSWORD HERE' entry_nodeIp = 'http://py4e-data.dr-chuck.net/json?' gmaps_api_key = 42 user_agents_list = ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36", "Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36", ]
# uninhm # https://atcoder.jp/contests/abc183/tasks/abc183_a # implementation print(max(0, int(input())))
d1 = {42: 100} d2 = {'abc': 'fob'} d3 = {1e1000: d1} s = set([frozenset([2,3,4])]) class C(object): abc = 42 def f(self): pass cinst = C() class C2(object): abc = 42 def __init__(self): self.oar = 100 self.self = self def __repr__(self): return 'myrepr' def __hex__(self): return 'myhex' def f(self): pass c2inst = C2() class C3(object): def __init__(self): self.abc = 42 self._contents = [1,2] def __iter__(self): return iter(self._contents) def __len__(self): return len(self._contents) def __getitem__(self, index): return self._contents[index] c3inst = C3() l = [1, 2, ] i = 3 pass
url = "https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Hurdle%202&url=worlds%2Ftutorial_en%2Fhurdle2.json" def turn_right(): turn_left() turn_left() turn_left() def hurdle(): move() turn_left() move() turn_right() move() turn_right() move() turn_left() for i in range(1, 7): hurdle()
class Test: def __init__(self, text): self.text = text def text(self): return self.text
# Instruments SST_INSTRUMENT = 'SST' POEMAS_INSTRUMENT = 'POEMAS' # File types TRK_TYPE = 'TRK' RBD_TYPE = 'RBD' # Instrument Types AVAILABLE_SST_TYPES = { RBD_TYPE: ["bi", "rs", "rf"] } AVAILABLE_POEMAS_TYPES = { TRK_TYPE: ["TRK"] } INSTRUMENT_TO_TYPE_MAP = { SST_INSTRUMENT: AVAILABLE_SST_TYPES, POEMAS_INSTRUMENT: AVAILABLE_POEMAS_TYPES } # Errors OBJECTS_NOT_FROM_SAME_INSTRUMENT = "Objects are not from the same instrument: {}" CONCATENATE_NOT_AVAILABLE_ERROR = "Concatenate operation not available for file with type {} from instrument {}" FILE_NOT_FOUND_ERROR = "File not found: {}" INVALID_PATH_TO_XML_ERROR = "Invalid path to XML: {}" INVALID_INSTRUMENT_ERROR = "Invalid instrument: {}" INVALID_FILE_TYPE_ERROR = "Invalid file type {} for instrument {}." INVALID_FILE_NAME = "Invalid filename {}" INVALID_XML_FILE = "Invalid xml type: {}" FILE_ALREADY_EXISTS = "File {} already exists." INVALID_LEVEL_TYPE = "This level type is not valid: {}. It must be a integer" FITS_LEVEL_NOT_AVAILABLE = "Fits level {} is not available for conversion" CANT_CONVERT_FITS_LEVEL = "Can't get fits level {} for object with level {}, please try a level higher than {}" COULDNT_MATCH_CONVERTED_DATA_TO_INSTRUMENT = "Couldn't match converted data fom file type {} to instrument {}" # Others XML_TABLE_PATH = "xml-tables/{}/{}" CONCATENATED_DATA = "Concatenated Data"
num1 = int(input('Digite o primeiro valor: ')) num2 = int(input('Digite o segundo valor: ')) if num1 > num2: print('{}{}{} é o maior.'.format('\033[1;36m', num1, '\033[m')) elif num1 == num2: print('Os {}dois valores{} são iguais'.format('\033[4;33m', '\033[m')) elif num2 > num1: print('{}{}{} é o maior.'.format('\033[1;36m', num2, '\033[m'))
# -*- coding: utf-8 -*- """ Created on Sun Apr 19 23:51:39 2020 @author: abcdk """ word = "Guten Morgen" extract = word[2:5:1] print(extract.upper()) word2 = "Racetrack" extract2 = word2[1:4:1] print(extract2.capitalize())
def get_sunday(): return 'Sunday' def get_monday(): return 'Monday' def get_tuesday(): return 'Tuesday' def get_default(): return 'Unknown' day = 4 switcher = { 0 : get_sunday, 1 : get_monday, 2 : get_tuesday } day_name = switcher.get(day,get_default)() print(day_name)
# Número para mês # Crie um programa que pergunta o número do mês e imprime o nome do mês. month = int(input("month? ")) - 1 months = ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"] print(months[month])
CONFIG_FILENAMES = [ '.vintrc.yaml', '.vintrc.yml', '.vintrc', ]
# 打印变量的值 a = 101 print(a) # 打印变量的唯一id print(id(a)) # 判断变量是否相等 == is a = 100 b = 100 print(a is b) a = 10000 b = 10000 print(a is b) # 打印变量的类型 print(type(a))
# -------------- This file adds actual expected results to submission file -----------------# f=open('submission.csv','r') g=open('testHistory.csv','r') # ts.csv generated before h=open('res.csv','w+') lines=f.readlines() i=0 for line in g.readlines(): k=line.split(',') toWrite=k[5] h.write(lines[i][0:-1]+','+toWrite+'\n') i+=1 h.close() f.close() g.close() #----------------- Note ---------------------# # After this file executed: # rename res.csv to submission.csv #--------------------------------------------#
""" Version. Doing it this way provides for access in setup.py and via __version__ """ __version__ = "0.1.4"
IRIS_BYPASS=False AWS_REGION = "us-west-1" IRIS_SNS_TOPIC = "iris-topic" IRIS_SQS_APP_QUEUE = "iris-test-queue" IRIS_POLL_INTERVAL = 20
''' Created on 2016年2月9日 @author: Darren ''' ''' Palindromic Squares Rob Kolstad Palindromes are numbers that read the same forwards as backwards. The number 12321 is a typical palindrome. Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on. Print both the number and its square in base B. PROGRAM NAME: palsquare INPUT FORMAT A single line with B, the base (specified in base 10). SAMPLE INPUT (file palsquare.in) 10 OUTPUT FORMAT Lines with two integers represented in base B. The first integer is the number whose square is palindromic; the second integer is the square itself. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B! SAMPLE OUTPUT (file palsquare.out) 1 1 2 4 3 9 11 121 22 484 26 676 101 10201 111 12321 121 14641 202 40804 212 44944 264 69696 ''' def palsquare(n): for num in range(1,301): cand=convert(num*num, n) if cand ==cand[::-1]: print(num,cand) def convert(num,base): #conver a 10 based num to new base res="" while num>0: if num%base>9: res=chr(ord("A")+num%base-10)+res else: res=str(num%base)+res num//=base return res palsquare(20)
# This dictionary is to define metrics that we should extract data from and then # their exposed name as predicted metric metrics = { 'actual_metric_name1': 'actual_metric_name1_predict', 'actual_metric_name2': 'actual_metric_name2_predict' } # prom_url = 'http://localhost/' expose_port = 8000 # interval in days interval = 30 # chunk size in hour chunk_size = 24
""" Data types used on Android and whatsapp """ class TextPlain: def __str__(self): return "text/plain" class AnyImage: def __str__(self): return "image/*" class AndroidVndContact: def __str__(self): return "vnd.android.cursor.dir/contact"
def print_hello(): print("hello!") def print_goodbye(): print("goodbye!")
n = int(input()) primary = [] secondary = [] matrix = [] for _ in range(n): matrix.append([int(x) for x in input().split()]) for r in range(n): primary.append(matrix[r][r]) secondary.append(matrix[r][n - 1 -r]) sum_p = (sum([x for x in primary])) sum_s = (sum([x for x in secondary])) print(abs(sum_p-sum_s))
# replace with the label of class for which you are interested in building the lexicon; # this should be the same as the label in your input files positive_class_label = "on-topic" # replace the label for the examples that do not belong to the topic of interest # this should be the same as the label in your input files negative_class_label ="off-topic" # lexicon size lexicon_size = 400
"""JPL Planetary and Lunar Ephemeris DE422 for the jplephem package. This is the most recent long-period ephemeris published by the Jet Propulsion Laboratory. While requiring more than half a gigabyte of space, it achieves quite high accuracy. :Name: DE422 (September 2009) :Years: -3000 through 3000 :Planets: Yes :Sun/Moon: Yes :Nutations: Yes :Librations: Yes :Report: `Jones, Fomalont, Dhawan, Romney, Folkner, Lanyi, Border, Jacobson (2010) [PDF] <http://arxiv.org/pdf/1012.0264>`_ :Size: 531 MB This ephemeris incorporates ranging data from recent spacecraft missions, including the Cassini mission to Saturn, which results in an accuracy for Saturn of a few milliarcseconds for positions over the past decade. If this ephemeris is too large for your application, take a look at `DE421 <http://pypi.python.org/pypi/de421>`_ and `DE423 <http://pypi.python.org/pypi/de423>`_ as alternatives. To compute using this ephemeris in Python, see the `jplephem <http://pypi.python.org/pypi/jplephem>`_ package. """
def loadfile(name): values = [] f = open(name, "r") for x in f: values.append(x) return values def day2(): depth = 0 position = 0 depth2 = 0 for i in range(0, len(values)): value = values[i].split() if value[0] == "forward": position += int(value[1]) depth2 += int(value[1]) * depth elif value[0] == "down": depth += int(value[1]) elif value[0] == "up": depth -= int(value[1]) return [position,depth, depth2] values = loadfile("data.txt") print(values) solution = day2() print("full solution: " + str(solution)) print("solution day2a: " + str(solution[0]*solution[1])) print("solution day2b: " + str(solution[0]*solution[2]))
"""Kata: Move Zeroes - Move all zeroes in list to end. #1 Best Practices Solution by riyakayal def move_zeros(arr): l = [i for i in arr if isinstance(i, bool) or i!=0] return l+[0]*(len(arr)-len(l)) """ def move_zeroes(array): all_zeroes = list(filter((lambda x: x == 0 and type(x) is not bool), array)) non_zeroes = list(filter((lambda x: x != 0 or type(x) is bool), array)) return non_zeroes + all_zeroes
class PrefixStorage(object): """Storage for store information about prefixes. >>> s = PrefixStorage() First we save information for some prefixes: >>> s["123"] = "123 domain" >>> s["12"] = "12 domain" Then we can retrieve prefix information by full key (longest prefix always win): >>> s.getByPrefix("123456") '123 domain' >>> s.getByPrefix("12456") '12 domain' If no prefix has been found then getByPrefix() returns default value: >>> s.getByPrefix("13456", "None") 'None' """ def __init__(self): self._mapping = {} self._sizes = [] def __setitem__(self, key, value): ln = len(key) if ln not in self._sizes: self._sizes.append(ln) self._sizes.sort() self._sizes.reverse() self._mapping[key] = value def getByPrefix(self, key, default=None): for ln in self._sizes: k = key[:ln] if k in self._mapping: return self._mapping[k] return default
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY short_version = '1.10.4' version = '1.10.4' full_version = '1.10.4' git_revision = 'e46c2d78a27f25e66624a818276be57ef9458e60' release = True if not release: version = full_version
def extractWwwAsianhobbyistCom(item): ''' Parser for 'www.asianhobbyist.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None if "Anime" in item['tags']: return None if "Articles" in item['tags']: return None if "L’Apprivoisement D’une Yandere" in item['tags']: return None tagmap = [ ('Boku wa Isekai', 'Boku wa Isekai de Fuyo Mahou to Shoukan Mahou wo Tenbin ni Kakeru', 'translated'), ('Traitor and Hero Party', 'Traitor and Hero Party', 'translated'), ('The God Slaying Hero and the Seven Covenants', 'The God Slaying Hero and the Seven Covenants', 'translated'), ('First Hunter', 'The First Hunter', 'translated'), ('Revolution of the 8th Class Mage', 'Revolution of the 8th Class Mage', 'translated'), ('The Villainess Is Being Doted on by the Crown Prince', 'The Villainess Is Being Doted on by the Crown Prince', 'translated'), ('The Lazy Swordmaster', 'The Lazy Swordmaster', 'translated'), ('My Pet Is a Holy Maiden', 'My Pet Is a Holy Maiden', 'translated'), ('I Will Quit the Entourage of the Villainess', 'I Will Quit the Entourage of the Villainess', 'translated'), ('The Archer of A Fictitious World', 'The Archer of A Fictitious World', 'translated'), ('The Spoilt Village Beauty', 'The Spoilt Village Beauty', 'translated'), ('Golden Word Master', 'Golden Word Master', 'translated'), ('Shadow Rogue', 'Shadow Rogue', 'translated'), ('LV999 Villager', 'LV999 Villager', 'translated'), ('Evil God Average', 'Evil God Average', 'translated'), ('Maou Ni', 'Maou ni Nattanode, Dungeon Tsukutte Jingai Musume to Honobono Suru', 'translated'), ('Uchi Musume', 'Uchi no Musume no Tame naraba, Ore wa Moshikashitara Maou mo Taoseru kamo Shirenai', 'translated'), ('Botsuraku', 'Botsuraku Youtei Nanode, Kajishokunin wo Mezasu', 'translated'), ('Akuya', 'Akuyaku Tensei Dakedo Doushite Kou Natta.', 'translated'), ('The Strong The Few Cultivators On Campus', 'The Strong The Few Cultivators On Campus', 'translated'), ('Magicraft Meister', 'Magi Craft Meister', 'translated'), ('A Tale of Two Phoenixes', 'A Tale of Two Phoenixes', 'translated'), ('The Taming of the Yandere', 'The Taming of the Yandere', 'translated'), ('Abyss Domination', 'Abyss Domination', 'translated'), ('Yuusha, Aruiwa Bakemono to Yobareta Shoujo', 'Yuusha, Aruiwa Bakemono to Yobareta Shoujo', 'translated'), ('The Manual of Duke\'s Daughter', 'The Manual of Duke\'s Daughter', 'translated'), ('That Time I Got Reincarnated As A Slime', 'That Time I Got Reincarnated As A Slime', 'translated'), ('Every Day the Protagonist Wants to Capture Me', 'Every Day the Protagonist Wants to Capture Me', 'translated'), ('kuro no maou', 'kuro no maou', 'translated'), ('Me, Her, and the Ballistic Weaponry', 'Me, Her, and the Ballistic Weaponry', 'translated'), ('Hilarious pampered consort: Lord I will wait for your divorce', 'Hilarious pampered consort: Lord I will wait for your divorce', 'translated'), ('Beastly Fēi that Go Against the Heaven: Coerced by the Huáng Shū', 'Beastly Fēi that Go Against the Heaven: Coerced by the Huáng Shū', 'translated'), ('One Man Army', 'One Man Army', 'translated'), ('Rebirth Junior High School: The Exceling Top Student Goddess', 'Rebirth Junior High School: The Exceling Top Student Goddess', 'translated'), ('Itai No Wa', 'Itai No Wa', 'translated'), ('Slime', 'Tensei Shitara Slime Datta Ken', 'translated'), ('Hero without Blood or Tear', 'Hero without Blood or Tear', 'translated'), ('The Magnificent Battle Records of a Former Noble Lady', 'The Magnificent Battle Records of a Former Noble Lady', 'translated'), ('Chiyu Mahou no Machigatta Tsukaikata ~Senjou wo Kakeru Kaifuku Youin~', 'Chiyu Mahou no Machigatta Tsukaikata ~Senjou wo Kakeru Kaifuku Youin~', 'translated'), ('The Daughter of the Albert House Wishes for Ruin', 'The Daughter of the Albert House Wishes for Ruin', 'translated'), ('The Black Demon King', 'The Black Demon King', 'translated'), ('Spice of Life', 'Spice of Life', 'translated'), ('Unexpected Marriage', 'Unexpected Marriage', 'translated'), ('Heavenly Star', 'Heavenly Star', 'translated'), ('Overlord of Blood and Iron', 'Overlord of Blood and Iron', 'translated'), ('Zhu Xian', 'Zhu Xian', 'translated'), ('Awakening', 'Awakening', 'translated'), ('I Somehow Got Strong By Raising Skills Related To Farming', 'I Somehow Got Strong By Raising Skills Related To Farming', 'translated'), ('I\'m a Villager So What?', 'I\'m a Villager So What?', 'translated'), ('Big Landlord', 'Big Landlord', 'translated'), ('Common Sense of a Duke\'s Daughter', 'Common Sense of a Duke\'s Daughter', 'translated'), ('The Traitor of the Hero Party', 'The Traitor of the Hero Party', 'translated'), ('Hiki Neet', '10 nen goshi no HikiNiito o Yamete Gaishutsushitara Jitaku goto Isekai ni Ten\'ishiteta', 'translated'), ('100 cheats', 'Because There Were 100 Goddesses in Charge of Reincarnation, I Received 100 Cheat Skills', 'translated'), ('Even Posing as a Hero is Easy', 'Yuusha no Furi mo Raku Janai–Riyuu? Ore ga Kami dakara–', 'translated'), ('Large Tit Stepdaughter', 'What’s Wrong With Liking My Busty Adopted Daughter', 'translated'), ('Busty Adopted Daughter', 'What’s Wrong With Liking My Busty Adopted Daughter', 'translated'), ('Virgin Demon King', '400 Years Old Virgin Demon King', 'translated'), ('400 Year Old Virgin Demon King', '400 Years Old Virgin Demon King', 'translated'), ('Dancer In The Shadow', 'Dancer In The Shadow', 'translated'), ('Reformation of the Checkmated Reincarnated Feudal Lord', 'Reformation of the Checkmated Reincarnated Feudal Lord', 'translated'), ('History\'s Strongest Manager', 'History\'s Strongest Manager', 'translated'), ('Black Belly Wife', 'Black Belly Wife', 'translated'), ('I Said Make My Abilities Average!', 'I Said Make My Abilities Average!', 'translated'), ('God of Cooking', 'God of Cooking', 'translated'), ('The Reincarnated Vampire Wants an Afternoon Nap', 'The Reincarnated Vampire Wants an Afternoon Nap', 'translated'), ('Possessing Nothing', 'Possessing Nothing', 'translated'), ('God-level Bodyguard in the City', 'God-level Bodyguard in the City', 'translated'), ('I am an alchemist. I have discarded self-restraint in the trash', 'I am an alchemist. I have discarded self-restraint in the trash', 'translated'), ('The Ability to Make Town!? ~Let’s Make a Japanese Town in Different World~', 'The Ability to Make Town!? ~Let’s Make a Japanese Town in Different World~', 'translated'), ('Lovable Package', 'Lovable Package', 'translated'), ('God of Thunder', 'God of Thunder', 'translated'), ('Max Level Newbie', 'Max Level Newbie', 'translated'), ('Because I’m a Weapon Shop Uncle', 'Because I\'m a Weapon Shop Uncle', 'translated'), ('Game Market 1983', 'Game Market 1983', 'translated'), ('My Castle My Castellian', 'My Castle My Castellian', 'translated'), ('Oda', 'Mysterious Job Called Oda Nobunaga', 'translated'), ('Defense Build', 'I hate being in pain, so I think I’ll make a full defense build.', 'translated'), ('Return of the 8th Class Mage', 'Return of the 8th Class Mage', 'translated'), ('di daughter’s rebirth: sheng shi wang fei', 'di daughter’s rebirth: sheng shi wang fei', 'translated'), ('rebirth: noble woman, poisonous concubine', 'rebirth: noble woman, poisonous concubine', 'translated'), ('Thousand Face Demonic Concubine', 'Thousand Face Demonic Concubine', 'translated'), ('how do i fix it?', 'i’ve led the villain astray', 'translated'), ('i’ve led the villain astray', 'i’ve led the villain astray', 'translated'), ('the tale of the ghost eyes', 'the tale of the ghost eyes', 'translated'), ('rebirth of the national male god', 'rebirth of the national male god', 'translated'), ('pulling together a villain reformation strategy', 'pulling together a villain reformation strategy', 'translated'), ('Assassin Landlord & Beauty Tenants', 'Assassin Landlord & Beauty Tenants', 'translated'), ('My Entire Class Was Summoned to Another World Except for Me', 'My Entire Class Was Summoned to Another World Except for Me', 'translated'), ('bringing along a ball and hiding from foreign devils', 'bringing along a ball and hiding from foreign devils', 'translated'), ('get lost! i don’t have a traitorous disciple like you', 'get lost! i don’t have a traitorous disciple like you', 'translated'), ('I Am An NPC', 'I Am An NPC', 'translated'), ('the wizard of the tower', 'the wizard of the tower', 'translated'), ('The Strange Adventure of a Broke Mercenary', 'The Strange Adventure of a Broke Mercenary', 'translated'), ('a mistaken marriage match: pursuit of murderer in liao yue', 'a mistaken marriage match: pursuit of murderer in liao yue', 'translated'), ('my c.e.o wife', 'my c.e.o wife', 'translated'), ('Strongest Naruto System', 'Strongest Naruto System', 'translated'), ('Instant Death', 'Instant Death', 'translated'), ('haunted duke’s daughter', 'haunted duke’s daughter', 'translated'), ('Arena', 'Arena', 'translated'), ('MEMORIZE', 'M E M O R I Z E', 'translated'), ('fanning the flames of war!', 'fanning the flames of war!', 'translated'), ('I’ve Led the Villain Astray, How Do I Fix It?', 'I’ve Led the Villain Astray, How Do I Fix It?', 'translated'), ('the lover’s prattle', 'the lover’s prattle', 'translated'), ('reborn only to love you again', 'reborn only to love you again', 'translated'), ('Counterattack of a White Lotus that was Reborn into an Apocalypse', 'Counterattack of a White Lotus that was Reborn into an Apocalypse', 'translated'), ('More Than A Few Blessings', 'More Than A Few Blessings', 'translated'), ('Online Game: Evil Dragon Against The Heaven', 'Online Game: Evil Dragon Against The Heaven', 'translated'), ('The King of the Battlefield', 'The King of the Battlefield', 'translated'), ('Golden Assistant', 'Golden Assistant', 'translated'), ('Rebirth of the Rich and Wealthy', 'Rebirth of the Rich and Wealthy', 'translated'), ('I Decided to Not Compete and Quietly Create Dolls Instead', 'I Decided to Not Compete and Quietly Create Dolls Instead', 'translated'), ('Otherworld Nation Founding Chronicles', 'Otherworld Nation Founding Chronicles', 'translated'), ('otoko nara ikkokuichijou no aruji o mezasa nakya', 'otoko nara ikkokuichijou no aruji o mezasa nakya', 'translated'), ('Being Able to Edit Skills in Another World, I Gained OP Waifus', 'Being Able to Edit Skills in Another World, I Gained OP Waifus', 'translated'), ('Boku wa Isekai de Fuyo Mahou to Shoukan Mahou wo Tenbin ni Kakeru', 'Boku wa Isekai de Fuyo Mahou to Shoukan Mahou wo Tenbin ni Kakeru', 'translated'), ('Other World’s Monster Breeder', 'Other World’s Monster Breeder', 'translated'), ('invincible saint ~salaryman', 'Invincible Saint ~Salaryman, the Path I Walk to Survive in This Other World~', 'translated'), ('qingge', 'qingge', 'translated'), ('Magi Craft Meister', 'Magi Craft Meister', 'translated'), ('albert ke no reijou wa botsuraku wo go shomou desu', 'albert ke no reijou wa botsuraku wo go shomou desu', 'translated'), ('sairin yuusha no fukushuu hanashi', 'sairin yuusha no fukushuu hanashi', 'translated'), ('kyuuketsu hime wa barairo no yume o miru', 'kyuuketsu hime wa barairo no yume o miru', 'translated'), ('Boundary Labyrinth and the Foreign Magician', 'Boundary Labyrinth and the Foreign Magician', 'translated'), ('let’s be an adventurer! ~defeating dungeons with a skill board~', 'let’s be an adventurer! ~defeating dungeons with a skill board~', 'translated'), ('tilea’s worries', 'Tilea no Nayamigoto', 'translated'), ('kaleidoscope of death', 'kaleidoscope of death', 'translated'), ('Magi’s Grandson', 'Magi’s Grandson', 'translated'), ('the man standing on top of the food chain', 'the man standing on top of the food chain', 'translated'), ('Shinka no Mi', 'Shinka no Mi', 'translated'), ('let’s be an adventurer! ~defeating dungeons with a skill board', 'let’s be an adventurer! ~defeating dungeons with a skill board', 'translated'), ('chinese almanac master', 'chinese almanac master', 'translated'), ('Helping with Adventurer Party Management', 'Helping with Adventurer Party Management', 'translated'), ('i’m scattering iq to the protagonist', 'i’m scattering iq to the protagonist', 'translated'), ('Blade Online', 'Blade Online', 'translated'), ('Real Cheat Online', 'Real Cheat Online', 'translated'), ('endo and kobayashi’s live commentary on the villainess', 'endo and kobayashi’s live commentary on the villainess', 'translated'), ('the s-classes that i raised', 'the s-classes that i raised', 'translated'), ('Thanks to a Different World Reincarnation', 'Thanks to a Different World Reincarnation', 'translated'), ('Reincarnation into the Barrier Master', 'Reincarnation into the Barrier Master', 'translated'), ('of course, i’ll claim palimony!', 'of course, i’ll claim palimony!', 'translated'), ('past life returner', 'past life returner', 'translated'), ('Green Skin', 'Green Skin', 'translated'), ('Chu Wang Fei', 'Chu Wang Fei', 'translated'), ('my castle my castellan', 'my castle my castellan', 'translated'), ('Waiting For You Online', 'Waiting For You Online', 'translated'), ('Liu Yao: The Revitalization of Fuyao Sect', 'Liu Yao: The Revitalization of Fuyao Sect', 'translated'), ('The Simple Life of Killing Demons', 'The Simple Life of Killing Demons', 'translated'), ('frontiers ~chronicles of bucket-san’s detailed pioneering~', 'frontiers ~chronicles of bucket-san’s detailed pioneering~', 'translated'), ('my 【repair】skill became an almighty cheat skill, so i thought i’d open up a weapon shop', 'my 【repair】skill became an almighty cheat skill, so i thought i’d open up a weapon shop', 'translated'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) titlemap = [ ('Because There Were 100 Goddesses ', 'Because There Were 100 Goddesses in Charge of Reincarnation, I Received 100 Cheat Skills', 'translated'), ('Botsuraku Youtei Volume', 'Botsuraku Youtei Nanode, Kajishokunin wo Mezasu', 'translated'), ('Reincarnated into a Werewolf', 'Jinrou e no Tensei, Maou no Fukukan', 'translated'), ('Reincarnated Into Werewolf ', 'Jinrou e no Tensei, Maou no Fukukan', 'translated'), ('Uchi no Musume no Tame naraba', 'Uchi no Musume no Tame Naraba, Ore Moshikashitara Maou mo Taoserukamo Shirenai.', 'translated'), ('Botsuraku Youtei Volume', 'Botsuraku Youtei Nanode, Kajishokunin wo Mezasu', 'translated'), ('Devouring The Heavens', 'Devouring The Heavens', 'translated'), ('The Taming of the Yandere', 'The Taming of the Yandere', 'translated'), ('Maou Ni', 'Maou ni Nattanode, Dungeon Tsukutte Jingai Musume to Honobono Suru', 'translated'), ('The Strong The Few Cultivators On Campus', 'The Strong The Few Cultivators On Campus', 'translated'), ('The Strong, The Few, True Cultivators on Campus', 'The Strong The Few Cultivators On Campus', 'translated'), ('Evolution Theory of the Hunter', 'Evolution Theory of the Hunter', 'translated'), ('Beast Piercing The Heavens', 'Beast Piercing The Heavens', 'translated'), ('Tower of Karma', 'Tower of Karma', 'translated'), ('400 Year Old Virgin Demon King', '400 Year Old Virgin Demon King', 'translated'), ('Expecting to Fall into Ruin Volume', 'Botsuraku Youtei Nanode, Kajishokunin wo Mezasu', 'translated'), ('Genius Sword Immortal', 'Genius Sword Immortal', 'translated'), ('Evil God Average', 'Evil God Average', 'translated'), ('The God Slaying Hero', 'The God Slaying Hero And The Seven Covenants', 'translated'), ('First Hunter', 'The First Hunter', 'translated'), ('Shadow Rogue', 'Shadow Rogue', 'translated'), ('Black Haired Knight', 'Black Haired Knight', 'translated'), ('The Lazy Swordmaster', 'The Lazy Swordmaster', 'translated'), ('Uchi Musume', 'Uchi Musume', 'translated'), ('Hero without Blood or Tear', 'Hero without Blood or Tear', 'translated'), ] for titlecomponent, name, tl_type in titlemap: if titlecomponent.lower() in item['title'].lower(): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
class Solution: def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ l = 0 r = len(numbers) - 1 while l < r: sum = numbers[l] + numbers[r] if sum < target: l += 1 elif sum > target: r -= 1 else: return [l + 1, r + 1]
# Define a Subtraction Function def sub(num1, num2): return num1 - num2
baseurl='\t\t\t<input name="marriageLine" type="radio" id="marriageLine%s" value="%s" /><label for="marriageLine%s"><img src="images/marriageLine/%s.jpg" height=195 width=150></label>' for i in range(1, 18): url = baseurl % (i,i,i,i) print(url+"\n")
class Duck: def swim(self): print("Duck is swimming!") def layEggs(self): print("Duck is laying eggs!") class Fish: def swim(self): print("Fish is swimming!") def layEggs(self): print("Fish is laying eggs!") class Diver: def swim(self): print("A human is waddling around in water!") def saySomethingFunny(self): print("MATLAB is a real programming language!") def swim(entity): entity.swim() def layEggs(entity): entity.layEggs() duck = Duck() fish = Fish() diver = Diver() duck.swim() duck.layEggs() fish.swim() fish.layEggs() diver.swim() diver.layEggs()
def findTagInChildren(children, key, value=None): """ Find in children a tag element with specified attribute key. If value is set to None, the value is returned. If value is specified, name et attrs of child are returned. In case no element or value is found, None is returned - children: list of tuples (name of element, element attributes) - return: value, (name, attibutes) or None """ #try to get tag with k = place for name, attrs in children: #Skip if this is not a tag if name != "tag": continue #It's a tag try: k = attrs['k'] except KeyError: continue else: if k != key: continue else: try: v = attrs['v'] except KeyError: continue else: if value is None: return v elif v == value: return name, attrs return """ Compare two strings and return True if strings match. Each string is converted into lower case characters before comparison. - characters are replaces with space characters. """ def compareStrings(string1, string2): s1 = string1.lower().replace('-', ' ') s2 = string2.lower().replace('-', ' ') match = False if s1 == s2: match = True return match
class main: a = '' def func(self): s = '' b = '\n\n\ntareq\n\n\n' for i in b: if i != '\n': s += i print(s) ii = main() ii.func()
def lambda_handler(event, context): message = event['Records'][0]['Sns']['Message'] print("handle message: " + message) webhook_url = 'https://hookb.in/RZYdoJVodkcREEj72WqV' http = urllib3.PoolManager() r = http.request( 'POST', webhook_url, body=message.encode('utf-8'), headers={'Content-Type': 'application/json'} ) print("webhook post response: " + r.data.decode('utf-8') ) return message
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 17:50:06 2020 @author: Carlos Mateo Jurado Díaz """ def CLEARLAYOUT(layout): for i in reversed(range(layout.count())): layoutItem = layout.itemAt(i) if layoutItem.widget() is not None: widgetToRemove = layoutItem.widget() widgetToRemove.setParent(None) layout.removeWidget(widgetToRemove) else: layoutToRemove = layout.itemAt(i) CLEARLAYOUT(layoutToRemove)
#!/usr/bin/env python """ CREATED AT: 2021/11/5 Des: https://leetcode.com/problems/arranging-coins/ GITHUB: https://github.com/Jiezhi/myleetcode Difficulty: Easy Tag: See: """ class Solution: def arrangeCoins(self, n: int) -> int: """ Runtime: 924 ms, faster than 35.91% Memory Usage: 14.3 MB, less than 39.42% 1 <= n <= 2^31 - 1 :param n: :return: """ i = 1 while n >= i: n, i = n - i, i + 1 return i - 1 def test(): assert Solution().arrangeCoins(n=1) == 1 assert Solution().arrangeCoins(n=2) == 1 assert Solution().arrangeCoins(n=3) == 2 assert Solution().arrangeCoins(n=4) == 2 assert Solution().arrangeCoins(n=5) == 2 assert Solution().arrangeCoins(n=6) == 3 assert Solution().arrangeCoins(n=7) == 3 assert Solution().arrangeCoins(n=8) == 3 assert Solution().arrangeCoins(n=9) == 3 assert Solution().arrangeCoins(n=10) == 4 if __name__ == '__main__': test()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 11 16:00:00 2020 @author: natnem """ def CountingSort(A): k = max(A) + 1 C = [0]*(k) #Auxillary array to keep track of the key appearances B = [0]*(len(A)) #To hold the output for i in A: C[i] = C[i] + 1 #0 i if key(Index) is in A else, increment for each apperance of keys for x in range(1,k): C[x] = C[x] + C[x-1] #to keep track of how many keys are before the key in C for j in range(len(A)-1,-1,-1): B[C[A[j]]-1] = A[j] #place the key in sorted place C[A[j]] = C[A[j]] - 1 #decrement key appearance from auxillary array return B A = [2,5,3,0,1,1] print(CountingSort(A))
class Descritor: def __init__(self, obj, set=None, get=None, delete=None): self.obj = obj self.set = set self.get = get self.delete = delete def __set__(self, obj, val): print('Estou setando algo') self.obj = val def __get__(self, obj, tipo=None): print('Estou pegango algo') return self.obj def __delete__(self, obj): print('Estou deletando algo') del self.obj def __repr__(self): return self.obj class NumeroPositivo: _n = None def get_n(self): print('get') return self._n def set_n(self, val): print('set') if val < 1: ... else: self._n = val def del_n(self): print('del') del self._n n = Descritor(_n)
# -*- coding: utf-8 -*- A = int(input()) B = int(input()) PROD = (A*B) print("PROD =", PROD)
class Persona: cedula = 0 nombre = '' telefono = 0 voto = 0 def __init__(self, cd, nm, tl, vt): self.cedula = cd self.nombre = nm self.telefono = tl self.voto = vt def getCedula(self): return self.cedula def getNombre(self): return self.nombre def getTelefono(self): return self.telefono def getVoto(self): return self.voto def getTodo(self): return self.cedula, self.nombre, self.telefono, self.voto class Estudiante(Persona): carnet = '' carrera = '' def __init__(self, cd, nm, tl, vt): self.carnet = '' self.carrera = '' Persona.__init__(self, cd, nm, tl, vt) def setCarnet(self, cn): self.carnet = cn def setCarrera(self, cr): self.carrera = cr def getCarnet(self): return self.carnet def getCarrera(self): return self.carrera def getTodo(self): datos = [] datos.append(Estudiante.getCarnet(self)) datos.append(Estudiante.getCarrera(self)) persona = Persona.getTodo(self) for p in persona: datos.append(p) return datos
def stingy(total_lambs): stingyList = [1, 1] x, total = 2, 2 while x <= total_lambs: value = stingyList[x-1] + stingyList[x-2] stingyList.append(value) total += int(stingyList[x]) if total > total_lambs: break x+= 1 return len(stingyList) def generous(total_lambs): generousList = [] x, total = 0, 0 while x <= total_lambs: current = 2**x generousList.append(current) total += current if total > total_lambs: break x += 1 return len(generousList) def solution(total_lambs): return stingy(total_lambs) - generous(total_lambs) if __name__ == "__main__": i1 = 143 print(solution(i1)) i2 = 10 print(solution(i2))
""" Desenvolva um programa que leia seis numeros inteiros e mostre a soma apenas daques que forem pares. Se o valor digitado for impar, desconsidere-o. """ soma = 0 for n in range (0, 6): numero = int(input('Digite um numero: ')) if numero %2 == 0: soma = soma + numero print(soma) print('FIM')
# In the 20×20 grid below, four numbers along a diagonal line have been marked in red. # # ``` # 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 # 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 # 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 # 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 # 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 # 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 # 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 # 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 # 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 # 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 # 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 # 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 # 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 # 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 # 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 # 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 # 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 # 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 # 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 # 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 # ``` # The product of these numbers is 26 × 63 × 78 × 14 = 1788696. # # What is the greatest product of four adjacent numbers in the same direction # (up, down, left, right, or diagonally) in the 20×20 grid? # # ------ # # Strategy # # - Create a matrix and load values into a list of lists # - Traverse each element in the row # - Create a temp list comprising of a legal set of elements that existing extending out in eight directions # - If the set is "illegal" i.e. the range goes beyond the boundaries of the grid, set phantom elements to zero or skip # - Compute the product of all elements in this tmp list and store it in a results list # - Find the max value in the results list and return it # adjacent_range = 4 input_grid = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48""" product_store = [] def main(): # Create the matrix matrix = load_grid(input_grid) # Using a,b instead of x,y because it will be confusing # without normalizing so it isn't y,x # a = 0 # Vertical, or row index # b = 0 # Horizontal, or column index a_max = len(matrix[0]) b_max = len(matrix) for a in range(a_max): for b in range(b_max): process_adjacent_products(matrix, (a, b), adjacent_range) print("Greatest product of four adjacent numbers in the same direction:") print(max(product_store)) def process_adjacent_products(_matrix, _coordinates, _range): # Moving counter-clockwise: E, SE, S, SW, W, NW, N, NE # where E, SE, and S are positively oriented from the origin # and N, NE, NW, W, and SW are negatively oriented from the origin # so the matrix is inverse for _ in range(2): process_products_over_range_and_direction(_matrix, _coordinates, _range) _matrix.reverse() _matrix = [sublist[::-1] for sublist in _matrix] def process_products_over_range_and_direction(_matrix, _coordinates, _range): _a = _coordinates[0] _b = _coordinates[1] # Just playing with an idea # (1, 0) Step increment a only (East to West) # (0, 1) Step increment b only (North to South) # (1, 1) Step increment both a and b (North-West to South-East) _cardinal_switches = [(1, 0), (0, 1), (1, 1)] for _switch in _cardinal_switches: _tmp_list = [] for _step in range(_range): # This test is to avoid index out of range errors if _a + (_switch[0] * _step) < len(_matrix[0]) and _b + (_switch[1] * _step) < len(_matrix): _tmp_list.append(_matrix[_a + (_switch[0] * _step)][_b + (_switch[1] * _step)]) product_store.append(get_product_of_list(_tmp_list)) def get_product_of_list(_list): _product = 1 for _factor in _list: _product *= _factor return _product def load_grid(_input): _output_matrix = [] _tmp_table = list(map(str, _input.split("\n"))) for _tmp_row in _tmp_table: _elements = list(map(int, _tmp_row.split(" "))) _output_matrix.append(_elements) return _output_matrix if __name__ == "__main__": main()
# In​ February, a major airline had 77.8​% of their flights arrive on time. Assume that the event that a given flight arrives on time is independent of the event that another flight arrives on time. # A writer plans to take four separate flights for her publisher next month. Assuming the airline has the same​ on-time performance as in​ February, what is the probability that all four flights arrive on​ time? prob = .778 round( prob * prob * prob * prob, 4 )
class Account: def __init__(self): self.__blocked: bool = False self.__bound: int = 1000000 self.__balance: int = 0 self.__max_credit: int = -1000 def deposit(self, _sum: int) -> bool: if self.__blocked : return False if _sum < 0 or _sum > self.__bound: return False self.__balance += _sum return True def withdraw(self, _sum: int) -> bool: if self.__blocked : return False if _sum < 0 or _sum > self.__bound : return False if self.__balance <= self.__max_credit + _sum: return False self.__balance -= _sum return True def get_balance(self) -> int: return self.__balance def get_max_credit(self) -> int: return -self.__max_credit def is_blocked(self) -> bool: return self.__blocked def block(self) -> None: self.__blocked = True def unblock(self) -> bool: if self.__balance < self.__max_credit: return False self.__blocked = False return True def set_max_credit(self, mc: int) -> bool: if abs(mc) > self.__bound: return False self.__max_credit = -mc return True
def process_sql_file(file_name): file, string = open(file_name, "r"), '' # for line in file, remove comments, space out '(' and ')', add line to output string: for line in file: line = line.rstrip() line = line.split('//')[0] line = line.split('--')[0] line = line.replace('(', ' ( ') line = line.replace(')', ' ) ') string += ' ' + line file.close() # remove multi-line comments: while string.find('/*') > -1 and string.find('*/') > -1: l_multi_line = string.find('/*') r_multi_line = string.find('*/') string = string[:l_multi_line] + string[r_multi_line + 2:] string = string.lower() # remove extra whitespaces and make list words = string.split() return words def find_table_names(words, rm_cte=False): table_names = set() previous_word = '' ctes = set() for word in words: if rm_cte and word == 'as': ctes.add(previous_word) if previous_word == 'from' or previous_word == 'join': if word != '(': if rm_cte and word not in ctes: table_names.add(word) if not rm_cte: table_names.add(word) previous_word = word return sorted(list(table_names)) # this function assumes that the .sql file does not have any syntax errors: def find_table_names_from_sql_file(file_name, rm_cte=False): words = process_sql_file(file_name) return find_table_names(words, rm_cte=rm_cte)
#Escreva um programa que leia três strings. Imprima o resultado da substituição na primeira, dos #caracteres da segunda pelos da terceira. string1 = input('Digite a primeira string: ') string2 = input('Digite a segunda string: ') string3 = input('Digite a terceira string: ') if len(string2) == len(string3): resultado = "" for i in string1: posicao = string2.find(i) if posicao != -1: resultado += string3[posicao] else: resultado += i if resultado == "": print('Todos os caracteres foram removidos!') else: print(f'\nOs caracteres {string2} foram substituídos por {string3} em {string1}, gerando: {resultado}\n') else: print('Erro! A segunda e a terceira string devem ter o mesmo tamanho!\n')
# Membership, identity, and logical operations x=[1,2,3] y=[1,2,3] print(x==y) #test equivalance print(x is y) #test object identity x=y # assignment print(x is y)
''' Created on Nov 20, 2014 This is a dummy to solve dependencies from error.py @author: Tim Gerhard ''' # The webfrontend does not dump errors. If this function is called anywhere, this simply doesn't matter. def dumpError(error): return
la_liga_goals = 43 champions_league_goals = 10 copa_del_rey_goals = 5 total_goals = la_liga_goals + champions_league_goals + copa_del_rey_goals
# Write a program that reads a temperature value and the letter C for Celsius or F for # Fahrenheit. Print whether water is liquid, solid, or gaseous at the given temperature # at sea level. type = str(input("Enter the temperature type, C for celsius or F for fahrenheit: ")) temperature = float(input("Enter the temperature: ")) if type == "C": if temperature >= 0 and temperature < 100: print("Water is liquid.") elif temperature >= 100: print("Water is gaseous.") else: print("Water is solid.") elif type == "F": if temperature >= 32 and temperature < 132: print("Water is liquid.") elif temperature >= 132: print("Water is gaseous.") else: print("Water is solid.")
def pop(heap): popped = heap[0] heap[0] = heap[-1] heap.pop() lq = len(heap) node = 0 while node < lq: minimum = heap[node] nxt_node = node l_node = node*2+1 r_node = node*2+2 if l_node < lq and heap[l_node] < minimum: minimum = heap[l_node] nxt_node = l_node if r_node < lq and heap[r_node] < minimum: minimum = heap[r_node] nxt_node = r_node if node != nxt_node: heap[node], heap[nxt_node] = heap[nxt_node], heap[node] node = nxt_node else: node = lq return popped def push(heap, item): heap.append(item) lq = len(heap) node = lq-1 while node > 0: nxt_node = (node-1)//2 if heap[nxt_node] > heap[node]: heap[node], heap[nxt_node] = heap[nxt_node], heap[node] node = nxt_node else: node = 0 # Read K, N, M from file # K: Convex-hull thickness # N: how many points, how many vertices # M: how many routes, how many edges # map(f, arr) -> for every element e in arr, we return f(e) and put back to arr # input().split(" ") -> ["10", "4", "7"]; # map(int, ["10", "4", "7"]) -> [10, 4, 7] K, N, M = map(int, input().split(" ")) # every element in routes is a dictionary # representation of the graph. routes = [{} for n in range(N)] for m in range(M): # for (m = 0; m < M; m++) # every loop sets append (t,h) to # routes[a-1][b-1] & routes[b-1][a-1] # a: start island, b: arriving island, t: edge length, h: wear amount a, b, t, h = map(int, input().split()) # routes[a-1] -> {} # {}.setdefault(b-1,[]) -> ({} -> {b-1, []}) return [] # [].append((t,h)) -> [(t,h)] # (t,h) # tuple routes[a-1].setdefault(b-1, []).append((t, h)) # a-1: {b-1: [(t,h)]} routes[b-1].setdefault(a-1, []).append((t, h)) # api: routes[a][b] -> [(t,h)] # infinity to be large INF = 10**10 # read the starting point to ending point # starting point:p, ending point:q p, q = map(int, input().split()) p, q = p-1, q-1 min_time = INF distance = [INF for n in range(N)] distance[p] = 0 visited = set() que = [(0, p, K)] while que: island = pop(que) if island[1] == q: min_time = island[0] break if island[1] in visited: continue visited.add(island[1]) # all the neighbors of island[1] for destination in routes[island[1]]: # routes[island[1]][destination] only returns one element for route in routes[island[1]][destination]: # route: (t_i, h_i) # distance[island[1]]: new distance to a new destination # destination: new destination # island[2] - route[1]: thickness left to_add = (distance[island[1]] + route[0], destination, island[2] - route[1]) # only if to_add[2] greater than 0, otherwise skip if to_add[2] > 0: if to_add[0] < distance[to_add[1]]: distance[to_add[1]] = to_add[0] push(que, to_add) if min_time == INF: min_time = -1 print(min_time)
def mike(): print("hola") mike() mike() mike() mike() mike()
# Python3 program to count triplets with # sum smaller than a given value # Function to count triplets with sum smaller # than a given value def countTriplets(arr, n, sum): # Sort input array arr.sort() # Initialize result ans = 0 # Every iteration of loop counts triplet with # first element as arr[i]. for i in range(0, n - 2): # Initialize other two elements as corner elements # of subarray arr[j+1..k] j = i + 1 k = n - 1 # Use Meet in the Middle concept while (j < k): # If sum of current triplet is more or equal, # move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum): k = k - 1 # Else move left corner else: # This is important. For current i and j, there # can be total k-j third elements. ans += (k - j) j = j + 1 return ans # Driver program if __name__ == '__main__': arr = [5, 3, 4, 7,1] n = len(arr) sum = 12 print(countTriplets(arr, n, sum))
""" 简单正则表达式的匹配 """ __author__ = 'Qiu Zongyan' #### 简化正则表达式匹配函数 ## 模式语言: ## 字符 c 与其自身匹配 ## ^ 与字符串开头匹配(匹配前缀) ## $ 与字符串结束匹配(匹配后缀) ## . 与任何字符匹配 ## * 和其前一字符一起,与该字符的0次或任意次出现匹配 ## 限制:字符串中不能出现上述元字符(不支持换意序列) def match(re, text): rlen, tlen = len(re), len(text) def match_here(re, i, text, j): """检查从text[j]开始的正文是否与re[i]开始的模式匹配""" while True: if i == rlen: return True if re[i] == '$': return i+1 == rlen and j == tlen if i+1 < rlen and re[i+1] == '*': return match_star(re[i], re, i+2, text, j) if j == tlen or (re[i] != '.' and re[i] != text[j]): return False i, j = i+1, j+1 def match_star(c, re, i, text, j): """在text里跳过0个或多个c后检查匹配""" for n in range(j, tlen): # print(c, n, i, j) if match_here(re, i, text, n): return True if text[n] != c and c != '.': break return False if re[0] == '^': if match_here(re, 1, text, 0): # 只匹配前缀 return 0 return -1 # 匹配前缀不成功 for n in range(tlen): # 检查各个位置的匹配 if match_here(re, 0, text, n): return n return -1 p1 = "a*b.*" p2 = "^ab*c.$" p3 = "a*bc.*bc" p4 = "aab*c$" print(match(p1, "bccdabaaabcbbabcccbc")) # 0 print(match(p1, "cccdabaaabcbbabcccbc")) # 4 print(match(p1, "cccdadcccbcbaabcccbc")) # 9 print(match(p2, "abbbbbca")) # 0 print(match(p2, "^^^^abbcd")) # -1 print(match(p2, "abbbbbcda")) # -1 print(match(p3, "bccdabaaabcbbabcccbc")) # 0 print(match(p3, "dccdabaaabcbbabcccbc")) # 6 print(match(p4, "hfahfjkhhaabbc")) # 9 print(match(p4, "hfahfjkhhaabbcd")) # -1
class UnknownResponseType(Exception): pass class UnknownDatetime(Exception): pass
t=int(input()) for i in range(t): s=int(input()) m=s%12 if m==1: print(s+11,'WS') elif m==2: print(s+9,'MS') elif m==3: print(s+7,'AS') elif m==4: print(s+5,'AS') elif m==5: print(s+3,'MS') elif m==6: print(s+1,'WS') elif m==7: print(s-1,'WS') elif m==8: print(s-3,'MS') elif m==9: print(s-5,'AS') elif m==10: print(s-7,'AS') elif m==11: print(s-9,'MS') elif m==0: print(s-11,'WS') # t=int(input()) # for i in range(t): # s=int(input()) # m=s%12 # l=11 # if m==0: # print(s-11,'WS') # for i in range(1,12): # if m==i: # print(s+l) # else: # l=l-2
__author__ = 'Mikhail' def add_line(line_one, line_two): """ >>> line_one = [1, 2, 3] >>> line_two = [1, 2, 3] >>> add_line(line_one, line_two) >>> line_one [2, 4, 6] >>> line_two [1, 2, 3] >>> add_line(line_two, line_one) >>> line_one [2, 4, 6] >>> line_two [3, 6, 9] """ for i in range(len(line_one)): line_one[i] += line_two[i] def multiply_by_value(line, value): """ >>> line_one = [1, 2, 3] >>> value = 5 >>> multiply_by_value(line_one, value) >>> line_one [5, 10, 15] """ for i in range(len(line)): line[i] *= value def gauss_method(matrix, result_vector): """ >>> matrix = [[1, 2, 3, 4], [1, 1, 1, 1], [1, 1, 2, 3], [1, 1, 2, 2]] >>> vector = [1, 0, 0, 0] >>> gauss_method(matrix, vector) >>> matrix [[1.0, -0.0, -0.0, -0.0], [-0.0, 1.0, -0.0, -0.0], [-0.0, -0.0, 1.0, -0.0], [0.0, 0.0, 0.0, 1.0]] >>> vector [-1.0, 1.0, -0.0, 0.0] >>> matrix = [[4, 2, 1], [7, 8, 9], [9, 1, 3]] >>> vector = [1, 1, 2] >>> gauss_method(matrix, vector) >>> matrix [[1.0, -0.0, -0.0], [-0.0, 1.0, -0.0], [-0.0, 6.082091352294336e-17, 1.0]] >>> vector [0.2608695652173913, 0.043478260869565265, -0.1304347826086957] >>> matrix = [[1, 3, 4], [2, 1, 4]] >>> vector = [4, 5] >>> gauss_method(matrix, vector) >>> matrix [[1.0, -0.0, 1.5999999999999996], [0.0, 1.0, 0.8]] >>> vector [2.1999999999999993, 0.6000000000000001] >>> matrix = [[1, 3, 2], [2, 6, 4], [1, 4, 3]] >>> vector = [7, 8, 1] >>> gauss_method(matrix, vector) >>> matrix [[1.0, -0.0, -1.0], [-0.0, 1.0, 1.0], [0.0, 0.0, 0.0]] >>> vector [24.999999999999996, -6.0, 3.0] >>> matrix = [[1, 1, -3], [2, 1, -2], [1, 1, 1], [1, 2, -3]] >>> vector = [-1, 1, 3, 1] >>> gauss_method(matrix, vector) >>> matrix [[1.0, -0.0, -0.0], [0.0, 1.0, 0.0], [-0.0, -0.0, 1.0], [0.0, 0.0, 0.0]] >>> vector [1.0, 1.0, 1.0, -0.25] >>> matrix = [[3, 3, -1], [1, -2, -3], [2, 1, -2]] >>> vector = [1, -11, -4] >>> gauss_method(matrix, vector) >>> matrix [[1.0, -0.0, 0.0], [0.0, 1.0, -0.0], [-0.0, -0.0, 1.0]] >>> vector [-1.0, 2.0, 2.0] """ the_smallest_matrix_size = min(len(matrix), len(matrix[0])) the_matrix_size = len(matrix) # forward for forward_row_id in range(the_smallest_matrix_size): column_id = forward_row_id if matrix[forward_row_id][column_id] == 0: # attempt to identify required row rows_were_switched = False for another_modified_row_id in range(forward_row_id + 1, the_matrix_size): if matrix[another_modified_row_id][column_id] != 0: # switch rows in the matrix for matrix_column_id in range(column_id, len(matrix[0]), 1): matrix[forward_row_id][matrix_column_id], matrix[another_modified_row_id][matrix_column_id] = \ matrix[another_modified_row_id][matrix_column_id], matrix[forward_row_id][matrix_column_id] # switch elements in result vector result_vector[forward_row_id], result_vector[another_modified_row_id] = \ result_vector[another_modified_row_id], result_vector[forward_row_id] rows_were_switched = True break if not rows_were_switched: continue normalization_value = matrix[forward_row_id][column_id] # change value on the element on diagonal multiply_by_value(matrix[forward_row_id], 1.0/normalization_value) result_vector[forward_row_id] *= 1.0/normalization_value # modification for modified_row_id in range(forward_row_id + 1, the_matrix_size): if matrix[modified_row_id][column_id] != 0: direct_or_reverse_gauss_step(column_id, forward_row_id, matrix, modified_row_id, result_vector) # reverse for reverse_row_id in range(the_smallest_matrix_size - 1, -1, -1): column_id = reverse_row_id if matrix[reverse_row_id][column_id] != 0: normalization_value = matrix[reverse_row_id][column_id] # change value on the element on diagonal multiply_by_value(matrix[reverse_row_id], 1.0/normalization_value) result_vector[reverse_row_id] *= 1.0/normalization_value # modification for modified_row_id in range(reverse_row_id - 1, -1, -1): if matrix[modified_row_id][column_id] != 0: direct_or_reverse_gauss_step(column_id, reverse_row_id, matrix, modified_row_id, result_vector) def direct_or_reverse_gauss_step(column_id, forward_row_id, matrix, modified_row_id, result_vector): """ """ modification = -(matrix[forward_row_id][column_id]) / (matrix[modified_row_id][column_id]) # normalise matrix row multiply_by_value(matrix[modified_row_id], modification) # normalise result vector result_vector[modified_row_id] *= modification # change required row add_line(matrix[modified_row_id], matrix[forward_row_id]) # change result vector result_vector[modified_row_id] += result_vector[forward_row_id] def analyse_gauss_method_results(matrix, result_vector): """ >>> matrix = [[1.0, -0.0, -0.0], [-0.0, 1.0, -0.0], [-0.0, 6.082091352294336e-17, 1.0]] >>> result_vector = [0.2608695652173913, 0.043478260869565265, -0.1304347826086957] >>> analyse_gauss_method_results(matrix, result_vector) YES 0.260869565217 0.0434782608696 -0.130434782609 >>> processed_matrix = [[1.0, -0.0, -1.0], [-0.0, 1.0, 1.0], [0.0, 0.0, 0.0]] >>> result_vector = [24.999999999999996, -6.0, 3.0] >>> analyse_gauss_method_results(processed_matrix, result_vector) NO >>> processed_matrix = [[1.0, -0.0, 1.5999999999999996], [0.0, 1.0, 0.8]] >>> result_vector = [2.1999999999999993, 0.6000000000000001] >>> analyse_gauss_method_results(processed_matrix, result_vector) INF >>> processed_matrix = [[1.0, -0.0, -0.0], [0.0, 1.0, 0.0], [-0.0, -0.0, 1.0], [0.0, 0.0, 0.0]] >>> result_vector = [1.0, 1.0, 1.0, -0.25] >>> analyse_gauss_method_results(processed_matrix, result_vector) NO """ # check on situation when the system has no answer for row_id, row in enumerate(matrix): if all([abs(row_element) < 1.0e-8 for row_element in matrix[row_id]]) and abs(result_vector[row_id]) > 1.0e-8: print("NO") return # system has infinite number of answers if len(matrix) < len(matrix[0]): print("INF") return # system has only one answer print("YES") print(" ".join([str(res) for res in result_vector])) if __name__ == "__main__": # data initialization data = list(map(lambda x: int(x), input().split())) amount_of_equations = data[0] amount_of_variables = data[1] initial_matrix = list() initial_vector = list() for equation_id in range(amount_of_equations): equation = list(map(lambda x: float(x), input().split())) initial_matrix.append(equation[:-1]) initial_vector.append(equation[-1]) gauss_method(initial_matrix, initial_vector) analyse_gauss_method_results(initial_matrix, initial_vector)
# # @lc app=leetcode id=25 lang=python3 # # [25] Reverse Nodes in k-Group # # https://leetcode.com/problems/reverse-nodes-in-k-group/description/ # # algorithms # Hard (46.35%) # Likes: 4377 # Dislikes: 423 # Total Accepted: 383.3K # Total Submissions: 813.3K # Testcase Example: '[1,2,3,4,5]\n2' # # Given a linked list, reverse the nodes of a linked list k at a time and # return its modified list. # # k is a positive integer and is less than or equal to the length of the linked # list. If the number of nodes is not a multiple of k then left-out nodes, in # the end, should remain as it is. # # You may not alter the values in the list's nodes, only nodes themselves may # be changed. # # # Example 1: # # # Input: head = [1,2,3,4,5], k = 2 # Output: [2,1,4,3,5] # # # Example 2: # # # Input: head = [1,2,3,4,5], k = 3 # Output: [3,2,1,4,5] # # # Example 3: # # # Input: head = [1,2,3,4,5], k = 1 # Output: [1,2,3,4,5] # # # Example 4: # # # Input: head = [1], k = 1 # Output: [1] # # # # Constraints: # # # The number of nodes in the list is in the range sz. # 1 <= sz <= 5000 # 0 <= Node.val <= 1000 # 1 <= k <= sz # # # # Follow-up: Can you solve the problem in O(1) extra memory space? # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if not head: return head dummy = ListNode(0, head) head = dummy while head: head = self._reverseK(head, k) return dummy.next def _reverseK(self, node, k): n1, nk = node.next, node for _ in range(k): nk = nk.next if nk is None: return nk nk_next = nk.next # reverse prev, curt = None, n1 while curt != nk_next: tmp = curt.next curt.next = prev prev = curt curt = tmp # connect node.next = nk n1.next = nk_next return n1 # @lc code=end
def mergeSortedArrays(L, R): sorted_array = [] i = j = 0 while i < len(L) and j < len(R): if L[i] < R[j]: sorted_array.append(L[i]) i += 1 else: sorted_array.append(R[j]) j += 1 # When we run out of elements in either L or M, # pick up the remaining elements and put in A[p..r] while i < len(L): sorted_array.append(L[i]) i += 1 while j < len(R): sorted_array.append(R[j]) j += 1 return sorted_array def mergeSort(nums): # exit condition!!! Important for a recursion! if (len(nums) <= 1): return nums # split the array to two smaller arrays middle = len(nums) // 2 L = nums[:middle] R = nums[middle:] # sort the smalle5r arrays L = mergeSort(L) R = mergeSort(R) nums = mergeSortedArrays(L, R) return nums array = [6, 5, 12, 10, 9, 1] mergeSort(array) print(array)
"abcd".startswith("ab") #returns True "abcd".endswith("zn") #returns False "bb" in "abab" #returns False "ab" in "abab" #returns True loc = "abab".find("bb") #returns -1 loc = "abab".find("ab") #returns 0 loc = "abab".find("ab",loc+1) #returns 2
# -*- encoding: utf-8 -*- """ Copyright (c) Minu Kim - minu.kim@kaist.ac.kr Templates from AppSeed.us This file is hidden for privacy issues. """
SOLVERS = ( { 'type': 'local', 'name': 'leo3', 'pretty-name': 'Leo III', 'version': '1.4', 'command': 'leo3 %s -t %d', }, { 'type': 'local', 'name': 'cvc4', 'command': 'cvc4 --output-lang tptp --produce-models --tlimit=%md %s', }, { 'type': 'local', 'name': 'picosat', 'command': './solvers/picosat-tptp.sh -L %d %s', }, { 'type': 'local', 'name': 'satisfiable-dummy', 'command': './solvers/satisfiable-dummy.sh %s -t %d', }, { 'type': 'local', 'name': 'unsatisfiable-dummy', 'command': './solvers/unsatisfiable-dummy.sh %s -t %d', }, { 'type': 'local', 'name': 'gaveup-dummy', 'command': './solvers/gaveup-dummy.sh %s -t %d', }, )
"""Choices for Rider APP""" status_choices = ( ('in_shop', 'In Shop'), ('enroute_destination', 'Enroute destination'), ('delivered', 'Delivered') ) IN_SHOP = 'in_shop'
""" For ease of use, please lay out your grid in Euclidean-plane format and NOT in numpy-type format. For example, if an object needs to be placed in the 3rd row and 7th column of the gridworld numpy matrix, enter its location in your layout dict as [7,3]. The codebase will take care of the matrix-indexing for you. For example, the above object will be queried as grid[3, 7] when placed into the grid. NOTE: the origin (0,0) is the top-left corner of the grid. The positive direction along the x-axis counts to the right and the positive direction along the y-axis """ LINEAR = { 'FOUR_PLAYERS': { 'WALLS': [ # First wall [0, 11], [1, 11], [2, 11], [3, 11], [4, 11], [5, 11], [8, 11], # Second wall [0, 7], [1, 7], [4, 7], [5, 7], [6, 7], [7, 7], [8, 7], # Third wall [0, 3], [1, 3], [2, 3], [3, 3], [4, 3], [5, 3], [8, 3] ], # Doors are double doors of coord [[x1,x2], [y1,y2]] 'DOORS': [ [[6, 7], [11, 11]], [[2, 3], [7, 7]], [[6, 7], [3, 3]] ], 'PLATES': [ [7, 13], [2, 9], [7, 5] ], 'AGENTS': [ [5, 13], [5, 12], [4, 13], [4, 12] ], 'GOAL': [ [3, 1] ] }, 'FIVE_PLAYERS': { 'WALLS': [ # First wall [0, 15], [1, 15], # [4, 15], [5, 15], [6, 15], [7, 15], [8, 15], # Second wall [0, 11], [1, 11], [2, 11], [3, 11], [4, 11], # [5, 11], [8, 11], # Third wall [0, 7], [1, 7], # [4, 7], [5, 7], [6, 7], [7, 7], [8, 7], # Fourth wall [0, 3], [1, 3], [2, 3], [3, 3], [4, 3], # [5, 3], [8, 3], ], # Doors are double doors of coord [[x1,x2], [y1,y2]] 'DOORS': [ [[2, 3, 4], [15, 15, 15]], [[5, 6, 7], [11, 11, 11]], [[2, 3, 4], [7, 7, 7]], [[5, 6, 7], [3, 3, 3]] ], 'PLATES': [ [2, 17], [7, 13], [2, 9], [7, 5] ], 'AGENTS': [ [6, 16], [5, 17], [5, 16], [4, 17], [4, 16] ], 'GOAL': [ [3, 1] ] }, 'SIX_PLAYERS': { 'WALLS': [ # First wall [0, 19], [1, 19], [2, 19], [3, 19], [4, 19], # [5, 19], [8, 19], # Second wall [0, 15], [1, 15], # [4, 15], [5, 15], [6, 15], [7, 15], [8, 15], # Third wall [0, 11], [1, 11], [2, 11], [3, 11], [4, 11], # [5, 11], [8, 11], # Fourth wall [0, 7], [1, 7], # [4, 7], [5, 7], [6, 7], [7, 7], [8, 7], # Fifth wall [0, 3], [1, 3], [2, 3], [3, 3], [4, 3], # [5, 3], [8, 3], ], # Doors are double doors of coord [[x1,x2], [y1,y2]] 'DOORS': [ [[5, 6, 7], [19, 19, 19]], [[2, 3, 4], [15, 15, 15]], [[5, 6, 7], [11, 11, 11]], [[2, 3, 4], [7, 7, 7]], [[5, 6, 7], [3, 3, 3]] ], 'PLATES': [ [7, 21], [2, 17], [7, 13], [2, 9], [7, 5] ], 'AGENTS': [ [6, 21], [6, 20], [5, 21], [5, 20], [4, 21], [4, 20] ], 'GOAL': [ [3, 1] ] } }
SEED_URLS = [ "https://www.microsoft.com/en-ca/p/immortals-fenyx-rising/c07kjzrh0l7s?activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/grand-theft-auto-v-premium-edition/C496CLVXMJP8?wa=wsignin1.0&lc=4105&activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/far-cry-5/br7x7mvbbqkm?activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/pathfinder-kingmaker-definitive-edition/bphqqn22gb7l?activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/call-of-duty-modern-warfare---digital-standard-edition/9NVQBQ3F6W9W?activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/ori-and-the-will-of-the-wisps/9N8CD0XZKLP4?activetab=pivot:overviewtab", "https://www.microsoft.com/EN-CA/p/red-dead-redemption-2/9N2ZDN7NWQKV?activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/tom-clancys-rainbow-six-siege-deluxe-edition/9p30k2nxwh82?activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/pillars-of-eternity-complete-edition/bs34vnw7h61f?activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/pillars-of-eternity-ii-deadfire-ultimate-edition/9pjd2kmx7tz6?activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/astroneer/9nblggh43kzb?cid=msft_web_chart&activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/farm-together/9mxsdjxfzq25?cid=msft_web_chart&activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/Mafia-III-Definitive-Edition/BVZLS7XZ68KF?rtc=1&activetab=pivot:overviewtab", "https://www.microsoft.com/EN-CA/p/little-nightmares/BWD88K55MK5W?id=Pubsalegame_Week13&activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/Nexomon-Extinction/9NCJR504WXT0?rtc=1&activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/GreedFall/BWMH4RQ4Q06F?rtc=1&activetab=pivot:overviewtab", "https://www.microsoft.com/en-ca/p/outriders-standard-edition/9p12rcxbf02p?activetab=pivot:overviewtab", ]
# salva no copiateste.txt o mesmo conteudo do teste.txt with open('teste.txt', 'r') as arquivolido: with open('copiateste.txt', 'w') as arquivocriado: for linha in arquivolido: arquivocriado.write(linha)
class Event: def __init__(self, event_type, time, direction, intersection): self.event_type = event_type self.time = time self.direction = direction self.intersection = intersection
""" Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". import zlib s = 'hello world!hello world!hello world!hello world!' # In Python 3 zlib.compress() accepts only DataType <bytes> y = bytes(s, 'utf-8') x = zlib.compress(y) print(x) print(zlib.decompress(x)) """ """ Please write a program to print the running time of execution of "1+1" for 100 times. import datetime before = datetime.datetime.now() for i in range(100): x = 1 + 1 after = datetime.datetime.now() execution_time = after - before print(execution_time.microseconds) """ """ Please write a program to shuffle and print the list [3,6,7,8]. import random lst = [3,6,7,8] random.shuffle(lst) print(lst) """ """ Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. if __name__ == '__main__': sub=['I','You'] verb=['Play','Love'] obj=['Hockey','Football'] for i in sub: for j in verb: for k in obj: print(f'{i} {j} {k}') """
#write import statement for reverse string function ''' 10 points Write a main function to .... Loop as long as user types y. Prompt user for a string (assume user will always give you good data). Pass the string to the reverse string function and display the reversed string '''
day = str(input()) if (day == "Monday") or (day == "Tuesday") or (day == "Friday"): print("12") elif (day == "Wednesday") or (day == "Thursday"): print("14") else: print("16")
''' Joãozinho tem que ajudar seu pai. Um relatório específico com alguns números está saindo com caracteres indesejáveis no meio. A ideia é apenas somar os 3 valores que aparecem em cada linha sempre na mesma posição, ignorando as letras e apresentar esta soma. Não existem espaços em branco na linha. Entrada A primeira linha de entrada contém um inteiro N (N < 100000). Seguem N linhas com exatos 14 caracteres que devem ser lidas e delas extraídos e somados os três números existentes. Saída Para cada linha de entrada, seu programa deve apresentar um valor numérico inteiro, que é a soma dos 3 números existentes na linha. ''' N = int(input()) for _ in range(N): string = list(input()) num = '0'; soma = [] for i in string: if i.isdigit(): soma.append(i) else: soma.append(' ') num = '' soma = map(int, ''.join(soma).split()) print(sum(soma))
def two_fer(name=""): if not name.strip(): return "One for you, one for me." else: return "One for {}, one for me.".format(name)
""" The probe's x,y position starts at 0,0. Then, it will follow some trajectory by moving in steps. On each step, these changes occur in the following order: The probe's x position increases by its x velocity. The probe's y position increases by its y velocity. Due to drag, the probe's x velocity changes by 1 toward the value 0; that is, it decreases by 1 if it is greater than 0, increases by 1 if it is less than 0, or does not change if it is already 0. Due to gravity, the probe's y velocity decreases by 1. """ def get_max(x_pos, y_pos, x_velocity, y_velocity, target_x1, target_x2, target_y1, target_y2): max_y = -100 while x_pos <= target_x2 and y_pos >= target_y2: if y_pos > max_y: max_y = y_pos x_pos, y_pos, x_velocity, y_velocity = calc_pos_and_velocity(x_pos, y_pos, x_velocity, y_velocity) if x_pos >= target_x1 and x_pos <= target_x2 and y_pos <= target_y1 and y_pos >= target_y2: return max_y return -100 def calc_pos_and_velocity(x, y, x_velocity, y_velocity): x_pos = x + x_velocity y_pos = y + y_velocity if x_velocity == 0: x_velocity = 0 elif x_velocity > 0: x_velocity -= 1 else: x_velocity += 1 y_velocity -= 1 return x_pos, y_pos, x_velocity, y_velocity def main(): # Example data # target area: x=20..30, y=-10..-5 target_x1 = 20 target_x2 = 30 target_y1 = -5 target_y2 = -10 x_pos = 0 y_pos = 0 x_vel = 6 y_vel = 3 max_y = get_max(x_pos, y_pos, x_vel, y_vel, target_x1, target_x2, target_y1, target_y2) assert max_y == 6, f'Expected 6, got {max_y}' x_vel = 6 y_vel = 9 max_y = get_max(x_pos, y_pos, x_vel, y_vel, target_x1, target_x2, target_y1, target_y2) assert max_y == 45, f'Expected 45, got {max_y}' # 17,-4 # Never reach target zone x_vel = 17 y_vel = -4 max_y = get_max(x_pos, y_pos, x_vel, y_vel, target_x1, target_x2, target_y1, target_y2) assert max_y == -100, f'Expected -100, got {max_y}' max_ys = [] max_set = set() for x in range(0, 1000): for y in range(-100, 100): x_vel = x y_vel = y max_y = get_max(x_pos, y_pos, x_vel, y_vel, target_x1, target_x2, target_y1, target_y2) if max_y != -100: max_ys.append(max_y) max_set.add((x_vel, y_vel)) # print(max_ys) print(max(max_ys)) assert max(max_ys) == 45, f'Expected 45, got {max(max_ys)}' # print(max_set) print(len(max_set)) assert len(max_set) == 112, f'Expected 112, got {len(max_set)}' # target area: x=155..215, y=-132..-72 print('INPUT DATA: target area: x=155..215, y=-132..-72') target_x1 = 155 target_x2 = 215 target_y1 = -72 target_y2 = -132 x_pos = 0 y_pos = 0 max_ys = [] max_set = set() for x in range(0, 1000): for y in range(-500, 500): x_vel = x y_vel = y max_y = get_max(x_pos, y_pos, x_vel, y_vel, target_x1, target_x2, target_y1, target_y2) if max_y != -100: max_ys.append(max_y) max_set.add((x_vel, y_vel)) # print(max_ys) print(max(max_ys)) assert max(max_ys) == 8646, f'Expected 8646, got {max(max_ys)}' print(len(max_set)) assert len(max_set) == 5945, f'Expected 5945, got {len(max_set)}' if __name__ == '__main__': main()
""" Write a Python program to check if two given strings are isomorphic to each other or not. """ def isIsomorphic(str1, str2): dict_str1 = {} dict_str2 = {} for i, value in enumerate(str1): dict_str1[value] = dict_str1.get(value, []) + [i] for j, value in enumerate(str2): dict_str2[value] = dict_str2.get(value, []) + [j] if sorted(dict_str1.values()) == sorted(dict_str2.values()): return True else: return False print(isIsomorphic("foo", "bar"))
class Args: def __init__(self, config, checkpoint): self.cfg = config self.checkpoint = checkpoint self.sp = True self.detector = "yolo" self.inputpath = "./" self.inputlist = "" self.inputimg = "" self.outputpath = "examples/res/" self.save_img = False self.vis = False self.profile = False self.format = "open" self.min_box_area = 0 self.detbatch = 5 self.posebatch = 80 self.eval = False self.gpus = "0" self.qsize = 1024 self.flip = False self.debug = False self.video = "" self.webcam = 1 self.save_video = False self.vis_fast = False self.pose_track = False
PANDA_MODELS = dict( gt_joints='dream-panda-gt_joints--495831', predict_joints='dream-panda-predict_joints--173472', ) KUKA_MODELS = dict( gt_joints='dream-kuka-gt_joints--192228', predict_joints='dream-kuka-predict_joints--990681', ) BAXTER_MODELS = dict( gt_joints='dream-baxter-gt_joints--510055', predict_joints='dream-baxter-predict_joints--519984', ) OWI_MODELS = dict( predict_joints='craves-owi535-predict_joints--295440', ) PANDA_ABLATION_REFERENCE_POINT_MODELS = dict( link0='dream-panda-gt_joints-reference_point=link0--864695', link1='dream-panda-gt_joints-reference_point=link1--499756', link2='dream-panda-gt_joints-reference_point=link2--905185', link4='dream-panda-gt_joints-reference_point=link4--913645', link5='dream-panda-gt_joints-reference_point=link5--669469', link9='dream-panda-gt_joints-reference_point=hand--588677', ) PANDA_ABLATION_ANCHOR_MODELS = dict( link0='dream-panda-predict_joints-anchor=link0--90648', link1='dream-panda-predict_joints-anchor=link1--375503', link2='dream-panda-predict_joints-anchor=link2--463951', link4='dream-panda-predict_joints-anchor=link4--388856', link5='dream-panda-predict_joints-anchor=link5--249745', link9='dream-panda-predict_joints-anchor=link9--106543', random_all='dream-panda-predict_joints-anchor=random_all--116995', random_top3='dream-panda-predict_joints-anchor=random_top_3_largest--65378', random_top5=PANDA_MODELS['predict_joints'], ) PANDA_ABLATION_ITERATION_MODELS = { 'n_train_iter=1': 'dream-panda-predict_joints-n_train_iter=1--752826', 'n_train_iter=2': 'dream-panda-predict_joints-n_train_iter=2--949003', 'n_train_iter=5': 'dream-panda-predict_joints-n_train_iter=5--315150', } RESULT_ID = 1804 DREAM_PAPER_RESULT_IDS = [ f'dream-{robot}-dream-all-models--{RESULT_ID}' for robot in ('panda', 'kuka', 'baxter') ] DREAM_KNOWN_ANGLES_RESULT_IDS = [ f'dream-{robot}-knownq--{RESULT_ID}' for robot in ('panda', 'kuka', 'baxter') ] DREAM_UNKNOWN_ANGLES_RESULT_IDS = [ f'dream-{robot}-unknownq--{RESULT_ID}' for robot in ('panda', 'kuka', 'baxter') ] PANDA_KNOWN_ANGLES_ITERATIVE_RESULT_IDS = [ f'dream-panda-orb-knownq--{RESULT_ID}', f'dream-panda-orb-knownq-online--{RESULT_ID}' ] CRAVES_LAB_RESULT_IDS = [ f'craves-lab-unknownq--{RESULT_ID}' ] CRAVES_YOUTUBE_RESULT_IDS = [ f'craves-youtube-unknownq-focal={focal}--{RESULT_ID}' for focal in (500, 750, 1000, 1250, 1500, 1750, 2000) ] PANDA_KNOWN_ANGLES_ABLATION_RESULT_IDS = [ f'dream-panda-orb-knownq-link{link_id}--{RESULT_ID}' for link_id in (0, 1, 2, 4, 5, 9) ] PANDA_UNKNOWN_ANGLES_ABLATION_RESULT_IDS = [ f'dream-panda-orb-unknownq-{anchor}--{RESULT_ID}' for anchor in ('link5', 'link2', 'link1', 'link0', 'link4', 'link9', 'random_all', 'random_top5', 'random_top3') ] PANDA_ITERATIONS_ABLATION_RESULT_IDS = [ f'dream-panda-orb-train_K={train_K}--{RESULT_ID}' for train_K in (1, 2, 3, 5) ]
n = int(input()) narr = list(map(int,input().split())) ev,od = 0,0 for i in range(n): if narr[i]%2==0: ev+=narr[i] else: od+=narr[i] print(od-ev)
def linear_search(array, n): """ - Definition - In computer science, linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list. Comlexity: Time Complexity: O(n) - since in worst case we're checking each element exactly once. """ is_found = False for i in array: if i == n: is_found = True else: continue return is_found
def _resource_from_cache_prefix(resource, cache): """ Combine the resource name with the cache prefix (if any) """ if getattr(cache, 'key_prefix', None): name = '{} {}'.format(resource, cache.key_prefix) else: name = resource # enforce lowercase to make the output nicer to read return name.lower() def quantize_key_values(key): """ Used in the Django trace operation method, it ensures that if a dict with values is used, we removes the values from the span meta attributes. For example:: >>> quantize_key_values({'key', 'value'}) # returns ['key'] """ if isinstance(key, dict): return key.keys() return key
#!usr/bin/env python3 # -*- coding:utf-8 -*- ''' Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. ''' class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): if nums[i] == target: left = i break else: return [-1, 1] # find the index of the rightmost appearance of `target` (by reverse # iteration). it is guaranteed to appear. for j in range(len(nums) - 1, -1, -1): if nums[j] == target: right = j break return [left, right] if __name__ == "__main__": assert Solution().searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4] assert Solution().searchRange([5, 7, 7, 8, 8, 10], 5) == [0, 0] assert Solution().searchRange([5, 7, 7, 8, 8, 10], 7) == [1, 2] assert Solution().searchRange([5, 7, 7, 8, 8, 10], 10) == [5, 5]
# Here we assume that cs_array has the dimensions (n_bins, n_chans, n_seg) # Where n_chans is the number of channels of interest ## cs_array has been filtered before this step cs_avg = np.mean(cs_array, axis=-1) ## Take the IFFT of the cross spectrum to get the CCF ccf_avg = fftpack.ifft(cs_avg, axis=0).real ccf_array = fftpack.ifft(cs_array, axis=0).real ## Apply normalization ccv_avg *= (2.0 / np.float(n_bins) / ref_rms) ccf_array *= (2.0 / np.float(n_bins) / ref_rms) ## Compute the standard error on each ccf bin from the segment-to-segment ## variations. ccf_resid = (ccf_array.T - ccf_avg.T).T ## Eqn 2.3 from S. Vaughan 2013, "Scientific Inference" sample_var = np.sum(ccf_resid**2, axis=2) / (meta_dict['n_seg'] - 1) ## Eqn 2.4 from S. Vaughan 2013, "Scientific Inference" standard_error = np.sqrt(sample_var / meta_dict['n_seg']) return ccf_avg, standard_error
# Copyright (c) 2017 Dustin Toff # Licensed under Apache License v2.0 load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository", "new_git_repository") def new_github_repository(name = None, user = None, project = None, commit = None, tag = None, sha256 = None, build_file = None, build_file_content = None): """ Equivalent to new_git_repository but for github repos If sha256 is set, the repository will be downloaded in its .tar.gz form, ensuring the bytes do not change over time, even when using a tag which may be changed in the origin. """ if sha256 != None: # Ordered by specificity id = commit or tag # GitHub strips the "v" from tags like "v1.0" and uses "1.0" instead github_id = id for num in range(10): if id.startswith("v{n}".format(n = num)): github_id = id[1:] break return http_archive(**{ "name": name, "sha256": sha256, "strip_prefix": "{project}-{id}".format(project = project, id = github_id), "urls": [ "https://github.com/{user}/{project}/archive/{id}.tar.gz".format(user = user, project = project, id = id), ], "build_file": build_file, "build_file_content": build_file_content, }) else: if build_file != None or build_file_content != None: method = new_git_repository else: method = git_repository return method(**{ "name": name, "remote": "https://github.com/{user}/{project}.git".format(user = user, project = project), "commit": commit, "tag": tag, "build_file": build_file, "build_file_content": build_file_content, }) def github_repository(name = None, user = None, project = None, commit = None, tag = None, sha256 = None): """ Equivalent to new_git_repository but for github repos """ return new_github_repository(name = name, user = user, project = project, commit = commit, tag = tag, sha256 = sha256)
""" sqmpy ~~~~~ A job management web application that makes it easier for scientists to submit and monitor jobs to remote to remote resources. `sqm' stands for Simple Queue Manager. """ __author__ = 'Mehdi Sadeghi' __version__ = '0.4'
int_list = list(map(int, input().split())) movement = int(input()) for i in range(movement): int_list.append(int_list[0]) int_list.remove(int_list[0]) print(int_list)
total = 0 count = 0 average = 0 smallest = None largest = None print('before largest:', largest) while True: inp = input('>') if inp == "done": break try: if float(inp): total += float(inp) count += 1 new_value = float(inp) if largest is None or new_value > largest: largest = new_value print('new_largest is', largest) if smallest is None or new_value < smallest: smallest = new_value print('new_smallest is', smallest) except ValueError: print('invalid input') if count != 0: print('done') print('largest is', largest) print('smallest is', smallest) print('count is', count) print(total) print('average=', total / count) else: print('enter a number please')
# # PySNMP MIB module Nortel-MsCarrier-MscPassport-AlarmMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-AlarmMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:19:28 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") ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint") DateAndTime, DisplayString, Unsigned32, RowPointer = mibBuilder.importSymbols("Nortel-MsCarrier-MscPassport-StandardTextualConventionsMIB", "DateAndTime", "DisplayString", "Unsigned32", "RowPointer") HexString, Hex, DigitString, AsciiString = mibBuilder.importSymbols("Nortel-MsCarrier-MscPassport-TextualConventionsMIB", "HexString", "Hex", "DigitString", "AsciiString") mscPassportMIBs, mscPassportTraps = mibBuilder.importSymbols("Nortel-MsCarrier-MscPassport-UsefulDefinitionsMIB", "mscPassportMIBs", "mscPassportTraps") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, TimeTicks, MibIdentifier, Counter32, NotificationType, Unsigned32, Gauge32, Counter64, iso, Integer32, ModuleIdentity, Bits, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "TimeTicks", "MibIdentifier", "Counter32", "NotificationType", "Unsigned32", "Gauge32", "Counter64", "iso", "Integer32", "ModuleIdentity", "Bits", "NotificationType") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") alarmMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4)) mscAlarmTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2)) mscMandatoryAlarmInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7)) mscComponentRowPointer = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 1), RowPointer()) if mibBuilder.loadTexts: mscComponentRowPointer.setStatus('mandatory') mscComponentName = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 2), DisplayString()) if mibBuilder.loadTexts: mscComponentName.setStatus('mandatory') mscEventTime = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 3), DateAndTime()) if mibBuilder.loadTexts: mscEventTime.setStatus('mandatory') mscActiveListStatus = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("message", 0), ("set", 1), ("clear", 2)))) if mibBuilder.loadTexts: mscActiveListStatus.setStatus('mandatory') mscSeverity = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("indeterminate", 0), ("critical", 1), ("major", 2), ("minor", 3), ("warning", 4), ("cleared", 5)))) if mibBuilder.loadTexts: mscSeverity.setStatus('mandatory') mscAlarmType = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("communications", 0), ("qualityOfService", 1), ("processing", 2), ("equipment", 3), ("environmental", 4), ("security", 5), ("operator", 6), ("debug", 7), ("unknown", 8)))) if mibBuilder.loadTexts: mscAlarmType.setStatus('mandatory') mscProbableCause = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 22, 23, 24, 25, 26, 27, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 80, 81, 82, 83, 84, 90, 91, 92, 93, 100, 101, 102, 110, 111, 112, 113, 114, 120, 121, 122, 200, 201, 202, 203, 204))).clone(namedValues=NamedValues(("lossOfSignal", 0), ("lossOfFrame", 1), ("framingError", 2), ("localTransmissionError", 3), ("remoteTransmissionError", 4), ("callEstablishmentError", 5), ("degradedSignal", 6), ("commSubsystemFailure", 7), ("commProtocolError", 8), ("lanError", 9), ("dteDceInterfaceError", 10), ("responseTimeExcessive", 20), ("queueSizeExceeded", 21), ("bandwidthReduced", 22), ("retransmissionRateReduced", 23), ("thresholdCrossed", 24), ("performanceDegraded", 25), ("congestion", 26), ("atOrNearCapacity", 27), ("storageCapacityProblem", 40), ("versionMismatch", 41), ("corruptData", 42), ("cpuCyclesLimitExceeded", 43), ("softwareError", 44), ("softwareProgramError", 45), ("softwareProgramTermination", 46), ("fileError", 47), ("outOfMemory", 48), ("underlyingResourceUnavail", 49), ("applicationSubsystemFailure", 50), ("configurationError", 51), ("powerProblem", 60), ("timingProblem", 61), ("processorProblem", 62), ("datasetModemError", 63), ("multiplexorProblem", 64), ("receiverFailure", 65), ("transmitterFailure", 66), ("outputDeviceError", 67), ("inputDeviceError", 68), ("ioDeviceError", 69), ("equipmentFailure", 70), ("adapterError", 71), ("duplicateInfo", 80), ("infoMissing", 81), ("infoModification", 82), ("infoOutOfSequence", 83), ("unexpectedInfo", 84), ("denialOfService", 90), ("outOfService", 91), ("proceduralError", 92), ("otherOperational", 93), ("cableTamper", 100), ("intrusionDetection", 101), ("otherPhysical", 102), ("authenticationFailure", 110), ("breachOfConfidence", 111), ("nonRepudiationFailure", 112), ("unauthorizedAccess", 113), ("otherSecurityService", 114), ("delayedInfo", 120), ("keyExpired", 121), ("outOfHoursActivity", 122), ("operationalCondition", 200), ("debugging", 201), ("unknown", 202), ("inactiveVirtualCircuit", 203), ("networkServerIntervention", 204)))) if mibBuilder.loadTexts: mscProbableCause.setStatus('mandatory') mscNtpIndex = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 8), DigitString().subtype(subtypeSpec=ValueSizeConstraint(8, 8)).setFixedLength(8)) if mibBuilder.loadTexts: mscNtpIndex.setStatus('mandatory') mscCommentData = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 7, 9), AsciiString().subtype(subtypeSpec=ValueSizeConstraint(0, 750))) if mibBuilder.loadTexts: mscCommentData.setStatus('mandatory') mscOptionalAlarmInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8)) mscNotificationID = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8, 1), Hex()) if mibBuilder.loadTexts: mscNotificationID.setStatus('mandatory') mscLpForHierClear = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8, 2), RowPointer()) if mibBuilder.loadTexts: mscLpForHierClear.setStatus('mandatory') mscOperatorData = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8, 3), HexString().subtype(subtypeSpec=ValueSizeConstraint(0, 750))) if mibBuilder.loadTexts: mscOperatorData.setStatus('mandatory') mscPid = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 25))) if mibBuilder.loadTexts: mscPid.setStatus('mandatory') mscFileName = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8, 5), DisplayString()) if mibBuilder.loadTexts: mscFileName.setStatus('mandatory') mscFileLineNumber = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8, 6), Unsigned32()) if mibBuilder.loadTexts: mscFileLineNumber.setStatus('mandatory') mscFileVersion = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8, 7), DisplayString()) if mibBuilder.loadTexts: mscFileVersion.setStatus('mandatory') mscInternalData = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 8, 8), HexString().subtype(subtypeSpec=ValueSizeConstraint(0, 750))) if mibBuilder.loadTexts: mscInternalData.setStatus('mandatory') mscProvisionalAlarmInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 9)) mscCid = MibScalar((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2, 9, 1), Unsigned32()) if mibBuilder.loadTexts: mscCid.setStatus('mandatory') mscCriticalAlarm = NotificationType((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2) + (0,1)).setObjects(("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentRowPointer"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentName"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscEventTime"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscActiveListStatus"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscSeverity"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscAlarmType"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscProbableCause"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscNtpIndex"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscCommentData")) mscMajorAlarm = NotificationType((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2) + (0,2)).setObjects(("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentRowPointer"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentName"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscEventTime"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscActiveListStatus"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscSeverity"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscAlarmType"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscProbableCause"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscNtpIndex"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscCommentData")) mscMinorAlarm = NotificationType((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2) + (0,3)).setObjects(("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentRowPointer"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentName"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscEventTime"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscActiveListStatus"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscSeverity"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscAlarmType"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscProbableCause"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscNtpIndex"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscCommentData")) mscWarningAlarm = NotificationType((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2) + (0,4)).setObjects(("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentRowPointer"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentName"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscEventTime"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscActiveListStatus"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscSeverity"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscAlarmType"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscProbableCause"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscNtpIndex"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscCommentData")) mscClearedAlarm = NotificationType((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2) + (0,5)).setObjects(("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentRowPointer"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentName"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscEventTime"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscActiveListStatus"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscSeverity"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscAlarmType"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscProbableCause"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscNtpIndex"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscCommentData")) mscIndeterminateAlarm = NotificationType((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 3, 2) + (0,6)).setObjects(("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentRowPointer"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscComponentName"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscEventTime"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscActiveListStatus"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscSeverity"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscAlarmType"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscProbableCause"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscNtpIndex"), ("Nortel-MsCarrier-MscPassport-AlarmMIB", "mscCommentData")) alarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 1)) alarmGroupCA = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 1, 1)) alarmGroupCA01 = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 1, 1, 2)) alarmGroupCA01A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 1, 1, 2, 2)) alarmNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 2)) alarmNotificationsGroupCA01A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 2, 1)) alarmCapabilities = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 3)) alarmCapabilitiesCA = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 3, 1)) alarmCapabilitiesCA01 = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 3, 1, 2)) alarmCapabilitiesCA01A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 4, 3, 1, 2, 2)) mibBuilder.exportSymbols("Nortel-MsCarrier-MscPassport-AlarmMIB", mscCommentData=mscCommentData, alarmCapabilitiesCA01=alarmCapabilitiesCA01, alarmCapabilitiesCA01A=alarmCapabilitiesCA01A, alarmCapabilities=alarmCapabilities, mscOptionalAlarmInfo=mscOptionalAlarmInfo, alarmNotificationsGroupCA01A=alarmNotificationsGroupCA01A, mscProvisionalAlarmInfo=mscProvisionalAlarmInfo, mscWarningAlarm=mscWarningAlarm, mscAlarmTrap=mscAlarmTrap, alarmCapabilitiesCA=alarmCapabilitiesCA, mscMandatoryAlarmInfo=mscMandatoryAlarmInfo, mscComponentRowPointer=mscComponentRowPointer, mscNtpIndex=mscNtpIndex, alarmGroup=alarmGroup, alarmNotifications=alarmNotifications, mscProbableCause=mscProbableCause, mscMinorAlarm=mscMinorAlarm, mscActiveListStatus=mscActiveListStatus, mscLpForHierClear=mscLpForHierClear, alarmGroupCA01A=alarmGroupCA01A, mscAlarmType=mscAlarmType, mscNotificationID=mscNotificationID, mscFileLineNumber=mscFileLineNumber, mscClearedAlarm=mscClearedAlarm, alarmGroupCA01=alarmGroupCA01, mscFileVersion=mscFileVersion, mscOperatorData=mscOperatorData, mscMajorAlarm=mscMajorAlarm, alarmGroupCA=alarmGroupCA, mscSeverity=mscSeverity, mscComponentName=mscComponentName, mscIndeterminateAlarm=mscIndeterminateAlarm, mscFileName=mscFileName, mscInternalData=mscInternalData, alarmMIB=alarmMIB, mscPid=mscPid, mscCriticalAlarm=mscCriticalAlarm, mscCid=mscCid, mscEventTime=mscEventTime)
def insertion_sort(a): for i in range (1,len(a)): c=a[i] k=i-1 while (k>=0) and (c<=a[k]) : a[k+1] = a[k] k=k-1 a[k+1] = c n=int(input("Enter No. Of Elements in List :-s ")) a=[i for i in range (n)] print ("Enter the Elements one after the other :- ") for i in range (n): a[i]=int(input()) insertion_sort(a) print(a)
""" assign a database version to the getpaid installation for future upgrades. """ def evolve( portal ): # the upgrade framework will take care of upgrading for us pass