content
stringlengths
7
1.05M
def add_native_methods(clazz): def initProto____(): raise NotImplementedError() def socketCreate__boolean__(a0, a1): raise NotImplementedError() def socketConnect__java_net_InetAddress__int__int__(a0, a1, a2, a3): raise NotImplementedError() def socketBind__java_net_InetAddres...
# -*- coding: utf-8 -*- """ Created on Sun Apr 8 09:45:29 2018 @author: abaena """ DATATYPE_AGENT = 'agent' DATATYPE_PATH_METRICS = 'pathmet' DATATYPE_LOG_EVENTS = 'logeve' DATATYPE_LOG_METRICS = 'logmet' DATATYPE_MONITOR_HOST = 'host' DATATYPE_MONITOR_MICROSERVICE = 'ms' DATATYPE_MONITOR_TOMCAT = 'tomc' DATATYPE_...
''' This can be solved using the slicing method used in list. We have to modify the list by take moving the last part of the array in reverse order and joining it with the remaining part of the list to its right''' class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return...
'''Crie um programa que leia dois valores e mostre um menu na tela: [1] somar [2] multiplicar [3] maior [4] novos numeros [5] sair do programa Seu programa devera realizar a operação solicitada em cada caso''' v1= int(input('Digite um numero: ')) v2 = int(input('Digite outro numero: ')) operac...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/viki/catkin_ws/src/beginner_tutorials/msg/Num.msg" services_str = "/home/viki/catkin_ws/src/beginner_tutorials/srv/ResetCount.srv;/home/viki/catkin_ws/src/beginner_tutorials/srv/AddTwoInts.srv" pkg_name = "beginner_tutorials" dependencies_str = ...
x=int(input("no 1 ")) y=int(input("no 2 ")) def pow(x,y): if y!=0: return(x*pow(x,y-1)) else: return 1 print(pow(x,y))
#!/usr/bin/python hamming_threshold = [50, 60] pattern_scale = [4.0, 6.0, 8.0, 10.0] fp_runscript = open("/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_validation.sh", 'w') fp_runscript.write("#!/bin/bash\n\n") cnt = 0 for i in range(len(hamming_threshold)): for j in range(len(pattern_scale)): cn...
# 2021.04.16 hard: class Solution: def isScramble(self, s1: str, s2: str) -> bool: ''' dp 问题: 1. 子字符串应该一样长. 很简单已经保证了 子字符串一样,那么久直接返回 True 2. 子字符串中 存在的字母应该一样, 同一个字母的数量应该一样多 Count() 两种分割方式,交换 或者 不交换不断的迭代下去: 分割的两种方式要写对! ''' @cache def df...
#!/usr/bin/env python colors = ['white', 'black'] sizes = ['S', 'M', 'L'] tshirts = [(color, size) for size in sizes for color in colors ] print(tshirts) tshirts = [(color, size) for color in colors for size in sizes ] print(tshirts)
if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) max = -9999999 max2 = -9999999 for i in arr: if(i>max): max2=max max=i elif i>max2 and max>i: max2=i print(max2)
class Stack: def __init__(self): self.stack = [] def add(self, dataval): # Use list append method to add element if dataval not in self.stack: self.stack.append(dataval) return True else: return False # Use peek to look at the top of the stack d...
class KataResult: def __init__(self, revenue, ipa, cost_of_kata, net_income, cost_of_goods, kata_penalty): self.revenue = revenue self.ipa = ipa self.cost_of_kata = cost_of_kata self.net_income = net_income self.cost_of_goods = cost_of_goods self.kata_penalty = kata...
su = 0 a = [3,5,6,2,7,1] print(sum(a)) x, y = input("Enter a two value: ").split() x = int(x) y = int(y) su = a[y] + sum(a[:y]) print(su)
def test_topic_regexp_matching(dequeuer): msg = {'company_name': 'test_company'} actions_1 = tuple(dequeuer.get_actions_for_topic('object__created', msg)) actions_2 = tuple(dequeuer.get_actions_for_topic('object__deleted', msg)) actions_3 = tuple(dequeuer.get_actions_for_topic('otherthing__created', msg...
# Find the closest number # Difficulty: Basic   Marks: 1 ''' Given an array of sorted integers. The task is to find the closest value to the given number in array. Array may contain duplicate values. Note: If the difference is same for two values print the value which is greater than the given number. Input: The firs...
#!/usr/bin/env python3 """sum_double Given two int values, return their sum. Unless the two values are the same, then return double their sum. sum_double(1, 2) → 3 sum_double(3, 2) → 5 sum_double(2, 2) → 8 source: https://codingbat.com/prob/p141905 """ def sum_double(a: int, b: int) -> int: """Sum Double. ...
# -*- coding: utf-8 -*- VERSION = (1, 0, 4) __version__ = "1.0.4" __authors__ = ["Stefan Foulis <stefan.foulis@gmail.com>", ]
''' This is the exceptions module: ''' ''' Exception of when user do not have the access to certain pages. ''' class CannotAccessPageException(Exception): pass ''' Exception of the first password and the second password does not match during registration. ''' class PasswordsNotMatchingException(Exception): p...
class TransportContext(object): """ The System.Net.TransportContext class provides additional context about the underlying transport layer. """ def GetChannelBinding(self,kind): """ GetChannelBinding(self: TransportContext,kind: ChannelBindingKind) -> ChannelBinding Retrieves the requested channel...
# encoding: utf-8 # input data constants MARI_EL = 'Республика Марий Эл' YOSHKAR_OLA = 'Республика Марий Эл, Йошкар-Ола' VOLZHSK = 'Республика Марий Эл, Волжск' VOLZHSK_ADM = 'Республика Марий Эл, Волжский район' MOUNTIN = 'Республика Марий Эл, Горномарийский район' ZVENIGOVO = 'Республика Марий Эл, Звениговский райо...
# Copyright 2016-2022 The FEAGI Authors. All Rights Reserved. # # 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 applic...
def is_triangle(func): def wrapped(sides): if any(i <= 0 for i in sides): return False sum_ = sum(sides) if any(sides[i] > sum_ - sides[i] for i in range(3)): return False return func(sides) return wrapped @is_triangle def is_equilateral(sides): retu...
#!/usr/bin/env python # -*- coding: utf-8 -*- BOT_NAME = 'book' SPIDER_MODULES = ['book.spiders'] NEWSPIDER_MODULE = 'book.spiders' IMAGES_STORE = '../storage/book/' COOKIES_ENABLED = True COOKIE_DEBUG = True LOG_LEVEL = 'INFO' # LOG_LEVEL = 'DEBUG' CONCURRENT_REQUESTS = 100 CONCURRENT_REQUESTS_PER_DOMAIN = 1000 U...
AP = "AP" BP = "BP" ARRIVE = "ARRIVE" NEUROMODULATORS = "NEUROMODULATORS" TARGET = "TARGET" OBSERVE = "OBSERVE" SET_FREQUENCY = "SET_FREQUENCY" DEACTIVATE = "DEACTIVATE" ENCODE_INFORMATION = "ENCODE_INFORMATION"
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 9 00:00:43 2018 @author: joy """ print(5 + 3) print(9 - 1) print(2 * 4) print(16//2)
#! /usr/bin/python3 print("HELLO PYTHON")
try: with open('proxies.txt', 'r') as file: proxy = [ line.rstrip() for line in file.readlines()] except FileNotFoundError: raise Exception('Proxies.txt not found.')
DILAMI_WEEKDAY_NAMES = { 0: "شمبه", 1: "یکشمبه", 2: "دۊشمبه", 3: "سۊشمبه", 4: "چارشمبه", 5: "پئنشمبه", 6: "جۊمه", } DILAMI_MONTH_NAMES = { 0: "پنجيک", 1: "نؤرۊز ما", 2: "کۊرچ ٚ ما", 3: "أرئه ما", 4: "تیر ما", 5: "مۊردال ما", 6: "شریرما", 7: "أمیر ما", 8: ...
#Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. #O programa será interronpido quando o número solicitado for negativo. c = 0 while True: print(30*'-') num = int(input('Quer ver a tabuada de qual valor ?')) print(30*'-') if num < 0: ...
""" Fragments of project version mutations """ PROJECT_VERSION_FRAGMENT = ''' content id name projectId '''
text = input() punc_remove = [",", ".", "!", "?"] for i in punc_remove: text = text.replace(i, "") print(text.lower())
''' Student: Dan Grecoe Assignment: Homework 1 Submission of the first homework assignment. The assignment was to create a python file with 2 functions multiply - Takes two parameters x and y and returns the product of the values provided. noop - Takes 0 parameters and returns...
# `name` is the name of the package as used for `pip install package` name = "package-name" # `path` is the name of the package for `import package` path = name.lower().replace("-", "_").replace(" ", "_") version = "0.1.0" author = "Author Name" author_email = "" description = "" # summary license = "MIT"
class TestClient: """ Test before_request and after_request decorators in __init__.py. """ def test_1(self, client): # disallowed methods res = client.put("/") assert res.status_code == 405 assert b"Method Not Allowed" in res.content res = client.options("/api/post/add...
x = 1 #x recebe 1 #print irá printar(mostrar) o valor desejado; print(x) # resultado: 1 print(x + 4) # é possível somar uma variável com um número, desde que a variável tenha um valor definido - resultado: 5 print(2 * 2) #um asterisco é usado para multiplicar - resultado: 4 print(3 ** 3) #dois asterisco é usado para el...
""" 继承调用关系 """ class A: def a_say(self): print('执行A:', self) class B(A): def b_say(self): A.a_say(self) # 效果与下面的语句相同 super().a_say() # super()方法调用父类的定义, # 默认传入当前对象的引用self A().a_say() # 类对象的直接使用,先创建一个类对象A print('执行B:', self) a = A() b = B() a.a_say()...
class Graph(object): """ A simple undirected, weighted graph """ def __init__(self): self.nodes = set() self.edges = {} self.distances = {} def add_node(self, value): self.nodes.add(value) def add_edge(self, from_node, to_node, distance): ...
class Config(object): """Configuration primitives. Inherit from or instantiate this class and call configure() when you've got a dictionary of configuration values you want to process and query. Would be nice to have _expand_cidrlist() so blacklists can specify ranges. """ def __init__(self, ...
__title__ = 'cisco_support' __description__ = 'Cisco Support APIs' __version__ = '0.1.0' __author__ = 'Dennis Roth' __license__ = 'MIT'
velocidade = float(input("Digite a sua velocidade em Km/h: ")) if velocidade > 80: amais = velocidade - 80 amais = amais*7 print("Você foi multado, devera pagar uma multa de: R${:.2f}".format(amais)) print("FIM, não se mate")
elements = [int(x) for x in input().split(', ')] even_numbers = [x for x in elements if x % 2 == 0] odd_numbers = [x for x in elements if x % 2 != 0] positive = [x for x in elements if x >= 0] negative = [x for x in elements if x < 0] print(f"Positive: {', '.join(str(x) for x in positive)}") print(f"Negative: {', '.j...
vals = { "yes" : 0, "residential" : 1, "service" : 2, "unclassified" : 3, "stream" : 4, "track" : 5, "water" : 6, "footway" : 7, "tertiary" : 8, "private" : 9, "tree" : 10, "path" : 11, "forest" : 12, "secondary" : 13, "house" : 14, "no" : 15, "asphalt" : 16, "wood" : 17, "grass" : 18, "paved" : 19, "primary" : 20, "un...
n1 = int(input('Digite um número e veja qual a sua tabuada: ')) n = 0 print('{} X {:2} = {:2}'.format(n1, 0, n1*n)) while n < 10: n += 1 print('{} X {:2} = {:2}'.format(n1, n, n1*n))
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ return binarySearch(nums,target,0,len(nums)-1) def binarySearch(nums, target, low, high): if (low > high): return -1 ...
def write_file(filess, T): f = open(filess, "w") for o in T: f.write("[\n") for l in o: f.write(str(l)+"\n") f.write("]\n") f.close() def save_hidden_weight(nb_hidden, hiddenw): for i in range(nb_hidden): write_file("save/base_nn_hid_" + str(i+1) + "w.nn", hiddenw[i]) def load_hiddenw(filess, hi...
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:148 ms, 在所有 Python3 提交中击败了35.57% 的用户 内存消耗:13.7 MB, 在所有 Python3 提交中击败了36.81% 的用户 解题思路: 回溯 具体实现见代码注释 """ class Solution: def splitIntoFibonacci(self, S: str) -> List[int]: def backtrack(S, current): if S == '' and len(current) > 2: # 字...
class Config(object): embedding_size = 300 n_layers = 1 hidden_size = 128 drop_prob = 0.2
begin_unit comment|'#!/usr/bin/env python' nl|'\n' nl|'\n' comment|'# Copyright 2013 OpenStack Foundation' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License");' nl|'\n' comment|'# you may not use this file except in compliance with the License.' nl|'\n' comment|'# You m...
class BrainfuckException(Exception): pass class BLexer: """ Static class encapsulating functionality for lexing Brainfuck programs. """ symbols = [ '>', '<', '+', '-', '.', ',', '[', ']' ] @staticmethod def lex(code): """ Return a generator for tokens in...
load("@fbcode_macros//build_defs:config.bzl", "config") load("@fbcode_macros//build_defs/config:read_configs.bzl", "read_int") load("@fbcode_macros//build_defs:core_tools.bzl", "core_tools") def _create_build_info( build_mode, buck_package, name, rule_type, platform, epochtime=0, host="", ...
sm.setSpeakerID(1013000) sm.sendNext("Ugh. This isn't going to work. I need something else. No plants. No meat. What, you have no idea? But you're the master, and you're older than me, too. You must know what'd be good for me!") sm.setPlayerAsSpeaker() sm.sendSay("#bBut I don't. It's not like age has anything to do wi...
class Solution: def chooseandswap (self, A): opt = 'a' fir = A[0] arr = [0]*26 for s in A : arr[ord(s)-97] += 1 i = 0 while i < len(A) : if opt > 'z' : break while opt < fir : if o...
class AccountManager(object): def __init__(self, balance = 0): self.balance = balance def getBalance(self): return self.balance def withdraw(self, value): if self.balance >= value: self.balance = self.balance - value print('Successful Withdrawal.') ...
class Response(object): """ """ def __init__(self, status_code, text): self.content = text self.cached = False self.status_code = status_code self.ok = self.status_code < 400 @property def text(self): return self.content def __repr__(self): retu...
# Exercicio 01 Tuplas x = int(input('Digite o primeiro numero: ')) y = int(input('Digite o segundo numero: ')) cont = 1 soma = x while cont < y: soma = soma + x cont = cont + 1 print('O resultado eh: {}' .format(soma))
''' To have a error free way of accessing and updating private variables, we create specific methods for this. Those methods which are meant to set a value to a private variable are called setter methods and methods meant to access private variable values are called getter methods. The below code is an example of g...
class Solution: def isMatch(self, s: str, p: str) -> bool: # this is a dynamic programming solution fot this matrix = [[False for x in range(len(p) + 1)] for x in range(len(s) + 1)] matrix[0][0] = True for i in range(1, len(matrix[0])): if p[i - 1] == "*": ...
# https://open.kattis.com/problems/luhnchecksum for _ in range(int(input())): count = 0 for i, d in enumerate(reversed(input())): if i % 2 == 0: count += int(d) continue x = 2 * int(d) if x < 10: count += x else: x = str(x) ...
inputFile = "3-input" outputFile = "3-output" dir = {'L': [-1,0],'R': [1,0],'U': [0,1],'D': [0,-1]} def readFile(): file = open(inputFile, "r") A,B = file.readlines() A,B = [line.split(",") for line in [A,B]] file.close() return A,B def writeFile(a, b): file = open(outputFile, "w+") fil...
name = 'Urban Dictionary Therapy' __all__ = ['UDTherapy', 'helper']
# -*- coding: utf-8 -*- """ Solution to Project Euler problem 179 - Consecutive positive divisors Author: Jaime Liew https://github.com/jaimeliew1/Project_Euler_Solutions """ def run(): N = int(1e7) n_factors = [1 for _ in range(N + 1)] # can start at 2 because 1 is a divisor for all numbers and wont c...
""" Problem: -------- Design a data structure that supports the following two operations: - `void addNum(int num)`: Add a integer number from the data stream to the data structure. - `double findMedian()`: Return the median of all elements so far. """ class MedianFinder: def __init__(self): """ ...
class SimulateMode: @staticmethod def start_simulation(device, guide=None): return
# Uses python3 n = int(input()) if n == 1: print(1) print(1) quit() W = n prizes = [] for i in range(1, n): if W>2*i: prizes.append(i) W -= i else: prizes.append(W) break print(len(prizes)) print(' '.join([str(i) for i in prizes]))
# Question 8 # Print even numbers in a list, stop printing when the number is 237 numbers = [ 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 8...
requested_toppings = ['mushrooms', 'extra cheese'] if 'mushrooms' in requested_toppings: print("Adding mushrooms.") if 'pepperoni' in requested_toppings: print("Adding pepperoni.") if 'extra cheese' in requested_toppings: print("Adding extra cheese.") print("\nFinished making your first pizza!") if 'mush...
# markdownv2 python-telegram-bot specific joined = '{} joined group `{}`' not_joined = '{} is already in group `{}`' left = '{} left group `{}`' not_left = '{} did not join group `{}` before' mention_failed = 'There are no users to mention' no_groups = 'There are no groups for this chat' # html python-telegram-bot spe...
class A: def fazer_algo(self): print("Palmeiras") def outro(self): print("campeão") class B: def __init__(self): self.a = A() def fazer_algo(self): #delega para self.a return self.a.fazer_algo() def outro(self): #delegando novamente return sel...
"""Defines a rule for runsc test targets.""" load("@io_bazel_rules_go//go:def.bzl", _go_test = "go_test") # runtime_test is a macro that will create targets to run the given test target # with different runtime options. def runtime_test(**kwargs): """Runs the given test target with different runtime options.""" ...
# Copyright 2019-2021 Huawei Technologies Co., Ltd # # 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 agre...
# -*- coding: utf-8 -*- MNIST_DATASET_PATH = 'raw_data/mnist.pkl.gz' TEST_FOLDER = 'test/' TRAIN_FOLDER = 'train/' MODEL_FILE_PATH = 'model/recognizer.pickle' LABEL_ENCODER_FILE_PATH = 'model/label_encoder.pickle' # Manual DEMO_HELP_MSG = '\n' + \ 'Input parameter is incorrect\n' + \ 'Display ...
#! /usr/bin/env python def cut_the_sticks(a): cuts = [] while len(a) > 0: cutter = a.pop() if cutter == 0: continue for i in range(len(a)): a[i] -= cutter cuts.append(len(a) + 1) return cuts if __name__ == '__main__': _ = input() value = map...
#pedir a altura e a largura de uma parede e dizer quantos litros de tinta vai gastar sabendo que cada litro de tinta pinta 2m2 altura = float(input('Qual a altura da parede? ')) largura = float(input('Qual a largura da parede? ')) area = altura * largura tinta = (altura * largura) / 2 print('Voce tem a area de {}x{} ...
nota1 = float(input('nota 1: ')) nota2 = float(input('nota 2: ')) media = (nota1 + nota2)/2 print('A media entre a nota 1 e a nota 2 é {}'.format(media))
num = int(input("Insira um numero para descobrir se este é par ou impar: ")) if num % 2 == 0: print("Este numero é par") else: print("Este numero é impar")
""" Configuration for docs """ # source_link = "https://github.com/[org_name]/pos_multie_print" # docs_base_url = "https://[org_name].github.io/pos_multie_print" # headline = "App that does everything" # sub_heading = "Yes, you got that right the first time, everything" def get_context(context): context.brand_html =...
tanmuContent = ''' <style> .barrage-input-tip { z-index: 1999; position: absolute; left: 10px; width: 179.883px; height: 35.7422px; line-height: 35.7422px; border-radius: 35.7422px; box-sizing: border-box; color: rgb(255, 255, 255); ...
# Moore Voting # Majority Element # Given an array of size n, find the majority element. # The majority element is the element that appears more than ⌊ n/2 ⌋ times. # assume at leat one element class Solution(object): def majorityElement(self, nums): count, major_num = 0, nums[0] for num in nums: ...
n, k, v = int(input()), int(input()), [] for i in range(n): v.append(int(input())) v = sorted(v, reverse=True) print(k + v[k:].count(v[k-1]))
#! python3 # __author__ = "YangJiaHao" # date: 2018/1/26 class Solution: def lengthOfLongestSubstring(self, s: str) -> int: d = dict() l, r = 0, 0 res = 0 while r < len(s): if s[r] not in d: d[s[r]] = None r += 1 res = max(...
def get_field_name_from_line(line): return line.split(':')[1].strip() def remove_description(line): if '-' in line: return line.split('-')[0].strip() else: return line def split_multiple_field_names(line): if ',' in line: field_names = line.split(',') return map(lambda ...
# -*- coding: utf-8 -*-# ''' @Project : ClassicAlgorighthms @File : HashTable.py @USER : ZZZZZ @TIME : 2021/4/25 18:25 ''' class Node(): ''' 链地址法解决冲突的结点 ''' def __init__(self, value = None, next = None): self.val = value self.next = next class HashTable(): ...
class Circle: def __init__(self, radius): self.radius = radius def compute_area(self): return self.radius ** 2 * 3.14 circle = Circle(2) print("Area of circuit: " + str(circle.compute_area()))
class Solution: def addStrings(self, num1: str, num2: str) -> str: i, j, result, carry = len(num1) - 1, len(num2) - 1, '', 0 while i >= 0 or j >= 0: if i >= 0: carry += ord(num1[i]) - ord('0') if j >= 0: carry += ord(num2[j]) - ord('0') ...
word = input('Enter a word') len = len(word) for i in range(len-1, -1, -1): print(word[i], end='')
ss = input('Please give me a string: ') if ss == ss[::-1]: print("Yes, %s is a palindrome." % ss) else: print('Nevermind, %s isn\'t a palindrome.' % ss)
class AbridgerError(Exception): pass class ConfigFileLoaderError(AbridgerError): pass class IncludeError(ConfigFileLoaderError): pass class DataError(ConfigFileLoaderError): pass class FileNotFoundError(ConfigFileLoaderError): pass class DatabaseUrlError(AbridgerError): pass class Ex...
def aumentar(preco, taxa): p = preco + (preco * taxa/100) return p def diminuir(preco, taxa): p = preco - (preco * taxa/100) return p def dobro(preco): p = preco * 2 return p def metade(preco): p = preco / 2 return p
DOMAIN = "fitx" ICON = "mdi:weight-lifter" CONF_LOCATIONS = 'locations' CONF_ID = 'id' ATTR_ADDRESS = "address" ATTR_STUDIO_NAME = "studioName" ATTR_ID = CONF_ID ATTR_URL = "url" DEFAULT_ENDPOINT = "https://www.fitx.de/fitnessstudios/{id}" REQUEST_METHOD = "GET" REQUEST_AUTH = None REQUEST_HEADERS = None REQUEST_PAYLOA...
#!/usr/bin/env python3 # coding: UTF-8 '''! module description @author <A href="email:fulkgl@gmail.com">George L Fulk</A> ''' __version__ = 0.01 def main(): '''! main description ''' print("Hello world") return 0 if __name__ == "__main__": # command line entry point main() # END #
# https://www.facebook.com/hackercup/problem/169401886867367/ __author__ = "Moonis Javed" __email__ = "monis.javed@gmail.com" def numberOfDays(arr): arr = sorted(arr) n = 0 while len(arr) > 0: k = arr[-1] w = k del arr[-1] while w <= 50: try: del arr[0] w += k except: break if w > 50: ...
class Robot: def __init__(self, left="MOTOR4", right="MOTOR2", config=1): print("init") def forward(self): print("forward") def backward(self): print("backward") def left(self): print("left") def right(self): print("right") def stop(self): pri...
"""Exceptions.""" class OandaError(Exception): """ Generic error class, catches oanda response errors """ def __init__(self, error_response): self.error_response = error_response msg = f"OANDA API returned error code {error_response['code']} ({error_response['message']}) " super...
""" Entradas monto de dinero presupuestal-->float-->a Salidas dinero correspondiente para ginecologia-->float-->b dinero correspondiente para traumatologia-->float-->c dinero correspondiente para pediatria-->float-->d """ a=float(input("Presupuesto anual al Hospital rural ")) b=a*0.40 c=a*0.30 d=a*0.30 print("El presup...
''' Created on 1.12.2016 @author: Darren '''''' Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path...
#Represents an object class Object: def __init__(self,ID,name): self.name = name self.ID = ID self.importance = 1 #keep track of the events in which this file was the object self.modifiedIn = [] self.addedIn = [] self.deletedIn = [] def getName(self)...
def uint(x): # casts x to unsigned int (1 byte) return x & 0xff def chunkify(string, size): # breaks up string into chunks of size chunks = [] for i in range(0, len(string), size): chunks.append(string[i:i + size]) return chunks def gen_rcons(rounds): # generates and returns round constants # the round cons...
def modulus_three(n): r = n % 3 if r == 0: print("Multiple of 3") elif r == 1: print("Remainder 1") else: assert r == 2, "Remainder is not 2" print("Remainder 2") def modulus_four(n): r = n % 4 if r == 0: print("Multiple of 4") elif r == 1: p...
""" Contains classes to handle batch data components """ class ComponentDescriptor: """ Class for handling one component item """ def __init__(self, component, default=None): self._component = component self._default = default def __get__(self, instance, cls): try: if ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 7 03:26:16 2019 @author: sodatab MITx: 6.00.1x """ """ 03.6-Finger How Many --------------------- Consider the following sequence of expressions: animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals...