content stringlengths 7 1.05M |
|---|
# leer e iterar sobre un archivo. Uso mas comun
def read():
f = open('myText.txt', mode='rt', encoding='utf-8')
for i in f:
print(i)
f.close()
# modo escritura. Saca error al no ser de lectura
def writeNotRead():
f = open('myText.txt', mode='wt', encoding='utf-8')
for i in f:
pr... |
APP_NAME = "dotpyle"
DOTPYLE_CONFIG_FILE_NAME = "dotpyle.yml"
DOTPYLE_LOCAL_CONFIG_FILE_NAME = "dotpyle.local.yml"
DOTFILES_FOLDER = "dotfiles"
SCRIPTS_FOLDER = "scripts"
DOTPYLE_CONFIG_FILE_NAME_TEMP = "dotpyle.temp.yml"
README_NAME = "README.md"
README_TEMPLATE_PATH = "dotpyle/templates/readme.md"
CONFIG_TEMPLATE_PAT... |
#!/usr/bin/python3
def print_list_integer(my_list=[]):
"prints all integers of a list"
for i in range(len(my_list)):
print("{:d}".format(my_list[i]))
|
"""
Given the head of a singly linked list,
return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
- Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
- Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
E... |
HOST = 'http://kevin:8000'
VERSION = 'v2'
API_URL = "{host}/{version}".format(host=HOST, version=VERSION)
API_TOKEN = None # set by wiredrive.auth.set_token()
SSL_VERIFY = True
# Any requests for more resources than the limit will be clamped down to it.
MAX_PAGINATION_LIMIT = 500
RFC3339_FORMAT = "%Y-%m-%dT%H:%M:%SZ... |
class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
m, n = q, p
while m % 2 == 0 and n % 2 == 0:
m, n = m / 2, n / 2
if n % 2 == 0 and m % 2 == 1: # receive at left side if n is even
return 2
# receive at right side: 0, or 1
if n % 2 ==... |
NAMES = {
'lane': 'Test1',
'lb': None,
'pu': 'Test1',
'sample': 'Test1',
'rg': 'Test1',
'pl': 'illumina'
}
DATA = {
'files': [
'/bcbio-nextgen/tests/test_automated_output/trimmed/1_1_Test1.trimmed.fq.gz',
'/bcbio-nextgen/tests/test_automated_output/trimmed/1_2_Test1.trimmed.... |
#zamjena vrijednosti dvije promjeljive
a = 5; b = 8
print(a, b)
a, b = b, a
print(a, b)
|
#W.A.P TO PRINT PATTERNS USING NESTED FOR
t=65
for i in range(0,4,1):
for j in range(0,i+1,1):
ch=chr(t)
print(ch,end='')
t = t + 1
print()
t=0
n=0
for i in range(0,5,1):
t=n
for j in range(0,i+1,1):
print(t,end='')
t=t+1
print()
t =0
for i in range(0, 5, 1)... |
"""
Exception classes for pyinstaller-versionfile.
"""
class InputError(Exception):
"""
The given metadata input file is not as expected.
"""
class UsageError(Exception):
"""
Exception for all cases where the end user is giving wrong inputs to the program.
"""
class ValidationError(Exceptio... |
"""
PASSENGERS
"""
numPassengers = 2740
passenger_arriving = (
(2, 5, 2, 2, 1, 0, 12, 12, 4, 3, 0, 0), # 0
(6, 3, 3, 2, 2, 0, 3, 8, 3, 5, 1, 0), # 1
(4, 6, 8, 1, 1, 0, 3, 8, 3, 4, 1, 0), # 2
(6, 5, 3, 4, 4, 0, 6, 2, 5, 1, 0, 0), # 3
(2, 2, 5, 5, 1, 0, 6, 6, 4, 5, 1, 0), # 4
(5, 8, 4, 5, 2, 0, 7, 9, 8, 3, ... |
#!/usr/bin/env python
def pin_iteration(fmt):
"""Iterate over the pinmap, yielding fmt formatted with idx, bank and pin."""
for i, (bank, pin) in enumerate(pinmap):
yield fmt.format(idx=i, bank=bank, pin=pin)
def strip(line):
"""Strip the identation of a line for the comment header."""
... |
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print(f"i can't wait to see your next trick, {magician.title()}", end="\n\n")
print("Thank you, everyone. That was a great magic show!")
'''
o nome da lista deve vir no plural
assim facili... |
list_x = [1,0,1,0,0,1]
list_u = ['a','B','c','F','e']
# filter函数返回结果代表真/假,True/False
r = filter(lambda x:True if x==1 else False,list_x)
r1 = filter(lambda x:x >= 'A' and x <= 'Z',list_u)
print(list(r))
print(list(r1)) |
# TALON: Techonology-Agnostic Long Read Analysis Pipeline
# Author: Dana Wyman
# -----------------------------------------------------------------------------
# Queries for working with exon and transcript lengths
def get_all_exon_lengths(cursor, build):
""" Compute all exon lengths and store in a dict """
ex... |
''' Estes são os exercícios sugeridos durante as aulas do curso de Introdução a Algoritmos do prof. Gustavo Guanabara. Este curso pode ser encontrado no seguinte endereço: https://www.cursoemvideo.com/course/curso-de-algoritmo/
Aula 7 - Estruturas Condicionais 1
Exercício 01: Está apto a dirigir? '''
print("--------... |
"""
This is a program written in python for finding GCD of two numbers.
This solution uses recursive approach as implementation.
Recursive approach means a fuction calling itself for which a base condition is given so that the program knows where to terminate.
"""
#definition of functions to find GCD of 2 numbers.
de... |
# -*- coding: utf-8 -*-
'''
File name: code\exploring_pascals_triangle\sol_148.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #148 :: Exploring Pascal's triangle
#
# For more information see:
# https://projecteuler.net/problem=148
# Pro... |
obj_path_map = {
"long_sofa": "04256520/68fce005fd18b5af598a453fd9fbd988",
"l_sofa": "04256520/575876c91251e1923d6e282938a47f9e",
"conic_bin": "02747177/cf158e768a6c9c8a17cab8b41d766398",
"square_prism_bin": "02747177/9fe4d78e7d4085c2f1b010366bb60ce8",
"faucet": "03325088/1f223cac61e3679ef235ab3c41a... |
# test the pyncparser package
# copy some data in here as str,
# and try to parse it
text = """<SUBMISSION>
<PAPER>
<ACCESSION-NUMBER>9999999997-22-000253
<TYPE>19B-4E
<PUBLIC-DOCUMENT-COUNT>1
<FILING-DATE>20220128
<EFFECTIVENESS-DATE>20220128
<FILER>
<COMPANY-DATA>
<CONFORMED-NAME>Cboe EDGA Exchange, Inc.
<CIK>000147... |
"""
==== KEY POINTS ====
- Given two non-empty arrays of integers, write a function that determines
whether the second array is a subsequence of the first one.
- [1, 3, 4] form a subsequence of the array [1, 2, 3, 4]
"""
"""
- Time Complexity: O(n)
- Space Complexity: O(1)
"""
def is_valid_subsequence1(array, seque... |
#
# PySNMP MIB module CXPCM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXPCM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:17:42 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... |
N = int(input())
H = list(map(int, input().split()))
answer = moved = 0
before_h = H[0]
for h in H[1:]:
if h > before_h:
moved = 0
else:
moved += 1
answer = max(answer, moved)
before_h = h
print(answer) |
def get_BMBC(pattern):
# 预生成坏字符表
BMBC = dict()
for i in range(len(pattern) - 1):
char = pattern[i]
# 记录坏字符最右位置(不包括模式串最右侧字符)
BMBC[char] = i + 1
return BMBC
def get_BMGS(pattern):
# 预生成好后缀表
BMGS = dict()
# 无后缀仅根据坏字移位符规则
BMGS[''] = 0
for i in range(len(patter... |
# Example distribution config used in tests in both test_cloudfront.py
# as well as test_cloudfront_distributions.py.
def example_distribution_config(ref):
"""Return a basic example distribution config for use in tests."""
return {
"CallerReference": ref,
"Origins": {
"Quantity": 1... |
def generate_matrix(size):
matrix = []
for i in range(size):
matrix.append([None] * size)
return matrix
def create_list_of_lines(matrix):
lines = []
#adding horizontal lines
for hor_line in matrix:
lines.append(hor_line)
#adding vertical lines
for i in range(len(matrix)... |
consumer_key = "mXzLJ779Al4UPyg3OJr1NzXdg"
consumer_secret = "yxQYDNvUs0JNEtEasA9CN4bEweImDIrISQit6eNWEmuCGP008G"
access_token = "1431634234783981568-WllRiFW0dQW7PjM2eBqYMIsfpqoJc8"
access_token_secret = "HahcSPryVc553SYEV6tOKPJkK2TcS2RX75jK3oOVNjRY1"
trigger = ""
timezone = 2 #change this into your timezone. for examp... |
def getKeys(os):
try:
dotenv = '.env.ini'
with open(dotenv, 'r') as file:
content = file.readlines()
content = [line.strip().split('=') for line in content if '=' in line]
env_vars = dict(content)
if file:
file.close()
return env_vars
exc... |
# 爬楼梯
class Solution:
# 递归
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
# 递归+备忘录
def climbStairs2(self, n: int) -> int:
def helper(x: int) -> int:
if x <= 2:
return ... |
{
"targets": [
{
"target_name": "tester",
"sources": [ "tester.cc", "tester.js" ]
}
]
} |
CONTROL_TOKEN = [int('1101010100', 2), # 00
int('0010101011', 2), # 01
int('0101010100', 2), # 10
int('1010101011', 2)] # 11
|
class CStaticConsts:
# Product dictionary indexes
title = 'title'
currencyType = 'currencyId'
itemPrice = 'itemPrice'
productUrl = 'productUrl'
currencyUSD = 'USD'
siteName = 'siteName'
# Supported sites
Ebay = 'Ebay'
Walmart = 'Walmart'
Amazon = 'Amazon'
|
# Strings taken from https://github.com/b1naryth1ef.
__all__ = (
'BOT_BROKEN_MSG',
'COUNCIL_QUEUE_MSG_NOT_FOUND',
'BAD_SUGGESTION_MSG',
'SUGGESTION_RECEIVED',
'SUGGESTION_APPROVED',
'SUGGESTION_DENIED',
'SUGGESTION_TOO_LARGE',
'UPLOADED_EMOJI_NOT_FOUND',
'SUBMITTER_NOT_FOUND'
)
COU... |
class SenalDiscreta:
# Constructor
# Si no se envian argumentos, se asignan los valores por defecto:
# (Solo un dato = 0, indice de inicio = 0, tipo de senial = finita = no periodica)
def __init__(self, datos = [0], indice_inicio = 0, periodica = False):
self.datos = datos
self.indice... |
TEXT = b"""
Overhead the albatross hangs motionless upon the air
And deep beneath the rolling waves in labyrinths of coral caves
The echo of a distant tide
Comes willowing across the sand
And everything is green and submarine
And no one showed us to the land
And no one knows the wheres or whys
But something stirs and ... |
class Solution:
def kthGrammar(self, N: int, K: int) -> int:
K -= 1
count = 0
while K:
count += 1
K &= K - 1
return count & 1
|
class scheduleElem():
def __init__(self, _tr, _op, _res):
self.tr = _tr
self.op = _op
self.res = _res
def __repr__(self):
return "{}{}({})".format(self.op, self.tr, self.res)
def getElem(strelem):
strtr = ''
op = ''
for i in strelem[0:strelem.find('(')]:
... |
"""a module housing logic to identify points when curves first cross a certain value
"""
__author__ = "Reed Essick (reed.essick@gmail.com)"
#-------------------------------------------------
def _data2crossing(d, ref):
'''returns the indecies of the 1D array 'data' that braket the first time it crosses ref'''
... |
def R(pcset):
"""Returns retrograde of pcset."""
return [pcset[x] for x in range(len(pcset)-1, -1, -1)]
def I(pcset):
"""Returns inversion of pcset."""
return [(12-x)%12 for x in pcset]
def RI(pcset):
"""Returns retrograde inversion of pcset."""
return I(R(pcset))
def M5(pcset):
return [(... |
def foo(*, a, b):
print(a)
print(b)
def bar():
fo<caret>o(a = 1, b = 2)
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def ... |
def max_sum_subarray(nums):
if not nums: return nums
max_sum = nums[0]
cur_sum = 0
for i in range(len(nums)):
cur_sum = max( cur_sum + nums[i], nums[i] )
max_sum = max( cur_sum, max_sum )
return max_sum
|
a = float( input(' Qual a altura da parede em metros?'))
c = float ( input(' Qual a largura da parede em metros?'))
mq = a * c
t = mq / 2
print (' Sua parede tem a dimensão de {} x {} e a área de {}m2'.format(a, c,mq))
print (' Será necessário {}litros de tinta.'.format(t))
'''Faça um programa que leia a largura e a a... |
# Project: Perle Chic
# The project is a production and sales price calculator,
# developed for an entrepreneur who owns a beads accessory store.
# Status: In progress (Beta Version)
preco_cm1 = 0.0025 # Preço centímetro do silicone
preco_cm2 = 0.00068 # Preço centímetro do nylon
mdo1 = 3.75 # Preço mão de... |
x=9
y=3 #integers
#arithmetic operators
print(x+y) #addition
print(x-y) #subtraction
print(x*y) #multiplication
print(x/y) #division
print(x%y) #modulus
print(x**y) #exponentiation
x=9.1918123
print(x//y) #floor division
#Assignment operators
x=9 #sets x to equal 9
x+=3 #x=x+3
print(x)
x=9
x-=3 #x=x-3
pri... |
# B2061-整数的个数
k = int(input())
num_1 = 0
num_5 = 0
num_10 = 0
num_list = list(map(int, input().split()))
for i in range(0, k):
if num_list[i] == 1:
num_1 += 1
elif num_list[i] == 5:
num_5 += 1
elif num_list[i] == 10:
num_10 += 1
print(num_1)
print(num_5)
print(num_10) |
class NoHostError(Exception):
pass
class NoHeartbeatError(Exception):
pass
class NoSudoError(Exception):
pass
class ServiceShutdown(Exception):
pass
|
'''
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
'''
class ListNode(object):
def __init__(self, x):
self.data=x
self.next=None
class Solution(object):
def Merge(self, pHead1, pHead2):
if pHead1==None and pHead2==None:
return None
elif pHead1==None:
return pHead2
elif pHead2==None:
return pHe... |
# !/usr/bin/python
def p_decorator(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
def strong_decorator(func):
def func_wrapper(name):
return "<strong>{0}</strong>".format(func(name))
return func_wrapper
def div_decorator(func):
def f... |
#
# PySNMP MIB module FOUNDRY-SN-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FOUNDRY-SN-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:15:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
n = int(input())
b = list(map(int, input().rstrip().split()))
count = 0
total = 0
l = len(b)-1
for i in b:
try:
if i%2 != 0:
b[count] += 1
b[count + 1] += 1
total += 1
except:
break
count += 1
if count == l:
break
if b[-1]%2 == 0:
pr... |
#
# PySNMP MIB module PAIRGAIN-DSLAM-ALARM-SEVERITY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PAIRGAIN-DSLAM-ALARM-SEVERITY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:27:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... |
def if_mkl_open_source_only(if_true, if_false = []):
"""Returns `if_true` if OneDNN v0.x is used.
Shorthand for select()'ing on whether we're building with
OneDNN v0.x open source library only, without depending on OneDNN binary form.
Returns a select statement which evaluates to if_true if we're buil... |
FORBIDDEN_TITLE_PUNCTUATION = [
"'",
",",
'"',
'?',
'/'
'\\',
'`',
'|',
'&'
]
class Query:
title = ''
from_service = ''
artist = ''
media_type = ''
def __init__(self, title, service = '', artist='', media_type=''):
if not (isinstance(title, str)
and isinstance(artist, str... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 13:48:21 2020
@author: zuoxichen
"""
def get_array_numbers(integer):
'''
Parameters
----------
int1 : integer
int.
Returns
-------
a set that contains all the number in a part.
'''
a=integer//3
... |
"""
04: Scheduling Launch Plans
---------------------------
"""
|
"""426 · Restore IP Addresses"""
class Solution:
"""
@param s: the IP string
@return: All possible valid IP addresses
"""
def restoreIpAddresses(self, s):
# write your code here
res = []
self.dfs(s, 0, "", res)
return res
def dfs(self, s, cnt, path, res):
... |
class Solution(object):
def numberOfArithmeticSlices(self, A):
"""
:type A: List[int]
:rtype: int
"""
if len(A) < 3:
return 0
dp = [0] * len(A)
if A[2] - A[1] == A[1] - A[0]:
dp[2] = 1
res = dp[2]
for i in range(3, len(A... |
# This python script is called on build via ModBundlesItems.json configuration
def OnPreBuild(**kwargs) -> None:
print("OnPreBuildItem.py called ...")
bundleItem = kwargs.get("_bundleItem")
info = kwargs.get("info")
assert bundleItem != None, "_bundleItem kwargs not found"
assert info != None, "i... |
# # Copyright 2016 Google Inc. All Rights Reserved.
# #
# # Licensed under the Apache License, Version 2.0 (the "License");
# # you may not use this file except in compliance with the License.
# # You may obtain a copy of the License at
# #
# # http://www.apache.org/licenses/LICENSE-2.0
# #
# # Unless required by a... |
#!/usr/bin/python3
class NetworkConfig(object):
def __init__(self, public_cidr, vpc, public_subnets, private_subnets, nat, jump, keypair, cd_service_role_arn,
public_hosted_zone_name, private_hosted_zone_id, private_hosted_zone_domain, nat_highly_available,
nat_gateways, sns_topi... |
# Copyright (C) 2019 Nan Wu, Jason Phang, Jungkyu Park, Yiqiu Shen, Zhe Huang, Masha Zorin,
# Stanisław Jastrzębski, Thibault Févry, Joe Katsnelson, Eric Kim, Stacey Wolfson, Ujas Parikh,
# Sushma Gaddam, Leng Leng Young Lin, Kara Ho, Joshua D. Weinstein, Beatriu Reig, Yiming Gao,
# Hildegard Toth, Kristine Py... |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Stocks.py",
"provenance": [],
"authorship_tag": "ABX9TyN2tEWSWwhJDRg3YG0iUDln",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": ... |
"""
Programa 008
Área de estudos.
data 15.11.2020 (Indefinida) Hs
@Autor: Abraão A. Silva
"""
# Capitação dos dados do usuário.
ganho_hora = float(input('Valor da hora trabalhada.: '))
horas_mes = int(input('Quantas horas trabalhadas(mês).: '))
# Calculo do salário base.
ganho_mensal = (horas_mes * ganho_hora)
#... |
HF_TOKENIZER_NEWS_CLASSIFIER = "mrm8488/bert-mini-finetuned-age_news-classification"
HF_MODEL_NEWS_CLASSIFIER = "mrm8488/bert-mini-finetuned-age_news-classification"
SUBREDDITS = "wallstreetbets+investing+options+pennystocks+options+stocks"
NEWS_SUBREDDITS = "news"
NUM_SUBMISSION_TO_GET = 10
NEWS_CLASSES = ["world",... |
def cria_matriz(num_linhas,num_colunas,valor):
''' (int, int, valor) -> Cria uma matriz (lista de listas)
num_linhas -> Vai armazenar um valor inteiro (int) com o número de linhas
num_colunas -> Vai armazenar um valor inteiro (int) com o número de colunas '''
matriz = [] # Lista Vazia
for i in rang... |
def getBASIC():
list = []
n = input()
while True:
line = n
if n.endswith('END'):
list.append(line)
return list
else:
list.append(line)
newN = input()
n = newN
def findLine(prog, T):
for i in range(0, len(prog)):
... |
# Created By Rabia Alhaffar In 15/February/2020
# A Script To Run From native_01.js And native_01.bat
print("Hello World")
input()
|
'''
Question:
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
'''
result_list = []
for i in range(2000,3201): # here the end is incremente... |
"""
613. High Five
O(nlogn) for sorting. then iterate through the array once. so o(n)
overall o(nlogn)
"""
'''
Definition for a Record
class Record:
def __init__(self, id, score):
self.id = id
self.score = score
'''
class Solution:
# @param {Record[]} results a list of <student_id, score>
#... |
MQTT_HOST = "mqtt-server"
MQTT_PORT = 1234
MQTT_USER = "mqtt-user"
MQTT_PASS = "mqtt-password"
MQTT_TOPIC = "frogbot"
|
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def treeToDoublyList(self, root: "Node") -> "Node":
def recur(root):
nonlocal last, first
if r... |
"""
Black \e[0;30m
Blue \e[0;34m
Green \e[0;32m
Cyan \e[0;36m
Red \e[0;31m
Purple \e[0;35m
Brown \e[0;33m
Gray \e[0;37m
Dark Gray \e[1;30m
Light Blue \e[1;34m
Light Green \e[1;32m
Light Cyan \e[1;36m
Ligh... |
# Here's a class Lightbulb. It has only one attribute that
# represents its state: whether it's on or off.
# Create a method change_state that changes the state of the
# lightbulb. In other words, the methods turns the light on or
# off depending on its current state. The method doesn't take any
# arguments and prin... |
clothes = [int(i) for i in input().split()] # List of clothes' values
rack_capacity = int(input()) # The maximum capacity of one rack
racks = 1
sum_clothes = 0
while clothes:
value = clothes.pop()
sum_clothes += value
if sum_clothes > rack_capacity:
sum_clothes = value
... |
# -*- coding: utf-8 -*-
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
tuple1 = ("abc", 34, True, 40, "male")
print(tuple1)
|
# Title : Find the percentage of odd/even elements
# Author : Kiran raj R.
# Date : 15:10:2020
list1 = [1, 2, 4, 0, 0, 8, 3, 5, 2, 3, 1, 34, 42]
def print_percentage(list_in):
count_odd = 0
count_even = 0
count_0 = 0
length = len(list1)
for elem in list_in:
if elem == 0:
... |
a = 5
print(type(a))
b = 5.5
print(type(b))
print(a+b)
print((a+b) * 2)
print(2+2+4-2/3) |
# Copyright 2011 Jamie Norrish (jamie@artefact.org.nz)
#
# 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... |
"""
Init file to follow PyPI requirements.
"""
print("Hello, World!")
|
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def getSuit(self):
return self.suit
def getValue(self):
return self.value
def __repr__(self):
return str(self.suit) + ", " + str(self.value)
def __str__(self):
return ... |
class Toy:
def __init__(self, newdescr: str, newlovable: float):
self.__description = newdescr
self.__lovable = newlovable
def getDescription(self) -> str:
return self.__description
def getLovable(self) -> float:
return self.__lovable
def setDescription(self, newdescr:... |
# Author: Ashish Jangra from Teenage Coder
num = 10
print("*")
for i in range(1, num):
print("*"+ " "*i +"*")
for i in range(num-2, 0, -1):
print("*"+ " "*i +"*")
print("*") |
#Translate account group IDS
def translate_acc_grp_ids(grp_id, dest_acc_grps, src_acc_grps):
if grp_id in [a_id['id'] for a_id in src_acc_grps]:
src_group = [grp for grp in src_acc_grps if grp['id'] == grp_id][0]
if src_group['name'] in [a_id['name'] for a_id in dest_acc_grps]:
dst_group... |
class Tile:
"""
Intersections keeps track of a set of tuples that are the keys
to the intersection dictionary
Edges keeps track of a set of unique ids that are the keys
to the edges dictionary
adjacent_tile returns whether a given tile is adjacent to the current tile
"""
def __init__... |
# -- coding:utf-8--
names = ['dzj','ljx','wwb','gyj','zke']
new_names = []
ls_names = names[:]
#while hi 意思是使用pop()函数删除列表中的值
#并且判断hi列表中是否有剩余的值
def name(hi):
while hi:
new_name = 'wow ' + hi.pop()
print(new_name)
new_names.append(new_name)
name(ls_names)
print(new_names)
print(names) |
class Solution:
# @param {int} n an integer
# @return {boolean} true if this is a happy number or false
def isHappy(self, n):
# Write your code here
sum = n
nums = {}
while sum != 1:
sum = self.cal_square_sum(sum)
if sum in nums:
return... |
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
if not nums:
return -1
left, right = 1, len(nums)
while left + 1 < right:
mid = (left + right) // 2
count = 0
for num in nums:
if num <= mid:
... |
A = [3,2,6,8,4,5,7,1]
for j in range(1,len(A)):
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i+1] = A[i]
i = i - 1
A[i + 1] = key
print(A) |
class Solution:
def longestLine(self, M: List[List[int]]) -> int:
if len(M) == 0:
return 0
rows, cols = len(M), len(M[0])
max_len = 0
@lru_cache(maxsize=None)
def dfs(row, col, direction):
subpath = 0
# directions: left, up, upleft, uprig... |
class Bcolors:
WHITE = "\033[97m"
CYAN = "\033[96m"
MAGENTA = "\033[95m"
BLUE = "\033[94m"
YELLOW = "\033[93m"
GREEN = "\033[92m"
RED = "\033[91m"
GREY = "\033[90m"
SOFTWHITE = "\033[37m"
SOFTCYAN = "\033[36m"
SOFTMAGENTA = "\033[35m"
SOFTBLUE = "\033[34m"
SOFTYELLOW ... |
# https://leetcode.com/problems/binary-tree-maximum-path-sum/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
# Time O(n) | Space O(log(n)... |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
seen = {}
for num in nums:
if num in seen:
del seen[num]
else:
seen[num] = False
for key in... |
MAX = 100
sum_even = 0
sum_odd = 0
for i in range(1, MAX+1):
if i % 2 == 0: sum_even += i
else: sum_odd += i
print(f'Suma parzystych {sum_even}\nSuma nieparzystych {sum_odd}')
|
def precision(y_true, y_pred, average='micro'):
true_entities = set([item for sublist in y_true for item in sublist])
pred_entities = set([item for sublist in y_pred for item in sublist])
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
score = nb_correct / nb_pr... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Simple Fun #6: Is Infinite Process?
#Problem level: 7 kyu
def is_infinite_process(a, b):
if b<a: return True
if (b-a)%2==1: return True
return False
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
else:
max_profit = 0
for i, v in enumerate(prices[:-1]):
if prices[i + 1] - prices[i] > 0:
... |
class RGBColor(object):
def __init__(self, red, green=None, blue=None):
self.red = red
self.green = green if green is not None else red
self.blue = blue if blue is not None else red
def __repr__(self):
return "#{:02x}{:02x}{:02x}".format(self.red, self.green, self.blue)
def... |
# magicians = ['alica', 'david', 'carolina']
# for magicians in magicians:
# print (magicians)
# print (magicians.title() + ", the was a great trick! " )
# print ( "I can't wait to see you next trick, " + magicians.title() + ". \n")
# print ("Thank you everyone, that was a great magic show!")
for valu... |
class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
cur = [0]*8
firstDay = []
count = 0
while N>0:
for i in range(1,7):
if cells[i-1] == cells[i+1]:
cur[i] = 1
else:
cur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.