content
stringlengths
7
1.05M
''' function : default value ''' def my_func(a=20, b=10): return a - b print(my_func()) print(my_func(30)) print(my_func(40, 5)) def my_func2(a, b=10): return a + b # default parameter value가 non-default paramter 보다 먼저 올 수 없다. # def my_func3(a=20, b): # return a + b ''' function : tuple parameter, dict parameter ''' def my_func_tuple(*p): return p print(type(my_func_tuple(10))) print(my_func_tuple(10, 20, 30)) def my_func_dict(**p): for k,v in p.items(): print(f'key = {k}, value = {v}') my_func_dict(a=1, b=2, c=3)
"""This module contains rules for the startup c library.""" load("//lib/bazel:c_rules.bzl", "makani_c_library") def _get_linkopts(ld_files): return (["-Tavionics/firmware/startup/" + f for f in ld_files]) def startup_c_library(name, deps = [], ld_files = [], linkopts = [], **kwargs): makani_c_library( name = name, deps = deps + ld_files, linkopts = linkopts + _get_linkopts(ld_files), **kwargs )
DATA = [ {"gender":"male","name":{"title":"mr","first":"brian","last":"watts"},"location":{"street":"8966 preston rd","city":"des moines","state":"virginia","postcode":15835},"dob":"1977-03-11 11:43:34","id":{"name":"SSN","value":"003-73-8821"},"picture":{"large":"https://randomuser.me/api/portraits/men/68.jpg","medium":"https://randomuser.me/api/portraits/med/men/68.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/men/68.jpg"}}, {"gender":"female","name":{"title":"miss","first":"terra","last":"jimenez"},"location":{"street":"1989 taylor st","city":"roseburg","state":"illinois","postcode":86261},"dob":"1987-05-08 18:18:06","id":{"name":"SSN","value":"896-95-9224"},"picture":{"large":"https://randomuser.me/api/portraits/women/17.jpg","medium":"https://randomuser.me/api/portraits/med/women/17.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/17.jpg"}}, {"gender":"female","name":{"title":"mrs","first":"jeanette","last":"thomas"},"location":{"street":"7446 hickory creek dr","city":"caldwell","state":"wyoming","postcode":73617},"dob":"1959-03-21 14:19:01","id":{"name":"SSN","value":"578-92-7338"},"picture":{"large":"https://randomuser.me/api/portraits/women/56.jpg","medium":"https://randomuser.me/api/portraits/med/women/56.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/56.jpg"}}, {"gender":"male","name":{"title":"mr","first":"darrell","last":"ramos"},"location":{"street":"4002 green rd","city":"peoria","state":"new york","postcode":62121},"dob":"1960-03-09 16:44:53","id":{"name":"SSN","value":"778-73-1993"},"picture":{"large":"https://randomuser.me/api/portraits/men/54.jpg","medium":"https://randomuser.me/api/portraits/med/men/54.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/men/54.jpg"}} ] # get data for all students to use in index and write a list def get_all_students(source): # new dictionary students = {} # write id as key and lastname as value into dict for record in source: id = record['id']['value'] # .title() capitalizes the first letter of each word in string lastname = (record['name']['last']).title() students.update({id:lastname}) # return a list of tuples sorted in alpha order by lastname # see https://pybit.es/dict-ordering.html - great resource! return sorted(students.items(), key=lambda x: x[1]) print(get_all_students(DATA))
def init() -> None: pass def run(raw_data: list) -> list: return [{"result": "Hello World"}]
def can_build(env, platform): return platform=="android" def configure(env): if (env['platform'] == 'android'): env.android_add_java_dir("android") env.android_add_res_dir("res") env.android_add_asset_dir("assets") env.android_add_dependency("implementation files('../../../modules/oppo/android/libs/gamesdk-20190227.jar')") env.android_add_dependency("implementation files('../../../modules/oppo/android/libs/oppo_mobad_api_v301_2018_12_07_release.jar')") env.android_add_default_config("applicationId 'com.opos.mobaddemo'") env.android_add_to_manifest("android/AndroidManifestChunk.xml") env.android_add_to_permissions("android/AndroidPermissionsChunk.xml") env.disable_module()
# -*- coding: utf-8 -*- def main(): r, c, d = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(r)] ans = 0 # See: # https://www.slideshare.net/chokudai/arc023 for y in range(r): for x in range(c): if (x + y <= d) and ((x + y) % 2 == d % 2): ans = max(ans, a[y][x]) print(ans) if __name__ == '__main__': main()
""" LECTURE D'UN FICHIER TEXTE """ """ QUESTION 1 """ with open("texte1", "r+") as f: print(f.read(11), end="\n\n") """ QUESTION 2 """ with open("texte1", "r+") as f: print(f.readline(), end="\n\n") f.readline() print(f.readline(), end="\n\n") """ QUESTION 3 """ with open("texte1", "r+") as f: lines = f.readlines() print(lines[1], lines[3]) """ QUESTION 1 """ with open("texte1", "r+") as f: for i in range(3): print(f.readline()) """ QUESTION 2 """ with open("texte1", "r+") as f: print(f.read(3))
#https://leetcode.com/problems/largest-rectangle-in-histogram/ #(Asked in Amazon SDE1 interview) class Solution: def largestRectangleArea(self, heights: List[int]) -> int: sta,finalL=[],[] it=0 for i in heights: #code for next smallest left it+=1 if sta: while(sta and i<=sta[-1][1]): sta.pop() if not sta: finalL.append(-1) elif (i>sta[-1][1]): finalL.append(sta[-1][0]-1) else: finalL.append(-1) sta.append([it,i]) print("finalL",finalL) # general len(heights) as for reverse it,sta,finalR=len(heights),[],[] #code of Next smallest right for i in heights[::-1]: #it-=1 for counting index it-=1 #as it process in reverse if sta: while(sta and i<=sta[-1][1]): sta.pop() if not sta: #if array empty 1 index ahead of last index finalR.append(len(heights)) elif (i>sta[-1][1]): finalR.append(sta[-1][0]) else: finalR.append(len(heights)) sta.append([it,i]) finalR=finalR[::-1] print("finalR",finalR) final=[] #calculate width=NSR-NSL-1 and area=width*height[k] ie arr[k] for k in range(len(heights)): final.append( (finalR[k] - finalL[k] -1) *heights[k]) print("area",final) return (max(final))
""" A simple program to calculate a chaotic function. This program will calculate the first ten values of a chaotic function with the form k(x)(1-x) where k=3.9 and x is provided by the user. """ def main(): """ Calculate the values of the chaotic function. """ x = float(input("Enter a number between 1 and 0: ")) # We will avoid using eval() because it is a security concern. # x = eval(input("Enter a number between 1 and 0: ")) for _ in range(10): x = 3.9 * x * (1 - x) print(x) # identifiers that start and end with double underscores (sometimes called # "dunders") are special in Python. if __name__ == "__main__": main()
class AppSettings: types = { 'url': str, 'requestIntegration': bool, 'authURL': str, 'usernameField': str, 'passwordField': str, 'buttonField': str, 'extraFieldSelector': str, 'extraFieldValue': str, 'optionalField1': str, 'optionalField1Value': str, 'optionalField2': str, 'optionalField2Value': str, 'optionalField3': str, 'optionalField3Value': str } def __init__(self): # The URL of the login page for this app self.url = None # str # Would you like Okta to add an integration for this app? self.requestIntegration = None # bool # The URL of the authenticating site for this app self.authURL = None # str # CSS selector for the username field in the login form self.usernameField = None # str # CSS selector for the password field in the login form self.passwordField = None # str # CSS selector for the login button in the login form self.buttonField = None # str # CSS selector for the extra field in the form self.extraFieldSelector = None # str # Value for extra field form field self.extraFieldValue = None # str # Name of the optional parameter in the login form self.optionalField1 = None # str # Name of the optional value in the login form self.optionalField1Value = None # str # Name of the optional parameter in the login form self.optionalField2 = None # str # Name of the optional value in the login form self.optionalField2Value = None # str # Name of the optional parameter in the login form self.optionalField3 = None # str # Name of the optional value in the login form self.optionalField3Value = None # str
class WikiPage: def __init__(self, title, uri=None, text=None, tags=None): self.title = title self.text = text or "" self.tags = tags or {} self.uri = uri or title self.parents = [] self.children = [] def add_child(self, page): self.children.append(page) page.add_parent(self) def add_parent(self, page): self.parents.append(page) if page.uri == "/": self.uri = "/" + self.uri else: self.uri = page.uri + "/" + self.uri
numbers = [12, 18, 128, 48, 2348, 21, 18, 3, 2, 42, 96, 11, 42, 12, 18] print(numbers) # Insert the number 5 to the beginning of the list. numbers.insert(0, 5) print(numbers) # Remove the number 2348 based on its value (as opposed to a hard-coded index of 4) from the list. numbers.remove(2348) print(numbers) # Create a second list of 5 different numbers and add them to the end of the list in one step. (Make sure it adds the # numbers to the list such as: [1, 2, 3, 4, 5] not as a sub list, such as [1, 2, 3, [4, 5]] ). more_numbers = [1, 2, 3, 4, 5] numbers.extend(more_numbers) print(numbers) # Sort the list using the built in sorting algorithm. numbers.sort() print(numbers) # Sort the list backwards using the built in sorting algorithm. numbers.sort(reverse=True) print(numbers) # Use a built-in function to count the number of 12's in the list. count = numbers.count(12) print(count) # Use a built-in function to find the index of the number 96. index = numbers.index(96) print(index) # Use slicing to get the first half of the list, then get the second half of the list and make sure that nothing was # left out or duplicated in the middle. print(len(numbers)) middle = len(numbers) // 2 first_half = numbers[:middle] # numbers[inclusive:exclusive] print(len(first_half), first_half) second_half = numbers[middle:] print(len(second_half), second_half) # Use slicing to create a new list that has every other item from the original list (i.e., skip elements, # using the step functionality). every_other = numbers[0:len(numbers) - 1:2] print(every_other) # Use slicing to get the last 5 items of the list. For this, please use negative number indexing. print(numbers) last_5 = numbers[:-6:-1] print(last_5)
class pbox_description: def __init__(self, pdb_id): self.pdb_id = pdb_id def get_pdb_id(self): return self.pdb_id
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-02-02 23:27:58 # @Last Modified by: 何睿 # @Last Modified time: 2019-02-02 23:29:33 class Solution: def addDigits(self, num): """ :type num: int :rtype: int """ if num == 0: return 0 b = num % 9 return b if b != 0 else 9
# Getting an input from the user x = int(input("How tall do you want your pyramid to be? ")) while x < 0 or x > 23: x = int(input("Provide a number greater than 0 and smaller than 23: ")) for i in range(x): z = i+1 # counts the number of blocks in the pyramid in each iteration y = x-i # counts the number of spaces in the pyramid in each iteration print(" "*y + "#"*z + " " + "#"*z) # this function builds the pyramid
class Solution: def reverseOnlyLetters(self, s: str) -> str: i = 0 j = len(s)-1 m = list(range(65, 91))+list(range(97, 123)) while i < j: if ord(s[i]) not in m: i += 1 continue if ord(s[j]) not in m: j -= 1 continue s = s[:i]+s[j]+s[i+1:j]+s[i]+s[j+1:] i += 1 j -= 1 return s obj = Solution() res = obj.reverseOnlyLetters(s="a-bC-dEf-ghIj") print(res)
'''Returns unmodifiable sets of "uninteresting" (e.g., not drug like) ligands. References ---------- - `D3R Project <https://github.com/drugdata/D3R/blob/master/d3r/filter/filtering_sets.py`_ ''' METAL_CONTAINING = set(['CP', 'NFU', 'NFR', 'NFE', 'NFV', 'FSO', 'WCC', 'TCN', 'FS2', 'PDV', 'CPT', 'OEC', 'XCC', 'NFS', 'C7P', 'TBR', 'NFC', 'CUB', 'VA3', 'FV1', 'IME', 'FC6', 'RU7', 'TBY', 'REI', 'REJ', 'CNB', 'MM1', 'MM2', 'MM6', 'MM5', 'YBT', 'CN1', 'CLF', 'CLP', 'NC1', 'V4O', 'HC0', 'VO3', 'CFM', 'CZL', 'CON', 'TBR', 'ICS', 'HCN', 'CFN', 'CFC', 'HF3', 'ZRC', 'F3S', 'SRM', 'HDD', 'CUA', 'RU8', 'B22', 'BEF', 'AG1', 'SF4', 'NCO', '0KA', 'FNE', 'QPT']) STABILIZERS = set(['B3P', 'PGE', '6JZ', '15P', 'PE3', 'XPE', '7PE', 'M2M', '13P', '3PP', 'PX4', '3OL', 'OC9', 'AE3', '6JZ', 'XPE', '211', 'ODI', 'DIA', 'PG5', 'CXE', 'ME2', 'P4G', 'TOE', 'PG5', 'PE8', 'ZPG', 'PE3', 'MXE']) BUFFERS = set(['MPO', 'NHE', 'CXS', 'T3A', '3CX', '3FX', 'PIN', 'MES', 'EPE', 'TRS', 'BTB', '144']) COFACTORS = set(['ATP', 'ADP', 'AMP', 'ANP', 'GTP', 'GDP', 'GNP', 'UMP', 'TTP', 'TMP', 'MGD', 'H2U', 'ADN', 'APC', 'M2G', 'OMG', 'OMC', 'UDP', 'UMP', '5GP', '5MU', '5MC', '2MG', '1MA', 'NAD', 'NAP', 'NDP', 'FAD', 'FMN', 'BH4', 'BPH', 'BTN', 'PST', 'SAM', 'SAH', 'COA', 'ACO', 'U10', 'HEM', 'HEC', 'HEA', 'HAS', 'DHE', 'BCL', 'CLA', '6HE', '7HE', 'DCP', '23T', 'H4B', 'WCC', 'CFN', 'AMP', 'BCL', 'BCB', 'CHL', 'NAP', 'CON', 'FAD', 'NAD', 'SXN', 'U', 'G', 'QUY', 'UDG', 'CBY', 'ST9', '25A', ' A', ' C', 'B12', 'HAS', 'BPH', 'BPB', 'IPE', 'PLP', 'H4B', 'PMP', 'PLP', 'TPP', 'TDP', 'COO', 'PQN', 'BCR', 'XAT']) COVALENT_MODS = set(['CS1', 'MSE', 'CME', 'CSO', 'LLP', 'IAS']) FRAGMENTS = set(['ACE', 'ACT', 'DMS', 'EOH', 'FMT', 'IMD', 'DTT', 'BME', 'IPA', 'HED', 'PEP', 'PYR', 'PXY', 'OXE', 'TMT', 'TMZ', 'PLQ', 'TAM', 'HEZ', 'DTV', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'D10', 'OCT', 'ETE', 'TZZ', 'DEP', 'BTB', 'ACY', 'MAE', '144', 'CP', 'UVW', 'BET', 'UAP', 'SER', 'SIN', 'FUM', 'MAK', 'PAE', 'DTL', 'HLT', 'ASC', 'D1D', 'PCT', 'TTN', 'HDA', 'PGA', 'XXD', 'INS', '217', 'BHL', '16D', 'HSE', 'OPE', 'HCS', 'SOR', 'SKM', 'KIV', 'FCN', 'TRA', 'TRC', 'MZP', 'KDG', 'DHK']) EXCIPIENTS = set(['CO2', 'SE', 'GOL', 'PEG', 'EDO', 'PG4', 'C8E', 'CE9', 'BME', '1PE', 'OLC', 'MYR', 'LDA', '2CV', '1PG', '12P', 'XP4', 'PL3', 'PE4', 'PEU', 'MPG', 'B8M', 'BOM', '2PE', 'PG0', 'PE5', 'PG6', 'P33', 'DTV', 'SDS', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'LHG', 'D10', 'OCT', 'LT1', 'ETE', 'BTB', 'PC1', 'ACT', 'ACY', '3GD', 'CDL', 'PLC', 'D1D']) JUNK = set(['AS8', 'PS9', 'CYI', 'NOB', 'DPO', 'MDN', 'APC', 'ACP', 'LPT', 'PBL', 'LFA', 'PGW', 'DD9', 'PGV', 'UPL', 'PEF', 'MC3', 'LAP', 'PEE', 'D12', 'CXE', 'T1A', 'TBA', 'NET', 'NEH', 'P2N', 'PON', 'PIS', 'PPV', 'DPO', 'PSL', 'TLA', 'SRT', '104', 'PTW', 'ACN', 'CHH', 'CCD', 'DAO', 'SBY', 'MYS', 'XPT', 'NM2', 'REE', 'SO4-SO4', 'P4C', 'C10', 'PAW', 'OCM', '9OD', 'Q9C', 'UMQ', 'STP', 'PPK', '3PO', 'BDD', '5HD', 'YES', 'DIO', 'U10', 'C14', 'BTM', 'P03', 'M21', 'PGV', 'LNK', 'EGC', 'BU3', 'R16', '4E6', '1EY', '1EX', 'B9M', 'LPP', 'IHD', 'NKR', 'T8X', 'AE4', 'X13', '16Y', 'B3P', 'RB3', 'OHA', 'DGG', 'HXA', 'D9G', 'HTG', 'B7G', 'FK9', '16P', 'SPM', 'TLA', 'B3P', '15P', 'SPO', 'BCR', 'BCN', 'EPH', 'SPD', 'SPN', 'SPH', 'S9L', 'PTY', 'PE8', 'D12', 'PEK']) DO_NOT_CALL = set(['CP', 'NFU', 'NFR', 'NFE', 'NFV', 'FSO', 'WCC', 'TCN', 'FS2', 'PDV', 'CPT', 'OEC', 'XCC', 'NFS', 'C7P', 'TBR', 'NFC', 'CUB', 'VA3', 'FV1', 'IME', 'FC6', 'RU7', 'TBY', 'REI', 'REJ', 'CNB', 'MM1', 'MM2', 'MM6', 'MM5', 'YBT', 'CN1', 'CLF', 'CLP', 'V4O', 'HC0', 'VO3', 'CFM', 'CZL', 'CON', 'ICS', 'HCN', 'CFN', 'CFC', 'HF3', 'ZRC', 'F3S', 'SRM', 'HDD', 'B3P', 'PGE', '6JZ', '15P', 'PE3', 'XPE', '7PE', 'M2M', '13P', '3PP', 'PX4', '3OL', 'OC9', 'AE3', '211', 'ODI', 'DIA', 'PG5', 'CXE', 'ME2', 'P4G', 'TOE', 'PE8', 'ZPG', 'MXE', 'MPO', 'NHE', 'CXS', 'T3A', '3CX', '3FX', 'PIN', 'MGD', 'NAD', 'NAP', 'NDP', 'FAD', 'FMN', 'BH4', 'BPH', 'BTN', 'COA', 'ACO', 'U10', 'HEM', 'HEC', 'HEA', 'HAS', 'DHE', 'BCL', 'CLA', '6HE', '7HE', 'H4B', 'BCB', 'CHL', 'SXN', 'QUY', 'UDG', 'CBY', 'ST9', '25A', 'B12', 'BPB', 'IPE', 'PLP', 'PMP', 'TPP', 'TDP', 'SO4', 'SUL', 'CL', 'BR', 'CA', 'MG', 'NI', 'MN', 'CU', 'PO4', 'CD', 'NH4', 'CO', 'NA', 'K', 'ZN', 'FE', 'AZI', 'CD2', 'YG', 'CR', 'CR2', 'CR3', 'CAC', 'CO2', 'CO3', 'CYN', 'FS4', 'MO6', 'NCO', 'NO3', 'SCN', 'SF4', 'SE', 'PB', 'AU', 'AU3', 'BR1', 'CA2', 'CL1', 'CS', 'CS1', 'CU1', 'AG', 'AG1', 'AL', 'AL3', 'F', 'FE2', 'FE3', 'IR', 'IR3', 'KR', 'MAL', 'GOL', 'MPD', 'PEG', 'EDO', 'PG4', 'BOG', 'HTO', 'ACX', 'CEG', 'XLS', 'C8E', 'CE9', 'CRY', 'DOX', 'EGL', 'P6G', 'SUC', '1PE', 'OLC', 'POP', 'MES', 'EPE', 'PYR', 'CIT', 'FLC', 'TAR', 'HC4', 'MYR', 'HED', 'DTT', 'BME', 'TRS', 'ABA', 'ACE', 'ACT', 'CME', 'CSD', 'CSO', 'DMS', 'EOH', 'FMT', 'GTT', 'IMD', 'IOH', 'IPA', 'LDA', 'LLP', 'PEP', 'PXY', 'OXE', 'TMT', 'TMZ', '2CV', 'PLQ', 'TAM', '1PG', '12P', 'XP4', 'PL3', 'PE4', 'PEU', 'MPG', 'B8M', 'BOM', 'B7M', '2PE', 'STE', 'DME', 'PLM', 'PG0', 'PE5', 'PG6', 'P33', 'HEZ', 'F23', 'DTV', 'SDS', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'LHG', 'D10', 'OCT', 'LI1', 'ETE', 'TZZ', 'DEP', 'DKA', 'OLA', 'ACD', 'MLR', 'POG', 'BTB', 'PC1', 'ACY', '3GD', 'MAE', 'CA3', '144', '0KA', 'A71', 'UVW', 'BET', 'PBU', 'SER', 'CDL', 'CEY', 'LMN', 'J7Z', 'SIN', 'PLC', 'FNE', 'FUM', 'MAK', 'PAE', 'DTL', 'HLT', 'FPP', 'FII', 'D1D', 'PCT', 'TTN', 'HDA', 'PGA', 'XXD', 'INS', '217', 'BHL', '16D', 'HSE', 'OPE', 'HCS', 'SOR', 'SKM', 'KIV', 'FCN', 'TRA', 'TRC', 'MTL', 'KDG', 'DHK', 'Ar', 'IOD', '35N', 'HGB', '3UQ', 'UNX', 'GSH', 'DGD', 'LMG', 'LMT', 'CAD', 'CUA', 'DMU', 'PEK', 'PGV', 'PSC', 'TGL', 'COO', 'BCR', 'XAT', 'MOE', 'P4C', 'PP9', 'Z0P', 'YZY', 'LMU', 'MLA', 'GAI', 'XE', 'ARS', 'SPM', 'RU8', 'B22', 'BEF', 'DHL', 'HG', 'MBO', 'ARC', 'OH', 'FES', 'RU', 'IAS', 'QPT', 'SR']) all_sets = [METAL_CONTAINING, STABILIZERS, BUFFERS, COFACTORS, COVALENT_MODS, \ FRAGMENTS, EXCIPIENTS, JUNK, DO_NOT_CALL] ALL_GROUPS = {item for subset in all_sets for item in subset}
#!/usr/bin/env python # Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. class ResultsWriters: def __init__(self): "" self.writers = [] def addWriter(self, writer): "" self.writers.append( writer ) def prerun(self, atestlist, rtinfo, verbosity): "" for wr in self.writers: wr.prerun( atestlist, rtinfo, verbosity ) def midrun(self, atestlist, rtinfo): "" for wr in self.writers: wr.midrun( atestlist, rtinfo ) def postrun(self, atestlist, rtinfo): "" for wr in self.writers: wr.postrun( atestlist, rtinfo ) def info(self, atestlist, rtinfo): "" for wr in self.writers: wr.info( atestlist, rtinfo )
# -*- coding: utf-8 -*- """ Created on Tue Oct 30 00:36:25 2018 @author: Ja4rsPC """ x = int(input('Please input integer 1:' )) y = int(input('Please input integer 2: ')) def maxVAlue(m,n): if m>n or m==n: return m else: return n print(maxVAlue(x,y), ' Is greatest') #Scoping def f(x): y = 1 x = x + y print('x = ', x) return x x = 3 y = 2 z = f(x) print('z =', z) print('x =', x) print('y =', y)
# Marcelo Campos de Medeiros # ADS UNIFIP 2020.1 # Patos-PB 17/03/2020 ''' Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário. ''' print('='*43) print('PROGRAMA DA ÁREA DO QUADRADO E SEU DOBRO') print('='*43,'\n') # variável valor do lado do quadrado print('='*43) lado = float(input('Digite um valor do lado de um quadrado: ')) print('='*43, '\n') # calculo da área do quadrado area = lado * 4 print(f'A área do quadrado é: {area:.2f}\n') # calculo do dobro da área dobro = area * 2 print(f'O dobro da área do quadrado é:{dobro:.2f}')
n = int(input()) s = [] for i in range(n): s.append(input()) # [d1, d2, d3, ..., dN] m = [] a = [] r = [] c = [] h = [] for i in s: if i[0] == "M": m.append(i) elif i[0] == "A": a.append(i) elif i[0] == "R": r.append(i) elif i[0] == "C": c.append(i) elif i[0] == "H": h.append(i) ml = len(m) al = len(a) rl = len(r) cl = len(c) hl = len(h) count1 = ml*al*rl + ml*al*cl + ml*al*hl + ml*rl*cl + ml*rl*hl + ml*cl*hl + al*rl*cl + al*rl*hl + al*cl*hl + rl*cl*hl print(count1)
""" Problem statement: We are given with N coins having value val_1 ... val_n , where n is even. We are playing a game with an opponent in alternating turns. In each particular turm one player selects one or last coin. We remove the coin from the row and get the value of the coin. Find the max possinle amoint of money one can win """ #Input: value in form of given sequence of coins #Output: Maximum value a player can win from the array of coins #Imp: N must be even def optimal_strategy(coin, N): #table to store sub problems storage = [[0 for i in range(N)] for i in range(N)] #Diagonal traversal for gap in range(N): for j in range(gap, N): i = j - gap x = 0 #option 1 : #choose ith coin with Vi value #now other player can choose between Vi+(F(i+2,j)) #or Vi+(F(i+1,j-1)) #take min of both if((i + 2) <= j): x = storage[i + 2][j] y = 0 #option 2 : #choose jth coin with Vj value #now other player can choose between Vi+(F(i+1,j-1)) #or Vi+(F(i,j-2)) #take min of both if((i + 1) <= (j - 1)): y = storage[i + 1][j - 1] z = 0 if(i <= (j - 2)): z = storage[i][j - 2] #store the maximum of all storage[i][j] = max(coin[i] + min(x, y), coin[j] + min(y, z)) #Output at storage[0][n01] return storage[0][N - 1] #input function def input_user(): arr = list(map(int,input("Enter the numbers:").strip().split(" "))) n = len(arr) print(optimal_strategy(arr, n)) if __name__ == "__main__": input_user()
# Section 9.3.2 snippets with open('accounts.txt', mode='r') as accounts: print(f'{"Account":<10}{"Name":<10}{"Balance":>10}') for record in accounts: account, name, balance = record.split() print(f'{account:<10}{name:<10}{balance:>10}') ########################################################################## # (C) Copyright 2019 by Deitel & Associates, Inc. and # # Pearson Education, Inc. All Rights Reserved. # # # # DISCLAIMER: The authors and publisher of this book have used their # # best efforts in preparing the book. These efforts include the # # development, research, and testing of the theories and programs # # to determine their effectiveness. The authors and publisher make # # no warranty of any kind, expressed or implied, with regard to these # # programs or to the documentation contained in these books. The authors # # and publisher shall not be liable in any event for incidental or # # consequential damages in connection with, or arising out of, the # # furnishing, performance, or use of these programs. # ##########################################################################
"""Core module of the project.""" def add(x: int, y: int) -> int: """Add two int numbers.""" return x + y
"""misc utils for training neural networks""" class HyperParameterScheduler(object): def __init__(self, initial_val, num_updates, final_val=None, func='linear', gamma=0.999): """ Initialize HyperParameter Scheduler class :param initial_val: initial value of the hyper-parameter :param num_updates: total number of updates for hyper-parameter :param final_val: final value of the hyper-parameter, if None then decay rate is fixed (0.999 for exponential 0 for linear) :param func: decay type ['exponential', linear'] :param gamma: fixed decay rate for exponential decay (if final value is given then this gamma is ignored) """ self.initial_val = initial_val self.total_num_epoch = num_updates self.final_val = final_val self.cur_hp = self.initial_val self.cur_step = 0 if final_val is not None: assert final_val >= 0, 'final value should be positive' if func == "linear": self.hp_lambda = self.linear_scheduler elif func == "exponential": self.hp_lambda = self.exponential_scheduler if initial_val == final_val: self.gamma = 1 else: self.gamma = pow(final_val / initial_val, 1 / self.total_num_epoch) if final_val is not None else gamma else: raise NotImplementedError('scheduler not implemented') def linear_scheduler(self, epoch): if self.final_val is not None: return (self.final_val - self.initial_val)*(epoch/self.total_num_epoch) + self.initial_val else: return self.initial_val - (self.initial_val * (epoch / self.total_num_epoch)) def exponential_scheduler(self, epoch): return self.initial_val * (self.gamma ** epoch) def step(self, epoch=None): assert self.cur_step <= self.total_num_epoch, "scheduler step shouldn't be larger than total steps" if epoch is None: epoch = self.cur_step self.cur_hp = self.hp_lambda(epoch) self.cur_step += 1 return self.cur_hp @property def get_value(self): return self.cur_hp
#Array of numbers numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #Prints out every number in array for number in numbers: print(number) print('') #Adds 1 to every number in array for number in numbers: number += 20 print(number)
""" #teste >>> motor = Motor() >>> motor.velocidade 0 >>> motor.acelerar() >>> motor.velocidade 1 >>> motor.acelerar() >>> motor.velocidade 2 >>> motor.acelerar() >>> motor.velocidade 3 >>> motor.frear() >>> motor.velocidade 1 >>> motor.frear() >>> motor.velocidade 0 >>> direcao = Direcao() >>> direcao.valor 'Norte' >>> direcao.girar_dir() >>> direcao.valor 'Leste' >>> direcao.girar_dir() >>> direcao.valor 'Sul' >>> direcao.girar_dir() >>> direcao.valor 'Oeste' >>> direcao.girar_dir() >>> direcao.valor 'Norte' >>> direcao.girar_esq() >>> direcao.valor 'Oeste' >>> direcao.girar_esq() >>> direcao.valor 'Sul' >>> direcao.girar_esq() >>> direcao.valor 'Leste' >>> direcao.girar_esq() >>> direcao.valor 'Norte' >>> carro = Carro(direcao,motor) >>> carro.calcular_velocidade() 0 >>> carro.acelerar() >>> carro.calcular_velocidade() 1 >>> carro.acelerar() >>> carro.calcular_velocidade() 2 >>> carro.acelerar() >>> carro.calcular_velocidade() 3 >>> carro.frear() >>> carro.calcular_velocidade() 1 >>> carro.frear() >>> carro.calcular_velocidade() 0 """ # classe motor class Motor: # velocidade inicial == 0 def __init__(self): self.velocidade = 0 # acrescenta em 1 a velocidade def acelerar(self): self.velocidade += 1 # frear reduz a velocidade em 2,mas o menor valor possivel é 0 def frear(self): self.velocidade -= 2 self.velocidade = max(0,self.velocidade) #funçao MAX(0,self.vel) 0 e o maximo q pode chegar # criando constante comforme a pep sempre sendo td maiúscula NORTE ='Norte' SUL = 'Sul' LESTE = 'Leste' OESTE = 'Oeste' # classe Direção class Direcao: # dicionario com rotaçao dir e esq rotacao_direita_dic = {NORTE:LESTE ,LESTE:SUL ,SUL:OESTE,OESTE:NORTE} rotacao_esquerda_dic = {NORTE:OESTE ,OESTE:SUL,SUL:LESTE, LESTE:NORTE } def __init__(self): self.valor = NORTE def girar_dir(self): self.valor = self.rotacao_direita_dic[self.valor] def girar_esq(self): self.valor =self.rotacao_esquerda_dic[self.valor] class Carro: def __init__(self,direcao,motor): self.velocidade = 0 def calcular_velocidade(self): return self.velocidade def acelerar(self): self.velocidade += 1 def frear(self): if self.velocidade <=1: self.velocidade = 0 else: self.velocidade -= 2
# Wrong answer 10% name = input() YESnames = [] NOnames = [] first = "" biggestName = 0 habay = "" while name != "FIM": name, choice = name.split() if choice == "YES": if first == "": first = name l = len(name) if biggestName < l: biggestName = l if name not in YESnames: YESnames.append(name) else: NOnames.append(name)
# -*- coding: utf-8 -*- __author__ = 'Huang, Hua' class CSV: def __init__(self, csv_line, sep): self.csv_line = csv_line self.content_list = csv_line.split(sep) if csv_line and isinstance(csv_line, str) else None def get_property(self, ind): if self.content_list and len(self.content_list) > ind: return self.content_list[ind] return None def is_object_valid(self, cls): if hasattr(cls, 'not_null_attrs'): for attr in getattr(cls, 'not_null_attrs'): if not hasattr(self, attr) or not getattr(self, attr): return False return True class FunctionDesc: """ python class mapping to org.apache.kylin.metadata.model.FunctionDesc """ def __init__(self): self.expression = None self.parameter = None self.returntype = None @staticmethod def from_json(json_dict): if not json_dict or type(json_dict) != dict: return None fd = FunctionDesc() fd.expression = json_dict.get('expression') # deserialize json for parameter fd.parameter = ParameterDesc.from_json(json_dict.get('parameter')) fd.returntype = json_dict.get('returntype') return fd class ParameterDesc: """ python class mapping to org.apache.kylin.metadata.model.ParameterDesc """ def __init__(self): self.type = None self.value = None @staticmethod def from_json(json_dict): if not json_dict or type(json_dict) != dict: return None pd = ParameterDesc() pd.type = json_dict.get('type') pd.value = json_dict.get('value') return pd
pi = { "00": { "value": "00", "description": "Base" }, "02": { "value": "02", "description": "POS" } }
class IntervalSchedulingInterval: """interval to schedule in interval scheduling""" def __init__(self, name: str, start_time: int, end_time: int): self.name = name self.start_time = start_time self.end_time = end_time def __repr__(self) -> str: return f"{self.name}({self.start_time}, {self.end_time})" def interval_scheduling(intervals: list[IntervalSchedulingInterval]) -> list[IntervalSchedulingInterval]: """computes biggest set of compatible intervals :param intervals: all available intervals :return: the biggest set of compatible intervals """ sorted_intervals = intervals.copy() sorted_intervals.sort(key=lambda i: i.start_time) selected_intervals = [] while sorted_intervals: new_interval = sorted_intervals.pop(0) selected_intervals.append(new_interval) for interval in sorted_intervals: if new_interval.start_time <= interval.start_time < new_interval.end_time: sorted_intervals.remove(interval) continue if new_interval.start_time < interval.end_time <= new_interval.end_time: sorted_intervals.remove(interval) continue if interval.start_time < new_interval.start_time and new_interval.end_time < interval.end_time: sorted_intervals.remove(interval) return selected_intervals
#decorators for functions def audio_record_thread(func): def inner(s): print("AudioCapture: Started Recording Audio") func(s) print("AudioCapture: Stopped Recording Audio") return return inner def file_saving(func, filename): def wrap(s, filename): print("Saving file...") func(s, filename) print("File saved") return return wrap
# -*- coding: utf-8 -*- """ ----------Phenix Labs---------- Created on Sat Jan 23 23:47:00 2021 @author: Gyan Krishna Topic: """ n = 6 #pattern 1 for i in range(n): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("") print("\n\n") #pattern 2 curr = [] prev = [1] for i in range(n): print("", end=" ") print(1) for i in range(1,n): curr = [1] for j in range(1,i): curr.append(prev[j]+ prev[j-1]) curr.append(1) prev = curr for i in range(n-i): print("", end=" ") for i in curr: print(i, end=" ") print("") print("\n\n") #pattern 3 text = "ABCD" for i in range(len(text)+1): print(text[0:i]) print("\n\n") #pattern 4 for i in range(n): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("") for i in range(n,0,-1): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("") print("\n\n") #pattern 5: for i in range(n,0,-1): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("") for i in range(n): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("")
# In case of ASCII horror, # need to get rid of this in the future. def ascii_saver(s): try: s = s.encode('ascii', errors='ignore') except: print('ascii cannot save', s) return s
''' Python program to round a fl oating-point number to specifi ednumber decimal places ''' #Sample Solution-1: def setListOfIntegerOptionOne (order_amt): print('\nThe total order amount comes to %f' % float(order_amt)) print('The total order amount comes to %.2f' % float(order_amt)) print() def setListOfIntegerOptionTwo (order_amt): print("\nThe total order amount comes to {:0.6f}".format(float(order_amt))) print("\nThe total order amount comes to {:0.2f}".format(float(order_amt))) def main (): inpOption = int (input ("Select options one of the options : |1|2|\n")) impNumber = float (input ("Input a number")) #Use dictionary instead of switch case selection = { 1 : setListOfIntegerOptionOne, 2 : setListOfIntegerOptionTwo, } for key in selection: if key == inpOption: selection[key](impNumber) break main ()
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 11:07:19 2020 @author: 766810 """ x=int(input('Enter number 1: ')) y=int(input('Enter number 2: ')) sum1=0 sum2=0 for i in range(1,x): if x%i==0: sum1+=i for j in range(1,y): if y%j==0: sum2+=j if(sum1==y and sum2==x): print('Amicable!') else: print('Not Amicable!')
class Solution(object): def lengthLongestPath(self, input): """ :type input: str :rtype: int """ maxLen = 0 curLen = 0 stack = [] dfa = {"init": 0, "char": 1, "escapeCMD": 2, "file": 3} state = 0 start = 0 level = 0 for i in xrange(0, len(input)): chr = input[i] if chr == '\n': curLen = 0 if len(stack) == 0 else stack[-1][1] if state == dfa["char"]: curLen += i - start stack.append((input[start:i], curLen + 1, level)) elif state == dfa["file"]: maxLen = max(maxLen, curLen + (i - start)) else: return -1 state = dfa["escapeCMD"] level = 0 elif chr == '\t': if state == dfa["escapeCMD"]: level += 1 else: return "TAB cannot be here" elif chr == '.': if state == dfa["char"] or state == dfa["file"] or state == dfa["escapeCMD"]: state = dfa["file"] else: return "unexpected char before dot", state else: if state == dfa["escapeCMD"]: while stack and stack[-1][2] >= level: stack.pop() start = i state = dfa["char"] elif state == dfa["init"]: state = dfa["char"] elif i == len(input) - 1: curLen = 0 if len(stack) == 0 else stack[-1][1] maxLen = max(maxLen, curLen + (i - start) + 1) # print 'state:', state # print 'stack:', stack # print 'level', level return maxLen
class PermissionsMixin: @classmethod def get_permissions(cls, info): return [permission(info) for permission in cls._meta.permission_classes] @classmethod def check_permissions(cls, info): for permission in cls.get_permissions(info): if not permission.has_permission(): raise PermissionError('Permission denied.')
## private settings SECRET_KEY = '' # UPDATE with random string ALLOWED_HOSTS = [ # local 'localhost', '127.0.0.1', # staging '35.232.16.182', ] INTERNAL_IPS = ['127.0.0.1'] ## for local and test servers TEST_ENV = True ## for prod server # TEST_ENV = False ## project info PROJECT_NAME = 'SourceDive' ## database local db_engine = 'django.db.backends.postgresql_psycopg2' db_name = 'sourcedive' db_user = 'sourcediveuser' db_password = 'sourcediveuser' db_host = 'db' db_port = '5432' ## social auth SOCIAL_AUTH_PASSWORDLESS = True SOCIAL_AUTH_ALWAYS_ASSOCIATE = True SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' # UPDATE see lastpass SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' # UPDATE see lastpass # NOTE: We don't want to whitelist anyone — access should be explicitly given # SOCIAL_AUTH_GOOGLE_WHITELISTED_DOMAINS = ['industrydive.com']
""" Project version and meta informations. """ __version__ = "0.3.6dev2" __title__ = "msiempy" __description__ = "msiempy - McAfee SIEM API Python wrapper" __author__ = "andywalden, tristanlatr, mathieubeland, and other contributors. " __author_email__ = "" __license__ = "The MIT License" __url__ = "https://github.com/mfesiem/msiempy" __keywords__ = "mcafee siem api python wrapper"
def bs(arr,target,s,e): if (s>e): return -1 m= int((s+e)/2) if arr[m]==target: return m elif target>arr[m]: return bs(arr,target,m+1,e) else: return bs(arr,target,s,m-1) if __name__ == "__main__": l1=[1, 2, 3, 4, 55, 66, 78] target = 67 print(bs(l1,target,0,len(l1)-1))
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage command += testshade("-g 16 16 -od uint8 -o Cout out0.tif wrcloud") command += testshade("-g 16 16 -od uint8 -o Cout out0_transpose.tif wrcloud_transpose") command += testshade("-g 16 16 -od uint8 -o Cout out0_varying_filename.tif wrcloud_varying_filename") command += testshade("-g 256 256 -param radius 0.01 -od uint8 -o Cout out1.tif rdcloud") command += testshade("-g 256 256 -param radius 0.01 -param filename cloud_masked_1.geo -od uint8 -o Cout out1_masked_1.tif rdcloud") command += testshade("-g 256 256 -param radius 0.01 -param filename cloud_masked_2.geo -od uint8 -o Cout out1_masked_2.tif rdcloud") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_zero_derivs.tif rdcloud_zero_derivs") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_zero_derivs_search_only.tif rdcloud_zero_derivs_search_only") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_search_only.tif rdcloud_search_only") command += testshade("-g 256 256 -param radius 0.1 -od uint8 -o Cout out2.tif rdcloud") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_rdcloud_varying_filename.tif rdcloud_varying_filename") command += testshade("--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying_maxpoint.tif rdcloud_varying_maxpoint") command += testshade("--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying_sort.tif rdcloud_varying_sort") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_rdcloud_get_varying_filename.tif rdcloud_get_varying_filename") command += testshade("--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying.tif rdcloud_varying") outputs = [ "out0.tif" ] outputs += [ "out0_transpose.tif" ] outputs += [ "out0_varying_filename.tif" ] outputs += [ "out1.tif" ] outputs += [ "out1_masked_1.tif" ] outputs += [ "out1_masked_2.tif" ] outputs += [ "out_zero_derivs.tif" ] outputs += [ "out_search_only.tif" ] outputs += [ "out_zero_derivs_search_only.tif" ] outputs += [ "out2.tif" ] outputs += [ "out_rdcloud_varying_filename.tif" ] outputs += [ "out_rdcloud_varying_maxpoint.tif" ] outputs += [ "out_rdcloud_varying_sort.tif" ] outputs += [ "out_rdcloud_varying.tif" ] outputs += [ "out_rdcloud_get_varying_filename.tif" ] # expect a few LSB failures failthresh = 0.008 failpercent = 3
PARAM_DESCR = { 'epochs': 'How many epochs to train.', 'learning rate': 'Optimizer learning rate.', 'batch size': 'The number of samples to use in one training batch.', 'decay': 'Learning rate decay.', 'early stopping': 'Early stopping delta and patience.', 'dropout': 'Dropout rate.', 'layers': 'The number of hidden layers.', 'optimizer': 'Which optimizer to use.' } LONG_DESCR = { 'learning rate': 'A hyperparameter which determines how quickly new learnings override old ones during training. In general, find a learning rate that is low enough that the network will converge to something useful, but high enough that the training does not take too much time.', 'batch size': 'Defines the number of samples to be propagated through the network at once in a batch. The higher the batch size, the more memory you will need.', 'epochs': 'The number of epochs define how often the network will see the complete set of samples during training.', 'decay': 'When using learning rate decay, the learning rate is gradually reduced during training which may result in getting closer to the optimal performance.', 'early stopping': 'Early Stopping is a form of regularization used to avoid overfitting when training. It is controlled via two parameters: Delta defines the minimum change in the monitored quantity to qualify as an improvement. Patience sets the number of epochs with no improvement after which training will be stopped.', 'dropout': 'Dropout is a regularization technique for reducing overfitting in neural networks, The term "dropout" refers to dropping out units (both hidden and visible) in a neural network during training.', 'layers': 'Deep learning models consist of a number of layers which contain one or more neurons. Typically, the neurons in one layer are connected to the next. Models with a higher number of layers can learn more complex representations, but are also more prone to overfitting.', 'optimizer': 'The algorithm which updates model parameters such as the weight and bias values when training the network.', 'sgd': 'Stochastic gradient descent, also known as incremental gradient descent, is a method for optimizing a neural network. It is called stochastic because samples are selected randomly instead of as a single group, as in standard gradient descent.', 'adam': 'The Adam optimization algorithm is an extension to stochastic gradient descent which computes adaptive learning rates for each parameter. Adam is well suited for many practical deep learning problems.', 'environment variables': """\ The following environment variables are available in VergeML: - VERGEML_PERSISTENCE The number of persistent instances - VERGEML_THEME The theme of the command line application - VERGEML_FUNKY_ROBOTS Funky robots""", "overfitting": "When a model performs well on the training samples, but is not able to generalize well to unseen data. During training, a typical sign for overfitting is when your validation loss goes up while your training loss goes down.", "underfitting": "When a model can neither model the training data nor generalize to new data.", "hyperparameters": "Hyperparameters are the parameters of a model that can be set from outside, i.e. are not learned during training. (e.g. learning rate, number of layers, kernel size).", "random seed": "An integer value that seeds the random generator to generate random values. It is used to repeatably reproduce tasks and experiments.", "project": "A VergeML project is just a directory. Typically it contains a vergeml.yaml file, a trainings directory and a samples directory.", 'project file': "A YAML file you can use to configure models, device usage, data processing and taks options.", 'checkpoint': 'A checkpoint is a static image of a trained AI. It can be used to restore the AI after training and make predictions.', 'stats': 'Stats are used to measure the performance of a model (e.g. accuracy).', 'samples': 'Samples are pieces of data (e.g. images, texts) that is being used to train models to create AIs.', 'val split': "Samples different from training samples that are used to evaluate the performance of model hyperparameters. You can set it via the --val-split option. See 'ml help split'.", 'test split': "Samples different from training samples that are used to evaluate the final performance of the model. You can set it via the --test-split option. See 'ml help split'.", 'split': 'split is a part of the sample data reserved for validation and testing (--val-split and --test-split options). It can be configured as either a percentage value (e.g. --val-split=10%) to reserve a fraction of training samples, a number to reserve a fixed number of samples, or a directory where the samples of the split are stored.', 'cache dir': 'A directory which contains the processed data.', } SYNONYMS = { 'stochastic gradient descent': 'sgd', 'hyperparameter': 'hyperparameters', 'project dir': 'project', 'training samples': 'samples', 'overfit': 'overfitting', 'underfit': 'underfitting' } def long_descr(key): key = key.replace("-", " ") key = SYNONYMS.get(key, key) return LONG_DESCR.get(key, "").strip() def short_param_descr(key): key = key.replace("-", " ") key = SYNONYMS.get(key, key) return PARAM_DESCR.get(key, "").strip()
"""Problem 2 - Paying Debt Off in a Year Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. In this problem, we will not be dealing with a minimum monthly payment rate. The following variables contain values as described below: balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example: Lowest Payment: 180 Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below: Monthly interest rate = (Annual interest rate) / 12.0 Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment) Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) """ def estimateRemainingBalance(balance, annualInterestRate, monthlyPaymentRate): monthlyUnpaidBalance = balance interest = 0 for i in range(13): if i > 0: balance = monthlyUnpaidBalance + interest pass monthlyUnpaidBalance = balance - monthlyPaymentRate interest = annualInterestRate/12 * monthlyUnpaidBalance return round(balance, 2) def estimateLowestPayment(balance, annualInterestRate, monthlyPaymentRate): monthlyPayment = monthlyPaymentRate while estimateRemainingBalance(balance, annualInterestRate, monthlyPayment) > 0: monthlyPayment += 10 print('Lowest Payment: ', monthlyPayment) return monthlyPayment
""" 9.3 – Usuários: Crie uma classe chamada User. Crie dois atributos de nomes first_name e last_name e, então, crie vários outros atributos normalmente armazenados em um perfil de usuário. Escreva um método de nome describe_user() que apresente um resumo das informações do usuário. Escreva outro método chamado greet_user() que mostre uma saudação personalizada ao usuário. Crie várias instâncias que representem diferentes usuários e chame os dois métodos para cada usuário. """ class User: def __init__(self, first_name, last_name, age, email): self.first_name = first_name self.last_name = last_name self.age = age self.email = email def describe_user(self): print("\nInformações do Usuário:") print(f"Nome: {self.first_name}") print(f"Sobrenome: {self.last_name}") print(f"Idade: {self.age}") print(f"E-mail: {self.email}") def greet_user(self): print(f'Olá, {self.first_name}! Seja bem vindo(a)!') user1 = User('Thiago', 'Souza', 31, 'thiago@mail.com') user2 = User('Paulo', 'Silva', 36, 'paulo@mail.com') user3 = User('Maria', 'Silveira', 20, 'maria@mail.com') user4 = User('Jessica', 'Herminio', 28, 'jessica@mail.com') user5 = User('Kaleb', 'Guimarães', 16, 'kaleb@mail.com') user1.greet_user() user2.greet_user() user3.greet_user() user4.greet_user() user5.greet_user() user1.describe_user() user2.describe_user() user3.describe_user() user4.describe_user() user5.describe_user()
def username_generator(first,last): counter = 0 username = "" for i in first: if counter <= 2: counter += 1 username += i counter = 0 for j in last: if counter <= 3: counter += 1 username += j return username def password_generator(username="testin"): password = "" counter = 0 for i in username: password += username[counter -1] counter += 1 return password print(password_generator())
# -*- coding: utf-8 -*- class Controller(object): def __init__(self, router, view): self.router = router self.view = view def show(self): if self.view: self.view.show() else: raise Exception("None view") def hide(self): if self.view: self.view.hide() else: raise Exception("None view") def go(self, ctrl_name, hide_self=True): self.router.go(ctrl_name) if hide_self: self.hide()
def geometric_eq(p,k): return (1-p)**k*p class GeometricDist: def __init__(self,p): self.p = p self.mean = (1-p)/p self.var = (1-p)/p**2 def __getitem__(self,k): return geometric_eq(self.p,k)
class letterCombinations: def letterCombinationsFn(self, digits: str) -> List[str]: # If the input is empty, immediately return an empty answer array if len(digits) == 0: return [] # Map all the digits to their corresponding letters letters = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"} def backtrack(index, path): # If the path is the same length as digits, we have a complete combination if len(path) == len(digits): combinations.append("".join(path)) return # Backtrack # Get the letters that the current digit maps to, and loop through them possible_letters = letters[digits[index]] for letter in possible_letters: # Add the letter to our current path path.append(letter) # Move on to the next digit backtrack(index + 1, path) # Backtrack by removing the letter before moving onto the next path.pop() # Initiate backtracking with an empty path and starting index of 0 combinations = [] backtrack(0, []) return combinations
class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [[0]*n for i in range(m)] for i in range(m): dp[i][n-1] = 1 for i in range(n): dp[m-1][i] = 1 for i in range(m-2,-1,-1): for j in range(n-2,-1,-1): dp[i][j] = dp[i+1][j] + dp[i][j+1] return dp[0][0]
n,m = list(map(int,input().split(' '))) coins = list(map(int,input().split(' '))) dp =[ [-1 for x in range(m+1)] for y in range(n+1) ] def getCount(amount,index): if amount == 0: return 1 if index == 1: coin = coins[0] if amount%coin == 0: return 1 else: return 0 if dp[amount][index] != -1: return dp[amount][index] ans = 0 parts = int(amount/(coins[index-1])) for i in range(parts+1): got = int(getCount(amount - i*coins[index-1],index-1)) ans = ans+got dp[amount][index] = ans return ans print(getCount(n,m))
class TableNotFound: def title(self): return "Table Not Found" def description(self): return "You are trying to make a query on a table that cannot be found. Check that :table migration exists and that migrations have been ran with 'python craft migrate' command." def regex(self): return r"no such table: (?P<table>(\w+))" class MissingCSRFToken: def title(self): return "Missing CSRF Token" def description(self): return "You are trying to make a sensitive request without providing a CSRF token. Your request might be vulnerable to Cross Site Request Forgery. To resolve this issue you should use {{ csrf_field }} in HTML forms or add X-CSRF-TOKEN header in AJAX requests." def regex(self): return r"Missing CSRF Token" class InvalidCSRFToken: def title(self): return "The session does not match the CSRF token" def description(self): return "Try clearing your cookies for the localhost domain in your browsers developer tools." def regex(self): return r"Invalid CSRF Token" class TemplateNotFound: def title(self): return "Template Not Found" def description(self): return """':template.html' view file has not been found in registered view locations. Please verify the spelling of the template and that it exists in locations declared in Kernel file. You can check available view locations with app.make('view.locations').""" def regex(self): return r"Template '(?P<template>(\w+))' not found" class NoneResponse: def title(self): return "Response cannot be None" def description(self): return """Ensure that the controller method used in this request returned something. A controller method cannot return None or nothing. If you don't want to return a value you can return an empty string ''.""" def regex(self): return r"Responses cannot be of type: None." class RouteMiddlewareNotFound: def title(self): return "Did you register the middleware key in your Kernel.py file?" def description(self): return "Check your Kernel.py file inside your 'route_middleware' attribute and look for a :middleware key" def regex(self): return r"Could not find the \'(?P<middleware>(\w+))\' middleware key"
# Copyright (C) 2014-2015 LiuLang <gsushzhsosgsu@gmail.com> # Use of this source code is governed by GPLv3 license that can be found # in http://www.gnu.org/licenses/gpl-3.0.html ''' 网盘错误代码对应的提示信息 ''' o = { 0: '成功', -1: '用户名和密码验证失败', -2: '备用', -3: '用户未激活(调用init接口)', -4: 'COOKIE中未找到host_key&user_key(或BDUSS)', -5: 'host_key和user_key无效', -6: 'bduss无效', -7: '文件或目录名错误或无权访问', -8: '该目录下已存在此文件', -9: '文件被所有者删除,操作失败', -10: '你的空间不足了哟,赶紧<a target=\'_blank\' href=\'http://yun.baidu.com/buy/center?tag=2\'>购买空间</a>吧', -11: '父目录不存在', -12: '设备尚未注册', -13: '设备已经被绑定', -14: '帐号已经初始化', -21: '预置文件无法进行相关操作', -22: '被分享的文件无法重命名,移动等操作', -23: '数据库操作失败,请联系netdisk管理员', -24: '要取消的文件列表中含有不允许取消public的文件。', -25: '非公测用户', -26: '邀请码失效', 1: '服务器错误 ', 2: '该文件夹不可以移动', 3: '一次操作文件不可超过100个', 4: '新文件名错误', 5: '目标目录非法', 6: '备用', 7: 'NS非法或无权访问', 8: 'ID非法或无权访问', 9: '申请key失败', 10: '创建文件的superfile失败', 11: 'user_id(或user_name)非法或不存在', 12: '部分文件已存在于目标文件夹中', 13: '此目录无法共享', 14: '系统错误', 103: '提取码错误', 104: '验证cookie无效', 201: '系统错误', 202: '系统错误', 203: '系统错误', 204: '系统错误', 205: '系统错误', 301: '其他请求出错', 501: '获取的LIST格式非法', 618: '请求curl返回失败', 619: 'pcs返回错误码', 600: 'json解析出错', 601: 'exception抛出异常', 617: 'getFilelist其他错误', 211: '无权操作或被封禁', 404: '秒传md5不匹配 rapidupload 错误码', 406: '秒传创建文件失败 rapidupload 错误码', 407: 'fileModify接口返回错误,未返回requestid rapidupload 错误码', 31080: '我们的服务器出错了,稍候试试吧', 31021: '网络连接失败,请检查网络或稍候再试', 31075: '一次支持操作999个,减点试试吧', 31116: '你的空间不足了哟,赶紧<a href=\'http://yun.baidu.com/buy/center?tag=2\'>购买空间</a>吧', 112: '页面已过期,请<a href=\'javascript:window.location.reload();\'>刷新</a>后重试', 111: '当前还有任务未完成,请等待当前任务结束后再进行操作', -32: '你的空间不足了哟,赶紧<a target=\'_blank\' href=\'http://yun.baidu.com/buy/center?tag=2\'>购买空间</a>吧' } t = { 0: '成功', -1: '由于您分享了违反相关法律法规的文件,分享功能已被禁用,之前分享出去的文件不受影响。', -2: '用户不存在,请刷新页面后重试', -3: '文件不存在,请刷新页面后重试', -4: '登录信息有误,请重新登录试试', -5: 'host_key和user_key无效', -6: '请重新登录', -7: '该分享已删除或已取消', -8: '该分享已经过期', -9: '访问密码错误', -10: '分享外链已经达到最大上限100000条,不能再次分享', -11: '验证cookie无效', -14: '对不起,短信分享每天限制20条,你今天已经分享完,请明天再来分享吧!', -15: '对不起,邮件分享每天限制20封,你今天已经分享完,请明天再来分享吧!', -16: '对不起,该文件已经限制分享!', -17: '文件分享超过限制', -30: '文件已存在', -31: '文件保存失败', -33: '一次支持操作999个,减点试试吧', -32: '你的空间不足了哟,赶紧购买空间吧', -70: '你分享的文件中包含病毒或疑似病毒,为了你和他人的数据安全,换个文件分享吧', 2: '参数错误', 3: '未登录或帐号无效', 4: '存储好像出问题了,请稍候再试', 108: '文件名有敏感词,优化一下吧', 110: '分享次数超出限制,可以到“我的分享”中查看已分享的文件链接', 114: '当前任务不存在,保存失败', 115: '该文件禁止分享', 112: '页面已过期,请<a href=\'javascript:window.location.reload();\'>刷新</a>后重试' } i = { 36000: '网络繁忙,请稍候再试', 36001: '参数错误', 36002: 'appid错误', 36003: '请刷新再试', 36004: '请重新登录', 36005: '用户未登录', 36006: '用户未激活', 36007: '用户未授权', 36008: '用户不存在', 36009: '用户空间不足', 36010: '文件不存在', 36012: '操作超时,请重试', 36013: '同时下载的任务过多,不能下载', 36014: '存储路径已使用', 36016: '任务已删除', 36017: '任务已完成', 36018: '解析失败,种子文件损坏', 36019: '任务正在处理中', 36020: '任务地址不存在', 36021: '普通用户最多同时下载1个任务哦!马上开通离线下载套餐,立即下载更多!', 36022: '同时下载的任务过多,不能下载', 36023: '普通用户每月只能离线下载5个任务哦!马上开通离线下载套餐,立即下载更多!', 36024: '本月下载数已超限制', 36025: '分享链接已失效', 36026: '链接格式有误', 36027: '链接格式有误', 36028: '暂时无法找到相关种子信息', 36031: '网络繁忙,请稍候再试', 36032: '离线文件因含有违规内容被系统屏蔽无法下载', -19: '请输入验证码' }
c.NotebookApp.ip = '*' c.NotebookApp.token = '' c.NotebookApp.password = '' c.NotebookApp.open_browser = False c.NotebookApp.port = 8081 c.NotebookApp.allow_remote_access = True c.NotebookApp.allow_origin_pat = '(^https://8081-dot-[0-9]+-dot-devshell\.appspot\.com$)|(^https://colab\.research\.google\.com$)'
prova1 = float ( input()) prova2 = float ( input ()) prova3 = float (input ()) media = (((prova1 * 2.0) + (prova2 * 3.0) + (prova3 * 5.0)) / 10 ) print("MEDIA = %0.1F" % media )
""" Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00. Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações: A - comprar apenas latas de 18 litros; B - comprar apenas galões de 3,6 litros; C - misturar latas e galões, de forma que o desperdício de tinta seja menor. Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, considere latas cheias. """ # -*- coding: utf-8 -*- tamanho = float(input("Informe a área a ser pintada: ")) litros = tamanho / 6 # Comprando somente em latas de 18 litros latas_18
# https://www.codechef.com/problems/DEVUGRAP for T in range(int(input())): N,K=map(int,input().split()) n,ans=list(map(int,input().split())),0 for i in range(N): if(n[i]>=K): ans+=min(n[i]%K,K-n[i]%K) else: ans+=K-n[i]%K print(ans)
class Pattern(object): """ [summary] """ @staticmethod def default() -> str: """[summary] Returns: pattern (str): [{level}][{datetime}] - {transaction} - {project_name}.{class_name}.{function_name} - _message: traceback """ _message = "{message}" _title_pattern: str = "[{level}][{datetime}] - {transaction} - " _name_pattern: str = "{project_name}.{class_name}.{function_name} - " _loggger_pattern = f"{_title_pattern}{_name_pattern}{_message}" pattern = _loggger_pattern return pattern
_first_index_in_every_row_list = list() def _build_first_index_in_every_row_list(): global _first_index_in_every_row_list _first_index_in_every_row_list.clear() _first_index_in_every_row_list.append(0) for delta in range(199, 1, -1): _first_index_in_every_row_list.append(_first_index_in_every_row_list[-1] + delta) _build_first_index_in_every_row_list() def parse_index(index, step=1): if not isinstance(index, int): index = int(index) date_seq_no = (index // 19900) * step correlation_no = index % 19900 # Use binary search to get fund number: # FIXME: Consider to compute fund number directly. low = correlation_no // 199 # include high = min(low * 2 + 1, len(_first_index_in_every_row_list)) # exclude while low < high: middle = (low + high) // 2 if _first_index_in_every_row_list[middle] < correlation_no: low = middle + 1 elif _first_index_in_every_row_list[middle] > correlation_no: high = middle else: low = middle break if _first_index_in_every_row_list[low] > correlation_no: low -= 1 fund1_no = low fund2_no = correlation_no - _first_index_in_every_row_list[fund1_no] + fund1_no + 1 return date_seq_no, fund1_no, fund2_no, correlation_no def calculate_correlation_no(fund1_no, fund2_no): if fund1_no == fund2_no: return None if fund1_no > fund2_no: tmp = fund1_no fund1_no = fund2_no fund2_no = tmp if fund1_no < 0: raise ValueError('fund1_no should >= 0, got %d.' % fund1_no) if fund2_no >= 200: raise ValueError('fund2_no should < 200, got %d.' % fund2_no) ''' input: f1 in [0, 198] f2 in [f1 + 1, 199] output: c = (199 + 198 + ... + (199 - f1 + 1)) + (f2 - (f1 + 1)) |----------- f1 terms -----------| = (199 + (199 - f1 + 1)) * f1 / 2 + (f2 - f1 - 1) = (399 - f1) * f1 / 2 + f2 - f1 - 1 ''' correlation_no = int(((399 - fund1_no) * fund1_no) // 2) + fund2_no - fund1_no - 1 return correlation_no def parse_square_ex_index(index, step=1): if not isinstance(index, int): index = int(index) date_seq_no = (index // 40000) * step index_rem = index % 40000 fund1_no = index_rem // 200 fund2_no = index_rem % 200 correlation_no = calculate_correlation_no(fund1_no, fund2_no) return date_seq_no, fund1_no, fund2_no, correlation_no
# Function for finding if it possible # to obtain sorted array or not def fun(arr, n, k): v = [] # Iterate over all elements until K for i in range(k): # Store elements as multiples of K for j in range(i, n, k): v.append(arr[j]); # Sort the elements v.sort(); x = 0 # Put elements in their required position for j in range(i, n, k): arr[j] = v[x]; x += 1 v = [] # Check if the array becomes sorted or not for i in range(n - 1): if (arr[i] > arr[i + 1]): return False return True # Driver code nk= input().split() K = int(nk[1]) n = int(nk[0]) arr= list(map(int,input().split())) if (fun(arr, n, K)): print("True") else: print("False")
# _*_ coding: utf-8 _*_ # 整数 age = 100_000 print('age:', age) # 浮点数 salary = 1000.02 print('salary:', salary) salary = 1.00002e3 print('salary:', salary) # 字符串 print("It's OK") print('It\'s OK') # 通过r表名引号中的所有字段都直接输出 print(r'It\\\'s OK') # 通过三个引号,可以输入多行字符串 print('''line1 line2 line3 ''') # 布尔值 is_good = True is_happy = True # 用and or not运算 print(is_good and is_happy) print(is_good or is_happy) print(not is_good) # 空值 address = None print('Address:', address) # 除法,计算结果是浮点数,即使是两个整数恰好整除 print('除法:', 10 / 3) print('除法:', 9 / 3) # 地板除 使用 // print('地板除法:', 10 // 3) print('地板除法:', 9 // 3) # 求余数 % print('求余数 10 % 3 =', 10 % 3) print('求余数 9 % 3 =', 9 % 3)
# -*- coding: utf-8 -*- """ Created on Tue Feb 19 20:59:13 2019 @author: sudar """ class url_feeder(object): def __init__(self, section): """initialize the feeder""" self.section = section def feeder(self): """We going to get the URL through each section over-view company information analysis company management financial Set a Flag to check what section is the user input The flag will check and trigger the specific section Pseudocode Set flag if the flag equal section company overview Then Scrape the data if not then keep going if the flag equal section analysis ......... """ ############################################################## """ Build the URL for specific company section """ try: flag = self.section base_url = 'https://www.reuters.com' base_url1 = 'https://csimarket.com' path_1 = '/finance' path_2 = '/stocks/' section_list = ['overview', 'company-officers', 'financial-highlights', 'analyst', 'industry', 'segment'] company_list = ['/MSFT.OQ', '/MET.N', '/MS.N', '/FNMA.PK', '/GM', '/PROC.NS', '/APO.N', '/BA.N', '/BRKa.N'] company_list1 = ['MSFT', 'MET','MS', 'FNMA', 'GM', 'PG', 'APO', 'BA', 'BRKA'] url_list = [] if self.section.lower: for company in company_list: if flag == section_list[0]: url = base_url + path_1 + path_2 + flag + company url_list.append(url) elif flag == section_list[1]: url = base_url + path_1 + path_2 + flag + company url_list.append(url) elif flag == section_list[2]: url = base_url + path_1 + path_2 + flag + company url_list.append(url) elif flag == section_list[3]: url = base_url + path_1 + path_2 + flag + company url_list.append(url) for company in company_list1: if flag == section_list[4]: url = base_url1 + '/stocks/competition.php?code=' + company url_list.append(url) elif flag == section_list[5]: url = base_url1 + '/stocks/segments.php?code=' + company url_list.append(url) return url_list except: return ("error") #############Uncomment to test#################### #test = url_feeder("company-officers") #print(test.feeder())
# day_3/classes.py """ Classes are a way to encapsulate code. It is a way of keeping functions and data that represent something together and is a core concept to understand for object oreinted programing. """ class Person: def __init__(self, name: str, age: int) -> None: """ Initializes the person class requires a name and an age. """ self.name = name self.age = age self.friends = [] def introduce(self) -> str: """ Introduces the person. """ return f'Hello my name is {self.name} and I am {self.age} years old.' def get_older(self, years: int) -> None: """ Ages the person by an amount of years """ self.age += years def add_friend(self, person) -> None: """ Adds another person to this persons friend list """ self.friends.append(person) return self def list_friends(self) -> str: """ Returns a string containg the names of this persons friends """ friends = '' for friend in self.friends: friends += friend.name + ' ' return self.name + "'s friends list is " + friends def __str__(self) -> str: return f'Person {self.name}, age {self.age}' """ By using classes you can inherit from another class and receive their methods or overide them with something else. """ class Student (Person): def __init__(self, name, age, grade): """ Initializes a student. """ super().__init__(name, age) self.grade = grade def introduce(self) -> str: """ Introduces a student. """ return f"I'm a student my name is {self.name}. I'm in grade \ {self.grade}, and I'm {self.age} years old" def __str__(self) -> str: return f'Student {self.name}, grade {self.grade}' """ Object oreiented programming is useful and many if not all jobs for coders will require you to be familiar with how it works but its also important to note that you can do much the same thing without it. For most of your personal projects you can decide to use object oriented or functional paradigms or a mix of both whatever you want. """ def create_person(name, age) -> dict: """ Creates a dictionary representation of a person """ return {'name': name, 'age': age, 'friends': []} def introduce(person) -> str: """ Introduces a dictionary representation of a person """ return f'Hello my name is {person["name"]} and I am {person["age"]} years old.' def get_older(person, years) -> None: """ Increments the age of a person """ person['age'] += years def string_rep(person) -> str: """ Represents the dictionary representation of a preson as a string """ return f'Person {person["name"]}, age {person["age"]}' def add_friend(person, person2) -> None: """ Adds a person to this functional persons friends list """ person['friends'].append(person2) return person def list_friends(person) -> str: """ Returns a string containg the names of this functional persons friends """ friends = '' for friend in person['friends']: friends += friend['name'] + ' ' return person['name'] + "'s friends list is " + friends def create_student(name, age, grade) -> dict: """ Creates a dictionary representation of a student. """ student = create_person(name, age) student['grade'] = grade return student def introduce_student(student) -> str: """ Introduces a functional student. """ return f"I'm a student my name is {student['name']}. I'm in grade \ {student['grade']}, and I'm {student['age']} years old" if __name__ == '__main__': print('Doing some things in an object oriented way') person1 = Person('John', 20) print(person1.introduce()) person1.get_older(6) print(person1.introduce()) student1 = Student('Baki', 18, 12) print(student1.introduce()) student1.get_older(3) # Still can get older even if the method isn't eplicately defined because it subclasses person print(student1.introduce()) student1.add_friend(person1) print(student1.list_friends()) print('') print('*' * 80) print('') print('Doing the same thing functionaly.') person2 = create_person('John', 20) print(introduce(person2)) get_older(person2, 6) print(introduce(person2)) student2 = create_student('Baki', 18, 12) print(introduce_student(student2)) get_older(student2,3) print(introduce_student(student2)) add_friend(student2, person2) print(list_friends(student2))
#coding = 'utf-8' # 打开文件,读取文件生成一维数组 with open('report.txt') as f: lines = f.readlines() # lines # 生成包含各科成绩的二维数组 scores = [] for line in lines: data = line.split() scores.append(data) # scores # 计算每位学生的总分和平均分 scores[0].extend(['总分','平均分']) stu_avg = 0 for grade in scores[1:]: stu_sum = 0 for s in grade[1:]: s = int(s) stu_sum += s stu_avg = round(stu_sum/len(grade[1:]), 1) grade.extend([str(stu_sum), str(stu_avg)]) # print(scores) result = sorted(scores, key = lambda x: x[-2], reverse = True) # print(result) # print(len(result)) # print(len(result[0])) # print(len(result[1])) # 添加各科平均分 num1 = len(result) # 二维数组行数 num2 = len(result[1]) # 二维数组列数 sub_avg = [] # 学科平均分一维数组 for j in range(1, num2): if j < num2 -1: sub_sum = 0 # 每个学科的总分 for k in range(1, num1): sub_sum += int(result[k][j]) sub_avg.append(str(round(sub_sum/(num1-1), 1))) else: sub_sum = 0 # 每个学科的总分 for k in range(1, num1): sub_sum += float(result[k][j]) sub_avg.append(str(round(sub_sum/(num1-1), 1))) # print(sub_avg) # print(result) sub_avg.insert(0,'平均') # print(sub_avg) result.insert(1, sub_avg) # print(result) # 替换不及格的成绩 for m in range(2,len(result)): for n in range(1,len(result[1])-2): if float(result[m][n]) < 60: result[m][n] = '不及格' # print(result[m][n]) #添加名次 result[0].insert(0, '名次') r = 0 for round in result[1:]: round.insert(0, r) r += 1 print(result) # 输出结果到result.txt with open('result.txt', 'w') as f: for result_lines in result: for result_line in result_lines: f.write(str(result_line) + ' ') f.write('\n')
class Pessoa: menbros_superiores = 2 menbro_inferiores=2 def __init__(self,*familia,name=None,idade=17): self.name= name self.familia= list(familia) self.idade= idade def comprimentar(self): return 'hello my code' def despedisir(self): return 'diz tchau ;3' def contar_1(self): return list(range(10,1,-1)) @staticmethod def estatico (): return 50 @classmethod def atributodeclasse(cls): return f'{cls} - membros superiores {cls.menbros_superiores},membros inferiores {cls.menbro_inferiores}' if __name__ == '__main__': djony = Pessoa(name='djony', idade=17) mother = Pessoa(djony,name='mother',idade=46) type (djony) print(djony.comprimentar()) print(djony.contar_1()) print(djony.name) print(mother.name) for familia in mother.familia: print(familia.name,familia.idade) print(djony.__dict__) print(Pessoa.estatico()) print(Pessoa.atributodeclasse())
print('{:=^40}'.format(' LOJAO DO PYTHON ')) n = float(input('Preço das compras: R$')) print('''FORMAS DE PAGAMENTO 1. Á vista dinheiro/cheque 2. Á vista cartão 3. 2x no cartão 4. 3x ou mais no cartão''') m = int(input('Qual é a modo de pagamento? ')) if m ==1: total = n - (n * 10 / 100) elif m == 2: total = n - (n * 5 / 100) elif m == 3: total = n parcela = total / 2 print('Sua compra sera parcelada em 2x de R${:.2f}'.format(parcela)) elif m == 4: total = n + (n * 20 / 100) p1 = int(input('quantas parcelas? ')) parcela = total / p1 print('Sua compra sera parcelada em {}x de R${:.2f}'.format(p1, parcela)) print('Sua compra de R${:.2f} vai custar R${:.2f}'.format(n, total))
# Given a non-negative number represented as an array of digits, # plus one to the number. # The digits are stored such that the most significant # digit is at the head of the list. def plusOne(digits): """ :type digits: List[int] :rtype: List[int] """ digits[-1] = digits[-1] + 1 res = [] ten = 0 i = len(digits)-1 while i >= 0 or ten == 1: sum = 0 if i >= 0: sum += digits[i] if ten: sum += 1 res.append(sum % 10) ten = sum / 10 i -= 1 return res[::-1] def plus_one(digits): n = len(digits) for i in range(n-1, -1, -1): if digits[i] < 9: digits[i] += 1 return digits digits[i] = 0 new_num = [0] * (n+1) new_num[0] = 1 return new_num
# coding: utf-8 def is_bool(var): return isinstance(var, bool) if __name__ == '__main__': a = False b = 0 print(is_bool(a)) print(is_bool(b))
class GameStats(): """跟踪游戏的统计信息""" def __init__(self,ai_settings): """初始化统计信息""" self.ai_settings=ai_settings self.reset_states() #游戏刚启动时处于活动状态 self.game_active=False #在任何情况下都不应该重置最高分得分 self.high_score=0 def reset_states(self): """初始化在游戏运行期间可能变化的统计信息""" self.ships_left = self.ai_settings.ship_limit self.score=0 self.level=1
alpha = { 'en-US': '^[A-Z]+$', 'az-AZ': '^[A-VXYZÇƏĞİıÖŞÜ]+$', 'bg-BG': '^[А-Я]+$', 'cs-CZ': '^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$', 'da-DK': '^[A-ZÆØÅ]+$', 'de-DE': '^[A-ZÄÖÜß]+$', 'el-GR': '^[Α-ώ]+$', 'es-ES': '^[A-ZÁÉÍÑÓÚÜ]+$', 'fa-IR': '^[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی]+$', 'fi-FI': '^[A-ZÅÄÖ]+$', 'fr-FR': '^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$', 'it-IT': '^[A-ZÀÉÈÌÎÓÒÙ]+$', 'nb-NO': '^[A-ZÆØÅ]+$', 'nl-NL': '^[A-ZÁÉËÏÓÖÜÚ]+$', 'nn-NO': '^[A-ZÆØÅ]+$', 'hu-HU': '^[A-ZÁÉÍÓÖŐÚÜŰ]+$', 'pl-PL': '^[A-ZĄĆĘŚŁŃÓŻŹ]+$', 'pt-PT': '^[A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$', 'ru-RU': '^[А-ЯЁ]+$', 'sl-SI': '^[A-ZČĆĐŠŽ]+$', 'sk-SK': '^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$', 'sr-RS@latin': '^[A-ZČĆŽŠĐ]+$', 'sr-RS': '^[А-ЯЂЈЉЊЋЏ]+$', 'sv-SE': '^[A-ZÅÄÖ]+$', 'th-TH': r'^[ก-๐\s]+$', 'tr-TR': '^[A-ZÇĞİıÖŞÜ]+$', 'uk-UA': '^[А-ЩЬЮЯЄIЇҐі]+$', 'vi-VN': '^[A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$', 'ku-IQ': '^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$', 'ar': '^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+', 'he': '^[א-ת]+', 'fa': r'^[\'آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی\']+$', 'hi-IN': r'^[\u0900-\u0961]+[\u0972-\u097F]*$', } alphanumeric = { 'en-US': '^[0-9A-Z]+$', 'az-AZ': '^[0-9A-VXYZÇƏĞİıÖŞÜ]+$', 'bg-BG': '^[0-9А-Я]+$', 'cs-CZ': '^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$', 'da-DK': '^[0-9A-ZÆØÅ]+$', 'de-DE': '^[0-9A-ZÄÖÜß]+$', 'el-GR': '^[0-9Α-ω]+$', 'es-ES': '^[0-9A-ZÁÉÍÑÓÚÜ]+$', 'fr-FR': '^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$', 'fi-FI': '^[0-9A-ZÅÄÖ]+$', 'it-IT': '^[0-9A-ZÀÉÈÌÎÓÒÙ]+$', 'hu-HU': '^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$', 'nb-NO': '^[0-9A-ZÆØÅ]+$', 'nl-NL': '^[0-9A-ZÁÉËÏÓÖÜÚ]+$', 'nn-NO': '^[0-9A-ZÆØÅ]+$', 'pl-PL': '^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$', 'pt-PT': '^[0-9A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$', 'ru-RU': '^[0-9А-ЯЁ]+$', 'sl-SI': '^[0-9A-ZČĆĐŠŽ]+$', 'sk-SK': '^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$', 'sr-RS@latin': '^[0-9A-ZČĆŽŠĐ]+$', 'sr-RS': '^[0-9А-ЯЂЈЉЊЋЏ]+$', 'sv-SE': '^[0-9A-ZÅÄÖ]+$', 'th-TH': r'^[ก-๙\s]+$', 'tr-TR': '^[0-9A-ZÇĞİıÖŞÜ]+$', 'uk-UA': '^[0-9А-ЩЬЮЯЄIЇҐі]+$', 'ku-IQ': '^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$', 'vi-VN': '^[0-9A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$', 'ar': '^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+', 'he': '^[0-9א-ת]+', 'fa': r'^[\'0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰\']+$', 'hi-IN': r'^[\u0900-\u0963]+[\u0966-\u097F]*$', } decimal = { 'en-US': '.', 'ar': '٫', } english_locales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM'] for i, locale in enumerate(english_locales): locale = "en-{}".format(english_locales[i]) alpha[locale] = alpha['en-US'] alphanumeric[locale] = alphanumeric['en-US'] decimal[locale] = decimal['en-US'] arabic_locales = [ 'AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE', ] for j, locale in enumerate(arabic_locales): locale = "ar-{}".format(arabic_locales[j]) alpha[locale] = alpha['en-US'] alphanumeric[locale] = alphanumeric['en-US'] decimal[locale] = decimal['en-US'] farsi_locales = [ 'IR', 'AF', ] for k, locale in enumerate(farsi_locales): locale = "fa-{}".format(farsi_locales[k]) alpha[locale] = alpha['en-US'] alphanumeric[locale] = alphanumeric['en-US'] decimal[locale] = decimal['en-US'] dot_decimal = ['ar-EG', 'ar-LB', 'ar-LY'] for n, _ in enumerate(farsi_locales): decimal[dot_decimal[n]] = decimal['en-US'] comma_decimal = [ 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'es-ES', 'fr-CA', 'fr-FR', 'fi-FI', 'id-ID', 'it-IT', 'ku-IQ', 'hi-IN', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN', ] for m, _ in enumerate(comma_decimal): decimal[comma_decimal[m]] = decimal['en-US'] alpha['fr-CA'] = alpha['fr-FR'] alphanumeric['fr-CA'] = alphanumeric['fr-FR'] alpha['pt-BR'] = alpha['pt-PT'] alphanumeric['pt-BR'] = alphanumeric['pt-PT'] decimal['pt-BR'] = decimal['pt-PT'] alpha['pl-Pl'] = alpha['pl-PL'] alphanumeric['pl-Pl'] = alphanumeric['pl-PL'] decimal['pl-Pl'] = decimal['pl-PL'] alpha['fa-AF'] = alpha['fa']
""" 面试题 32(二):分行从上到下打印二叉树 题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层 打印到一行。 """ class BinaryTreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def connect_binarytree_nodes(parent: BinaryTreeNode, left: BinaryTreeNode, right: BinaryTreeNode) -> BinaryTreeNode: if parent: parent.left = left parent.right = right return parent def print_binary_tree(tree: BinaryTreeNode) -> list: """ Print tree from top to bottom by level. Parameters ----------- binary_tree: BinaryTreeNode Returns --------- out: list Tree items list. Notes ------ """ if not tree: return [] queue1, queue2 = [tree], [] q1res, q2res = [], [] res = [] while True: while len(queue1): node = queue1.pop(0) q1res.append(node.val) if node.left: queue2.append(node.left) if node.right: queue2.append(node.right) if q2res: res.append(q2res) q2res = [] while len(queue2): node = queue2.pop(0) q2res.append(node.val) if node.left: queue1.append(node.left) if node.right: queue1.append(node.right) if q1res: res.append(q1res) q1res = [] if not queue1 and not queue2: break return res def print_binary_tree2(tree: BinaryTreeNode) -> list: if not tree: return [] queue1, queue2 = [tree], [] res = [] while queue1 or queue2: tmp = [] while queue1: # for i in range(len(queue1)) node = queue1.pop(0) tmp.append(node.val) if node.left: queue2.append(node.left) if node.right: queue2.append(node.right) if tmp: res.append(tmp) tmp = [] while queue2: #for i in range(len(queue2)): node = queue2.pop(0) tmp.append(node.val) if node.left: queue1.append(node.left) if node.right: queue1.append(node.right) if tmp: res.append(tmp) return res def print_binary_tree3(tree: BinaryTreeNode) -> list: if not tree: return [] queue, res = [tree], [] while queue: tmp = [] for i in range(len(queue)): node = queue.pop(0) tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) if tmp: res.append(tmp) return res def print_binary_tree4(tree: BinaryTreeNode) -> list: if not tree: return [] queue, res, tmp = [tree], [], [] next_level, tobe_print = 0, 1 while queue: node = queue.pop(0) tmp.append(node.val) if node.left: queue.append(node.left) next_level += 1 if node.right: queue.append(node.right) next_level += 1 tobe_print -= 1 if tobe_print == 0: tobe_print = next_level next_level = 0 res.append(tmp) tmp = [] return res if __name__ == '__main__': tree = BinaryTreeNode(8) connect_binarytree_nodes(tree, BinaryTreeNode(6), BinaryTreeNode(6)) connect_binarytree_nodes(tree.left, BinaryTreeNode(5), BinaryTreeNode(7)) connect_binarytree_nodes(tree.right, BinaryTreeNode(7), None) res = print_binary_tree4(tree) print(res)
class Conta: def __init__(self, numero, nome, saldo=0): self._numero = numero self._nome = nome self._saldo = saldo def atualiza(self, taxa): self._saldo += self._saldo * taxa def deposita(self, valor): self._saldo += valor - 0.10 class ContaCorrente(Conta): def atualiza(self, taxa): self._saldo += self._saldo * taxa * 2 class ContaPoupanca(Conta): def atualiza(self, taxa): self._saldo += self._saldo * taxa * 3 if __name__ == "__main__": c = Conta('123-4', 'joao', 1000) cc = ContaCorrente('123-5', 'pedro', 1000) cp = ContaPoupanca('123-6', 'Maria', 1000) c.atualiza(0.01) cc.atualiza(0.01) cp.atualiza(0.01) print(c._saldo, cc._saldo, cp._saldo)
# -*- coding: utf-8 -*- # Coded by Sungwook Kim # 2020-12-13 # IDE: Jupyter Notebook def Fact(a): res = 1 for i in range(a): res = res * (i + 1) return res T = int(input()) for i in range(T): r, n = map(int, input().split()) a = Fact(n) b = Fact(r) c = Fact(n-r) print(int(a / (c * b)))
# The base class for application-specific states. class SarifState(object): def __init__(self): self.parser = None self.ppass = 1 # Taking the easy way out. # We need something in case a descendent wants to trigger # on change to ppass. def set_ppass(self, ppass): self.ppass = ppass def get_ppass(self): return self.ppass def set_parser(self, parser): self.parser = parser def get_parser(self): return self.parser # These functions are named for the handler they reside in # plus the function in that handler. # Only functions that called the state are here. def original_uri_base_id_add(self, uri, uriBaseId, key): raise NotImplementedError("original_uri_base_id_add") def resources_object_member_end(self, parser, key): raise NotImplementedError("resources_object_member_end") def rules_v1_object_member_end(self, parser, key): raise NotImplementedError("rules_v1_object_member_end") def rules_item_array_element_end(self, parser, idx): raise NotImplementedError("rules_item_array_element_end") def run_object_member_end(self, tool_name): raise NotImplementedError("run_object_member_end") def run_object_start(self, parser): raise NotImplementedError("run_object_start") def results_item_array_element_end(self, parser, idx): raise NotImplementedError("results_item_array_element_end") def file_item_add(self, file_item): raise NotImplementedError("file_item_add")
# store the input from the user into age age = input("How old are you? ") # store the input from the user into height height = input(f"You're {age}? Nice. How tall are you? ") # store the input from the user into weight weight = input("How much do you weigh? ") # print the f-string with the age, height and weight print(f"So you're {age} old. {height} tall and {weight} heavy.")
def loss_layer(self, predicts, labels, scope='loss_layer'): with tf.variable_scope(scope): predict_classes = tf.reshape(predicts[:, :self.boundary1], [self.batch_size, self.cell_size, self.cell_size, self.num_class]) predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2], [self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell]) predict_boxes = tf.reshape(predicts[:, self.boundary2:], [self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell, 4]) response = tf.reshape(labels[:, :, :, 0], [self.batch_size, self.cell_size, self.cell_size, 1]) boxes = tf.reshape(labels[:, :, :, 1:5], [self.batch_size, self.cell_size, self.cell_size, 1, 4]) boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]) / self.image_size classes = labels[:, :, :, 5:] offset = tf.constant(self.offset, dtype=tf.float32) offset = tf.reshape(offset, [1, self.cell_size, self.cell_size, self.boxes_per_cell]) offset = tf.tile(offset, [self.batch_size, 1, 1, 1]) predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] + offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] + tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.square(predict_boxes[:, :, :, :, 2]), tf.square(predict_boxes[:, :, :, :, 3])]) predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3, 4, 0]) iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes) # calculate I tensor [BATCH_SIZE, CELL_SIZE, CELL_SIZE, BOXES_PER_CELL] object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True) object_mask = tf.cast((iou_predict_truth >= object_mask), tf.float32) * response # calculate no_I tensor [CELL_SIZE, CELL_SIZE, BOXES_PER_CELL] noobject_mask = tf.ones_like(object_mask, dtype=tf.float32) - object_mask boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size - offset, boxes[:, :, :, :, 1] * self.cell_size - tf.transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :, 2]), tf.sqrt(boxes[:, :, :, :, 3])]) boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0]) # class_loss class_delta = response * (predict_classes - classes) class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta), axis=[1, 2, 3]), name='class_loss') * self.class_scale # object_loss object_delta = object_mask * (predict_scales - iou_predict_truth) object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(object_delta), axis=[1, 2, 3]), name='object_loss') * self.object_scale # noobject_loss noobject_delta = noobject_mask * predict_scales noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(noobject_delta), axis=[1, 2, 3]), name='noobject_loss') * self.noobject_scale # coord_loss coord_mask = tf.expand_dims(object_mask, 4) boxes_delta = coord_mask * (predict_boxes - boxes_tran) coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale tf.losses.add_loss(class_loss) tf.losses.add_loss(object_loss) tf.losses.add_loss(noobject_loss) tf.losses.add_loss(coord_loss)
# -*-- coding: utf-8 -* def discretize(self, Npoint=-1): """Returns the discretize version of the SurfRing Parameters ---------- self: SurfRing A SurfRing object Npoint : int Number of point on each line (Default value = -1 => use the line default discretization) Returns ------- point_list : list List of complex coordinates """ # check if the SurfRing is correct self.check() # getting lines that delimit the SurfLine point_list = self.out_surf.discretize(Npoint=Npoint) point_list.extend(self.in_surf.discretize(Npoint=Npoint)) return point_list
# AKSHITH K # BUBBLE SORT IMPLEMENTED IN PYTHON RECURSIVELY. def bubblesort(arr, n): # checking if the array does not need to be sorted and has a length of 1. if n <= 1: return # creating a for-loop to iterate for the elements in the array. for i in range(0, n - 1): # creating an if-statement to check for the element not being in the right position. if arr[i] > arr[i + 1]: # code to perform the swapping method. arr[i], arr[i + 1] = arr[i + 1], arr[i] # recursively calling the function for the sorting. return bubblesort(arr, n - 1) # DRIVER CODE FOR TESTING THE ALGORITHM. arr = [4, 9, 1, 3, 0, 2, 6, 8, 5, 7] n = len(arr) bubblesort(arr, n) print(arr)
__author__ = 'Claudio' """Demonstrate how to use Python’s list comprehension syntax to produce the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]. """ def demonstration_list_comprehension(): return [idx*x for idx, x in enumerate(range(1,11))]
## Problem 10.2 # write a program to read through the mbox-short.txt # and figure out the distribution by hour of the day for each of the messages. file_name = input("Enter file:") file_handle = open(file_name) hour_list = list() for line in file_handle: # pull the hour out from the 'From ' line # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 if line.startswith("From"): line_list = line.split() if len(line_list) > 2: # find the time and then split the string a second time hour = line_list[5][:2] hour_list.append(hour) # accumulate the counts for each hour hour_dict = dict() for key in hour_list: hour_dict[key] = hour_dict.get(key, 0) + 1 # sort by hour srt_list = sorted(hour_dict.items()) # print out the counts, sorted by hour for (k,v) in srt_list: print (k,v)
#!/usr/bin/env python3 def f(*cs): ''' args : cotes, ou liste de cotes output : probabilités, fraction de marge ''' if len(cs)==1: cs=cs[0] ks=[1/c for c in cs] t=sum(ks) return [k/t for k in ks], 1-1/t def g(m1,m2,c2): return 100*(-m1+(1-m2)*(1-1/c2)) def h(m1,m2): # retourne le c2 minimal. return 1/(1 - m1/(1-m2)) #c2 > 1/(1 - m1/(1-m2)) #print(f(16,1.01)) #print(h(0.05,0.05)) _, m1 = f(24,11.5,1.13) print(h(m1,0.05)) print(g(m1,0.05,1.6))
#nome = input('digite seu nome: ') #if nome == 'artur': # print('que nome bonito {}'.format(nome)) #elif nome in 'carol andre carlos': # print('nome legal') #else: # print('nome coco') valor=int(input('qual o valor da casa? ')) salario=int(input('digite o valor do seu salario: ')) prazo=int(input('em quanto tempo pretende pagar o financiamento? ')) meses = (prazo*12) if valor / meses <= salario*0.3: print('seu credito foi aprovado') elif valor/meses >= salario * 0.3: print('credito não aprovado')
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # Copyright (C) 2010 Serge Tarkovski <serge.tarkovski@gmail.com> # Copyright (C) 2010 Rich Newpol (IE override) <rich.newpol@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This IE-specific override is required because IE doesn't allow # empty element to generate events. Therefore, when the mouse moves # (or clicks) happen over *only* the GlassWidget (which is empty) # they stop flowing. however, IE does provide setCapture/releaseCapture # methods on elements which can be used to same effect as a regular # GlassWidget. # This file implements the IE version of GlassWidget simply by mapping # the GlassWidget API to the use of setCapture/releaseCapture # we re-use the global 'mousecapturer' to prevent GlassWidget.hide() # from releasing someone else's capture def show(mousetarget, **kwargs): global mousecapturer # get the element that wants events target_element = mousetarget.getElement() # insure element can capture events if hasattr(target_element,"setCapture"): # remember it mousecapturer = target_element # start capturing DOM.setCapture(target_element) def hide(): global mousecapturer if hasattr(mousecapturer,"releaseCapture"): DOM.releaseCapture(mousecapturer) mousecapturer = None
# WAP to show the use of if..elif..else season= input("Enter season : ") print(season) if season == 'spring': print('plant the garden!') elif season == 'summer': print('water the garden!') elif season == 'fall': print('harvest the garden!') elif season == 'winter': print('stay indoors!') else: print('unrecognized season')
# # PySNMP MIB module HH3C-L2TP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-L2TP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:14:47 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") ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint") hh3cCommon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cCommon") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, TimeTicks, Counter64, NotificationType, ObjectIdentity, Gauge32, MibIdentifier, iso, Integer32, ModuleIdentity, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "TimeTicks", "Counter64", "NotificationType", "ObjectIdentity", "Gauge32", "MibIdentifier", "iso", "Integer32", "ModuleIdentity", "IpAddress") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") hh3cL2tp = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 139)) hh3cL2tp.setRevisions(('2013-07-05 15:18',)) if mibBuilder.loadTexts: hh3cL2tp.setLastUpdated('201307051518Z') if mibBuilder.loadTexts: hh3cL2tp.setOrganization('Hangzhou H3C Tech. Co., Ltd.') hh3cL2tpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1)) hh3cL2tpScalar = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1)) hh3cL2tpStats = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1)) hh3cL2tpStatsTotalTunnels = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cL2tpStatsTotalTunnels.setStatus('current') hh3cL2tpStatsTotalSessions = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cL2tpStatsTotalSessions.setStatus('current') hh3cL2tpSessionRate = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cL2tpSessionRate.setStatus('current') mibBuilder.exportSymbols("HH3C-L2TP-MIB", PYSNMP_MODULE_ID=hh3cL2tp, hh3cL2tpObjects=hh3cL2tpObjects, hh3cL2tpStatsTotalTunnels=hh3cL2tpStatsTotalTunnels, hh3cL2tpScalar=hh3cL2tpScalar, hh3cL2tpStatsTotalSessions=hh3cL2tpStatsTotalSessions, hh3cL2tp=hh3cL2tp, hh3cL2tpSessionRate=hh3cL2tpSessionRate, hh3cL2tpStats=hh3cL2tpStats)
kuukiondo = 70 shitsudo = 100 if kuukiondo >= 100: print("A") elif kuukiondo >= 92 and shitsudo > 75: print("B") elif kuukiondo > 88 and shitsudo >= 85: print("C") elif kuukiondo == 75 and shitsudo <= 65: print("D") else: print("E")
class Solution1: def maxSubArray(self, nums: List[int]) -> int: total_max, total = -1e10, 0 for i in range( len(nums) ): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: total_max = total return total_max class Solution2: ## divide and conquer approach def middlemax( self, nums, LL, mid, RR ): totalL, totalR, totalL_max, totalR_max = 0, 0, nums[mid], nums[mid+1] # Left for i in range( mid, LL-1, -1 ): totalL += nums[i] if( totalL_max < totalL ): totalL_max = totalL # Right for i in range( mid+1, RR+1 ): totalR += nums[i] if( totalR_max < totalR ): totalR_max = totalR return totalR_max + totalL_max def findmax( self, nums, LL, RR ): if LL >= RR: return nums[LL] mid = LL + (RR-LL)//2 mmax = self.middlemax( nums, LL, mid, RR ) lmax = self.findmax( nums, LL, mid ) rmax = self.findmax( nums, mid+1, RR ) return max( [mmax, lmax, rmax] ) def maxSubArray(self, nums: List[int]) -> int: Length = len(nums) return self.findmax( nums, 0, Length-1 )
""" ID: tony_hu1 PROG: sort3 LANG: PYTHON3 """ def check_swap(current_num): global unsorted global sorted global num global steps global area for i in range(num): if sorted[i] > current_num: return if sorted[i] == current_num: if unsorted[i] == current_num: unsorted[i] = 0 else: wrong_num = unsorted[i] area[1] = unsorted[0:count_1] area[2] = unsorted[count_1:count_1 + count_2] area[3]= unsorted[count_1 + count_2 : num] if current_num in area[wrong_num]: to_be_changed = area[wrong_num].index(current_num) + alterable[wrong_num-1] else: to_be_changed = unsorted[alterable[current_num]:num].index(current_num) + alterable[current_num] unsorted[i],unsorted[to_be_changed] = 0,unsorted[i] steps += 1 sorted = [] with open('sort3.in') as filename: for line in filename: sorted.append(int(line.rstrip())) num = sorted[0] del sorted[0] unsorted = sorted[0:num] sorted.sort() area = dict() steps = 0 count_1 = sorted.count(1) count_2 = sorted.count(2) alterable = {1:count_1,2:count_1+count_2} for i in range(1,3): check_swap(i) fout = open('sort3.out', 'w') fout.write(str(steps)+'\n')
################################################################################ # # # ____ _ # # | _ \ ___ __| |_ __ _ _ _ __ ___ # # | |_) / _ \ / _` | '__| | | | '_ ` _ \ # # | __/ (_) | (_| | | | |_| | | | | | | # # |_| \___/ \__,_|_| \__,_|_| |_| |_| # # # # Copyright 2021 Podrum Studios # # # # Permission is hereby granted, free of charge, to any person # # obtaining a copy of this software and associated documentation # # files (the "Software"), to deal in the Software without restriction, # # including without limitation the rights to use, copy, modify, merge, # # publish, distribute, sublicense, and/or sell copies of the Software, # # and to permit persons to whom the Software is furnished to do so, # # subject to the following conditions: # # # # The above copyright notice and this permission notice shall be included # # in all copies or substantial portions of the Software. # # # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # # IN THE SOFTWARE. # # # ################################################################################ class metadata_dictionary_type: key_flags: int = 0 key_health: int = 1 key_variant: int = 2 key_color: int = 3 key_nametag: int = 4 key_owner_eid: int = 5 key_target_eid: int = 6 key_air: int = 7 key_potion_color: int = 8 key_potion_ambient: int = 9 key_jump_duration: int = 10 key_hurt_time: int = 11 key_hurt_direction: int = 12 key_paddle_time_left: int = 13 key_paddle_time_right: int = 14 key_experience_value: int = 15 key_minecart_display_block: int = 16 key_minecart_display_offset: int = 17 key_minecart_has_display: int = 18 key_old_swell: int = 20 key_swell_dir: int = 21 key_charge_amount: int = 22 key_enderman_held_runtime_id: int = 23 key_entity_age: int = 24 key_player_flags: int = 26 key_player_index: int = 27 key_player_bed_position: int = 28 key_fireball_power_x: int = 29 key_fireball_power_y: int = 30 key_fireball_power_z: int = 31 key_aux_power: int = 32 key_fish_x: int = 33 key_fish_z: int = 34 key_fish_angle: int = 35 key_potion_aux_value: int = 36 key_lead_holder_eid: int = 37 key_scale: int = 38 key_interactive_tag: int = 39 key_npc_skin_id: int = 40 key_url_tag: int = 41 key_max_airdata_max_air: int = 42 key_mark_variant: int = 43 key_container_type: int = 44 key_container_base_size: int = 45 key_container_extra_slots_per_strength: int = 46 key_block_target: int = 47 key_wither_invulnerable_ticks: int = 48 key_wither_target_1: int = 49 key_wither_target_2: int = 50 key_wither_target_3: int = 51 key_aerial_attack: int = 52 key_boundingbox_width: int = 53 key_boundingbox_height: int = 54 key_fuse_length: int = 55 key_rider_seat_position: int = 57 key_rider_rotation_locked: int = 58 key_rider_max_rotation: int = 58 key_rider_min_rotation: int = 59 key_rider_rotation_offset: int = 60 key_area_effect_clound_radius: int = 61 key_area_effect_clound_waiting: int = 62 key_area_effect_clound_particle_id: int = 63 key_shulker_peak_id: int = 64 key_shulker_attach_face: int = 65 key_shulker_attached: int = 66 key_shulker_attach_pos: int = 67 key_trading_player_eid: int = 68 key_trading_career: int = 69 key_has_command_block: int = 70 key_command_block_command: int = 71 key_command_block_last_output: int = 72 key_command_block_track_output: int = 73 key_controlling_rider_seat_number: int = 74 key_strength: int = 75 key_max_strength: int = 76 key_spell_casting_color: int = 77 key_limited_life: int = 78 key_armor_stand_pose_index: int = 79 key_ender_crystal_time_offset: int = 80 key_always_show_nametag: int = 81 key_color_2: int = 82 key_name_author: int = 83 key_score_tag: int = 84 key_baloon_attached_entity: int = 85 key_pufferfish_size: int = 86 key_bubble_time: int = 87 key_agent: int = 88 key_sitting_amount: int = 89 key_sitting_amount_previous: int = 90 key_eating_counter: int = 91 key_flags_extended: int = 92 key_laying_amount: int = 93 key_laying_amount_previous: int = 94 key_duration: int = 95 key_spawn_time: int = 96 key_change_rate: int = 97 key_change_on_pickup: int = 98 key_pickup_count: int = 99 key_interact_text: int = 100 key_trade_tier: int = 101 key_max_trade_tier: int = 102 key_trade_experience: int = 103 key_skin_id: int = 104 key_spawning_flames: int = 105 key_command_block_tick_delay: int = 106 key_command_block_execute_on_first_tick: int = 107 key_ambient_sound_interval: int = 108 key_ambient_sound_interval_range: int = 109 key_ambient_sound_event_name: int = 110 key_fall_damage_multiplier: int = 111 key_name_raw_text: int = 112 key_can_ride_target: int = 113 key_low_tier_cured_discount: int = 114 key_high_tier_cured_discount: int = 115 key_nearby_cured_discount: int = 116 key_nearby_cured_discount_timestamp: int = 117 key_hitbox: int = 118 key_is_buoyant: int = 119 key_buoyancy_data: int = 120 key_goat_horn_count: int = 121 type_byte: int = 0 type_short: int = 1 type_int: int = 2 type_float: int = 3 type_string: int = 4 type_compound: int = 5 type_vector_3_i: int = 6 type_long: int = 7 type_vector_3_f: int = 8
class Base(object): def __secret(self): print("don't tell") def public(self): self.__secret() class Derived(Base): def __secret(self): print("never ever") if __name__ == "__main__": print("Base class members:", dir(Base)) print("Derived class members:", dir(Derived)) print("Base.public() result:") Base().public() print("Derived.public() result:") Derived().public()
# Basic script to find primer candidates # Hits are 20bp in length, with 50-55% GC content, GC clamps in the 3' end, and no more than 3xGC at the clamp # Paste the target exon sequences from a FASTA sequence with no white spaces # Exon 1 is where forward primer candidates will be identified exon1 = "GCAGTGTCACTAGGCCGGCTGGGGGCCCTGGGTACGCTGTAGACCAGACCGCGACAGGCCAGAACACGGGCGGCGGCTTCGGGCCGGGAGACCCGCGCAGCCCTCGGGGCATCTCAGTGCCTCACTCCCCACCCCCTCCCCCGGGTCGGGGGAGGCGGCGCGTCCGGCGGAGGGTTGAGGGGAGCGGGGCAGGCCTGGAGCGCCATGAGCAGCCCGGATGCGGGATACGCCAGTGACGACCAGAGCCAGACCCAGAGCGCGCTGCCCGCGGTGATGGCCGGGCTGGGCCCCTGCCCCTGGGCCGAGTCGCTGAGCCCCATCGGGGACATGAAGGTGAAGGGCGAGGCGCCGGCGAACAGCGGAGCACCGGCCGGGGCCGCGGGCCGAGCCAAGGGCGAGTCCCGTATCCGGCGGCCGATGAACGCTTTCATGGTGTGGGCTAAGGACGAGCGCAAGCGGCTGGCGCAGCAGAATCCAGACCTGCACAACGCCGAGTTGAGCAAGATGCTGG" # Exon 2 is where reverse primer candidates will be identified exon2 = "GCAAGTCGTGGAAGGCGCTGACGCTGGCGGAGAAGCGGCCCTTCGTGGAGGAGGCAGAGCGGCTGCGCGTGCAGCACATGCAGGACCACCCCAACTACAAGTACCGGCCGCGGCGGCGCAAGCAGGTGAAGCGGCTGAAGCGGGTGGAGGGCGGCTTCCTGCACGGCCTGGCTGAGCCGCAGGCGGCCGCGCTGGGCCCCGAGGGCGGCCGCGTGGCCATGGACGGCCTGGGCCTCCAGTTCCCCGAGCAGGGCTTCCCCGCCGGCCCGCCGCTGCTGCCTCCGCACATGGGCGGCCACTACCGCGACTGCCAGAGTCTGGGCGCGCCTCCGCTCGACGGCTACCCGTTGCCCACGCCCGACACGTCCCCGCTGGACGGCGTGGACCCCGACCCGGCTTTCTTCGCCGCCCCGATGCCCGGGGACTGCCCGGCGGCCGGCACCTACAGCTACGCGCAGGTCTCGGACTACGCTGGCCCCCCGGAGCCTCCCGCCGGTCCCATGCACCCCCGACTCGGCCCAGAGCCCGCGGGTCCCTCGATTCCGGGCCTCCTGGCGCCACCCAGCGCCCTTCACGTGTACTACGGCGCGATGGGCTCGCCCGGGGCGGGCGGCGGGCGCGGCTTCCAGATGCAGCCGCAACACCAGCACCAGCACCAGCACCAGCACCACCCCCCGGGCCCCGGACAGCCGTCGCCCCCTCCGGAGGCACTGCCCTGCCGGGACGGCACGGACCCCAGTCAGCCCGCCGAGCTCCTCGGGGAGGTGGACCGCACGGAATTTGAACAGTATCTGCACTTC" # Function that receives a gene string (only C, G, T or A characters) and outputs an array of primer hits # Looks for a GC clamp reading from start to end of the string def find_hit(gene) -> object: hits = [] for i in range(len(gene) - 20): if gene[i] == 'C' or gene[i] == 'G': if gene[i + 1] == 'C' or gene[i + 1] == 'G': if gene[i + 2] != 'C' and gene[i + 2] != 'G': cg_count = 0 for base in gene[i:i + 20]: if base == 'C' or base == 'G': cg_count += 1 if cg_count == 10 or cg_count == 11: hits.append(gene[i:i + 20]) return hits # Reverse exon 1 as GC clamp should be at the end of the primer exon1 = exon1[::-1] hits_exon1 = find_hit(exon1) hits_rev = [] for elem in hits_exon1: hits_rev.append(elem[::-1]) # Prints out the hits as read in a FASTA sequence (5' to 3') print("Forward primer candidates:") print(hits_rev) print("Reverse primer candidates:") print(find_hit(exon2))
# Objective # Today we're discussing scope. Check out the Tutorial tab for learning materials and an instructional video! # The absolute difference between two integers, # and , is written as . The maximum absolute difference between two integers in a set of positive integers, , is the largest absolute difference between any two integers in # . # The Difference class is started for you in the editor. It has a private integer array ( # ) for storing non-negative integers, and a public integer ( # ) for storing the maximum absolute difference. # Task # Complete the Difference class by writing the following: # A class constructor that takes an array of integers as a parameter and saves it to the # instance variable. # A computeDifference method that finds the maximum absolute difference between any # numbers in and stores it in the # instance variable. # Input Format # You are not responsible for reading any input from stdin. The locked Solution class in the editor reads in # lines of input. The first line contains , the size of the elements array. The second line has space-separated integers that describe the # array. # Constraints # , where # Output Format # You are not responsible for printing any output; the Solution class will print the value of the # instance variable. # Sample Input # STDIN Function # ----- -------- # 3 __elements[] size N = 3 # 1 2 5 __elements = [1, 2, 5] # Sample Output # 4 # Explanation # The scope of the # array and integer is the entire class instance. The class constructor saves the argument passed to the constructor as the # instance variable (where the computeDifference method can access it). # To find the maximum difference, computeDifference checks each element in the array and finds the maximum difference between any # elements: # The maximum of these differences is , so it saves the value as the instance variable. The locked stub code in the editor then prints the value stored as , which is . class Difference: def __init__(self, a): self.__elements = a # Add your code here def computeDifference(self): diff_array=[] #loop through the i+1 to the last element and through the first ement to the second last element for i in range(len(self.__elements)-1): for j in range(i+1,len(self.__elements)): diff=abs(self.__elements[j]-self.__elements[i]) diff_array.append(diff) self.maximumDifference=max(diff_array) # End of Difference class _ = input() a = [int(e) for e in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference)
#another way of doing recursive palindrome def is_palindrome(s): ln = len(s) if s != '': if s[ln-1] == s[0]: return True and is_palindrome(s[1:ln-1]) return False return True assert is_palindrome('abab') == False assert is_palindrome('abba') == True assert is_palindrome('madam') == True assert is_palindrome('madame') == False assert is_palindrome('') == True #non recursive loop method def is_palindrome_loop(s): ln = len(s) for i in xrange(ln/2): if not (s[i] == s[ln-i-1]): return False return True assert is_palindrome_loop('abab') == False assert is_palindrome_loop('abba') == True assert is_palindrome_loop('madam') == True assert is_palindrome_loop('madame') == False assert is_palindrome_loop('') == True #easier pythonic way def is_pal_easy(s): return s == s[::-1] assert is_pal_easy('abab') == False assert is_pal_easy('abba') == True assert is_pal_easy('madam') == True assert is_pal_easy('madame') == False assert is_pal_easy('') == True
lista_cadastro = [] def placa_v(): if len(lista_cadastro) > 0: print('tem placa ') else: print('não tem placa')
class Profile(object): @property def name(self): return self.__name @property def trustRoleArn(self): return self.__trustRoleArn @property def sourceProfile(self): return self.__sourceProfile @property def credentials(self): return self.__credentials @name.setter def name(self, value): self.name = value @trustRoleArn.setter def trustRoleArn(self, value): self.__trustRoleArn = value @sourceProfile.setter def sourceProfile(self, value): self.__sourceProfile = value @credentials.setter def credentials(self, value): self.__credentials = value def __init__(self, name = None, trustRoleArn = None, sourceProfile = None, credentials = None): self.__name = name self.__trustRoleArn = trustRoleArn self.__sourceProfile = sourceProfile self.__credentials = credentials
# f_name = 'ex1.txt' f_name = 'input.txt' all_ingredients = set() possible_allergens = dict() recipes = list() with open(f_name, 'r') as f: for i, line in enumerate(f.readlines()): # get a list of the ingredients and record the food recipe as a set of the # ingredients (recipes = [{'aaa', 'bbb'}, {...}] ingredients = line.split(' (')[0].strip().split() recipes.append(set(ingredients)) all_ingredients |= set(ingredients) # get a list of the allergens and store a dict of allergens with the food it is # contained in (allergens_in_food[dairy] = {1, 2, 3...} allergens = line.split(' (')[1][9:-2].strip().split(', ') for a in allergens: if a not in possible_allergens: possible_allergens[a] = set(ingredients) else: possible_allergens[a] &= set(ingredients) # Part 1: count occurence of each ingredient not a possible allergen in the recipes all_possible_allergens = set((x for ing_set in possible_allergens.values() for x in ing_set)) no_allergens = all_ingredients - all_possible_allergens part1 = 0 for ing in no_allergens: part1 += sum(1 for r in recipes if ing in r) print(f'Part 1: {part1}') # Part 2 final_allergens = dict() queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1] while queue: allg = queue.pop(0) ing = possible_allergens[allg].pop() final_allergens[allg] = ing possible_allergens.pop(allg) for x in possible_allergens: if ing in possible_allergens[x]: possible_allergens[x].remove(ing) queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1] # generate the part2 output, ingredients sorted by allergen name part2 = ','.join([final_allergens[x] for x in sorted(final_allergens)]) print('Part 2:', part2)
S = 0 T = 0 L = [] for i in range(11): L.append(list(map(int,input().split()))) L.sort(key = lambda t:(t[0],t[1])) for i in L: T+=i[0] S += T + i[1]*20 print(S)
# Evaluacion de expresiones print(3+5) print(3+2*5) print((3+2)*5) print(2**3) print(4**0.5) print(10%3) print('abra' + 'cadabra') print('ja'*3) print(1+2) print(1.0+2.0) print(1.0+2) print(1/2) print(1//2) print(1.0//2.0) print('En el curso hay ' + str(30) + ' alumnos') print('100'+'1') print(int('100') +1) # Variables a = 8 # la variable contiene el valor 8 b = 12 # la variable contiene el valor 12 print(a) print(a+b) c = a + 2 * b #creamos una expresion, se evalua y define c print(c) a = 10 #redefinimos a print(c) # el valor de c no cambia # Usar nombre descriptivos para variables a = 8 b = 12 c = a * b # Mejor: ancho = 8 largo = 12 area = ancho * largo print(area) dia = '12'; mes = 'marzo'; agno = '2018' hoy = dia + ' de ' + mes + ' de '+ agno print(hoy) # Errores ''' No incluidos directamente para que el programa corra # Errores de tipo dia = 13 mes = 'marzo' print('Hoy es ' + dia + ' de ' + mes) # Mes es tipo int # solucion print('Hoy es ' + str(dia) + ' de ' + mes) # Transformamos a string # Errores de identacion x = 3 x #tiene un 'tab' de diferencia' # Errores de sintaxis numero = 15 antecesor = (numero -1)) # Un ) de mas # Errores de nombre lado1 = 15 area = lado1/lado2 # lado2 no definido '''
# pytest -v --sudo --ssh-config=.ssh/config --ansible-inventory=inventory --hosts='ansible://appservers' tests/test_appserver.py # パッケージがインストールされている def test_installed_default_package(host): assert host.package('docker-ce').is_installed # 起動すべきサービスが起動している def test_running_default_service(host): assert host.service('docker').is_running # Swarm クラスタが起動している def test_swarm_active(host): state = host.run("docker info | grep Swarm:") assert 'Swarm: active' in state.stdout # 公開サービスが意図したポートでリッスンしている # def test_listen_default_port(host): # assert host.socket('tcp://0.0.0.0:80').is_listening
class GameStats(): """TRACK STATISTICS FOR FROM ANOTHER WORLD""" def __init__(self, ai_settings): """INITIALIZE STATISTICS""" self.ai_settings = ai_settings self.reset_stats() # START GAME IN AN INACTIVE STATE self.game_active = False def reset_stats(self): """INITIALIZE STATISTICS THAT CAN CHANGE DURING THE GAME""" self.ships_left = self.ai_settings.ship_limit self.score = 0 self.level = 1