content
stringlengths
7
1.05M
class ExecutionStep(object): def run(self, db): raise NotImplementedError('Method run(self, db) is not implemented.') def explain(self): raise NotImplementedError('Method explain(self) is not implemented.')
class A(object): def __init__(self): print("init") def __call__(self): print("call ") a = A() #imprime init A() #imprime call #https://pt.stackoverflow.com/q/109813/101
""" stub test, remove this when there's actual testing """ def test_nothing(): """ do nothing """
def check_for_subfolders(folder_id, service): new_sub_patterns = {} folders = service.files().list(q="mimeType='application/vnd.google-apps.folder' and parents in '"+folder_id+"' and trashed = false",fields="nextPageToken, files(id, name)",pageSize=400).execute() all_folders = folders.get('files', []) a...
''' Double Ended Queue or deque is the extended version of Queue because in deque you can add and remove form both first and last position of the Queue. ''' def Deque(): def __init__(self): self._deque = [] def add_first(self,e): 'Add the item in first position.' self._deque.insert(0,e...
class Error : def __init__(self,name,details,position): self.name = name self.details = details self.position = position def __str__(self): return f'Error : {self.name} -> {self.details} | line :{self.position.line} col : {self.position.col}' class IllegalCharError(Erro...
#!/usr/bin/env python # Copyright 2016 Zara Zaimeche # 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...
""" 75 - Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares. """ n = (int(input('Digite um número: ')), int(input('Digite outro número: ')), ...
"""Constants and membership tests for ASCII characters""" NUL = 0 SOH = 1 STX = 2 ETX = 3 EOT = 4 ENQ = 5 ACK = 6 BEL = 7 BS = 8 TAB = 9 HT = 9 LF = 10 NL = 10 VT = 11 FF = 12 CR = 13 SO = 14 SI = 15 DLE = 16 DC1 = 17 DC2 = 18 DC3 = 19 DC4 = 20 NAK = 21 SYN = 22 ETB = 23 CAN = 24 EM = 25 SUB = 26 ESC = 27 FS = 28 GS = ...
graph = { '5' : ['3','7'], '3' : ['2', '4'], '7' : ['8'], '2' : [], '4' : ['8'], '8' : [] } visited = set() def dfs(visited, graph, node): if node not in visited: print (node) visited.add(node) for neighbour in graph[node]: dfs(visited, graph, neighbour) # Drive...
""" Constants for the Shopcart Service """ NOT_FOUND = "Not Found"
#!/usr/bin/env python3 def part1(filename): with open(filename) as f: line = f.readline() floor = 0 for c in line: if c == '(': floor += 1 elif c == ')': floor -= 1 print(floor) def part2(filename): with open(filename) as f: line = f.read...
alist = ['bob', 'alice', 'tom', 'jerry'] # for i in range(len(alist)): # print(i, alist[i]) print(list(enumerate(alist))) for data in enumerate(alist): print(data) for i, name in enumerate(alist): print(i, name)
test = { 'name': 'q2', 'points': 6, 'suites': [ { 'cases': [ {'code': ">>> model.get_layer(index=0).output_shape[1] \n" '300', 'hidden': False, 'locked': False}, {'code': ">>> model.get_layer(inde...
def linear_search_with_sentinel(arr, key): i = 0 arr.append(key) while arr[i] != key: i += 1 if i == len(arr) - 1: return -1 return i
# -*- coding: utf-8 -*- """ Copyright (C) 2014-2016 bromix (plugin.video.youtube) Copyright (C) 2016-2018 plugin.video.youtube SPDX-License-Identifier: GPL-2.0-only See LICENSES/GPL-2.0-only for more information. """ class RegisterProviderPath(object): def __init__(self, re_path): self._...
# No.1/2019-06-10/68 ms/13.3 MB class Solution: def generateParenthesis(self, n: int) -> List[str]: l=['()'] if n==0: return [] for i in range(1,n): newl=[] for string in l: for index in range(len(string)//2+1): temp=string[:index]...
#function start def sumtriangle(n): if n == 1: return 1 else: return n+(sumtriangle(n-1)) #recursive function #function end n = int(input("Enter number :")) while (n!= -1): #loop start print(sumtriangle(n)) n = int(input("Enter number :")) print("Finished")
''' Создание архива ''' s, n = [int(e) for e in input().split()] a = [] for i in range(n): a.append(int(input())) a.sort() new = 0 for i in a: if (i <= s): s -= i new += 1 print(new)
# Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta. No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno individualmente. aluno = list() boletim = [] while True: nome = input('Nome: ') nota1 = float(i...
def generator(num): if num < 0: yield 'negativo' else: yield 'positivo'
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"color2num": "00_utils.ipynb", "colorize": "00_utils.ipynb", "calc_logstd_anneal": "00_utils.ipynb", "save_frames_as_gif": "00_utils.ipynb", "conv2d_output_size": "00_utils...
def sumofdigits(number): sum = 0 modulus = 0 while number!=0 : modulus = number%10 sum+=modulus number/=10 return sum print(sumofdigits(123))
class Solution: def generate(self, numRows: int) -> List[List[int]]: ans = [] for i in range(1, numRows+1): level = [1] * i if ans: for j in range(1, i-1): level[j] = ans[-1][j-1] + ans[-1][j] ...
def module_fuel(mass, full_mass=True): '''Calculate the amount of fuel for each part. With full mass also calculate the amount of fuel for the fuel. ''' fuel_mass = (mass // 3) - 2 total = 0 if fuel_mass <= 0: return total elif full_mass: total = fuel_mass + module_fuel(fuel_...
def describe_pet (animal_type,pet_name): """Exibe informações sobre um animal de estimação""" print("\nI have a "+ animal_type) print("My "+animal_type+"'s name is "+pet_name.title()) #argumentos devem ser fornecidos na posição de seus respectivos parametros describe_pet(animal_type='hamster', pet_name...
""" @Author : dilless @Time : 2018/6/23 0:59 @File : __init__.py.py """
def recursive_power(x, y): if y == 0: return 1 if y >= 1: return x * recursive_power(x, y - 1) print(recursive_power(2, 10)) print(recursive_power(10, 100))
primary_duties=[ 'agree', 'agrees', 'duty', 'you will', 'must', 'has to', 'is required', 'requires', 'warrant', 'warrants', 'you shall', 'obligated', 'is liable', 'is responsible for', 'responsibility', 'obligation', 'obligations', 'may not', '...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This subpackage contains modules and packages for identifying sources in an astronomical image and estimating their morphological parameters (e.g. centroid and shape parameters). """
def export_datatable(byc): if not "table" in byc["output"]: return if not "datatable_mappings" in byc: return if not byc["response_type"] in byc["datatable_mappings"]["io_params"]: return print('Content-Type: text/tsv') print('Content-Disposition: attachment; filename='+byc...
''' Consider a currency system in which there are notes of six denominations, namely, Rs. 1, Rs. 2, Rs. 5, Rs. 10, Rs. 50, Rs. 100. If the sum of Rs. N is input, write a program to computer smallest number of notes that will combine to give Rs. N. Input The first line contains an integer T, total number of test...
numero = int(input('Digite um número entre 0 e 9999: ')) u = numero % 10 d = numero // 10 % 10 c = numero // 100 % 10 m = numero // 1000 % 10 print('Unidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}'.format(u,d,c,m))
#Los ficheros sirven para guardar datos .csv o bien importar datos, para diferentes situaciones. #Para consulta o guardar datos. #a adicionar Añadir elemento a un fichero. #w Modo de escritura de ficheros #r modo de lectura de ficheros #Agregar informacion nueva en un fichero nombre = input('Nombre :') #+ adicionar fu...
# 给你一个二进制字符串 s(仅由 '0' 和 '1' 组成的字符串)。 # 返回所有字符都为 1 的子字符串的数目。 # 由于答案可能很大,请你将它对 10^9 + 7 取模后返回。 # 示例 1: # 输入:s = "0110111" # 输出:9 # 解释:共有 9 个子字符串仅由 '1' 组成 # "1" -> 5 次 # "11" -> 3 次 # "111" -> 1 次 # 示例 2: # 输入:s = "101" # 输出:2 # 解释:子字符串 "1" 在 s 中共出现 2 次 # 示例 3: # 输入:s = "111111" # 输出:21 # 解释:每个子字符串都仅由 '1' 组成 # 示例 4:...
#encoding:utf-8 urls = ( '/admin/?', 'controller.admin.index', '/admin/login', 'controller.admin.login', '/admin/logout', 'controller.admin.logout', #--------------user ----------- #----用户信息表---- "/admin/user_list", "controller.admin.user.user_list", "/admin/user_read/(\d+)", "controller...
# Databricks notebook source # MAGIC %run ./Student-Environment # COMMAND ---------- # MAGIC %run ./Utilities-Datasets # COMMAND ---------- def path_exists(path): try: return len(dbutils.fs.ls(path)) >= 0 except Exception: return False def install_datasets(reinstall=False): working_dir ...
class DungeonTile: def __init__(self, canvas_tile, is_obstacle): self.canvas_tile = canvas_tile self.is_obstacle = is_obstacle
#!/usr/bin/env python3 """Write a function which takes a float n as argument and returns the floor of the float""" def floor(n: float) -> int: """return int part of n Args: n (float): arg Returns: int: value int of np """ return int(n)
######## # Copyright (c) 2018 Cloudify Platform Ltd. 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 requi...
class loss(object): def __init__(self): self.last_input = None self.grads = {} self.grads_cuda = {} def loss(self, x, labels): raise NotImplementedError def grad(self, x, labels): raise NotImplementedError def loss_cuda(self, x, labels): raise NotImplem...
def example_function(arg1: int, arg2: int =1) -> bool: """ This is an example of a docstring that conforms to the Google style guide. The indentation uses four spaces (no tabs). Note that each section starts with a header such as `Arguments` or `Returns` and its contents is indented. Arguments: ...
''' Visualizing USA Medal Counts by Edition: Line Plot Your job in this exercise is to visualize the medal counts by 'Edition' for the USA. The DataFrame has been pre-loaded for you as medals. INSTRUCTIONS 100XP Create a DataFrame usa with data only for the USA. Group usa such that ['Edition', 'Medal'] is the index. ...
class ArrayList: DEFAULT_CAPACITY = 64 def __init__(self, physicalSize: int = 0): self.data = None self.logicalSize = 0 self.physicalSize = self.DEFAULT_CAPACITY if physicalSize > 1: self.physicalSize = physicalSize self.data = [0] * self.physicalSize d...
#!/usr/bin/env python3 class Style: """Shortcuts to terminal styling escape sequences""" BOLD = "\033[1m" END = "\033[0m" FG_Black = "\033[30m" FG_Red = "\033[31m" FG_Green = "\033[32m" FG_Yellow = "\033[33m" FG_Blue = "\033[34m" FG_Magenta = "\033[35m" FG_Cyan = "\033[36m" ...
# Function for nth Fibonacci number def Fibonacci(n): # First Fibonacci number is 0 if n == 0: return 0 # Second Fibonacci number is 1 elif n == 1: return 1 else: return Fibonacci(n - 1) + Fibonacci(n - 2) k = input("Enter a Number. Do not enter any string or symbol") tr...
# 字节数组 bytearray 可变的 print(bytearray()) print(bytearray(1)) # 整数 print(bytearray([1, 2, 3, 4])) # 可迭代 print(bytearray("hello,world", encoding='utf-8')) # 字符串 encod ba = bytearray([1, 2, 3, 4]) print("更改前:", ba) ba[0] = 2 print("更改后:", ba)
""" Conversion functions """ # Depth and length conversions def ft_to_m(inputvalue): """ Converts feet to metres. Parameters ---------- inputvalue : float Input value in feet. Returns ------- float Returns value in metres. """ return inputvalue * 0.3048 def m_...
""" https://leetcode.com/problems/insert-interval/ Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Outpu...
def checkpalindromic(num): i = 1 newNum = num while i <= 50: newNum = newNum + int(str(newNum)[::-1]) i = i + 1 if str(newNum) == str(newNum)[::-1]: return True return False ans = 0 for i in range(1,10000): if not checkpalindromic(i): ans += 1 pr...
with open('mar27') as f: content = f.readlines() for line in content: split = line.split(' ') if split[0] == 'Episode:': print("("+str(int(split[1])) + "," + split[3].split("\n")[0] + ")")
mystring="hello world" #Print Complete string print(mystring) print(mystring[::]) #indexing of string print(mystring[0]) print(mystring[4]) #slicing print(mystring[1:7]) print(mystring[0:10:2]) # Methods print(mystring.upper()) print(mystring.split()) #formatting print("hello world {},".format("Loki")) print("hello...
''' Fuente teorica y base: Scientia et Technica Año XIII, No x, Mes de 200x. Universidad Tecnológica de Pereira. ISSN 0122-1701 Referencia en código: https://repl.it/talk/learn/Python-Quine-McCluskey-Algorithm/14461 Funcionamiento del algoritmo 1. Busqueda de implicantes primos 2. Hacer tabla de...
# Copyright © 2020 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
## Advent of Code 2018: Day 8 ## https://adventofcode.com/2018/day/8 ## Jesse Williams ## Answers: [Part 1]: 36566, [Part 2]: 30548 class Node(object): def __init__(self, chs, mds): self.header = (chs, mds) # number of child nodes and metadata entries as specified in the node header self.childNode...
'A somewhat inefficient (because of string.index) cypher' plaintext = 'meet me at the usual place' fromLetters = 'abcdefghijklmnopqrstuv0123456789 ' toLetters = '6n4pde3fs 2c1ivjr05lq8utbgam7hk9o' for plaintext_char in plaintext: from_letters_index: int = fromLetters.index(plaintext_char) encrypted_letter...
def common_ground(s1,s2): words = s2.split() return ' '.join(sorted((a for a in set(s1.split()) if a in words), key=lambda b: words.index(b))) or 'death'
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
#contador = 0 #print("2 elevado a la" + str(contador) + " es igual a: " + str(2**contador)) contador = 1 print("2 elevado a la" + str(contador) + " es igual a: " + str(2**contador))
# Building a stack using python list class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): if self.is_empty() == True: return None else: ...
entrada = input() coste_avion, coste_coche, coste_habitacion, coste_comida, min_amigos, maximo_amigos = entrada.split() amigos = [] costes_personas = [] valor_pequeño = 0 numero_amigos = 0 for x in range(int(min_amigos), int(maximo_amigos)+1): numero_coches = 0 if x % 5 == 0: numero_coches = x//5 ...
# coding=utf-8 """Score problem dynamic programming solution Python implementation.""" def sp(n): dp = [0] * (n + 1) dp[0] = 1 for i in range(3, n + 1): dp[i] += dp[i - 3] for i in range(5, n + 1): dp[i] += dp[i - 5] for i in range(10, n + 1): dp[i] += dp[i - 10] return...
def maxArea(height) -> int: res=0 length=len(height) for x in range(length): if height[x]==0: continue prev_y=0 for y in range(length-1,x,-1): if (height[y]<=prev_y): continue ...
# --- Day 8: Seven Segment Search --- # Each digit of a seven-segment display is rendered by turning on or off any of seven segments named a through g: # So, to render a 1, only segments c and f would be turned on; the rest would be off. # To render a 7, only segments a, c, and f would be turned on. # # For each displa...
class Solution: def checkIfExist(self, arr: List[int]) -> bool: m = {} for n in arr: if n in m: m[n] += 1 else: m[n] = 1 for n in arr: if n * 2 in m and n is not 0: return True e...
class Parent: def __init__(self, last_name, eye_color): self.last_name = last_name self.eye_color = eye_color def show_info(self): print("Last name - "+self.last_name) print("Eye color - "+self.eye_color) class Child(Parent): def __init__(self, last_name, eye_color, number...
""" WxAPI Exceptions """ class WxAPIException(Exception): """Base class for exceptions in this module""" def __init__(self, message): self.message = message class InvalidFormat(WxAPIException): """The format provided is invalid""" class FormatNotAllowed(WxAPIException): """The format provided...
class Solution: def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ J = set(J) return sum(1 for stone in S if stone in J)
# # PySNMP MIB module HUAWEI-PWE3-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-PWE3-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:34:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
def median(nums): """ Find median of a list of numbers. >>> median([0]) 0 >>> median([4,1,3,2]) 2.5 Args: nums: List of nums Returns: Median. """ sorted_list = sorted(nums) med = None if len(sorted_list) % 2 == 0: mid_index_1 = len(sorted_list) ...
# Autogenerated config.py # # NOTE: config.py is intended for advanced users who are comfortable # with manually migrating the config file on qutebrowser upgrades. If # you prefer, you can also configure qutebrowser using the # :set/:bind/:config-* commands without having to write a config.py # file. # # Documentation:...
'''from flask import Flask from threading import Thread app = Flask('') @app.route('/') def main(): return print("Your bot is alive!") def run(): app.run(host="0.0.0.0", port=8080) 4692 def keep_alive(): server = Thread(target=run) server.start()''' '''from flask import Flask from threading import Th...
# # PySNMP MIB module CYCLADES-ACS-ADM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CYCLADES-ACS-ADM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:18:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
US_CENSUS = {'age': {'18-24': 0.1304, '25-44': 0.3505, '45-64': 0.3478, '65+': 0.1713}, # Age from 2010 US Census https://www.census.gov/prod/cen2010/briefs/c2010br-03.pdf 'education': {'Completed graduate school': 0.1204, ...
"""Convert units for human readable values""" conv_factor = { 'K': 1/1024, 'M': 1, 'G': 1024, 'T': 1024*1024 } def convert_to_base(string): """Convert the string to an integer number of base units. Example: 3G = 3*1024 """ stripped = string.strip() try: return int(stripped)...
# しゃくとり法 N = int(input()) A = list(map(int, input().split())) result = 0 r = 0 xs = A[0] cs = A[0] for l in range(N): while r < N - 1 and xs ^ A[r + 1] == cs + A[r + 1]: r += 1 xs ^= A[r] cs += A[r] result += r - l + 1 xs ^= A[l] cs -= A[l] print(result)
def get_range (string): return_set = set() for x in string.split(','): x = x.strip() if '-' not in x and x.isnumeric(): return_set.add(int(x)) elif x.count('-')==1: from_here, to_here = x.split('-')[0].strip(), x.split('-')[1].strip() ...
# Implementation of SequentialSearch in python # Python3 code to sequentially search key in arr[]. # If key is present then return its position, # otherwise return -1 # If return value -1 then print "Not Found!" # else print position at which element found def Sequential_Search(dlist, item): pos = 0 found = ...
user_name = "user" password = "pass" url= "ip address" project_scope_name = "username" domain_id = "defa"
CURRENCY_LIST_ACRONYM = [ ('AUD','Australia Dollar'), ('GBP','Great Britain Pound'), ('EUR','Euro'), ('JPY','Japan Yen'), ('CHF','Switzerland Franc'), ('USD','USA Dollar'), ('AFN','Afghanistan Afghani'), ('ALL','Albania Lek'), ('DZD','...
#!/usr/bin/python # -*- coding: utf-8 -*- if __name__=='__main__': print("Hello every body, I am Thomas.Li. I will be study hard for algorithms excercise")
class CIDR(object): def __init__(self, base, size=None): try: base, _size = base.split('/') except ValueError: pass else: if size is None: size = _size self.size = 2 ** (32 - int(size)) self._mask = ~(self.size - ...
''' URL: https://leetcode.com/problems/minimum-falling-path-sum Time complexity: O(nm) Space complexity: O(nm) ''' class Solution: def minFallingPathSum(self, A): """ :type A: List[List[int]] :rtype: int """ memo = [[None for i in range(len(A[0]))] for j in range(len(A))] ...
USERS = "users" COMMUNITIES = 'communities' TEAMS = 'teams' METRICS = 'metrics' ACTIONS = 'actions'
''' Created on 28-mei-2016 @author: vincent Static configuration, updated and generated by autoconf ''' VERSION = "0.1.0"
# -*- coding: utf-8 -*- # SiteProfileNotAvailable compatibility class SiteProfileNotAvailable(Exception): pass
# 817. Linked List Components # ttungl@gmail.com # We are given head, the head node of a linked list containing unique integer values. # We are also given the list G, a subset of the values in the linked list. # Return the number of connected components in G, where two values are connected if they appear consecutive...
class Queen: def __init__(self, row: int, column: int): if row not in range(0, 8) or column not in range(0, 8): raise ValueError("Must be between 0 and 7") self.i = row self.j = column def can_attack(self, another_queen: 'Queen') -> bool: if self.i == another_queen....
def append_suppliers_list(): suppliers = [] counter = 1 supply = "" while supply != "stop": supply = input(f'Enter first name and last name of suppliers {counter} \n') suppliers.append(supply) counter += 1 suppliers.pop() return suppliers append_supplier...
def test(a,b,c): a =1 b =2 c =3 return [1,2,3] a = test(1,2,3) print(a,test)
class BaseData: def __init__(self): self.root_dir = None self.gray = None self.div_Lint = None self.filenames = None self.L = None self.Lint = None self.mask = None self.M = None self.N = None def _load_mask(self): raise NotImpleme...
def decimal_to_binary(decimal_integer): return bin(decimal_integer).replace("0b", "") def solution(binary_integer): count = 0 max_count = 0 for element in binary_integer: if element == "1": count += 1 if max_count < count: max_count = count else:...
rows= int(input("Enter the number of rows: ")) cols= int(input("Enter the number of columns: ")) matrixA=[] print("Enter the entries rowwise for matrix A: ") for i in range(rows): a=[] for j in range(cols): a.append(int(input())) matrixA.append(a) matrixB=[] print("Enter the entries rowwise for m...
""" - 기본적으로 1개의 서브리스트가 나올때까지 분할을 진행 - 이후 배열값을 반복문을 통해 비교 -> 정렬 ->교환 후 합치기 ref : https://www.geeksforgeeks.org/merge-sort/ """ def merge_sort(arr): if len(arr) >1 : mid = len(arr) // 2 # 배열의 중간 찾기 left = arr[:mid] # 나눠진 왼쪽부분 right = arr[mid:] # 나눠진 오른쪽 부분 # 재귀 분할정복...
class Solution(object): def rob(self, nums): def helper(nums, i): le = len(nums) if i == le - 1: return nums[le-1] if i == le - 2: return max(nums[le-1], nums[le-2]) if i == le - 3: return max(nums[le-3] + nums[...
k = int(input()) for z in range(k): l = int(input()) n = list(map(int,input().split())) c = 0 for i in range(l-1): for j in range(i+1,l): if n[i]>n[j]: c += 1 if c%2==0: print('YES') else: print('NO')
test = { 'name': 'q3_1_1', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> len(my_20_features) 20 """, 'hidden': False, 'locked': False }, { 'code': r""" >>> np.all([f in test_movies.labels f...
line = input().split() H = int(line[0]) W = int(line[1]) array = [] def get_ij(index): i = index // W if (i % 2 == 0): j = index % W else: j = W - index % W - 1 return i+1, j+1 for i in range(H): if i % 2 == 0: array.extend([int(a) for a in input().split()]) else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ VERSION Control de versiones. Autor: PABLO PIZARRO @ github.com/ppizarror Fecha: SEPTIEMBRE 2016 Licencia: MiT licence """ __version__ = '1.0.0'
# -*- coding: utf-8 -*- """ Created on Sun May 20 21:01:53 2018 @author: DrLC """ class VarDecl(object): def __init__(self, line=""): line = line.strip().strip(';,').strip().split() self.__type = line[0] assert self.__type in ["int", "float"], "Invalid type \""+self.__type+"\...