content
stringlengths
7
1.05M
# -*- coding: utf-8 -*- """ Created on Tue Aug 6 18:14:12 2019 @author: Maverick1 """ def rk4(f, t_n, x_n, u_n, h): k1 = h * f(t_n, x_n, u_n) k2 = h * f(t_n + 0.5 * h , x_n + 0.5 * k1, u_n) k3 = h * f(t_n + 0.5 * h , x_n + 0.5 * k2, u_n) k4 = h * f(t_n + h, x_n + k3, u_n) return x_n + ((k1 + 2.0 * k2 + 2.0...
"""Conversions and constants for Feet and Metere Converter program.""" METERS_PER_FOOT = 0.3048 def to_feet(meters: float) -> float: """Return the meter value as feet.""" return meters / METERS_PER_FOOT def to_meters(feet: float) -> float: """Return the feet value as meters""" return feet *...
#!/usr/bin/env python3 #finds number of letters and digits inp = input("Enter key: ") digit = 0 letter = 0 for i in inp: if i.isdigit(): digit+=1 elif i.isalpha(): letter+=1 else: pass print("Letter = ",letter) print("Digit = ",digit)
def test_comment(client, commentable, real_login): comment = 'comment here' commentable.post_comment(comment) [c] = _get_comments(client, commentable) assert c['comment'] == comment assert commentable.refresh().num_comments == 1 def test_delete_comment(client, commentable, real_login): comment ...
def strip_all(v): """ Strips every string in array :param v: list/tuple of strings :return: list """ return [s.strip() for s in v] def split(inp,n): """ Splits an input list into a list of lists. Length of each sub-list is n. :param inp: :param n: :return: """ if...
accuracy_scores = { 'id1': 0.27, 'id2': 0.75, 'id3': 0.61, 'id4': 0.05, 'id5': 0.4, 'id6': 0.67, 'id7': 0.69, 'id8': 0.52, 'id9': 0.7, 'id10': 0.3 } # store the top 3 values from the dictionary as a list max_accs = ___ # create an empty list that will hold ids of participants with the highes accuracy max_id...
class RFIDReaderException(Exception): pass class RFIDReaderTypeException(RFIDReaderException): pass
''' Block commnt(블록 주석) ''' print('Hello, Python') #Ctrl+Shift+F10: 파이썬 코드 실행 # 변수 사용 - 프로그램에 필요한 데이터를 저장하는 공간 # 변수 이름 = 값 age = 16 print(age) # 파이썬의 문자열: 따옴표('') 또는 큰따옴표("") 사용 name = '김수인' print(name) company = '아이티월' print(company) str1 = ' He said "yes!"' print(str1) str2 = "I'm a boy." print(str2) str3 = ...
__MAJOR = "0" __MINOR = "0" __MICRO = "1.post1" __VERSION__ = "{}.{}.{}".format(__MAJOR, __MINOR, __MICRO)
""" 파일 이름 : 2523.py 제작자 : 정지운 제작 날짜 : 2017년 7월 28일 프로그램 용도 : 별을 출력한다. """ # 입력 num = int(input()) # 출력 # 증가 부분 for i in range(num - 1): print('*' * (i + 1)) # 중간 부분 print('*' * num) # 감소 부분, 증가 부분의 range 함수를 반대로 구성 for i in range(num - 2, -1, -1): print('*' * (i + 1))
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name : morse Description : Author : x3nny date : 2021/10/29 ------------------------------------------------- Change Activity: 2021/10/29: Init -----------------------------------...
class FSM(object): def __init__(self, instructions): self.result={} self.instructions={} for i in instructions.split("\n"): temp=i.split("; ") self.result[temp[0]]=int(temp[-1]) self.instructions[temp[0]]=temp[1].split(", ") def run_fsm(self, star...
class Point: def __init__(self, x, y): self.x = x self.y = y def recOverlap(l1, r1, l2, r2): # if rectangle is to the left side of one another if (l1.x >= r2.x) or (l2.x >= r1.x): print('hi') return False # if rectangle is one above the other if (l1.y <= r2.y) or (l...
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\postures\posture_errors.py # Compiled at: 2018-02-21 00:22:03 # Size of source mod 2**32: 1046 bytes...
#!/usr/bin/python3 # Constants DEPTH = 256 NUM_REGISTERS = 8 # Read assembly code from code.txt with open("code.txt", 'r') as f: lines = f.readlines() # Initialize machine code machineCode = ["0000"] # Initialize maps # Memory isn't really a register but acts like one regMap = {'prefix' : 0, 'a' : 1, 'b' : 2, 'c'...
# Given a binary tree, find the length of the longest consecutive sequence path. # # The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse). # # For example, # # ...
#1 s1="MT" s2=10 s3="su" s4=5 pi=3.141592653 print(s1+s3) print(s2+s4) print('%10.3f'%pi) #2 print("my_age = 18 # 女孩子永远18") print("my_eyes = brown") #3 print('\"To be or no to be,\" \nHamlet said,\n\"that is a question\"') #4 print(1+2,2+3,3-4,4/5,5*6%7)
real = float(input('Quanto dinheiro você tem na carteira? R$')) dolar = real/5.34 euro = real/5.92 print('Com {:.2f} reais você pode comprar {:.2f} dólares e {:.2f} euros.'.format(real, dolar, euro))
""" source 폴더입니다. """ __version__ = '1.0'
# coding=utf-8 # Author: Jianghan LI # Question: 066.Plus_One # Complexity: O(N) # Date: 2017-08-02 10:51-10:53, 0 wrong try class Solution(object): def plusOne(self, digits): for i in range(len(digits)): if digits[-1 - i] < 9: return digits[:-1 - i] + [digits[-1 - i] + 1] + [...
""" inits node 'game_move' note: stub, does not check for unreachable, relies on simulation through `setStringSignal("move", -)` then wait for 2s @ros_param /game/move/skip_move_validation: bool should goal move be checked for validity? default: false (do NOT skip validation) /game/tower{name}...
coluna = int(input('Entre com a quantidade de colunas ')) contador = 0 linha = int(input('Entre com a quantidade de linhas ')) for i in range (1, linha + 1): for i in range (1, coluna + 1): contador += 1 print(contador, end=' ') print()
#!/usr/bin/env python3 #Take input from the user in celsius, convert to Fahrenheit and #use if logic to give feedback regarding the temperature def main(): temp_celsius = float(input("What is the temperature in Celsius?: ")) f = convert_celsius_to_fahrenheit(temp_celsius) if f > 80: print("It's hot...
print("Enter Two Numbers, And I'll sum It") try: first_num = int(input("\nFirst number - ")) sec_num = int(input("\nSecond number - ")) except ValueError: print("you have entered wrong value!!") else: answer = first_num + sec_num print(answer)
name = "rezutil" version = "1.4.5" # build with bez build system build_command = "python {root}/rezbuild.py" private_build_requires = ["python-2.7+<4"] def commands(): env = globals()["env"] env.PYTHONPATH.prepend("{root}/python")
# Copyright (c) 2010-2013, Regents of the University of California. # All rights reserved. # # Released under the BSD 3-Clause license as published at the link below. # https://openwsn.atlassian.net/wiki/display/OW/License class ParserException(Exception): GENERIC = 1 TOO_SHORT = 2 ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if head is None or head.next is None:...
input = """ true. a(1) :- true. b(1) :- true. gen1 :- not a(1). gen2 :- not b(1). %%%%%%%%%%%%%%%%%%%%%% unrel | a(2). gen3 :- unrel. gen3 :- gen1. a(2) :- not gen3. gen4 :- gen2. b(2) :- not gen4. """ output = """ true. a(1) :- true. b(1) :- true. gen1 :- not a(1). gen2 :- not b(1). %%...
N = int(input()) ans = N for i in range(N+1): cnt = 0 t = i while t>0: cnt+=t%6 t//=6 j=N-i while j>0: cnt+=j%9 j//=9 ans = min(ans,cnt) print(ans)
# Copyright 2018 Carsten Blank # 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, s...
""" overly simple example of function to test with pytest """ def add_two_ints(first_int, second_int): """ function to add two numbers together :param first_int: the first number to add together :param second_int: the second number to add together :return: sum of inputs, may be positive or negativ...
# -------------- #Code starts here def palindrome(num): while True: num+=1 if str(num) == str(num)[::-1]: return num break print(palindrome(123)) # -------------- #Code starts here #Function to find anagram of one word in another def a_scramble(str_1,str_2): r...
'''Simple logger for information and debugging Used when connected to the microcontroller (e.g. Pyboard) and monitoring the code via the REPL ''' class Logger: def __init__(self, prestring='JETI EX BUS'): self.default_prestring = prestring self.prestring = prestring def log(self, msg_type,...
class MoveLog: def __init__(self): self.moves = [] self.count = 0 def add(self, move): self.moves.append(move) self.count += 1 def pop(self): self.count -= 1 return self.moves.pop() def count(self): return self.count def reset(self): ...
# -*- coding: UTF-8 -*- # Date : 2020/1/17 9:36 # Editor : gmj # Desc : # redis配置 REDIS_CONFIG = { 'HOST': '127.0.0.1', # 'HOST': '106.13.63.136', 'PORT': 6379, 'PWD': 'gmj760808', 'DB': 1, 'SET_KEY': 'default_key', } # mysql配置 BD_MYSQL_CONFIG = { 'HOST': '127.0.0.1', # 'HOST': '...
t = int(input()) while t: A = input() B = input() f = False; for i in A: if i in B: f = True; break; if f == True: print("Yes") else: print("No") t = t-1
k = int(input().split(' ')[1]) words = input().split(' ') currentLine = [] for word in words: currentLine.append(word) if len(''.join(currentLine)) > k: currentLine.pop() print(' '.join(currentLine)) currentLine = [word] print(' '.join(currentLine))
#if customizations are required when doing a a linking of the jpackage code to the OS def main(j,jp,force=True): recipe=jp.getCodeMgmtRecipe() recipe.link(force=force)
valores = list() c = 0 for cont in range(0, 5): valores.append(int(input(f'Digite o {c + 1} valor: '))) c += 1 for c, v in enumerate(valores): print(f'Na posição {c} encontrei o valor {v}!') print('Cheguei ao final da lista.')
#Python 3.X solution for Easy Challenge #0005 #GitHub: https://github.com/Ashkore #https://www.reddit.com/user/Ashkoree/ def program(username): print ("Hello "+username) def login(username,password): validuser = False validpass = False with open("usernames.txt","r") as usernamefile: usernameli...
n1 = float(input('Quantos metros de altura a parede tem: ')) n2 = float(input('E de largura: ')) a = n1*n2 t = a/2 print ('O total da área é {}m2, considerando que cada litro de tinta pinte 2x2m, \n' 'você precisara de {:.3f}L de Tinta.'.format(a,t))
dict_Marie = { "AD" : "a", "ABBÁTJA" : "abaïe", " " : "adhuc", #Mot latin "ADÍUDA" : "ahie", "HÁBET" : "aie", #verbe "ADILLE" : "al", # "ALÁCRIS" : "alegres ", # "ELMỌSNA" : "almones ", # "ADMÁSSOS" : "amassez ", # "AMĘN" : "amen ", # "AMÍCU" : "ami ", # "AMÍCOS" : "amis ", # "AMÍCU" : "amiu ", # "ADNUNTI...
numero = int(input('Digite um número: ')) print('='*15) print('Tabuda do {}'.format(numero)) print('{} x 1 = {}'.format(numero, (numero*1))) print('{} x 2 = {}'.format(numero, (numero*2))) print('{} x 3 = {}'.format(numero, (numero*3))) print('{} x 4 = {}'.format(numero, (numero*4))) print('{} x 5 = {}'.format(num...
class CommandError(Exception): @property def msg(self): if self.args: return self.args[0] return "An error occurred while running this command ..." class ConverterNotFound(CommandError): pass class BadArgumentCount(CommandError): def __init__(self, *args, func): s...
string = str(input("Enter a string. ")) def encode(string): if not string: return "" x = 1 while x < len(string) and string[0] == string[x]: x += 1 return string[0]+str(x)+encode(string[x:]) print(encode(string))
class Solution: def getMoneyAmount(self, n: int) -> int: @lru_cache(maxsize=None) def cost(low, high): """ minmax algorithm: the minimal values among all possible (worst) scenarios """ if low >= high: return 0 ...
# -*- coding: utf-8 -*- pad = '<pad>' unk = '<unk>' bos = '<bos>' eos = '<eos>'
# Reading input file f = open("inputs/day01.txt", "r") lines = f.readlines() input_numbers = list(map(lambda x: int(x.replace("\n","")), lines)) def part1(numbers): last_num = total = 0 first_line = True for number in numbers: if first_line: first_line = False elif number > last...
# MenuTitle: Compare Metrics # -*- coding: utf-8 -*- __doc__ = """ Compares the metrics values in all glyphs in the front font with the other opened font. Any glyphs with differences are coloured accordingly. """ Glyphs.clearLog() COLOR_1 = 3 COLOR_1_Name = 'Yellow' COLOR_2 = 7 COLOR_2_Name = 'Blue' COLOR_3 = 0 COLOR_...
class ComplianceAlertingException(Exception): pass class AwsClientException(ComplianceAlertingException): pass class ClientFactoryException(ComplianceAlertingException): pass class FilterConfigException(ComplianceAlertingException): pass class MissingConfigException(ComplianceAlertingException):...
CONSTANTS = [ ['tau', 6.28318530717958623200, 'τ'], ['e', 2.71828182845904509080, 'e'] ] cst = [x[0] for x in CONSTANTS] def replace_constants(string): for cnst in CONSTANTS: string = string.replace(cnst[0],str("{:.20f}".format(cnst[1]))) return string
# # @lc app=leetcode.cn id=242 lang=python3 # # [242] 有效的字母异位词 # # https://leetcode-cn.com/problems/valid-anagram/description/ # # algorithms # Easy (63.98%) # Likes: 394 # Dislikes: 0 # Total Accepted: 244.5K # Total Submissions: 382.2K # Testcase Example: '"anagram"\n"nagaram"' # # 给定两个字符串 s 和 t ,编写一个函数来判断 t 是...
def keep_while(func, items): for item in items: result = func(item) if result: yield item
''' Created on 30.12.2018 @author: ED ''' name = "PyTrinamic" desc = "TRINAMIC's Python Technology Access Package" def showInfo(): print(name + " - " + desc) " motor types " class MotorTypes(): DC = 0 BLDC = 1 DC_BLDC = 2 STEPPER = 3 ...
IMAGE_DIR = './data' CONTENT_IMAGE_NAME = 'octopus.jpg' STYLE_IMAGE_NAME = 'hockney.jpg' SIZE = 400 STEPS = 2000 DISPLAY_INTERVAL = 400
"""Custom Exception Classes for Phylotyper Module """ class PhylotyperError(Exception): """Basic exception for errors raised by Phylotyper modules""" def __init__(self, subtype, msg=None): if msg is None: msg = "An error occured for subtype {}".format(subtype) super(PhylotyperError...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool: if not root: return ...
class CapStr(str): # __new__实例化第一个调用的方法,很少重写,使用python默认方案就行 def __new__(cls, string): string = string.upper() return str.__new__(cls, string) a = CapStr("I love python") print(a)
def numLines(filename): 'telt het aantal regels in een bestand' infile = open(filename, 'r') lineList = infile.readlines() infile.close() return len(lineList) maxNummer = 0 lineCount = 1 kaartnummers = open("kaartnummers.txt", 'a') with open('kaartnummers.txt', 'r') as kaartnummers: # Dit is...
nil = 0 num = 0 max = 1 cap = 'A' low = 'a' print('Equality : \t', nil, '= =', num, nil == num) print('Equality : \t', cap, '= =', low, cap == low) print('Inequality : \t', nil, '!=', max, nil != max)
File = open("File PROTEK/Data2.txt", "r") dataMhs = {} i = 1 for data in File: dictsiji = {} dataDict = data.split("|") dictsiji['NIM'] = dataDict[0] dictsiji['Nama'] = dataDict[1] dictsiji['Alamat'] = dataDict[2].rstrip("\n") dataMhs[i] = dictsiji i += 1 print(dataMhs)
def extractGakuseitranslationsWordpressCom(item): ''' Parser for 'gakuseitranslations.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PGT', 'Every Morning the Most Popular G...
# 遍历二叉树 """ 给定一个数组,构建二叉树,并且按层次打印这个二叉树 """ class Node(object): """ 二叉树节点 """ def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def tree(): """ 1 / \ 3 2 /\ /\ 7 6 5 4 ...
# -*- coding: utf-8 -*- """ @description: @author: LiuXin @contact: xinliu1996@163.com @Created on: 2020/12/30 下午4:16 """ def get_inchannels(backbone): """ :return: """ if (backbone in ['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnext50_32x4d', 'wide_resnet50_2', 'wide_resnet101_2...
def leiaDinheiro(msg): while True: num = str(input(msg).strip().replace(',', '.')) cont = 0 if num.count('.') > 1: cont -= 1 for c, p in enumerate(num): if p.isnumeric(): cont += 1 if p == '.': cont += 1 if c...
n, m, x, y = map(int, input().split()) horse_position = [[x,y],[x-1,y-2], [x-1, y+2], [x+1, y-2], [x+1, y+2], [x-2, y-1], [x-2, y+1], [x+2, y-1], [x+2, y+1]] #print(horse_position) f = [[0, 1]] #calculating ways without hourse for i in range(1, n+1): f.append([1]) if ([i, 0] in horse_position): f[i][0] = 0 #prin...
today_date = input("Qual a data de hoje? ") breakfast_calories = int(input("\nCalorias do seu Café da manhã: ")) lunch_calories = int(input("\nCalorias do seu almoço: ")) dinner_calories = int(input("\nCalorias da sua janta: ")) snack_calories = int(input("\nCalorias do seu lanche: ")) content_calories = breakfast_cal...
#=================================\CONFIG./===================================== # default System camera access code = 1, if connect with any external camera put 1,2 and so on with the no of connected cameras. camera_no = 0 # To count the total number of people (True/False). People_Counter = True # Set the threshol...
n1 = float(input('Primeira nota: ')) n2 = float(input('Segunda nota: ')) n3 = float(input('Terceira nota: ')) m = (n1+n2+n3)/3 print('A sua média foi {:.1f}'.format(m)) if m >= 6.0: print('Sua média foi Boa! Parabéns!') else: print('Sua média foi ruim! ESTUDE MAIS!')
def get_file_type_from_extension(ext): ext_to_file = { 'py': 'python', 'c': 'c', 'cs': 'csharp', } return ext_to_file.get(ext)
""" İlkel veri tipli değişkenler sadece belli bir ilkel veri tipindeki değerleri tutmamızı sağlıyor. Ancak biz birden fazla değeri tek bir değişkenin içinde tutmak istediğimizde koleksiyon (colections) adı verilen veri tiplerinden yararlanıyoruz. Bu veri tipleri: 1.Liste(List) 2.Sözlük(Disctio...
d = float(input('Insira distancia ser percorrida: ')) if d <= 200: p = d * 0.50 print(f'A viagem vai custar R${p:.2f}') else: p = d * 0.45 print(f'A viagem vai custar R${p:.2f}')
# numeros de casos entrance = int(input()) # variavel countC = 0 listaP = [] p1 = 2 p2 = 3 p3 = 5 # calcular media while countC < entrance: a1, a2, a3 = map(float, input().split(' ')) mediaP = ((a1 * p1) + (a2 * p2) + (a3 * p3))/(p1 + p2 + p3) listaP.append(mediaP) countC = countC +...
# https://leetcode.com/problems/longest-common-prefix/ # Write a function to find the longest common prefix string amongst an array of # strings. # If there is no common prefix, return an empty string "". ################################################################################ # one-pass -> compare with the...
# Problem Statement # # Given the root of a binary tree, then value v and depth d, you need to add a # row of nodes with value v at the given depth d. The root node is at depth 1. # # The adding rule is: given a positive integer depth d, for each NOT null tree # nodes N in depth d-1, create two tree nodes with value v ...
S = input() things = [] curr = S[0] count = 1 for i in range(1,len(S)): if(S[i] == curr): count += 1 else: things.append((count,int(curr))) count = 1 curr = S[i] things.append((count,int(curr))) print(" ".join(str(i) for i in things))
# https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ # Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): # Runtime: 41 ms, faster than 46.10% of Python online...
for _ in range(int(input())): n = int(input()) pages=list(map(int,input().split())) m = int(input()) mem = [] ans=0 i=0 while i<n: if pages[i] not in mem: if len(mem)==m: mem.pop(0) mem.append(pages[i]) else: mem...
''' cardlist.py Name: Wengel Gemu Collaborators: None Date: September 6th, 2019 Description: This program checks user input against a list to see if it is valid. ''' # this is a list containing all of the valid values for a card cards = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] card_value = input("En...
""" 0759. Employee Free Time Hard We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing common, positive-length free time for all ...
def plus_matrix(A,B) : C = zeroMat(A) for i in range(len(A)) : for j in range(len(A[0])) : C[i][j] = A[i][j] + B[i][j] return C def zeroMat(A): c = [] for i in range(len(A)): row = [] for _ in range(len(A[i])): row.append(0) c.append(row) ...
''' List Nesting ''' # List in string list_str = ['list in string', 'list'] str_nest = list_str print(str_nest) # List in List list0 = ['list', 'in'] list1 = ['list'] list_nest = [list0, list1] print(list_nest) # List in Dictionary list_dict0 = ['list', 'dictionary'] list_dict1 = ['in'] dict_nest = { 'secto...
class Language(object): ''' Programming Language mapper that should be subclassed by any new Language ''' valid_extensions = [] invalid_extensions = [] ignore_files = [] ignore_dirs = [] def __init__(self): pass def load_language( self ): raise NotImplementedError("load_language should be implemente...
class Solution(object): def validUtf8(self, data): """ :type data: List[int] :rtype: bool """ data_bin=map(lambda a: bin(a%2**8)[2:].zfill(8), data) # print data_bin k=0 while k<len(data_bin): num=data_bin[k] # print nu...
# mistertribs - experiment 2 # https://youtu.be/jZTu6qttvMU Scale.default = Scale.minor Root.default = 0 Clock.bpm = 105 ~b1 >> bass(dur=8, oct=4) ### b1.room = 1 b1.shape = PWhite(1) ### ~d1 >> play('V [ -]', dur=2, room=1, mix=.5) ~k1 >> karp([0,3,6,10], dur=.25, sus=.5, echo=.5, amp=var([0,1],[15,1]), oct=7) ...
""" 1146 medium snapshot array """ class SnapshotArray: # memory limit exceeded def __init__(self, length: int): self.array = [0] * length self.snaps = {} self.count = 0 def set(self, index: int, val: int) -> None: self.array[index] = val def snap(self) -> int: ...
def main(a, b, c, d): return 1 if a - c >= 2 and b - d >= 2 else 0 if __name__ == '__main__': print(main(*map(int, input().split())))
def dobro(n): return n*2 def metade(n): return n/2 def aumentar(n,v=10): novo = n x = (n*v)/100 return novo + x def diminuir(n,v=13): novo = n x = (n*v)/100 return novo - x
class AbstractRepositoryFile(object): ADDED = "A" MODIFIED = "M" DELETED = "D" IGNORED = "I" RENAMED = "R" UNVERSIONED = "?" NOT_MODIFIED = " " CONFLICTED = "C" STATE_MAP = { "A": "added", "M": "modified", "D": "deleted", "I": "ignored", "R": "renamed", "?": "unversioned", " ": "not modified...
if PY_V<2.7: class deque2(collections.deque): """ This class add support of <maxlen> for old deque in python2.6. Thx to Muhammad Alkarouri. http://stackoverflow.com/a/4020363 """ def __init__(self, iterable=(), maxlen=None): collections.deque.__init__(self, iterable, ...
######################################################################## ''' say something .... ''' # from epidemix.utils.plot import * # from epidemix.utils.partition import * __version__ = "1.1.2" ########################################################################
f1_scores_001_train = { 'Wake': [0.45828943664803573, 0.47566984186570316, 0.5875755194928342, 0.7704458983749956, 0.8776419969393865, 0.9099441500276573, 0.922647481237028, 0.9350972410673902, 0.9465349405012661, 0.9534392971969388, 0.9572805948925108, 0.9627780979304024, 0.96717726274524...
# Dynamic programming method ''' # mainRun(weight,value,capacity,type) n: number of items value: value of each item weight: weight of each item capacity: capacity of bag m: memery matrix type: 'right2left' or 'left2right' ''' # right to left def Knapsack(value,w...
#!/usr/bin/env python2 # Author: Jayden Navarro # CAPTURE_GROUP: default_project rgx_default_project = [ 'export CURR_WS=\"(.*)\"' ] fmt_default_project = 'export CURR_WS=\"%s\"\n' # CAPTURE_GROUP: projects rgx_projects = [ r'\"\$CURR_WS\" == \"(.*)\"', 'export CURR_PK=\"(.*)\"', 'export CURR_TYPE=\"...
def lazy_attr(compute_value_func): """ Use as a decorator for a method that computes a value based on unchanging data. It turns the function into a read-only property. It is computed only when requested, and stores the value so it only needs to be computed once. Notice that since it replaces the fun...
class Car: PURCHASE_TYPES = ("LEASE", "CASH") __sales_list = None @classmethod def get_purchase_types(cls): return cls.PURCHASE_TYPES @staticmethod def get_sales_list(): if Car.__sales_list == None: Car.__sales_list = [] return Car.__sales_list...
def nextGreaterElement(n: int) -> int: digits = list(reversed([int(d) for d in str(n)])) result = None for i in range(len(digits) - 1): if digits[i] > digits[i+1]: toSwap = 0 while digits[toSwap] <= digits[i+1]: toSwap += 1 digits[toSwap], digits[i...
class SudokuSolver: def __init__(self, board): self.board = board def print_board(self): """ Prints the current board to solve""" for i in range(len(self.board)): if i % 3 == 0 and i != 0: print("------------------------") for j in range(len(s...
# sum(of_list) is built in def mysumli(li): if li == []: return 0 else: return li[0] + mysumli(li[1:]) # print(li[0:-4]) lis = [1, 1, 1] print(mysumli(lis))
# Determining the Grade using the user's score = float(input('Enter score between 0.0 and 1.0: ')) if score > 0.0 and score < 1.0: if score >= 0.9: print('A') elif score >= 0.8: print('B') elif score >= 0.7: print('C') elif score >= 0.6: print('D') else: pri...