content stringlengths 7 1.05M |
|---|
if True:
pass
else:
x = 3
|
print("Welcome to the Band Name Generator.")
city_name =input("What's name of the city you grew up in?\n")
pet_name =input("What's your pet's name?\n")
print("Your band name could be Bristole Rabbit")
|
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""
abcabcbb
i
j
{}
"""
seen = set()
best = 0
i = 0
for j in range(0, len(s)):
end_char = s[j]
while end_char in seen:
... |
#!/usr/bin/env python
# encoding: utf-8
__title__ = "Arithmatic Coding"
__author__ = "Waleed Yaser (waleedyaser95@gmail.com)"
__version__ = "1.0"
"""
Arithmatic Coding
~~~~~~~~~~~~~~~~~
A class for implementing Arithmatic coding.
constructor takes 3 parameters:
*symbols list
*probalit... |
class Settings:
info = {
"version": "0.2.0",
"description": "Python library which allows to read, modify, create and run EnergyPlus files and simulations."
}
groups = {
'simulation_parameters': [
'Timestep',
'Version',
'SimulationControl',
... |
DEBUG = False
SECRET_KEY = '3tJhmR0XFbSOUG02Wpp7'
CSRF_ENABLED = True
CSRF_SESSION_LKEY = 'e8uXRmxo701QarZiXxGf'
|
#SALÁRIO E AUMENTO | IF: OU ELSE:
salário = float(input('Qual é o salário do funcionário? R$'))
if salário <= 1250:
novosalário = salário + (salário * 15 / 100) #Aumento de 15%
else:
novosalário = salário + (salário * 10 / 100) #Aumento de 10%
print('Quem ganhava R${:.2f} passa a ganhar {:.2f}.'.format(salário,... |
'''
Statement
Given a month - an integer from 1 to 12, print the number of days in it in the year 2017.
Example input #1
1
(January)
Example output #1
31
Example input #2
2
(February)
Example output #2
28
'''
month = int(input())
if month == 2:
print(28)
elif month < 8:
if month % 2 == 0:
print(30... |
# Challenge No 9 Intermediate
# https://www.reddit.com/r/dailyprogrammer/comments/pu1y6/2172012_challenge_9_intermediate/
# Take a string, scan file for string, and replace with another string
def main():
pass
def f_r():
fn = input('Please input filename: ')
sstring = input('Please input string t... |
list1=[2,3,8,5,9,2,7,4]
i=0
print("before list",list1)
while i<len(list1):
j=0
while j<i:
if list1[i]<list1[j]:
temp=list1[i]
list1[i]=list1[j]
list1[j]=temp
j+=1
i+=1
print("after",list1) |
class TimezoneTool:
@classmethod
def tzdb2abbreviation(cls, tzdb):
if tzdb == "Asia/Seoul":
return "KST"
if tzdb == "America/Los_Angeles":
return "ET"
raise NotImplementedError({"tzdb":tzdb})
|
# == Parameters == #
β = 1 / 1.05
ρ, mg = .7, .35
A = eye(2)
A[0, :] = ρ, mg * (1-ρ)
C = np.zeros((2, 1))
C[0, 0] = np.sqrt(1 - ρ**2) * mg / 10
Sg = np.array((1, 0)).reshape(1, 2)
Sd = np.array((0, 0)).reshape(1, 2)
Sb = np.array((0, 2.135)).reshape(1, 2)
Ss = np.array((0, 0)).reshape(1, 2)
economy = Economy(β=β, Sg=S... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 13:43:13 2017
@author: ktt
"""
def flatten(py_list):
flat = []
for k in py_list:
if k not in [None, (), [], {}]:
if isinstance(k, list):
flat.extend(flatten(k))
else:
flat.a... |
def shortest_path(sx, sy, maze):
w = len(maze[0])
h = len(maze)
board = [[None for i in range(w)] for i in range(h)]
board[sx][sy] = 1
arr = [(sx, sy)]
while arr:
x, y = arr.pop(0)
for i in [[1, 0], [-1, 0], [0, -1], [0, 1]]:
nx, ny = x + i[0], y + i[1]
... |
def contador(i, f, p):
"""
=> Faz uma contagem e mosta na tela.
:param i: início da contagem
:param f: fim da contagem
:param p: passo da contagem
:return:sem retorno
"""
c = i
while c <= f:
print(f"{c}", end="...")
c += p
print("FIM!")
# Programa principal
cont... |
# -----------------------------------------------------------------------------
# Copyright (c) 2013-2022, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.tx... |
# Este programa resuelve el siguiente problema:
# Link: https://www.spoj.com/problems/INTEST/
# Input:
# La entrada comienza con dos números enteros positivos n k (n, k<=10^7). Las siguientes n líneas de
# entrada contienen un entero positivo t, no mayor de 10^9, cada uno
# Output:
# Escriba un solo entero a la salida... |
def bytes(b):
""" Print bytes in a humanized way """
def humanize(b, base, suffices=[]):
bb = int(b)
for suffix in suffices:
if bb < base:
break
bb /= float(base)
return "%.2f %s" % (bb, suffix)
print("Base 1024: ", humanize(
b, 1024, ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB',... |
try:
f=open("no.py","r")
print(f.read())
except BaseException as msg:#打印具体的异常信息
print(msg)
#正常情况下
f=open("baidu.py","r")
print(f.read())
'''
异常try except 与else和finally的配合使用
'''
try:
print("异常测试")
except BaseException as msg:
print(msg)
else:
print("运行正常,无报错")
finally:
print("不管有无异常。都... |
""" Merge Sort Algorithm: Divide and Conquer Algorithm"""
"""Implementation: Merging two sorted arrays"""
def merge_sort(arr1, arr2):
n1 = len(arr1)
n2 = len(arr2)
index1, index2 = 0, 0
while index1 < n1 and index2 < n2:
if arr1[index1] <= arr2[index2]:
print(arr1[index1], end=" ... |
#!/usr/bin/env python
""" generated source for module Mapping """
class Mapping(object):
""" generated source for class Mapping """
key = []
def __init__(self):
""" generated source for method __init__ """
self.key = ["#"]*26
@classmethod
def fromTranslation(self, cipher, translati... |
# 1
# Answer: Programming language
# 2
# Answer: B
# 3
print("Hi")
# 4
# Answer: quit()
# 5
# Answer: 6
# 6
# Answer: B
# 7
# Answer: - 10 +
# 8
# Answer: >>> 1 / 0
# 9
# Answer: A
# 10
# Answer: 15.0
# 11
# Answer: 3
# 12
# Answer: A
# 13
# Answer: \"something\"
# 14
# Answer: input
# 15
# Answer: "World... |
#!/usr/bin/env python3
# vim: set fileencoding=utf-8 fileformat=unix expandtab :
"""__setup__.py -- metadata for xdwlib, A DocuWorks library for Python.
Copyright (C) 2010 HAYASHI Hideki <hideki@hayasix.com> All rights reserved.
This software is subject to the provisions of the Zope Public License,
Version 2.1 (ZPL... |
#!/usr/bin/env python
NAME = 'BIG-IP Local Traffic Manager (F5 Networks)'
def is_waf(self):
if self.matchcookie(r'^BIGipServer'):
return True
elif self.matchheader(('X-Cnection', r'^close$'), attack=True):
return True
else:
return False
|
print("ma petite chaine en or", end='')
|
# function for insertion sort
def Insertion_Sort(list):
for i in range(1, len(list)):
temp = list[i]
j = i - 1
while j >= 0 and list[j] > temp:
list[j + 1] = list[j]
j -= 1
list[j + 1] = temp
# function to print list
def Print_list(list):
for i in range(... |
def cleanupFile(file_path):
with open(file_path,'r') as f:
with open("data/transactions.csv",'w') as f1:
next(f) # skip header line
for line in f:
f1.write(line)
def getDateParts(date_string):
year = ''
month = ''
day = ''
date_parts = date_string.split('-')
if (len(date_parts) > 2):
year = date_... |
#calculation of power using recursion
def exponentOfNumber(base,power):
if power == 0:
return 1
else:
return base * exponentOfNumber(base,power-1)
print("Enter only positive numbers below: ",)
print("Enter a base: ")
number = int(input())
print("Enter a power: ")
exponent = int(input())
re... |
def sma():
pass
def ema():
pass
|
dict1={'Influenza':['Relenza','B 0 D'],'Swine Flu':['Symmetrel','B L D'],'Cholera':['Ciprofloxacin','B 0 D'],'Typhoid':['Azithromycin','B L D'],'Sunstroke':['Barbiturates','0 0 D'],'Common cold':['Ibuprufen','B 0 D'],'Whooping Cough':['Erthromycin','B 0 D'],'Gastroentritis':['Gelusil','B 0 D'],'Conjunctivitus':['Romyci... |
'''
Created on 2016年1月21日
@author: Darren
'''
def countGreater(nums):
def sort(enum):
half = len(enum) // 2
if half:
left, right = sort(enum[:half]), sort(enum[half:])
for i in range(len(enum))[::-1]:
if not right or left and left[-1][1] < right[-1][1]:
... |
"""
The Program receives from the USER
a university EVALUATION in LETTERS (for example: A+, C-, F, etc.)
and returns (displaying it) the corresponding evaluation in POINTS.
"""
# START Definition of FUNCTIONS
def letterGradeValida(letter):
if len(letter) == 1:
if (65 <= ord(letter[0].upper()) <= 68) or ... |
def solve(captcha, step):
result = 0
for i in range(len(captcha)):
if captcha[i] == captcha[(i + step) % len(captcha)]:
result += int(captcha[i])
return result
if __name__ == '__main__':
solve_part1 = lambda captcha: solve(captcha, 1)
solve_part2 = lambda captcha: solve(captcha,... |
print ('{0:.3f}'.format(1.0/3))
print('{0} / {1} = {2:.3f}'.format(3, 4,3/4 ))
# fill with underscores (_) with the text centered
# (^) to 11 width '___hello___'
print ('{0:_^9}'.format('hello'))
def variable(name=''):
print('{0:*^12}'.format(name))
variable()
print('{0:*^12}'.format('sendra'))
variable()
# keyword... |
INH = "Inherent" # The 'address' is inherent in the opcode. e.g. ABX
INT = "Interregister" # An pseudo-addressing for an immediate operand which specified registers for the EXG and TFR instructions
IMM = "Immediate" # Operand immediately follows the opcode. A literal. Could be 8-bit (LDA), 16-bi... |
"""Question 3: Accept string from a user and display only those characters
which are present at an even index number."""
def evenIndexNumber(palabra):
print("Printing only even index chars")
for i in range(0, len(palabra), 2):
print("index[", i, "]", palabra[i:i+1])
word=input("Enter Strin... |
'''
Given a number A. Find the fatorial of the number.
Problem Constraints
1 <= A <= 100
'''
def factorial(A: int) -> int:
if A <= 1:
return 1
return (A * factorial(A-1))
if __name__ == "__main__":
A = 3
print(factorial(A)) |
i = 125874
while True:
if sorted(str(i)) == sorted(str(i * 2)) == sorted(str(i * 3)) == sorted(str(i * 4)) == sorted(str(i * 5)) == sorted(str(i * 6)):
break
else:
i += 1
print(i) |
#!/usr/bin/env python3
a = ["uno", "dos", "tres"]
b = [f"{i:#04d} {e}" for i,e in enumerate(a)]
print(b)
|
def test_app_is_created(app):
assert app.name == 'care_api.app'
def test_request_returns_404(client):
assert client.get('/url_not_found').status_code == 404 |
def pi_nks(limit: int) -> float:
pi: float = 3.0
s: int = 1
for i in range(2, limit, 2):
pi += (s*4/(i*(i+1)*(i+2)))
s = s*(-1)
return pi
def pi_gls(limit: int) -> float:
pi: float = 0.0
s: int = 1
for i in range(1, limit, 2):
pi += (s*(4/i))
s = s*(-1)
... |
#
# Script for converting collected NR data into
# the format for comparison with the simulations
#
def clean_and_save(file1, file2, cx, cy, ech):
''' Remove rows with character ech from
the data in file1 column cy and corresponding
rows in cx, then save to file2. Column numbering
starts with 0. '''
with... |
# Set to 1 or 2 to show what we send and receive from the SMTP server
SMTP_DEBUG = 0
SMTP_HOST = ''
SMTP_PORT = 465
SMTP_FROM_ADDRESSES = ()
SMTP_TO_ADDRESS = ''
# these two can also be set by the environment variables with the same name
SMTP_USERNAME = ''
SMTP_PASSWORD = ''
IMAP_HOSTNAME = ''
IMAP_USERNAME = ''
IMA... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
"""
Messages dictionary
==================
This module takes care of logging, using levels ERROR|DEBUG. Other levels could be added in the future
This is to make it easier to translate the language of this tool and to centralize the logging behavior
> Ignacio Tamayo, TSP, 2016
> Version 1.4
> Date: Sept 2016
"""
... |
#Si se nombra un método de esta manera: "__init__", no será un método regular, será un constructor.
#Si una clase tiene un constructor, este se invoca automática e implícitamente
# cuando se instancia el objeto de la clase.
#El constructor:
#Esta obligado a tener el parámetro "self" (se configura automáticamente).
#Pud... |
class Memorability_Prediction:
def mem_calculation(frame1):
#print ("Inside mem_calculation function")
start_time1 = time.time()
resized_image = caffe.io.resize_image(frame1,[227,227])
net1.blobs['data'].data[...] = transformer1.preprocess('data', resized_image)
... |
#
# PySNMP MIB module ZYXEL-OAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-OAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:45:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
def to_xyz(self):
"""Performs the corrdinate change and stores the resulting field in a VectorField object.
Parameters
----------
self : VectorField
a VectorField object
Returns
-------
a VectorField object
"""
# Dynamic import to avoid loop
module = __import__("SciDataT... |
class ToolVariables:
@classmethod
def ExcheckUpdate(cls):
cls.INTAG = "ExCheck"
return cls
|
test = {
'name': 'q1_2',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> mean_based_estimator(np.array([1, 2, 3])) is not None
True
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>>... |
class ScheduleItem:
def __init__(item, task):
item.task = task
item.start_time = None
item.end_time = None
item.child_start_time = None
item.pred_task = None
item.duration = task.duration
item.total_effort = None
item.who = ''
class Schedule:
def ... |
#%%
class Book:
def __init__(self,author,name,pageNum):
self.__author = author
self.__name = name
self.__pageNum = pageNum
def getAuthor(self):
return self.__author
def getName(self):
return self.__name
def getPageNum(self):
return self.__pageNu... |
# ---------------------------------------------------------------------------------------------
# Copyright (c) Akash Nag. All rights reserved.
# Licensed under the MIT License. See LICENSE.md in the project root for license information.
# ------------------------------------------------------------------------------... |
lista = []
mai = 0
men = 0
for c in range(0,5):
lista.append( int(input(f'Digite um Valor para Posição {c}: ')))
if c == 0:
mai = men = lista[0]
else:
if lista[c] > mai:
mai = lista[c]
if lista[c] < men :
men = lista[c]
print('-='*30)
print(f'Sua Lista é ... |
N = int(input())
M = int(input())
res = list()
for x in range(N, M+1):
cnt = 0
if x > 1:
for i in range(2, x):
if x % i == 0:
cnt += 1
break
if cnt == 0:
res.append(x)
if len(res) > 0:
print(sum(res))
print(min(res))
else:
... |
# Application settings
# Flask settings
DEBUG = False
# Flask-restplus settings
RESTPLUS_MASK_SWAGGER = False
SWAGGER_UI_DOC_EXPANSION = 'none'
# API metadata
API_TITLE = 'MAX Breast Cancer Mitosis Detector'
API_DESC = 'Predict the probability of the input image containing mitosis.'
API_VERSION = '0.1'
# default mo... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 24 10:17:54 2021
@author: User
"""
#%%
nombre = 'Naranja'
cajones = 100
precio = 91.1
print(f'{nombre:>10s} {cajones:>10d} {precio:>10.2f}')
#%%
# Formato a diccionarios
s = {
'nombre': 'Naranja',
'cajones': 100,
'precio': 91.1
}
print('{nombre:>10s} {cajones... |
def notas(* notas, sit = False):
"""
--> Recebe n notas de alunos e retorna um dicionário com Quantidade de notas, A maior nota, A menor nota, A média da turma e a situação.
:param notas: Recebe n notas passadas na função, não recebe lista
:param sit: Parametro opcional para mostrar a situação do alu... |
#
# @lc app=leetcode id=1431 lang=python3
#
# [1431] Kids With the Greatest Number of Candies
#
# @lc code=start
class Solution:
def kidsWithCandies(self, candies: List[int], extra_candies: int) -> List[bool]:
max_candies = max(candies)
return [i + extra_candies >= max_candies for i in candies]
# @... |
"""
This module contains all files for a django deployment 'site'.
When called via the manage.py command, this folder is used as regular django setup.
"""
|
'''
Exercício Python 087: Aprimore o desafio anterior, mostrando no final:
A) A soma de todos os valores pares digitados.
B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha.
'''
matriz = [[0,0,0], [0,0,0], [0,0,0]]
maior = somapar = terceira_coluna = 0
for l in range(0,3):
for c in range(... |
# -*- coding: utf-8 -*-
"""
This package implements various parameterisations of properties from the
litterature with relevance in chemistry.
"""
|
def repeated_n_times(nums):
# nums.length == 2 * n
n = len(nums) // 2
for num in nums:
if nums.count(num) == n:
return num
print(repeated_n_times([1, 2, 3, 3]))
print(repeated_n_times([2, 1, 2, 5, 3, 2]))
print(repeated_n_times([5, 1, 5, 2, 5, 3, 5, 4]))
|
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
# See:
# https://docs.microsoft.com/en-us/windows/win32/eventlog/event-types
# https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-reporteventa#parameters
# https://docs.microsoft.com/en... |
# Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
user_input = int(input('Введите трехзначное число: '))
hundreds = user_input // 100
dozens = user_input % 100 // 10
units = user_input % 10
summary = hundreds + dozens + units
multiplication = hundreds * dozens * units
print(f'Результ... |
@outputSchema('vals: {(val:chararray)}')
def convert(the_input):
# This converts the indeterminate number of vals into a bag.
out = []
for map in the_input:
out.append(map)
return out
|
"""Settings for depicting LaTex figures"""
class Figure:
"""Figure class for depicting HTML and LaTeX.
:param path:
The path to an image
:type path:
str
:param title:
The caption of the figure
:param title:
str
:param label:
The label of the label
:p... |
class Solution:
def recurse(self, n, stack, cur_open) :
if n == 0 :
self.ans.append(stack+')'*cur_open)
return
for i in range(cur_open+1) :
self.recurse(n-1, stack+(')'*i)+'(', cur_open-i+1)
# @param A : integer
# @return a list of strings
def g... |
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
i = 0 # how many bit right shifted
while left != right:
left >>= 1
right >>= 1
i += 1
return left << i
# TESTS
for left, right, expected in [
(5, 7, 4),
(0, 1, 0),
(26,... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"plot_sequence": "10_core_overview.ipynb",
"plot_sequence_1d": "10_core_overview.ipynb",
"get_alphabet": "11_core_elements.ipynb",
"get_element_counts": "11_core_elements.ipynb",
... |
print("Challenges 38: WAF program to print the number of prime numbers which are less than or equal to a given integer.")
n = 7
nums = range(2, n+1)
num_of_divisors = 0
counter = 0
for x in nums:
for i in range(1, x+1):
if x % i == 0:
num_of_divisors += 1
if num_of_divisors == 2:
counter ... |
def n_to_triangularno_stevilo(n):
stevilo = 0
a = 1
for i in range(n):
stevilo += a
a += 1
return stevilo
def prvo_triangularno_stevilo_Z_vec_kot_k_delitelji(k):
j = 0
n = 0
stevilo_deliteljev = 0
while stevilo_deliteljev <= k:
stevilo_deliteljev = 0
... |
# mock.py
# Test tools for mocking and patching.
# Copyright (C) 2007 Michael Foord
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# mock 0.3.1
# http://www.voidspace.org.uk/python/mock.html
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml
# Scripts maintained at ht... |
# coding=utf-8
"""
:Copyright: © 2022 Advanced Control Systems, Inc. All Rights Reserved.
@Author: Darren Liang
@Date : 2022-02-28
"""
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree(object):
def __init__(s... |
"""Decorators used for adding functionality to the library."""
def downcast_field(property_name, default_value = None):
"""A decorator function for handling downcasting."""
def store_downcast_field_value(class_reference):
"""Store the key map."""
setattr(class_reference, "__deserialize_downca... |
a = 10
def f():
global a
a = 100
def ober():
b = 100
def unter():
nonlocal b
b = 1000
def unterunter():
nonlocal b
b = 10000
unterunter()
unter()
print(b)
ober()
def xyz(x):
return x * x
z = lambda x: x * x
print(z(... |
# Responsible for giving targets to the Quadrocopter control lopp
class HighLevelLogic:
def __init__(self, control_loop, state_provider):
self.controllers
self.flightmode = FlightModeLanded()
self.control_loop = control_loop
state_provider.registerListener(self)
# Tells all sy... |
keyb = '`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;\'ZXCVBNM,./'
while True:
try:
frase = input()
decod = ''
for c in frase:
if c == ' ':
decod += c
else:
decod += keyb[keyb.index(c)-1]
print(decod)
except EOFError:
break |
outputs = []
## Test Constructor
output = """PROFILING Command: ['./testConstructor ']
PrecisionTuner: MODE PROFILING
PrecisionTuner: MODE PROFILING
"""
outputs.append(output)
output = """Error no callstacks\n"""
outputs.append(output)
output = """Strategy Command: ['./testConstructor ']
Strategy: 1, STEP reached:... |
# Bubble Sort
def bubble_sort(array: list) -> tuple:
""""will return the sorted array, and number of swaps"""
total_swaps = 0
for i in range(len(array)):
swaps = 0
for j in range(len(array) - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], ... |
# Copyright 2021 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, ... |
def fun(n):
fact = 1
for i in range(1,n+1):
fact = fact * i
return fact
n= int(input())
k = fun(n)
j = fun(n//2)
l = j//(n//2)
print(((k//(j**2))*(l**2))//2) |
palavras = ("Aprender", "Programar", "Linguagem", "Python", "Curso", "Gratis", "Estudar", "Praticar", "Trabalhar ", "Mercado", "Programar", "Futuro")
for vol in palavras:
print(f"\nNa palavra {vol.upper()} temos", end=" ")
for letra in vol:
if letra.lower() in "aeiou":
print(letra, end=" ")
|
# a = int(input('Numerador: ')) # se tentarmos colocar uma letra aqui vai da erro de valor ValueError
# b = int(input('Denominador: ')) # se colocar 0 aqui vai acontecer uma excecao ZeroDivisionError - divisao por zero
# r = a/b
# print(f'A divisao de {a} por {b} vale = {r}')
# para tratar erros a gente usa o com... |
##
## Programación en Python
## ===========================================================================
##
## La columna 3 del archivo `data.csv` contiene una fecha en formato
## `YYYY-MM-DD`. Imprima la cantidad de registros por cada mes separados
## por comas, tal como se muestra a continuación.
##
## Rta/... |
print("Estou aprendendo Python")
nome = input("Qual o seu nome?")
idade = int(input("Qual sua idade?"))
peso = float(input("Qual o seu peso?"))
result = f"""
Seu Nome é: {nome}
Sua idade é: {idade}
E seu Peso é: {peso}
"""
print(result)
|
class Color(APIObject, IDisposable):
"""
Represents a color in Autodesk Revit.
Color(red: Byte,green: Byte,blue: Byte)
"""
def Dispose(self):
""" Dispose(self: APIObject,A_0: bool) """
pass
def ReleaseManagedResources(self, *args):
""" ReleaseManagedResources(s... |
class Solution:
def numTilings(self, n: int) -> int:
mod = 1_000_000_000 + 7
f = [[0 for i in range(1 << 2)] for i in range(2)]
f[0][(1 << 2) - 1] = 1
o0 = 0
o1 = 1
for i in range(n):
f[o1][0] = f[o0][(1 << 2) - 1]
f[o1][1] = (f[o0][0] + f[o0][... |
"""Constants that define time formats"""
F1 = '%Y-%m-%dT%H:%M:%S'
F2 = '%Y-%m-%d'
|
def escreva(texto):
tam = len(texto) + 4
print('~' * tam)
print(f' {texto}')
print('~' * tam)
escreva(str(input('Digite um texto: '))) |
"""Media files location specifications."""
def workflow_step_media_location(instance, filename):
"""Return the location of a stored media file for a Workflow Step."""
workflow_id = instance.workflow_step.workflow.id
step_id = instance.workflow_step_id
ui_identifier = instance.ui_identifier
file_ex... |
# -*- coding: utf-8 -*-
stations = {4349: 'Мусоргского (на Керамику)', 3426: 'Пионерская (на 1-й км)', 3461: 'Техучилище (на 1-й км)',
3380: 'Каменные палатки (на Комсомольскую)', 3348: 'Г-ца Исеть (на Шарташскую)',
3362: 'Декабристов (к Большакова)', 963627: 'Бульвар Малахова (на Фучика)', 350... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# normal recursive solution
# this recursive solution will call more methods which cause Time Limit Exceed
class Solution1:
# @param {TreeNode} root
# @return... |
url = 'http://127.0.0.1:3001/post'
dapr_url = "http://localhost:3500/v1.0/invoke/dp-61c2cb20562850d49d47d1c7-executorapp/method/health"
# dapr_url = "http://localhost:3500/v1.0/healthz"
# res = requests.post(dapr_url, json.dumps({'a': random.random() * 1000}))
# res = requests.get(dapr_url, )
#
#
#
# print(res.text)
... |
#!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_c_float_v_floatarray.tif test_splineinverse_c_flo... |
# src: https://github.com/dchest/tweetnacl-js/blob/acab4d4883e7a0be0b230df7b42c0bbd25210d39/nacl.js
__pragma__("js", "{}", r"""
(function(nacl) {
'use strict';
// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
//
// Implementation derived from TweetNaCl version 20140427.
// See for details: htt... |
"""
N : 1 * 2 * 3 * .... * N
"""
def factorial(n: int) -> int:
result = 1
for i in range(1, n + 1):
result *= i
return result
"""
nPr = n! / (n - r)!
"""
def permutation(n: int, r: int) -> int:
return factorial(n) // factorial(n - r)
# return 24 // factorial(n - r)
# return 24 // f... |
'''
Example:
import dk
cfg = dk.load_config(config_path='~/donkeycar/donkeycar/parts/RLConfig.py')
print(cfg.CAMERA_RESOLUTION)
'''
MODE_COMPLEX_LANE_FOLLOW = 0
MODE_SIMPLE_LINE_FOLLOW = 1
MODE_STEER_THROTTLE = MODE_COMPLEX_LANE_FOLLOW
# MODE_STEER_THROTTLE = MODE_SIMPLE_LINE_FOLLOW
PARTIAL_NN_CNT = 45000
#... |
def build_filter(args):
return Filter(args)
class Filter:
def __init__(self, args):
pass
def file_data_filter(self, file_data):
file_ctx = file_data["file_ctx"]
if not file_ctx.isbinary():
file_data["data"] = file_data["data"].replace(b"\r\n", b"\n")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.