content
stringlengths
7
1.05M
"""Class that provides function(s) related to calcuations of Fibonacci numbers. TODO: Add some additional error handling: - How do I handle desiredSequence and ensuring it is an integer. TODO: Overflow handling? TODO: Can I cleanup the calculation """ class Fibonacci: """This class provides Fibonacci...
class File: def directory(self) -> str: pass def name(self) -> str: pass def extension(self) -> str: pass def path(self): return self.directory() + self.name() + self.extension() class FileBase(File): directoryStr = '' nameStr = '' extensionStr = '' ...
class pointsTrajectory: def __init__(self, points, factor = [1,1]): self.factor = factor self.points = [[-1, 0]] + points + [[1, 0]] def getPos(self, phase, factor = None): factorTotal = self.factor if(factor != None): for i in range(len(factor)): factorTotal *= factor[i] #Contact with the ground...
ABI_ENDPOINT = "https://api.etherscan.io/api?module=contract&action=getabi&address=" POLYGON_ABI_ENDPOINT = ( "https://api.polygonscan.com/api?module=contract&action=getabi&address=" ) ENDPOINT = "" POLYGON_ENDPOINT = "" ATTRIBUTES_FOLDER = "raw_attributes" IMPLEMENTATION_SLOT = ( "0x360894a13ba1a3210667c828492...
def test_is_open_property(factories): survey = factories.SurveyFactory(num_expected=5) survey.record_salary(10, key=5) survey.record_salary(10, key=3) survey.record_salary(10, key=7) survey.record_salary(10, key=13) assert survey.is_open assert not survey.is_finalized survey.finalize(1...
#Given a string s, find all its potential permutations. #The output should be sorted in lexicographical order. #For s = "CBA", the output should be # stringPermutations(s) = ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]; #For s = "ABA", the output should be # stringPermutations(s) = ["AAB", "ABA", "BAA"]. #CodeSignal p...
def mdc12(x): y = [] if x["_MDC12"] == 0: return y if x["707&708|ORPCS"] > 0: if x["_MCC"] + x["_CC"] > 0: y.append("707") else: y.append("708") if x["709&710|ORPCS"] > 0: if x["_MCC"] + x["_CC"] > 0: y.append("709") else: ...
""" Various hooks for extending Splitgraph, including: * External object handlers (:mod:`splitgraph.hooks.external_objects`) allowing to download/upload objects to locations other than the remote Splitgraph engine. * FDW handlers (:mod:`splitgraph.hooks.mount_handlers`) that allow to use the Postgres engine's ...
# Generated by https://github.com/chanzuckerberg/single-cell-curation/blob/main/notebooks/compute_ancestor_mapping.ipynb ontology_mapping = { "HsapDv:0000000": ["HsapDv:0000000"], "HsapDv:0000001": ["HsapDv:0000001"], "HsapDv:0000002": ["HsapDv:0000002", "HsapDv:0000045", "HsapDv:0000001"], "HsapDv:000...
t=int(input()) for i in range(t): n=int(input()) arr_a=[0]*n arr_b=[0]*n arr_a=[int(x) for x in input().split()] arr_b=[int(x) for x in input().split()] arr_a_min=min(arr_a) arr_b_min=min(arr_b) ans=0 for i in range(n): if arr_b[i] != arr_b_min and arr_a[i] == arr_a_min: ans += (arr_b[i] - arr_b_min) if...
class Tile: map_word = "Pine forest" def describe(self): print("There are not so many trees around but the ground is full of " "pine needles and pine cones.\n") def action(self, player, do): print("I don't understand.") def leave(self, player, direction): ...
def find_erasures(bit_list: list, codeword_length: int, data_words: int): erasures = [] for c in range(0, codeword_length*data_words, codeword_length): all_one = (bit_list[c:c+codeword_length].count('1') == codeword_length) all_zero = (bit_list[c:c+codeword_length].count('0') == codeword_length)...
def test_smoke(client): r = client.get('/', follow_redirects=True) assert r.status_code == 200 assert 'Registreerimisvorm' in r.data
#!/usr/bin/env python2 #encoding: UTF-8 def fizz_buzz(n): """ return fizz when divisible by 3 return buzz when divisible by 5 return fizzbuz when divisible by both 3 and 5 """ if n % 3 == 0 and n % 5 == 0: return 'fizzbuzz' elif n % 3 == 0: return 'fizz' elif n % 5 == 0: ...
class Complex : def __init__(self, x, y) : self.rPart = x self.iPart = y def __str__(self) : return 'Complex({0} + i{1})'.format(self.rPart, self.iPart) def __eq__(self, other) : return self.rPart == other.rPart and self.iPart == other.iPart def __add__(self, oth...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def deleteNode(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode...
def make_string(w): if w == '': return '' u = w[0] count = 1 if u == '(' else -1 chk_perfect = (True if count > 0 else False) for ch in w[1:]: u += ch count += (1 if ch == '(' else -1) if count == 0: break if chk_perfect and count < 0: ...
s = "abcsssaa" print(s.count('a')) print(s.count('s'))
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node'): if not root: return [] stack, results = [(root, 0)], [] while stack: ...
# -*- coding: utf-8 -*- ''' Helper functions ''' def get_value_or_none(value): value = float(value) if value == -1.0: return None return value def gazepoint_to_icl_pointlist_v1(gp): x = get_value_or_none(gp['comb_x']) y = get_value_or_none(gp['comb_y']) return [x, y] def gazepoint_to_...
current_floor = 0 with open("exercise_and_input/01/input.txt", "r") as f: content = f.readlines() parens = content[0].strip() current_floor += parens.count("(") current_floor -= parens.count(")") print(f"Last floor : {current_floor}") # Now we go one by one to find when santa gets in the basement current_floo...
def maxPoints(elements): # Write your code here retMaxPoints = 0 uniqueElements = set() for tElement in elements: uniqueElements.add(tElement) countElements = {} for tElement in elements: if(tElement not in countElements): countElements[tElement] = 0 cou...
RANDOM_SEED = 42 N_SAMPLE = 1000 ERROR_THRESHOLD = .5 NUM_FEATURES = 6 TREATMENT_COL = 'treatment' SCORE_COL = 'score' GROUP_COL = 'group' OUTCOME_COL = 'outcome' CONTROL_NAME = 'control' TREATMENT_NAMES = [CONTROL_NAME, 'treatment1', 'treatment2', 'treatment3'] CONVERSION = 'conversion'
''' Python program to find the largest number where commas or periods are decimal points. Input: ['100', '102,1', '101.1'] Output: 102.1 ''' #License: https://bit.ly/3oLErEI def test(str_nums): str_nums_formatted = [] for s in str_nums: str_nums_formatted.append (float(s.replace(",", "."))) ...
class Farm: def visit_chickens(self) -> str: return "cluck" def visit_cows(self) -> str: return "moo" def visit_animals(animal: str) -> str: """ post: __return__ != "moo" """ try: return getattr(Farm(), "visit_" + animal)() except: return ""
a=[[1,2,3],[4,5,6]] b=[[0,0],[0,0],[0,0]] for i in range(3): for y in range(2): b[i][y]=a[y][i] print(b)
def generate_readable_list(list_to_process): """ Generate the message for get_command() to print when the user provides an input that does not match any commands. Arguments --------- commands : list[str] The list of commands that can be entered. Returns ------- ...
""" Module to load object """ class OBJ: """ Class to load object """ def __init__(self, filename, swapyz=False): """Loads a Wavefront OBJ file. """ self.vertices = [] self.normals = [] self.texcoords = [] self.faces = [] material = None...
class Solution: def XXX(self, str: str) -> int: INT_MAX = pow(2,31)-1 INT_MIN = pow(2,31) tag = 1 #去掉左边的空格 str = str.lstrip(' ') if(len(str)==0): return 0 #如果第一位是负号更改tag值,i后移一位 if(str[0] == '-' or str[0]=='+'): if(str[0]=='-'): ...
class BoardListProcessor: def getCardsPerListData(self, lists): output_data = {} for l,cards in lists.items(): output_data[l] = len(cards) return output_data def getCardsPerMemberData(self, lists, members): output_data = {} output_data = {...
# this is a comment. anything on a line that starts with a # is not treated by Python as code def my_function(a, var, var2, var_3, some_var, another_var, cow, pig): print(a + var + var2 + var_3 + some_var + another_var + cow + pig) my_function(8, 16, 32, 64, 128, 256, 512, 1024)
KEYWORDS_LIST = [ # 'yellow vests', # '#yellowvests', # 'gilets jaunes', # '#giletsjaunes', # 'macron', # 'french protests', 'brexit' ]
splunk = 'https://SPLUNK-SERVER-HERE' port = 'SPLUNK-HEC-PORT-HERE' token = "SPLUNK-HEC-TOKEN-HERE" def heckle(splunk, port, message, token): token = "Splunk " + token req = requests.post(splunk + ":"+ port + "/services/collector/raw", headers = { 'Authorization': token }, data = message) if req.status_c...
# # File: psaExceptions.py # Created: 05/09/2014 # Author: Francesco Ciaccia # # Description: # Custom execption class to manage error in the PSC # class psaExceptions(): class confRetrievalFailed(Exception): pass
def join_terms(terms): if len(terms) == 0: return "0" rval = "" first = True for sign, factors in terms: if first: if sign != '+': rval += sign first = False else: rval += " {} ".format(sign) if not factors: rval += "1" else: rval += " ".join(factors) ...
#~~~~~~ GAMES RULES ~~~~~~ #~~~~~~ DICTIONARIES ~~~~~~ #----- English ----- letters_english = [] #total length must be 100 for i in range(12): letters_english.append('E') for i in range(9): letters_english.append('I') letters_english.append('A') for i in range(8): letters_english.append('O') for i in range(6): ...
""" Sandbox for developing natural language processing (NLP) tools for Pylearn2, including datasets and models """
class Solution: def longestSubstring(self, s: str, k: int) -> int: if len(s) < k: return 0 for c in set(s): if s.count(c) < k: return max(self.longestSubstring(t, k) for t in s.split(c)) return len(s)
if len(editor.getSelText()) > 0: editor.copy() else: editor.copyText(editor.getCurLine())
ta = [int(e) for e in input().split()] tb = [int(e) for e in input().split()] sa = 0 sb = 0 for i in range(3): if ta[i] > tb[i]: sa += 1 elif ta[i] < tb[i]: sb += 1 print(f'{sa} {sb}')
def smart_truncate(content, length=120, suffix='...'): if len(content) <= length: return content else: return ' '.join(content[:length + 1].split(' ')[0:-1]) + suffix
n = int(input()) for i in range(n,0,-1): for j in range(i*2): print('*',end=' ') print() for i in range(1,n+1): for j in range(i*2): print('*',end=' ') print()
""" Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ # brute-force method num = 0 for i in range(1, 1001): num += i**i print ( str(num)[-10:] )
#!/usr/bin/env python """ Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits). 1st octet 128 has the binary representation: 10000000 2nd octet 32 has the binary representation: 00100000 3rd octet 10 has the binary representation: 00001010 ...
n = 0 while n < 10: n = n + 1 if n % 2 == 0: continue print(n) else: print('executed done')
def execution_time(fn, *args): start = time.time() fn(args) if args else fn() end = time.time() t = end - start print('fn {} took {} s to run'.format(fn.__name__, t))
class RunTests: def __init__(self): self.testlist = {} self.test_idx = 0 def add(self, test): self.testlist[len(self.testlist)] = test def start_test(self): if self.test_idx >= len(self.testlist): return idx = self.test_idx self.test_idx += 1 ...
script = """ distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \ && curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | apt-key add - \ && curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | tee /etc/apt/sources.list.d/nvidia-docker.list sudo apt-get update sudo apt-ge...
#! python3 print("2.3") name = "peter" print(f"Hello {name.title()}!. Do you want learn Python ") print("2.4") name = "peter" print(name.title()) print(name.upper()) print(name.lower()) print("2.5") name = "albert einstein" print(f"{name.title()} once said: 'A person who never made a mistake never tried anything new...
"""AWS API Errors""" class AWSError(Exception): """Base-class for all AWS Errors""" code = 'InvalidRequest' status = 400 class AWSSignatureMismatch(AWSError): """Error codes from https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html""" code = 'SignatureDoesNotMatch' status = 4...
n = [] a =[] while True: o = input('name, age separeted by space: ').split(' ') n.append (o[0]) a.append (int(o[1])) y = input('one more?(y/n): ') if y == 'n': break for idx, val in enumerate(n): print(f"user {idx}: {val}, {a[idx]}") sum = 0 for n in a: #цикл sum = sum + n #сумма все...
#!/usr/bin/env python3 # License MIT # Copyright 2016-2021 Alex Winkler # Version 3.0.0 guild_ids = [ 93055209017729024, 223949725068427264 ] logtarget = 339287109988909057 # Here the channel id of the channel we want the private channel logs to be stored in privcat = 360564294401916929 # This is the id of the "Pr...
def read_off(file): f=file.readline().strip() n_verts, n_faces, n_dontknow = tuple([int(s) for s in file.readline().strip().split(' ')]) verts = [[float(s) for s in file.readline().strip().split(' ')] for i_vert in range(n_verts)] faces = [[int(s) for s in file.readline().strip().split(' ')][1:] for i_f...
"""Settings for the ``multilingual_project_blog`` app.""" CANONICAL_URL_IGNORE_PATTERNS = [ r'\.ico', r'\.ics', r'/ctype/$', r'/admin/', ] HERO_SLIDER_APPS_MODELS_LIST = [ ('multilingual_news', 'newsentry'), ('document_library', 'document'), ('multilingual_events', 'event'), ]
# Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção Inteira. n = float(input('Digite um número real: ')) print(f'A parte inteira é {int(n)}')
# -*- coding: utf-8 -*- """ Created on Thu Aug 22 13:20:37 2019 @author: Joule """ class Spiller: """Spiller er en superclass for de senere spillertypene""" def __init__(self, name): self.name = name def velg_aksjon(self): """metode for å velge aksjon""" pass ...
def make_generators_generator(g): """Generates all the "sub"-generators of the generator returned by the generator function g. >>> def every_m_ints_to(n, m): ... i = 0 ... while (i <= n): ... yield i ... i += m ... >>> def every_3_ints_to_10(): ... fo...
# # PySNMP MIB module IBM2212-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IBM2212-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:39: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 2019, 0...
#!/usr/bin/env python n = input("Type in an integer for the amount of fibonacci numbers you want.") def fibs(n): fib_list = [1] a=0 b=1 while n > 1: fib_list.append(a+b) c=a a=b b=b+c n=n-1 return(fib_list) print(fibs(n))
def write_rel(output_path: str, rel: list, header: list, use_floats: [bool, None] = False): print(f"Writing python job output to {output_path}") with open(output_path, "w") as f: f.write(f"{','.join(header)}\n") if not use_floats: rows_formatted = [",".join(str(int(v)) for v in r...
# SPDX-License-Identifier: MIT """A pluggable Django application to generate analogous, legacy, paper-based calendar inlays.""" __author__ = "Mischback" """The current project owner.""" __app_name__ = "django-calingen" """The name of the application.""" __version__ = "1.0.0" """The current version.""" default_app_...
def hash_string(s): mod = 1000000009 result=0 for c in s: result = (result * 239 + ord(c)) % mod return result % mod
# -*- coding: utf-8 -*- # ap_version: '11point' / 'MaxIntegral' / 'Integral' test_iterations = 500 layer_test = "yes" # if Ture, test the already existed model; # if false, the model is not trained, and the result will be put in the Base/TempSpeed folder # and the model_idx will have no use. test_already_created = Tru...
# 入力 N = int(input()) A = [list(map(int, input().split())) for _ in range(N)] # Aに対してワーシャルフロイドを適用した結果と比較して解を求める ans = ( -1 if any( A[u][v] > A[u][k] + A[k][v] for u in range(N) for v in range(u + 1, N) for k in range(N) if k != u and k != v ) else sum(sum(a) for a in...
#!/usr/local/bin/python # -*- coding:utf-8 -*- def readTxT(): file_object = open('/Users/miraclewong/Projects/Python-for-Linux-SAAO/chapter8/ips.txt') try: str = file_object.read() print(str) finally: file_object.close() def main(): readTxT() if __name__ == '__main__': main(...
''' if __name__ == "__main__": import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) print(sys.path) '''
#DESAFIO VALIDAR DIGITO CPF cpf = input("Digite um cpf no formato ###.###.###-## ") cpf = cpf.replace('.', '') cpf = cpf.replace('-', '') cpf_format = cpf[:-2] total = 0 index = 0 reverso = 10 calcula_digito = 0 digito_1 = '' digito_2 = '' while digito_2 == '': if reverso >= 2: total += reverso * int(cpf_...
room = shape.box(-10, -4, -8, s=2, t=2, normalize_tc=False) room.texture = texture("prototype.png") room.pos.y = 2 sl = shape.sphere(0.05) sl.color.set(1, 0, 0, 0.5) player.left_hand.add_child(sl, True) sr = shape.sphere(0.05) sr.color.set(0, 1, 0, 0.5) sr.set_parent(player.right_hand) player.locomotion.walk(player....
################################## Main ################################## query_seq =input("Enter Protein Query Sequence : ") # "PQGEFG" len_of_word = input("Enter The Length Of Word : ") #4 word_threshold = input("Enter Word Threshold : ") #1...
# # PySNMP MIB module ALCATEL-IND1-MVRP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-MVRP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:03:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
""" 传输对象模式(Transfer Object Pattern)用于从客户端向服务器一次性传递带有多个属性的数据。传输对象也被称为数值对象。传输对象是一个具有 getter/setter 方法的简单的 POJO 类,它是可序列化的,所以它可以通过网络传输。它没有任何的行为。服务器端的业务类通常从数据库读取数据,然后填充 POJO,并把它发送到客户端或按值传递它。对于客户端,传输对象是只读的。客户端可以创建自己的传输对象,并把它传递给服务器,以便一次性更新数据库中的数值。以下是这种设计模式的实体。 业务对象(Business Object) - 为传输对象填充数据的业务服务。 传输对象(Transfer Object) - ...
def race_cond_check(stateArray): counter = 0 for state in reversed(stateArray): if len(state.programCounters) == 0: counter = counter + 1 else: break return counter
class people: # 定义基本属性 name = ''; age = 0; # 定义私有属性,外部无法直接访问 __weight = 0 # 定义构造方法 def __init__(self, name, age, weight): self.name = name; self.age = age; self.__weight = weight; def speak(self): print("%s 说: 我 %d 岁。" % (self.name, self.age)) # 单继承示例 ...
# # PySNMP MIB module H3C-STORM-CONSTRAIN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-STORM-CONSTRAIN-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:23:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
def create_list(start,len): nums = [] for i in range(len): nums.append(start+i) return nums start,len = input("Enter your start and len:\n").split() nums = create_list(int(start),int(len)) print (nums)
class BotError(Exception): pass class VoiceError(BotError): pass class NoVoice(VoiceError): pass class BadVoice(VoiceError): pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Вариант: (N + mod 22) + 1 = 7 # Задание: Определить среди всех двузначных чисел те, которые делятся на сумму # своих цифр. if __name__ == '__main__': for a in range(10, 99): # Выбор значения а из диапазона b = a // 10 # Первая цифра двузначного чис...
"""Tests For Flask-App Web Site""" def test_app_name(app_instance): """Test application name""" assert app_instance.name == "web_site_kripta.web_site_kripta"
''' Problem 6 The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 =...
#! python3 bloco_atrs = ('bloco_accesskey', 'bloco_id') ul_atrs = ('ul_id', 'ul_style') def get_atrs(informados, suportados): return ' '.join(f'{k.split("_")[-1]}="{v}"' for k, v in informados.items() if k in suportados) def tab_bloco(conteudo, *args, classe='success', inline=False, **novos_...
class Persona: def __init__(self, nombre): self.nombre = nombre def avanzar(self): print('Caminando') class Ciclista(Persona): def __init__(self, nombre): super().__init__(nombre) def avanzar(self): print('Pedaleando') def run(): persona = Persona('Oscar') ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"Learner.get_preds": "00_inference.ipynb", "Learner.predict": "00_inference.ipynb", "TabularLearner.predict": "00_inference.ipynb", "Interpret": "01_tabular.core.ipynb", "s...
class Solution(object): def __init__(self, nums): self.nums = nums def pick(self, target): return random.choice([k for k, v in enumerate(self.nums) if v == target])
# Python - 3.6.0 Test.assert_equals(encode('scout', 1939), [20, 12, 18, 30, 21]) Test.assert_equals(encode('masterpiece', 1939), [14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8])
dict( target = ["/data/nmt/works/step_-1_prepare_datas/binarized_text.en.shuf.h5"], source = ["/data/nmt/works/step_-1_prepare_datas/binarized_text.zh.shuf.h5"], indx_word = "/data/nmt/works/step_-1_prepare_datas/ivocab.zh.pkl", indx_word_target = "/data/nmt/works/step_-1_prepare_datas/ivocab.en.pkl", ...
# 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...
class SubInfo: """ This class contains info of the subtitle like the time and the text to display""" # E.G # 906 # 00:59:15,789 --> 00:59:18,789 # Mike's married? def __init__(self, index, time, text): self._index = index self._time = time self._text = text def GetI...
n = 500 with open("WIP/test.txt", "w") as f: out = "1" * n out += "\n" out *= n f.write(str(n) + " " + str(n) + "\n") f.write(out)
VERSION = "1.0" LOGGING_CONFIG = { 'version': 1, 'formatters': {'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', }}, 'handlers': {'console': { 'class': 'logging.StreamHandler', 'stream': 'ext://sys.stdout', 'formatter': 'default' }, 'f...
# A Note represents a fret-computed note in the final output class Note: def __init__(self, fnote, duration=None): self._duration = duration # the duration of the note, as a fraction of a measure self._fnote = fnote # the FrettedNote for this object, representing the guita...
""" Tic Tac Toe (and more generally, 2-D grid environments) that display in browser. Created by Peter Norvig NB: need to work on both Python 2 and 3 """ ############################################################################## # CSS and HTML ######################################################################...
class State: def __init__(self, lc, lm, rc, rm): self.lc = lc self.lm = lm self.rc = rc self.rm = rm def __repr__(self): return f"{self.lc},{self.lm}-{self.rc},{self.rm}" def is_done(self): return self.rc == 3 and self.rm == 3 def is_valid(self): ...
class Queue: arr = [] def enqueue(self,item): self.arr.append(item) def dequeue(self): if len(self.arr) > 0: ditem = self.arr[0] del self.arr[0] return ditem else: return #queue is empty def dispaly(self): print(s...
# Specify structure for custom cmake functions additional_commands = { "opencensus_lib": { "flags": [ "PUBLIC", ], "kwargs": { "HEADERS": "*", "DEPENDS": "*", "SOURCES": "*" } } } # If comment markup is enabled, don't reflow the first comment block in # eachlistfile. Use thi...
# Exceptions (Title) # Reading # ZeroDivisionError: # # This program divides a number by another number. def main(): # Get two numbers. num1 = int(input('Enter a number: ')) num2 = int(input('Enter another number: ')) # Divide num1 by num2 and display the result. result = num1 / num2 print(f'{num1}...
class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=37): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Olá {id(self)}' if __name__ == '__main__': maxwell = Pessoa(nome='Maxwell') lucimar = Pessoa(m...
lista = [1,2,3,4] soma = 0 soma = (lista[0]*10) +(lista[1]*10)+(lista[2]*30)+(lista[3]*50) media = soma/100 print(media)
# Check if it is prime or composite ?? # Composite is a number that greater than 1 and not prime def prime_or_composite(num): flag = 1 if num == 0 or num == 1: flag = 2 return flag for i in range(2, num): if num % i == 0: flag = 0 break return flag numbe...
# # Pascal # # Copyright 2017, Adam Edwards # # 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 ...
""" Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; } Test case format: For simplicity sake, each node's va...