content
stringlengths
7
1.05M
def file_name_for_format(file_format): names = { 'json': 'data', 'xlsx': 'catalog' } file_name = names[file_format] return file_name
def main(request, response): location = request.GET.first(b"location") if request.method == u"OPTIONS": if b"redirect_preflight" in request.GET: response.status = 302 response.headers.set(b"Location", location) else: response.status = 200 response.hea...
# set random number generator np.random.seed(2020) # initialize step_end, t_range, v and syn step_end = int(t_max / dt) t_range = np.linspace(0, t_max, num=step_end) v = el * np.ones(step_end) syn = i_mean * (1 + 0.1 * (t_max/dt) ** (0.5) * (2 * np.random.random(step_end) - 1)) # loop for step_end - 1 steps for step...
##Patterns: E0107 def test(): a = 1 ##Err: E0107 ++a ##Err: E0107 --a
# # PySNMP MIB module BIANCA-BRICK-OSPF-ERR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BIANCA-BRICK-OSPF-ERR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:21:24 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
""" File: complement.py ---------------------------- This program uses string manipulation to tackle a real world problem - finding the complement strand of a DNA sequence. THe program asks uses for a DNA sequence as a python string that is case-insensitive. Your job is to output the complement of it. """ def main():...
def deep_index(lst, w): return [[i, sub.index(w)] for (i, sub) in enumerate(lst) if w in sub] class variable(): def __init__(self, name, val): self.name = name self.val = val class variableHandler(): def __init__(self): self.varList = [] def create(self, varName, varVal): ...
#!/usr/bin/python3 # code for AdventOfCode day 1 http://adventofcode.com/2017/day/1 # get user input WITHOUT validation # the code will fail when repeating non numeric chars input_seq = input() # append first algarism to the end of a new 'extended' # that way we can use a single 'for' loop for everything input_seq_...
class Player: next_id = 1 def __init__(self, name, corp_id=None, runner_id=None): self.id = Player.next_id Player.next_id += 1 self.name = name self.corp_id = corp_id self.runner_id = runner_id self.score = 0 self.sos = 0 self.esos = 0 se...
word = input('Enter a word') letter = input('Enter a letter') def count(word, letter): counter = 0 for character in word: if character == letter: counter = counter + 1 print(counter) count(word, letter)
''' Implement a function which takes as input a string s and returns true if s is a palindromic string. ''' def is_palindrome(s): # Time: O(n) # i moves forward, and j moves backward. i, j = 0, len(s) - 1 while i < j: # i and j both skip non-alphanumeric characters. while not s[i].isalnum...
def game(player1, player2): history = [] while len(player1) != 0 and len(player2) != 0: state = {'player1': player1.copy(), 'player2': player2.copy()} if state in history: return True, player1 + player2 history.append(state) num1 = player1.pop(0) num2 = player...
#!/usr/bin/env python3 ###################################################################################### # # # Program purpose: Creates a string made of the first 2 and the last 2 chars # # from a gi...
''' Copyright (©) 2021 Kiet Pham <kiet.riley2005@gmail.com> This software/program has a copyright license, more information is in the 'LICENSE' file IF YOU WANT TO USE/COPY/MODIFY/REPRODUCE/RE-DISTRIBUTE THIS PROGRAM, YOU MUST INCLUDE A COPY OF THE LICENSE Author Name: Kiet Pham Author Contact: kiet.riley2005@gmail.co...
# Program to implement Affine Cipher for encryption and decryption #returns gcd of two numbers def gcd(num1, num2): if num2 == 0: return num1 return gcd(num2, num1 % num2) #returns the inverse of a number if it exists, else '-1', under mod def inverse(number, mod): if gcd(number, mod) != 1: ...
# coding=utf-8 # autogenerated using ms_props_generator.py PROPS_ID_MAP = { "0x0001": {"data_type": "0x0102", "name": "TemplateData"}, "0x0002": {"data_type": "0x000B", "name": "AlternateRecipientAllowed"}, "0x0004": {"data_type": "0x0102", "name": "ScriptData"}, "0x0005": {"data_type": "0x000B", "name"...
try: with open("input.txt", "r") as fileContent: segments = [[segment.split(" -> ")] for segment in fileContent.readlines()] segments = [tuple([int(axis) for axis in coordinate.strip().split(",")]) for segment in segments for coordinates in segment for coordin...
def return_rate_limit(github): rate_limit = github.get_rate_limit() rate = rate_limit.rate return rate.remaining
# https://leetcode.com/problems/count-and-say/description/ # # algorithms # Hard (27.1%) # Total Accepted: 165.2k # Total Submissions: 609.6k # beats 100.0% of python submissions # 我的方法是采用位运算来做,用bit串的每一位来指代一个positive num class Solution(object): def firstMissingPositive(self, nums): """ :type num...
""" Determine whether an integer is a palindrome. Do this without extra space. A palindrome integer is an integer x for which reverse(x) = x where reverse(x) is x with its digit reversed. Negative numbers are not palindromic. Example : Input : 12121 Output : True Input : 123 Output : False """ class Solution: ...
class Node: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def __str__(self): return str(self.key) def print_path(path): s = "" for p in path: s += str(p) + " " print(f"{s}\n---") def paths_with_sum(ro...
a = 35 b = 7 print("a % b =", a % b)
# -*- coding: utf-8 -*- """ Created on Thu Jul 9 09:42:41 2020 @author: sv """ #num_obj = 4 #for idx in range(1,num_obj): # print('idx = ', idx) path = 'assets/obj_name.txt' objname_list = [] count = 0 objfile = open(path, 'r') Lines = objfile.readlines() for line in Li...
class Car: """ Docstring describing the class """ def __init__(self, car_name) -> None: self.car_name = car_name def __str__(self) -> str: return f"Soh uma string mano {self.car_name}" def anda(self): return f"Anda {self.car_name}" car = Car("ecosport") print(car.and...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com). { "name": "Panama - Accounting", "description": """ Panamenian accounting chart and tax localization. Plan contable panameño e impuestos de ...
def valid_parentheses(s): if not s: return True elif len(s) == 1: return False d = {"(": ")", "{": "}", "[": "]"} stack = [] for bracket in s: if bracket in d: stack.append(bracket) elif d[stack.pop()] != bracket: return False return len...
#!/usr/bin/env python3 # # Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # DOH_URI = '/.well-known/dns-query' DOH_MEDIA_TYPE = 'application/dns-udpwireformat' DOH_CONT...
"""" Practice File 3 Created By David Story Description: All about bit operators! """ # Some basic examples of hex, dec, and bin in Python print("Example Using 0xAA:") hexvalue = 0xAA print(hex(hexvalue)) print(int(hexvalue)) print(bin(hexvalue)) print("Example Using decimal 65:") decimal = 65 print(int(decimal)) pr...
class Complex(object): """Class to save the complex file""" def __init__(self, id, filename): """Creator of Complex class Arguments: - id - string, the id of the complex - filename - string, the file name of the complex """ self.id = id self.chain_dict =...
load("//ruby/private:constants.bzl", "RULES_RUBY_WORKSPACE_NAME") load("//ruby/private:providers.bzl", "RubyRuntimeContext") DEFAULT_BUNDLER_VERSION = "2.1.2" BUNDLE_BIN_PATH = "bin" BUNDLE_PATH = "lib" SCRIPT_INSTALL_BUNDLER = "download_bundler.rb" SCRIPT_ACTIVATE_GEMS = "activate_gems.rb" SCRIPT_BUILD_FILE_GENERATO...
# Designing window for login def login(): global login_screen login_screen = Toplevel(main_screen) login_screen.title("Login") login_screen.geometry("300x250") Label(login_screen, text="Please enter details below to login").pack() Label(login_screen, text="").pack() global username_verify...
def solution(n, times): leftLim = 1; rightLim = max(times) * n; answer = max(times) * n while leftLim <= rightLim: # print(leftLim, rightLim) lim = (leftLim + rightLim)//2; check = sum([lim//time for time in times]) if check >= n: answer = min(answer, lim) rightLim...
def resta(num_1, num_2): print('Restando:', num_1, '-', num_2) resta_total = num_1 - num_2 print('El resultado es:',resta_total) return resta_total def app_resta(): inp_1 = None # Can be used 'None' instead of 0 too inp_2 = None while inp_1 == None: try: inp_1 = int(inp...
""" pyifc.compress._exceptions -------------------------- Exceptions used in pyifc.compress module. """ class FileExtensionError(Exception): """ Raised when extension of the file is not correct. """ pass
class User: """ Class that generates new instances of contacts """ def __init__(self,user_name, password): """ This will construct an object of the instance of the class user """ self.user_name = user_name self.password = password user_list = [] #This is the...
def cycleSort(array, *args): for cycle_start in range(0, len(array) - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, len(array)): if array[i] < item: pos += 1 if pos == cycle_start: continue w...
class FileStream(Stream,IDisposable): """ Exposes a System.IO.Stream around a file,supporting both synchronous and asynchronous read and write operations. FileStream(path: str,mode: FileMode) FileStream(path: str,mode: FileMode,access: FileAccess) FileStream(path: str,mode: FileMode,access: FileAccess,...
aI, aO, aT, aJ, aL, aS, aZ = map(int, input().split()) ans = aO p = [aI, aJ, aL] for i in range(3): if p[i] >= 2: if p[i] % 2 == 0: ans += (p[i] - 2) // 2 * 2 p[i] = 2 else: ans += p[i] // 2 * 2 p[i] = 1 p.sort() if sum(p) >= 5: ans += sum(p) // 2 ...
class Solution: def twoSum(self, nums , target) : # a python dictionary(hash) # key is number # value is index of list: nums number_dictionary = dict() for index, number in enumerate(nums): # put every number into dictionary...
""" 0693. Binary Number with Alternating Bits Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary r...
""" Anfang des Algorithmus """ def mergeSort(list): # überprüft, ob die Länge der übergebenen Liste größer als 1 ist if len(list) > 1: # länge der Liste n = len(list) # mitte der Liste mitte = n //2 # linke hälfte der Liste linke_haelfte = list[:mitt...
n = int(input("Enter the number : ")) fact = 1 for i in range(1,n + 1): fact = fact * i print("Factorial of {} is {}".format(n,fact))
""" This module contains all the string constants defined for this repo. """ """ Regex declarations used in Web Info module. """ RE_VISITORS = "^> (.*?) visitors per day <$" RE_IP_V6 = "IPv6.png'><a href='\/info\/whois6\/(.*?)'>" RE_IP_LOCATION = "IP Location: <\/td> <td class='vmiddle'><span class='cflag (.*?)'><\/spa...
pkgname = "lua5.4-zlib" pkgver = "1.2" pkgrel = 0 build_style = "makefile" make_build_target = "linux" hostmakedepends = ["pkgconf"] makedepends = ["lua5.4-devel", "zlib-devel"] pkgdesc = "Zlib streaming interface for Lua (5.4)" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "https://github.com/brimwo...
# TempConv.py # Celcius to Fahreinheit def Fahreinheit(temp): temp = float(temp) temp = (temp*9/5)+32 return temp # Fahreinheit to Celcius def Celcius(temp): temp = float(temp) temp = (temp-32)*5/9 return temp
friends = ["Sam","Samantha","Saurab"] start_with_s = [x for x in friends if x.startswith("S")] #compare list friends and start_with_s, bot are same value but result should be false. #Because two are different list print(friends is start_with_s) print("friends : ", id(friends)," start_with_s : ",id(start_with_s)) #if...
# La longitud de la lista es N-1. Entonces, la suma de todos los N elementos, es decir, la suma de los números de 1 a N # se puede calcular usando la fórmula n * (n + 1) / 2. Encontramos la suma de todos los elementos de la lista y la # restamos de la suma de los primeros N números naturales, el resultado de la resta s...
# -*- coding: UTF-8 -*- def value_judge(request, *args): # 查看客户端有没有漏传字段 for i in args: if i not in request.data or request.data.get(i) == '' or request.data.get(i) is None: return False return True
#!/usr/bin/python3 # 100-weight_average.py def weight_average(my_list=[]): """Return the weighted average of all integers in a list of tuples.""" if not isinstance(my_list, list) or len(my_list) == 0: return (0) avg = 0 size = 0 for tup in my_list: avg += (tup[0] * tup[1]) ...
"""" entradas preciocomputador-->P-->float valorcuotas-->T-->float salidas porcentajerecargo-->por-->float """ #entradas P=float(input("Ingrese el precio del computador: ")) T=float(input("Ingrese el valor de las cuotas: ")) #caja negra tc=T*12 r=tc-P por=(r*100)/P #salidas print("El porcentaje de recargo es del ",...
class MSDocument(object): def setZoomValue(self, zoomLevel): """ Zoom the document. 1.0 represents actual size, 2.0 means 200% etc. """ # Not implemented pass def export(self): """ Takes you to the the export tool. Pass nil as the argument. """ ...
#Escreva um programa que leia um inteiro não negativo n e #imprima a soma dos n primeiros números primos. primo=[] n=int(input("Informe um numero: ")) if(n>0): for c in range(1,n+1): i=0 for u in range(1,c+1): if(c%u==0): i+=1 if(i<=2): print(c) ...
# -*- coding: utf-8 -*- """ pygments.console ~~~~~~~~~~~~~~~~ Format colored console output. :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ esc = "\x1b[" codes = {} codes[""] = "" codes["reset"] = esc + "39;49;00m" ...
## Given a position, write a function to ## find if that position is within 5 points of a monster: a_treasure_map = { "45,46": "sea monster", "55,38": "air monster", "33,78": "lava monster", "22,23": "shining castle", "64,97": "shield of truth", "97,3": "sword of power", } def near_monster(position, a_trea...
def batch_iterator(iterable, batch_size): iterator = iter(iterable) iteration_stopped = False while True: batch = [] for _ in range(batch_size): try: batch.append(next(iterator)) except StopIteration: iteration_stopped = True ...
""" Constants file for wiating backend """ AUTH0_CLIENT_ID = 'AUTH0_CLIENT_ID' AUTH0_DOMAIN = 'AUTH0_DOMAIN' AUTH0_CLIENT_SECRET = 'AUTH0_CLIENT_SECRET' AUTH0_CALLBACK_URL = 'AUTH0_CALLBACK_URL' AUTH0_AUDIENCE = 'AUTH0_AUDIENCE' SECRET_KEY = 'SECRET_KEY' S3_BUCKET = 'S3_BUCKET' ES_CONNECTION_STRING = 'ES_CONNECTION_STR...
def cuberoot2(x0): x = x0 i = 0 while True: nextIt = (1/3)*(2*x+2/(x**2)) if (abs(nextIt - x) <= 10**-7): break else: i += 1 x = nextIt print("The sequence starting at", x0, "converges to", x,"in", i, "iterations.") cuberoot2(20) def nesty(x): f = (x - 1) ** 5 g = x ** 5 - 5 ...
""" Module: 'machine' on micropython-rp2-1.15 """ # MCU: {'family': 'micropython', 'sysname': 'rp2', 'version': '1.15.0', 'build': '', 'mpy': 5637, 'port': 'rp2', 'platform': 'rp2', 'name': 'micropython', 'arch': 'armv7m', 'machine': 'Raspberry Pi Pico with RP2040', 'nodename': 'rp2', 'ver': '1.15', 'release': '1.15.0'...
# add a key to a dicitonary # Sample dictionary: {0:10,1:20} # Expected Result: {0:10,1:20,2:30} a={0:10,1:20} a[2]=30 print(a)
# 이 코드의 오류를 수정하고 아래 설명에 따라 테스트하세요. # 2.00을 입력하면 "Tax rate is : 0.07" 을 출력하세요. # 1.00을 입력하면 "Tax rate is : 0.07" 을 출력하세요. # 0.50을 입력하면 "Tax rate is : 0" 을 출력하세요. price = input('how much did you pay? ') price = float(price) if price >= 1.00: tax = .07 print('Tax rate is: ' + str(tax)) else: tax = 0 print...
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Scott Burns <sburns@nmr.mgh.harvard.edu> # # License: BSD (3-clause) def parse_config(fname): """Parse a config file (like .ave and .cov files) Parameters ---------- fname : string config file name Returns...
add_user_permissions_response = { 'user': 'enterprise_search', 'permissions': ['permission1'] }
# # Function for program annotation-to-outline. Responsible for writing the # LaTex structure to file. # def writeToLatex(fileName, outlineContents, defContents, titleContents): # Write contents to .tex file f = open(fileName, 'w') # file object # write LaTex preamble to file f.write("\\documentcla...
dist1={0: 460146, 1: 211769, 2: 89768, 3: 41207, 4: 21465, 5: 10368, 6: 6336, 7: 3640, 8: 2378, 9: 1440, 10: 1068, 11: 694, 12: 483, 13: 336, 14: 237, 15: 155, 16: 153, 17: 128, 18: 94, 19: 81, 20: 123, 21: 71, 22: 89, 23: 40, 24: 44, 25: 43, 26: 25, 27: 15, 28: 19, 29: 19, 30: 23, 31: 19, 32: 6, 33: 13, 34: 8, 35: 3, ...
a = str(input('Digite: ')) def temLetra_a(a): if('a' in a): return True else: return False variavel = temLetra_a(a) if variavel == True: print('tem letra A') elif variavel == False: print('Não tem letra {}'.format(a)) else: print('...') ''' testando outros módulos ''' def fu...
# def get_words(sentence): # return list(filter((lambda x: len(str(x)) > 0), str(sentence).split(sep=' '))) # # # def get_word_count(sentence): # return get_words(sentence).count() def get_word_freq_in_sentences(word, sentences): """ :param word: the word which frequency we calculate :para...
class SpaceAge: def __init__(self, seconds: float): self.seconds = seconds def _space_age(self, ratio: float = 1.0, ndigits: int = 2) -> float: return round(self.seconds / 31557600.0 / ratio, ndigits) def on_mercury(self) -> float: return self._space_age(0.2408467) def on_ven...
# This program demonstrates the repetition operator. def main(): # Print nine rows increasing in length. for count in range(1, 10): print('Z' * count) # Print nine rows decreasing in length. for count in range(8, 0, -1): print('Z' * count) # Call the main function. main()
"""Definitions for using tools like saved_model_cli.""" load("//tensorflow:tensorflow.bzl", "clean_dep", "if_xla_available") load("//tensorflow:tensorflow.bzl", "tfcompile_target_cpu") load("//tensorflow/compiler/aot:tfcompile.bzl", "target_llvm_triple") def _maybe_force_compile(args, force_compile): if force_com...
#num = 1 # #while num < 10: # print(num) # num = num+1 #nome = 'cecilia' # #for letra in nome: # print(letra) #for num in range(1,6): # print(num) lista = [1,2,3,4,5,6] for num in lista: print(num)
s = input('as: ') print(s)
class Solution: def match(self, pattern, strs): words = strs.split() patterns = list(pattern) patternList = self.getPattern(patterns) wordList = self.getPattern(words) return patternList == wordList def getPattern(self, strList): index = 1 tmpDict = {} ...
def getAverageOverPercentage(n, score): avg = sum(score) / n std = 0 for i in score: if i > avg: std += 1 return round(std / n * 100, 3) for _ in range(int(input())): data = list(map(int, input().split())) result = getAverageOverPercentage(data[0], data[1:]) print("%.3f"%result + '%')
# We explicitly test here that the constructor is not included in the signatures. @abstract class Abstract: x: int def __init__(self, x: int) -> None: self.x = x __book_url__ = "dummy" __book_version__ = "dummy"
# • Define una clase Estudiante en el que almacenamos # el nombre y un diccionario cuyas claves son # asignaturas a las que asociamos calificaciones. # • Un estudiante recibe nombre al ser construido, # pero nada más. # • Si e es un estudiante, con e.califica(‘EI1022’, 10) le # asignamos un 10 a la asignatura EI1022. C...
__author__ = 'chira' # for-loop : when number of iterations known # while-loop : when iteration depends on condition for i in range(5,10): print(i) print("------------"); i = 5 while i < 10: print(i) i += 1 print("------------");
class keyBox: def __init__(self): self.wallet_addresses = [] self.private_keys = [] #for testing self.private_keys.append(b'p.Oids\xedb\xa3\x93\xc5\xad\xb9\x8d\x92\x94\x00\x06\xb9\x82\xde\xb9\xbdBg\\\x82\xd4\x90W\xd0\xd5') self.private_keys.append(b'\x16\xc3\xb37\xb8\x8aG`\xdf\xad\xe3},\x9a\xb4...
"""Dude Middleware.""" class ClacksOverhead(object): """Inject HTTP headers into your response.""" def __init__(self, app, *headers, **kwargs): """Initialize the header injector.""" self.app = app self.headers = (headers or ( ('X-Clacks-Overhead', 'GNU'), )) + tupl...
for i in range(1, 6): for j in range(1, i + 1): print('* ', end='') print() for i in range(4, 0, -1): for j in range(1, i + 1): print('* ', end='') print()
class Node: def __init__(self, val): self.val = val self.next = None # Single List, without sentinel node # class MyLinkedList: # # def __init__(self): # """ # Initialize your data structure here. # """ # self.header = None # self.size = 0 # # def ge...
class Solution: # @param num, a list of integer # @return an integer def findPeakElement(self, num): l, r = 0, len(num)-1 while l < r: m = (l+r) / 2 if m == 0 or num[m] > num[m-1]: if m == r or num[m] > num[m+1]: return m ...
OPENSEARCH_GIT_RAW = "gits" OPENSEARCH_GIT_GITHUB_CLEAN = "git_github_clean" OPENSEARCH_INDEX_GITHUB_COMMITS = "github_commits" OPENSEARCH_INDEX_GITHUB_ISSUES = "github_issues" OPENSEARCH_INDEX_GITHUB_ISSUES_COMMENTS = "github_issues_comments" OPENSEARCH_INDEX_GITHUB_ISSUES_TIMELINE = "github_issues_timeline" OPENSEAR...
Dataset_Path = dict( CULane = "/workspace/CULANE_DATASET", Tusimple = "/workspace/TUSIMPLE_DATASET", bdd100k = "/workspace/BDD100K_DATASET" )
"""Routes config.""" def includeme(config): """All routes for the app.""" config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('results', '/results/{id:\w+}') config.add_route('about', '/about')
code = [input() for _ in range(610)] for i in range(len(code)-1): if code[i][:3] == 'jmp': code[i] = 'nop' + code[i][3:] elif code[i][:3] == 'nop': code[i] = 'jmp' + code[i][3:] instr_idx = 0 acc_value = 0 executed_ops = set() while instr_idx not in executed_ops and instr_idx ...
class Solution: def maxRotateFunction(self, A): """ :type A: List[int] :rtype: int """ mx, sm = 0, sum(A) for i in range(len(A)): mx += i * A[i] curr = mx for i in range(1, len(A)): curr = curr - sm + A[i - 1] * len(A) ...
"""Multiplication Table, by Al Sweigart al@inventwithpython.com Print a multiplication table. This and other games are available at https://nostarch.com/XX Tags: tiny, beginner, math""" __version__ = 0 print('Multiplication Table, by Al Sweigart al@inventwithpython.com') # Print the horizontal number labels: print(' ...
array = [1,2,3,4,5] result = [5,1,4,2,3] # in-place replacement def rearrange_sorted_max_min_2(arr): max_index = len(arr) - 1 min_index = 0 max_elem = arr[max_index] + 1 # orig element of stored as remainder, max or min element stored # as multiplier, this allows to swap numbers in place, finally...
n = int(input()) sv = sq = 0 for i in range(n): sv += float(input()) q = len(str(input()).split()) sq += q print('day {}: {} kg'.format(i + 1, q)) print('{:.2f} kg by day'.format(float(sq / n))) print('R$ {:.2f} by day'.format(float(sv / n)))
#Print PY print("teste") print("RR", 1, "RRR", 3, sep="\n") print("RR", 3, "RRR", 3, end="\n") #sep é o separador entre os valores, por padrão o separador é um espaço em branco. #end é o que acontecerá ao final da função, por padrão há uma quebra de linha, uma nova linha (\n). #O Python utiliza por convenção o ...
# variables dependent on your setup boardType = "atmega2560" # atmega168 | atmega328p | atmega2560 | atmega1280 | atmega32u4 comPort = "COM3" # com4 for atmega328 com8 for mega2560 SHIFT = 47 LATCH = 48 DATA = 49 # start Arduino service named arduino arduino = Runtime.createAndStart("arduino", "Arduino") arduino.se...
airline = pd.read_csv('data/international-airline-passengers.csv', parse_dates=['Month'], sep=';') airline.set_index('Month', inplace=True) ax = airline.plot(legend=False) ax.set_xlabel('Date') ax.set_ylabel('Passengers')
n=int(input()) if n>=0: sum=int((n*(n+1))/2) print(sum) else: print("Invalid Input")
"""InterviewBit. Programming > Arrays > Min Steps In Infinite Grid. """ class Solution: """Solution.""" # @param A : list of integers # @param B : list of integers # @return an integer def coverPoints(self, A, B): """Cover points.""" x, y = A[0], B[0] steps = 0 fo...
def moving_average(timeseries, k): result = [] for begin_index in range(0, len(timeseries) - k): end_index = begin_index + k current_sum = 0 for v in timeseries[begin_index:end_index]: current_sum += v current_avg = current_sum / k result.append(curren...
# Array # Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). # # Example 1: # Input: [1,3,5,4,7] # Output: 3 # Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. # Even though [1,3,5,7] is also an increasing subsequence, it...
class Cord: homepage = ( 1, 42, 529,984 ) question = ( 42,317,519,426 ) answer1 = ( 48,487,510,558 ) answer2 = ( 48,573,510,645 ) answer3 = ( 48,660,510,732 ) answer1_clk = ( 94,524 ) answer2_clk = ( 94,609 ) answer3_clk = ( 94,694 )
#Exercise 4-2 - Animals animals = ['lion', 'tiger', 'cat'] for animal in animals: print(animal.title(), "it's a feline.") print('Only one is a great pet.')
class ICustomFactory: """ Enables users to write activation code for managed objects that extend System.MarshalByRefObject. """ def CreateInstance(self, serverType): """ CreateInstance(self: ICustomFactory,serverType: Type) -> MarshalByRefObject Creates a new instance of the specifie...
PICTURE_DEFAULT = { "image": { "url": str, "name": str }, "thumbnail": { "url": str, "name": str } }