content
stringlengths
7
1.05M
#!/usr/bin/python3 ''' BubbleSort.py by Xiaoguang Zhu ''' array = [] print("Enter at least two numbers to start bubble-sorting.") print("(You can end inputing anytime by entering nonnumeric)") # get numbers while True: try: array.append(float(input(">> "))) except ValueError: # exit inputing break print("\nTh...
medida = float(input("uma distancai em metros: ")) cm = medida * 100 mm = medida * 1000 dm = medida / 10 dam = medida * 1000000 hm = medida / 100 km = medida * 0.001 ml = medida * 0.000621371 m = medida * 100000 print("A medida de {:.0f}m corresponde a {:.0f} mm \n{:.0f} cm \n{:.0f} dm \n{:.0f} dam \n{:.0f} hm \n{:.2f...
def create_supervised_data(env, agents, num_runs=50): val = [] # the data threeple action_history = [] predict_history = [] mental_history = [] character_history = [] episode_history = [] traj_history = [] grids = [] ep_length = env.maxtime filler = env.get_filler() obs = env.reset(setting=setting, nu...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists: list): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None...
def create_path(path:str): """ :param path:path is the relative path from the pixel images folder :return: return the relative path from roots of project """ return current_path + path #a function name is before the parameters and after the def #function parameters: the values that the function kn...
def rep_hill(x, n): """Dimensionless production rate for a gene repressed by x. Parameters ---------- x : float or NumPy array Concentration of repressor. n : float Hill coefficient. Returns ------- output : NumPy array or float 1 / (1 + x**n) """ return...
n = int(input()) vip_guest = set() regular_guest = set() for _ in range(n): reservation_code = input() if reservation_code[0].isdigit(): vip_guest.add(reservation_code) else: regular_guest.add(reservation_code) command = input() while command != "END": if command[0].isdigit(): ...
class alttprException(Exception): pass class alttprFailedToRetrieve(Exception): pass class alttprFailedToGenerate(Exception): pass
EXPECTED_TABULATED_HTML = """ <table> <thead> <tr> <th>category</th> <th>date</th> <th>downloads</th> </tr> </thead> <tbody> <tr> <td align="left">2.6</td> <td align="left">2018-08-15</td> <td align="right">51</t...
# Runtime: 84 ms, faster than 22.95% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree. # Memory Usage: 23.1 MB, less than 91.67% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree. # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # ...
load( "//tensorflow/core/platform:rules_cc.bzl", "cc_library", ) def poplar_cc_library(**kwargs): """ Wrapper for inserting poplar specific build options. """ if not "copts" in kwargs: kwargs["copts"] = [] copts = kwargs["copts"] copts.append("-Werror=return-type") cc_library(**kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Question: Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also t...
# Copyright (C) 2018 Garth N. Wells # # SPDX-License-Identifier: MIT """This module provides a model for a monitoring station, and tools for manipulating/modifying station data """ class MonitoringStation: """This class represents a river level monitoring station""" def __init__(self, station_id, measure_id...
a = input("Enter the string:") b = a.find("@") c = a.find("#") print("The original string is:",a) print("The substring between @ and # is:",a[b+1:c])
def fahrenheit_to_celsius(F): ''' Function to compute Celsius from Fahrenheit ''' K = fahrenheit_to_kelvin(F) C = kelvin_to_celsius(K) return C
def read_lines(file_path): with open(file_path, 'r') as handle: return [line.strip() for line in handle] def count_bits(numbers): counts = [0] * len(numbers[0]) for num in numbers: for i, bit in enumerate(num): counts[i] += int(bit) return counts lines = read_lines('test...
famous_name = "albert einstein" motto = "A person who never made a mistake never tried anything new." message = famous_name.title() + "once said, " + '"' + motto + '"' print(message)
JIRA_DOMAIN = {'RD2': ['innodiv-hwacom.atlassian.net','innodiv-hwacom.atlassian.net'], 'RD5': ['srddiv5-hwacom.atlassian.net']} API_PREFIX = 'rest/agile/1.0' # project_id : column_name STORY_POINT_COL_NAME = {'10005': 'customfield_10027', '10006': 'customfield_10027', ...
class PixelMeasurer: def __init__(self, coordinate_store, is_one_calib_block, correction_factor): self.coordinate_store = coordinate_store self.is_one_calib_block = is_one_calib_block self.correction_factor = correction_factor def get_distance(self, calibration_length): distance...
# Programming for the Puzzled -- Srini Devadas # You Will All Conform # Input is a vector of F's and B's, in terms of forwards and backwards caps # Output is a set of commands (printed out) to get either all F's or all B's # Fewest commands are the goal caps = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B...
s=input() t=input() ss=sorted(map(s.count,set(s))) tt=sorted(map(t.count,set(t))) print('Yes' if ss==tt else 'No')
def anagrams(word, words): agrams = [] s1 = sorted(word) for i in range (0, len(words)): s2 = sorted(words[i]) if s1 == s2: agrams.append(words[i]) return agrams
#!/usr/bin/env python """ WhatIsCode This extremely simple script was an inspiration driven by a combination of Paul Ford's article on Bloomberg Business Week, "What is Code?"[1] and Haddaway's song, "What is Love"[2]. It is probably best enjoyed while watching an 8-bit demake of the song[3], or 16-bit if you prefer...
initialScore = int(input()) def count_solutions(score, turn): if score > 50 or turn > 4: return 0 if score == 50: return 1 result = count_solutions(score + 1, turn + 1) for i in range(2, 13): result += 2 * count_solutions(score + i, turn + 1) return result print(count...
#!/usr/bin/env python3 def gcd(a, b): if a == 0 : return b return gcd(b%a, a) a = 12000 b = 8642 print(gcd(a, b))
def solve(): n = int(input()) k = list(map(int,input().split())) hashmap = dict() j = 0 ans = 0 c = 0 for i in range(n): if k[i] in hashmap and hashmap[k[i]] > 0: while i > j and k[i] in hashmap and hashmap[k[i]] > 0: hashmap[k[j]] -= 1 ...
# Here the rate is set for Policy flows, local to a compute, which is # lesser than policy flows across computes expected_flow_setup_rate = {} expected_flow_setup_rate['policy'] = { '1.04': 6000, '1.05': 9000, '1.06': 10000, '1.10': 10000, '2.10': 13000} expected_flow_setup_rate['nat'] = { '1.04': 4200, '1.05':...
# Dynamic Programming Python implementation of Min Cost Path # problem R = 3 C = 3 def minCost(cost, m, n): # Instead of following line, we can use int tc[m+1][n+1] or # dynamically allocate memoery to save space. The following # line is used to keep te program simple and make it working #...
""" 迭代器 --> yield """ class CommodityController: def __init__(self): self.__commoditys = [] def add_commodity(self, cmd): self.__commoditys.append(cmd) def __iter__(self): index = 0 yield self.__commoditys[index] index += 1 yield self.__commoditys[in...
print('=' * 12 + 'Desafio 53' + '=' * 12) frase = input('Digite sua frase: ') frase = frase.strip().replace(" ","").upper() tamanho = len(frase) contador = 0 igual = 0 for i in range(tamanho - 1, -1, -1): if frase[contador] == frase[i]: igual += 1 contador += 1 if contador == tamanho: print('A frase...
def create_box(input_corners): x = (float(input_corners[0][0]), float(input_corners[1][0])) y = (float(input_corners[0][1]), float(input_corners[1][1])) windmill_lats, windmill_lons = zip(*[ (max(x), max(y)), (min(x), max(y)), (min(x), min(y)), (max(x), min(y)), ...
class Label: @staticmethod def from_str(value): for l in Label._get_supported_labels(): if l.to_str() == value: return l raise Exception("Label by value '{}' doesn't supported".format(value)) @staticmethod def from_int(value): assert(isinstance(val...
'''70. Climbing Stairs Easy 3866 127 Add to List Share You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 ...
RESOURCES = { 'posts': { 'schema': { 'title': { 'type': 'string', 'minlength': 3, 'maxlength': 30, 'required': True, 'unique': False }, 'body': { 'type': 'string', ...
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
pkgname = "python-sphinx-removed-in" pkgver = "0.2.1" pkgrel = 0 build_style = "python_module" hostmakedepends = ["python-setuptools"] checkdepends = ["python-sphinx"] depends = ["python-sphinx"] pkgdesc = "Sphinx extension for versionremoved and removed-in directives" maintainer = "q66 <q66@chimera-linux.org>" license...
class Case : def __init__(self,x,y): self.id = str(x)+','+str(y) self.x = x self.y = y self.piece = None def check_case(self): """renvoie la piece si la case est occupé,renvoie -1 sinon """ if(self.piece != None): return self.piece re...
class Solution: def canPartition(self, nums: List[int]) -> bool: dp, s = set([0]), sum(nums) if s&1: return False for num in nums: dp.update([v+num for v in dp if v+num <= s>>1]) return s>>1 in dp
class Solution: def sortLinkedList(self, head: Optional[ListNode]) -> Optional[ListNode]: prev = head curr = head.next while curr: if curr.val < 0: prev.next = curr.next curr.next = head head = curr curr = prev.next else: prev = curr curr = curr...
def descuento(niños=int(input("Cuantos niños son "))): if niños==2: descuentoTotal=10 elif niños==3: descuentoTotal=15 elif niños==4: descuentoTotal=18 elif niños>=5: descuentoTotal=18+(niños-4)*1 return print(descuentoTotal) descuento()
"""Preprocessing Sample.""" __author__ = 'Devon Welcheck' def preprocess(req, resp, resource, params): # pylint: disable=unused-argument """Preprocess skeleton."""
#Análise do relatório de vôos e viagens do aeroporto de Boston com base nos relatórios econômicos oficiais with open('economic-indicators.csv', 'r') as boston: total_voos = 0 maior = 0 total_passageiros = 0 maior_media_diaria = 0 ano_usuario = input('Qual ano deseja pesquisar?: ') #Retornar o t...
""" Profile ../profile-datasets-py/div52/011.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div52/011.py" self["Q"] = numpy.array([ 1.60776800e+00, 5.75602400e+00, 7.00189400e+00, 7.33717600e+00, 6.76175900e+00, 8.41951900e+00, 6.5464...
class Pessoa: #substantivo def __init__(self, nome: str, idade: int) -> None: self.nome = nome #substantivo self.idade = idade #substantivo def dirigir(self, veiculo: str) -> None: #verbos print(f'Dirigindo um(a) {veiculo}') def cantar(self) -> None: #verbos print('lalalala...
""" [2016-07-22] Challenge #276 [Hard] ∞ Loop solver part 2 https://www.reddit.com/r/dailyprogrammer/comments/4u3e96/20160722_challenge_276_hard_loop_solver_part_2/ This is the same challenge as /u/jnazario's excellent [∞ Loop solver](https://www.reddit.com/r/dailyprogrammer/comments/4rug59/20160708_challenge_274_har...
'''Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. Ex: n = leiaInt('Digite um n: ')''' def leiaInt(msg): ok = False valor = 0 while True: n = str...
API_GROUPS = { 'authentication': ['/api-auth/', '/api/auth-valimo/',], 'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',], 'organization': [ '/api/customers/', '/api/customer-permissions-log/', '/api/customer-permissions-reviews/', '/api/customer-permis...
# -*- coding: utf-8 -*- """Module compliance_suite.functions.update_server_settings.py Functions to update server config/settings based on the response of a previous API request. Each function should accept a Runner object and modify its "retrieved_server_settings" attribute """ def update_supported_filters(runner, ...
df = pd.read_csv(DATA) df = df.sample(frac=1.0) df.reset_index(drop=True, inplace=True) result = df.tail(n=10)
def to_binary(number): binarynumber="" if (number!=0): while (number>=1): if (number %2==0): binarynumber=binarynumber+"0" number=number/2 else: binarynumber=binarynumber+"1" number=(number-1)/2 else: bi...
x = 5 y = 3 z = x + y print(x) print(y) print(x + y) print(z) w = z print(w)
#Calculadora de tabuada n = int(input('Deseja ver tabuada de que numero?')) for c in range(1, 13): print('{} X {:2}= {} '. format(n, c, n * c))
COLUMNS = [ 'tipo_registro', 'nro_pv_matriz', 'vl_total_bruto', 'qtde_cvnsu', 'vl_total_rejeitado', 'vl_total_rotativo', 'vl_total_parcelado_sem_juros', 'vl_total_parcelado_iata', 'vl_total_dolar', 'vl_total_desconto', 'vl_total_liquido', 'vl_total_gorjeta', 'vl_total...
# Ask user to enter their country name. # print out their phone code. l_country_phone_code = ["China","86","Germany","49","Turkey","90"] def country_name_to_phone_code_list(country_name): for index in range(len(l_country_phone_code)): if l_country_phone_code[index] == country_name: return l_country_phone_code[...
""" EGF string variables for testing. """ # POINT valid_pt = """PT Park Name, City, Pond, Fountain Post office Square, Boston, FALSE, TRUE 42.356243, -71.055631, 2.0 Boston Common, Boston, TRUE, TRUE 42.355465, -71.066412, 10.0 """ invalid_pt_geom = """PTs Park Name, City, Pond, Fountain Post office S...
class GuidAttribute(Attribute,_Attribute): """ Supplies an explicit System.Guid when an automatic GUID is undesirable. GuidAttribute(guid: str) """ def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ f...
'''Disciplina: Programação I Trabalho prático ano lectivo 2013/2014 Realizado por Hiago Oliveira (29248) e Rui Oliveira (31511) ''' class Village: # Constructor method # Used to create a new instance of Village, taking in arguments like # its size and population, then builds the board used throughout the ...
def palavras_repetidas(fileName, word): file = open(fileName, 'r') count = 0 for i in file.readlines(): if word in i: count += 1 print(f'{word} aparece no arquivo {fileName} {count} vez(es).')
n = int(input()) x = 0 for i in range(n): l = set([j for j in input()]) if "+" in l: x += 1 else : x -= 1 print(x)
client = pymongo.MongoClient("mongodb+srv://usermgs:udUnpg6aJnCp9d2W@cluster0.2ivys.mongodb.net/baseteste?retryWrites=true&w=majority") db = client.test
class Mammal: x = 10 def walk(self): print("Walking") # class Dog: # def walk(self): # print("Walking") # class Cat: # def walk(self): # print("Walking") class Dog(Mammal): def bark(self): print("Woof, woof!") class Cat(Mammal): pass # Just used here as Py...
class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=35): self.nome = nome self.idade = idade self.filhos = list(filhos) def cumprimentar(self): return f'Olá{id(self)}' if __name__ == '__main__': thaila = Pessoa(nome='Thaila') junior = Pessoa(thaila,...
# # @lc app=leetcode.cn id=1203 lang=python3 # # [1203] print-in-order # None # @lc code=end
''' Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we re...
def check_hgt(h): if "cm" in h: return 150 <= int(h.replace("cm","")) <= 193 elif "in" in h: return 59 <= int(h.replace("in","")) <= 76 else: return False def check_hcl(h): if h[0] != '#' or len(h) != 7: return False for x in h[1:]: if not x in list("...
def test_deploying_contract(client, hex_accounts): pre_balance = client.get_balance(hex_accounts[1]) client.send_transaction( _from=hex_accounts[0], to=hex_accounts[1], value=1234, ) post_balance = client.get_balance(hex_accounts[1]) assert post_balance - pre_balance == 12...
if __name__ == '__main__': _, X = input().split() subjects = list() for _ in range(int(X)): subjects.append(map(float, input().split())) for i in zip(*subjects): print("{0:.1f}".format(sum(i)/len(i)))
promt = "Here you can enter" promt += "a series of toppings>>>" message = True while message: message = input(promt) if message == "Quit": print(" I'll add " + message + " to your pizza.") else: break promt = "How old are you?" promt += "\nEnter 'quit' when you a...
def foo(a, b): x = a * b y = 3 return y def foo(a, b): x = __report_assign(7, 8, 3) x = __report_assign(pos, v, 3) y = __report_assign(lineno, col, 3) print("hello world") foo(3, 2) report_call(0, 3, foo, (report_eval(3), report_eval(2),))
class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2) + int(b, 2))[2:] if __name__ == '__main__': a = "11" b = "1" solution = Solution() result = solution.addBinary(a, b) print(result) result1 = int(a, 2) result2 = int(b, 2) print(result1) pr...
""" [intermediate] challenge #5 Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/pnhtj/2132012_challenge_5_intermediate/ """ words = [] sorted_words = [] with open('intermediate/5/words.txt', 'r') as fp: words = fp.read().split() sorted_words = [''.join(sorted(word)) for word in word...
a=int(input()) b=int(input()) print (a/b) a=float(a) b=float(b) print (a/b)
"""Abstract planet type.""" class Planet(type): """Abstract Planet object.""" MEAN_RADIUS = (None, None) # [km] ± err [km] RADII = ((None, None), (None, None), (None, None)) # [km] ± err [km] def __str__(cls): return cls.__name__ def __repr__(cls): retur...
# -*- coding: utf-8 -*- """ Individual scratchpad and maybe up-to-date CDP instance scrapers. """
def test_Dict(): x: dict[i32, i32] x = {1: 2, 3: 4} # x = {1: "2", "3": 4} -> sematic error y: dict[str, i32] y = {"a": -1, "b": -2} z: i32 z = y["a"] z = y["b"] z = x[1] def test_dict_insert(): y: dict[str, i32] y = {"a": -1, "b": -2} y["c"] = -3 def test_dict_get(...
states = {'Pending', 'Ready', 'Creating', 'Running', 'Cancelled', 'Error', 'Failed', 'Success'} complete_states = ('Cancelled', 'Error', 'Failed', 'Success') valid_state_transitions = { 'Pending': {'Ready'}, 'Ready': {'Creating', 'Running', 'Cancelled', 'Error'}, 'Creating': {'Ready', 'Running'}, 'Run...
def assigned_type_mismatch(): x = 666 x = '666' return x def annotation_type_mismatch(x: int = '666'): return x def assigned_type_mismatch_between_calls(case): if case: x = 666 else: x = '666' return x
# https://www.codewars.com/kata/576757b1df89ecf5bd00073b/train/python def tower_builder(n_floors): times = 1 space = ((2*n_floors -1) // 2) tower = [] for _ in range(n_floors): tower.append((' '*space) + ('*' * times) + (' '*space)) times += 2 space -= 1 return tower
#! /usr/bin/env python # Programs that are runnable. ns3_runnable_programs = ['build/src/aodv/examples/ns3.27-aodv-debug', 'build/src/bridge/examples/ns3.27-csma-bridge-debug', 'build/src/bridge/examples/ns3.27-csma-bridge-one-hop-debug', 'build/src/buildings/examples/ns3.27-buildings-pathloss-profiler-debug', 'build/...
# Arithmetic progression # A + (A+B) + (A+2B) + (A+3B) + ... + (A+(C-1)B)) def main(): N = int(input("data:\n")) l = [] for x in range(0,N): a,b,c = input().split(" ") a,b,c = int(a),int(b),int(c) s = 0 for each in range(0,c): s += a + (b*each) ...
#!/usr/bin/env python3 # Algorithm: Quick sort # Referrence: https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort.py def quick_sort(num_list): """ Quick sort in Python If length of the list is 1 or less, there is no point in sorting it. Hence, the code works on lists with sizes grea...
col = { "owid": { "Notes": "notes", "Entity": "entity", "Date": "time", "Source URL": "src", "Source label": "src_lb", "Cumulative total": "tot_n_tests", "Daily change in cumulative total": "n_tests", "Cumulative total per thousand": "tot_n_tests_pthab...
# https://codeforces.com/problemset/problem/1030/A n = int(input()) o = list(map(int, input().split())) print('HARD' if o.count(1) != 0 else 'EASY')
class Solution: # @param {integer[]} candidates # @param {integer} target # @return {integer[][]} def combinationSum(self, candidates, target): candidates.sort() return self.combsum(candidates, target) def combsum(self, nums, target): if target == 0: return [[]] ...
def decimal2base(num, base): convert_string = "0123456789ABCDEF" if num < base: return convert_string[num] remainder = num % base num = num // base return decimal2base(num, base) + convert_string[remainder] print(decimal2base(1453, 16))
# wykys 2019 def bin_print(byte_array: list, num_in_line: int = 8, space: str = ' | '): def bin_to_str(byte_array: list) -> str: return ''.join([ chr(c) if c > 32 and c < 127 else '.' for c in byte_array ]) tmp = '' for i, byte in enumerate(byte_array): tmp = ''.join([t...
expected_output = { 'environment-information': { 'environment-item': [{ 'class': 'Temp', 'name': 'PSM 0', 'status': 'OK', 'temperature': { '#text': '25 ' 'degrees ' 'C ' '/ ' '77 '...
# Declan Barr 19 Mar 2018 # Script that contains function sumultiply that takes two integer arguments and # returns their product. Does this without the * or / operators def sumultiply(x, y): sumof = 0 for i in range(1, x+1): sumof = sumof + y return sumof print(sumultiply(11, 13)) print(sumultip...
""" link : https://leetcode.com/problems/koko-eating-bananas/ """ class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def condition(val): hr = 0 for i in piles: hr += (val + i - 1)//val return hr <= h left,right = ...
class Node: def __init__(self, value, child, parent): self._value = value self._child = child self._parent = parent def get_value(self): #Return the value of a node return self._value def get_child(self): #Return the value of a node return self._chil...
# -*- coding: utf-8 -*- """ Created on Thu May 28 15:30:04 2020 @author: Christopher Cheng """ class Circle (object): def __init__(self): self.radius = 0 def change_radius(self, radius): self.radius = radius def get_radius (self): return self.radius class Rectangle(object): ...
class AvatarPlugin: """ Abstract interface for all Avatar plugins Upon start() and stop(), plugins are expected to register/unregister their own event handlers by the means of :func:`System.register_event_listener` and :func:`System.unregister_event_listener` """ def __init__(self, system)...
#!/usr/bin/env python # encoding=utf-8 """ inner_rpc.ir_exceptions ----------------- 该模块主要包括公共的异常定义 """ class BaseError(Exception): pass class SocketError(BaseError): pass class SocketTimeout(SocketError): pass class DataError(BaseError): pass
name = 'eric Pearson' # Упражнение 3. message = f'Hello {name}, would you like to learn some Python today?' print(message) # Упражнение 4. message = f'Hello {name.lower()}, would you like to learn some Python today?' print(message) message = f'Hello {name.upper()}, would you like to learn some Python today?' print(me...
def find_sum(arr, s): curr_sum = arr[0] start = 0 n = len(arr) - 1 i = 1 while i <= n: while curr_sum > s and start < i: curr_sum = curr_sum - arr[start] start += 1 if curr_sum == s: return "Found between {} and {}".format(start, i ...
class HoloResponse: def __init__(self, success, response=None): self.success = success if response != None: self.response = response
x = float(1) y = float(2.8) z = float("3") w = float("4.2") print(x) print(y) print(z) print(w) # Author: Bryan G
""" Project name: SortingProblem File name: BubbleSort.py Description: version: Author: Jutraman Email: jutraman@hotmail.com Date: 04/07/2021 21:49 LastEditors: Jutraman LastEditTime: 04/07/2021 Github: https://github.com/Jutraman """ def bubble_sort(array): length = len(array) for i in range(length): ...
""" ORM是django的核心思想, object-related-mapping对象-关系-映射 ORM核心就是操作数据库的时候不再直接操作sql语句,而是操作对象 定义一个类,类中有uid,username等类属型,sql语句insert修改的时候直接插入这个User对象 """ # ORM映射实现原理,通过type修改类对象信息 # 定义这个元类metaclass class ModelMetaclass(type): def __new__(cls, name, bases, attrs): # name --> User # bases --> o...
def capture_high_res(filename): return "./camerapi/tmp_large.jpg" def capture_low_res(filename): return "./camerapi/tmp_small.jpg" def init(): return def deinit(): return