content
stringlengths
7
1.05M
API_STAGE = 'dev' APP_FUNCTION = 'handler_for_events' APP_MODULE = 'tests.test_event_script_app' DEBUG = 'True' DJANGO_SETTINGS = None DOMAIN = 'api.example.com' ENVIRONMENT_VARIABLES = {} LOG_LEVEL = 'DEBUG' PROJECT_NAME = 'test_event_script_app' COGNITO_TRIGGER_MAPPING = {}
AVAILABLE_OUTPUTS = [ (20, 'out 1'), (21, 'out 2') ]
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isValidBST(self, root): def util(root, low, high): if not root: return True return low < root...
class Solution: def reverseVowels(self, s): """ :type s: str :rtype: str """ vow = ['a', 'e', 'i', 'o', 'u'] ch = [c for c in s] low, high = 0, len(ch) - 1 while low < high: while low < high and ch[low] not in vow: print("l...
""" Copyright 2019 Islam Elnabarawy 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 ...
""" ID: tony_hu1 PROG: milk3 LANG: PYTHON3 """ filein = [] with open('milk3.in') as filename: for line in filename: filein.append(line.rstrip()) filein = filein[0].split(' ') a = int(filein[0]) b = int(filein[1]) c = int(filein[2]) list_possibilities = [[[False]*c]*b]*a m = get_possible(a,b,c) outstring = ...
#input # 28 # RP PP RR PS RP # PR PP SR PS SS RR RS RP # PR SP PR RS RP PP RS # RP PS PS PR SS RR PP PR SP SP RR PR PS PS SP # RS PS RR PR RP PR RS SR SR RR PP PP SR RS RP # RR RR RR SP PR RP RR PP SP PS RR RS SP # SS RP RP PP SS RR RP PS SP RR RS SR RS RS SS PS # SR SP SR RP RP SS SP PP SS SS SS SS RP # SR PP RP PP RP...
"""Custom exceptions. All the exceptions raised by the code in avazu_ctr_prediction.* should derive from Avazu-Ctr-PredictionException """ class AvazuCtrPredictionException(Exception): """Mother class for common avazu_ctr_prediction exceptions.""" pass class MissingModelException(AvazuCtrPredictionExcepti...
# -*- coding: utf-8 -*- """ Простейшим примером использования полиморфизма является функция print, которая вызывает у переданного ей объекта метод __str__. """ print('str') print(42)
sum =0 n = 99 while n>0: sum = sum+n n=n-2 if n<10: break print(sum) #---------- for x in range(101): if x%2==0: continue else: print(x) #---------- y = 0 while True: print(y) y=y+1
''' 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。   示例 1: 输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2: 输入: nums = [1], k = 1 输出: [1] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/top-k-frequent-elements ''' class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: top_dict = {} for...
def imprimePorIdade(pDIct = dict()): sortedDict = sorted(pDIct.items(), key = lambda x: x[1], reverse=False) for i in sortedDict: print(i[0], i[1]) pass pass testDict = { "narto": 29, "leo": 13, "antonia": 45, "mimosa": 27, } imprimePorIdade(testDict)
#sublist def sub_list(list): return list[1:3] result = sub_list([1,2,3,4,5]) print(result) #concatenation list1 = [1,2,4,5,6] list2 = [5,6,7,8,9] list3 = list1 + list2 print(list3) #traverse for element in list3: print(element) #list slicing def get_sublist(list): return [list[0:3], list[3:]] print...
# -*- coding: utf-8 -*- __author__ = 'Allen' #ValueRef 是指向数据库中二进制数据对象的Python对象,是对数据库中数据的引用。 class ValueRef(object): def __init__(self,referent=None,address=0): self._referent = referent#就是它引用的值 self._address = address#就是该值在文件中的位置 def prepare_to_store(self,storage): '''存储之前要做的事情,此处不实现...
# _*_ coding:utf-8 _*_ #!/usr/local/bin/python encrypted = [6,3,1,7,5,8,9,2,4] def decrypt(encryptedTxt): head = 0 tail = len(encryptedTxt)-1 decrypted = [] while len(encryptedTxt)>0: decrypted.append(encryptedTxt[0]) del encryptedTxt[0] print(encryptedTxt) if(len(encr...
# https://www.codewars.com/kata/550554fd08b86f84fe000a58/train/python def in_array(array1, array2): result = [] array1 = list(set(array1)) for arr1_element in array1: for arr2_element in array2: if arr2_element.count(arr1_element) != 0: result.append(arr1_element) ...
'''Refaça o desafio 051, lendo um número e a razão de uma PA, e mostrando os 10 primeiros termos dessa PA utilizando while''' print('\033[31m==\033[m'*11) print('\033[33mProgressão Aritmética\033[m') print('\033[31m==\033[m'*11) x = 0 resposta = '' while resposta != 'n': resposta = str(input('''Gostaria de Calcula...
#!/usr/bin/python #https://practice.geeksforgeeks.org/problems/is-binary-number-multiple-of-3/0 def sol(x): """ If the diff. of even set bits and odd set bits is divisible by 3, then the number is divisible by 3 """ n = len(x) oddCount = 0 evenCount = 0 for i in range(n): i...
#!/usr/bin/env python # -*- coding: utf8 -*- # coding: utf8 # This class is used for the communication between bots class LinkCable(): def __init__(self, engine): # Class attributes self.engine = engine self.buy_waiting_ack = False self.buy_username = "" self.buy_pokestuff =...
class MyCircularQueue: def __init__(self, k: int): self.q = [None] * k self.front_idx = -1 self.back_idx = -1 self.capacity = k def display_elements(self): print("The elements in the Queue are ") print_str = "" # add the elements to the print string ...
def binary_search(search_val, search_list): midpoint = (len(search_list)-1) // 2 if search_val == search_list[midpoint]: return True elif len(search_list) == 1 and search_val != search_list[0]: return False elif search_val > search_list[midpoint]: return binary_search(search_val...
class CachedAccessor: def __init__(self, name, accessor): self._name = name self._accessor = accessor def __get__(self, obj, cls): if obj is None: return self._accessor accessor_obj = self._accessor(obj) setattr(obj, self._name, accessor_obj) return...
matrix = [[0,0,0], [0,0,0], [0,0,0]] for l in range(0,3): for c in range(0,3): matrix[l][c] = int(input(f'digite um numero [{l}][{c}]: ')) print('-='*30) for l in range(0,3): for c in range(0,3): print(f'[{matrix[l][c]:^5}]', end='') print()
# -*- coding: utf-8 -*- # Scrapy settings for FinalProject project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/l...
def _try_composite(a, d, n, s): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n - 1: return False return True def is_prime(n): """ Deterministic variant of the Miller-Rabin primality test to determine whether a given number is prime...
""" https://edabit.com/challenge/FgAsxMCaEzvKhnuAH Deep Arithmetic Create a function that takes an array of strings of arbitrary dimensionality ([], [][], [][][], etc) and returns the deep_sum of every separate number in each string in the array. Examples deep_sum(["1", "five", "2wenty", "thr33"]) ➞ 36 deep_sum([...
soma = 0 cont = 0 for contador in range(1,501, 2): if contador % 3 == 0: cont = cont + 1 soma = soma + contador print('A soma dos {} números ímpares múltiplos de 3 é {}'.format(cont, soma))
class Solution: def stringMatching(self, words: List[str]) -> List[str]: words.sort(key=len) res = [] lps = [self._compute_lps(w) for w in words[:-1]] for i in range(len(words)): for j in range(i + 1, len(words)): if self._kmp(words[i], words[j], lps[i]): ...
def get_users(passwd: str) -> dict: """Split password output by newline, extract user and name (1st and 5th columns), strip trailing commas from name, replace multiple commas in name with a single space return dict of keys = user, values = name. """ output = {} for line in passwd...
def char_concat(word): string = '' for i in range(int(len(word)/2)): string += word[i] + word[-i-1] + str(i+1) return string
def transcribe(seq: str) -> str: """ transcribes DNA to RNA by generating the complement sequence with T -> U replacement """ rna="" for i in seq: if i not in 'ATGC': rna = "Invalid Input" ##only accepts ATGC as a input break ##builds a rna string by con...
class KdcVendor(basestring): """ Kerberos Key Distribution Center (KDC) Vendor Possible values: <ul> <li> "microsoft" , <li> "other" </ul> """ @staticmethod def get_api_name(): return "kdc-vendor"
def test_chain_web3_is_preconfigured_with_default_from(project): default_account = '0x0000000000000000000000000000000000001234' project.config['web3.Tester.eth.default_account'] = default_account with project.get_chain('tester') as chain: web3 = chain.web3 assert web3.eth.defaultAccount ==...
args = dict( models = [ { "name": 'RandomForestClassifier', 'params': { 'n_estimators': [60], 'max_depth': [12], 'min_samples_split': [6], 'min_samples_leaf': [2], # 'max_features': [12], ...
#Ascending order n = int(input().strip()) a = list(map(int, input().strip().split(' '))) for i in range(n): for j in range(n-1): if(a[j]>a[j+1]): a[j],a[j+1]=a[j+1],a[j] print(a) #Descending order Data = [75,3,73,7,6,23,89,8] for i in range(len(Data)): for j in range(len(Data)-1): ...
class Solution: def letterCasePermutation(self, S: str) -> List[str]: ans = [] self.dfs(S, 0, ans, []) return ans def dfs(self, S, i, ans, path): if i == len(S): ans.append(''.join(path)) return self.dfs(S, i+1, ans, path + [S[i]]...
# Copyright (c) 2013-2017 by Ron Frederick <ronf@timeheart.net>. # All rights reserved. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License v1.0 which accompanies this # distribution and is available at: # # http://www.eclipse.org/legal/epl-v10.html # #...
#!/usr/bin/env python3 def validate_user(username, minlen): if type(username) != str: raise TypeError("username must be a string") if len(username) < minlen: return False if not username.isalnum(): return False # Username can't begin with a number if username[0].isnumeric():...
# Get balances queries LIQUIDITY_POSITIONS_QUERY = ( """ liquidityPositions ( first: $limit, skip: $offset, where: {{ user_in: $addresses, liquidityTokenBalance_gt: $balance, }}) {{ id liquidityTokenBalance pair {{ ...
# # PySNMP MIB module HPN-ICF-DHCPRELAY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-DHCPRELAY-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:37:51 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
# ============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 10921.py # Description: UVa Online Judge - 10921 # ============================================================================= source = li...
#!/usr/bin/python3 def words_count(filename): with open(filename, 'r') as file: strg = file.read() number = len(strg.split()) return number print(words_count("testscript.py")) a = [1, 2, 3] b = (4, 5, 8) for i, j in zip(a,b): print(i + j)
""" Module that implements APL's dyadic operators. """ def jot(*, aalpha, oomega): """Define the dyadic jot ∘ operator. Monadic case: f∘g ⍵ f g ⍵ Dyadic case: ⍺ f∘g ⍵ ⍺ f g ⍵ """ def derived(*, alpha=None, omega): return aalpha(alpha=alpha, omega=oomega(omega=omega...
def main(): n, k = map(int, input().split()) h = list(map(int, input().split())) cost = [float('inf')] * n cost[0] = 0 for i in range(1, n): for j in range(1, k + 1): if i - j < 0: break else: cost[i] = min(cost[i], cost[i - j] + abs(h[...
grammar = """ nonzeroDigit = digit:x ?(x != '0') digits = <'0' | nonzeroDigit digit*>:i -> int(i) netstring = digits:length ':' <anything{length}>:string ',' -> string receiveNetstring = netstring:string -> receiver.netstringReceived(string) """ class NetstringSender(object): def __init__(self, transport): ...
""" type ctrl+space this executes this file type ctrl+. you see the result in a pane to see the result in a file type ctrl+. select line 20 (g 20 g v $) type ctrl+enter this executes your selection you see the result in a pane to see the result in a file type ctrl+. """ print('hello world!') """ ...
class SimApp(QWidget): def __init__(self, env): super().__init__() self.env = env self.initUI() def initUI(self): grid = QGridLayout() self.setLayout(grid) grid.addWidget(QLabel('pods_min:'), 0, 0) grid.addWidget(QLabel('pods_max:'), 1, 0) grid.a...
class ContentBasedFiltering: def limit_number_of_recommendations(self,limit): self.limit = limit def __init__(self,db, regenerate = False): self.db = db self.table = 'content_based_recommendations' if regenerate or not db.table_exists(self.table): self.generate_sim...
APP_VERSION = '1.4.5.112' PEER_ID = 'A6B186B2630BDAE0641F78858136A65D' ACT = 'tab_show' OS_VERSION = 'Windows 10' TAB_ID = 'all' ACCOUNT_TYPE = '4' PHONE_AREA = '86' PRODUCT_ID = '0' PROTOCOL_VERSION = '1' # 系统初始化调用 URL_INIT = 'http://xyajs.data.p2cdn.com/o_onecloud_pc_cycle' URL_ACCOUNT_BASE = 'http://account.onethi...
liste = [1, 2 , 5, 3, 6, 4] print (sorted(liste)) # listenin aslı ile oynamadan sıralı sekilde yazdırır print ("\n") print (liste) # burada listenin aslını görecegiz print("\n") liste.sort() ...
#This code has conflicting attributes, #but the documentation in the standard library tells you do it this way :( #See https://discuss.lgtm.com/t/warning-on-normal-use-of-python-socketserver-mixins/677 class ThreadingMixIn(object): def process_request(selfself, req): pass class HTTPServer(object): ...
""" 1. Clarification 2. Possible solutions - Backtracking + Bit manipulation - Iterative + Bit manipulation 3. Coding 4. Tests """ # T=O(len(all letters in arr) + 2^n), S=O(n) class Solution: def maxLength(self, arr: List[str]) -> int: masks = list() for s in arr: mask = 0 ...
gamestr = "Baldur's Gate EE 2.6.6.0" headers = ["Area", "NPC", "XP", "Gold Carried", "Pickpocket Skill", "Item Price (base)", "Item Type", "Item"] areas = [ "act04 (Spawned)", "act05 (Spawned)", "act06 (Spawned)", "actboun (Spawned)", "actnesto (Spawned)", "aldcut01 (Spawned)", "aldcut02 (Spawned)", "ar0004 - ...
def cap_text(text): ''' Input a String Output a Capitalized String ''' # return text.capitalize() return text.title()
# test to make sure that every brand in our file is at least 3 characters long with open('car-brands.txt') as f: result = all(map(lambda row: len(row) >= 3, f)) print(result) # => True # test to see if any line is more than 10 characters with open('car-brands.txt') as f: result = any(map(lambda row: len(row...
FUTEBOL = 'Futebol' VOLEI = 'Volei' NATACAO = 'Natacao' LUTA = 'Luta' ESPORTES_CAPACITADOS = [ (FUTEBOL, 'Futebol'), (VOLEI, 'Volei'), (NATACAO, 'Natação'), (LUTA, 'Luta'), ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # File Name: master.py # Description : # Author : SanYapeng # date: 2019-05-18 # Change Activity: 2019-05-18: name = "alex" def func(): print("我是func") class Person: def __init__(self, name, age): self.name = n...
# from log_utils.remote_logs import ( # post_output_log, post_build_complete, # post_build_error, post_build_timeout) class TestPostOutputLog(): def test_post_output_log(self): pass class TestPostBuildComplete(): def test_post_build_complete(self): pass class TestPostBuildError(): ...
""" A simple stock analyzer that collects data from 3 stock-listed company files (NASDAQ, NYSE, and AMEX), and parses it into a single delimited file where a user can search company data from all 3 file sources. Author: Oscar Lopez """ def clean_data(data): """ Removes any trailing new lines, replaces '"' wi...
# Small Pizza: $15 # Medium Pizza: $20 # Large Pizza: $25 # Pepperoni for Small Pizza: +$2 # Pepperoni for Medium or Large Pizza: +$3 # Extra cheese for any size pizza: + $1 print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L ") add_pepperoni = input("Do you want pepperon...
# # PySNMP MIB module FMX1830 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FMX1830 # Produced by pysmi-0.3.4 at Mon Apr 29 19:00:22 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)...
# # @lc app=leetcode id=78 lang=python3 # # [78] Subsets # # https://leetcode.com/problems/subsets/description/ # # algorithms # Medium (64.66%) # Likes: 5346 # Dislikes: 109 # Total Accepted: 728.5K # Total Submissions: 1.1M # Testcase Example: '[1,2,3]' # # Given an integer array nums of unique elements, retur...
""" CS241 Checkpoint 02B Written by Chad Macbeth """ ### Get file name from the user def get_filename(): filename = input("Enter file: ") return filename ### Open the file and analyze words and lines ### Returns a tuple (word count, line count) def read_file(filename): file_in = open(filename, "r") line_c...
REDIS_URL = 'redis://redis/0' ERROR_NO_IMAGE = 'Please provide an image' ERROR_NO_TEXT = 'Please provide some text' MAX_SIZE = (512, 512) # Where to store the models weights # (except for Keras' that are stored in ~/.keras) WEIGHT_PATH = './weights' # Original model source: https://drive.google.com/drive/folders/0B...
s = input() print(any(char.isalnum() for char in s)) print(any(char.isalpha() for char in s)) print(any(char.isdigit() for char in s)) print(any(char.islower() for char in s)) print(any(char.isupper() for char in s))
"""Kata url: https://www.codewars.com/kata/544675c6f971f7399a000e79.""" def string_to_number(s: int) -> int: return int(s)
# -*- coding: utf-8 -*- # @Author: jpch89 # @Email: jpch89@outlook.com # @Time: 2018/7/28 20:29 def convert_number(s): try: return int(s) except ValueError: return None
# This test verifies that __name__ == "__main__" works properly in Python Loader if __name__ == "__main__": print('Test: 1234567890abcd')
def run(): my_list = [1, 'Hi', True, 4.5] my_dict = { "first_name": "Hernan", "last_name": "Chamorro", } super_list = [ { "first_name": "Hernan", "last_name": "Chamorro",}, { "first_name": "Gustavo", "last_name": "Ramon",}, { "first_name": "Bruno", "last_name": "...
friends = ['Mark', 'Simona', 'Paul', 'Jeremy', 'Colin', 'Sophie'] counter = 0 for counter, friend in enumerate(friends, start=1): print(counter, friend) print(list(enumerate(friends))) print(dict(enumerate(friends)))
def removeElement_1(nums, val): """ Brute force solution Don't preserve order """ # count the frequency of the val val_freq = 0 for num in nums: if num == val: val_freq += 1 # print(val_freq) new_len = len(nums) - val_freq # remove the element from the list ...
print("Gerador de PA") inicio = int(input("Primeiro termo: ")) razao = int(input("Razão: ")) cont = 1 while cont <= 10: print(inicio, end=", " ) inicio += razao cont += 1 print("acabou !!")
""" 给定一个已按照**升序排列**的有序数组,找到两个数使得它们相加之和等于目标数 返回这两个数的index, 从1开始(不是从0开始) """ sample_numbers = [2, 7, 11, 15] def twoSum(array, target): # assume the array already been sorted low, high = 0, len(array) - 1 while low < high: result = array[low] + array[high] if result < target: low...
""" Building a Pie Chart A pie chart is a circular graphical representation of a dataset, where each category frequency is represented by a slice (or circular sector) with an amplitude in degrees given by the single frequency percentage over the total of frequencies. You can obtain the degrees of sectors following thes...
""" Programa 110 Área de estudos. data 08.12.2020 (Indefinida) Hs @Autor: Abraão A. Silva """ # Declaração e inicialização das variáveis compostas. codigo_objetos, relatorios = list(), list() # Imprimi a tabela, recolhe as informações, faz verificações de validez, por fim armazena. while True: print('{:-^46}...
# # @lc app=leetcode id=109 lang=python3 # # [109] Convert Sorted List to Binary Search Tree # # https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/ # # algorithms # Medium (49.90%) # Likes: 2801 # Dislikes: 95 # Total Accepted: 287.7K # Total Submissions: 568.6K # Testcase Exampl...
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Tests for shared flocker components. """
class Tree_node: def __init__(self,data): self.data = data self.parent = None self.left = None self.right = None def __repr__(self): return repr(self.data) def add_left(self, node): self.left = node if node is not None: node.parent = sel...
""" Write a function that satisfies the following rules: Return true if the string in the first element of the list contains all of the letters of the string in the second element of the list. """ def mutation(input_list): short, long = sorted(map(lambda l: l.lower(), input_list), key=lambda item: len(item)) ...
class Solution(object): def numberOfBeams(self, bank): """ :type bank: List[str] :rtype: int """ beams = 0 bank_len = len(bank) if bank_len == 1: return 0 else: i = 0 j = 1 while(j < bank_len): ...
def fatorial(num, show=False): ''' -> calcula o fatorial de um número :param num: o número a ser calculado :param show: (opcional) mostrar ou não a conta :return: o valor fatorial de um número num ''' f = 1 for c in range(num, 0, -1): f = f * c if show == True: ...
class RegularExpression(): def __init__(self, regexStr): self.regexStr = regexStr def __str__(self): return self.regexStr
# @Fábio C Nunes - 24.06.20 def ficha(nome='<Desconhecido>', gols= 0): print(f'O Jogador {nome} fez {gols} gols no campeonato.') #Main n = str(input('Nome do jogador: ')) gol = str(input('Nº de gols: ')) if gol.isnumeric(): gol = int(gol) else: gol = 0 if n.strip() == '': ficha(gols=gol) else: fich...
def pythonic_solution(S, P, Q): I = {'A': 1, 'C': 2, 'G': 3, 'T': 4} # Obvious solution, scalable and compact. But slow for very large S # with plenty of entropy. result = [] for a, b in zip(P, Q): i = min(S[a:b+1], key=lambda x: I[x]) result.append(I[i]) return result def pr...
class shapeCharacter: rotationNumber = 1 def moveRight(self): self.x1 = self.x1 + 1 self.x2 = self.x2 + 1 self.x3 = self.x3 + 1 self.x4 = self.x4 + 1 self.cordinates = [(self.y1,self.x1), (self.y2,self.x2), (self.y3,self.x3), (self.y4,self.x4)] self.rotationCord...
""" My implementation of fizzbuzz. """ def fizzbuzz(number): if number % 3 == 0 and number % 5 == 0: print ('fizzbuzz') elif number % 3 == 0: print ('fizz') elif number % 5 != 0: print ('buzz') if __name__ == '__main__': fizzbuzz(15)
# class Solution(object): # def isValid(self, s): # class Solution: def isValid(self, s): stack = [] dic = {']' :'[', '}':'{', ')':'('} for c in s: if c in dic.values(): stack.ap...
''' Project: SingleLinkedList File: SingleLinkedList.py Author: Sanjay Vyas Description: Implementation of a simple linked list in Python Revision History: 2018-November-17: Initial Creation Copyright (c) 2019 Sanjay Vyas License: This code is meant for learning algorithms and writing clean c...
""" [2015-12-09] Challenge #244 [Easy]er - Array language (part 3) - J Forks https://www.reddit.com/r/dailyprogrammer/comments/3wdm0w/20151209_challenge_244_easyer_array_language_part/ This challenge does not require doing the previous 2 parts. If you want something harder, the rank conjunction from Wednesday's chal...
#MODIFICANDO UMA TUPLA tpl_values = (10, 14, 16, 20) try: tpl_values[1] = 26 except (TypeError) as err: print(f"Error: {err}") #ALTERANDO LISTA DENTRO DE UMA TUPLA tpl_values = (10, 14, 16, 20, [24,26]) try: tpl_values[4].append(30) print(tpl_values) except (TypeError) as err: print(f"Error: {er...
# -*- coding: utf-8 -*- def __download(core, filepath, request): request['stream'] = True with core.request.execute(core, request) as r: with open(filepath, 'wb') as f: core.shutil.copyfileobj(r.raw, f) def __extract_gzip(core, archivepath, filename): filepath = core.os.path.join(core....
if __name__ == '__main__': try: main() log.info("Script completed successfully") except Exception as e: log.critical("The script did not complete successfully") log.exception(e) sys.exit(1)
# Birthday Wishes # Demonstrates keyword arguments and default parameter values # День рождения # Демонстрирует именованные аргументы и значения параметров по умолчанию # positional parameters # позиционные параметры def birthday1(name, age): print("С днём рождения, ", name, "!", " Вам сегодня исполняется ", age,...
bind = '127.0.0.1:8000' workers = 3 user = 'web' timeout = 120
user_input = input("Input two words separated by space to create key value pairs, or enter nothing to quit") empty_dict = {} while user_input != "": words = user_input.split(" ") if len(words) >= 2: empty_dict[words[0]] = words[1] else: print("not enough words to create an entry") user_i...
class Snapshot: def __init__(self, state: any, index: int): self.state = state self.index = index class RecoverSnapshot(Snapshot): def __init__(self, data: any, index: int): super().__init__(data, index) class PersistedSnapshot(Snapshot): def __init__(self, data: any, index: int)...
'''Instructions Congratulations, you've got a job at Python Pizza. Your first job is to build an automatic pizza order program. Based on a user's order, work out their final bill. Small Pizza: $15 Medium Pizza: $20 Large Pizza: $25 Pepperoni for Small Pizza: +$2 Pepperoni for Medium or Large Pizza: +$3 Extra ch...
def positive_sum(arr): positive_list = [] for i in arr: if i > 0: positive_list.append(i) return(sum(positive_list)) # Best Practices def positive_sum(arr): return sum(x for x in arr if x > 0)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`orion.core.cli.checks.presence` -- Presence stage for database checks =========================================================================== .. module:: presence :platform: Unix :synopsis: Checks for the presence of a configuration. """ class Pres...
''' We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. Example 1: Input: A = 'abc...