content stringlengths 7 1.05M |
|---|
CATEGORIES = {
"all",
"arts",
"automotive",
"baby",
"beauty",
"books",
"boys",
"computers",
"electronics",
"girls",
"health",
"kitchen",
"industrial",
"mens",
"pets",
"sports",
"games",
"travel",
"womens",
}
CATEGORIES_CHOICES = [
("all",... |
"""#ip 2
addi 2 16 2
seti 1 2 4
seti 1 8 1
mulr 4 1 5
eqrr 5 3 5
addr 5 2 2
addi 2 1 2
addr 4 0 0
addi 1 1 1
gtrr 1 3 5
addr 2 5 2
seti 2 6 2
addi 4 1 4
gtrr 4 3 5
addr 5 2 2
seti 1 2 2
mulr 2 2 2
addi 3 2 3
mulr 3 3 3
mulr 2 3 3
muli 3 11 3
addi 5 2 5
mulr 5 2 5
addi 5 8 5
addr 3 5 3
addr 2 0 2
seti 0 4 2
setr 2 5 5
m... |
mensaje = "Registre el nombre del estudiante "
estudiantes = []
estudiante = input(mensaje)
estudiantes.append(estudiante)
estudiante = input(mensaje)
estudiantes.append(estudiante)
estudiante = input(mensaje)
estudiantes.append(estudiante)
estudiante = input(mensaje)
estudiantes.append(estudiante)
estudiante = input(m... |
# from https://www.ngdc.noaa.gov/geomag/WMM/data/WMM2020/WMM2020_Report.pdf
EQUATOR_RADIUS = 6378137
FLATTENING = 1 / 298.257223563
EE2 = FLATTENING * (2 - FLATTENING) # eecentricity squared
N_MAX = 12 # degree of expansion
|
# -*- coding: utf-8 -*-
def suma(num1, num2):
sm = num1 + num2
return sm
print(suma(2,3))
|
myVariable = 0
def when_started1():
global myVariable
fork_motor_group.spin_to_position(1100, DEGREES, wait=False)
drivetrain.turn_for(RIGHT, 22, DEGREES, wait=True)
# Get goalpost with 2 rings into our zone (22 points)
drivetrain.drive_for(FORWARD, 1200, MM, wait=True)
drivetrain.set... |
n = int(input('Digite o ano para saber se ele foi, é ou será bissesto: '))
if n % 400 == 0:
print(f'O ano de {n} é bissesto!')
else:
if n % 4 == 0 and n % 100 != 0:
print(f'O ano de {n} é bissesto!')
else:
print(f'O ano de {n} não é bissesto!')
|
def search(f, k, ma):
la = 0
r = ma
while r - la > 1:
d = (la + r) // 2
t = f(d)
if t >= k:
r = d
else:
la = d
return r
a, b, c, x, k = map(int, input().split())
def f(t):
if t > b:
rp = t
elif a <= t and t * (1 + c / 100) >... |
def startup(addPluginHook, addHook, world) :
addPluginHook(world, "list", main, 1, ["self", "info", "args", "world"])
def main(self, info, args, world) :
"""list
The list command lists all plugins"""
pluginlist = world.plugins.keys()
pluginlist.sort()
self.msg(info["channel"], "I will send you the l... |
print("Digite um número de 0 a 10")
n = int(input())
nFatorial = 1
for i in range(2, n+1):
nFatorial = nFatorial * i
print("%d! = %d" %(n, nFatorial)) |
#!/usr/bin/env python
class H2O:
def __init__(self):
pass
def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None:
# releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen()
def oxygen(self, releaseOxygen: 'Callable[[], None]') -> No... |
def recursive_update(default, custom):
"""A recursive version of Python dict#update"""
if not isinstance(default, dict) or not isinstance(custom, dict):
raise TypeError('Params of recursive_update() must be a dictionnaries.')
for key in custom:
if isinstance(custom[key], dict) and isinstanc... |
def longestValidParentheses(s: str) -> int:
result = 0
if not s:
return result
n = len(s)
stack = [-1]
for i in range(n):
if s[i] == "(":
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
... |
"""
Selection Sort
https://en.wikipedia.org/wiki/Selection_sort
Worst-case performance: O(N^2)
If you call selection_sort(arr,True), you can see the process of the sort
Default is simulation = False
"""
def selection_sort(arr, simulation=False):
iteration = 0
if simulation:
print("iteration",iter... |
n1 = float(input('Digite o salario atual do funcionario: R$ '))
if n1 > 1250:
n1 = n1 + (n1*10/100)
print(' O novo salario desse colaborador é de R$ {:.2f}'.format(n1))
else:
n1 = n1 + (n1*15/100)
print(' O novo salario desse colaborador é de R$ {:.2f}'.format(n1))
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
i... |
'''
Leia 1 valor inteiro N (2 < N < 1000). A seguir, mostre a tabuada de N:
1 x N = N 2 x N = 2N ... 10 x N = 10N
Entrada
A entrada contém um valor inteiro N (2 < N < 1000).
Saída
Imprima a tabuada de N, conforme o exemplo fornecido.
'''
N = int(input())
for i in range(1, 11):
print('{} x... |
# -*- coding: utf-8 -*-
# Visigoth: A lightweight Python3 library for rendering data visualizations in SVG
# Copyright (C) 2020-2021 Visigoth Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to... |
#!/usr/bin/python3
class FctCheck:
def __init__(self):
pass
def ding_dong(self):
print('')
def _check_me(self, arg):
return True if arg is not None else False
|
def greet(name):
print(f'Good Day, {name}')
name = input('Enter your name: ')
greet(name) |
'''
#Задача 1
#Вывести на экран 5 строк из нулей, причем каждая из строк должна быть пронумерована
s=0; i=0
while i <=4 :
i=i+1
s = 0
print ((i), (s))
#Задача 2
#Пользователь в цикле вводит 10 цифр, Найти количество введенных пользователем цифр 5.
count = 0
for i in range (10):
number = input('Введите ... |
def ver1(sum):
if sum == 1501500:
print("Correct!")
return
else:
print("Incorrect")
return
def hint1():
print("Remember to increment the loop in 3s. Also make sure that the last element is 3001, as it will not be included.")
return
def ver2(product):
if product == 430... |
"""
Decorators
El patrón de diseño decorador es difernte del decorador.
Nos permiten inyectar código para modificar el comportamiento dede un meotodo, función o launa clase.
Sirve para modificar el código y la implementación.
¿Cuando uso los decoradores y qué ventajs me trae?
"""
#El argumento es lo que tenemos int... |
mat = [[x for x in range(4)],
[x for x in range(4,8)],
[x for x in range(8,12)],
[x for x in range(12,16)]]
print(mat)
d = 4
for k in range(0,d):
print("d: ",end=" ")
row , col = range(0,k + 1), range(k,-1,-1)
for i,j in zip(row,col):
print(mat[i][j],end =" ")
... |
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
class Solution:
def solve(self, node):
count = 0
currentNode = node
while currentNode:
count += 1
currentNode = currentNode.next
return cou... |
test = open("needsConversion", "r")
split = test.readlines()
out = """from enum import Enum
class MeshTag(Enum):
"""
i = 0
for l in split:
if "*" in l:
continue
stripped = [x for x in l.replace("\n", "").split(" ") if x != "" and x != "\n"]
if len(stripped) == 0:
continue
out += "\t" ... |
"""
PASSENGERS
"""
numPassengers = 15271
passenger_arriving = (
(2, 7, 3, 3, 0, 1, 1, 1, 0, 0, 1, 1, 0, 9, 0, 3, 2, 3, 1, 2, 1, 1, 2, 0, 0, 0), # 0
(6, 4, 3, 2, 1, 2, 2, 2, 0, 0, 1, 0, 0, 7, 5, 3, 1, 2, 3, 1, 2, 1, 2, 0, 1, 0), # 1
(1, 4, 2, 4, 5, 3, 1, 1, 0, 1, 0, 0, 0, 9, 3, 2, 3, 3, 0, 1, 1, 0, 3, 0, 0, 0), ... |
class FastaParser(object):
def __init__(self, in_file):
self.in_file = in_file
try: (".fasta" in in_file) == True
except ValueError:
raise Exception("%s is not a .fasta file." % (in_file))
try: os.path.exists(in_file) == True
except IOError:
raise Exception("%s can not be found." % (in_file))
|
class Shape:
def __init__(self):
self.__matrix = [[1]]
self.color = ''
self.xy = [0, 0]
def set_matrix(self, new_matrix):
self.__matrix = new_matrix[:]
def is_colored_block(self, x, y):
return self.__matrix[y][x] == 1
def is_shape(self, x, y):
x -= self... |
"""LeetCode, 937
1. The first word in log is the identifier.
2. The letter logs come before all digit logs.
3. The letter-logs are sorted lexicographically by their contents.
If their contents are the same, then sort them lexicographically by their identifiers.
4. The digit-logs maintain their relative ordering."""
de... |
# -*- coding: utf-8 -*-
"""
This exercise is from the book "Think Python: How to Think Like a Computer
Scientist" by Allen B. Downey
"""
def right_justify(string):
"""
Takes a string as a parameter and prints the string with enough leading
spaces so that the last letter of the string is in column 70 of t... |
# fizzbuzz in python
for i in range(1, 101):
printed = False
if i % 3 == 0:
printed = True
print('Fizz', end='')
if i % 5 == 0:
printed = True
print('Buzz', end='')
if not printed:
print(i, end='')
print()
|
# noinspection PyUnusedLocal
def fizz_buzz(number):
if (number % 3 == 0 or '3' in str(number)) and (number % 5 == 0 or '5' in str(number)):
delux = deluxe(number)
if delux:
return "fizz buzz " + delux
return "fizz buzz"
if number % 3 == 0 or '3' in str(number):
... |
# @file Validate Binary Search Tree
# @brief Given a binary tree, check if it is a valid binary search tree (BST).
# https://leetcode.com/problems/validate-binary-search-tree
'''
Assume a BST is defined as follows:
Left subtree of a node contains only nodes with keys lesser than node's key.
Right subtree of a node c... |
class BatchTaskCreateOutDTO(object):
def __init__(self):
self.taskID = None
def getTaskID(self):
return self.taskID
def setTaskID(self, taskID):
self.taskID = taskID
|
#Escreva um programa que leia dois números inteiros e compare-os
# indicando qual o maior número, menor ou se são iguais
num1 = int(input('Digite um número: '))
num2 = int(input('Digite outro número: '))
if num1 > num2:
print(f'O número {num1} é maior que o número {num2}')
elif num2 > num1:
print(f'O número: ... |
def resolve_path2d(seq1, seq2, path):
'''
Given path dictionary, resolve the aligned sequence pair
(which means it supports only DP2d)
#! NOTE: path[(i, j)] = ('prev_step', (prev_x, prev_y))
@param:
seq1 & seq2: sequences used to generate the path dictionary in method DP2d()
#! seq1: x
... |
#
# PySNMP MIB module TRAPEZE-NETWORKS-SYSTEM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-SYSTEM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
"""
Given two words (beginWord and endWord), and a dictionary's word list,
find the length of shortest transformation sequence
from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordLis... |
"""Errors for PyGLEIF."""
class PyGLEIFError(Exception):
"""Base Error"""
pass
class NoMatchError(PyGLEIFError):
"""An error happened sending or receiving a command."""
pass
|
#!/usr/bin/python3
# python实现队列
# Date: 2020-07-13
class Queue():
"""列表实现队列"""
def __init__(self):
self.items = []
def isEmpty(self):
return [] == self.items
def size(self):
return len(self.items)
def isExist(self, item):
return item in self.items
def pickIte... |
# model
model = dict(type='ResNet', depth=18, num_classes=10, maxpool=False)
loss = dict(type='CrossEntropyLoss')
# dataset
root = '/path/to/your/dataset'
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
batch_size = 512
num_workers = 4
data = dict(
train=dict(
ds_dict=dict(
type=... |
# Copyright (c) 2018-2019 Simons Observatory.
# Full license can be found in the top level "LICENSE" file.
"""Test Suite for Simons Observatory TOD Simulation and Processing.
This directory contains the unittest suite.
"""
|
#Felipe Lima
#Linguagem: Python
#Exercício 02 do site: https://wiki.python.org.br/EstruturaSequencial
#Entra com um número
numero = float(input("Digite um número: "))
#Imprime o número digitado
print("O número digitado foi {}.".format(numero)) |
#!/usr/bin/env python
# encoding: utf-8
"""
binary_tree_level_order_traversal.py
Created by Shengwei on 2014-07-29.
"""
# https://oj.leetcode.com/problems/binary-tree-level-order-traversal/
# tags: easy, tree, traversal, bfs
"""
Given a binary tree, return the level order traversal of its nodes' values. (ie, from le... |
class DNSError(Exception):
"""Raised when the resolv cannot be done"""
pass
class TimeExceeded(Exception):
"""Raised when the packet cannot reach the destination"""
pass
class UnknownError(Exception):
"""Raised when the error is unknown (not implemented yet)"""
pass
|
# -*- coding: utf-8 -*-
"""
exceptions.py
~~~~~~~~~~~~~
<Add description of the module here>.
:copyright: (c) 2015-2020 by Jochen Gerhaeusser.
:license: BSD, see LICENSE for details
"""
class ByteOrderTypeError(TypeError):
""" Raised if an inappropriate byte order type is assigned to a field class.
"""
... |
# d.update((['two', 'II'], ['four', 4]))
d = {'one': 1, 'two': 2, 'three': 3}
print(d.update((['two', 'II'], ['four', 4])))
print(d)
|
"""
File: boggle.py
Name: Justin Huang
----------------------------------------
TODO: Boggle Mission
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
dic_list = []
time = 0
def main():
"""
TODO:
"""
boggle = []
read_dic... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
if head is None or head.next is None:
return None
sl... |
'''
Дополните приведенный код, так чтобы он вывел сумму минимального и максимального элементов списка numbers.
numbers = [12.5, 3.1415, 2.718, 9.8, 1.414, 1.1618, 1.324]
print()
'''
numbers = [12.5, 3.1415, 2.718, 9.8, 1.414, 1.1618, 1.324]
print(min(numbers) + max(numbers))
|
BASE_URL = 'https://storyweaver.org.in/api/v1/illustrations-search'
DEFAULT_PAGE_NUM = 1
DEFAULT_PER_PAGE = 10
MAX_PAGE_NUM = 1164
DATA_FOLDER_PATH = '\\Documents\\Github\\Storyweaver\\static\\data\\'
MODEL_FOLDER_PATH = '\\Documents\\Github\\Storyweaver\\model\\'
DETECTED_OBJECT_OUTPUT_PATH = '\\Documents\\Github\\Sto... |
class JobService:
def update_status(self):
pass
|
try:
name, surname = input().split()
print(f"Welcome to our party, {name} {surname}")
except ValueError:
print("You need to enter exactly 2 words. Try again!")
|
class Status:
def __init__(self, x, y):
self.x = x
self.y = y
self.active = False
def max_y(self):
# Het maximale ei gehalte is
# 1 stapje = 0.30mm
# max = 3 meter
max_mm = 3 * 1000
max_steps = max_mm / 0.30
return max_steps
def set_y(self, y):
self.y = y
f = open('/boot/y.txt', 'w')
f.writ... |
r = 's'
c = media = menor = maior = soma = 0
while r in 'Ss':
n = int(input('Digite um valor: '))
soma += n
c += 1
if c == 1:
maior = menor = n # Faz o maior e o menor valerem N
elif n > maior:
maior = n
elif n < menor:
menor = n
r = str(input('Quer continuar? [S/N]:... |
ENTRY_POINT = 'total_match'
FIX = """
Add test case when two list have equal number of chars.
"""
#[PROMPT]
def total_match(lst1, lst2):
'''
Write a function that accepts two lists of strings and returns the list that has
total number of chars in the all strings of the list less than the other list.
... |
"""
Database module
"""
class Database(object):
"""
Defines data structures and methods to store article content.
"""
# pylint: disable=W0613
def merge(self, url, ids):
"""
Merges the results of an existing database into the current database. This method returns
a list of i... |
def MAIN(Number):
if Number > 0:
return Number
return 0
if __name__ == "__main__":
print(
"Hello, World")
MAIN(0)
|
returnedDate = [ int( x ) for x in input( ).split( ' ' ) ]
dueDate = [ int( x ) for x in input( ).split( ' ' ) ]
fine = 0
if returnedDate[ 2 ] > dueDate[ 2 ]:
fine = 10000
elif returnedDate[ 2 ] < dueDate[ 2 ]:
fine = 0
elif returnedDate[ 2 ] == dueDate[ 2 ] and returnedDate[ 1 ] > dueDate[ 1 ]:
fine = 50... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2021 by DeepLn
# Distributed under the MIT software license, see the accompanying
KLINE_INTERVAL = [
"1m",
"3m",
"5m",
"15m",
"30m",
"1h",
"2h",
"4h",
"6h",
"8h",
"12h"... |
num = int(input('Digite um número para calcular seu Faotorial:'))
c = num
cont = 0
f = 1
for n in range(1,num):
cont = cont + 1
num = num * cont
print(f'O fatorial do número digitado é de {num}')
while c > 0:
f = f * c
c = c - 1
print(f'O fatorial do número digitado é de {f}')
|
def color(cor):
"""
Função para colorir as saídas no terminal
:param cor:
# LIMPA FORMATAÇÃO:
"limpa"
# FUNDOS:
"FdBranco"
"FdVerm"
"FdVerde"
"FdAmarelo"
"FdAzul"
"FdRoxo"
"FdAzulClaro"
"FdCinza"
# LETRAS:
"LtBranca"
"LtVerm"
"LtVerde"
"LtAma... |
# Copyright Notice:
# Copyright 2017, Fitbit, Inc.
# 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 to ... |
# -*- coding: utf-8 -*-
# Author: XuMing <shibing624@126.com>
# Data: 17/10/15
# Brief:
with open("1.txt", "r", encoding="utf-8") as f:
for i in f:
parts = i.strip().split("\t")
print(parts[22])
|
donor_dict = \
{
1: 3,
2: 6,
3: 9,
4: 12,
5: 11,
6: 8,
7: 5,
8: 2,
9: 1,
10: 4,
11: 7,
12: 10,
}
cell_dict = {
'CD68': {
'legend': "Macrophage (CD68+)",
'full': "Macrophage (CD68+)",
'sho... |
# File type implements the Context Manager Protocol
# can therefore use a file in a with as statement
with open('myfile.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line, end='')
print('Done')
|
# -*- coding:utf-8 -*-
"""
@author: Alden
@email: sunzhenhy@gmail.com
@date: 2018/4/6
@version: 1.0.0.0
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
... |
class Solution:
def numberOfSubarrays(self, nums: 'List[int]', k: int) -> int:
odds = []
x = 0
for i, num in enumerate(nums):
if num % 2 == 1:
odds.append(x)
x = 0
else:
x += 1
odds.append(x)
res = 0
... |
"""
DAG (Directed Acyclic Graph)
"""
class Node:
_id = 0
def __init__(self,
weights,
# parent: list = [],
# edges: list = [],
_id=None,
creator=None):
# id
if _id != None:
self._id = _id
... |
# the following file holds meta information about the sunpy package
sunpy_releases = {'0.9': '2018/04/22', '0.8': '2017/08/17', '0.7': '2016/05/24', '0.6': '2015/07/21',
'0.5': '2014/06/13', '0.4': '2014/02/14', '0.3': '2013/08/30',
'0.2': '2012/11/26', '0.1': '2011/09/28'}
repo_pa... |
def parse(filename: str):
with open(filename) as file:
fileLines = file.read().split('\n')
width, height = len(fileLines[0]), len(fileLines)
eastHerd, southHerd = set(), set()
for y, line in enumerate(fileLines):
for x, char in enumerate(line):
if char ==... |
# coding=utf-8
"""
两个链表的交叉
描述: 请写一个程序,找到两个单链表最开始的交叉节点。
思路:
我一开始的解法做了一个错误示范
我一开始想的是 把两个链表翻转
然后从头开始对比,不一致时。
那之前一个元素就是起点。
然后会发现一个问题就是
A:6->7->。。。->13->null
B:1->2->3->。。。->13->null
RA: 13->12->。。。->6->null
这对B的就有影响了
RB: 6->5->4->3->2->1->null
B的结构都变了
"""
"""
Definition of ListNode
class ListNode(object):
def __... |
preco = float(input("Entre com o preço da mercadoria R$ "))
desconto = int(input("Entre com o percentual de desconto: "))
print(f"O valor do desconto será de R${preco * (desconto/100):.2f}")
print(f"O preço da mercadoria com desconto será de R${preco - preco * (desconto/100):.2f}")
|
USES_BASE64 = True
REDIRECT = None
AUTHOR = 'BrocaProgs'
APPNAME = 'PyQt_Socius'
|
# Lista ordenada sem repetições
lista = []
for i in range(5):
n = int(input("Digite um valor: "))
if i == 0 or n > lista[-1]:
lista.append(n)
print("O numero foi adicionado no final da lista ...")
else:
for i in range(5):
if n <= lista[i]:
lista.insert(i, ... |
"""profile_ex
This module contains supporting code to be used by cProfile
The cProfile can be run on this file (from the commandline) as:
$python -m cProfile profile_ex.py
This module is compatible with Python 3.5.x. It contains
supporting code for the book, Learning Python Application Development,
Packt Publishing.
... |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "dedecms")
whatweb.recog_from_file(pluginname, "templets/default/style/dedecms.css", "DedeCMS")
|
# Python function to print leaders in array
def printLeaders(l, size):
m=[]
max_element = l[size-1]
m.append(max_element)
for i in range(size-2, -1, -1):
if max_element <= l[i]:
m.append(l[i])
max_element = l[i]
for k in range(len(m)-1... |
class Parser:
def __init__(self):
pass
def parse(self, record):
raise NotImplementedError('the parse method should be implemented by subclasses')
class Success(Parser):
def __init__(self):
super().__init__()
def parse(self, record):
return [('', record)]
class Pre... |
a < b < c
x in y
x not in y
x is y
x is not y
x < y
x > y
x >= y
x <= y
x == y
x != y
|
VERSION = '0.0.1'
WELCOME_MSG = """\
Kite REPL, version: {}\
""".format(VERSION)
REPL_USAGE = """\
?, :h, :help - Show help message
:e, :env - Show current dynamic environment
:d, :del <name> - Delete name from the environment (todo)
:b, :builtin - Show built-in environment
:l, :load ... |
# url -> https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/11/ALDS1_11_A
N = int(input().rstrip())
def generateGraph(N):
graph = [[0]*N for _ in range(N)]
for _ in range(N):
U, A, *B = map(int, input().rstrip().split())
for i in range(A):
graph[U-1][B[i]-1] = 1
... |
# Copyright 2016 Anselm Binninger, Thomas Maier, Ralph Schaumann
#
# 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 appl... |
#! Metanit.com - Python: Chapter 2, lesson 3 "Operations with Numbers".
y = 0x0a # hexadecimal system, 11
a = 0o11 # octal system, 9
x = 0b101 # binary system, 5
z = x + y
# Awesome string formatters.
print("{0} in binary {0:08b}; in hex {0:02x} in octal {0:02o}".format(z))
# {:n} - 'n' indicates h... |
# Python - 3.6.0
test.assert_equals(string_to_number('1234'), 1234)
test.assert_equals(string_to_number('605'), 605)
test.assert_equals(string_to_number('1405'), 1405)
test.assert_equals(string_to_number('1234'), 1234)
|
"""Calculate the simple edit distance.
Calculates the simple edit distance by calculating a Longest Common
Subsequence (LCS) alignment [1]_. The implementation is adapted from [2]_.
This method is useful when only the simple edit distance is needed (not
an or all alignments).
See Also
--------
algebra.lcs.all_lcs : C... |
def get_formatted(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print('Please tell me your name:')
# print('Press "q" to quit')
f_name = input('Fist Name: ')
l_name = input('Last Name: ')
formatted_name = get_formatted(f_name, l_name)... |
find_sum_of_squearse = lambda x, y: x**2 + y**2
print(find_sum_of_squearse(3, 5))
words = ["hello", "monkey", "python"]
wordsSort = max(words, key = lambda x: x.count("1"))
print(wordsSort) |
# -*- coding:utf-8 -*-
# 信息门户账号密码
username = ''
password = ''
# 邮箱账号密码
emailUsername = ''
emailPassword = ''
|
class KomodoRPC:
node_addr = '127.0.0.1'
rpc_port = 7777
req_method = 'POST'
rpc_username = ''
rpc_password = ''
req_auth = {
'user': rpc_username,
'pass': rpc_password
}
req_url = 'http://{0}:{1}/'.format(str(node_addr), str(rpc_port))
req_headers = {
... |
def josephus(n, k):
q = [i for i in range(1, n + 1)]
j = 0
while len(q) > 1:
j = (j + k - 1) % len(q)
q.pop(j)
return q[0]
print(josephus(41, 3)) |
# Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
#
# Example 1:
#
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
#
#
#
# Note:
# In the string, each word is separated by single spac... |
#python program to print strings and type
str1 = "Hi my name is Matthew. I am String"
str2 = 'Hi my name is Precious. I am also String'
#displaying string str1 and its type
print(str1)
print(type(str1))
#displaying string str1 and its type
print(str2)
print(type(str2))
|
# Define a String
str = "python"
# Convert String in Upper Case and assign to variable strupper
strupper = str.upper();
# Print both the original and the converted fields
print(str+ " is converted to the Upper Case as "+ strupper);
|
Search_Amish={
'Amish+Romance':['http://www.amazon.com/s/ref=sr_pg_5?rh=i%3Aaps%2Ck%3AAmish+Romance&page=1','http://www.amazon.com/s/ref=sr_pg_5?rh=i%3Aaps%2Ck%3AAmish+Romance&page=2','http://www.amazon.com/s/ref=sr_pg_5?rh=i%3Aaps%2Ck%3AAmish+Romance&page=3','http://www.amazon.com/s/ref=sr_pg_5?rh=i%3Aaps%2Ck%3AAmish+... |
class Solution:
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [0] + [float('inf')] * amount
for i in range(1, amount + 1): dp[i] = min([dp[i - c] if i - c >= 0 else float('inf') for c in coins]) + 1
... |
def find(searchList, elem):
endList = []
for indElem in range(0,len(elem)):
resultList = []
for ind in range(0, len(searchList)):
if searchList[ind] == elem[indElem]:
resultList.append(ind)
endList.extend([resultList])
retur... |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
title = "AJAX Helper"
host = "localhost"
port = 8001
|
Names = ["John","Steve","Brian","Jim","Alex","Paul","Micheal","Bruce","Alfred","Buzz","Eric","Gary"]
Nombre = [i for i in range(1,1000000)]
def affiche(names):
for name in names:
yield name
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.