content stringlengths 7 1.05M |
|---|
"""
Decorators provide a way to intercept a decorated function, method, or class.
Ultimately, the decorator accepts the function as its only argument
Decorators can then either return the original function, or another one
"""
# pattern 1: Decorator that returns the original function
def change_default(func):
"""Th... |
ADMINS = ()
MANAGERS = ADMINS
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framewo... |
# Projeto estruturado para aperfeiçoamento de lógica da programação
#cria linhas para separar o códico na hora da compilação e ficar mais facíl entendimento
def lin():
print('_' * 30)
# semana 2 etapa 1 se apresentando e pedindo alguns dados do cliente
def obter_limite():
print ('Olá, seja bem-vindo a loja ... |
# Motor Controller class initialization constants
ZERO_POWER = 309 # Value to set thrusters to 0 power
NEG_MAX_POWER = 226 # Value to set thrusters to max negative power
POS_MAX_POWER = 391 # Value to set thrusters to max positive power
FREQUENCY = 49.5 # Frequency at which the i2c to pwm will be updated
POWER_THRE... |
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
for i in range(len(arr)):
for j in range(len(arr)):
if i != j and arr[i] == 2*arr[j]:
return True
return False
|
"""
Name : Even odd
Author : [Mayank Goyal) [https://github.com/mayankgoyal-13]
"""
num = int(input("Enter your number: "))
if num % 2 == 0:
print('The given number is even')
else:
print('The given number is odd')
|
valorCasa = float(input("Valor da casa: "))
salario = float(input("Seu salário: "))
tempoPgtoAno = int(input("Pagará em quantos anos: "))
tempoPgtoMes = tempoPgtoAno * 12
valorMaxPar = salario * .3
valorPar = valorCasa / tempoPgtoMes
if valorPar > valorMaxPar:
print("\033[31mEmpréstimo negado.\033[m")
els... |
def pattern(N):
if(N==2):
for i in range(N):
print(("#"*1+" ")*N)
if(N==3):
for i in range(N-1):
print(("#"*2+" ")*N)
if(N==4):
for i in range(N-2):
print(("#"*3+" ")*N)
pattern(2)
pattern(3)
pattern(4) |
my_list = ['один', 'два', 'три', 'четыре', 'пять']
list_2 = ['шесть', 'семь']
my_list.extend(list_2)
print(my_list)
|
def addDataSource(doc, name, url):
"""
Add a DataSource to the given InterMine items XML
Returns the item.
"""
dataSourceItem = doc.createItem('DataSource')
dataSourceItem.addAttribute('name', name)
dataSourceItem.addAttribute('url', url)
doc.addItem(dataSourceItem)
return dataSou... |
# import numpy as np
# a = np.array([17,22,4,2,14,24,0,5,8,7,27,28,15,25,12,9,20,3,29,16,10,6,1,13,18,23,11,26,21,19])
# np.random.shuffle(a)
# print(a.tolist())
# np.random.shuffle(a)
# print(a.tolist())
# np.random.shuffle(a)
# print(a.tolist())
need_rerun = [
{'bodies': [300, 301, 302, 303, 304, 305, 306, 307,... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1107/B
# 类似筛子?
# https://codeforces.com/blog/entry/64847
# 性质: n%9=x
def f(l):
k,x = l
return 9*(k-1)+x
t = int(input())
for _ in range(t):
l = list(map(int,input().split()))
print(f(l))
|
# Copyright (c) 2021 Jeff Irion and contributors
#
# This file is part of the adb-shell package.
"""ADB shell functionality.
"""
__version__ = '0.4.1'
|
class _Food:
color = (107, 0, 0)
def __init__(self, pos_x, pos_y, live = 100):
self.pos_x = pos_x
self.pos_y = pos_y
self.live = live
def get_pos_x(self):
return self.pos_x
def get_pos_y(self):
return self.pos_y
def live_decrement(self):
self.live -=1 |
""" Code to solve Lychrel number
So this is a very popular math question
The idea is to take any number as num and reverse it.
Now add the reversed number to num and repeat the process unless
a palindrome is obtained. The weird thing about this process is that
for nearly every number ends with ... |
# -*- coding: utf-8 -*-
"""Test for autolag of adfuller, unitroot_adf
Created on Wed May 30 21:39:46 2012
Author: Josef Perktold
"""
# The only test from this file has been moved to test_unit_root (2018-05-04)
|
while True:
print('Enter you age: ')
age = input()
if age.isdecimal():
break
print('Please enter a number for age')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers') |
# -*- coding: utf-8 -*-
class ApiException(Exception):
errors = []
def __init__(self, errors, code):
self.errors = errors
self.code = code
|
#
# PySNMP MIB module HP-ICF-DHCPv6-SNOOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-DHCPv6-SNOOP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:21:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
#
# PySNMP MIB module ESI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ESI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:52:21 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, 09:23:15)... |
# Copyright 2018 The go-python Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
doc="range"
a = range(255)
b = [e for e in a]
assert len(a) == len(b)
a = range(5, 100, 5)
b = [e for e in a]
assert len(a) == len(b)
a = range(100 ,0, 1)
... |
def selectionsort(arr):
i=0
while(i<len(arr)):
#find index of minimum number between index i and index n-1 where n=len(arr)
num,ind=arr[i],i
for j in range(i+1,len(arr)):
if(arr[j]<num):
num=arr[j]
ind=j
#swap number at ind with number at i
temp=arr[i]
arr[i]=arr[ind]
arr[ind]=temp
i+=1
re... |
__title__ = 'road-surface-detection'
__version__ = '0.0.0'
__author__ = 'Esri Advanced Analytics Team'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2020 by Esri Advanced Analytics Team'
# add specific imports below if you want more control over what is visible
## from . import utils
|
ImgHeight = 32
data_roots = {
'iam_word': '/mydrive/MyDrive/khoa_luan/khoa_luan/data/'
}
data_paths = {
'iam_word': {'trnval': 'trnvalset_words%d.hdf5'%ImgHeight,
'test': 'testset_words%d.hdf5'%ImgHeight},
'iam_word_org': {'trnval': 'trnvalset_words%d_OrgSz.hdf5'%ImgHeight,
... |
# vim: set fileencoding=<utf-8> :
# Copyright 2018-2020 John Lees and Nick Croucher
'''PopPUNK (POPulation Partitioning Using Nucleotide Kmers)'''
__version__ = '2.2.1'
|
n=int(input())
a=list(map(int,input().split()))
a.sort()
l=list(set(a))
k=l[0]
i=0
c=0
while(i!=n and k<=max(l)):
if(k==l[i]):
k=k+1
i=i+1
c=c+1
else:
break
print(c)
|
#Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the #node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, #you should return NULL.
# Definition for a binary tree node.
# class TreeNode:
# def __init__... |
# Purpose: Grouping entities by DXF attributes or a key function.
# Created: 03.02.2017
# Copyright (C) 2017, Manfred Moitzi
# License: MIT License
def groupby(entities, dxfattrib='', key=None):
"""
Groups a sequence of DXF entities by an DXF attribute like 'layer', returns the result as dict. Just specify
... |
def find_pivot_index(nums):
"""
Suppose a sorted array A is rotated at some pivot unknown to you
beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element. NOTE: The array will not contain duplicates.
"""
min_num = nums[0]
pivot_index = 0
left = 0
right =... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 14 19:55:42 2017
@author: Zachary
"""
aList = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
def flatten(aList):
flattenedList = []
for i in range(len(aList)):
listOne = aList[i]
if type(listOne) == list:
for k in range... |
class ContainerAlreadyResolved(Exception):
def __init__(self):
super().__init__("Container already resolved can't be resolved again")
class ForbiddenChangeOnResolvedContainer(Exception):
def __init__(self):
super().__init__("Container can't be modified once resolved")
class ServiceAlreadyDef... |
'''
We are given a list schedule of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order... |
# from cf.util import read_train_data
# 1. 获取用户和用户之间的相似度
# 1.1 正常逻辑的用户相似度计算 jaccard distance=交集/并集
def user_normal_simmilarity(train_data):
# 相似度字典
w = dict()
# n^2*l^2 l < m
for u in train_data.keys():
if w.get(u, -1) == -1:
w[u] = dict()
for v... |
# -*- coding: utf-8 -*-
#
# LICENCE MIT
#
# DESCRIPTION Callgraph helpers for ast nodes.
#
# AUTHOR Michal Bukovsky <michal.bukovsky@trilogic.cz>
#
class VariablesScope(object):
def __init__(self, ctx):
self.ctx, self.var_names = ctx, ctx.var_names.copy()
def __enter__(self):
re... |
peso = float(input('Digite seu peso: [KG]'))
alt = float(input('Digite a altura: [m]'))
imc = peso / (alt**2)
print("IMC: {:.2f}".format(imc))
if imc < 18.5:
print("Abaixo do Peso!")
elif imc >= 18.5 and imc <= 25:
print("Você está no PESO IDEAL!")
elif 25.1 >= imc and imc <= 30:
print("Você está com SOBR... |
dna_to_rna_map = {
"G" : "C",
"C" : "G",
"T" : "A",
"A" : "U"
}
def to_rna(dna_strand):
return "".join([dna_to_rna_map[nuc] for nuc in dna_strand]) |
# Design a hit counter which counts the number of hits received in the past 5 minutes.
#
# Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earli... |
# Program untuk menampilkan belah ketupat
print('\n==========Belah Ketupat==========\n')
obj_1 = 1
for row_1 in range(6, 0, -1):
for col_1 in range(row_1):
print(' ', end='')
for print_obj_1 in range(obj_1):
print('#', end='')
obj_1+=2
if row_1 == 1:
obj_2 = 9
print('')... |
blocks = {
'CJK Unified Ideographs Extension A': (0x3400, 0x4DBF),
'CJK Unified Ideographs': (0x4E00, 0x9FFF),
'CJK Unified Ideographs Extension B': (0x20000, 0x2A6DF),
'CJK Unified Ideographs Extension C': (0x2A700, 0x2B73F),
'CJK Unified Ideographs Extension D': (0x2B740, 0x2B81F),
'CJK Unified Ideographs Exten... |
#app = faust.App('myapp', broker='kafka://localhost')
class QUANTAXIS_PUBSUBER():
def __init__(self, name, broker='rabbitmq://localhost'):
self.exchange = name
#@app.agent(value_type=Order)
def agent(value_type=order):
pass |
class Util:
def __init__(self):
pass
@staticmethod
def compress_uri(uri, base_uri, prefix_map):
uri = uri.strip('<>')
if uri.startswith(base_uri):
return '<' + uri[len(base_uri):] + '>'
for prefix, prefix_uri in prefix_map.items():
if uri.startswith(p... |
class Image(object):
"""Image.
:param src:
:type src: str
:param alt:
:type alt: str
"""
def __init__(self, data=None):
if data is None:
data = {}
self.src = data.get('src', None)
self.alt = data.get('alt', None)
|
class ContactHelper:
def __init__(self, app):
self.app = app
def open_add_contact_page(self):
# open add creation new contact
wd = self.app.wd
wd.find_element_by_link_text("add new").click()
def fill_form(self, contact):
# fill contacts form
wd = self.app.w... |
MODEL_CONFIG = {
'unet':{
'simplenet':{
'in_channels':1,
'encoder_name':'simplenet',
'encoder_depth':5,
'encoder_channels':[32,64,128,256,512], #[1,2,4,8,16]
'encoder_weights':None,
'decoder_use_batchnorm':True,
'decoder_at... |
# Python - 3.6.0
stock = {
'football': 4,
'boardgame': 10,
'leggos': 1,
'doll': 5
}
test.assert_equals(fillable(stock, 'football', 3), True)
test.assert_equals(fillable(stock, 'leggos', 2), False)
test.assert_equals(fillable(stock, 'action figure', 1), False)
|
# How to Find the Smallest value
largest_so_far = -1
print('Before', largest_so_far)
for the_num in [1, 99, 24, 25, 56, 4, 57, 89, 5, 94, 21] :
if the_num > largest_so_far :
largest_so_far = the_num
print(largest_so_far, the_num)
print('After', largest_so_far)
|
"""Common utilities for dealing with paths."""
def filter_files(filetypes, files):
"""Filters a list of files based on a list of strings."""
filtered_files = []
for file_to_filter in files:
for filetype in filetypes:
filename = file_to_filter if type(file_to_filter) == "string" else file_to_filter.base... |
integers = [ 1, 6, 4, 3, 15, -2]
print("integers[0] = ", integers[0])
print("integers[1] = ", integers[1])
print("integers[2] = ", integers[2])
print("integers[3] = ", integers[3])
print("integers[4] = ", integers[4])
print("integers[5] = ", integers[5])
|
#!/usr/bin/env python3
"""Find the element that appears once in sorted array.
Given a sorted array A, size N, of integers; every element appears twice except for one. Find that element
in linear time complexity and without using extra memory.
Source:
https://practice.geeksforgeeks.org/problems/find-the-element-that... |
# # ###
# #
# letter = input ("Please enter a letter:\n")
# if (letter == 'i'):
# print ("am lettera vowela")
# elif (letter== 'a'):
# print("am lettera vowela")
# if (letter == 'u'):
# print ("am lettera vowela")
# elif (letter== 'e'):
# print("am lettera vowela")
# if (letter == 'o'):
# print('am ... |
n = input()
l = list(map(int,raw_input().split()))
m = 0
mi = n-1
for i in range(n):
if l[i]> l[m]:
m=i
if l[i]<=l[mi]:
mi = i
if mi>m:
print (n+m-mi-1)
else:
print (n+m-mi-2)
|
class Solution(object):
def processQueries(self, queries, m):
"""
:type queries: List[int]
:type m: int
:rtype: List[int]
"""
ans=[]
P=range(1, m+1)
for i in range(len(queries)):
toPop=P.index(queries[i])
ans.append(toP... |
districts = {
'C01':("Downtown", "Harbourfront", "King West Village", "Little Italy"),
'C02':("The Annex", "Yorkville", "Summerhill", "Wychwood Park", "Deer Park (Yonge-St. Clair)", "South Hill"),
'C03':("Corso Italia", "Forest Hill South", "Oakwood-Vaughan", "Cedarvale"),
'C04':("Bedford Park", "Lawrence Manor", "Nort... |
'''Bet.py
'''
class Bets:
def __init__(self):
self.win = 0
self.info = {"dealer":self.dealer, "player":self.player}
def dealer(self, dealer):
self.dealer = dealer
def player(self, player):
self.player = player
def win(self):
self.win = self.od... |
"""Exercício Python 094: 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... |
#!/usr/bin/python
with open('INCAR', 'r') as file:
lines=file.readlines()
for n,i in enumerate(lines):
if 'MAGMOM' in i:
# print(i)
items=i.split()
index=items.index('=')
moments=items[index+1:]
# print(moments)
magmom=''
size=4
for i in ra... |
#
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
class text:
def __init__(self,text,*,thin=False,cancel=False,underline=False,bold=False,Italic=False,hide=False,Bg="black",Txt="white"):
self.__color={
"black":30,
"red":31,
"green":32,
"yellow":33,
"blue":34,
"mazenta":35,
... |
# 23. Merge k Sorted Lists
# Runtime: 148 ms, faster than 33.74% of Python3 online submissions for Merge k Sorted Lists.
# Memory Usage: 17.8 MB, less than 82.01% of Python3 online submissions for Merge k Sorted Lists.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None)... |
configuration = None
def init():
global configuration
configuration = None
|
class FileSourceDepleted(Exception):
"""Exception raised when attempting to read from a depleted source file
Attributes:
filepath(str): path to depleted file
message(str): error message
"""
def __init__(self, filepath: str, message: str = "File source is depleted"):
"""Construc... |
class ArpProperties(object):
def __init__(self, bpm, base_note, pitch_value):
self.bpm = bpm
self.base_note = base_note
self.pitch = pitch_value
|
# Python añadirá internamente el nombre de la clase delante de __baz
class Foo(object):
def __init__(self):
self.__baz = 42
def foo(self):
print(self.__baz)
# Como el método __init__ empieza por __, en realidad será Bar__init__, y el del padre Foo__init__. Así existen por separado
class Bar(Fo... |
# Day26 of 100 Days Of Code in Python
# get common numbers from two files using list comprehension
with open("file1.txt") as file1:
file1_data = file1.readlines()
with open("file2.txt") as file2:
file2_data = file2.readlines()
result = [int(item) for item in file1_data if item in file2_data]
print(result) |
pricelist = []
price = ""
while price != "kolar":
print(""" \n\nThe following things are
what you can do whith this program.
0 = Exit
1 = Show pricelist
2 = Add price
3 = Delete pricelist
4 = Sort pricelist """)
choice = input(" \n Choice : ")
if choice == "0":
pr... |
#!/usr/bin/python3
# Problem : https://code.google.com/codejam/contest/351101/dashboard#s=p0
__author__ = 'Varun Barad'
def main():
no_of_test_cases = int(input())
for i in range(no_of_test_cases):
credit = int(input())
no_of_items = int(input())
items = input().split(' ')
for... |
# The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
##
#73167176531330624919225119674426574742355349194934
#96983520312774506326239578318016984801869478851843
#85861560789112949495459501737958331952853208805511
#12540698747158523863050715693290963295227443043557
... |
usuarios={
"iperurena": {
"nombre": "Iñaki",
"apellido": "Perurena",
"password": "123123"
},
"fmuguruza": {
"nombre": "Fermín",
"apellido": "Muguruza",
"password": "654321"
},
"aolaizola": {
... |
def dibujo (base,altura):
dibujo=print("x"*base)
for fila in range (altura):
print("x"+" "*(base-2)+"x")
dibujo=print("x"*base)
dibujo(7,5)
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
G = [0]*(n+1)
G[0], G[1] = 1, 1
for i in range(2, n+1):
for j in range(1, i+1):
G[i] += G[j-1] * G[i-j]
return G[n]
class MathSolution(object):
... |
#
# PySNMP MIB module PACKETFRONT-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PACKETFRONT-SMI
# Produced by pysmi-0.3.4 at Wed May 1 14:36:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
casa = float(input('Valor da casa: '))
sal = float(input('Salário do comprador: R$'))
anos = int(input('prazo em anos de financiamento: '))
prest = casa / (anos * 12)
smin = sal * 0.3
print('para pagar uma casa de R${:.2f} em {} anos '.format(casa, anos), end='')
print('a prestação será de R${:.2f}'.format(prest))
if ... |
#!/bin/python3
def generate_prime_numbers(lim):
"""
Generates prime numbers above 100 10**100
"""
start = 10**100
l = []
for num in range(start, lim):
for n in range(2, num):
if num % n == 0:
print("Not found")
break
else: # If the mo... |
#coding:utf-8
'''
使用ProxyHandler在程序中动态设置代理
import urllib2
proxy = urllib2.ProxyHandler({'http': '127.0.0.1:8087'})
opener = urllib2.build_opener([proxy,])
urllib2.install_opener(opener)
response = urllib2.urlopen('http://www.zhihu.com/')
print response.read()
'''
'''
直接调用 opener 的 open方法代替全局的 urlopen方法
import urllib... |
"""7 valores numéricos
lista de par
lista de impar"""
números = [[], []]
print('=-' * 30)
for c in range(1, 8):
num = int(input('Digite o {}o. valor. '.format(c)))
if num % 2 == 0:
números[1].append(num)
else:
números[0].append(num)
for c in range(0, 2):
números[c].sort()
print('=-' * 30... |
"""
Board class that the game takes place in/against/on
"""
class Board(object):
"""The game Board"""
def __init__(self):
brown = ('Mediterranean Avenue', 'Baltic Avenue')
lightBlue = ('Oriential Avenue', 'Vermont Avenue', 'Connecticut Avenue')
pink = ('St. Charles PLace', 'States Avenue... |
# Python3.5
# 定义一个栈类
class Stack():
# 栈的初始化
def __init__(self):
self.items = []
# 判断栈是否为空,为空返回True
def isEmpty(self):
return self.items ==[]
# 向栈内压入一个元素
def push(self, item):
self.items.append(item)
# 从栈内推出最后一个元素
def pop(self):
return self.items.pop()
... |
"""Rules for ANTLR 3."""
def imports(folder):
""" Returns the grammar and token files found below the given lib directory. """
return (native.glob(["{0}/*.g".format(folder)]) +
native.glob(["{0}/*.g3".format(folder)]) +
native.glob(["{0}/*.tokens".format(folder)]))
def _get_lib_dir(imports):
... |
#
# @lc app=leetcode id=989 lang=python3
#
# [989] Add to Array-Form of Integer
#
# https://leetcode.com/problems/add-to-array-form-of-integer/description/
#
# algorithms
# Easy (44.85%)
# Total Accepted: 12.6K
# Total Submissions: 28.1K
# Testcase Example: '[1,2,0,0]\n34'
#
# For a non-negative intege... |
class Error(Exception):
"""
Base class for other exceptions
"""
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
return self.message if self.message else " "
class DatabaseError(Error):
de... |
# Python Program to find Perfect Number using For loop
Number = int(input(" Please Enter any Number: "))
Sum = 0
for i in range(1, Number):
if(Number % i == 0):
Sum = Sum + i
if (Sum == Number):
print(" %d is a Perfect Number" %Number)
else:
print(" %d is not a Perfect Number" %Number)
|
## Copyright (c) 2022, Team FirmWire
## SPDX-License-Identifier: BSD-3-Clause
TASKNAMES_LTE = [
"ERT",
"EMACDL",
"EL2H",
"EL2",
"ERRC",
"EMM",
"EVAL",
"ETC",
"LPP",
"IMC",
"SDM",
"VDM",
"IWLAN",
"WO",
"EL1",
"EL1_MPC",
"MLL1",
"SIMMNGR",
"L1ADT... |
def helper(N):
if (N <= 2):
print ("NO")
return
value = (N * (N + 1)) // 2
if(value%2==1):
print ("NO")
return
s1 = []
s2 = []
if (N%2==0):
shift = True
start = 1
last = N
while (start < last):
if (shift):
... |
ls=[12,3,9,4,1]
a=len(ls)
l=[]
for i in reversed(range(a)):
l.append(ls[i])
print(l)
|
html = """\
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>$title</title>
<style media="screen">
html {
background-color: #dfdfdf;
color: #333;
}
body {
max-width: 750px;
margin: ... |
def test_alert_message(alert_message):
"""Use this for check message in different cases:Incorrectly username/password, only username, only password by
parameters """
print(alert_message)
assert 'No match for Username and/or Password.' in alert_message
|
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
n = len(height)
d = [0] * n
for i in range(n):
d[i] = height[i]
for i in range(1, n):
avg = d[i-1] / (i * 1.0)
... |
'''Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares.
No final, mostre os valores pares e ímpares em ordem crescente.'''
num = [[], []]
c=0
while True:
n = int(input('Digite um número: '))
if n % 2 == 0:
... |
"""
Function to retrieve location of a key in nested data structure
"""
def locate_element(data, look_up_elem):
'''
Function to locate the exact location of a an element in a data structure
'''
data_orig = data
loc_list = []
#### Step 1: Create loop: while look_up_elem not in loc_list
whil... |
#default
def printx(name,age):
print(name)
print(age)
return;
printx(name='miki',age=96)
#keyword
def printm(str):
print(str)
return;
printm(str='sandy')
#required
def printme(str):
print(str)
return;
printme()
|
# Add Bold Tag in String
# Given a string s and a list of strings words, you need to add a closed pair of bold tag
# <b> and </b> to wrap the substrings in s that exist in dict.
# If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag.
# Also, if two substrings wrapped by bol... |
class Car:
def __init__(self,marka,model,god,speed=0):
self.marka=marka
self.model=model
self.god=god
self.speed=speed
def speed_up(self):
self.speed+=5
def speed_down(self):
self.speed-=5
def speed_stop(self):
self.speed=0
def print_speed(... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n , k ) :
count = 0
for i in range ( 0 , n ) :
if ( arr [ i ] <= k ) :
count = co... |
def is_leap(year):
leap = False
if year%400==0:
return True
if year%4==0 and year%100!=0:
return True
return leap
year = int(input())
print(is_leap(year)) |
"""
'The module for first_inside_quotes'
Arthur Wayne asw263
September 22 2020
"""
def first_inside_quotes(s):
"""
Returns the first substring of s between two (double) quotes
A quote character is one that is inside a string, not one that
delimits it. We typically use... |
"""
A linked list is given such that each node contains an additional random pointer
which could point to any node in the list or null.
Return a deep copy of the list.
"""
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# ... |
with open("inp1.txt") as file:
data = file.read()
depths = [int(line) for line in data.splitlines()]
depth_inc_cnt = 0
for i in range(1, len(depths)):
if depths[i] > depths[i - 1]:
depth_inc_cnt += 1
print(f"Part 1: {depth_inc_cnt}")
assert depth_inc_cnt == 1832
depth_windowed_inc_cnt = 0
for i in... |
class ListNode:
def __init__ (self, val, next = None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head):
dummy = ListNode(0)
curr = dummy
dummy.next = head
while curr.next and curr.next.next:
tmp = curr.next
tmp2 ... |
# UVa 11450 - Wedding Shopping - Bottom Up (faster than Top Down)
def main():
TC = int(input())
for tc in range(TC):
MAX_gm = 30 # 20 garments at most and 20 models per garment at most
MAX_M = 210 # maximum budget i... |
LOVE = 'this'
def lover():
"""
docstring
"""
print(LOVE)
def print_nothing():
"""
printing nothing
"""
print('nothing')
def print_nothings():
"""
printing nothings
"""
print('nothings')
class All():
"""
Some doc right here
"""
def __init__(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.