content
stringlengths
7
1.05M
"""Libpdf exceptions.""" class LibpdfException(Exception): """Generic libpdf exception class."""
N = float(input()) if N >= 0 and N <= 25: print('Intervalo [0,25]') elif N > 25 and N <= 50: print('Intervalo (25,50]') elif N > 50 and N <= 75: print('Intervalo (50,75]') elif N > 75 and N <= 100: print('Intervalo (75,100]') else: print('Fora de intervalo')
# Write a function called delete_starting_evens() that has a parameter named lst. # The function should remove elements from the front of lst until the front of the list is not even. The function should then return lst. # For example if lst started as [4, 8, 10, 11, 12, 15], then delete_starting_evens(lst) should retur...
c = float(input('Informe a temperatura em C: ')) f = (c * 9/5)+ 32 print('A temperatura de {}°C corresponde a {}°F!'.format(c,f))
db_config = { 'host':'', #typically localhost if running this locally 'port':'', #typically 3306 if running a standard MySQl engine 'user':'', #mysql user with full privileges on the DB 'pass':'', #password of the mysql user 'db':''} #database in which all tables will be stored (must be already created)
squares = [1, 4, 9, 16, 25] print(squares) # [1, 4, 9, 16, 25] print(squares[0]) # 1 print(squares[-1]) # 25 cubes = [1, 8, 27, 65, 125] cubes[3] = 64 print(cubes) # [1, 8, 27, 64, 125] cubes.append(216) cubes.append(7 ** 3) print(cubes) # [1, 8, 27, 64, 125, 216, 343] print(8 in cubes) # True print(None in c...
REPOSITORY_LOCATIONS = dict( bazel_gazelle = dict( sha256 = "be9296bfd64882e3c08e3283c58fcb461fa6dd3c171764fcc4cf322f60615a9b", urls = ["https://github.com/bazelbuild/bazel-gazelle/releases/download/0.18.1/bazel-gazelle-0.18.1.tar.gz"], ), bazel_skylib = dict( sha256 = "2ef429f5d7ce7...
# 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): num = input(msg) if num.isnumeric(): return int(num) else: ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head): return nodeSwap(head) def nodeSwap(head): if head and head.next is None: return head count = 1 ...
# Strings normal_string = 'you will see a \t tab' print(normal_string) raw_string = r"you won't see a \t tab" print(raw_string) content = ['Joe', 26] format_string = f"His name's {content[0]} and he's {content[1]}." print(format_string) # Numbers # to be continued..
# static qstrs, should be sorted # extracted from micropython/py/makeqstrdata.py static_qstr_list = [ "", "__dir__", # Put __dir__ after empty qstr for builtin dir() to work "\n", " ", "*", "/", "<module>", "_", "__call__", "__class__", "__delitem__", "__enter__", "_...
# To raise an exception, you can use the 'raise' keyword. # Note that you can only raise an object of the Exception class or its subclasses. # Exception is an inbuilt class in python. # To raise subclasses of Exception(custom Exception) we have to create our own custom Class. # We can also pass message along with exc...
# CANDY REPLENISHING ROBOT n,t = [int(a) for a in input().strip().split()] Ar = [int(a) for a in input().strip().split()] i = 0 c = n count = 0 while t: #print(c) if c<5: count += (n-c) c += (n-c) #print(count) c -= Ar[i] t -= 1 i += 1 print(count)
a = float(input('Nhập a: ')) b = float(input('Nhập b: ')) c = float(input('Nhập c: ')) if a + b <= c or b + c <= a or c + a <= b: print(f"Ba số {a, b, c} Không phải là độ dài các cạnh của một tam giác.") else: if a**2 + b**2 == c**2 or b**2 + c**2 == a**2 or c**2 + a**2 == b**2: print(f"Ba số {...
''' Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example: Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4 ''' # 2018-10-19 # 221. maximal-square # https://leetcode.com/problems/maximal-square/ """ # https://blog.csdn.net/u012501459/art...
class Solution(object): def minPatches(self, nums, n): """ :type nums: List[int] :type n: int :rtype: int """ i = 0 patches = 0 miss = 1 while miss <= n: if i < len(nums) and nums[i] <= miss: miss += nums...
c = ["red", "blue", "yellow"] # 変数cの値が変化しないように訂正してください c_copy = c[:] c_copy[1] = "green" print(c)
class Benchmark(): def __init__(self): super().__init__() #Domain should be a list of lists where each list yields the minimum and maximum value for one of the variables. pass def calculate(self, x_var, y_var): pass def clip_to_domain(self, x_var, y_var): if...
# # PySNMP MIB module HUAWEI-L3VPN-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-L3VPN-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:45:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
# Exercício Python 059 # Leia 2 valores e mostre um menu # [1] somar # [2] multiplicar # [3] maior # [4] novos números # [5] sair do programa maior = 0 a = int(input('Digite o primeiro valor: ')) b = int(input('Digite o segundo valor: ')) escolha = int(input('Digite o que quer fazer:\n' '[1] Somar\...
class Subscriber: def __init__(self, name): self.name = name def update(self, message): print(f'{self.name} got message {message}')
class RedisConnectionMock(object): """ Simple class to mock a dummy behaviour for Redis related functions """ def zscore(self, redis_prefix, day): pass def zincrby(self, redis_prefix, day, amount): pass
""" LC735 Asteroid Collision We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the a...
class Point: def __init__(self,x,y,types,ide) -> None: self.x = x self.y = y self.type = types self.id = ide def getID(self): return self.id def getX(self): return self.x def getY(self): return self.y def getType(self): ret...
class Solution(object): def longestWord(self, words): """ :type words: List[str] :rtype: str """ wset = set(words) res = "" for w in words: isIn = True for i in range(1, len(w)): #check if all subwords in if w[:i] not i...
#!/usr/bin/env python3 # ## Code: def get_kth_prime(n:int)->int: # By Trial and Error, find the uppper bound of the state space max_n = 9*10**6 # Declare a list of bool values of size max_n is_prime = [True]*max_n # We already know that 0 and 1 are not prime is_prime[0], is_prime[1] = Fal...
#!/usr/bin/env python """actions.py Contains actions for interaction board state """
lista=[ { "id":0, "name":"tornillos", "precio": 10, "stock": 100 } ] while True: comando=int(input("Ingrese comando\n0:listar articulos\n1:consultar stock\n2:añadir articulo\n3:modificar stock\n\n")) if(comando==0): print("hay " + str(len(lista)) + " articulos: "...
# https://leetcode-cn.com/problems/swap-nodes-in-pairs/ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution1: ''' Date: 2022.04.26 Pass/Error/Bug: 3/0/0 执行用时: 32 ms, 在所有 Python3 提交中击败了 89.62% 的...
x = int(input()) d = [0] * 1000001 for i in range(2,x+1): d[i] = d[i-1] + 1 if i%2 == 0: d[i] = min(d[i], d[i//2] + 1) if i%3 == 0: d[i] = min(d[i], d[i//3] + 1) print(d[x])
class PipelineException(Exception): pass class CredentialsException(Exception): pass
num = int(input("enter somthing")) base = int(input("enter a base")) b = bin(num)[2:] o = oct(num)[2:] h = hex(num)[2:] print(b,o,h) x = num lst = [] while x >0: lst.append(int(x%base)) xmod = x%base x = (x-xmod)/base lst.reverse() print(lst) x = 0 for i in range(len(lst)): if lst[i] != 0: x +=...
# https://leetcode.com/problems/integer-break/ #Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. #Return the maximum product you can get. class Solution(object): def integerBreak(self, n): """ :type n: int :rtype: in...
def findSeatId(line : str) -> int: row = findPosition(line[0:7], "F", "B") column = findPosition(line[7:], "L", "R") return (row << 3) + column def findPosition(line : str, goLow: str, goHigh:str) -> int: pos = 0 stride = 1 << (len(line) - 1) for c in line: if c == goHigh: ...
class Intersection(): def __init__(self,t,object): self.t = t self.object = object class Intersections(list): def __init__(self,i): self += i def hit(self): hit = None pos = list(filter(lambda x: x.t >= 0,self)) if len(pos): hit = min(pos,ke...
""" Some constants related to Cityscapes and SUN datasets """ # Taken from deeplabv3 trained on COCO CITYSCAPES_MEAN = [0.485, 0.456, 0.406] CITYSCAPES_STD = [0.229, 0.224, 0.225] # Mapping of IDs to labels # We follow https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py # We m...
class Config: SECRET_KEY = '86cbed706b49dd1750b080f06d030a23' SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db' SQLALCHEMY_TRACK_MODIFICATIONS =False SESSION_COOKIE_SECURE = True REMEMBER_COOKIE_SECURE = True MAIL_SERVER = 'smtp@google.com' MAIL_PASSWORD = '' MAIL_USERNAME = ''...
# This tests long ints for 32-bit machine a = 0x1ffffffff b = 0x100000000 print(a) print(b) print(a + b) print(a - b) print(b - a) # overflows long long implementation #print(a * b) print(a // b) print(a % b) print(a & b) print(a | b) print(a ^ b) print(a << 3) print(a >> 1) a += b print(a) a -= 123456 print(a) a *= ...
# # PySNMP MIB module CTIF-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTIF-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:44:24 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,...
""" Created on Wed Jan 26 23:57:01 2022 @author: G.A. """ ## PS1 Part A: House Hunting # Variables annual_salary = float(input("Enter your annual salary:")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal:")) total_cost = float(input("Enter the cost of your dream home:")) portio...
def egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y def modinv(a, m): gcd, x, y = egcd(a, m) if gcd != 1: return None # modular inverse does not exist else: return x % m def affine...
# RestDF Default settings PORT: int = 8000 HOST: str = 'localhost' DEBUG: bool = False
def reindent(s, numSpaces, prefix=None): _prefix = "\n" if prefix: _prefix+=prefix if not isinstance(s,str): s=str(s) _str = _prefix.join((numSpaces * " ") + i for i in s.splitlines()) return _str def format_columns(data, columns=4, max_rows=4): max_len = max( list(map( len...
cont = 0 maior = 0 menor = 0 contm = 0 contn = 0 somaI = 0 media = 0 for i in range (1, 5): nome = str(input('informe seu nome ')) sexo = str(input('qual seu sexo (M) masculino (F) feminino (P) prefere não dizer ')) idade = int(input('informe sua idade ')) cont = cont + 1 somaI = m...
C = {'azul': '\033[1;36m', 'verde': '\033[1;32m'} d = int(input('{}Digite a distância da viagem em Km: '.format(C['azul']))) if d > 200: p = d*0.45 print('{}Sua viagem custará {}R${:.2f}'.format(C['azul'], C['verde'], p)) else: p = d*0.5 print('{}Sua viagem custará {}R${:.2f}'.format(C['azul'],...
class User: ''' class that generates a new instance of a password user __init__ method that helps us to define properitis for our objet Args: ''' user_list = [] #Empty user list def __init__(self,name,password): self.name=name self.password=password ...
# # PySNMP MIB module ALCATEL-IND1-MLD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-MLD-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:18:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
class Solution: def minimumTime(self, s: str) -> int: n = len(s) ans = n left = 0 # min time to remove illegal cars so far for i, c in enumerate(s): left = min(left + (ord(c) - ord('0')) * 2, i + 1) ans = min(ans, left + n - 1 - i) return ans
SCREEN_HEIGHT, SCREEN_WIDTH = 600, 600 # Controls UP = 0, -1 DOWN = 0, 1 LEFT = -1, 0 RIGHT = 1, 0 # Window grid GRID_SIZE = 20 GRID_WIDTH = SCREEN_WIDTH / GRID_SIZE GRID_HEIGHT = SCREEN_HEIGHT / GRID_SIZE
st = input("pls enter student details: ") student_db = {} while(st != "end"): ind = st.find(' ') student_db[st[:ind]] = st[ind + 1:] st = input("pls enter student details: ") roll = input("psl enter roll no : ") while(roll != 'X'): print(stude...
def max_end3(nums): if nums[0] > nums[-1]: return nums[0:1]*3 return nums[-1:]*3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- name = "rqmts" __version__ = "1.0.0"
# 14_A fábrica de refrigerantes Meia-Cola vende seu produto em três formatos: # lata de 350 ml, garrafa de 600 ml e garrafa de 2 litros. # Se um comerciante compra uma determinada quantidade de cada formato. # Faça um algoritmo para calcular quantos litros de refrigerante ele comprou. lata = int(input('Informe a qu...
"""Constants for Hive.""" ATTR_MODE = "mode" ATTR_TIME_PERIOD = "time_period" ATTR_ONOFF = "on_off" CONF_CODE = "2fa" CONFIG_ENTRY_VERSION = 1 DEFAULT_NAME = "Hive" DOMAIN = "hive" PLATFORMS = ["binary_sensor", "climate", "light", "sensor", "switch", "water_heater"] PLATFORM_LOOKUP = { "binary_sensor": "binary_sens...
print(""" 087) Aprimore o desafio anterior, mostrando no final: A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha. """) matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] spar = maior = scol = 0 for l in range(0,3): for c in range(0,3): matri...
# FIXME: Stub class PreprocessorInfoChannel(object): def addLineForTokenNumber(self, line, toknum): pass
assert easy_cxx_is_root @brutal.rule(caching='memory', traced=1) def c_compiler(): cc = brutal.env('CC', []) if cc: return cc NERSC_HOST = brutal.env('NERSC_HOST', None) if NERSC_HOST: return ['cc'] return ['gcc'] @brutal.rule(caching='memory', traced=1) def cxx_compiler(): cxx = brutal.env('CXX', [...
def word_flipper(str): if len(str) == 0: return str #split strings into words, as words are separated by spaces so words = str.split(" ") new_str = "" for i in range(len(words)): words[i] = words[i][::-1] return " ".join(words) # Test Cases print ("Pass" if ('retaw' == word_fl...
def merge_sort(arr): if len(arr) <= 1: return mid = len(arr)//2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) merge_lists(left, right, arr) def merge_lists(a,b,arr): len_a = len(a) len_b = len(b) i = j = k = 0 while i < len_a and j < len...
# FLOW011 for i in range(int(input())): salary=int(input()) if salary<1500: print(2*salary) else: print(1.98*salary + 500)
#encoding:utf-8 subreddit = 'bikinimoe' t_channel = '@BikiniMoe' def send_post(submission, r2t): return r2t.send_simple(submission)
simType='sim_file' symProps = [ {'set': 'memory', 'RBs': [{'higher_order': False, 'pred_name': 'non_exist', 'P': 'non_exist', 'object_name': 'bar_0.703780466095', 'pred_sem': [], 'object_sem': [['X', 1, 'X', 'nil', 'state'], ['X_0.790476190476', 1, 'X', 0.79047619047619044, 'value'], ['Y', 1, 'Y', 'nil', 'state'], ['Y_...
# Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the # number of ways it can be decoded. # For example, the message '111' would give 3, since it could be decoded as # 'aaa', 'ka', and 'ak'. # You can assume that the messages are decodable. For example, '001' is not # allowed. ALPHA...
service_entry = """ --- apiVersion: networking.istio.io/v1alpha3 kind: ServiceEntry metadata: name: {cfg[name]}-backend-redirect spec: hosts: - {cfg[upstream][host]} location: MESH_EXTERNAL ports: - number: 443 name: tcp protocol: TLS resolution: DNS """ virtual_service = """ --- apiVersion: netwo...
N = int(input()) c = 0 for i in range(0, N // 5 + 1): for j in range(0, N // 4 + 1): five, four = 5 * i, 4 * j if five + four == N: c += 1 print(c)
num1 = 10 num2 = 14 num3 = 12 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number between",num1,",",num2,"and",num3,"is",largest)
day = int(input()) even = int(input()) end = int(input()) plan_a = round(max(0, day - 100) * 0.25 + even * 0.15 + end * 0.2, 2) plan_b = round(max(0, day - 250) * 0.45 + even * 0.35 + end * 0.25, 2) print('Plan A costs {:2}'.format(plan_a)) print('Plan B costs {:2}'.format(plan_b)) if plan_a < plan_b: print('Plan ...
#Check if the number entered is special '''a=int(input("Enter a number: ")) b=a fact=1 s=0 while a!=0: d=a%10#5;4;1 print(a,d) for i in range(1,d+1): fact*=i s+=fact#120;144;145 fact=1 a=a//10 if s==b: print("The given number, ", b,"is a special number") else: print("The given nu...
# MAXIMISE GCD def gcd(a,b): if a%b==0: return(b) if b%a==0: return(a) if a==b: return(a) if a>b: return gcd(a%b,b) if b>a: return gcd(a,b%a) n = int(input()) Arr = list(map(int, input().strip().split())) x = Arr[n-1] mx = 1 j = 0 for i ...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def getAllElements(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rtype: List[int] """ ans = [] ...
## ## # File auto-generated against equivalent DynamicSerialize Java class class NewAdaptivePlotRequest(object): def __init__(self): self.fileContents = None self.fileName = None self.bundleName = None self.description = None def getFileContents(self): return self.fil...
def fatorial(n, show=False): """ -> Calcula o fatorial de um número. :param n: Onúmero a ser calculado. :param show: (opcional) Mostrar ou não a conta. :return: O valor do fatorial do número n. """ fat = 1 for i in range(n, 0, -1): if show: if i > 1: p...
load("@rules_scala_annex//rules:external.bzl", "scala_maven_import_external") load("//repos:rules.bzl", "overlaid_github_repository") def singularity_scala_repositories(): com_chuusai_shapeless_repository() com_github_mpilquist_simulacrum_repository() eu_timepit_refined_repository() io_circe_circe_repo...
cipher = '11b90d6311b90ff90ce610c4123b10c40ce60dfa123610610ce60d450d000ce61061106110c4098515340d4512361534098509270e5d09850e58123610c9' pubkey = [99, 1235, 865, 990, 5, 1443, 895, 1477] flag = "" for i in range(0, len(cipher), 4): c = int(cipher[i:i+4], 16) for m in range(0x100): test = 0 for p...
#coding:utf-8 ''' filename:vowel_counts.py chap:4 subject:9 conditions:chap3_35 string solution:count a,e,i,o,u ''' text = '''You raise me up,so I can stand on mountains You raise me up to walk on stromy seas I am strong when I am on your shoulders You raise me up to more than I can be''' v...
# reading ocntents from file # fp=open('file.txt') fp=open('file.txt','r') # by default it opens in read mode text=fp.read() print(text)
class Entry(object): def __init__(self): self.name = '' self.parent = '' self.created = 0 self.lastUpdate = 0 self.lastAccess = 0 def create(self): pass def delete(self): pass def getFullPath(self): if not self.parent: return...
class HashMap: def __init__(self): self.bucket = {} def put(self, key: int, value: int) -> None: self.bucket[key] = value def get(self, key: int) -> int: if key in self.bucket: return self.bucket[key] return -1 def remove(self, key: int) -> None: i...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def imprimirMensaje(): print("Mensaje Especial: ") print("¡Estoy aprendiendo a usar funciones!") def conversacion(opcion): print("Hola") print("¿Cómo estás?, elegiste la opción ", opcion) print("Adiós") for x in range(3): imprimirMensaje() opcion = input("Elige una opcione (1,2,3): ") if op...
# -*- coding: UTF-8 -*- # # You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. # # You may assume the two numbers do not contain any leading zero, exce...
class DisjointSet: def __init__(self, elements): self.parent = [0] * elements self.size = [0] * elements def make_set(self, value): self.parent[value] = value self.size[value] = 1 def find(self, value): while self.parent[value] != value: value = self.pa...
def factor(num1: float, num2: float): if num1 % num2 == 0: return f"{num2} is a factor of {num1}" else: return f"{num2} is not a factor of {num1}" num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) print(factor(num1, num2))
n = input() cnt = 0 for i in n: if 'A' <= i <= 'C': cnt += 3 elif 'D' <= i <= 'F': cnt += 4 elif 'G' <= i <= 'I': cnt += 5 elif 'J' <= i <= 'L': cnt += 6 elif 'M' <= i <= 'O': cnt += 7 elif 'P' <= i <= 'S': cnt += 8 elif 'T' <= i <= 'V': ...
# Média 2 a=float(input()) b=float(input()) c=float(input()) media=((a*2.0)+(b*3.0)+(c*5.0))/10 print('MEDIA = {:.1f}'.format(media))
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:84 ms, 在所有 Python3 提交中击败了61.57% 的用户 内存消耗:13.8 MB, 在所有 Python3 提交中击败了5.00% 的用户 解题思路: 具体实现见代码注释 """ class Solution: def sortString(self, s: str) -> str: s_list = list(s) # 字符串转列表 result = [] # 保存最终结果 reverse = False # 翻转顺序 ...
class ClosestDistanceInfo: def __init__(self, first, second, neighbours): self.mFirst = first self.mSecond = second self.mNeighbours = neighbours
# -*- coding: utf-8 -*- { 'actualizada': ['actualizadas'], 'eliminada': ['eliminadas'], 'fila': ['filas'], 'seleccionado': ['seleccionados'], }
"""sample scripts for covariance related stuff""" def cov(v1, v2): assert len(v1) == len(v2), "vectors should be of same size" m1 = sum(v1) / (len(v1)) m2 = sum(v2) / (len(v2)) cov = 0 for i in range(0, len(v1)): cov += (v1[i] - m1)*(v2[i]-m2) return cov / (len(v1) -1 ) def cov_matri...
""" Here's some complexity: what if the user gives us a letter in input() and not a number? Or what if it's an decimal (float) instead of an integer? We need to validate our inputs. """ def get_values(): """ Retrieves two values to multiply """ user_values = input("On the next line, enter the values t...
#! /usr/bin/env python3 description =""" Counting Sundays Problem 19 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, ...
# coding: utf-8 ######################################################################### # 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> # # author yeeku.H.lee kongyeeku@163.com # # # # version...
class node(object): def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data def set_next(self, next): self.next = next def get_next(self): return self.next def has_next(self): return self.next...
# Longest common sub sequence: def find_length_lcs(a1, a2): N = len(a1) dp = [[0 for i in range(N + 1)] for j in range(N + 1)] for i in range(1, N + 1): for j in range(1, N + 1): if a1[i - 1] == a2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: ...
entries = [ { 'env-title': 'atari-alien', 'env-variant': 'No-op start', 'score': 5778, 'stddev': 2189, }, { 'env-title': 'atari-amidar', 'env-variant': 'No-op start', 'score': 3537, 'stddev': 521, }, { 'env-title': 'atari-assaul...
class CacheData: def __init__(self, cache=None, root=None,hit=None,full=None): self.cache = cache self.root = root self.hit = hit self.full = full
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
validators = { "departure location": [[45, 609], [616, 954]], "departure station": [[32, 194], [211, 972]], "departure platform": [[35, 732], [744, 970]], "departure track": [[40, 626], [651, 952]], "departure date": [[44, 170], [184, 962]], "departure time": [[49, 528], [538, 954]], "arriva...
# Exercício Python 061: Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA, # mostrando os 10 primeiros termos da progressão usando a estrutura while. term = int(input('Enter a first term: ')) reason = int(input('Enter a reason: ')) count = 0 while count < 10: print(f'{term}', end=' -> ') count += 1...
#!/usr/bin/python3 # 旋转数组 def rotate(nums: list, k: int) -> None: for i in range(k): nums.insert(0, nums.pop(len(nums) - 1)) if __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(arr) rotate(arr, 3) print(arr)