content stringlengths 7 1.05M |
|---|
"""
link: https://leetcode.com/problems/subarray-sum-equals-k
problem: 求数组中是否存在子串满足其和为给定数字,求满足条件子串数。
solution: 记录前缀和。
"""
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
s, cur, res = {0: 1}, 0, 0
for x in nums:
if cur + x - k in s:
res += s[cur... |
print('\n==== MAIOR/MENOR ====')
num1 = float(input('Digite o primeiro número:'))
num2 = float(input('Digite o segundo número:'))
num3 = float(input('Dugite o terceiro número:'))
maior = num1
if num2 > num1 and num2 > num3:
maior = num2
if num3 > num1 and num3 > num2:
maior = num3
menor = num1
if num2 < num1 an... |
#-------------------------------------------------------------
# Name: Michael Dinh
# Date: 10/10/2018
# Reference: Pg. 169, Problem #6
# Title: Book Club Points
# Inputs: User inputs number of books bought from a store
# Processes: Determines point value based on number of books bought
# Outputs: Number of points user... |
def arraypermute(collection, key):
return [ str(i) + str(j) for i in collection for j in key ]
class FilterModule(object):
def filters(self):
return {
'arraypermute': arraypermute
} |
#
# PySNMP MIB module SNIA-SML-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNIA-SML-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:04 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,... |
'''
Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela.
'''
# Fazer um dicionario para aluno
aluno = dict()
# Pedir nome e média do aluno
aluno['nome'] = str(input('Nome: '))
aluno['média'] = float(input(f'Média de {alu... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i in range(len(nums)):
if dic.get(target - nums[i]) is not None:
return [dic[target - nums[i]], i]
dic[nums[i]] = i
|
"""
LeetCode #561:
https://leetcode.com/problems/array-partition-i/description/
"""
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2])
|
#!/usr/bin/env python3
ARP = [
{'mac_addr': '0062.ec29.70fe', 'ip_addr': '10.220.88.1', 'interface': 'gi0/0/0'},
{'mac_addr': 'c89c.1dea.0eb6', 'ip_addr': '10.220.88.20', 'interface': 'gi0/0/0'},
{'mac_addr': 'a093.5141.b780', 'ip_addr': '10.220.88.22', 'interface': 'gi0/0/0'},
{'mac_addr': '0001.00ff.0001', 'ip_addr... |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, "Script/FocusSlide.js", "southidc")
whatweb.recog_from_content(pluginname, "southidc")
whatweb.recog_from_file(pluginname,"Script/Html.js", "southidc")
|
'''
width search
Explore all of the neighbors nodes at the present depth '''
three_d_array = [[[i for k in range(4)] for j in range(4)] for i in range(4)]
sum = three_d_array[1][2][3] + three_d_array[2][3][1] + three_d_array[0][0][0]
print(sum) |
class MapperError(Exception):
"""Broken mapper configuration error."""
pass
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
5
5
"""
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
root = n = ListNode(0)
carry = 0
sum = 0
... |
def txt_category_to_dict(category_str):
"""
Parameters
----------
category_str: str of nominal values from dataset meta information
Returns
-------
dict of the nominal values and their one letter encoding
Example
-------
"bell=b, convex=x" -> {"bell": "b", "convex":... |
"""
Web fragments.
"""
__version__ = '0.3.2'
default_app_config = 'web_fragments.apps.WebFragmentsConfig' # pylint: disable=invalid-name
|
def f(x):
print('a')
y = x
print('b')
while y > 0:
print('c')
y -= 1
print('d')
yield y
print('e')
print('f')
return None
for val in f(3):
print(val)
#gen = f(3)
#print(gen)
#print(gen.__next__())
#print(gen.__next__())
#print(gen.__next__())
#print(... |
file = open("test/TopCompiler/"+input("filename: "), mode= "w")
sizeOfFunc = input("size of func: ")
lines = input("lines of code: ")
out = []
for i in range(int(int(lines) / int(sizeOfFunc)+2)):
out.append("def func"+str(i)+"() =\n")
for c in range(int(sizeOfFunc)):
out.append(' println "hello worl... |
#! /usr/bin/env python3
'''
Disjoint Set Class that provides basic functionality.
Implemented according the functionality provided here:
https://en.wikipedia.org/wiki/Disjoint-set_data_structure
@author: Paul Miller (github.com/138paulmiller)
'''
class DisjointSet:
'''
Disjoint Set : Utility class that helps implem... |
#!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'dàdūn'
CN=u'大敦'
NAME=u'dadun41'
CHANNEL='liver'
CHANNEL_FULLNAME='LiverChannelofFoot-Jueyin'
SEQ='LR1'
if __name__ == '__main__':
pass
|
frase = input("Digite uma frase: ").strip().upper()
frase = frase.replace(" ","")
inverso = frase[::-1]
print(f"O inverso de {frase} é {inverso}")
if (frase == inverso):
print("A frase digitada é um palíndromo!")
else:
print("A frase digitada não é um palíndromo!") |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under t... |
#!/usr/bin/python
# https://code.google.com/codejam/contest/2933486/dashboard
# application of insertion sort
N = int(input().strip())
for i in range(N):
M = int(input().strip())
deck = []
count = 0
for j in range(M):
deck.append(input().strip())
p = 0
for k in range(len(deck)):
if k > 0 and deck[k]... |
# escreva um programa que pergunte a quantidade de quilometros percorridos por um carro alugado e a quantidade
# de dias pelos quais ele foia alugado. calcule o preço a pagar sabenco que o carro custa R$ 60,00 o dia
# e R$ 0.15 por km rodado
dias = int(input('Quabtos dias ficou com o carro? '))
km = float(input('Quan... |
def sum(arr: list, start: int, end: int)->int:
if start > end:
return 0
elif start == end:
return arr[start]
else:
midpoint: int = int(start + (end - start) / 2)
return sum(arr, start, midpoint) + sum(arr, midpoint + 1, end)
numbers1: list = []
numbers2: list =... |
class Car:
def __init__(self, pMake, pModel, pColor, pPrice):
self.make = pMake
self.model = pModel
self.color = pColor
self.price = pPrice
def __str__(self):
return 'Make = %s, Model = %s, Color = %s, Price = %s' %(self.make, self.model, self.color, self.price)
... |
class SimpleTreeNode:
def __init__(self, val, left=None, right=None) -> None:
self.val = val
self.left = left
self.right = right
class AdvanceTreeNode:
def __init__(self, val, parent=None, left=None, right=None) -> None:
self.val = val
self.parent: AdvanceTreeNode = par... |
#
# PySNMP MIB module CISCO-OPTICAL-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OPTICAL-MONITOR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:08:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... |
name = 'Bob'
if name == 'Alice':
print('Hi Alice')
print('Done')
|
def tup(name, len):
ret = '('
for i in range(len):
ret += f'{name}{i}, '
return ret + ')'
for i in range(10):
print(
f'impl_unzip!({tup("T",i)}, {tup("A",i)}, {tup("s",i)}, {tup("t",i)});')
|
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.rec = rectangle
self.newRec = []
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
self.newRec.append((row1, col1, row2, col2, newValue))
def get... |
# model
model = Model()
i0 = Input("op_shape", "TENSOR_INT32", "{4}")
weights = Parameter("ker", "TENSOR_FLOAT32", "{1, 3, 3, 1}", [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
i1 = Input("in", "TENSOR_FLOAT32", "{1, 4, 4, 1}" )
pad = Int32Scalar("pad_same", 1)
s_x = Int32Scalar("stride_x", 1)
s_y = Int32Scalar("strid... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 13:28:17 2020
@author: Robinson Montes
Carlos Murcia
"""
|
{
"targets": [
{
"target_name": "cityhash",
"include_dirs": ["cityhash/"],
"sources": [
"binding.cc",
"cityhash/city.cc"
]
}
]
}
|
# def positive_or_negative(value):
# if value > 0:
# return "Positive!"
# elif value < 0:
# return "Negative!"
# else:
# return "It's zero!"
# number = int(input("Wprowadz liczbe: "))
# print(positive_or_negative(number))
def calculator(operation, a, b):
if operation == "add":
... |
pkgname = "eventlog"
pkgver = "0.2.13"
pkgrel = 0
_commit = "a5c19163ba131f79452c6dfe4e31c2b4ce4be741"
build_style = "gnu_configure"
hostmakedepends = ["pkgconf", "automake", "libtool"]
pkgdesc = "API to format and send structured log messages"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-3-Clause"
url = "... |
"""Echoes everything you say.
Usage:
/echo
/echo Hi!
Type 'cancel' to stop echoing.
"""
def handle_update(bot, update, update_queue, **kwargs):
"""Echo messages that user sends.
This is the main function that modulehander calls.
Args:
bot (telegram.Bot): Telegram bot itself
update ... |
#
# PySNMP MIB module CISCO-COMPRESSION-SERVICE-ADAPTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMPRESSION-SERVICE-ADAPTER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
#... |
user_input = '5,4,25,18,22,9'
user_numbers = user_input.split(',')
user_numbers_as_int = []
for number in user_numbers:
user_numbers_as_int.append(int(number))
print(user_numbers_as_int)
print([number for number in user_numbers])
print([number*2 for number in user_numbers])
print([int(number) for number in use... |
line = "Please have a nice day"
# This takes a parameter, what prefix we're looking for.
line_new = line.startswith('Please')
print(line_new)
#Does it start with a lowercase p?
# And then we get back a False because,
# no, it doesn't start with a lowercase p
line_new = line.startswith('p')
print(line_new)
|
a=[1,2]
for i,s in enumerate(a):
print(i,"index contains",s)
|
def gen_help(bot_name):
return'''
Hello!
I am a telegram bot that generates duckduckgo links from tg directly.
I am an inline bot, you can access it via @{bot_name}.
If you have any questions feel free to leave issue at http://github.com/cleac/tgsearchbot
'''.format(bot_name=bot_name)
|
#class Solution:
# def checkPowersOfThree(self, n: int) -> bool:
#def checkPowersOfThree(n):
# def divisible_by_3(k):
# return k % 3 == 0
# #if 1 <= n <= 2:
# if n == 2:
# return False
# if divisible_by_3(n):
# return checkPowersOfThree(n//3)
# else:
# n = n - 1
# ... |
n = int(input('Enter A Number:'))
count = 1
for i in range(count, 11, 1):
print (f'{n} * {count} = {n*count}')
count +=1 |
# Sum of the diagonals of a spiral square diagonal
# OPTIMAL (<0.1s)
#
# APPROACH:
# Generate the numbers in the spiral with a simple algorithm until
# the desdired side is obtained,
SQUARE_SIDE = 1001
DUMMY_SQUARE_SIDE = 5
DUMMY_RESULT = 101
def generate_numbers(limit):
current = 1
internal_square = 1
steps = ... |
def left_join(d1, d2):
"""
Function that a LEFT JOINs 2 dictionaries into a single data structure.
All the values in the first dictionary are returned, and if values exist in the “right” dictionary, they are added to the {results dictionary}. If no values exist in the right dictionary, then None should be ... |
"""
Представление данных.
"""
class Pars:
def __init__(self, date, lesson, group, time, teacher):
self.date_lesson = date
self.lesson = lesson
self.group = group
self.time = time
self.teacher = teacher
|
def get_data(query):
"""[summary] make variable of chart.graphs.drawgraph.Graph().CustomDraw(kwargs) from querydict. The querydict from index.html
Args:
query ([type]): [description] querydict like <QueryDict: {'csrfmiddlewaretoken': ['2aboKu6bYhaa5OiUS5cWLytPpUpEMFLLqsYlZAE3MWervMwfoQ3HP9RlRcjEl9U... |
PI = 3.14
SALES_TAX = 6
if __name__ == '__main__':
print('Constant file directly executed')
else:
print('Constant file is imported') |
# ------------------------------------------------------------------------
# Copyright 2015 Intel Corporation
#
# 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/li... |
{
'targets': [
{
'target_name': 'electron-dragdrop-win',
'include_dirs': [
'<!(node -e "require(\'nan\')")',
],
'defines': [ 'UNICODE', '_UNICODE'],
'sources': [
],
'conditions': [
['OS=="win"', {
'sources': [
"src/addon.cpp",
... |
def format_reader_port_message(message, reader_port, error):
return f'{message} with {reader_port}. Error: {error}'
def format_reader_message(message, vendor_id, product_id, serial_number):
return f'{message} with ' \
f'vendor_id={vendor_id}, ' \
f'product_id={product_id} and ' \
... |
word="boy"
print(word)
reverse=[]
l=list(word)
for i in l:
reverse=[i]+reverse
reverse="".join(reverse)
print(reverse)
l=[1,2,3,4]
print(l)
r=[]
for i in l:
r=[i]+r
print(r) |
path = '08-File-Handling-Lab-Resources/File Reader/numbers.txt'
file = open(path, 'r')
num_sum = 0
for num in file:
num_sum += int(num)
print(num) # read
print(num_sum)
print(file.read()) # .read(n) n = number
|
class BindingTypes:
JSFunction = 1
JSObject = 2
class Binding(object):
def __init__(self, type, src, dest):
self.type = type
self.src = src
self.dest = dest
|
def faculty_evaluation_result(nev, rar, som, oft, voft, alw):
''' Write code to calculate faculty evaluation rating according to asssignment instructions
:param nev: Never
:param rar: Rarely
:param som: Sometimes
:param oft: Often
:param voft: Very Often
:param alw: Always
:ret... |
HTTP_HOST = ''
HTTP_PORT = 8080
FLASKY_MAIL_SUBJECT_PREFIX = "(Info)"
FLASKY_MAIL_SENDER = 'ycs_ctbu_2010@126.com'
FLASKY_ADMIN = 'ycs_ctbu_2010@126.com'
SECRET_KEY = "\x02|\x86.\\\xea\xba\x89\xa3\xfc\r%s\x9e\x06\x9d\x01\x9c\x84\xa1b+uC"
LOG = "/var/flasky"
# WSGI Settings
WSGI_LOG = 'default'
# Flask-... |
class Action:
def __init__(self, fun, id=None):
self._fun = fun
self._id = id
def fun(self):
return self._fun
def id(self):
return self._id
|
def encode(plaintext, key):
"""Encodes plaintext
Encode the message by shifting each character by the offset
of a character in the key.
"""
ciphertext = ""
i, j = 0, 0 # key, plaintext indices
# strip all non-alpha characters from key
key2 = ""
for x in key: key2 += x if x.isalp... |
# criar uma matriz identidade de tamanho NxN, onde N é informado pelo usuário.
# Criar uma segunda matriz que é o dobro da primeira.
# 1 0 0
# 0 1 0
# 0 0 1
def criaMatriz (n, m):
mat = [0]*n
for i in range(m):
mat[i] = [0] * n
return mat
def criaMatrizEye(n):
mat = criaMatriz(n,n)
... |
# -*- coding: utf-8 -*-
word_regexes = {
'en': r'[A-Za-z]+',
'pl': r'[A-Za-zęóąśłżźćń]+',
'ru': r'[АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя]+',
'uk': r'[АаБбВвГ㥴ДдЕеЄєЖжЗзИиІіЇїЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЬЮюЯя]+',
'tr': r'[a-zA-ZçÇğĞüÜöÖşŞıİ]+',
}
alphabets = {
... |
class dotIFC2X3_Product_t(object):
# no doc
Description = None
IFC2X3_OwnerHistory = None
Name = None
ObjectType = None
|
'''
###############################################
# ####################################### #
#### ######## Simple Calculator ########## ####
# ####################################### #
###############################################
## ##
###########... |
print('=' * 12 + 'Desafio 72' + '=' * 12)
numeros = (
'Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze',
'Catorze', 'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
while True:
escolha = int(input('Digite um número entre 0 e 20: '))
... |
def handle_error_response(resp):
codes = {
-1: FactomAPIError,
-32008: BlockNotFound,
-32009: MissingChainHead,
-32010: ReceiptCreationError,
-32011: RepeatedCommit,
-32600: InvalidRequest,
-32601: MethodNotFound,
-32602: InvalidParams,
-32603:... |
#
# @lc app=leetcode.cn id=292 lang=python3
#
# [292] Nim 游戏
#
# https://leetcode-cn.com/problems/nim-game/description/
#
# algorithms
# Easy (69.62%)
# Likes: 501
# Dislikes: 0
# Total Accepted: 102.9K
# Total Submissions: 146K
# Testcase Example: '4'
#
# 你和你的朋友,两个人一起玩 Nim 游戏:
#
#
# 桌子上有一堆石头。
# 你们轮流进行自己的回合,你作... |
# Encapsulate the pairs of int multiples to related string monikers
class MultipleMoniker:
mul = 0
mon = ""
def __init__(self, multiple, moniker) -> None:
self.mul = multiple
self.mon = moniker
# Define object to contain methods
class FizzBuzz:
# Define the int to start counting at
... |
"""
Load and Display an OBJ Shape.
The loadShape() command is used to read simple SVG (Scalable Vector Graphics)
files and OBJ (Object) files into a Processing sketch. This example loads an
OBJ file of a rocket and displays it to the screen.
"""
ry = 0
def setup():
size(640, 360, P3D)
global rocket
ro... |
print("Zadávejte celá čísla za každým Enter: nebo jen Enter pro ukončení")
total = 0
count = 0
while True:
line = input("číslo: ")
if line:
try:
number = int(line)
except ValueError as err:
print(err)
continue
total += number
count += 1
else:
break
if count:
pri... |
class ContentType:
"""AI Model content types."""
MODEL_PUBLISHING = 'application/vnd.iris.ai.model-publishing+json'
MODEL_TRAINING = 'application/vnd.iris.ai.model-training+json'
|
#
# 1265. Print Immutable Linked List in Reverse
#
# Q: https://leetcode.com/problems/print-immutable-linked-list-in-reverse/
# A: https://leetcode.com/problems/print-immutable-linked-list-in-reverse/discuss/436558/Javascript-Python3-C%2B%2B-1-Liners
#
class Solution:
def printLinkedListInReverse(self, head: 'Immu... |
class Grid:
def __init__(self, grid: [[int]]):
self.grid = grid
self.flashes = 0
self.ticks = 0
self.height = len(grid)
self.width = len(grid[0])
self.flashed_cells: [str] = []
def tick(self):
self.ticks += 1
i = 0
for row in self.grid:... |
fid = {
"2": "亞洲無碼原創區",
"15": "亞洲有碼原創區",
"4": "歐美原創區",
"25": "國產原創區",
"5": "動漫原創區",
"26": "中字原創區",
"27": "轉帖交流區"
}
base_url = "http://www.t66y.com"
page_path = "thread0806.php"
page_num = list(range(1, 101))
headers = {
"Connection": "keep-alive",
"Cache-Control": "max-age=0",
"... |
#6. Дан список чисел. Выведите все элементы списка, которые больше предыдущего элемента.
def bigger_then_pred(values):
number_that_bigger_then_pred = []
for index, value in enumerate(values):
if value > values[index - 1]:
number_that_bigger_then_pred.append(value)
return number_tha... |
#%%
text=open('new.txt', 'r+')
text.write('Hello file')
for i in range(0, 11):
text.write(str(i))
print(text.seek(2))
#%%
#file operations Read & Write
text=open('sampletxt.txt', 'r')
text= text.read()
print(text)
text=text.split(' ')
print(text)
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"load_audio": "00_core.ipynb",
"AudioMono": "00_core.ipynb",
"duration": "00_core.ipynb",
"SpecImage": "00_core.ipynb",
"ArrayAudioBase": "00_core.ipynb",
"ArraySp... |
class ObjAlreadyExist(Exception):
"""Is used when is created multiple objects of same RestApi class."""
def __init__(self, cls=None, message=None):
if not (cls and message):
message = "RestApi object was created twice."
elif not message:
message = "{} object was created t... |
"""
focal_point
===========
The *focal_point* extension allows you to drag a marker on image thumbnails
while editing, thus specifying the most relevant portion of the image. You can
then use these coordinates in templates for image cropping.
- To install it, add the extension module to your ``INSTALLED_APPS`` sett... |
def leiaDinheiro(msg):
valido = False
valor = 0
while not valido:
din = str(input(msg)).strip().replace(',', '.')
if din.isalpha() or din == '':
print(f'\033[0;31mERRO! \"{din}\" é um preço inválido!\033[m')
else:
valido = True
return float(din) |
version = "1.0"
version_maj = 1
version_min = 0
|
digits = {'0': 'zero', '1': 'jeden', '2': 'dwa', '3': 'trzy', '4': 'cztery', '5': 'pięć', \
'6': 'sześć', '7': 'siedem', '8': 'osiem', '9': 'dziewięć'}
user_input = input("Wpisz cyfry, a ja zamienię je na słowa: \n")
for i in range(len(user_input)):
if user_input[i] not in '0123456789':
continue... |
r = range(5) # Counts from 0 to 4
for i in r:
print(i)
r = range(1,6) # Counts from 1 to 5
for i in r:
print(i)
# Step Value
r = range(1,15,3) # Counts from 1 to 15 with a gap of '3', thereby, counting till '13' only as 16 is not in the... |
# Apartado 24 (Clases)
"""
¿En qué consiste la Programación Orientada a Objetos (POO)?
- En trasladar la naturaleza de los objetos de la vida real a código
de programación (en algún lenguaje de programación, como Python).
Los objetos de la realidad tienen características (atributos o propiedades)
y funcionalidades o c... |
# --- Day 3: Toboggan Trajectory ---
line_list = [line.rstrip("\n") for line in open("input.txt")]
def slopecheck(hori, vert):
pos = 0
found = 0
i = 0
for line in line_list:
if i % vert == 0:
if line[pos % len(line)] == "#":
found += 1
pos += hori
i += 1
return found
a = slopecheck(1, 1)
b = slope... |
#093_Cadastro_de_jogadores.py
jogador = {}
gols = []
totgols = 0
print("")
jogador['Nome'] = str(input("Nome: "))
jogador['Partidas Jogadas'] = int(input("Quantidades de partidas: "))
for i in range(0,jogador['Partidas Jogadas']):
g = int(input(f" Quantidades de gols na {i+1}º partida: "))
gols.append(g)
... |
# kgen_extra.py
kgen_file_header = \
"""
! KGEN-generated Fortran source file
!
! Filename : %s
! Generated at: %s
! KGEN version: %s
"""
kgen_subprograms = \
"""FUNCTION kgen_get_newunit() RESULT(new_unit)
INTEGER, PARAMETER :: UNIT_MIN=100, UNIT_MAX=1000000
LOGICAL :: is_opened
INTEGER :: nunit, new_un... |
def sum(*n):
total=0
for n1 in n:
total=total+n1
print("the sum=",total)
sum()
sum(10)
sum(10,20)
sum(10,20,30,40) |
"""
Django configurations for the project.
These configurations include:
* settings: Project-wide settings, which may be customized per environment.
* urls: Routes URLs to views (i.e., Python functions).
* wsgi: The default Web Server Gateway Interface.
""" |
name = 'late_binding'
version = "1.0"
@late()
def tools():
return ["util"]
def commands():
env.PATH.append("{root}/bin")
|
# functions
# i.e., len() where the () designate a function
# functions that are related to str
course = "python programming"
# here we have a kind of function called a "method" which
# comes after a str and designated by a "."
# in Py all everything is an object
# and objects have "functions"
# and "functions" have ... |
#!/usr/bin/python
"""
Fizz Buzz in python 3
P Campbell
February 2018
"""
for i in range(1,101):
if i % 3 == 0 or i % 5 == 0 :
if i % 3 == 0:
msg = "Fizz"
if i % 5 == 0:
msg += "Buzz"
print (msg)
msg = ""
else:
print (i)
|
print("""
087) Aprimore o desafio anterior, mostrando no final:
A) A soma de todos os valores somaDosPares digitados.
B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha.
""")
tamanhoDaMatriz = 3
matriz = []
saida = ''
somaDosPares = somaDosNumerosDaTerceiraColuna = 0
titulo = f' Usando números... |
class DirectoryObjectSecurity(ObjectSecurity):
""" Provides the ability to control access to directory objects without direct manipulation of Access Control Lists (ACLs). """
def AccessRuleFactory(self,identityReference,accessMask,isInherited,inheritanceFlags,propagationFlags,type,objectType=None,inheritedObjectTyp... |
#this is to make change from dollar bills
change=float(input("Enter an amount to make change for :"))
print("Your change is..")
print(int(change//20), "twenties")
change=change % 20
print(int(change//10), "tens")
change=change % 10
print(int(change//5), "fives")
change=change % 5
print(int(change//1), "ones")
change=ch... |
def calc_fuel(mass):
fuel = int(mass / 3) - 2
return fuel
with open("input.txt") as infile:
fuel_sum = 0
for line in infile:
mass = int(line.strip())
fuel = calc_fuel(mass)
fuel_sum += fuel
print(fuel_sum)
|
def main() -> None:
a, b, c = map(int, input().split())
d = [a, b, c]
d.sort()
print("Yes" if d[1] == b else "No")
if __name__ == "__main__":
main()
|
def sums(target):
ans = 0
sumlist=[]
count = 1
for num in range(target):
sumlist.append(count)
count = count + 1
ans = sum(sumlist)
print(ans)
#print(sumlist)
target = int(input(""))
sums(target)
|
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['print_hello']
# Cell
def print_hello(to):
"Print hello to the user"
return f"Hello, {to}!" |
## @ingroup methods-mission-segments
# expand_state.py
#
# Created: Jul 2014, SUAVE Team
# Modified: Jan 2016, E. Botero
# ----------------------------------------------------------------------
# Expand State
# ----------------------------------------------------------------------
## @ingroup methods-mission-segme... |
# Keys are ISO 3166-2:PL abbr.
VOIVODESHIPS = {
"DS": {"teryt": "02", "name_pl": "dolnośląskie"},
"KP": {"teryt": "04", "name_pl": "kujawsko-pomorskie"},
"LU": {"teryt": "06", "name_pl": "lubelskie"},
"LB": {"teryt": "08", "name_pl": "lubuskie"},
"LD": {"teryt": "10", "name_pl": "łódzkie"},
"MA"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.