content stringlengths 7 1.05M |
|---|
"""
https://leetcode.com/problems/number-of-islands/
"""
class Solution:
""" Wrapper for LeetCode Solution """
def numIslands(self, grid: [[str]]) -> int:
"""
Determines the number of islands in a matrix, before destroying them
"""
# No islands or land
if not grid or n... |
# author Mahmud Ahsan
# --------------------
# msmath module under mspack package
# --------------------
def sum(x, y):
return x + y
def subtract(x, y):
return x - y
def multiplication(x, y):
return x * y
def division(x, y):
return x / y |
rows=input()
rows=int(rows)
k=0
matrixList=[]; evenMatrix=[]
while rows!=0:
matrix=input()
matrix=matrix.split(", "); matrix=[int(e) for e in matrix]
e=0; elements=len(matrix)
matrixList.append([])
while e < elements:
matrixList[k].append(matrix[0])
del matrix[0]
... |
def profitable_gamble(prob, prize, pay):
if prob * prize > pay:
return True
return False
print(profitable_gamble(4,8,12)) |
#addition.py
def add(a,b):
return a+b
a=int(input("Enter the a value"))
b= int(input("Enter the b value"))
c=add(a,b)
print(c) |
"""
VARIAVEIS COMPOSTAS (LISTAS PARTE 2)
dados = [nome, idade]
pessoas.append(dados[:]) -> o [:] é usado para fazer uma copia da lista "dados"
print(pessoas[0][0]) -> Neste Caso pessoas terá dentro dela a lista "dados", e pegará assim então o item 0 da lista
"dados, que é "nome".
""" |
class DissectError(Exception):
"""
Error when
- initially parsing / constructing a message (Checksum error, message to small, ...) or
- trying to access data / certain attributes (No payload, payload too small, payload does make no sense)
May also occur when encountering edge cases not yet handled by the disse... |
class Block:
def __init__(self):
self.statements = []
def add_statement(self, statement):
self.statements.append(statement)
|
# TODO: Just change this to CSS
colors = {
"text" : "#aaaaaa",
"background" : "#222221",
"plot_background" : "#222221",
"plot_gridlines" : "#777776",
"page_background" : "#222221"
} |
clang_env = {
"ASAN_SYMBOLIZER_PATH": "/usr/local/bin/llvm-symbolizer",
"CC": "/usr/local/bin/clang",
"GCOV": "/dev/null",
"LD_LIBRARY_PATH": "/usr/local/lib",
"MSAN_SYMBOLIZER_PATH": "/usr/local/bin/llvm-symbolizer",
"TSAN_SYMBOLIZER_PATH": "/usr/local/bin/llvm-symbolizer",
"UBSAN_SYMBOLIZE... |
# Task 03. Special Numbers
num = int(input())
digits = [x for x in range(1,num+1)]
is_special = False
for digit in digits:
digit_iter = [int(x) for x in str(digit)]
if sum(digit_iter) == 5 or sum(digit_iter) == 7 or sum(digit_iter) == 11:
is_special = True
else:
is_special = False
pri... |
__version__ = '0.11.2'
# import importlib
# import logging
# from pathlib import Path
# importlib.reload(logging)
# logpath = Path.home() / 'p4reduction.log'
# logging.basicConfig(filename=str(logpath), filemode='w',
# format='%(asctime)s %(levelname)s: %(message)s',
# datefmt='... |
def binario(n):
num = []
while(n>1):
if(n==2 or n==3):
resto = n % 2
n //= 2
num.append(resto)
num.append(n)
else:
resto = n % 2
n //= 2
num.append(resto)
return num
n = int(input('digite um numero: '))
n... |
# Aula 20 - 05-12-2019
# Surgiu a necessidade de envio massivo de e-mails dos clientes cadastrados
# no arquivo cadastro1.txt
# >>>> Fazer tudo com metodos <<<<<
# 1 - Para isso o programa necessita que separe os clientes maiores de 20 anos
# em um arquivo separado chamado menores_de_idade.txt
# 2 - Separar os c... |
#
#
# Package libApp in directory source
#
#
print("Loaded libApp")
#
# This file can be left empty, but its presence informs the import mechanism
#
|
EXPECTED_DAILY_WEBSITE_GENERATE_SAMPLES_QUERIES_SIZE = """delimiter //
DROP PROCEDURE IF EXISTS get_daily_samples_size_websites;
CREATE PROCEDURE get_daily_samples_size_websites (
IN id INT,
OUT entry0 FLOAT,
OUT entry1 FLOAT,
OUT entry2 FLOAT,
OUT entry3 FLOAT,
OUT entry4 FLOAT,
OUT entry5 ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Corwin Brown <corwin@corwinbrown.com>
# Copyright: (c) 2017, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if... |
"""
Ordered fractions
Problem 71
https://projecteuler.net/problem=71
Consider the fraction n/d, where n and d are positive
integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
If we list the set of reduced proper fractions for d ≤ 8
in ascending order of size, we get:
1/8, 1/7, 1/6, 1/5, 1/4, ... |
VERSION = "3.6.dev1"
SERIES = '.'.join(VERSION.split('.')[:2])
|
cookie = {
'ipb_member_id': '',
'ipb_pass_hash': '',
'igneous': '',
} |
reta1 = int(input("Valor da 1° reta: "))
reta2 = int(input("Valor da 2° reta: "))
reta3 = int(input("Valor da 3° reta: "))
if reta1+reta2 > reta3 and reta1+reta3 > reta2 and reta2+reta3 > reta1:
print("Formam um triangulo")
else:
print("Não formam um triangulo")
|
def asal_mi(sayi):
if(sayi==1):
return False
elif(sayi==2):
return True
else:
for i in range(2,sayi):
if(sayi%i ==0) :
return False
return True
while True:
sayi = input("sayi : ")
if(sayi =="q"):
break
else:
... |
"""
TASK: Find the edit distance between two given strings.
The edit distance between two strings refers to the minimum number of character insertions,
deletions, and substitutions required to change one string to the other
"""
def edit_distance(str1: str, str2: str) -> int:
print("->edit_distance: str1={}, str2... |
class UserTarget:
@staticmethod
def get_response():
return "Response by UserTarget"
|
guys = list()
dado = list()
tormai = tormen = 0
for c in range(0,3):
dado.append(str(input('Nome: ')))
dado.append(int(input('Idade: ')))
guys.append(dado[:])
dado.clear()
print(guys)
for p in guys:
if p[1] >=21:
print(f'{p[0]} é maior de idade.')
tormai += 1
else:
print(... |
class ATM:
def __init__(self, balance, bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def calcul(self,request):
self.withdrawals_list.append(request)
self.balance -= request
notes =[100,50,10,5]
for note in notes :... |
# Минимум 4 чисел
def min4(a, b, c, d):
return min(min(a, b), min(c, d))
if __name__ == '__main__':
a, b, c, d = int(input()), int(input()), int(input()), int(input())
print(min4(a, b, c, d))
|
# ESTATISTICAS EM PRODUTOS
# Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre:
# A) qual é o total gasto na compra.
# B) quantos produtos custam mais de R$1000.
# C) qual é o nome do produto mais barato.
st = sm = maior = men... |
#
# @lc app=leetcode id=53 lang=python3
#
# [53] Maximum Subarray
#
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if all([x < 0 for x in nums]):
return max(nums)
running_sum = 0
ans = 0
for x in nums:
running_sum += x
... |
#include inc/node.py
class Example(Node):
def __init__(self, selector):
self.dom_bind_to_node_by_selector(selector)
print(self._node)
self.dom_set_classes(['blue'])
# some raw js...
# RawJS("""/* foo */""")
|
# flake8: NOQA: E501
# This proves that the given key (which is an account) exists on the trie rooted at this state
# root. It was obtained by querying geth via the LES protocol
state_root = b'Gu\xd8\x85\xf5/\x83:e\xf5\x9e0\x0b\xce\x86J\xcc\xe4.0\xc8#\xdaW\xb3\xbd\xd0).\x91\x17\xe8'
key = b'\x9b\xbf\xc3\x08Z\xd0\xd47\x... |
#!/usr/bin/python
#
# This file is part of PyRQA.
# Copyright 2015 Tobias Rawald, Mike Sips.
"""
Custom exceptions.
"""
class UnsupportedNeighbourhoodException(Exception):
""" Neighbourhood chosen is not supported. """
def __init__(self, message):
super(UnsupportedNeighbourhoodException, self).__init... |
# Minizip library
unz = StaticLibrary( 'unz', sources = ['ioapi.c', 'mztools.c', 'unzip.c', 'zip.c'] )
# minizip
minizip = Executable( 'minizip', libs = [ unz, 'z' ], sources = ['minizip.c'] )
# miniunz
miniunz = Executable( 'miniunz', libs = [ unz, 'z' ], sources = ['miniunz.c'] )
# Platform specific setti... |
"""
The tests in this module are based on those from Python
https://github.com/python/cpython/tree/master/Lib/test/test_json
Licensed under the Python Software Foundation License Version 2.
Copyright © 2001-2020 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com . All rights reserved.
Copyrig... |
_base_ = [
'./coco_resize.py'
]
data = dict(
train=dict(classes=('person',)),
val=dict(classes=('person',)),
test=dict(classes=('person',))
)
|
class DFS:
def __init__(self):
self.visited_node_counter = 0
def visitor(self):
self.visited_node_counter += 1
def visit(self, node):
node.accept_visitor(self.visitor)
for child in node.children: self.visit(child)
class Node:
def __init__(self):
self.children = []
def add_child(self,... |
n=int(input())
l=[1 for i in range(n)]
for i in range(1,n):
for x in range(n):
if x==0:
continue
else:
l[x]=l[x]+l[x-1]
print(l[-1])
|
android = 70 # percents of people using nova poshta on android
ios = 30 # percents of people using nova poshta on ios
people_count = 5000000
ios_people = people_count/ 100 * ios
print (ios_people, " people using nova poshta on ios.") |
# Desenvolva um algoritmo em Python que exiba os números pares entre 0 a 10
for num in range(11):
if num%2==0:
print(num) |
class Profile:
'''
Example
my = Profile('Rob')
my.company = 'CPF'
my.hobby = ['Reading','Sleeping','Eating']
print(my.name)
my.show_email()
my.show_myart()
my.show_hobby()
'''
def __init__(self,name):
self.name = name
self.company = ''
self.hobby = []
self.art = '''
|\ _... |
def format_duration(seconds):
years = int(seconds/(365*24*60*60))
days = int((seconds-(years*365*24*60*60))/(24*60*60))
hours = int((seconds-(years*365*24*60*60)-(days*24*60*60)) / (60*60))
mins = int((seconds-(years*365*24*60*60)-(days*24*60*60) - hours*60*60)/60)
sec = (seconds -(years*365*24*60*... |
# "range(1,11)" just provides us a list of numbers 1-10 (the last number isn't included).
# The list in this case would look like this: [1,2,3,4,5,6,7,8,9,10].
# For loop
## This takes each number inside "range", and saves it as a variable "i". It does whatever is in the loop with that variable, then moves to the next... |
"""
Exercícios proposto
"""
carrinho = []
carrinho.append(('Produto 1', 30))
carrinho.append(('Produto 2', 20))
carrinho.append(('Produto 3', 50))
total = sum([float(y) for x, y in carrinho])
# total = {x: y+y for x, y in carrinho}
print(total)
|
def merge_sort(sorted_l1, sorted_l2):
""" Merge sorting two sorted array """
result = []
i = 0
j = 0
while i < len(sorted_l1) and j < len(sorted_l2):
if sorted_l1[i] < sorted_l2[j]:
result.append(sorted_l1[i])
i += 1
else:
result.append(sorted_l2... |
math_str = input("please input a number: ")
math = int(math_str)
math6 = 6
if math == math6:
print("Yes, it is 6!")
elif math < math6:
print("That's less than 6!")
else:
print("That's more than 6!")
|
a = arr = [[False for i in range(100)] for j in range(100)]
ans = 0
sl = 0
block= []
def findLargestRectangle(blockNumber):
global sl
global block
block = blockNumber
for i in block: sl += i
for i in range(1,9):
find(i, 1)
return ans
def find(r,n):
global ans
global a
# ca... |
"""
В условиях предыдущей задачи определите количество школьников, ставших победителями в каждом классе. Победителями
объявляются все, кто набрал наибольшее число баллов по данному классу. Гарантируется, что в каждом классе был хотя бы
один участник.
Формат вывода
Выведите три числа: количество победителей олимпиады п... |
# -*- coding: utf-8 -*-
# @Time : 2019-12-20 17:31
# @Author : songzhenxi
# @Email : songzx_2326@163.com
# @File : LeetCode_77_1034.py
# @Software: PyCharm
# 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
#
# 示例:
#
# 输入: n = 4, k = 2
# 输出:
# [
# [2,4],
# [3,4],
# [2,3],
# [1,2],
# [1,3],
# [1,4],
# ]
# Related... |
# Adicione na classe MyLinkedList, um método que retorne a quantidade de elementos na lista.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class MyLinkedList:
def __init__(self):
self.head = None
self.length = 0
def add(self, value):
... |
def rook_cells_under_attack(p, width=8, height=8):
cells = []
for i in range(height):
cells.append((p[0], i))
for i in range(width):
cells.append((i, p[1]))
return cells
# TODO: add width and height parameters
def bishop_cells_under_attack(p, width=8, height=8):
cells = []
for ... |
nome = str(input("Digite seu nome completo: ")).strip()
nome = nome.lower()
#verifica = nome.find('silva') > 0
print("Seu nome tem Silva? ")
#print("{}".format(verifica))
print("{}".format("silva" in nome))
|
# Solution
# O(n*l) time / O(c) space
# n - number of words
# l - length of the longest word
# c - number of unique characters across all words
def minimumCharactersForWords(words):
maximumCharacterFrequencies = {}
for word in words:
characterFrequencies = countCharacterFrequencies(word)
updateMax... |
a = map(int, input().split())
b = map(int, input().split())
c = map(int, input().split())
d = map(int, input().split())
e = map(int, input().split())
_a, _b, _c, _d, _e = sum(a), sum(b), sum(c), sum(d), sum(e)
m = max(_a, _b, _c, _d, _e)
if m == _a:
print(1, _a)
elif m == _b:
print(2, _b)
elif m == _c:
pr... |
L=[23,45,88,23,56,78,96]
Temp=L[0]
L[0]=L[-1]
L[-1]=Temp
print(L)
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {integer} s
# @param {integer[]} nums
# @return {integer}
def minSubArrayLen(self, s, nums):
start = 0
sum = 0
min_size = float("inf")
for i in xrange(len(nums)):
sum += nums[i]
... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
'TEST_NAME': 'test1.db',
}
}
ROOT_URLCONF='testapp.urls'
SITE_ID = 1
SECRET_KEY = "not very secret in tests"
ALLOWED_HOSTS = (
'testserver',
'*'
)
INSTALLED_APPS = (
"rest_framework",
... |
#Write a Python program that reads your height in cms and converts your height to feet and inches.
heightCM = float(input('Enter the height in CM: '))
totalInch = heightCM * 0.393701
heightInch = (totalInch % 12)
heightFeet = (totalInch - heightInch)*0.0833333
print('The height is : ',heightFeet,' feet AND 163',... |
"""Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True."""
class Solution:
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
check = set()
for c in s:
... |
#!/usr/bin/env python3.7
rules = {}
with open('input.txt') as fd:
for line in fd:
words = line[:-1].split()
this_bag = words[0]+ " " + words[1]
rules[this_bag] = []
b = line[:-1].split('contain')
bags = b[1].split(',')
for bag in bags:
words = bag.split()... |
ordered_params = ['vmax', 'km', 'k_synt_s', 'k_deg_s', 'k_deg_p']
n_vars = 2
def model(y, t, yout, p):
#---------------------------------------------------------#
#Parameters#
#---------------------------------------------------------#
vmax = p[0]
km = p[1]
k_synt_s = p[2]
k_deg_s = p[3]
... |
"""
Purpose: Stakoverflow question finding first and last coordinates for values in matrix
Date created: 2019-12-28
URI: https://stackoverflow.com/questions/59511521/how-to-get-start-and-end-of-subsection-of-2d-array-where-a-condition-holds/59511652#59511652
Contributor(s):
Mark M.
"""
a = [[0, 0, 0, 0],
... |
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
ls=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
ls.append(b)
print("Max number in the list is:",max_num_in_list(ls))
|
def ports():
portas_top10 = [21,22,23,25,53,80,110,139,443,445]
portas_top20 = [21,22,23,25,53,80,110,135,139,143,443,445,993,995,1723,2222,3306,3389,5900,8080,8291]
portas_top30 = [21,22,23,25,80,110,135,139,143,443,445,993,995,1723,2222,3306,3389,5900,5060,5666,6001,8000,8008,8080,8291,8443,8888,10000,32768,491... |
iter_num = 0
def fib(num):
global iter_num
iter_num += 1
print("Iteration number {0}. num = {1}".format(iter_num, num))
# Base class for fibonnaci series
if num==0 or num==1:
return 1
# Recursive call
else:
return fib(num-1)+fib(num-2)
if __name__ == '__main__':
num =... |
class Solution:
@staticmethod
def _encode(word):
enc = []
idx = 0
repeat = 0
prev = None
while idx < len(word):
if word[idx] == prev:
idx += 1
repeat += 1
else:
if prev:
... |
def getNext(instr):
count=0
curch=instr[0]
outstr=[]
for ch in instr:
if ch != curch:
outstr.append(str(count)+curch)
curch=ch
count=1
else:
count+=1
outstr.append(str(count)+curch)
return ''.join(outstr)
a=['1']
for i in range(31)... |
# coding=utf-8
__author__ = 'Gareth Coles'
class BaseAlgorithm(object):
def hash(self, value, salt):
pass
def check(self, hash, value, salt):
return hash == self.hash(value, salt)
def gen_salt(self):
pass
|
description = ''
pages = ['header',
'my_account']
def setup(data):
pass
def test(data):
navigate('http://store.demoqa.com/')
click(header.my_account)
verify_is_not_selected(my_account.remember_me)
capture('Remember me is not selected')
def teardown(data):
pass
|
# -*- coding: utf-8 -*-
# 配置参数
class Config:
def __init__(self):
self.BATCH_SIZE = 64
self.TEST_BATCH_SIZE = 1000
self.EPOCHS = 3
self.LEARNING_RATE = 0.001
self.SGD_MOMENTUM = 0.5
self.SEED = 1
self.LOG_INTERVAL = 10 |
# Vamos a convertir un numero entero en una lista de sus digitos
numero = int(input('Dime tu numero\n'))
digitos =[]
while numero !=0:
digitos.insert(0,numero%10)
numero //= 10
print('Los digitos de su numero son',digitos)
|
def main():
input = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1... |
n=int(input().strip())
b=input().strip()
step=0
for i in range(0,n-2):
if(b[i]+b[i+1]+b[i+2]=='010'):
step+=1
print(step)
|
# -*- coding: utf-8 -*-
"""
View and Model base classes used to control access permissions for CRUD requests.
"""
__version__ = '0.1' |
"""Dummy technologies
"""
def insert_dummy_technologies(technologies, tech_p_by, all_specified_tech_enduse_by):
"""Define dummy technologies
Where no specific technologies are assigned for an enduse
and a fueltype, dummy technologies are generated. This is
necessary because the model needs a technolog... |
SHOWNAMES = [
"ap1/product-id",
"ap1/adc0",
"ap1/adc1",
"ap1/adc2",
"ap1/din0",
"ap1/din1",
"ap1/din2",
"ap1/din3",
"ap1/led1",
"ap1/led2",
"ap1/device-id",
"ap1/vendor-id",
"ap1/dout0",
"ap1/dout1",
"ap1/dout2",
"ap1/dout3",
"ap1/reset",
"ap1/dout... |
def merge(left, right, sorted_lst):
i, j, k = 0, 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
sorted_lst[k] = left[i]
i += 1
else:
sorted_lst[k] = right[j]
j += 1
k += 1
while i < len(left):
sorted_lst... |
# vestlus:admin:actions
def make_read(model, request, queryset):
queryset.update(read=True)
make_read.short_description = "Mark as read"
def make_unread(model, request, queryset):
queryset.update(read=False)
make_unread.short_description = "Mark as unread"
def make_private(model, request, queryset):
... |
def find(key, dictionary):
"""
Generator to extract items from complex nested data structures
source: https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-python-dictionaries-and-lists
:param key: Key to look for
:param dictionary: Object with nested dicts and lists
... |
class FeedMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
if self.is_atom_feed(environ['PATH_INFO']):
def _start_response(status, headers, exc_info=None):
return start_response(status, self.set_charset(headers... |
var = 0
print("Hello!")
while var < 10:
print(10 - var, end="\n")
var += 2 |
email = input("Introduce email: ")
if email.count("@") == 1 and email.count("@", 1, len(email) - 1) == 1:
print("La dirección de correo es correcta.")
else:
print("La dirección de correo es incorrecta.")
|
def main():
# input
ABCs = [*map(int, input().split())]
# compute
# output
print(2 * sum([ABCs[i-1]*ABCs[i] for i in range(3)]))
if __name__ == '__main__':
main()
|
# global关键字声明的变量必须在全局作用域上,不能嵌套作用域上,
# 当要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量怎么办呢,这时就需要nonlocal关键字了
def outer():
count = 10
def inner():
# nonlocal count
# global count
count = 100
print(count)
inner()
print(count)
outer()
# 当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了,
# 当修改... |
async def async_value(value):
"""
Gives an object which can be used in .thenReturn for methods that are coroutines
:param value: what should be returned after coroutine is awaited
:return: coroutine that can be awaited
"""
return value
# noinspection PyPep8Naming
class async_iter:
"""
... |
def get_larger(x, y):
if x > y:
return x
else:
return y
larger_value = get_larger(23, 32)
print(larger_value)
def add_numbers(x, y):
total = x + y
return total
print("This won't be printed")
print(add_numbers(4, 5))
#Comment and doc string
# few variables below
x = 10
y = 5
# m... |
class Worker:
""" An abstraction of a worker. """
def __init__(self, worker_id: str):
""" Create a worker instance.
Args:
worker_id: the id that uniquely identifies the user.
"""
self._worker_id = worker_id
def worker_id(self) -> str:
... |
"""
imutils/ml/aug/image/__init__.py
"""
|
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
Crea un programa, que calcule el equivalente humano de la edad de un
perro. Si los dos primeros años de vida de un perro equivalen diez años
humanos, y los siguientes años de vida de un perro equivalen cada uno a
cuatro años humanos.
"""
def calcular(edad... |
#Q.1 Convert tuples to list.
tup=(5,4,2,'a',16,'ram') #this is a tuples.
l=[] #this is empty list.
lenght=len(tup)
for i in (tup):
l.append(i)
print("list converted form tuples is :",l)
|
#A particularly hard problem to solve
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
#Suppose we have two arrays that are sorted
#l1 = [1,2,3]
#l2 = [4,5,6]
#L1 + L2 = [1,2,3,4,5,6]
#The median 3.5.
#Notice that the ind... |
epsilon = 0.001
def sqr_root(low,high,n,const_value):
mid = (low+high)/2.0
mid_2 = mid
for _i in range(n-1):
mid_2*=mid
dif = mid_2 - const_value
if abs(dif) <= epsilon:
return mid
elif mid_2 > const_value:
return sqr_root(low,mid,n,const_value)
elif mid_2 < const_value:
return sqr... |
#! /usr/bin/python3
# seesway.py -- This script counts from -10 to 10 and then back from 10 to -10
# Author -- Prince Oppong Boamah<regioths@gmail.com>
# Date -- 27th August 2015
for i in range(-10, 11): print(i)
for i in range(9, -1, -1): print(i)
for i in range(-10, 0): print(i)
|
#WAP to input marks of 5 subject and find average and assign grade
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the ... |
"""Kata url: https://www.codewars.com/kata/5803c0c6ab6c20a06f000026."""
def swap_vowel_case(st: str) -> str:
return ''.join(
x.swapcase() if x.lower() in 'aeoui' else x for x in st
)
|
class Solution:
def thirdMax(self, nums: List[int]) -> int:
maxs = [-float('inf'),-float('inf'),-float('inf')]
m = 0
for i in range(len(nums)):
if nums[i] not in maxs:
if m < 3 :
maxs[m] = nums[i]
m += 1
... |
VERSION = '0.2'
TYPE = 'type'
LIBRML = 'libRML'
ITEM = 'item'
ID = 'id'
ACTIONS = 'actions'
RESTRICTIONS = 'restrictions'
PERMISSION = 'permission'
TENANT = 'tenant'
MENTION = 'mention'
SHARE = 'sharealike'
USAGEGUIDE = 'usageguide'
TEMPLATE = 'template'
#XML
XRESTRICTION = 'restriction'
XACTION = 'action'
XPART = '... |
def factorial(n):
if(n == 0):
return 1
else:
return n*factorial(n-1)
if __name__ == "__main__":
number = int(input("Enter number:"))
print(f'Factorial of {number} is {factorial(number)}')
|
# TRATANDO VÁRIOS VALORES v1.0
# Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).
cont = 0
s = 0
valor = int(... |
A = True
B = False
C = A and B
D = A or B
if C == True:
print("A and B is True.")
else:
print("A and B is False.")
if D == True:
print("A or B is True.")
else:
print("A or B is False.")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.