content stringlengths 7 1.05M |
|---|
left_eye_connection = [
# Left eye.
(263, 249),
(249, 390),
(390, 373),
(373, 374),
(374, 380),
(380, 381),
(381, 382),
(382, 362),
(263, 466),
(466, 388),
(388, 387),
(387, 386),
(386, 385),
(385, 384),
(384, 398),
(398, 362)
]
left_eyebrow_connection... |
# --------------------------------------------------------
# GA3C for Dragon
# Copyright(c) 2017 SeetaTech
# Written by Ting Pan
# --------------------------------------------------------
class Config(object):
#########################################################################
# Game configuration
... |
INPUT_BUCKET = 'input-image-files'
OUTPUT_BUCKET = 'output-image-files'
INPUT_QUEUE = 'https://sqs.us-east-1.amazonaws.com/378107157540/Request-Queue'
OUTPUT_QUEUE = 'https://sqs.us-east-1.amazonaws.com/378107157540/Response-Queue'
|
f='11'
for i in range(5):
c=1
s=''
for j in range(len(f)-1):
if f[j]==f[j+1]:
c+=1
else:
s=(str(c)+(f[j]))
s=str(c)+(f[j])
f=str(s)
print(f)
|
"""API routes"""
ROUTE_CVE_ANNOUNCEMENTS = "/api/v3/cve_announcements"
ROUTE_GROUPS = "/api/v3/groups"
ROUTE_HOSTS = "/api/v3/hosts"
ROUTE_NODES = "/api/v3/nodes"
ROUTE_PING = "/api/v3/ping"
ROUTE_REMOTE_ACCESSES = "/api/v3/remote_accesses"
ROUTE_SECURITY_ISSUES = "/api/v3/security_issues"
ROUTE_SERVERS = "/api/v3/ser... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class ComposeModeException(Exception):
""" Base exception for compose-mode """
class ComposeModeYmlNotFound(ComposeModeException):
""" Exception raised when no configuration file was found """
def main():
pass
if __name__ == '__main__':
main()
|
"""
© https://sudipghimire.com.np
Create 3 different classes Length, Weight, and Time
Add respective attributes to store values.
Add static methods for conversion of different units.
Example:
Length: cm to inches, kilometer to miles, etc
Weight: KG to pounds, gram to Ounces, etc.
Time: seconds to hours, milliseconds... |
query = """
type Query {
photo(photoId: ID!): Photo!
photos(page: Int, profileId: ID, photosPerPage: Int): PhotoPagination!
profile(profileId: ID!): Profile!
profiles(page: Int, perPage: Int): ProfilePagination!
identifyFace(faceId: ID!): [IdentifyFaceResult]!
task(taskCollectionId: ID!): Task
... |
a=input("ENTER THE NUMBER\n")
if a[0]==a[1] or a[0]==a[2] or a[0]==a[3] or a[0]==a[4] or a[1]==a[2] or a[1]==a[3] or a[1]==a[4] or a[2]==a[3] or a[2]==a[4]:
print("THE ENTERED NUMBER IS NOT A UNIQUE NUMBER")
else:
print(a,"IS AN UNIQUE NUMBER")
|
#Realice un algoritmo que, con base en una calificacion proporcionada (0-10), indique con letra la calificacion que le corresponde: 10 es “A", 9 es “B", 8 es “C", 7 y 6 son “D", y de 5 a 0 son “F". Represente el diagrama de flujo, el pseudocédigo y el diagrama N/ S correspondiente.
def estCondicional01():
#Definir va... |
def isPrime(n: int)->bool:
"""
Give an Integer 'n'. Check if 'n' is Prime or Not
:param n:
:return: bool - True or False
A no. is prime if it is divisible only by 1 & itself.
1- is neither Prime nor Composite
- check for n being a even number i.e divisble by 2
- check for n being divi... |
c = int(input('Digite o cpf: '))
f = c // 100
num = f
digito = str(c % 100)
i = 2
soma = 0
resto = 0
while f > 0:
resto = f % 10
soma = soma + (resto * i)
f = f // 10
i = i + 1
dv = 11 - (soma % 11)
if dv == 10 or dv == 11:
dv = 0
# calculando o segundo dígito verificador
i = 3
soma = 0
resto = 0
wh... |
# The goal of this exercise is to get hands-on experience working with
# list comprehensions, and other comprehensions. Write a complementary
# function to each of the below, which accomplishes the same logic in
# a one-liner (using list/set/dict comprehensions).
# Exercise 1
# Adds 5 to each element
def add_five(nu... |
n = len(x)
if n % 2:
median_ = sorted(x)[round(0.5*(n-1))]
else:
x_ord, index = sorted(x), round(0.5 * n)
median_ = 0.5 * (x_ord[index-1] + x_ord[index])
median_ |
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2020-01-31 10:42
# @Author : Fabrice LI
# @File : 20200128_623_K_edit_distance.py
# @User : liyihao
# @Software : PyCharm
# @Description: todo
#Reference:**********************************************
"""
Given a set... |
'''
핵심: data.sort(key=(lambda x: (-x[1], x[2], -x[3], x[0])))
sort()의 key option func은
해당 list의 데이터 자체를 바꾸진 않는다.
(내부적으로 sorting할때 compare할때만 사용하는 듯.)
'''
N = int(input())
data = []
for _ in range(N):
line = input().split()
data.append((line[0], int(line[1]), int(line[2]), int(line[3])))
# debug
# print(N)
# ... |
def agreeanswer():
i01.disableRobotRandom(30)
i01.setHandSpeed("left", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 0.90)
i01.setTorsoSpeed(1.0, 1.0, 1.0)... |
# GENERAL TREE STRUCTURE SETUP
# Santiago Garcia Arango, July 2020
"""
The goal is to create a tree structure to organize better the information.
The final result should be able to create a tree and print it like this:
(from the "root", be able to go deep in a tree structure)
UNIVERITY (level 0)
|__MANAGEMENT (lev... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1node = l1
l2node = l2
prenode = None
r... |
"""
容器 - 总结
1. 种类与特点
字符串:存储字符编码值,不可变,序列
列表:存储变量,可变,序列
元组:存储变量,不可变,序列
字典:存储键值对,可变,散列
键:必须唯一且不可变数据(数字,bool,字符串,元组)
集合:存储键,可变,散列
2. 不可变与可变:
在内存中所有的数据都可以视为不可变数据,
为了开发更加方便,创建了可变数据.
可变:预留空间 + 自... |
def linear_search(arr, value):
"""
My Python implementation of linear search
Searches an array and returns either the index of the value (if found) or -1 (if not found)
Time complexity: O(n)
Space complexity: O(1)
"""
for i in range(len(arr)): # O(n)
if arr[i] == val... |
# Filename: route.py
"""
Transit Route Module
"""
# Standard libraries
class Route(object):
"""
A representation of a route. Every route has:
* name - string
* id - unique identification (string) for the route for the agency
* stops - list of stops relevant for the route
"""
def __init__... |
database_path = "{projects}/brewmaster/server/data/"
heater_port = 12
port_number = 5000
stirrer_port = 13
temp_sensor_path = "/sys/bus/w1/devices/{your_sensor_id}/w1_slave"
use_fake = True
|
# input
B = input()
# process
'''
XI는 IX로 바꾼다.
LX는 XL로 바꾼다.
VI는 IV로 바꾼다.
'''
if B[ :2] == "LX" and B[ :3] != "LXX":
B = B.replace("LX", "XL")
if B[len(B) - 2: ] == "XI":
B = B.replace("XI", "IX")
if B[ :2] == "LX" and B[ :3] != "LXX":
B = B.replace("LX", "XL")
units = None
for i in range(len(B)):
if B[i] == 'V' ... |
# def favcolors(mameet,qj,mustafa):
# print(mameet, qj,mustafa)
# favcolors(qj='green',mameet='black',mustafa='blue')
# # ,,
def favcolors(**kwargs):
print(kwargs)
for key,val in kwargs.items():
print('Favourite color of',key,'is',val)
# favcolors(qj='green',mameet='black',mustafa='blue',fatima='... |
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
# Formatting for date objects.
DATE_FORMAT = 'N j, Y'
# Formatting for time objects.
TIME_FORMAT = 'P'
# Formatti... |
ENTRY_POINT = 'minSubArraySum'
#[PROMPT]
def minSubArraySum(nums):
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums.
Example
minSubArraySum([2, 3, 4, 1, 2, 4]) == 1
minSubArraySum([-1, -2, -3]) == -6
"""
#[SOLUTION]
max_sum = 0
s = 0
f... |
# Listas são mutável.
print('{:=^50}'.format(' EXEMPLO 01 '))
num = [2, 5, 9, 1]
print(num)
print('{:=^50}'.format(' EXEMPLO 02 ')) # O num[2] irá substituir na posição 2 pelo valor 3.
num = [2, 5, 9, 1]
num[2] = 3
print(num)
print('{:=^50}'.format(' EXEMPLO 03 ')) # O .append() cria um novo elemento na lista
num = ... |
number_of_rooms = int(input())
free_chairs = 0
insufficiency = False
for i in range(1, number_of_rooms + 1):
list_of_chairs_and_people = input().split()
chairs = len(list_of_chairs_and_people[0])
needed_ones = int(list_of_chairs_and_people[1])
if chairs >= needed_ones:
free_chairs += cha... |
def funcion():
return 5
def generador():
yield 1,2,3,4,5,6,7,8,9
print(generador())
print(generador())
print(generador())
|
# vim: set ts=8 sts=4 sw=4 tw=99 et:
#
# This file is part of AMBuild.
#
# AMBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
class InternalCompilerError(Exception):
"""
An internal compiler error is unrecoverable and fatal.
It should never happen for any user input.
"""
def __init__(self, message=''):
self.message = message
pass
def __str__(self):
return self.message... |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.authentication
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Authentication(object):
"""Implementation of the 'Authentication' model.
TODO: type model description here.
Attri... |
"""
This is the PyTurbSim 'stress models' package.
For more information or to use this package import the stressModels.api
package, e.g.:
>>> import pyts.stressModels.api as rm
**Currently the stress package does not function properly, unless no coherence is used. Fixing this is near the top of the list of things t... |
class BusInPOZ:
def __init__(self, intersection, check_in_bus_info, check_in_phase, check_in_phasetime, check_in_time, last_check_in):
self.intersection_of_interest = intersection
self.bus_id = check_in_bus_info.idVeh
self.check_in_time = check_in_time
self.check_in_phase = chec... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the message... |
# -*- coding: utf-8 -*-
__version__ = '0.5.0.dev0'
PROJECT_NAME = "gx-tool-db"
PROJECT_OWNER = PROJECT_USERAME = "galaxyproject"
PROJECT_AUTHOR = 'Galaxy Project and Community'
PROJECT_EMAIL = 'jmchilton@gmail.com'
PROJECT_URL = "https://github.com/galaxyproject/gx-tool-db"
RAW_CONTENT_URL = "https://raw.github.com... |
"""
https://leetcode.com/problems/design-hashset/
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a ... |
#! Line breaks in 'print' function.
print(
"""1 line
2 line
3 line"""
)
print(
'1 line\n'
'2 line\n'
'3 line')
# Separator parameter.
print(
'1 line\n',
'2 line\n',
'3 line',
sep='______\n')
# End paramerer.
print('hello', 'kato', sep=' ', end="!")
|
class Vertex:
def __init__(self, x=None, y=None):
self.pos = [x, y]
self.x = x
self.y = y
self.data = None
def __str__(self):
return f"{self.pos}"
def __repr__(self):
return f"{self.pos}"
def __hash__(self):
return hash(''.join([str(x) for x... |
# 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 rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return max(self.dfs... |
#$Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/xmlBase/xmlBaseLib.py,v 1.4 2009/01/23 00:21:04 ecephas Exp $
def generate(env, **kw):
if not kw.get('depsOnly',0):
env.Tool('addLibrary', library = ['xmlBase'], package = 'xmlBase')
if env['PLATFORM']=='win32' and env.get('CONTAINERNAME','')... |
# Python program to print the first non-repeating character
NO_OF_CHARS = 256
# Returns an array of size 256 containg count
# of characters in the passed char array
def getCharCountArray(string):
count = [0] * NO_OF_CHARS
for i in string:
count[ord(i)] += 1
return count
# The function returns in... |
class Solution:
def reverse(self, x: int) -> int:
if x < 0 and x >= (-2**31):
# x_str = str(x)
# x_str_rev = '-'
# access from the 2nd last element excluding "-" sign
x_str_rev = '-' + str(x)[len(str(x)):0:-1]
if int(x_str_rev) < (-2**31):
... |
# Реализуйте функцию find_phone_by_name
# которая находит телефон в хеше по имени и возвращает номер телефона.
# Используйте hash[key] для поиска телефона.
phone_book = {
'Marcus Aurelius': '+380445554433',
'Antonius': '+38022222',
'Julius': '+38033333',
}
def find_phone_by_name(phones: dict, name: ... |
# This problem was asked by Palantir.
# Given a number represented by a list of digits, find the next greater permutation of a
# number, in terms of lexicographic ordering. If there is not greater permutation possible,
# return the permutation with the lowest value/ordering.
# For example, the list [1,2,3] should retur... |
def length_of_longest_substring(s):
dici = {}
max_s_rep = repeticao_na_fila = 0
for i, value in enumerate(s):
if value in dici:
num_repetidos = dici[value] + 1
if num_repetidos > repeticao_na_fila:
repeticao_na_fila = num_repetidos
num_repeticoes = i +... |
#!/usr/bin/python3
f = open("/home/bccue/Cores-SweRV/testbench/asm/hello_world.s", "r")
g = open("/home/bccue/Cores-SweRV/testbench/asm/hello_world_c.c", "w")
for data in f:
data = data.strip("\n")
if (data == "") or ("//" in data):
continue
#New text to print to terminal
if (".ascii" in data):
print("__as... |
player_one = []
player_two = []
board = {"a":"_","b":"_","c":"_",
"d":"_","e":"_","f":"_",
"g":"_","h":"_","i":"_"}
def register_players():
pone = input("Please write the name of player one: ")
ptwo = input("Please write the name of player two: ")
player_one.append(pone)
p... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
default_app_config = 'mosquitto.apps.Config'
|
#Loading one line from file and starting a dictionary
for line in open('rosalind_ini6.txt', 'r').readlines():
contents = line.split()
dictionary = dict()
#Checking if a word from line is in dictionary, then sum the occurrences
for i in range(0, len(contents), 1):
if (contents[i] not in dictionary):
... |
# Python file
# Save this with extension .py
# Made By Arnav Naik
# A beginner's guide to Python
print("Welcome To The Trivia!!")
# Scoring
total_q = 4
print("Total Questions: ", total_q)
def question_1():
global score
score = int(0)
# Question1
question1 = str(input("1. What's the bes... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def get_grade(self):
if self.score>100 or self.score<0:
raise ValueError("the score is wrong!")
if self.score < 60:
retu... |
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head: return None
cur = head
st... |
class Solution:
def toLowerCase(self, str: str) -> str:
res = []
for i in range(len(str)):
if 65 <= ord(str[i]) <= 92:
res.append(chr(ord(str[i]) + 32))
else:
res.append(str[i])
return "".join(res)
def toLowerCase2(self, str: str) ... |
class NotInitedException(Exception):
"""Deprecated! was used to state that the database in the general config was not inited yet"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class MissingUserException(Exception):
"""The requested User could not be found"""
... |
# --------------
# Code starts here
# Create the lists
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio' ]
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
# Concatenate both the strings
new_class = (class_1 + class_2)
print (new_class)
# Append the list
new_class.append('Peter... |
#!/usr/bin/env python3
# Created by Tiago Minuzzi, 2020.
# Files
in_fasta = "teste.fasta"
in_ids = "ids.txt"
out_fasta = "res_fas.fa"
# Empty dictionary to store sequences
fas_dict = {}
# Read reference fasta file
with open(in_fasta, "r") as fasta:
fasta=fasta.readlines()
for linha in fasta:
linha = linha.strip()
... |
# 두 배열의 원소 교체
n, k = map(int, input().split()) # N과 K를 입력받기
list_data1 = list(map(int, input().split())) # 배열 A의 모든 원소를 입력받기
list_data2 = list(map(int, input().split())) # 배열 B의 모든 원소를 입력받기
list_data1 = sorted(list_data1) # 배열 A는 오름차순 정렬 수행
list_data2 = sorted(list_data2, reverse=True) # 배열 B는 내림차순 정렬 수행
# 첫... |
#strings = """ We love our mom she helps us is in varius ways.
#She makes food for us.
#She takes us to school.
#She always takes care of us.
#""" #multiline strings
#print (strings)
sentence1 = 'Tamim is a great player'
sentence2 = "\"Bangldesh\" is a developing country"
print (sentence1)
print (sentence2)
length ... |
class State:
def __init__(self, goal, task, visual, ):
self.goal = None
self.task = None
self.visual = None
self.features = None |
for i in range(1, 10):
print(i, end=', ')
print()
for i in range(0, 10, 2):
print(i, ' ', end='')
print()
for i in range(10, 1, -2):
print(i, ' ', end='')
|
class BatchCancelled(Exception):
"""
Error used when a batch has been cancelled.
"""
pass
|
#!/usr/bin/env python
"""iexport.py: export the unallocated spaces."""
class Run:
"""Keeps track of a single run"""
def __init__(self,start,len):
self.start = start
self.len = len
self.end = start+len-1
def __str__(self):
return "Run<%d--%d> (len %d)" % (self.start,self.end... |
"""
Union find algorithm
"""
def get_parent(arr, i):
if arr[i] == i:
return i
arr[i] = get_parent(arr, arr[i])
return arr[i]
def union_parent(arr, a, b):
a = get_parent(arr, a)
b = get_parent(arr, b)
if a < b:
arr[b] = a
else:
arr[a] = b
def find_parent(arr, a, ... |
# Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko
# Copyright 2019-2020 Intel Corporation
#
# SPDX-License-Identifier: AGPL-3.0-or-later
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[0;33m'
FAIL = '\033[91m'
ENDC = '\033[0m'
CLRSCR = ... |
# Longest Increasing Subsequence
# We have discussed Overlapping Subproblems and Optimal Substructure properties.
# Let us discuss Longest Increasing Subsequence (LIS) problem as an example
# problem that can be solved using Dynamic Programming.
# The Longest Increasing Subsequence (LIS) problem is to find the length... |
##Ejercicio 2
# el siguiente codigo busca la raiz entera de un numero dado usando BS
# Busqueda Binaria
# Entrada:
# 16 (si se desea encontrar de un numero
# mayor 20 incrementar el tamanio del array)
# Salida:
# Does not exist
#or
# "The element was found " +48
#
# El ejercicio incluye el ordenamiento del arra... |
number = input("Type a number: ")
try:
number = float(number)
print("The number is: ", number)
except:
print("Invalid number") |
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger el... |
def show_banner(value: str, times: int):
print(value * times)
def validate_loan_eligibility(has_income: bool, credit_report: bool, payment_default: bool) -> str:
if(has_income and (credit_report and (not payment_default))):
return "Eligible for loan"
else:
return "Not Eligible for loan"
... |
#!/usr/bin/env python3
shifted_serial = '''
0000000000400d00 db 0x96 ; '.'
0000000000400d01 db 0x9e ; '.'
0000000000400d02 db 0x86 ; '.'
0000000000400d03 db 0xb0 ; '.'
0000000000400d04 db 0xb4 ; '.'
0000000000400d05 db 0x8c ; '.'
0000000000400d06 db 0x5a ;... |
class Node:
hostname = None
username = None
key_file = None
def __init__(self, hostname, username, key_file):
self.hostname = hostname
self.username = username
self.key_file = key_file
def __repr__(self):
return self.__str__()
def __str__(self):
return ... |
dia = input('Insira o dia em que você nasceu:')
mes = input('Insira o mês em que você nasceu:')
ano = input('Insira o ano em que você nasceu:')
print('Você nasceu no dia', dia, 'de', mes, ' no ano de ', ano)
|
#!/usr/bin/python
"""
Generate a line in the html table.
"""
def gen_records(in_data):
"""
Generate a sorted list of results to be output in an html table.
"""
rec_vec = []
factor = 0
for rec in in_data:
new_rec = {}
if factor == 0:
expon = 2 * len(in_data[rec][1]) ... |
def _print_error_message(error_message, default_message):
if error_message == "default":
print(default_message)
elif error_message:
print(error_message)
def _filter_inputs_by_min(inputs_int, min_val, error_message="default"):
default_message = "Input value should be bigger\
than or eq... |
def sub(s):
# print(s)
a = list(map(int, s.split('-')))
print(a)
return a[0]*2 - sum(a)
def main():
s = input()
add = s.split('+')
print(add)
print(sum(map(sub, add)))
if __name__ == "__main__":
print(main()) |
""" The layer module contains a Layer class to help when working with layers."""
class Layer(object):
def __init__(self, definition):
# Name -- Required
try:
self.name = definition['name']
except KeyError:
raise KeyError('The "name" key is required for the ... |
# File system, where one can create and edit files protected with Login system. You can call it Personal Diary.
def menu():
print("***Menu***")
inp = input("Welcome user... \nWant to Login(lgn) or Register(reg) (lgn/reg)? ")
if inp == 'lgn':
loginAcct()
elif inp == 'reg':
regA... |
m3 = range(0,1000,3)
m5 = range(0,1000,5)
m15 = range(0,1000,15)
answer = sum(m3)+sum(m5)-sum(m15)
print (answer)
|
#!/usr/bin/env python
class Solution(object):
def numDistinct(self, s, t):
"""
Counts the number of distinct subequences of t in s.
"""
n = len(s)
m = len(t)
if n == 0 or m == 0:
return 0
#
# Setup the DP. Each entry dp[i][j] represents ... |
__all__=["layer",
"fflayers",
"convnet"
"model",
"optimize"
"cost",
"train",
"util",
"nnfuns",
"dataset"] |
test = {
'name': 'Problem EC1',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> key_distance_diff("wird", "word", 4)
0.6834861261734088
>>> key_distance_diff("aird", "word", 4)
1.650081475501692
>>> key_distance_diff("bord", "w... |
[
[
0.20155604,
0.13307383,
0.12784087,
float("NaN"),
0.06557849,
0.07970277,
float("NaN"),
0.05212981,
],
[
0.24451376,
0.14168013,
0.12661545,
float("NaN"),
0.10445491,
0.10288933,
float... |
def compares_expressions(exp1, exp2) -> bool:
def compile_exp(exp):
return exp.compile(compile_kwargs={"literal_binds": True})
return str(compile_exp(exp1)) == str(compile_exp(exp2))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isMirror(self,t1,t2):
if not t1 and not t2:
return True
elif not t1 or not... |
def reverse(self):
"""Reverse the begin and end point of the Line
Parameters
----------
self : Segment
An Segment object
Returns
-------
"""
end = self.end
self.end = self.begin
self.begin = end
|
#!/usr/bin/python
""" run under recipient user's account """
""" if exists .forward send new mail """
""" else deliver to mbox/Maildir """
|
"""
In Python 2, search path is F, A, X, Y, B.
With Python 3, search path should be : F, A, X, Y, B, Y, X and after removing « bad heads » : F, A, B, Y, X.
"""
class X():
def who_am_i(self):
print("I am a X")
class Y():
def who_am_i(self):
print("I am a Y")
class A(Y, X):
def who_am_i... |
#Desafio: Crie um script que leia o dia, o mês e ano de nascimento de uma pessoa e mostre uma mensagem com data formatada.
dia = input('Qual é o dia do deu nascimento?')
mes = input('Qual é o mês do deu nascimento?')
ano = input('Qual é o ano do deu nascimento?')
print('Você nasceu no dia', dia, 'de', mes, 'de', ... |
""" Defines various physical units for use within narwhal """
# For now, units are simply defined as constants, allowing them to serve as
# hashes
meter = "meter"
kilometer = "kilometer"
decibar = "decibar"
second = "second"
degree_celsius = "degree_celsius"
psu = "psu"
# compound units
meter_per_second = "meter_per... |
class BaseParagraphElement(object):
def __init__(self, element: dict, document):
self._element = element
self._document = document
@property
def start_index(self) -> int:
return self._element.get("startIndex")
@property
def end_index(self) -> int:
return self._eleme... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 10:15:43 2019
@author: Training23
"""
def createdic(n):
n=dict(n)
return n
def acessdic(n):
c={2:2,3:2,1:2}
return c[n]
def update(n,m):
c={2:2,3:2,1:2}
c[n]=m
return c
def delete():
... |
#Bottle deposits
x = float(input('Enter the number of containers holding 1 litre or less: '))
y = float(input('Enter the number of containers holding more than 1 litre: '))
refund = float((x*.10)+(y*.25))
print('The refund received will be $',refund) |
__SEPARATOR = '/'
__LAYER_TEMPLATE = '...../...../..?../...../.....'
__INNER_BORDER = set([(1,2), (3,2), (2,1), (2,3)])
def calculateBiodiversityRating(layout):
layoutString = layout.replace(__SEPARATOR, '')
biodiveristyRating = 0
for i in range(0, len(layoutString)):
if layoutString[i] == '#':
... |
{
"targets": [
{
"target_name": "aacencoder",
"sources": [ "aacencoder.cc" ],
"include_dirs": [
],
"libraries": [
"-lfaac"
]
}
]
}
|
def main():
my_tuple = (4, 4, 3, 2, 5, 7, 8, 8, 8, 7)
evens = tuple([ item for item in my_tuple if item & 1 == 0 ])
odds = tuple([ item for item in my_tuple if item & 1 == 1 ])
print("Evens :", evens);
print("Odds :", odds);
if __name__ == '__main__':
main()
|
"""Should raise SyntaxError: can't use starred expression here"""
*a
|
# http://codeforces.com/problemset/problem/263/A
matrix = [list(map(int, input().split())) for i in range(5)]
# x = [x for x in matrix if 1 in x][0]
# print(x.index(1))
row_counter = 0
for i in range(5):
if sum(matrix[i]) > 0:
break
row_counter += 1
col_counter = 0
for i in range(5):
if matrix[r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.