content
stringlengths
7
1.05M
# Copyright 2021 Jake Arkinstall # # Work based on efforts copyrighted 2018 The Bazel Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. load("//toolchain/internal:common.bzl", _python = "python") # If a new Circle version is missing from this list, please add the details here # and send a PR on github. To calculate the sha256, use # ``` # curl -s https://www.circle-lang.org/linux/build_{X}.tgz | sha256sum # ``` _circle_builds = { "141": struct( version = "141", url = "https://www.circle-lang.org/linux/build_141.tgz", sha256 = "90228ff369fb478bd4c0f86092725a22ec775924bdfff201cd4529ed9a969848", ), "142": struct( version = "142", url = "https://www.circle-lang.org/linux/build_142.tgz", sha256 = "fda3c2ea0f9bfb02e9627f1cb401e6f67a85a778c5ca26bd543101d51f274711", ), } def download_circle(rctx): circle_version = str(rctx.attr.circle_version) if circle_version not in _circle_builds: fail("Circle version %s has not been configured in toolchain/internal/circle_builds.bzl" % circle_version) spec = _circle_builds[circle_version] rctx.download_and_extract( spec.url, sha256 = spec.sha256, )
def add(matA,matB): dimA = [] dimB = [] # find dimensions of arrA a = matA b = matB while type(a) == list: dimA.append(len(a)) a = a[0] # find dimensions of arrB while type(b) == list: dimB.append(len(b)) b = b[0] #is it possible to add them if dimA != dimB: raise Exception("dimension mismath {} != {}".format(dimA,dimB)) #add em together newArr = [[0 for _ in range(dimA[1])] for _ in range(dimA[0])] for i in range(dimA[0]): for j in range(dimA[1]): newArr[i][j] = matA[i][j] + matB[i][j] return newArr
# This file contains code that can be used later which cannot fit in right now. '''This is the function to run 'map'. This is paused so that PyCUDA can support dynamic parallelism. if stmt.count('map') > 0: self.kernel_final.append(kernel+"}") start = stmt.index('map') + 2 declar = self.device_py[self.device_func_name.index(stmt[start])] print declar, stmt caller = stmt[start+1:-1] called = declar[declar.index('('):-2] print caller, called end = len(stmt) - 1 map_name = "map_" + str(stmt[start]) print map_name self.map_func.append(map_name) # self.global_func.append(map_name) kernel = "__device__ void " + map_name + "( " args = [] # print self.device_py, self.device_sentences, self.device_func_name, self.device_var_nam, self.device_type_vars for i in declar[3:-2]: if i != ",": args.append(i) kernel += str(self.type_vars[self.var_nam.index(caller[called.index(i)])]) + " " + str(i) + "," # print self.type_args, self.var_nam, self.type_args[self.var_nam.index(i)] kernel += str(self.type_vars[self.var_nam.index(stmt[0])]) + " " + str(stmt[0]) kernel += "){\n" + "int tid = threadIdx.x + blockIdx.x * blockDim.x;\n" shh = shlex.shlex(self.device_sentences[self.device_func_name.index(stmt[start])][0]) self.ismap.append(True) print self.type_vars kernel += stmt[0] + "[tid] = " print self.device_sentences[self.device_func_name.index(stmt[start])] if shh.get_token() == 'return': j = shh.get_token() while j is not shh.eof: if j in args: kernel += j + "[tid] " else: kernel += j j = shh.get_token() kernel += ";\n" # print kernel # print stmt[0] print "Printing Kernel", kernel return kernel'''
""" Code implementing standard data types. Can depend on core and calc, and no other Sauronlab packages. """
class Solution(object): def calculateMinimumHP(self, dungeon): """ :type dungeon: List[List[int]] :rtype: int """ if not dungeon: return 0 N = len(dungeon) M = len(dungeon[0]) matrix = [] for i in range(N): row = [0] * M matrix.append(row) matrix[N - 1][M - 1] = ( 1 if dungeon[N - 1][M - 1] >= 0 else -dungeon[N - 1][M - 1] + 1 ) for n in range(M + N - 1, -1, -1): for x in range(N): y = n - x if y < 0 or y >= M: continue candidates = [] if x + 1 < N: candidates.append(matrix[x + 1][y]) if y + 1 < M: candidates.append(matrix[x][y + 1]) if not candidates: continue min_need = min(candidates) if dungeon[x][y] >= 0: if dungeon[x][y] >= min_need: matrix[x][y] = 1 else: matrix[x][y] = min_need - dungeon[x][y] else: matrix[x][y] = min_need - dungeon[x][y] return matrix[0][0]
# Copyright 2017 Rice University # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class RetReverseMapper: def __init__(self, vocab): self.vocab = vocab self.ret_type = [] self.num_data = 0 return def add_data(self, ret_type): self.ret_type.extend(ret_type) self.num_data += len(ret_type) def get_element(self, id): return self.ret_type[id] def decode_ret(self, ret_type): print('--Ret Type--') print(self.vocab.chars_type[ret_type]) def reset(self): self.ret_type = [] self.num_data = 0
names = [] children = [] with open("day7.txt") as f: for line in f.readlines(): data = line.split('->') names.append(data[0].split(" ")[0]) if len(data) == 2: [x.strip() for x in data[1].split(',')] children.append([x.strip() for x in data[1].split(',')]) children = [element for sublist in children for element in sublist] print("Result = ", [x for x in names if x not in children])
# Implementation of EA def gcd(p, q): while q != 0: (p, q) = (q, p % q) return p # Implementation of the EEA def extgcd(r0, r1): u, v, s, t = 1, 0, 0, 1 # Swap arguments if r1 is smaller if r1 < r0: temp = r1 r1 = r0 r0 = temp # While Loop to cumpute params while r1 != 0: q = r0//r1 r0, r1 = r1, r0-q*r1 u, s = s, u-q*s v, t = t, v-q*t return r0, u, v # User Interface function def main(): print("Geben sie r0 ein: ") r0 = int(input()) print("Geben sie r1 ein: ") r1 = int(input()) print("----- Ergebnis ----") a1, u1, v1 = extgcd(r0, r1) print("GCD: ", a1) print("s: ", u1) print("t: ", v1) if __name__ == "__main__": main()
year=int(input("Enter any year to check for leap year: ")) if year%4==0: if year%100==0: if year%400==0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year))
s = input().strip() while(s != '0'): tam = len(s) i = 1 anagrama = 1 while(i <= tam): anagrama = anagrama * i i = i + 1 print(anagrama) s = input().strip()
class Solution: """ @param numbers: An array of Integer @param target: target = numbers[index1] + numbers[index2] @return: [index1, index2] (index1 < index2) """ def twoSum(self, numbers, target): # write your code here #遍历一遍,边遍历变查询哈希表,如果余数不再哈希表里面,就把当前值假如哈希表。如果在,就直接返回。这个方法 #时间复杂度O(n) 空间复杂度O(n) hashmap = {} #值, index for index, num in enumerate(numbers): if target - num in hashmap: return [hashmap[target - num], index] #如果target - 现在的数不再哈希表里面,就把当前的值假如哈希表 hashmap[num] = index return [-1, -1] # """ # 方法2: # 先sort 时间复杂度O(nlogn),如果只需要返回值的话空间复杂度是O(1),但是这边是需要返回index,这就不是O(1)了 # 然后2pointers O(n), 空间复杂度 O(1) # 合起来时间复杂度O(n+nlogn) = O(nlogn), 空间复杂度如果只返回值的话O(1), 但是这边要返回index所以O(n)
# # @lc app=leetcode.cn id=1587 lang=python3 # # [1587] parallel-courses-ii # None # @lc code=end
class Solution: def findComplement(self, num: int) -> int: num = bin(num)[2:] ans = '' for i in num: if i == "1": ans += '0' else: ans += '1' ans = int(ans, 2) return ans
# # PySNMP MIB module AT-PIM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-PIM-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:30:27 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, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion") modules, = mibBuilder.importSymbols("AT-SMI-MIB", "modules") pimNeighborIfIndex, pimInterfaceStatus = mibBuilder.importSymbols("PIM-MIB", "pimNeighborIfIndex", "pimInterfaceStatus") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Counter32, ModuleIdentity, TimeTicks, ObjectIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Integer32, iso, Unsigned32, NotificationType, Bits, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Counter32", "ModuleIdentity", "TimeTicks", "ObjectIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Integer32", "iso", "Unsigned32", "NotificationType", "Bits", "Gauge32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") pim4 = ModuleIdentity((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97)) pim4.setRevisions(('2005-01-20 15:25',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: pim4.setRevisionsDescriptions(('Initial Revision',)) if mibBuilder.loadTexts: pim4.setLastUpdated('200501201525Z') if mibBuilder.loadTexts: pim4.setOrganization('Allied Telesis, Inc') if mibBuilder.loadTexts: pim4.setContactInfo('http://www.alliedtelesis.com') if mibBuilder.loadTexts: pim4.setDescription('Contains definitions of managed objects for the handling PIM4 enterprise functions on AT switches. ') pim4Events = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0)) pim4NeighbourAddedTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 1)).setObjects(("PIM-MIB", "pimNeighborIfIndex")) if mibBuilder.loadTexts: pim4NeighbourAddedTrap.setStatus('current') if mibBuilder.loadTexts: pim4NeighbourAddedTrap.setDescription('A pim4NeighbourAddedTrap trap signifies that a PIM neighbour has been added') pim4NeighbourDeletedTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 2)).setObjects(("PIM-MIB", "pimNeighborIfIndex")) if mibBuilder.loadTexts: pim4NeighbourDeletedTrap.setStatus('current') if mibBuilder.loadTexts: pim4NeighbourDeletedTrap.setDescription('A pim4NeighbourDeletedTrap trap signifies that a PIM neighbour has been deleted') pim4InterfaceUpTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 3)).setObjects(("PIM-MIB", "pimInterfaceStatus")) if mibBuilder.loadTexts: pim4InterfaceUpTrap.setStatus('current') if mibBuilder.loadTexts: pim4InterfaceUpTrap.setDescription('A pimInterfaceUp trap signifies that a PIM interface has been enabled and is active') pim4InterfaceDownTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 4)).setObjects(("PIM-MIB", "pimInterfaceStatus")) if mibBuilder.loadTexts: pim4InterfaceDownTrap.setStatus('current') if mibBuilder.loadTexts: pim4InterfaceDownTrap.setDescription('A pimInterfaceDown trap signifies that a PIM interface has been disabled and is inactive') pim4ErrorTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 5)).setObjects(("AT-PIM-MIB", "pim4ErrorTrapType")) if mibBuilder.loadTexts: pim4ErrorTrap.setStatus('current') if mibBuilder.loadTexts: pim4ErrorTrap.setDescription('A pim4ErrorTrap trap is generated when a PIM error is incremented') pim4ErrorTrapType = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("pim4InvalidPacket", 1), ("pim4InvalidDestinationError", 2), ("pim4FragmentError", 3), ("pim4LengthError", 4), ("pim4GroupaddressError", 5), ("pim4SourceaddressError", 6), ("pim4MissingOptionError", 7), ("pim4GeneralError", 8), ("pim4InternalError", 9), ("pim4RpaddressError", 10)))).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: pim4ErrorTrapType.setStatus('current') if mibBuilder.loadTexts: pim4ErrorTrapType.setDescription('The type of the last error that resulted in a error trap being sent. The default value is 0 if no errors have been detected') mibBuilder.exportSymbols("AT-PIM-MIB", pim4InterfaceDownTrap=pim4InterfaceDownTrap, pim4NeighbourAddedTrap=pim4NeighbourAddedTrap, pim4ErrorTrap=pim4ErrorTrap, pim4InterfaceUpTrap=pim4InterfaceUpTrap, pim4NeighbourDeletedTrap=pim4NeighbourDeletedTrap, pim4=pim4, pim4Events=pim4Events, PYSNMP_MODULE_ID=pim4, pim4ErrorTrapType=pim4ErrorTrapType)
def create_phone_number(n): return (f'({n[0]}{n[1]}{n[2]}) {n[3]}{n[4]}{n[5]}-{n[6]}{n[7]}{n[8]}{n[9]}') # Best Practices def create_phone_number(n): print ("({}{}{}) {}{}{}-{}{}{}{}".format(*n))
class Class: def __init__(self, name): self.name = name self.fields = [] def __str__(self): lines = ['class %s:' % self.name] if not self.fields: lines.append(' pass') else: lines.append(' def __init__(self):') for f in self.fields: lines.append(' %s' % f) return '\n'.join(lines)
n1 = int(input('Digite um valor :')) n2 = n1*2 n3 = n1*3 nrz = n1**(1/2) print('O valor digitado foi {},\n seu dobro é : {},\n seu triplo é: {} \ne sua raiz quadrada é {}'.format(n1,n2,n3,nrz)) 100
class LCS: def __init__(self,str1,str2): self.str1=str1 self.str2=str2 self.m=len(str1) self.n=len(str2) self.dp = [[0 for x in range(self.n + 1)] for x in range(self.m + 1)] def lcs_length(self): for i in range(self.m): for j in range(self.n): if self.str1[i] == self.str2[j]: self.dp[i+1][j+1]=self.dp[i][j]+1 else: self.dp[i+1][j+1]=max(self.dp[i][j+1],self.dp[i+1][j]) return self.dp[-1][-1] def lcs_sequence(self): index = self.dp[self.m][self.n] seq = [""] * (index+1) seq[index] = "" i,j = self.m,self.n while i > 0 and j > 0: if self.str1[i-1] == self.str2[j-1]: seq[index-1] = self.str1[i-1] i = i - 1 j = j - 1 index -= 1 elif self.dp[i][j-1] < self.dp[i-1][j]: i = i - 1 else: j = j - 1 seq_str=''.join(seq[:-1]) return seq_str str1 = "CDEFGABC" str2 = "CEFDABGAC" MySeq=LCS(str1,str2) print('Least Common Subsequence length-->',MySeq.lcs_length()) print('Least Common Subsequence-->',MySeq.lcs_sequence()) ##OUTPUT: ''' Least Common Subsequence length--> 6 Least Common Subsequence--> CEFABC '''
# n = s = 0 # while n != 999: # FLAG (PONTO DE PARADA) # n = int(input('Digite um número: ')) # s += n # s -= 999 # GAMBIARRA PARA O FLAG NÃO ENTRAR NA SOMA!!! # print('A soma vale {}'.format(s)) n = s = 0 while True: n = int(input('Digite um número: ')) if n == 999: break s += n # print('A soma vale {}'.format(s)) print(f'A soma vale {s}') # F-STRING = atualização do print a partir do Python 3.6
print(''' Exercício 51 da aula 13 de Python Curso do Guanabara Day 22 Code Python - 21/05/2018 ''') primeira = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) décima = primeira + (10 - 1) * razao print('Os primeiros 10 termos são:', end=' ') for n in range(primeira, décima + razao, razao): print('{}'.format(n), end=' -> ') print('FIM')
# Copyright (c) 2014 Eventbrite, Inc. All rights reserved. # See "LICENSE" file for license. """These functions should be made available via cs2mako in the Mako context""" def include(clearsilver_name): """loads clearsilver file and returns a rendered mako file""" pass # need to put whatever ported clearsilver functions we have in here
################################################################################ ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## ## (C) Copyrights Dr. Michel F. Sanner and TSRI 2016 ## ################################################################################ ######################################################################## # # Date: 2015 Authors: Michel Sanner # # sanner@scripps.edu # # The Scripps Research Institute (TSRI) # Molecular Graphics Lab # La Jolla, CA 92037, USA # # Copyright: Michel Sanner and TSRI 2015 # ######################################################################### # # $Header: /mnt/raid/services/cvs/python/packages/share1.5/mglutil/util/io.py,v 1.1.4.1 2017/07/26 22:31:38 annao Exp $ # # $Id: io.py,v 1.1.4.1 2017/07/26 22:31:38 annao Exp $ # class Stream: def __init__(self): self.lines = [] def write(self, line): self.lines.append(line) # helper class to make stdout set of lines look like a file that ProDy can parse class BufferAsFile: def __init__(self, lines): self.lines = lines def readlines(self): return self.lines
parties = [] class Political(): @staticmethod def exists(name): """ Checks if a party with the same name exists Returns a boolean """ for party in parties: if party["name"] == name: return True return False def create_political_party(self, name, hqAddress, logoUrl): party= { "party_id": len(parties)+1, "name": name, "hqAddress": hqAddress, "logoUrl": logoUrl } parties.append(party) return party def get_political_parties(self): if len(parties) == 0: print('List is empty') return parties def get_specific_political_party(self, party_id): if parties: for party in parties: if party['party_id'] == party_id: return party def edit_political_party(self, data, party_id): if parties: for party in parties: if party['party_id'] == party_id: # return party party["name"] = data.get( 'name', party["name"]) party["hqAddress"] = data.get( 'hqAddress', party["hqAddress"]) party["logoUrl"] = data.get( 'logoUrl', party["logoUrl"]) return parties def delete_political_party(self, party_id): if parties: for party in parties: if party['party_id'] == party_id: parties.remove(party) return party return None
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 16 11:05:36 2021 @author: Olli Nevalainen (Finnish Meteorological Institute) """
# Copyright (c) 2019 The Bazel Utils Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. load("//:conditions.bzl", "if_windows") load("//:warnings.bzl", "default_warnings") ############################################################################### # warning ############################################################################### # NOTE: Should be combiend wih safest_code_linkopts() in "linkopts.bzl" def safest_code_copts(): return select({ "@com_chokobole_bazel_utils//:windows": [ "/W4", ], "@com_chokobole_bazel_utils//:clang_or_clang_cl": [ "-Wextra", ], "//conditions:default": [ "-Wall", "-Werror", ], }) + default_warnings() # NOTE: Should be combiend wih safer_code_linkopts() in "linkopts.bzl" def safer_code_copts(): return if_windows([ "/W3", ], [ "-Wall", "-Werror", ]) + default_warnings() ############################################################################### # symbol visibility ############################################################################### def visibility_hidden(): return if_windows([], ["-fvisibility=hidden"]) ############################################################################### # sanitizers ############################################################################### # NOTE: Should be combiend wih asan_linkopts() in "linkopts.bzl" def asan_copts(): return ["-fsanitize=address"]
#!/usr/bin/python3 # -*- coding: utf-8 -*- def f(x): return(x**2-2*x-3) def hata(x1,x2): return((x1-x2)/x1) x1 = int(input("bir başlangıç değeri girin: ")) x3 = int(input("ikinci başlangıç değerini girin: ")) for i in range(5): x2 = x1 - (f(x1)*(x3-x1))/(f(x3)-f(x1)) print(x3, x1, x2, hata(x2,x1)) x1,x3 = x3,x2
fps = 60 game_duration = 120 # in sec window_width = 1550 window_height = 800
class Solution(object): def maxLength(self, arr): """ :type arr: List[str] :rtype: int """ if not arr: return 0 if len(arr) == 1: return len(arr[0]) result = [0] self.max_unique(arr, 0, "", result) return result[0] def max_unique(self, arr, index, current, result): """Finds the max possible length of s""" if index == len(arr) and (self.unique_chars(current) > result[0]): result[0] = self.unique_chars(current) return if index == len(arr): return self.max_unique(arr, index + 1, current, result) self.max_unique(arr, index + 1, current+arr[index], result) def unique_chars(self, word): """ Returns the length of the word if all chars are unique else -1 """ count = [0] * 26 offset = ord('a') for char in word: index = ord(char) - offset count[index] += 1 if count[index] > 1: return -1 return len(word) arr = ["un", "iq", "ue"] obj = Solution() result = obj.maxLength(arr) print(result)
def main(): ans = 1 for n in range(1, 501): ans += f(n) print(ans) def f(n): return 4 * (2 * n + 1)**2 - (12 * n) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- __all__ = [ "StorageBackend" ] class StorageBackend(object): """Base class for storage backends.""" async def store_stats(self, stats): raise NotImplementedError
""" discpy.types ~~~~~~~~~~~~~~ Typings for the Discord API :copyright: (c) 2021 The DiscPy Developers (c) 2015-2021 Rapptz :license: MIT, see LICENSE for more details. """
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 16 12:02:13 2019 Customized by Pedro Villarroel from Peter Norvig's spell.py Words list retrieved from FrequencyWords by Hermit Dave (@hermitdave on github) """ """ #es_WORDS = pd.read_csv('Documents/Machine_Learning/MeLi_Classifier/data/es_50k.txt', es_WORDS = pd.read_csv('data/es_50k.txt', sep=' ', header = None, index_col = 0, names = ['freq'], dtype={'freq' : np.uint32}) #pt_WORDS = pd.read_csv('Documents/Machine_Learning/MeLi_Classifier/data/pt_br_50k.txt', pt_WORDS = pd.read_csv('data/pt_br_50k.txt', sep=' ', header = None, index_col = 0, names = ['freq'], dtype={'freq' : np.uint32}) """ class corrector: def __init__(self, contador): self.N = sum(list(contador.values())) self.freq = contador def P(self, word): #Probabilidad de la palabra return self.freq[word] / self.N def correction(self, word): #Correction más probable return max(self.candidates(word), key=self.P) def candidates(self, word): #"Generate possible spelling corrections for word." return (self.known([word]) or self.known(self.edits1(word)) or self.known(self.edits2(word)) or [word]) def known(self, words): #"The subset of `words` that appear in the dictionary of WORDS." return set(w for w in words if w in self.freq) def edits1(self, word): #"All edits that are one edit away from `word`." letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1] replaces = [L + c + R[1:] for L, R in splits if R for c in letters] inserts = [L + c + R for L, R in splits for c in letters] return set(deletes + transposes + replaces + inserts) def edits2(self, word): #"All edits that are two edits away from `word`." return (e2 for e1 in self.edits1(word) for e2 in self.edits1(e1))
def get_param_dict(self): """Get the parameters dict from ELUT Parameters ---------- self : ELUT an ELUT object Returns ---------- param_dict : dict a Dict object """ param_dict = {"R1": self.R1, "L1": self.L1, "T1_ref": self.T1_ref} return param_dict
class A(object): pass print(A.__sizeof__) # <ref>
#Write a Python program to print the following floating numbers upto 2 decimal places with a sign. x = 3.1415926 y = 12.9999 a = float(+x) b = float(-y) print(round(a,2)) print(round(b,2))
# A place for secret local/dev environment settings UNIFIED_DB = { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'DB_NAME', 'USER': 'username', 'PASSWORD': 'password', } MONGODB_DATABASES = { 'default': { 'NAME': 'wtc-console', 'USER': 'root', 'PASSWORD': 'root', } }
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def pseudoPalindromicPaths (self, root: TreeNode) -> int: s = set() def dfs(root): if not root: return 0 if root.val in s: s.discard(root.val) else: s.add(root.val) res = dfs(root.left) + dfs(root.right) if not root.left and not root.right: res += len(s)<=1 if root.val in s: s.discard(root.val) else: s.add(root.val) return res return dfs(root)
'''For 18 points, answer the following questions: "Recursion" is when a function solves a problem by calling itself. Recursive functions have at least 2 parts: 1. Base case - This is where the function is finished. 2. Recursive case (aka Induction case) - this is where the function calls itself and gets closer to the base case. ''' #The Fibonacci sequence is a classic example of a recursive function. #The sequence is: 1,1,2,3,5,8,13,21,34,55, and so on. #You calculate the sequence by starting with two numbers (such as 1,1) #then you get the next number by adding the previous two numbers. #Here it is as a recursive function. def fibonacci(a,b,n): '''a and b are the starting numbers. n is how deep into the sequence you want to calculate.''' if n==0: return a+b else: return fibonacci(b,a+b,n-1) #1. Which case (the if or the else) is the base case and which #is the recursive case? #2. Write code that uses the function to print out the first 8 numbers #in the sequence. #3. What error do you get if you pass a decimal as the third argument #to the function? #4. How can you fix that error? #5. Write this function using loops. #You can factor using recursion. Check it out. #Note that start=2 defines an argument with a default value. #For example: If I write factor(10) then start defaults at the value 2 #If I write: factor(81,3) then start takes the value 3. def factor(number, start=2): if start > number: return [] elif number % start == 0: return [start]+factor(number/start, start) else: return factor(number,start+1) #6. Find all the factors of 360 using this function. #7. There are three cases in factor. Which are the base case(s)? #Which are the recursive case(s)?
''' Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Solution: Copyright 2017 Dave Cuthbert License MIT ''' def find_multiples(factor, limit): list_of_factors = [] for num in range(limit): if num % factor == 0: list_of_factors.append(num) return list_of_factors def sum_of_list(list_to_sum): list_sum = 0 for i in list_to_sum: list_sum += i return list_sum def clean_up_lists(list1, list2): tmp_list = list1[:] tmp_list.extend(list2) return set(tmp_list) def solve_problem(factor1, factor2, maximum): list_factor_1 = find_multiples(factor1, maximum) list_factor_2 = find_multiples(factor2, maximum) return(sum_of_list(clean_up_lists(list_factor_1, list_factor_2))) if __name__ == "__main__": MAX_VALUE = 1000 LIST_FACTOR_1 = 3 LIST_FACTOR_2 = 5 print(solve_problem(LIST_FACTOR_1, LIST_FACTOR_2, MAX_VALUE))
# Time: O(n) # Space: O(1) class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ result = [] i = 0 while i < len(intervals) and newInterval[0] > intervals[i][1]: result += intervals[i], i += 1 while i < len(intervals) and newInterval[1] >= intervals[i][0]: newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])] i += 1 result.append(newInterval) result.extend(intervals[i:]) return result
d1=['13CS10001','12CS30016','12CS30043','12CS30042','12CS30043','13CS10038','12CS30017','12CS30044','13CS10041','12CS30041','12CS30010', '13CS10020','12CS30025','12CS30027','12CS30032','13CS10035','12CS30003','12CS30044','12CS30016','13CS10038','13CS10021','12CS30028', '12CS30016','13CS10006','13CS10046','13CS10034','12CS30037','12CS30017','13CS10025','12CS30014','13CS10035','12CS30005','12CS30036'] d1s = set(d1) print(len(d1)) print(len(d1s))
# -*- coding: utf-8 -*- def includeme(config): config.add_route('index', '') config.include(admin_include, '/admin') config.include(post_include, '/post') config.add_route('firework', '/firework') config.add_route('baymax', '/baymax') def admin_include(config): config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('all_posts', '/all_posts') def post_include(config): config.add_route('new_post', '/new_post') config.add_route('post_detail', '/detail/{id}') config.add_route('post_edit', '/edit/{id}') config.add_route('post_delete', '/delete/{id}')
def ada_int(f, a, b, tol=1.0e-6, n=5, N=10): area = trapezoid(f, a, b, N) check = trapezoid(f, a, b, n) if abs(area - check) > tol: # bad accuracy, add more points to interval m = (b + a) / 2.0 area = ada_int(f, a, m) + ada_int(f, m, b) return area
# -*- coding:utf-8 -*- # @Script: array_partition_1.py # @Author: Pradip Patil # @Contact: @pradip__patil # @Created: 2019-03-20 23:06:35 # @Last Modified By: Pradip Patil # @Last Modified: 2019-03-21 21:07:13 # @Description: https://leetcode.com/problems/array-partition-i/ ''' Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in the range of [-10000, 10000]. ''' class Solution: def arrayPairSum(self, nums): return sum(sorted(nums)[::2]) if __name__ == "__main__": print(Solution().arrayPairSum([1, 4, 3, 2])) print(Solution().arrayPairSum([]))
# Options class SimpleOpt(): def __init__(self): self.method = 'gvae' self.graph_type = 'ENZYMES' self.data_dir = './data/ENZYMES_20-50_res.graphs' self.emb_size = 8 self.encode_dim = 32 self.layer_num = 3 self.decode_dim = 32 self.dropout = 0.5 self.logits = 10 # self.adj_thresh = 0.6 self.max_epochs = 50 self.lr = 0.003 self.gpu = '2' self.batch_size = 56 self.epochs_log = 1 # self.DATA_DIR = './data/dblp/' # self.output_dir = './output/' class Options(): def __init__(self): self.opt_type = 'simple' # self.opt_type = 'argparser @staticmethod def initialize(epoch_num=1800): opt = SimpleOpt() opt.max_epochs = epoch_num return opt
set_name(0x8013570C, "PresOnlyTestRoutine__Fv", SN_NOWARN) set_name(0x80135734, "FeInitBuffer__Fv", SN_NOWARN) set_name(0x80135760, "FeAddEntry__Fii8TXT_JUSTUsP7FeTableP5CFont", SN_NOWARN) set_name(0x801357E4, "FeAddTable__FP11FeMenuTablei", SN_NOWARN) set_name(0x80135860, "FeAddNameTable__FPUci", SN_NOWARN) set_name(0x80135988, "FeDrawBuffer__Fv", SN_NOWARN) set_name(0x80135FB4, "FeNewMenu__FP7FeTable", SN_NOWARN) set_name(0x80136034, "FePrevMenu__Fv", SN_NOWARN) set_name(0x8013617C, "FeSelUp__Fi", SN_NOWARN) set_name(0x80136264, "FeSelDown__Fi", SN_NOWARN) set_name(0x8013634C, "FeGetCursor__Fv", SN_NOWARN) set_name(0x80136360, "FeSelect__Fv", SN_NOWARN) set_name(0x801363B0, "FeMainKeyCtrl__FP7CScreen", SN_NOWARN) set_name(0x80136578, "InitDummyMenu__Fv", SN_NOWARN) set_name(0x80136580, "InitFrontEnd__FP9FE_CREATE", SN_NOWARN) set_name(0x801366A0, "FeInitMainMenu__Fv", SN_NOWARN) set_name(0x8013671C, "FeInitNewGameMenu__Fv", SN_NOWARN) set_name(0x801367D0, "FeNewGameMenuCtrl__Fv", SN_NOWARN) set_name(0x80136984, "FeInitPlayer1ClassMenu__Fv", SN_NOWARN) set_name(0x80136A08, "FeInitPlayer2ClassMenu__Fv", SN_NOWARN) set_name(0x80136A8C, "FePlayerClassMenuCtrl__Fv", SN_NOWARN) set_name(0x80136AD4, "FeDrawChrClass__Fv", SN_NOWARN) set_name(0x80136F6C, "FeInitNewP1NameMenu__Fv", SN_NOWARN) set_name(0x80136FC8, "FeInitNewP2NameMenu__Fv", SN_NOWARN) set_name(0x8013701C, "FeNewNameMenuCtrl__Fv", SN_NOWARN) set_name(0x801375E4, "FeCopyPlayerInfoForReturn__Fv", SN_NOWARN) set_name(0x80137710, "FeEnterGame__Fv", SN_NOWARN) set_name(0x80137738, "FeInitLoadMemcardSelect__Fv", SN_NOWARN) set_name(0x801377B8, "FeInitLoadChar1Menu__Fv", SN_NOWARN) set_name(0x80137820, "FeInitLoadChar2Menu__Fv", SN_NOWARN) set_name(0x80137890, "FeInitDifficultyMenu__Fv", SN_NOWARN) set_name(0x80137934, "FeDifficultyMenuCtrl__Fv", SN_NOWARN) set_name(0x80137A20, "FeInitBackgroundMenu__Fv", SN_NOWARN) set_name(0x80137A6C, "FeInitBook1Menu__Fv", SN_NOWARN) set_name(0x80137ABC, "FeInitBook2Menu__Fv", SN_NOWARN) set_name(0x80137B0C, "FeBackBookMenuCtrl__Fv", SN_NOWARN) set_name(0x80137D50, "PlayDemo__Fv", SN_NOWARN) set_name(0x80137D64, "FadeFEOut__Fv", SN_NOWARN) set_name(0x80137E28, "DrawBackTSK__FP4TASK", SN_NOWARN) set_name(0x80137FB0, "FeInitMainStuff__FP4TASK", SN_NOWARN) set_name(0x8013805C, "FrontEndTask__FP4TASK", SN_NOWARN) set_name(0x80138508, "DrawFeTwinkle__Fii", SN_NOWARN) set_name(0x801385E4, "___6Dialog", SN_NOWARN) set_name(0x8013860C, "__6Dialog", SN_NOWARN) set_name(0x8013868C, "GetOverlayOtBase__7CBlocks", SN_NOWARN) set_name(0x80138694, "CheckActive__4CPad", SN_NOWARN) set_name(0x80138CB0, "InitCredits__Fv", SN_NOWARN) set_name(0x80138D44, "PrintCredits__Fiiiiii", SN_NOWARN) set_name(0x80139574, "DrawCreditsTitle__Fiiiii", SN_NOWARN) set_name(0x8013962C, "DrawCreditsSubTitle__Fiiiii", SN_NOWARN) set_name(0x801396E4, "CredCountNL__Fi", SN_NOWARN) set_name(0x80139750, "DoCredits__Fv", SN_NOWARN) set_name(0x80139B38, "PRIM_GetPrim__FPP8POLY_FT4", SN_NOWARN) set_name(0x80139BB4, "ClearFont__5CFont", SN_NOWARN) set_name(0x80139BD8, "GetCharHeight__5CFontUc", SN_NOWARN) set_name(0x80139C18, "___7CScreen", SN_NOWARN) set_name(0x80139C38, "GetFr__7TextDati", SN_NOWARN) set_name(0x8013E1F4, "endian_swap__FPUci", SN_NOWARN) set_name(0x8013E228, "sjis_endian_swap__FPUci", SN_NOWARN) set_name(0x8013E270, "to_sjis__Fc", SN_NOWARN) set_name(0x8013E2F0, "to_ascii__FUs", SN_NOWARN) set_name(0x8013E378, "ascii_to_sjis__FPcPUs", SN_NOWARN) set_name(0x8013E3FC, "is_sjis__FPUc", SN_NOWARN) set_name(0x8013E408, "sjis_to_ascii__FPUsPc", SN_NOWARN) set_name(0x8013E490, "read_card_directory__Fi", SN_NOWARN) set_name(0x8013E6F0, "test_card_format__Fi", SN_NOWARN) set_name(0x8013E7E0, "checksum_data__FPci", SN_NOWARN) set_name(0x8013E81C, "delete_card_file__Fii", SN_NOWARN) set_name(0x8013E914, "read_card_file__FiiiPc", SN_NOWARN) set_name(0x8013EAF0, "format_card__Fi", SN_NOWARN) set_name(0x8013EBB4, "write_card_file__FiiPcT2PUcPUsiT4", SN_NOWARN) set_name(0x8013EED8, "new_card__Fi", SN_NOWARN) set_name(0x8013EF6C, "service_card__Fi", SN_NOWARN) set_name(0x80155064, "GetFileNumber__FiPc", SN_NOWARN) set_name(0x80155124, "DoSaveOptions__Fv", SN_NOWARN) set_name(0x8015514C, "DoSaveGame__Fv", SN_NOWARN) set_name(0x8015529C, "DoLoadGame__Fv", SN_NOWARN) set_name(0x80155340, "DoFrontEndLoadCharacter__Fi", SN_NOWARN) set_name(0x80155398, "McInitLoadCard1Menu__Fv", SN_NOWARN) set_name(0x801553D8, "McInitLoadCard2Menu__Fv", SN_NOWARN) set_name(0x80155418, "ChooseCardLoad__Fv", SN_NOWARN) set_name(0x801554B4, "McInitLoadGameMenu__Fv", SN_NOWARN) set_name(0x80155518, "McMainKeyCtrl__Fv", SN_NOWARN) set_name(0x80155768, "McCharCardMenuCtrl__Fv", SN_NOWARN) set_name(0x801559B0, "McMainCharKeyCtrl__Fv", SN_NOWARN) set_name(0x80155E28, "ShowAlertBox__Fv", SN_NOWARN) set_name(0x80156034, "GetLoadStatusMessage__FPc", SN_NOWARN) set_name(0x801560E8, "GetSaveStatusMessage__FiPc", SN_NOWARN) set_name(0x80156208, "ShowGameFiles__FPciiG4RECTi", SN_NOWARN) set_name(0x80156368, "ShowCharacterFiles__FiiG4RECTi", SN_NOWARN) set_name(0x801564E4, "PackItem__FP12PkItemStructPC10ItemStruct", SN_NOWARN) set_name(0x80156570, "PackPlayer__FP14PkPlayerStructi", SN_NOWARN) set_name(0x8015677C, "UnPackItem__FPC12PkItemStructP10ItemStruct", SN_NOWARN) set_name(0x80156884, "VerifyGoldSeeds__FP12PlayerStruct", SN_NOWARN) set_name(0x8015695C, "UnPackPlayer__FPC14PkPlayerStructiUc", SN_NOWARN) set_name(0x80156C20, "ConstructSlotName__FPci", SN_NOWARN) set_name(0x80156D18, "GetSpinnerWidth__Fi", SN_NOWARN) set_name(0x80156DBC, "ReconstructSlotName__Fii", SN_NOWARN) set_name(0x801571B4, "GetTick__C4CPad", SN_NOWARN) set_name(0x801571DC, "GetDown__C4CPad", SN_NOWARN) set_name(0x80157204, "SetPadTickMask__4CPadUs", SN_NOWARN) set_name(0x8015720C, "SetPadTick__4CPadUs", SN_NOWARN) set_name(0x80157214, "SetRGB__6DialogUcUcUc", SN_NOWARN) set_name(0x80157234, "SetBack__6Dialogi", SN_NOWARN) set_name(0x8015723C, "SetBorder__6Dialogi", SN_NOWARN) set_name(0x80157244, "___6Dialog_addr_80157244", SN_NOWARN) set_name(0x8015726C, "__6Dialog_addr_8015726C", SN_NOWARN) set_name(0x801572EC, "GetOverlayOtBase__7CBlocks_addr_801572EC", SN_NOWARN) set_name(0x801572F4, "BLoad__Fv", SN_NOWARN) set_name(0x80157310, "ILoad__Fv", SN_NOWARN) set_name(0x80157364, "OLoad__Fv", SN_NOWARN) set_name(0x80157388, "LoadQuest__Fi", SN_NOWARN) set_name(0x80157450, "BSave__Fc", SN_NOWARN) set_name(0x80157468, "ISave__Fi", SN_NOWARN) set_name(0x801574C8, "OSave__FUc", SN_NOWARN) set_name(0x8015750C, "SaveQuest__Fi", SN_NOWARN) set_name(0x801575D8, "PSX_GM_SaveGame__FiPcT1", SN_NOWARN) set_name(0x80157B38, "PSX_GM_LoadGame__FUcii", SN_NOWARN) set_name(0x80157C5C, "PSX_CH_LoadGame__Fi", SN_NOWARN) set_name(0x80157CFC, "PSX_CH_LoadBlock__Fii", SN_NOWARN) set_name(0x80157D24, "PSX_CH_SaveGame__Fii", SN_NOWARN) set_name(0x80157EA8, "RestorePads__Fv", SN_NOWARN) set_name(0x80157F68, "StorePads__Fv", SN_NOWARN) set_name(0x80158024, "GetIcon__Fv", SN_NOWARN) set_name(0x80158060, "PSX_OPT_LoadGame__Fiib", SN_NOWARN) set_name(0x801580BC, "PSX_OPT_SaveGame__FiPc", SN_NOWARN) set_name(0x801581F4, "LoadOptions__Fv", SN_NOWARN) set_name(0x801582CC, "SaveOptions__Fv", SN_NOWARN) set_name(0x80158370, "RestoreLoadedData__Fb", SN_NOWARN) set_name(0x801386C4, "CreditsText", SN_NOWARN) set_name(0x8013891C, "CreditsTable", SN_NOWARN) set_name(0x80139CF4, "card_dir", SN_NOWARN) set_name(0x8013A1F4, "card_header", SN_NOWARN) set_name(0x80139C54, "sjis_table", SN_NOWARN) set_name(0x8013F1C0, "save_buffer", SN_NOWARN) set_name(0x801531C4, "CharDataStruct", SN_NOWARN) set_name(0x80154FA4, "TempStr", SN_NOWARN) set_name(0x80154FE4, "AlertStr", SN_NOWARN) set_name(0x8013F118, "McLoadGameMenu", SN_NOWARN) set_name(0x8013F0C4, "ClassStrTbl", SN_NOWARN) set_name(0x8013F134, "McLoadCard1Menu", SN_NOWARN) set_name(0x8013F150, "McLoadCard2Menu", SN_NOWARN)
APKG_COL = r''' INSERT INTO col VALUES( null, :creation_time, :modification_time, :modification_time, 11, 0, 0, 0, '{ "activeDecks": [ 1 ], "addToCur": true, "collapseTime": 1200, "curDeck": 1, "curModel": "' || :modification_time || '", "dueCounts": true, "estTimes": true, "newBury": true, "newSpread": 0, "nextPos": 1, "sortBackwards": false, "sortType": "noteFld", "timeLim": 0 }', :models, '{ "1": { "collapsed": false, "conf": 1, "desc": "", "dyn": 0, "extendNew": 10, "extendRev": 50, "id": 1, "lrnToday": [ 0, 0 ], "mod": 1425279151, "name": "Default", "newToday": [ 0, 0 ], "revToday": [ 0, 0 ], "timeToday": [ 0, 0 ], "usn": 0 }, "' || :deck_id || '": { "collapsed": false, "conf": ' || :options_id || ', "desc": "' || :description || '", "dyn": 0, "extendNew": 10, "extendRev": 50, "id": ' || :deck_id || ', "lrnToday": [ 5, 0 ], "mod": 1425278051, "name": "' || :name || '", "newToday": [ 5, 0 ], "revToday": [ 5, 0 ], "timeToday": [ 5, 0 ], "usn": -1 } }', '{ "' || :options_id || '": { "id": ' || :options_id || ', "autoplay": ' || :autoplay_audio || ', "lapse": { "delays": ' || :lapse_steps || ', "leechAction": ' || :leech_action || ', "leechFails": ' || :leech_threshold || ', "minInt": ' || :lapse_min_interval || ', "mult": ' || :leech_interval_multiplier || ' }, "maxTaken": ' || :max_time_per_answer || ', "mod": 0, "name": "' || :options_group_name || '", "new": { "bury": ' || :bury_related_new_cards || ', "delays": ' || :new_steps || ', "initialFactor": ' || :starting_ease || ', "ints": [ ' || :graduating_interval || ', ' || :easy_interval || ', 7 ], "order": ' || :order || ', "perDay": ' || :new_cards_per_day || ', "separate": true }, "replayq": ' || :replay_audio_for_answer || ', "rev": { "bury": ' || :bury_related_review_cards || ', "ease4": ' || :easy_bonus || ', "fuzz": 0.05, "ivlFct": ' || :interval_modifier || ', "maxIvl": ' || :max_interval || ', "minSpace": 1, "perDay": ' || :max_reviews_per_day || ' }, "timer": ' || :show_timer || ', "usn": 0 } }', '{}' ); '''
def sum_numbers(text: str) -> int: return sum([int(x) for x in text.split() if x.isnumeric()]) if __name__ == '__main__': print("Example:") print(sum_numbers('hi')) # These "asserts" are used for self-checking and not for an auto-testing assert sum_numbers('hi') == 0 assert sum_numbers('who is 1st here') == 0 assert sum_numbers('my numbers is 2') == 2 assert sum_numbers( 'This picture is an oil on canvas painting by Danish artist Anna Petersen between 1845 and 1910 year' ) == 3755 assert sum_numbers('5 plus 6 is') == 11 assert sum_numbers('') == 0 print("Coding complete? Click 'Check' to earn cool rewards!")
class snake: poison='venom' # shared by all instances def __init__(self, name): self.name=name # instance variable unique to each instance def change_name(self, new_name): self.name=new_name cobra= snake('cobra') print(cobra.name)
name = input("Enter Your Username: ") age = int(input("Enter Your Age: ")) print(type(age)) if type(age) == int: print("Name :" ,name) print("Age :", age) else: print("Enter a valid Username or Age")
# glob.py viewPortX = None viewPortY = None
''' Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more. ''' def first_last6(nums): return nums[0] == 6 or nums[-1] == 6
números = [] maior = 0 menor = 0 for c in range(0, 5): n = int(input('Digite um valor: ')) if c == 0: maior = menor = n números.append(n) print('Adicionado ao final da lista...') else: if n > maior: maior = n números.append(maior) print('Adicionado ao final da lista...') elif n < menor: menor = n números.insert(0, menor) print('Adicionado na posição 0 da lista...') elif n < números[-1]: números.insert(-1, n) print('Adicionado antes do último...') else: números.insert(1, n) print('Adicionado antes do último!') print('-=' * 30) print(f'Os valores digitados em ordem foram {números}')
def insertion_sort(lst): for i in range(len(lst)): j = (i - 1) temp = lst[i] while j >= 0 and temp < lst[j]: lst[j+1] = lst[j] j = j-1 lst[j + 1] = temp return lst
# the public parameters are passed as they are known globally def attacker(prime, root, alicepublic, bobpublic): attacksecret1=int(input("Enter a secret number1 for attacker: ")) attacksecret2=int(input("Enter a secret number2 for attacker: ")) print('\n') print ("Attacker's public key -> C=root^attacksecret(mod(prime))") attackpublic1=(root**attacksecret1)%prime attackpublic2=(root**attacksecret2)%prime print ("Attacker public key1 which is shared with Party1: ", attackpublic1) print ("Attacker public key2 which is shared with Party2: ", attackpublic2) print('\n') key1=(alicepublic**attacksecret1)%prime key2=(bobpublic**attacksecret2)%prime print("The key used to decrypt message from A and modify: ",key1) print("The key used to encrypt message to be sent to B is: ",key2) return(attackpublic1,attackpublic2) # Prime to be used print ("Both parties agree to a single prime") prime=int(input("Enter the prime number to be considered: ")) # Primitive root to be used print ("Both must agree with single primitive root to use") root=int(input("Enter the primitive root: ")) # Party1 chooses a secret number alicesecret=int(input("Enter a secret number for Party1: ")) # Party2 chooses a secret number bobsecret=int(input("Enter a secret number for Party2: ")) print('\n') # Party1 public key A=(root^alicesecret)*mod(prime) print ("Party1's public key -> A=root^alicesecret(mod(prime))") alicepublic=(root**alicesecret)%prime print ("Party1 public key is: ",alicepublic, "\n") # Party2 public key B=(root^bobsecret)*mod(prime) print ("Party2's public key -> B=root^bobsecret(mod(prime))") bobpublic=(root**bobsecret)%prime print ("Party2 public key is", bobpublic, "\n") # Party1 now calculates the shared key K1: # K1 = B^(alicesecret)*mod(prime) print ("Party1 calculates the shared key as K=B^alicesecret*(mod(prime))") alicekey=(bobpublic**alicesecret)%prime print ("Party1 calculates the shared key and results: ",alicekey, "\n") # Party2 calculates the shared key K2: # K2 = A^(bobsecret)*mod(prime) print ("Party2 calculates the shared key as K=A^bobsecret(mod(prime))") bobkey =(alicepublic**bobsecret)%prime print ("Party2 calculates the shared key and results: ", bobkey, "\n") #Both Alice and Bob now share a key which Eve cannot calculate print ("Attacker does not know the shared private key that Party1 & Party2 can now use") print("Now Eve implements Man In the Middle Attack !!") # Party1 and Party2 exchange their public keys # Eve(attacker) nows both parties public keys keys=attacker(prime, root, alicepublic, bobpublic) alicekey=(keys[0]**alicesecret)%prime print("Party1 calculates the shared key with attacker's public key1: ") print ("Shared final key: ",alicekey) bobkey =(keys[1]**bobsecret)%prime print("Party2 calculates the shared key with attacker's public key2: ") print ("Shared final key: ", bobkey, "\n") print("The final keys are different. ") ''' ----------OUTPUT---------- Both parties agree to a single prime Enter the prime number to be considered: 61 Both must agree with single primitive root to use Enter the primitive root: 43 Enter a secret number for Party1: 6756 Enter a secret number for Party2: 8356 Party1's public key -> A=root^alicesecret(mod(prime)) Party1 public key is: 34 Party2's public key -> B=root^bobsecret(mod(prime)) Party2 public key is 15 Party1 calculates the shared key as K=B^alicesecret*(mod(prime)) Party1 calculates the shared key and results: 34 Party2 calculates the shared key as K=A^bobsecret(mod(prime)) Party2 calculates the shared key and results: 34 Attacker does not know the shared private key that Party1 & Party2 can now use Now Eve implements Man In the Middle Attack !! Enter a secret number1 for attacker: 7349 Enter a secret number2 for attacker: 3560 Attacker's public key -> C=root^attacksecret(mod(prime)) Attacker public key1 which is shared with Party1: 17 Attacker public key2 which is shared with Party2: 47 The key used to decrypt message from A and modify: 9 The key used to encrypt message to be sent to B is: 47 Party1 calculates the shared key with attacker's public key1: Shared final key: 9 Party2 calculates the shared key with attacker's public key2: Shared final key: 47 The final keys are different. >>> ''' ''' Took help from: 1. https://sublimerobots.com/2015/01/simple-diffie-hellman-example-python/ 2. https://trinket.io/python/d574095364 3. https://www.wolframalpha.com/widgets/view.jsp?id=ef51422db7db201ebc03c8800f41ba99 Thanks for the help ! '''
REC1 = b"""cam a22002051 4500001001300000003000400013005001700017008004100034010001700075035001900092040001800111050001600129100003500145245017600180260004300356300001900399500002600418650002100444650004900465 00000002 DLC20040505165105.0800108s1899 ilu 000 0 eng  a 00000002  a(OCoLC)5853149 aDLCcDSIdDLC00aRX671b.A921 aAurand, Samuel Herbert,d1854-10aBotanical materia medica and pharmacology;bdrugs considered from a botanical, pharmaceutical, physiological, therapeutical and toxicological standpoint.cBy S. H. Aurand. aChicago,bP. H. Mallen Company,c1899. a406 p.c24 cm. aHomeopathic formulae. 0aBotany, Medical. 0aHomeopathyxMateria medica and therapeutics.""" REC_MX = b"""cpc a2200733 a 4500001001300000003000400013005001700017007000700034007001000041007000700051007000700058008004100065010001700106040002400123043001200147050001700159100005500176245003400231246004300265246005400308260001000362300006000372300006300432300005900495300006000554300004500614300006100659351073000720520069901450520033602149524010102485540008002586545032702666500012702993500007303120541011503193650005103308650004703359650005303406650006003459650006903519650005803588650004803646650006103694650006003755650005703815650005803872650006003930650006403990650005904054650006804113650006904181650006404250655004204314655004404356655003904400655004504439655005304484655004504537655005004582655005004632852009104682856010804773 00650024 DLC20101209130102.0kh|bo|gt|cj||s kg|b||kh|c||000724i19802005xxu eng  a 00650024  aDLCcDLCdDLCegihc an-us-dc00aGuide Record1 aHighsmith, Carol M.,d1946-ephotographer,edonor.10aHighsmith archiveh[graphic].33aCarol M. Highsmith archiveh[graphic].33aCarol M. Highsmith photograph archiveh[graphic]. c1980- a276 photographic prints :bgelatin silver ;c8 x 10 in. a241 photographic prints :bcibachrome, color ;c8 x 10 in. a824 transparencies :bfilm, color ;cchiefly 4 x 5 in. a1213 negatives :bsafety film, b&w ;cchiefly 4 x 5 in. a2 photographs (digital prints) :bcolor. a11,271 photographs :bdigital files, TIFF, mostly color. aFilm negatives and transparencies are organized by type of film and size in the following filing series: LC-HS503 (4x5 color transparencies), LC-HS505 (120 color slides), LC-HS507 (120 color slides, mounted), LC-HS513 (4x5 negatives), LC-HS543 (4x5 color negatvies) and LC-HS545 (120 color negatives) . Within each filing series negatives and transparencies are arranged numerically by a one-up number assigned by the photographer. Photographic prints or digital scans serve as reference copies for the negatives and transparencies and are organized by project or subject into groups with the call number designation LOT. Each LOT is cataloged separately and linked through the collection title: Carol M. Highsmith archive.0 aThe archive consists primarily of photographs documenting buildings, urban renewal efforts, and historic preservation. Many of the photographs document the Washington, D.C. area. Projects for the General Services Administration (GSA) show US government buildings through the United States. Projects for the Urban Land Institute document urban settings such as San Antonio, Texas and the greater Los Angeles, California region. Also included are photographs of President Ronald Reagan meeting with Republican Senatorial candidates and photographs of Lexington, Virginia. In addition, there are two photographs taken near the crash site of United Airlines Flight 93 in Shanksville, Pennsylvania.0 aIn 2007, the photographer began to add born digital photographs to the archive, beginning with a large project documenting the Library of Congress buildings; continuing the GSA building documentation; and in 2009 launching the Carol M. Highsmith's America project to document each state in the United States, starting with Alabama.8 aPublished images must bear the credit line: The Library of Congress, Carol M. Highsmith Archive. aNo known restrictions on publication. Photographs are in the public domain. aDistinguished architectural photographer, based in Washington, D.C., Highsmith documents architecture and architectural renovation projects in the nation's capitol and throughout the United States. She bases her career on the work of noted documentary and architectural photographer Frances Benjamin Johnston (1864-1952). aThis archive is open-ended; future gifts are expected. The catalog record will be updated as new accessions are processed. aCollection includes Highsmith's captions which accompany the images. cGift;aCarol M. Highsmith;d1992, 1994, 2002;e(DLC/PP-1992:189, DLC/PP-1994:020, DLC/PP-2002:038), and later. 7aArchitecturezUnited Statesy1980-2010.2lctgm 7aChurcheszUnited Statesy1980-2010.2lctgm 7aCities & townszUnited Statesy1980-2010.2lctgm 7aCommercial facilitieszUnited Statesy1980-2010.2lctgm 7aConservation & restorationzWashington (D.C.)y1980-2000.2lctgm 7aCultural facilitieszUnited Statesy1980-2010.2lctgm 7aDwellingszUnited Statesy1980-2010.2lctgm 7aEducational facilitieszUnited Statesy1980-2010.2lctgm 7aGovernment facilitieszUnited Statesy1980-2010.2lctgm 7aHistoric buildingszUnited Statesy1980-2010.2lctgm 7aMilitary facilitieszUnited Statesy1980-2010.2lctgm 7aMonuments & memorialszUnited Statesy1980-2010.2lctgm 7aSocial & civic facilitieszUnited Statesy1980-2010.2lctgm 7aParades & processionszUnited Statesy1980-20102lctgm 7aPresidents & the CongresszWashington (D.C.)y1980-1990.2lctgm 7aSports & recreation facilitieszUnited Statesy1980-2010.2lctgm 7aTransportation facilitieszUnited Statesy1980-2010.2lctgm 7aAerial photographsy1980-2010.2gmgpc 7aPortrait photographsy1980-1990.2gmgpc 7aGroup portraitsy1980-1990.2gmgpc 7aGelatin silver printsy1980-2000.2gmgpc 7aDye destruction printsxColory1980-2000.2gmgpc 7aSafety film negativesy1980-2010.2gmgpc 7aFilm transparenciesxColory1980-2010.2gmgpc 7aDigital photographsxColory2000-2010.2gmgpc aLibrary of CongressbPrints and Photographs DivisioneWashington, D.C., 20540 USAndcu41zSearch for Highsmith items in Prints & Photographs Online Cataloguhttp://hdl.loc.gov/loc.pnp/pp.highsm""" REC_MP = b"""cem a22002531 4500001001300000003000400013005001700017007000900034008004100043010001700084035002000101040002600121043001200147050002300159100003500182245017700217255001900394260004600413300003200459505012300491651002800614650005100642710002300693 00004452 DLC20121013005559.0ad canzn940812m18981906pau e eng  a 00004452  a(OCoLC)30935992 aDLCcPPiHidPPiDdDLC an-us-pa00aG1264.P6bH62 18981 aHopkins, Griffith Morgan,cJr.10aReal estate plat-book of the city of Pittsburgh :bfrom official records, private plans and actual surveys /cconstructed under the direction and published by G.M. Hopkins. aScales differ. aPhiladelphia :bG.M. Hopkins,c1898-1906. a4 v. :bcol. maps ;c59 cm.0 av.1. 13th-14th, 22nd-23rd wards -- v. 2. 18th-21st, 37th wards -- v. 3 6th-12th, 15th-17th wards -- v. 4. 1st-5th, 7th 0aPittsburgh (Pa.)vMaps. 0aReal propertyzPennsylvaniazPittsburghvMaps.2 aG.M. Hopkins & Co.""" REC_CF = b"""cmm a2200349 a 4500001001300000003000400013005001700017007001500034008004100049010001700090020001500107040001300122050001000135082001400145245013600159256003100295260007500326300004100401490005900442538024400501538020300745500002700948521004300975520012701018650002001145650001701165700002401182700002501206700002201231710004901253830007701302 00021631 DLC20030624102241.0co |||||||||||000110s2000 ohu f m eng  a 00021631  a1571170383 aDLCcDLC00aTA16510a620.121300aLeak testing CD-ROMh[computer file] /ctechnical editors, Charles N. Jackson, Jr., Charles N. Sherlock ; editor, Patrick O. Moore. aComputer data and program. aColumbus, Ohio :bAmerican Society for Nondestructive Testing,cc2000. a1 computer optical disc ;c4 3/4 in.1 aNondestructive testing handbook. Third edition ;vv. 1 aSystem requirements for Windows: i486 or Pentium processor-based PC; 8MB RAM on Windows 95 or 98 (16MB recommended); 16MB RAM on Windows NT (24MB recommended); Microsoft Windows 95, 98, or NT 4.0 with Service Pack 3 or later; CD-ROM drive. aSystem requirements for Macintosh: Apple Power Macintosh ; 4.5MB RAM available to Acrobat Reader (6.5 recommended); Apple System Software 7.1.2 or later; 8MB available hard disk space; CD-ROM drive. aTitle from disc label. aQuality control engineers, inspectors. aTheory and application of nondestructive tests for characterization and inspection of industrial materials and components. 0aLeak detectors. 0aGas leakage.1 aJackson, Charles N.1 aSherlock, Charles N.1 aMoore, Patrick O.2 aAmerican Society for Nondestructive Testing. 0aNondestructive testing handbook (3rd ed. : Electronic resource) ;vv. 1.""" REC_MU = b"""cjm a22002771a 4500001001300000003000400013005001700017007001500034008004100049050001400090010001700104020001100121024001700132028003400149035002300183040001800206042001300224100002400237245005000261260004700311300004100358500001800399511006100417505038100478650001600859 00000838 DLC20030506181700.0sd|zsngnnmmned000824s1998 nyuppn d00aSDA 16949 a 00000838  c$15.981 a60121531262102aUPTD 53126bUniversal Records a(OCoLC)ocm39655785 aOCOcOCOdDLC alcderive0 aMcGruffc(Musician)10aDestined to beh[sound recording] /cMcGruff. aNew York, NY :bUniversal Records,cp1998. a1 sound disc :bdigital ;c4 3/4 in. aCompact disc.0 aRap music performed by McGruff ; with accomp. musicians.0 aGruff express -- Harlem kidz get biz -- This is how we do -- Many know -- Exquisite -- The spot (interlude) -- What part of the game -- Who holds his own -- What cha doin' to me -- Destined to be -- Freestyle -- Dangerzone -- What you want -- Before we start -- Reppin' uptown (featuring The Lox) -- The signing (interlude) -- Stop it -- Before we start (remix) (bonus track). 0aRap (Music)""" REC_CR = b"""nas a2200157 a 4500001001300000003000400013005001700017008004100034010001700075035002000092040001300112042000700125245008500132260007400217500012100291 00000000 DLC19940915171908.0940906u19949999dcuuu 0 0eng  a 00000000  a(OCoLC)31054590 aDLCcDLC alc00aOnline test record /cJohn D. Levy, Serial Record Division, Library of Congress. aWashington, DC :bLibrary of Congress, Serial Record Division,c1994- aThis record provides a marker in the LC MUMS ONUM index that will prevent other records with this LCCN from loading.""" REC_VM = b"""cgm a22001817a 4500001001300000003000400013005001700017007002400034008004100058010001700099040001300116050003000129245008400159260004000243300005900283541008300342710005200425 00270273 DLC20000412151520.0m 991028s xxu v|eng  a 00270273  aDLCcDLC00aCGC 9600-9605 (ref print)00aAfflictionh[motion picture] /cLargo Entertainment; directed by Paul Schrader. aU.S. :bLargo Entertainment,c1997. a12r of 12 on 6 reels :bsd., col. ;c35 mm. ref print. dReceived: 3/24/00;3ref print;ccopyright deposit--407;aCopyright Collection.2 aCopyright Collection (Library of Congress)5DLC""" REC_02 = b"""cem a22002893a 4500001001300000003000400013005001700017007000900034007000700043008004100050010003000091017003400121034001400155040001300169050002400182052000900206110003000215245003700245255002700282260001900309300003400328530007900362651002300441752001700464852008600481856010100567 00552205DLC20000621074203.0aj|canzncr||||000313s1915 xx d 0 eng  a 00552205z 99446781  aF27747bU.S. Copyright Office0 aab140000 aDLCcDLC00aG4970 1915b.R3 TIL a49702 aRand McNally and Company.00aMap of the island of Porto Rico. aScale [ca. 1:140,000]. a[S.l.],c1915. a1 map :bcol. ;c71 x 160 cm. aAvailable also through the Library of Congress web site as a raster image. 0aPuerto RicovMaps. aPuerto Rico.0 aLibrary of CongressbGeography and Map DivisioneWashington, D.C. 20540-4650ndcu7 dg4970fct000492gurn:hdl:loc.gmd/g4970.ct000492uhttp://hdl.loc.gov/loc.gmd/g4970.ct0004922http"""
"""A bunch of click related tools / helpers / patterns that have a potential of reuse across clis. TODO: We would improve sharing by moving these to a separate re-usable repository instead of copying. """
''' your local settings. Note that if you install using setuptools, change this module first before running setup.py install. ''' oauthkey = '7dkss6x9fn5v' secret = 't5f28uhdmct7zhdr' country = 'US'
#!/usr/bin/env python3 # Conditional Statements def drink(money): if (money >= 2): return "You've got yourself a drink!" else: return "NO drink for you!" print(drink(3)) print(drink(1)) def alcohol(age, money): if (age >= 21) and (money >= 5): # if statement return "we're getting a drink!" elif (age >= 21) and (money < 5): # else-if statement return "Come back with more money!" elif (age < 21) and (money >= 5): return "Nice try, kid!" else: # else statement return "You're too poor and too young" print(alcohol(21, 5)) print(alcohol(21, 4)) print(alcohol(20, 4))
def getUniqueID(inArray): ''' Given an int array that contains many duplicates and a single unique ID, find it and return it. ''' pairDictionary = {} for quadID in inArray: # print(quadID) # print(pairDictionary) if quadID in pairDictionary: del pairDictionary[quadID] else: pairDictionary[quadID] = 1 return pairDictionary.keys() def getUniqueIDSpaceOptimized(inArray): a = 0 for quadID in inArray: a = a ^ quadID return a def main(): # should return 9 as the unique integer testArray = [1,2,5,3,2,5,3,1,9,3,4,3,4] print("Unique ID was: %s"%(getUniqueID(testArray))) print("With space optimized solution, unique ID was: %s"%(getUniqueIDSpaceOptimized(testArray))) if __name__ == "__main__": main()
# create a dictionary from two lists using zip() # More information using help('zip') and help('dict') # create two lists dict_keys = ['bananas', 'bread flour', 'cheese', 'milk'] dict_values = [2, 1, 4, 3] # iterate over lists using zip iterator_using_zip = zip(dict_keys, dict_values) # create the dictionary from the zip dictionary_from_zip = dict(iterator_using_zip) print(dictionary_from_zip) # prints {'bananas': 2, 'bread flour': 1, 'cheese': 4, 'milk': 3}
p = int(input()) q = int(input()) for i in range(1, 101): if i % p == q: print(i)
# PATH UPLOAD_FOLDER = './upload_file' GENERATE_PATH = './download_file' # DATABASE DATABASE = 'mysql' DATABASE_URL = 'localhost:3306' USERNAME = 'root' PASSWORD = 'root'
# TODO - bisect operations class SortedDictCore: def __init__(self, *a, **kw): self._items = [] self.dict = dict(*a,**kw) ## def __setitem__(self,k,v): self._items = [] self.dict[k]=v def __getitem__(self,k): return self.dict[k] def __delitem__(self,k): self._items = [] del self.dict[k] ## def sort(self): if self._items: return self._items = sorted(self.dict.items(),key=lambda x:(x[1],x[0])) def items(self): self.sort() return self._items def update(self,*a,**kw): self._items = [] self.dict.update(*a,**kw) class SortedDict(SortedDictCore): def sd_get(self,k): return self.dict.get(k) def sd_set(self,k,v): self[k] = v def sd_del(self,k): if k in self.dict: del self.dict[k] def sd_add(self,k,v): try: self[k] += v except KeyError: self[k] = v return self[k] def sd_items(self,a=None,b=None,c=None): if a is not None or b is not None or c is not None: return self.items() else: return self.items()[a:b:c] # *_many def sd_get_many(self,k_iter): return (self.sd_get(k) for k in k_iter) def sd_set_many(self,kv_iter): for k,v in kv_iter: self.sd_set(k,v) def sd_del_many(self,k_iter): for k in k_iter: self.sd_del(k) def sd_add_many(self,kv_iter): out = [] for k,v in kv_iter: x = self.sd_add(k,v) out.append(x) return out if __name__=="__main__": d = SortedDict(a=3,b=1,c=2,d=(2,2)) d['x'] = 1.5 d.sd_add('a',0.1) d.sd_add('y',0.1) print(d.items()[-2:])
n = 2001 number = 1 while n < 2101: if number % 10 == 0: print("\n") number += 1 if n % 100 == 0: if n % 400 == 0: print(n, end=" ") n += 1 number += 1 continue else: n += 1 continue else: if n % 4 == 0: print(n, end=" ") n += 1 number += 1 continue else: n += 1 continue
# Python - 3.6.0 def high_and_low(numbers): lst = [*map(int, numbers.split(' '))] return f'{max(lst)} {min(lst)}'
# Peça um número para o usuário e mostre se ele é positivo ou negativo numero = int(input("Digite um número")) print("positivo") if numero >=0 else print("Negativo")
#!/usr/bin/env python # -*- coding=utf-8 -*- s = set('huangxiang') print('s=', s) t = frozenset('huangxiang') print('t= ', t) print('type(s):', type(s)) print('type(t)', type(t)) print('len(s)=', len(s)) print('len(t)=', len(t)) """输出结果: s= {'i', 'g', 'x', 'a', 'h', 'u', 'n'} t= frozenset({'i', 'g', 'x', 'a', 'h', 'u', 'n'}) type(s): <class 'set'> type(t) <class 'frozenset'> len(s)= 7 len(t)= 7 """
online_store = { "keychain": 0.75, "tshirt": 8.50, "bottle": 10.00 } choicekey = int(input("How many keychains will you be purchasing? If not purchasing keychains, enter 0. ")) choicetshirt = int(input("How many t-shirts will you be purchasing? If not purchasing t-shirts, enter 0. ")) choicebottle = int(input("How many t-shirts will you be purchasing? If not purchasing water bottles, enter 0. ")) if choicekey > 9: online_store['keychain'] = 0.65 if choicetshirt > 9: online_store['tshirt'] = 8.00 if choicebottle > 9: online_store['bottle'] = 8.75 print("You are purchasing " + str(choicekey) + " keychains, " + str(choicetshirt) + " t-shirts, and " + str(choicebottle) + " water bottles.") perskey = input("Will you personalize the keychains for an additional $1.00 each? Type yes or no. ") perstshirt = input("Will you personalize the t-shirts for an additional $5.00 each? Type yes or no. ") persbottle = input("Will you personalize the water bottles for an additional $7.50 each? Type yes or no. ") if perskey == ("yes" or "Yes"): online_store['keychain'] = online_store['keychain'] + 1.00 if perstshirt == ("yes" or "Yes"): online_store['tshirt'] = online_store['tshirt'] + 5.00 if persbottle == ("yes" or "Yes"): online_store['bottle'] = online_store['bottle'] + 7.50 keychain = online_store['keychain'] tshirt = online_store['tshirt'] bottle = online_store['bottle'] totalkey = choicekey * keychain totaltshirt = choicetshirt * tshirt totalbottle = choicebottle * bottle grandtotal = totalkey + totaltshirt + totalbottle print("Keychain total: $" + str(totalkey)) print("T-shirt total: $" + str(totaltshirt)) print("Water bottle total: $" + str(totalbottle)) print("Your order total: $" + str(grandtotal))
# -*- coding: utf-8 -*- config = {} config['log_name'] = 'app_log.log' config['log_format'] = '%(asctime)s - %(levelname)s: %(message)s' config['log_date_format'] = '%Y-%m-%d %I:%M:%S' config['format'] = 'json' config['source_dir'] = 'data' config['output_dir'] = 'export' config['source_glob'] = 'monitoraggio_serviz_controllo_giornaliero_*.pdf' config['processed_dir'] = 'processed'
_mods = [] def get(): return _mods def add(mod): _mods.append(mod)
n = int(input()) lst = [list(map(int, input().split())) for _ in range(n)] dp = [[0]*3 for _ in range(n)] for i in range(3): dp[0][i] = lst[0][i] for i in range(1, n): dp[i][0] = max(dp[i-1][1], dp[i-1][2])+lst[i][0] dp[i][1] = max(dp[i-1][0], dp[i-1][2])+lst[i][1] dp[i][2] = max(dp[i-1][0], dp[i-1][1])+lst[i][2] print(max(dp[n-1]))
# cases where FunctionAchievement should not unlock # >> CASE def test(): pass # >> CASE def func(): pass func # >> CASE def func(): pass f = func f() # >> CASE func() # >> CASE func
""" Tools to validate schema of python objects """ class RoyalValidationError(Exception): pass class SchemaValidator(object): def __init__(self, **kwargs): self.schema = kwargs self.checks = [] def validate(self, obj): for key in self.schema: if key not in obj: raise RoyalValidationError("Expected key '" + key + "' in object.") if isinstance(self.schema[key], type) and not isinstance(obj[key], self.schema[key]): raise RoyalValidationError("Expected key '" + key + "' to be of type: " + str(self.schema[key])) for check in self.checks: if not check(obj): raise RoyalValidationError("Object does not pass all checks") def add_check(self, check): self.checks.append(check)
class Solution: def removeDuplicates(self, nums: List[int]) -> int: return len(nums) if len(nums) < 2 else self.calculate(nums) @staticmethod def calculate(nums): result = 0 for i in range(1, len(nums)): if nums[i] != nums[result]: result += 1 nums[result] = nums[i] return result + 1
# split()采用none为sep时,可以自动舍去末尾的空格 class Solution: def lengthOfLastWord(self, s: str) -> int: l = s.split() if len(l)==0: return 0 return len(l[-1]) # 语言无差别解法 class Solution1: def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ cnt, tail = 0, len(s) - 1 while tail >= 0 and s[tail] == ' ': tail -= 1 while tail >= 0 and s[tail] != ' ': cnt += 1 tail -= 1 return cnt if __name__=='__main__': a=Solution1() print(a.lengthOfLastWord('a fewigb '))
''' 在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符。 ''' # 存储在字典中 class Solution(object): def FirstcomeChar(self, s): if s==None or s=="": return " " strList=list(s) dic={} for i in strList: if i not in dic.keys(): dic[i]=0 dic[i]+=1 for i in strList: if dic[i]==1: return i return " " # 定义一个函数,输入两个字符串,从第一个字符串中删除在第二个字符串中出现过的所有字符。 def deletefromTwo(self, s1, s2): if s2=="": return s1 if s2==None: return s2=set(s2) s1=list(s1) for i in s2: if i in s1: while i in s1: s1.pop(s1.index(i)) return "".join(s1) # 删除字符串中所有重复出现的字符 def deletechongfu1(self,s): return set(s) def deletechongfu2(self, s): res=[] for i in s: if i not in res: res.append(i) return "".join(res) s=Solution() print(s.deletefromTwo("We are students.", "aeiou"))
# function with large number of arguments def fun(a, b, c, d, e, f, g): return a + b + c * d + e * f * g print(fun(1, 2, 3, 4, 5, 6, 7))
# Input: nums = [0,1,2,2,3,0,4,2], val = 2 # Output: 5, nums = [0,1,4,0,3] # Explanation: Your function should return length = 5, # with the first five elements of nums containing 0, 1, 3, 0, and 4. # Note that the order of those five elements can be arbitrary. # It doesn't matter what values are set beyond the returned length. class Solution: def removeElement(self, nums: List[int], val: int) -> int: try: while True: nums.remove(val) finally: return len(nums)
print(43*'\033[1;31m=') print(8*'\033[1;33m-\033[m', '\033[1mG E R A D O R D E P A', 8*'\033[1;33m-') print(43*'\033[1;31m=\033[m') first = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) term = first cont = 1 resp = 10 tot = 0 while resp != 0: tot += resp while cont <= tot: print(term, end=' -> ') term += razao cont += 1 print('PAUSA') resp = int(input('Quantos termos você quer mostrar a mais? ')) print(f'Foram exibidos {tot} termos.')
"""Top-level package for py_tutis.""" __author__ = """Chidozie C. Okafor""" __email__ = "chidosiky2015@gmail.com" __version__ = "0.1.0"
# Copyright 2021 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Partial implementation for Swift frameworks with third party interfaces.""" load( "@build_bazel_rules_apple//apple/internal:processor.bzl", "processor", ) load( "@build_bazel_rules_apple//apple/internal:swift_info_support.bzl", "swift_info_support", ) load( "@bazel_skylib//lib:partial.bzl", "partial", ) load( "@bazel_skylib//lib:paths.bzl", "paths", ) def _swift_framework_partial_impl( *, actions, avoid_deps, bundle_name, framework_modulemap, label_name, output_discriminator, swift_infos): """Implementation for the Swift framework processing partial.""" if len(swift_infos) == 0: fail(""" Internal error: Expected to find a SwiftInfo before entering this partial. Please file an \ issue with a reproducible error case. """) avoid_modules = swift_info_support.modules_from_avoid_deps(avoid_deps = avoid_deps) bundle_files = [] expected_module_name = bundle_name found_module_name = None found_generated_header = None modules_parent = paths.join("Modules", "{}.swiftmodule".format(expected_module_name)) for arch, swiftinfo in swift_infos.items(): swift_module = swift_info_support.swift_include_info( avoid_modules = avoid_modules, found_module_name = found_module_name, transitive_modules = swiftinfo.transitive_modules, ) # If headers are generated, they should be generated equally for all archs, so just take the # first one found. if (not found_generated_header) and swift_module.clang: if swift_module.clang.compilation_context.direct_headers: found_generated_header = swift_module.clang.compilation_context.direct_headers[0] found_module_name = swift_module.name bundle_interface = swift_info_support.declare_swiftinterface( actions = actions, arch = arch, label_name = label_name, output_discriminator = output_discriminator, swiftinterface = swift_module.swift.swiftinterface, ) bundle_files.append((processor.location.bundle, modules_parent, depset([bundle_interface]))) bundle_doc = swift_info_support.declare_swiftdoc( actions = actions, arch = arch, label_name = label_name, output_discriminator = output_discriminator, swiftdoc = swift_module.swift.swiftdoc, ) bundle_files.append((processor.location.bundle, modules_parent, depset([bundle_doc]))) swift_info_support.verify_found_module_name( bundle_name = expected_module_name, found_module_name = found_module_name, ) if found_generated_header: bundle_header = swift_info_support.declare_generated_header( actions = actions, generated_header = found_generated_header, label_name = label_name, output_discriminator = output_discriminator, module_name = expected_module_name, ) bundle_files.append((processor.location.bundle, "Headers", depset([bundle_header]))) modulemap = swift_info_support.declare_modulemap( actions = actions, framework_modulemap = framework_modulemap, label_name = label_name, output_discriminator = output_discriminator, module_name = expected_module_name, ) bundle_files.append((processor.location.bundle, "Modules", depset([modulemap]))) return struct(bundle_files = bundle_files) def swift_framework_partial( *, actions, avoid_deps = [], bundle_name, framework_modulemap = True, label_name, output_discriminator = None, swift_infos): """Constructor for the Swift framework processing partial. This partial collects and bundles the necessary files to construct a Swift based static framework. Args: actions: The actions provider from `ctx.actions`. avoid_deps: A list of library targets with modules to avoid, if specified. bundle_name: The name of the output bundle. framework_modulemap: Boolean to indicate if the generated modulemap should be for a framework instead of a library or a generic module. Defaults to `True`. label_name: Name of the target being built. output_discriminator: A string to differentiate between different target intermediate files or `None`. swift_infos: A dictionary with architectures as keys and the SwiftInfo provider containing the required artifacts for that architecture as values. Returns: A partial that returns the bundle location of the supporting Swift artifacts needed in a Swift based sdk framework. """ return partial.make( _swift_framework_partial_impl, actions = actions, avoid_deps = avoid_deps, bundle_name = bundle_name, framework_modulemap = framework_modulemap, label_name = label_name, output_discriminator = output_discriminator, swift_infos = swift_infos, )
class Solution: def firstMissingPositive(self, nums: List[int], res: int = 1) -> int: for num in sorted(nums): res += num == res return res
""" 1991 : 트리 순회 URL : https://www.acmicpc.net/problem/1991 Input : 7 A B C B D . C E F E . . F . G D . . G . . Output : ABDCEFG DBAECFG DBEGFCA """ tree = {} def preorder(root): traversal = [] traversal += root if tree[root]['left'] is not None: traversal += preorder(tree[root]['left']) if tree[root]['right'] is not None: traversal += preorder(tree[root]['right']) return traversal def inorder(root): traversal = [] if tree[root]['left'] is not None: traversal += inorder(tree[root]['left']) traversal += root if tree[root]['right'] is not None: traversal += inorder(tree[root]['right']) return traversal def postorder(root): traversal = [] if tree[root]['left'] is not None: traversal += postorder(tree[root]['left']) if tree[root]['right'] is not None: traversal += postorder(tree[root]['right']) traversal += root return traversal n = int(input()) for i in range(n): name, left, right = input().split() tree[name] = { 'left': left if left is not '.' else None, 'right': right if right is not '.' else None, } print(''.join(preorder('A'))) print(''.join(inorder('A'))) print(''.join(postorder('A')))
# # PySNMP MIB module Wellfleet-AOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-AOT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:32:37 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) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") NotificationType, Bits, Integer32, ModuleIdentity, ObjectIdentity, Counter32, TimeTicks, Gauge32, Counter64, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Bits", "Integer32", "ModuleIdentity", "ObjectIdentity", "Counter32", "TimeTicks", "Gauge32", "Counter64", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "MibIdentifier") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") wfAsyncOverTcpGroup, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfAsyncOverTcpGroup") wfAot = MibIdentifier((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1)) wfAotDelete = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotDelete.setStatus('mandatory') wfAotDisable = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotDisable.setStatus('mandatory') wfAotState = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("init", 3), ("notpresent", 4))).clone('down')).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotState.setStatus('mandatory') wfAotInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2), ) if mibBuilder.loadTexts: wfAotInterfaceTable.setStatus('mandatory') wfAotInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1), ).setIndexNames((0, "Wellfleet-AOT-MIB", "wfAotInterfaceSlotNumber"), (0, "Wellfleet-AOT-MIB", "wfAotInterfaceCctNumber")) if mibBuilder.loadTexts: wfAotInterfaceEntry.setStatus('mandatory') wfAotInterfaceDelete = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotInterfaceDelete.setStatus('mandatory') wfAotInterfaceDisable = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotInterfaceDisable.setStatus('mandatory') wfAotInterfaceCctNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotInterfaceCctNumber.setStatus('mandatory') wfAotInterfaceSlotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotInterfaceSlotNumber.setStatus('mandatory') wfAotInterfaceState = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("init", 3))).clone('down')).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotInterfaceState.setStatus('mandatory') wfAotInterfaceType = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("singledrop", 1), ("multidrop", 2))).clone('singledrop')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotInterfaceType.setStatus('mandatory') wfAotInterfaceAttachedTo = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("primary", 1), ("secondary", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotInterfaceAttachedTo.setStatus('mandatory') wfAotInterfacePktCnt = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotInterfacePktCnt.setStatus('mandatory') wfAotKeepaliveInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 86400)).clone(120)).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotKeepaliveInterval.setStatus('mandatory') wfAotKeepaliveRto = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 600)).clone(4)).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotKeepaliveRto.setStatus('mandatory') wfAotKeepaliveMaxRetry = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 99)).clone(5)).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotKeepaliveMaxRetry.setStatus('mandatory') wfAotPeerTable = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3), ) if mibBuilder.loadTexts: wfAotPeerTable.setStatus('mandatory') wfAotPeerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1), ).setIndexNames((0, "Wellfleet-AOT-MIB", "wfAotPeerSlotNumber"), (0, "Wellfleet-AOT-MIB", "wfAotPeerCctNumber"), (0, "Wellfleet-AOT-MIB", "wfAotPeerRemoteIpAddr"), (0, "Wellfleet-AOT-MIB", "wfAotPeerLocalTcpListenPort"), (0, "Wellfleet-AOT-MIB", "wfAotPeerRemoteTcpListenPort"), (0, "Wellfleet-AOT-MIB", "wfAotConnOriginator")) if mibBuilder.loadTexts: wfAotPeerEntry.setStatus('mandatory') wfAotPeerEntryDelete = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotPeerEntryDelete.setStatus('mandatory') wfAotPeerEntryDisable = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotPeerEntryDisable.setStatus('mandatory') wfAotPeerSlotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerSlotNumber.setStatus('mandatory') wfAotPeerCctNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerCctNumber.setStatus('mandatory') wfAotPeerRemoteIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 5), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerRemoteIpAddr.setStatus('mandatory') wfAotConnOriginator = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("self", 1), ("partner", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotConnOriginator.setStatus('mandatory') wfAotPeerLocalTcpListenPort = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1000, 9999))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerLocalTcpListenPort.setStatus('mandatory') wfAotPeerRemoteTcpListenPort = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1000, 9999))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerRemoteTcpListenPort.setStatus('mandatory') wfAotPeerLocalTcpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1000, 9999))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerLocalTcpPort.setStatus('mandatory') wfAotPeerRemoteTcpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1000, 9999))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerRemoteTcpPort.setStatus('mandatory') mibBuilder.exportSymbols("Wellfleet-AOT-MIB", wfAotPeerRemoteIpAddr=wfAotPeerRemoteIpAddr, wfAotInterfaceState=wfAotInterfaceState, wfAotInterfaceAttachedTo=wfAotInterfaceAttachedTo, wfAotPeerTable=wfAotPeerTable, wfAotInterfaceCctNumber=wfAotInterfaceCctNumber, wfAotState=wfAotState, wfAotPeerEntryDisable=wfAotPeerEntryDisable, wfAotPeerLocalTcpListenPort=wfAotPeerLocalTcpListenPort, wfAotPeerLocalTcpPort=wfAotPeerLocalTcpPort, wfAotPeerEntryDelete=wfAotPeerEntryDelete, wfAotDelete=wfAotDelete, wfAotDisable=wfAotDisable, wfAotInterfaceType=wfAotInterfaceType, wfAotInterfaceEntry=wfAotInterfaceEntry, wfAotKeepaliveInterval=wfAotKeepaliveInterval, wfAotPeerSlotNumber=wfAotPeerSlotNumber, wfAotPeerCctNumber=wfAotPeerCctNumber, wfAotInterfaceDisable=wfAotInterfaceDisable, wfAotInterfaceSlotNumber=wfAotInterfaceSlotNumber, wfAotInterfaceTable=wfAotInterfaceTable, wfAotKeepaliveMaxRetry=wfAotKeepaliveMaxRetry, wfAotInterfaceDelete=wfAotInterfaceDelete, wfAotPeerEntry=wfAotPeerEntry, wfAotConnOriginator=wfAotConnOriginator, wfAotPeerRemoteTcpListenPort=wfAotPeerRemoteTcpListenPort, wfAotPeerRemoteTcpPort=wfAotPeerRemoteTcpPort, wfAotInterfacePktCnt=wfAotInterfacePktCnt, wfAot=wfAot, wfAotKeepaliveRto=wfAotKeepaliveRto)
# absoluteimports/__init__.py print("inside absoluteimports/__init__.py")
''' 5 - Remapping categories To better understand survey respondents from airlines, you want to find out if there is a relationship between certain responses and the day of the week and wait time at the gate. The airlines DataFrame contains the day and wait_min columns, which are categorical and numerical respectively. The day column contains the exact day a flight took place, and wait_min contains the amount of minutes it took travelers to wait at the gate. To make your analysis easier, you want to create two new categorical variables: - wait_type: 'short' for 0-60 min, 'medium' for 60-180 and long for 180+ - day_week: 'weekday' if day is in the weekday, 'weekend' if day is in the weekend. The pandas and numpy packages have been imported as pd and np. Let's create some new categorical data! Instructions - Create the ranges and labels for the wait_type column mentioned in the description above. - Create the wait_type column by from wait_min by using pd.cut(), while inputting label_ranges and label_names in the correct arguments. - Create the mapping dictionary mapping weekdays to 'weekday' and weekend days to 'weekend'. - Create the day_week column by using .replace(). ''' # Create ranges for categories label_ranges = [0, 60, 180, np.inf] label_names = ['short', 'medium', 'long'] # Create wait_type column airlines['wait_type'] = pd.cut(airlines['wait_min'], bins=label_ranges, labels=label_names) # Create mappings and replace mappings = {'Monday': 'weekday', 'Tuesday': 'weekday', 'Wednesday': 'weekday', 'Thursday': 'weekday', 'Friday': 'weekday', 'Saturday': 'weekend', 'Sunday': 'weekend'} airlines['day_week'] = airlines['day'].replace(mappings) ''' Note: ---------------------------------------------------------------------- we just created two new categorical variables, that when combined with other columns, could produce really interesting analysis. Don't forget, we can always use an assert statement to check our changes passed. ---------------------------------------------------------------------- '''
def read_file(): file_input = open("data/file_input_data.txt", 'r') file_data = file_input.readlines() file_input.close() return file_data if __name__ == "__main__": data = read_file() print(type(data)) print(data) for line in data: print(line)
def is_armstrong_number(number): digits = [int(i) for i in str(number)] d_len = len(digits) d_sum = 0 for digit in digits: d_sum += digit ** d_len return d_sum == number
# Preprocessing config SAMPLING_RATE = 22050 FFT_WINDOW_SIZE = 1024 HOP_LENGTH = 512 N_MELS = 80 F_MIN = 27.5 F_MAX = 8000 AUDIO_MAX_LENGTH = 90 # in seconds # Data augmentation config MAX_SHIFTING_PITCH = 0.3 MAX_STRETCHING = 0.3 MAX_LOUDNESS_DB = 10 BLOCK_MIXING_MIN = 0.2 BLOCK_MIXING_MAX = 0.5 # Model config LOSS = "binary_crossentropy" METRICS = ["binary_accuracy", "categorical_accuracy"] CLASSES = 2 # For audio augmentation - deprecated STRETCHING_MIN = 0.75 STRETCHING_MAX = 1.25 SHIFTING_MIN = -3.5 SHIFTING_MAX = 3.5
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def repo(): http_archive( name = "fmt", strip_prefix = "fmt-7.1.3", urls = ["https://github.com/fmtlib/fmt/releases/download/7.1.3/fmt-7.1.3.zip"], sha256 = "5d98c504d0205f912e22449ecdea776b78ce0bb096927334f80781e720084c9f", build_file = "@//third_party/fmt:fmt.BUILD", )
"""Constants and variables common to the whole program @var VISUALIZE: whether to generate video @var PRECONDITIONER_CLASS: class or function that returns preconditioner object (1-parameter callable object) for CG, see L{SGSPreconditioner} for example @var PRECONDITIONER: preconditioner object (1-parameter callable object) that returns I{z} for a given I{r} @var SGS_ITERATIONS: number of Symmetric Gauss-Seidel iterations @var OPTIMIZE_SGS: whether to use Fortran code for Symmetric Gauss-Seidel @var OPTIMIZE_AX: whether to use Fortran code for matrix-vector multiplication @var STIFFNESS_FUNCTION: coefficient function that returns stiffness for any point (x,y) """ VISUALIZE = True PRECONDITIONER_CLASS = None PRECONDITIONER = None SGS_ITERATIONS = None OPTIMIZE_SGS = True OPTIMIZE_AX = True STIFFNESS_FUNCTION = None
""" In a given integer array nums, there is always exactly one largest element. Find whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwise return -1. Your runtime beats 80.31 % of python submissions. """ class Solution(object): def dominantIndex(self, nums): """ :type nums: List[int] :rtype: int """ """ Method 1 Using Python built-in functions Your runtime beats 80.31 % of python submissions. """ if len(nums) > 1: arr = sorted(nums, reverse=True) if arr[0] >= 2*arr[1]: return nums.index(arr[0]) else: return -1 return 0 """ Method 2 """ max_one = max_two = float("-inf") max_index = 0 if len(nums) > 1: for elem in range(0, len(nums)): if nums[elem] > max_one: max_two = max_one max_one = nums[elem] max_index = elem if max_one > nums[elem] > max_two: max_two = nums[elem] if max_one >= 2 * max_two: return max_index else: return -1 else: return 0
# 1 - push # 2 - pop # 3 - print max element # 4 - print max element # last - print all elements n = int(input()) query = [] for _ in range(n): num = input().split() if num[0] == "1": query.append(int(num[1])) elif num[0] == "2": if query: query.pop() continue elif num[0] == "3": if query: # !!!!!!!!!!!!!!!!!!!!!!!!! print(max(query)) elif num[0] == "4": if query: # !!!!!!!!!!!!!!!!!!!!!!!!! print(min(query)) print(', '.join([str(x) for x in reversed(query)]))
# Constants for the image IMAGE_URL = str(input("Enter a valid image URL: ")) IMAGE_WIDTH = 280 IMAGE_HEIGHT = 200 blueUpFactor = int(input("How much more blue do you want this image | Enter a value between 1 and 255")) maxPixelValue = 255 image = Image(IMAGE_URL) image.set_position(70, 70) image.set_size(IMAGE_WIDTH, IMAGE_HEIGHT) add(image) # Filter to brighten an image def blueFilter(pixel): blue = blueColour(pixel[2]) return blue def blueColour(colorValue): return min(colorValue + blueUpFactor, maxPixelValue) def changePicture(): for x in range(image.get_width()): for y in range(image.get_height()): pixel = image.get_pixel(x,y) newColor = blueFilter(pixel) image.set_blue(x, y, newColor) # Give the image time to load print("Creating Blue Skies....") print("Might take a minute....") timer.set_timeout(changePicture, 1000)
class Solution: def reverseOnlyLetters(self, S: str) -> str: alpha = set([chr(i) for i in list(range(ord('a'), ord('z')+1)) + list(range(ord('A'), ord('Z')+1))]) words, res = [], list(S) for char in res: if char in alpha: words.append(char) for i in range(len(res)): if res[i] in alpha: res[i] = words.pop() return ''.join(res)
# SPDX-FileCopyrightText: 2020 Splunk Inc. # # SPDX-License-Identifier: Apache-2.0 def normalize_to_unicode(value): """ string convert to unicode """ if hasattr(value, "decode") and not isinstance(value, str): return value.decode("utf-8") return value def normalize_to_str(value): """ unicode convert to string """ if hasattr(value, "encode") and isinstance(value, str): return value.encode("utf-8") return value
number = int(input()) while number < 1 or number > 100: print('Invalid number') number = int(input()) print(f'The number is: {number}')
class Configuration(object): config={} def __str__(self): return str(Configuration.config) @staticmethod def defaults(): Configuration.config['api_base_link'] = 'https://api.twitch.tv/kraken/' @staticmethod def load(file=None): if file: with open (file, 'r', encoding='utf-8') as fh: Configuration.config['api_base_link'] = 'https://api.twitch.tv/kraken/' else: Configuration.defaults()
# By Taiwo Kareem <taiwo.kareem36@gmail.com> # Github <https://github.com/tushortz> # Last updated (08-February-2016) # Card class class Card: # Initialize necessary field variables def __init__(self, *code): # Accept two character arguments if len(code) == 2: rank = code[0] suit = code[1] # Can also accept one string argument elif len(code) == 1: if len(code[0]) == 2: rank = code[0][0] suit = code[0][1] else: raise ValueError("card codes must be two characters") else: raise ValueError("card codes must be two characters") self.rank = rank self.suit = suit # All available ranks self.RANKS = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" ] # All available suits self.SUITS = ["C", "D", "H", "S"] # Error checks if not self.rank in self.RANKS: raise ValueError("Invalid rank") if not self.suit in self.SUITS: raise ValueError("Invalid suit") # String representation of cards def __str__(self): return "%s%s" % (self.rank, self.suit) # Class Methods def getRanks(self): return self.RANKS def getSuits(self): return self.SUITS def getRank(self): return self.rank def getSuit(self): return self.suit def hashCode(self): prime = 31 result = 1 result = str(prime * result) + self.rank result = str(prime * result) + self.suit return result def equals(self, thing): same = False if (thing == self): same = True elif (thing != None and isinstance(thing, Card)): if thing.rank == self.rank and thing.suit == self.suit: same = True else: same = False return same def compareTo(self, other): mySuit = self.SUITS.index(self.suit) otherSuit = self.SUITS.index(other.suit) difference = mySuit - otherSuit if difference == 0: myRank = self.RANKS.index(self.rank) otherRank = self.RANKS.index(other.rank) difference = myRank - otherRank return difference