content
stringlengths
7
1.05M
test_input_1 = """\ 8 8 WBWBWBWB BWBWBWBW WBWBWBWB BWBBBWBW WBWBWBWB BWBWBWBW WBWBWBWB BWBWBWBW """ test_input_2 = """\ 10 13 BBBBBBBBWBWBW BBBBBBBBBWBWB BBBBBBBBWBWBW BBBBBBBBBWBWB BBBBBBBBWBWBW BBBBBBBBBWBWB BBBBBBBBWBWBW BBBBBBBBBWBWB WWWWWWWWWWBWB WWWWWWWWWWBWB """ test_input_3 = """\ 8 8 BWBWBWBW WBWBWBWB BWBWBW...
"""Exercício Python 62: Melhore o DESAFIO 61; pergunte para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos.""" # dados do usuário primeiro = int(input('Primeiro termo: ')) razao = int(input('Razão da PA: ')) # variáveis termo = primeiro contador = 1...
# Write a small program to ask for a name and an age. # When both values have been entered, check if the person # is the right age to go on an 18-30 holiday (they must be # over 18 and under 31). # If they are, welcome them to the holiday, otherwise print # a (polite) message refusing them entry. name = input("Please e...
class Phone: def __init__(self, str): str = ''.join([x for x in str if x in '0123456789']) if len(str) == 10: self.number = str elif len(str) == 11 and str[0] == '1': self.number = str[1:] else: raise ValueError('bad format') self....
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...
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar: # Considerando: # USD 1.00 = R$ 5.40 real = float(input('\nQuanto dinheiro você tem na carteira? \nR$ ')) dolar = real / 5.40 print('Com R$ {:.2f} você pode comprar USD {:.2f}\n'.format(real, dolar))
studentdata = {} alldata = [] studentdata['Name'] = str(input("Type the Student's name: ")) studentdata['AVGRADE'] = float(input("Type the Average Grade of the Student: ")) if studentdata['AVGRADE'] < 5: studentdata['Situation'] = ("Reproved") elif studentdata['AVGRADE'] > 5 and studentdata['AVGRADE'] < 7: stud...
# -*- coding: utf-8 -*- f = open(filename) char = f.read(1) while char: process(char) char = f.read(1) f.close()
b = str(input()).split() d = int(b[0]) c= int(b[1]) e = '.|.' for i in range(1,d,2): print((e*i).center(c,'-')) print(('WELCOME').center(c,'-')) for i in range(d-2,-1,-2): print((e * i).center(c, '-'))
LANGUAGE_CODE = 'ru-RU' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
fila1="abcdefghi" fila2="jklmnopqr" fila3="stuvwxyz" n=int(input()) for i in range(0,n): flag=True palabras=input() palabras=palabras.strip().split() if (len(palabras[0])==len(palabras[1])): if (palabras[0]==palabras[1]): print("1") pass else: ...
# Which of the following expressions return the infinity values? # Suppose, the variables inf and nan have been defined. nan = float("nan") inf = float("inf") print(0.0 / inf) # nan print(inf / 2 - inf) # inf print(100 * inf + nan) # inf print(inf - 10 ** 300) # nan print(-inf * inf) ...
# Crie um programa que leia nome, sexo e idade de várias pessoas, # guardando os dados de cada pessoa em um dicionário e todos os # dicionários em uma lista. No final, mostre: # # A) Quantas pessoas foram cadastradas # B) A média de idade # C) Uma lista com as mulheres # D) Uma lista de pessoas com idade acima da média...
lines = open('input.txt', 'r').readlines() # create graph node_hash_list = dict() node_hash_list["start"] = set() for line in lines: p1, p2 = line.strip().split("-") if p2 not in node_hash_list: node_hash_list[p2] = set() if p1 not in node_hash_list: node_hash_list[p1] = set() if not...
KEY_TO_SYM = { "ArrowLeft": "Left", "ArrowRight": "Right", "ArrowUp": "Up", "ArrowDown": "Down", "BackSpace": "BackSpace", "Tab": "Tab", "Enter": "Return", # 'Shift': 'Shift_L', # 'Control': 'Control_L', # 'Alt': 'Alt_L', "CapsLock": "Caps_Lock", "Escape": "Escape", "...
#!/usr/bin/env python #coding: utf-8 # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a list of integers def postorderTraversal(self, root): i...
{ "cells": [ { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "append: 0.09872150200000007\n", "concat: 0.10876064500000027\n", "unpack: 0.14667600099999945\n" ] } ], "sourc...
""" CM, your case/content management system for the internet. Copyright Alex Li 2003. Package structure: cm/ html/ (UI subpackages...) htmllib/ (HTML frontend shared library) model/ (Business Domain subpackages) ... (framework modules...such as database access, security/permission checking, sessio...
def method1(): a = [1, 2, 3, 4, 5] for _ in range(1): f = a[0] for j in range(0, len(a) - 1): a[j] = a[j + 1] a[len(a) - 1] = f return a if __name__ == "__main__": """ from timeit import timeit print(timeit(lambda: method1(), number=10000)) 0.008410404003370...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: # init if head: p1 = head p2 = ...
STOP_WORDS = set( """ a acuerdo adelante ademas además afirmó agregó ahi ahora ahí al algo alguna algunas alguno algunos algún alli allí alrededor ambos ante anterior antes apenas aproximadamente aquel aquella aquellas aquello aquellos aqui aquél aquélla aquéllas aquéllos aquí arriba aseguró asi así atras aun aunqu...
def maak_fizzbuzz(n): """Zie ook: https://en.wikipedia.org/wiki/Fizz_buzz""" for getal in range(1, n+1): if getal % 3 == 0 and getal % 5 == 0: print("FizzBuzz") elif getal % 3 == 0: print("Fizz") elif getal % 5 == 0: print("Buzz") else: ...
# posts model # create an empty list posts=[] def posts_db(): return posts
while True: try: n, inSeq = int(input()), input().split() inSeq = ''.join(inSeq) stack = '' def outSeq(inSeq, stack): if len(inSeq) == 0: return [''.join(reversed(stack))] if len(stack) == 0: outLater = outSeq(inSeq[1:...
GET_USERS = "SELECT users FROM all_users WHERE user_id = '{}'" CREATE_MAIN_TABLE = "CREATE TABLE all_users(user_id text NOT NULL, users text NOT NULL);" ADD_USER = "UPDATE all_users SET users = '{}' WHERE user_id = '{}'" CREATE_USER = "INSERT INTO all_users (user_id, users) VALUES ('{}', ' ')" GET_ALL_IDS = "SELECT...
class Extractor: def __str__(self): return self.__class__.__name__ class ExtractByCommand(Extractor): def feed(self, command): if not hasattr(self, command['type']): return getattr(self, command['type'])(command)
REGISTERED_METHODS = [ "ACL", "BASELINE-CONTROL", "BIND", "CHECKIN", "CHECKOUT", "CONNECT", "COPY", "DELETE", "GET", "HEAD", "LABEL", "LINK", "LOCK", "MERGE", "MKACTIVITY", "MKCALENDAR", "MKREDIRECTREF", "MKWORKSPACE", "MOVE", "OPTIONS", ...
"""Linked list module.""" class Node: """Node of a linked list.""" def __init__(self, value, next = None): self.value = value self.next = next class LinkedList: """Linked List data structure.""" def __init__(self, head = None): self.head = head def __iter__(self): ...
pessoa = {} lista = [] toti = m = 0 while True: pessoa.clear() pessoa['nome'] = str(input('Nome: ')).strip().capitalize() while True: pessoa['sexo'] = str(input('Sexo: [M/F] ')).strip().lower()[0] if pessoa['sexo'] in 'mf': break print('ERRO! por favor, digite apenas M ou...
# coding=utf-8 """Self organizing list (transpose method) Python implementation.""" class Node: def __init__(self, key, val): self.key = key self.val = val self.next = None class SelfOrganizingList: def __init__(self): self.first = None def add_node(self, key, val): ...
def open_file(): '''Remember to put a docstring here''' while True: file_name = input("Input a file name: ") try: fp = open(file_name) break except FileNotFoundError: print("Unable to open file. Please try again.") continue return fp ...
class C(object): """Silly example!!!""" def __init__(self): """XXXX""" self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") # clas...
# # https://projecteuler.net/problem=4 # # Largest palindrome product # Problem 4 # # A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digits numers is 9009 = 91 x 99. # Find the largest palindrome made from the product of two 3-digit numbers. # Solution def rever...
class Player: """ Defines all character related attributes. Used by scripts.py. """ day = 0 timeofday = 6 stats = { 'name': 'Player', 'health': 100, 'speed': 1, 'intelligence': 1, 'rads': 0, } inventory = { ...
class ItemModel: def __init__(self): self.vowels = ['A', 'E', 'I', 'O', 'U'] self.rare_letters = ['X', 'J'] self.other_letters = ['B', 'C', 'D', 'F', 'G', 'H', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y', 'Z'] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Python for AHDA. Part 4, Example 1. Please rename: 'sample_thomas_moore_download.txt' to: 'Moore.txt' """ # Cut a subset of a file F_IN = 'Moore.txt' F_106 = 'Moore_106.txt' F_4170 = 'Moore_4170.txt' # by slicing a string with open(F_IN, 'r', encoding='utf-8',...
#-*-coding:utf-8-*- def bmi(w, h): bmi = (w/(h**2))*10000.0 if bmi<15.0 : str = "VSU" elif bmi<16.0: str = "SUN" elif bmi<18.5: str = "UND" elif bmi<25.0: str = "NOR" elif bmi<30.0: str = "OVE" elif bmi<35.0: str = "MOV" elif bmi<40.0: ...
""" Add riverwalls to the domain Gareth Davies, Geoscience Australia 2014+ """ def setup_riverwalls(domain, project): # ######################################################################### # # Add Riverwalls [ must happen after distribute(domain) in parallel ] # # #####################...
class Block: """Minecraft PI block description. Can be sent to Minecraft.setBlock/s""" def __init__(self, id, data=0): self.id = id self.data = data def __cmp__(self, rhs): return hash(self) - hash(rhs) def __eq__(self, rhs): return self.id == rhs.id and self.data == rh...
"""depsgen.bzl """ load("@build_stack_rules_proto//rules:providers.bzl", "ProtoDependencyInfo") def _depsgen_impl(ctx): config_json = ctx.outputs.json output_deps = ctx.outputs.deps config = struct( out = output_deps.path, name = ctx.label.name, deps = [dep[ProtoDependencyInfo] fo...
class P: def __init__( self, name, alias ): self.name = name # public self.__alias = alias # private def who(self): print('name : ', self.name) print('alias : ', self.__alias) class X: def __init__( self, x ): self.set_x( x ) def get_x( self ): return se...
cor_do_alien = 'vermelho' if cor_do_alien == 'verde': print('Você acabou de ganhar 5 pontos!') else: print('Você acabou de ganhar 10 pontos!')
class search: def __init__(): pass def ParseSearch(request): tab = {} if request.len > 0: pass pass def search(request): pass
a = int(input()) b = int(input()) c = int(input()) mul = str(a * b * c) for i in range(0, 10): count = 0 for j in mul: if i == int(j): count += 1 print(count)
#User function Template for python3 # https://gitlab.com/pranav/my-sprints/-/snippets/2215721 ''' Input: a = 5, b = 5, x = 11, # dest = (5, 5), x = 11 Output: 0 | - R - | (-1) * x1 + 1 * x2 = a (-1) * y1 + 1 * y2 = b x1 + x2 + y1 + y2 = x TC: O(1) SC: O(1) --- Exponential TC algo...
#!/usr/bin/python3 n = int(input()) _ = input() for i in range(n): a = int(input()) print(a*(i+1))
class NanometerPixelConverter: def __init__(self, pitch_nm: float): self._pitch_nm = pitch_nm def to_pixel(self, value_nm: float) -> int: return int(value_nm / self._pitch_nm) def to_nm(self, value_pixel: int) -> float: return value_pixel * self._pitch_nm
#!/usr/bin/env python # Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. ...
# 399-evaluate-division.py # # Copyright (C) 2019 Sang-Kil Park <likejazz@gmail.com> # All rights reserved. # # This software may be modified and distributed under the terms # of the BSD license. See the LICENSE file for details. class Solution: def calcEquation(self, equations: List[List[str]], values: List[float...
valor = float(input('Qual é o preço normal do produto? ')) print(''' Formas de pagamento disponíveis: [A] À vista no dinheiro ou cheque (10% de desconto) [B] À vista no cartão (5% de desconto) [C] Em até 2x no cartão (preço normal) [D] A partir de 3x vezes no cartão (20% de juros) ''') forma_pagamento = input('Qual é...
def a_kv(n): return n*n*(-1)**n def sumkv(n): return sum(map(a_kv, range(1, n+1))) def mysum(n): if (n % 2) == 0: k = n / 2 print(2*k*k+k) else: k = (n+1) / 2 print(-2*k*k+k) print(sumkv(1)) print(sumkv(2)) print(sumkv(3)) print(sumkv(4)) mysum(1) mysum(2) mysum(3) mys...
"Utilities for generating starlark source code" def _to_list_attr(list, indent_count = 0, indent_size = 4, quote_value = True): if not list: return "[]" tab = " " * indent_size indent = tab * indent_count result = "[" for v in list: val = "\"{}\"".format(v) if quote_value else v ...
""" File: largest_digit.py Name: Sharlene Chen ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 p...
""" Project: Author: """ def is_object_has_method(obj, method_name): assert isinstance(method_name, str) maybe_method = getattr(obj, method_name, None) return callable(maybe_method) __all__ = ['is_object_has_method']
def init(): global originlist, ellipselist, adjmatrix, adjcoordinates, valcount,num,dim,iterate, primA adjmatrix = [] # the adjmatrix is the list of edges that being created adjcoordinates = []; # the adjval gives the dimension coordinates (for plotting for the nth point) valcount = -1; # valcount keeps the nu...
def add_numbers(numbers): result = 0 for i in numbers: result += i #print("number =", i) return result result = add_numbers([1, 2, 30, 4, 5, 9]) print(result)
target_number = 0 increment = 0 while target_number == 0: sum1 = 0 increment += 1 for j in range(1, increment): sum1 += j factors = 0 for k in range(1, int(sum1**.5)+1): if sum1 % k == 0: factors += 1 factors = factors * 2 if factors > 500: target_number...
# Jun - Dangerous Hide-and-Seek : Neglected Rocky Mountain (931000001) if "exp1=1" not in sm.getQRValue(23007): sm.sendNext("Eep! You found me.") sm.sendSay("Eh, I wanted to go further into the wagon, but my head wouldn't fit.") sm.sendSay("Did you find Ulrika and Von yet? Von is really, really good at hidi...
# Create a program that asks the user to enter their name and their age. # Print out a message addressed to them that tells them the year that they will turn 100 years old. print("Insert your name") name = input() print("Insert yor age") age_str = input() age_int = int(age_str) print(f"{name}, you will be {age_int+100}...
#Conversor de Moedas 29/01/20 real = float(input('Quanto de dinheiro você tem na carteira? R$')) dolar = real / 4.23 #3.27 Dolar do dia do curso euro = real / 4.66 #euro do dia ienejap = real / 25.77 #moeda Japonesa peso = real / 187.37 #Peso Chileno print('Com R${:.2f} você pode comprar US${:.2f} \n Euro {:.2...
""" Dependencies that are needed for jinja rules """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("//tools:defs.bzl", "clean_dep") def jinja_deps(): maybe( http_archive, name = "markupsafe_archive", ...
def find_player(matrix): for r in range(len(matrix)): for c in range(len(matrix)): if matrix[r][c] == 'P': return r, c def check_valid_cell(size, r, c): return 0 <= r < size and 0 <= c < size string = input() size = int(input()) field = [list(input()) for _ in range(size)...
def weekDay(dayOfTheWeek): d = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday' } return d[dayOfTheWeek]
def Load_data(filename): with open(filename) as f: content = f.readlines() content = [x.strip() for x in content] Transaction = [] for i in range(0, len(content)): Transaction.append(content[i].split()) return Transaction #To convert initial transaction into frozenset def create_...
L=list(map(int,input().split())) L.insert(0,L.pop()) size=len(L) dp=[[[500000 for r in range(5)] for l in range(5)] for i in range(size)] dp[0][0][0]=0 def cal(a, b): if a==b: return 1 elif a==0: return 2 elif abs(a-b)==2: return 4 else: return 3 # ddr...
description = 'The just-bin-it histogrammer.' devices = dict( det_image1=device( 'nicos_ess.devices.datasources.just_bin_it.JustBinItImage', description='A just-bin-it image channel', hist_topic='ymir_visualisation', data_topic='FREIA_detector', brokers=['172.30.242.20:9092'...
class Coverage(object): def __init__(self): self.swaggerTypes = { 'Chrom': 'str', 'BucketSize': 'int', 'MeanCoverage': 'list<int>', 'EndPos': 'int', 'StartPos': 'int' } def __str__(self): return 'Chr' + self.Chrom + ": " + str...
DB_TABLES = [] class Table: insertString = "CREATE TABLE {tableName} (" def __init__(self, name, columns): self.name = name self.columns = columns def getQuerry(self): res = self.insertString.format(tableName=self.name) for columns in self.columns: ...
''' @jacksontenorio8 Faça um programa que leia cinco valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitando e as suas respectivas posições na lista. ''' lista_num = [] maior = 0 menor = 0 for i in range(0, 5): lista_num.append(int(input(f'Digite um número na posição ...
### create list_of_tuples: points = [ (1,2), (3,4), (5,6) ] ### retrieve the first element from the first tuple: print(points[0][0]) # 1 ### retrieve the last element from the first tuple: print(points[0][-1]) # 2 ### retrieve the first element from the last tuple: print(points[-1][0]) # 5 ### retrieve ...
def reverse(string): """ runtime complexity of this algorithm is O(n) """ # Starting index start_index = 0 # Ending index array = list(string) last_index = len(array) - 1 while last_index > start_index: # Swap items array[start_index], array[last_index] = \ a...
def to_string(val): if val is None: return '' else: return str(val)
x = int(input()) b = bool(input()) int_one_int_op_int_id = x + 0 int_one_int_op_bool_id = x + False int_one_bool_op_int_id = x | 0 int_one_bool_op_bool_id = x | False int_many_int_op_int_id = x + x + 0 int_many_int_op_bool_id = x + x + False int_many_bool_op_int_id = x | x | 0 int_many_bool_op_bool_id = x | x | False ...
attr = [[164, 5, 4, 3, 2, 1, 11, 10, 9, 8, 7, 6, 12, 14, 13, 15, 18, 16, 17, 19, 20, 22, 21, 25, 24, 23, 28, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76], [163, 77,...
#!/usr/bin/python3 def safeDivide(x,y): try: a = x/y except: a = 0 finally: return a print(safeDivide(10,0)) # Can also specify a particular exception.. def this_fails(): x = 1/0 try: this_fails() except ZeroDivisionError as errmsg: print('I am handling a run-time error:', errmsg)
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. class CuteBaseTimer: '''A base class for timers, allowing easy central stopping.''' __timers = [] # todo: change to weakref list def __init__(self, parent): self.__parent = parent CuteBaseTimer.__timers...
def sep_str(): inp = input(str("Enter word/words with '*' sign wherever you want: ")).rsplit("*", 1)[0] return inp print(sep_str())
# -*- coding: utf-8 -*- """ Created on Tue Jun 11 20:14:24 2019 @author: Administrator """ class Solution: def majorityElement(self, nums: list) -> list: # x=0 # y=0 # cx=0 # cy=0 # for num in nums: # if (cx==0 or num == x) and num != y: # cx += 1 # ...
num=int(input("Informe o valor: ")) sucessor= num +1 antecessor= num -1 print("O sucessor é: ", sucessor) print("O antecessor é: ", antecessor)
# global vars g_dataset_dir = "../dataset/" g_train_dir = g_dataset_dir + "/train/" g_test_dir = g_dataset_dir + "/test/" g_image_size = 400 g_grid_row = 8 g_grid_col = 8 g_grid_num = g_grid_row * g_grid_col g_grid_size = int(g_image_size / g_grid_row) g_down_sampled_size = 200 g_down_sampled_grid_size = int(g_grid...
""" This package contains the sphinx extensions used by Astropy. The `automodsumm` and `automodapi` modules contain extensions used by Astropy to generate API documentation - see the docstrings for details. The `numpydoc` module is dervied from the documentation tools numpy and scipy use to parse docstrings in the nu...
ONE_DAY_IN_SEC = 86400 SCHEMA_VERSION = "2018-10-08" NOT_APPLICABLE = "N/A" ASFF_TYPE = "Unusual Behaviors/Application/ForcepointCASB" BLANK = "blank" OTHER = "Other" SAAS_SECURITY_GATEWAY = "SaaS Security Gateway" RESOURCES_OTHER_FIELDS_LST = [ "Name", "suid", "suser", "duser", "act", "cat", ...
input_file = open("input.txt","r") input_lines = input_file.readlines() #print(*input_lines) rules = [] tickets = [] for line in input_lines: if line[0].isalpha() and 'or' in line: #print("Rule") firstLow = line.split(' ')[-3].split('-')[0] firstHigh = line.split(' ')[-3].split('-')[1] ...
# # PySNMP MIB module PANASAS-BLADESET-MIB-V1 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PANASAS-BLADESET-MIB-V1 # Produced by pysmi-0.3.4 at Mon Apr 29 20:27:54 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
#!/usr/bin/env python3 def step(n): if n%2==0: return n/2 else: return 3*n + 1 def to_one(n): count = 0 while n != 1: n = step(n) count += 1 return count def all_chains(highest): for i in range(1, highest): yield (i, to_one(i)) print(max( ...
#program to check whether every even index contains an even number # and every odd index contains odd number of a given list. def odd_even_position(nums): return all(nums[i]%2==i%2 for i in range(len(nums))) print(odd_even_position([2, 1, 4, 3, 6, 7, 6, 3])) print(odd_even_position([2, 1, 4, 3, 6, 7, 6, 4])) print(od...
love = 'I would love to be in ' places = [ 'zion', 'bryce', 'moab', 'arches', 'candyland', 'sedona'] for x in places: print(x)
# This Python file uses the following encoding: utf-8 """This file contains functions for the formatting of the the test results files.""" def line(char: str = "_", newline: bool = False) -> None: """Prints a character 70 times, with an optional preceding newline.""" if newline is True: print () i...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. load("//antlir/bzl:constants.bzl", "REPO_CFG") def check_flavor_exists(flavor): if flavor not in REPO_CFG.flavor_to_config: fai...
# ====================================================================== # Subterranean Sustainability # Advent of Code 2018 Day 12 -- Eric Wastl -- https://adventofcode.com # # Python implementation by Dr. Dean Earl Wright III # ====================================================================== # ==============...
""" 51 / 51 test cases passed. Runtime: 108 ms Memory Usage: 19.3 MB """ class Solution: def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]: graph = [[] for _ in range(n)] ans = [0] * n for x, y in paths: graph[x - 1].append(y - 1) graph[y - 1].append(...
#Python program to remove the n'th # index character from a nonempty string. inputStr = "akfjljfldksgnlfskgjlsjf" n = 5 def abc(inputStr, n): if n > len(inputStr): print("invalid 'n'.") return 0 return inputStr[0:n-1] + inputStr[n:] newStr = abc(inputStr,n) print(newStr)
class SetCommands(): def __init__(self, command): self.command = command def speed(self, x: int): """ description: set speed to x cm/s x: 10-100 response: ok, error """ return self.command(f'speed {x}') def rc_control(self, a, b, c, d): ...
## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved # see LICENSE.txt for license information def bucket_stats(l): """given a list of khashmir instances, finds min, max, and average number of nodes in tables""" max = avg = 0 min = None def count(buckets): c = 0 for bucket in ...
DEFAULT_MEROSS_HTTP_API = "https://iot.meross.com" DEFAULT_MQTT_HOST = "mqtt.meross.com" DEFAULT_MQTT_PORT = 443 DEFAULT_COMMAND_TIMEOUT = 10.0
# Desenvolva um programa em Python que receba a matricula, o nome, o teste, a prova dos alunos de uma turma, até que seja digitado 0 para a matricula do aluno. # O programa deverá calcular e exibir, para cada aluno, a matricula, o nome, a média e se o aluno está aprovado(media>=7), Final(media >=5 e <7) ou reprovado(...
t = int(input()) while t > 0: s = input() new = '' c=1 for i in range(len(s)): if i == 0: new+=s[i] elif i!=0 and s[i] != s[i-1]: new+=str(c) c=1 new+=s[i] elif s[i] == s[i-1] and new[-1] == s[i]: c+=1 print(new) ...
class RelinquishOptions(object,IDisposable): """ Options to control behavior of relinquishing ownership of elements and worksets. RelinquishOptions(relinquishEverything: bool) """ def Dispose(self): """ Dispose(self: RelinquishOptions) """ pass def ReleaseUnmanagedResources(self,*args): """ ...
# Vim has the best keybindings ever class Vim: @property def __best__(self): return True
#!/usr/bin/env python # -*- coding: utf-8 -*- def all_messages(): return \ { "0": "Nettacker-motor begon ...\n\n", "1": "python nettacker.py [opties]", "2": "Toon Nettacker Help Menu", "3": "Gelieve de licentie en afspraken te lezen https://github.com/virain...