content
stringlengths
7
1.05M
# Converts Celsius to Fahrenheit celsius = float(input('Digite a temperatura (°C): ')) fahrenheit = celsius / 5 * 9 + 32 print('{:.1f} °C equivalem a {:.1f} °F.'.format(celsius, fahrenheit))
a, b = map(int, input().split()) if b >= 45: print(a, b-45) elif a != 0 and b < 45: print(a-1, b+15) else: print(23, b+15)
N = int(input()) soma = 0 for k in range(N): X = int(input()) if X >= 10 and X <= 20: soma+=1 print("%d in" % (soma)) print("%d out" % (abs(N-soma)))
""" Using up to one million tiles how many different "hollow" square laminae can be formed? """ def cal(): TILES = 10**6 answer = 0 for n in range(3, TILES // 4 + 2): # Outer square length for k in range(n - 2, 0, -2): # Inner square length if n * n - k * k > TILES: break answer += 1 return str(answ...
class Metric(object): """ A performance measure that is associated with Element :param metricId: Metric FQN :type metricId: string :param metricType: Metric Type :type metricType: string :param sparseDataStrategy: Sparse data strategy :type sparseDataStrate...
# Time: O(h) # Space: O(1) # Definition for a Node. class Node: def __init__(self, val): pass class Solution(object): def lowestCommonAncestor(self, p, q): """ :type node: Node :rtype: Node """ a, b = p, q while a != b: a = a.parent if a els...
class ValueType(object): '''Define _key() and inherit from this class to implement comparison and hashing''' # def __init__(self, *args, **kwargs): super(ValueType, self).__init__(*args, **kwargs) def __eq__(self, other): return type(self) == type(other) and self._key() == other._key() def __ne__(self, ...
def is_even(number:int): """ This function verifies if the number is even or not Returns: True if even false other wise """ return number % 2 == 0 def is_prime(number: int): """ This function finds if the number is prime Returns: True if prime false otherwise """ ...
""" Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? Would this affect the run-time complexity? How and why? Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. The array may conta...
# # PySNMP MIB module CISCO-SRST-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SRST-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:12:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
# bootstrap glyph icon ICON_TYPE_GLYPH = 'glyph' # image relative to Flask static folder ICON_TYPE_IMAGE = 'image' # external image ICON_TYPE_IMAGE_URL = 'image-url'
array = [] while True: line = input() if "DEBUG" == line: break array += list(map(int, filter(None, line.split(" ")))) for i in range(len(array) - 6): if array[i] == 32656 and array[i + 1] == 19759 and array[i + 2] == 32763: n = array[i + 4] start = i + 6 end = start +...
""" Minimalistic application with fields, managers etc. for full text search support in PostgreSQL. Inspired by: https://github.com/linuxlewis/djorm-ext-pgfulltext """ __version__ = '0.1.0' FTS_CONFIGURATIONS = { 'simple': 'simple', 'en': 'english', 'da': 'danish', 'nl': 'dutch', 'fi': 'finnish',...
''' Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other...
pens_pack_price = 5.80 markers_pack_price = 7.20 whiteboard_cleaner_per_liter_price = 1.20 amount_pen_packs = int(input("Enter the amount of pen packs: ")) amount_marker_packs = int(input("Enter the amount of marker packs: ")) whiteboard_cleaner_liters = int(input("Enter the ampunt of liters of whiteboard cleaner: "))...
def configure(self): #Add Components compress = self.add('compress', CompressionSystem()) mission = self.add('mission', Mission()) pod = self.add('pod', Pod()) flow_limit = self.add('flow_limit', TubeLimitFlow()) tube_wall_temp = self.add('tube_wall_temp', TubeWallTemp()) #Boundary Input C...
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
n, d = [int(i) for i in input().split()] A = {} C = {} shoots = 0 def rangeD(e1, s2, e2): tmp = min(e1, e2) - s2+1 return(tmp if tmp >= 0 else -1) for _ in range(n): s, e, t, num = [i for i in input().split()] s, e, num = int(s), int(e), int(num) shoots += (e-s+1)*num if (t == "A"): ...
name = input("Please enter your name: ") if name == 'Bob': print("You are a part of the top 1 percent!") elif name == 'Alice': print("You are a part of the top 1 percent!") else: print("Go away filthy peasent")
## Integer Type num = 3 # type() print(type(num)) # <class 'int'> ## Float Type num = 3.14156 print(type(num)) # <class 'float'> ### Arithmetics operator # Addition : 3 + 2 ==> 5 # Subtraction : 3 - 2 ==> 1 # Multiplication : 3 * 10 ==> 30 # Division : 3 / 2 ...
"""Constants for the HomeSeer integration.""" DOMAIN = "homeseer" ATTR_REF = "ref" ATTR_LOCATION = "location" ATTR_LOCATION2 = "location2" ATTR_NAME = "name" ATTR_VALUE = "value" ATTR_STATUS = "status" ATTR_DEVICE_TYPE_STRING = "device_type_string" ATTR_LAST_CHANGE = "last_change" CONF_HTTP_PORT = "http_port" CONF_A...
# Importable string for GQL query org_team_members_query = """query orgTeamMembers($organization: String!, $team: String!) { organization(login:$organization) { team(slug:$team) { name members{ nodes { login name ...
my_list = ["a", "b", "c", "d", "e"] item_count = len(my_list) print(f"My list has {item_count} items:") for i in my_list: print(i)
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making GameAISDK available. This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright...
class Solution: def isMajorityElement(self, nums: List[int], target: int) -> bool: ''' T: O(log n) and S: O(1) ''' def binarySearch(nums, target, side): index = -1 lo, hi = 0, len(nums) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 ...
class Solution: def majorityElement(self, nums: List[int]) -> int: result, count = nums[0], 1 for num in nums: if result == num: count += 1 else: if count == 1: result = num else: count -= 1 return result
# # PySNMP MIB module ENTERASYS-THREAT-NOTIFICATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-THREAT-NOTIFICATION-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:04:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using P...
# from posixpath import split # import PyPDF2 # import os # pdfName = input("unsplit PDF file name/path (Example.pdf): ") # try: # with open(pdfName, 'rb') as pdfFile: # print("วิชา math2 การบ้านครั้งที่ 0 กลุ่ม 99 ลำดับที่ 00 ส่งปี 60 เดือน 01 วันที่ 01") # newName = input("new file name/path (ma...
def quick_sort(items): if len(items) > 1: pivot_index = 0 smaller_items = [] larger_items = [] for i, val in enumerate(items): if i != pivot_index: if val < items[pivot_index]: smaller_items.append(val) else: ...
def test_one(camera): assert "camera" in globals() or "camera" in locals() """def test_two(self): camera.start_mjpg_streamer() assert camera.check_mjpg_streamer()""" """def test_three(self): camera.stop_mjpg_streamer() assert not camera.check_mjpg_streamer()""" """def test_four(self): fname ...
""" Differences between alpa.parallelize and jax.pmap ================================================= The most common tool for parallelization or distributed computing in jax is `pmap <https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap>`_. With several lines of code change, we can use ``pmap`` for da...
''' #params: 9104483 [1] train-result=0.4161, valid-result=0.4865 [62.0 s] [2] train-result=0.5830, valid-result=0.5648 [67.0 s] [3] train-result=0.6017, valid-result=0.5805 [67.7 s] [4] train-result=0.6100, valid-result=0.5874 [73.3 s] [5] train-result=0.6135, valid-result=0.5911 [66.8 s] [6] train-result=0.6151, val...
"""Load dependencies needed to compile the protobuf library as a 3rd-party consumer.""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") PROTOBUF_MAVEN_ARTIFACTS = [ "com.google.code.findbugs:jsr305:3.0.2", "com.google.code.gson:gson:2.8.9", "com.google.errorprone:error_prone_annotatio...
def search(min_, max_, els, dec, inc): for c in els: if c == dec: max_ = (min_+max_)/2 elif c == inc: min_ = (min_+max_)/2 return min_ def getid(card): l = search(0, 128, card[:7], 'F', 'B') c = search(0, 8, card[7:], 'L', 'R') return l, c with open('in...
# Binary search recursive version def rec_binary_search(arr, ele): if len(arr) == 0: return False else: mid = int(len(arr)/2) if arr[mid] == ele: return True else: if ele < arr[mid]: return rec_binary_search(arr[:mid], ele) e...
# "sequence.replaceSelection": true BASE_EMOTICONS = [ u":)", u":-)", u":))", u":-))", u":)))", u":-)))", u"(:", u"(-:", u"=)", u"(=", u":]", u":-]", u"[:", u"[-:", u":o)", u"(o:", u":}", u":-}", u"8)", u"8-)", u"(-8", u";)", u";-)", u"(;", u"(-;", u":(", u":-(", u":((", u":-((", u":(((", u":-(((", u"):", u")-:", u"=("...
class CabernetException(Exception): def __init__(self, value): self.value = value def __str__(self): return 'CabernetException: %s' % self.value
def get_coordinate(record): pass def convert_coordinate(coordinate): pass def compare_records(azara_record, rui_record): pass def create_record(azara_record, rui_record): pass def clean_up(combined_record_group): pass
# This object is created to carry along the variables of interest for display purposes class RegObject: def __init__(self, res_list, interest, controls): self.res = res_list self.variables_of_interest = list(dict.fromkeys([x.lower() for x in interest])) # This avoids errors in the formatte...
# -*- coding: utf-8 -*- def devices_info_all(pushbots): return pushbots.devices_info_all() def device_info(pushbots, token): return pushbots.device_info(token=token)
def determine_config_type(config_parser): '''Determines the type of a ceph.conf file and returns it. Args: config_parser (configparser): Parser object with read in ceph.conf to check. Returns: rados_deploy.StorageType of the ceph.conf.''' if 'memstore device bytes' in config_parser['gl...
class IgnoreMe: def __init__(self, *args, **kwds): ... def __call__(self, *args, **kwds): return self def __getattr__(self, __name: str): return self def __bool__(self): return False def __nonzero__(self): return self.__bool__()
# -*- coding: utf-8 -*- """ Created on Fri Jun 22 01:50:15 2018 @author: Akash """ class Queue: def __init__(self): self.queue = list() def enqueue(self, data): self.queue.insert(0, data) return True def dequeue(self): return self.queue.p...
# encoding: utf-8 # module select # from (pre-generated) # by generator 1.147 """ This module supports asynchronous I/O on multiple file descriptors. *** IMPORTANT NOTICE *** On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors. """ # no imports # functions def select(rlist, wlist, xlist...
def merge_ordered_list(in_list1: list, in_list2: list) -> list: """ Merge two ordered list :param in_list1: the first source list :param in_list2: the second source list :return: the merged list """ _list1 = in_list1.copy() _list2 = in_list2.copy() _output_list = [] idx_2 = 0 ...
k=1 for i in range(1,6): for j in range(i): if k<10: print(k,end='') k+=1 if k==10: print(1,end='') else: k=2 print()
'''Exercício para for 02''' nomes = ['jessica','saara','rodrigo','eric','marcela','jorge','priscila'] lista_upper = [] for x in nomes: print(nomes(upper(x)))
def launch_network(): global network global difficulty network = set() difficulty = 1
''' @Date: 2019-12-08 19:58:01 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors: ywyz @LastEditTime: 2019-12-08 20:01:19 ''' def count(s, ch): num = 0 for char in s: if char == ch: num += 1 return num def main(): strings = input("Input a string: ...
# !/usr/bin/env python3 ####################################################################################### # # # Program purpose: Define a string containing special characters in # # vario...
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class Solution2: def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ def dfs(node, depth): if node is Non...
ALL = ( ("al'iraq", 'Iraq'), ("aljazā'ir", 'Algeria'), ("amelikahuipu'ia", 'United States'), ("cote d'ivoire", 'Ivory Coast'), ("coted'ivoire", 'Ivory Coast'), ("democratic people's republic of koread", 'North Korea'), ("democraticpeople'srepublicofkoread", 'North Korea'), ("ityop'ia", '...
__all__ = ['getColMap', 'ColMapDict'] def getColMap(opsdb): """Get the colmap dictionary, if you already have a database object. Parameters ---------- opsdb : rubin_sim.maf.db.Database or rubin_sim.maf.db.OpsimDatabase Returns ------- dictionary """ try: version = opsdb.o...
class OptimizerWrapper: """ A wrapper to make optimizer more concise """ def __init__(self, model, optimizer, lr_scheduler=None): self.model = model self.optimizer = optimizer self.lr_scheduler = lr_scheduler def step(self, inputs, labels): self.zero_grad() ...
# # PySNMP MIB module ORiNOCO-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ORiNOCO-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:35:34 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, 0...
n = int(input()) segundos = n%60 minutos = (n / 60) % 60 horas = n / (60 * 60) print("%i:%i:%i" % (horas, minutos, segundos))
# s <= ns # 1. e <= ns: change # 2. ns < e < ne: change # => e < ne: change # else: cnt += 1, don't change class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: intervals.sort() s = e = -1 cnt = 0 for ns, ne in intervals: if e < ne: ...
# List grades=[12,60,15,70,90] grades[0]=55 #update grades[0] print (grades[0]) print (grades[1:4]) grades = grades + [12,33] print (grades) length = len(grades) print(length) # Nested List data = [[3,4,5],[6,7,8]] print(data[0][1]) print(data[0][0:2]) data[0][0:2] = [5,5,5] print(data) # Tuple print ("///////////...
# Copyright 2017 Mirantis, Inc. # # 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 agr...
# Variables x = 15 price = 9.99 discount = 0.2 result = price * (1 - discount) print(result)
# Security misconfiguration is the most commonly seen issue. This is commonly a result of insecure # default configurations, incomplete or ad hoc configurations, open cloud storage, misconfigured # HTTP headers, and verbose error messages containing sensitive information. Not only must all # operating systems, frame...
""" net: a set of processes; compartment: a compartment consists of input: space: []; """ """ from sth import register, register into which net; # function.py (external) def process_a(data, parameter): # data must be a regular objects. pass # assembling net from function import process_a net = Net() n...
class Solution: def nextGreatestLetter(self, letters, target): left, right = 0, len(letters) - 1 while left < right: mid = left + (right - left) // 2 if letters[mid] > target: right = mid else: left = mid + 1 if letters[lef...
# exercício em inglês implementado para atividade no SoloLearn weight = float(input()) height = float(input()) bmi = weight / (height ** 2) if(bmi < 18.5): print('Underweight') elif(bmi < 25): print('Normal') elif(bmi < 30): print('Overweight') else: print('Obesity')
notunuz =int(input("Lütfen yıl sonu not ortalamanızı giriniz:")) if (notunuz >=90): print("AA ile geçtiniz") elif(notunuz >=85): print("BA ile geçtiniz") elif(notunuz >=80): print("BB ile geçtiniz") elif(notunuz >=75): print("CB ile geçtiniz") elif(notunuz >=65): print("DC ile geçtiniz") elif(notunu...
class Document: def __init__(self,SentenceList,id=-1): self.id=id self.value=SentenceList self.attr={} def __str__(self): s ="Document id: {0}, value: {1}, attributes: {2}".format(self.id,self.value,self.attr) return s
''' At this point, you've got all the basics necessary to start employing modules. We still have to teach classes, among a few other necessary basics, but now would be a good time to talk about modules. IF you are using linux, installing python modules is incredibly stupid easy. For programming, linux is just lovely...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # pylint:disable=bad-whitespace # pylint:disable=line-too-long # pylint:disable=too-many-lines # pylint:disable=invalid-name # ######################################################### # # ************** !! WARNING !! *************** # ******* THIS FILE WAS A...
# You can customize these lists according to you're requirement. #list for finding admin panels: adminfinder_db = ["/acceso.asp", "/acceso.php", "/access/", "/access.php", "/account/", "/account.asp", "/account.html", "/account.php", "/acct_login/", "/_adm_/", "/_adm/", "/adm/", "/adm2/", "/adm/admloginuser.asp", "/ad...
class Intersection: def __init__(self, no, x_p, y_p): self.no = no self.x = x_p self.y = y_p
##Ejercicio 2 # el siguiente codigo identifica si existe alguna suma entre dos elementos # distintos dentro de la listta , que sumen 10. # Complejidad del algoritmo : O(n^2) por los dos for implementados uno dentro del otro # # Entrada: # - #Si hay entonces # Salida: # Son: 2 + 8 = 10 # True #Si no # Salida: # Fal...
""" Given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return True if you can make arr equal to target, or False otherwise. Example: Input: target = [1,2,...
n1 = float(input('Primeira nota: ')) n2 = float(input('Segunda nota: ')) media = (n1 + n2) / 2 if media > 7: print('Sua média foi de {}, você está APROVADO!'.format(media)) elif media >= 5 and media < 6.9: print('Sua média foi de {}, você está de RECUPERAÇÃO!'.format(media)) else: print('Sua média foi de {}...
#fibbonancci numvers def fibonancci(n): if n <= 1: return 1 l = [None]*(n+1) # l[:n] = 0*(n) l[0]= 0 l[1] = 1 # print(l) for i in range(2,n+1): l[i] = l[i-1]+l[i-2] print(l) return l[n+1] def fib_rec(n): if n <= 1: return n print(n) retu...
#Intersection class, the processing unit where traffic light control takes place #coded by sayfeddine DEFAULT_CYCLE = 60 # default cycle length to start with ( in seconds or "step" for SUMO) """ cycle length formula : C = (1.5*L + 5)/(1.0 - SYi)) C : optimum cycle length that minimise the delay cycle is always betwee...
# Define a function to find the truth by shifting the letter by a specified amount def lassoLetter( letter, shiftAmount ): # Invoke the ord function to translate the letter to its ASCII code # Save the code value to the variable called letterCode letterCode = ord(letter.lower()) # The ASCII number repr...
def isInterleave(s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ m, n, t = len(s1), len(s2), len(s3) if m + n != t: return False dp = [False] * (n + 1) dp[0] = True for i in range(m + 1): for j in range(n + 1): if i > 0:...
def reconcile(hub, high): ''' Take the extend statement and reconcile it back into the highdata ''' errors = [] if '__extend__' not in high: return high, errors ext = high.pop('__extend__') for ext_chunk in ext: for id_, body in ext_chunk: if id_ not in high: ...
class SlabShapeVertexType(Enum, IComparable, IFormattable, IConvertible): """ An enumerated type listing all Vertex types of Slab Shape Edit. enum SlabShapeVertexType,values: Corner (1),Edge (2),Interior (3),Invalid (0) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__(y) ...
""" The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer n, return its complement. Example 1: Input: n = 5 Output: ...
print("__name__ = ",__name__) if __name__ == "__main__": print("Rodou direto") else: print("Rodou através de import")
def approximation(x, x1, x2, y, y1, y2): a1 = (y1-y)/(x1-x) a2 = (1/(x2-x1))*(((y2-y)/(x2-x)) - ((y1-y)/(x1-x))) return ((x1+x)/2) - (a1/(2*a2))
''' CLASS: VnfmDriverTemplate AUTHOR: Vinicius Fulber-Garcia CREATION: 21 Oct. 2020 L. UPDATE: 28 Jul. 2021 (Fulber-Garcia; Included the "vnfmAddress" attribute) DESCRIPTION: Template for the implementation of VNFM drivers that run in the "Access Subsystem" internal module. The drivers must inhert this class ...
# Optional Problem Set, Question 1 def ndigits(x): ''' assumes x is an integer returns the digits of x ''' # If x equals 0 (due to integer division), it means that no digits are left. if x == 0: return 0 # Otherwise, it returns 1 + the digits of the integer divided by 10. return...
version = '1.3.1' major = 1 minor = 3 micro = 1 release_level = 'final' serial = 0 version_info = (major, minor, micro, release_level, serial)
#import math res = set() for i in range(2,101): for j in range(2,101): res.add(i ** j) print(len(res))
class Solution: def addBinary(self, a: str, b: str) -> str: c=int(a,2)+int(b,2) return str(bin(c))[2:]
n=int(input()) if n%2!=0: print("Weird") if n in range(2,7) and n%2==0: print("Not Weird") if n in range(6,21) and n%2==0: print("Weird") if n>20 and n%2==0: print("Not Weird")
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: # n^2 runtime degrees = [0] * n graph = [[] for _ in range(n)] for road in roads: degrees[road[0]] += 1 degrees[road[1]] += 1 graph[road[0]].append(road[1]) ...
__author__ = 'hs634' ''' Given a binary tree where all the right nodes are leaf nodes, flip it upside down and turn it into a tree with left leaf nodes. Keep in mind: ALL RIGHT NODES IN ORIGINAL TREE ARE LEAF NODE. /* for example, turn these: * * 1 1 * / \ / \ * ...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyAutogradGamma(PythonPackage): """autograd compatible approximations to the derivatives of the Gamma-famil...
# Convertir datos cualitativos en cuantitativos # Se les da un valor numérico para poder hacer operaciones y entrenar el modelo def nivel_indices_to_int(word): word_dict = {'Bajo' : 1, 'Medio' : 2, 'Alto' :3, 0: 0} return word_dict[word] def factores_to_int(word): word_dict = {'Clase baja' : 1, 'Clase ...
a = 0 b = 0 c = 0 if a == b: c = 100 else: c = 10 print(c) if c == 10: print('c == 10') else: print('c == 100') ''' output 100 c == 100 '''
''' Calcula as raizes de uma equação do segundo grau. f(x) = ax**2 + b*x + c ''' def f(a, b, c): x1 = (-b + (b**2 - 4*a*c)**(1/2)) / (2*a) x2 = (-b - (b**2 - 4*a*c)**(1/2)) / (2*a) return x1, x2 x1, x2 = f(1, 0.25, -5) print("\nO valor de x1 é: {0:.5f}".format(x1)) print("O valor de x2 é: {0:.5f...
def simulation_parameter_validate(end_t, initial_conditions, rates_params, drain_params): assert isinstance(end_t, (int, float)), "End_t must be a float or int" assert end_t > 0, "End_t most be a positive number" assert isinstance(initial_conditions, dict), "Expected {} got {} for initial conditions"\ ...
# # This is the Robotics Language compiler # # Transform.py: Deep Inference code transformer # # Created on: 25 February, 2019 # Author: Gabriel Lopes # Licence: license # Copyright: Robot Care Systems BV # def transform(code, parameters): return code, parameters
# Operators PLUS = '+' MINUS = '-' MUL = '*' DIV = '/' FLOORDIV = '//' MOD = '%' POWER = '^' ARITHMATIC_LEFT_SHIFT = '<<<' ARITHMATIC_RIGHT_SHIFT = '>>>' XOR = 'xor' BINARY_ONES_COMPLIMENT = '~' BINARY_LEFT_SHIFT = '<<' BINARY_RIGHT_SHIFT = '>>' AND = 'and' OR = 'or' NOT = 'not' IN = 'in' # TODO NOT_IN = 'not in' # T...
#!/usr/bin/env python3 """ - domain: GoogleCode Jam 2019 - contest: Round 1C - problem: B - title: Power Arrangers - link: https://codingcompetitions.withgoogle.com/codejam/round/00000000000516b9/0000000000134e91 - hash: GKS19_1B_B - author: Vitor SRG - version: 1.0 ...
""" Rabin-Karp or Karp-Robin is an pattern matching algorithm with average case and best case complexity O(m + n) and the worst case complexity O(mn), it is most efficient when used with multiple patterns as it is able to check if any of a set of patterns match a section of text in O(1) given the precomp...
# 6-dars 1-uyga vazifa # My_list = ['Dadam: O`ktam ', 'Onam: Dilrabo', 'Akam: Shoxrux', 'O`zim: Abduhalim', 'Ukam: Sardor'] # for elem in My_list: # print(elem) # 2-uyga vazifa # Standart kiruvchi ma'lumotdagi vergul bilan ajratilgan so'zlar ketma-ketligini teskar...