content stringlengths 7 1.05M |
|---|
with open("spiderman.txt") as song:
print(song.read(2))
print(song.read(8))
print(song.read())
|
# -*- coding: utf-8 -*-
#
# Specifies the name of the last variable considered
# before plotting
#
lastvar = "k"
#
# Specifies the columns to be plotted
# and its label (in grace format)
#
col_contents = [(1, "\\f{Symbol} <r>"), (2, "\\f{Symbol} <dr>"), (3, "U\\sl")]
#
# Specifies the grace format of the x axis
#
... |
print(open('teste_win1252.txt', errors='strict').read())
print(open('teste_win1252.txt', errors='replace').read())
print(open('teste_win1252.txt', errors='ignore').read())
print(open('teste_win1252.txt', errors='surrogateescape').read())
print(open('teste_win1252.txt', errors='backslashreplace').read())
|
# --------------
class_1 = ["Geoffrey Hinton", "Andrew Ng", "Sebastian Raschka", "Yoshua Bengio"]
class_2 = ["Hilary Mason", "Carla Gentry", "Corinna Cortes"]
new_class = class_1 + class_2
print(new_class)
new_class.append("Peter Warden")
print(new_class)
new_class.remove("Carla Gentry")
print(new_class)
course... |
"""
Regularization works by penalizing model complexity. If the initial model is not
complex enough to correctly describe the data then no amount of regularization
will help as the model needs to get more complex to improve, not less.
"""; |
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
#print(full_name)
#print(f"Hello, {full_name.title()}!")
message = f"Hello, {full_name.title()}!"
print(message)
#print("\tPython")
#print("Languages:\nPython\nC\nJavaScript")
print("Languages:\n\tPython\n\tC\n\tJavaScript") |
class FakeConfig(object):
def __init__(
self,
src_dir=None,
spec_dir=None,
stylesheet_urls=None,
script_urls=None,
stop_spec_on_expectation_failure=False,
stop_on_spec_failure=False,
random=True
):
self._src_... |
class Timer:
def __init__(self, bot, ring_every=1.0):
self.bot = bot
self.last_ring = 0.0
self.ring_every = ring_every
@property
def rings(self):
if (self.bot.time - self.last_ring) >= self.ring_every:
self.last_ring = self.bot.time
return True
... |
#!/usr/bin/python3
class ComplexThing:
def __init__(self, name, data):
self.name = name
self.data = data
def __str__(self):
return self.name + ": " + str(self.data)
|
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
Dictionary storing numerical values.
"""
class NumberDict( dict ) :
"""
An instance of this class acts like an a... |
class Answer:
def __init__(self, text, id):
self.id = id
self.text = text
class Question:
def __init__(self, id, text, answers, correct_id):
self.id = id
self.text = text
self.answers = answers
self.correct_id = correct_id
class Quiz:
def __init__(self, na... |
CATEGORIES = [
('Arts & Entertainment', [
'Books & Literature',
'Celebrity Fan/Gossip',
'Fine Art',
'Humor',
'Movies',
'Music',
'Television'
]),
('Automotive', [
'Auto Parts',
'Auto Repair',
'Buying/Selling Cars',
'Car C... |
class VirusFoundException(Exception):
"""Exception raised for detecting a virus in a file upload"""
pass
class InvalidExtensionException(Exception):
"""Exception raised for an attachment with an invalid extension"""
pass
class InvalidFileTypeException(Exception):
"""Exception raised for an attachm... |
print( "Welcome to the Shape Generator:" )
cont = True
shape1 = 0
shape2 = 0
shape3 = 0
shape4 = 0
shape5 = 0
shape6 = 0
drawAnotherShape = False
def menu():
print()
print( "This program draw the following shapes:" )
print( f"{'1) Horizontal Line':>20s}" )
print( f"{'2) Vertical Line':>18s}" )
pr... |
num = 45
# symVal = {1000:'M',900:'CM',500:'D',400:'CD',100:'C',90:'XC',50:'L',40:'XL',10:'X',9:'IX',5:'V',4:'IV',1:'I'}
# romanNum = ''
# i = 0
# while num > 0 :
# curVal = list(symVal)[i]
# for _ in range(num // curVal):
# # if (divmod(num,4)[1] == 0 or divmod(num,9)[1] == 0):
# romanNum += ... |
# -*- coding: utf-8 -*-
TO_EXCLUDE = [
"ACITAK",
"ACITAK",
"ADASUW",
"AFEHOL",
"AFENAA",
"AFENAA",
"AMUTEI",
"AQUCOF",
"AQUCOF",
"AQUDAS",
"AQUDAS",
"ARADEE",
"ATAGOQ",
"ATAGOR",
"ATAGOR",
"BAXLA",
"BAXLAP",
"BAXLAP",
"BICPOV",
"BICPOV",
... |
# -*- coding: utf-8 -*-
URL = '127.0.0.1'
PORT = 27017
DATABASE = 'MyFunctions'
COLLECTION = 'FunctionCheckers'
FILE_PATH = '../examples/functions.py'
CATCHER = 'result'
IMPORT_POST = True
STATIC_POST = True
FUNC_POST = True
|
"""
=========== Exercise 1 =============
Using a list, create a shopping list of 5 items. Then
print the whole list, and then each item individually.
"""
shopping_list = [] # Fill in with some values
print(shopping_list) # Print the whole list
print() # Figure out how to print individual values
"""
... |
#Parsing and Extracting
data= "From Stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008"
atpos= data.find("@")
print(atpos)
atss= data.find(" ",atpos) #here it starts at 21 and then goes and find the next space
print(atss)
host= data[atpos+1: atss] #Now we are extracting the part that we are interested in
print(host)
#... |
"""Code to add interactive highlighting of series in matplotlib plots."""
class SelectorCursor(object):
"""An abstract cursor that may traverse a sequence of fixed length
in any order, repeatedly, and which includes a None position.
Executes a notifier when a position becomes selected or desel... |
# Solution
def part1(data):
stack = []
meta_sum = 0
gen = input_gen(data)
for x in gen:
if x != 0 or len(stack) % 2 == 1:
stack.append(x)
continue
m = next(gen)
while m > 0 or len(stack) > 0:
for _ in range(m):
meta_sum += next(... |
"""
In this problem, we need a structure to store which character occurs how many
times. It is best to use a dict object; but here we will use only lists. We will
keep counts in a list of two element lists. For example:
[["a",3],["b",5],["z",3]]
"""
def add_char(store,char):
"""add a character to the count store"... |
## IMPORTANT: Must be loaded after `02-service-common.py
## announcement service
service_env = dict()
service_url = f'{hub_hostname}:{service_port}'
if c.JupyterHub.internal_ssl:
# if we are using end-to-end mTLS, then pass
# certs to service and set scheme to `https`
# TODO: Generate certs automatic... |
def test_binary_byte_str_code(fake):
assert isinstance(fake.binary_byte_str(code=True), str)
def test_decimal_byte_str_code(fake):
assert isinstance(fake.decimal_byte_str(code=True), str)
def test_binary_byte_str(fake):
assert isinstance(fake.binary_byte_str(), str)
def test_decimal_byte_str(fake):
... |
#Classe usada para erros gerais relacionados as arestas
class ArestasIncompatibilityException(Exception):
def __init__(self,message :str):
super().__init__(message) |
# -*- coding: utf-8 -*-
"""
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
class Drzewo:
nazwa = 'Sosna'
wiek = 40
wysokosc = 25
drzewo_1 = Drzewo()
drzewo_2 = Drzewo()
# %%
print(id(drzewo_1))
print(id(drzewo_2))
# %%
dir(drzewo_1)
# %%
drzewo_1.nazwa
drzewo_1.wiek
drzewo_1.wysokosc
... |
nota1= float(input('Digite a primeira nota: '))
nota2= float(input('Digite a segunda nota: '))
med= (nota1+nota2)/2
if med<5:
print('reprovado')
if med>5 and med<6.9:
print('recuperation')
if med>7:
print('parabens espertão') |
""" Exercício 22
nome = str(input("Digite seu nome completo: "))
print(nome.upper())
print(nome.lower())
nome1 = len(nome)
nome2 = nome1 - nome.count(' ')
nome3 = nome.split()
print('O nome {} possui {} caracteres, e o primeiro nome possui'.format(nome, nome2), len(nome3[0]))
"""
""" Exercício 23
valor = int(input('... |
#Embedded file name: /Users/versonator/Hudson/live/Projects/AppLive/Resources/MIDI Remote Scripts/LPD8/consts.py
""" The following consts should be substituted with the Sys Ex messages for requesting
a controller's ID response and that response to allow for automatic lookup"""
ID_REQUEST = 0
ID_RESP = 0
GENERIC_STOP = ... |
#Program 20
#Write a program to write roll no, name and marks of 'n' students in a data file "marks.dat"
#Name: Vikhyat Jagini
#Class: 12
#Date of Execution: 26/08/2021
n=int(input("Enter the number of students you want to store data of in the data file:"))
f=open(r"C:\Python\Class 12 python\Lab Programs\BinaryFiles... |
def is_xpath_selector(selector):
"""
A basic method to determine if a selector is an xpath selector.
"""
if (
selector.startswith("/")
or selector.startswith("./")
or selector.startswith("(")
):
return True
return False
def is_link_text_selector(sele... |
# Qutebrowser config
# Sessions
c.auto_save.session = True
c.session.lazy_restore = True
# Tabs
c.tabs.position = 'left'
c.tabs.width = 200
c.tabs.new_position.unrelated = 'next'
c.tabs.background = True
# Hints
c.hints.mode = 'number'
c.hints.auto_follow = 'full-match'
c.content.pdfjs = True
c.content.javascript... |
#!/usr/bin/env python3
"""
Module with function to slice a matrix
"""
def np_slice(matrix, axes={}):
"""
Slices a matrix along a specific axes
Returns the new matrix
"""
return matrix[-3:, -3:]
|
class RichTextBoxSelectionTypes(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies the type of selection in a System.Windows.Forms.RichTextBox control.
enum (flags) RichTextBoxSelectionTypes,values: Empty (0),MultiChar (4),MultiObject (8),Object (2),Text (1)
"""
def __eq__(self, *arg... |
CODE_GAP = '-'
CODE_BACKGROUND = '-'
class State:
"""
Node in the HMM architecture, with emission probability
"""
def __init__(self, emission, module_id, state_id):
"""
:param emission: Multinomial distribution of nucleotide generation, one float value for each nucleotide
:par... |
def clean_string(s):
result=[]
for i in s:
if i=="#":
if result:
result.pop(-1)
else:
result.append(i)
return "".join(result) |
def dimensoes(matriz):
li = len(matriz)
c = 1
for i in matriz:
c = len(i)
return li, c
def soma_matrizes(m1, m2):
l, c = dimensoes(m1)
if dimensoes(m1) == dimensoes(m2):
m3 = m1
for i in range(0, l):
for col in range(0, c):
m3[i][col] = m... |
def collatz(n):
# recursion 재귀 함수
if n == 1:
return [1]
else:
if n % 2 == 0:
return [n] + collatz(n // 2)
else:
return [n] + collatz(3 * n + 1)
n = int(input())
seq = collatz(n)
print(seq)
for i in range(len(seq)):
print(seq[i], end=" ")
print(len... |
n1 = float(input('Digite o primeiro número: '))
n2 = float(input('Digite o segundo: '))
if n1 > n2:
print('O primeiro número é maior')
elif n2 > n1:
print('O segundo número é maior')
else:
print('Os dois números são iguais') |
'''
isnumeric, isdigit, isdecimal (metodos de String) :
essas funções verificam se o usuaario digiou um numero POSITIVO SEM PONTO FLUTUANTE
'''
num1 = input('digiteum numero ')
num2 = input('digite outro numero ')
teste1 = num1.isnumeric()
teste2 = num2.isnumeric()
try:
if teste1:
num1 = int(num1)
... |
"""Sorting Algorithms config."""
FILES_REPO = "files/"
IN_REPO = "files/in/"
OUT_REPO = "files/out/"
LOGS_REPO = "files/out/logs/"
SEPARATOR = " - "
STR_SIZE = 50
STR_NUMBER = 50
MAIN_DESCRIPTION = 'Sorting Algorithms'
ALGORITHM_DESCRIPTION = 'execute sorting algorithm (insertionsort, \
... |
"""
Description:
A demo of the ord() and chr() functions in python\
for ASCII table reference, please visit http://www.asciitable.com/
"""
__author__ = "Canadian Coding"
# chr() takes an int and returns the corresponding ASCII character
print(chr(65)) # prints 'A'
print(chr(97)) # prints 'a'
# ord() takes... |
"""
This module implements the Scorer Class.
A Scorer tracks the match, mismatch, gap, and xdrop values.
The Scorer is also responsible for calculating the dynamic programming
function value and direction.
"""
class Scorer():
"""Scorer Class"""
def __init__ ( self, match, mismatch, gap, xdrop ):
"""
... |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self, head=None):
self.head = head
def insert(self, value):
node = Node(value) # Node of [3]
if self.head is not None:
node.next = self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
db = {
'host': 'localhost',
'port': 6379
}
dbnames = {
'default': 1,
'ephermal': 8
}
|
"""
One of the most enjoyable hard questions on Leetcode.
A really hard problem until you break it down into smaller subproblems
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxPathSum(root: TreeNode) -> int:... |
class Tests(unittest.TestCase):
def _sim_model(self, data: Tensor) -> Tensor:
""" Simulated model for generating uncertainity scores. Intention
is to be a placeholder until real models are used and for testing."""
return torch.rand(size=(data.shape[0],))
def setUp(self):
... |
"""
Given a list of points on the 2-D plane and an integer K. The task is to find K closest points to the origin and
print them.
Note: The distance between two points on a plane is the Euclidean distance.
Input : point = [[3, 3], [5, -1], [-2, 4]], K = 2
Output : [[3, 3], [-2, 4]]
Square of Distance of origin from thi... |
# -*- coding: utf-8 -*-
#: The title of this site
SITE_TITLE='HasGeek Funnel'
#: Support contact email
SITE_SUPPORT_EMAIL = 'test@example.com'
#: TypeKit code for fonts
TYPEKIT_CODE=''
#: Google Analytics code UA-XXXXXX-X
GA_CODE=''
#: Database backend
SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'
#: Secret key
SECRET... |
a = input('Digie algo: ')
print('O tipo primitivo è :',type(a))
print('só tem espaços? ',a.isspace())
print('é numérico? ',a.isalnum())
print('è alfanumérico?', a.isalnum())
print('é alfabético? ', a.isalpha())
print('está em maúscilo?',a.isupper())
print('está em minúsculo? ', a.islower())
|
"""
Account: This clump of functions manage the account features for the API.
Their functions are like:
- Main account management.
- Register with {username} {email} {password} {confirmation}.
- Login with {username} {password}.
- Reset password {recovery key} with {new password} {confirmation}.
- Lo... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = Node("head")
self.size = 0
def __str__(self):
cur = self.head.next
out = ""
while cur:
out += str(cur.value) + "->"
... |
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 014
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
c = float(input('Informe a temperatura em °C: '))
f = c * 9 / 5 + 32
print(f'A temperatura de {c}°C corresponde a {f:.1f}°F')
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Obrigado ... |
#!/usr/bin/python
# related: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
class Worker():
SUCCESS = 1
FAILURE = 2
def test(self):
return Worker.FAILURE
t = Worker()
t.test()
if (t.test() == Worker.FAILURE):
print("I got a failure status")
if (t... |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
def rescale_bbox(height, width, bbox):
""... |
# Copyright Notice:
# Copyright 2016-2019 DMTF. All rights reserved.
# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Interface-Emulator/blob/master/LICENSE.md
# Redfish Emulator Role Service.
# Temporary version, to be removed when AccountService goes dynamic
class AccountSe... |
# the highest score
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# or you can use the max() function
# max = max(student_scores)
highest = student_scores[0]
for index in range(0, len(stude... |
"""Constants used by the OpenMediaVault integration."""
DOMAIN = "openmediavault"
DEFAULT_NAME = "OpenMediaVault"
DATA_CLIENT = "client"
ATTRIBUTION = "Data provided by OpenMediaVault integration"
DEFAULT_HOST = "10.0.0.1"
DEFAULT_USERNAME = "admin"
DEFAULT_PASSWORD = "openmediavault"
DEFAULT_DEVICE_NAME = "OMV"
DEF... |
# -*- coding: utf-8 -*-
# These are found in Repack-MPQ/fileset.{locale}#Mods#Core.SC2Mod#{locale}.SC2Data/LocalizedData/Editor/EditorCategoryStrings.txt
# EDSTR_CATEGORY_Race
# EDSTR_PLAYERPROPS_RACE
# The ??? means that I don't know what language it is.
# If multiple languages use the same set they should be comma s... |
class Solution(object):
def singleNumber(self, nums):
diff = reduce(lambda x, y: x ^ y, nums, 0)
diff &= -diff
res = [0, 0]
for num in nums:
res[num & diff == 0] ^= num
return res |
# Clase libro | libro() significa heredar de otra clase --> libro(biblioteca) | hijo(padre).
class libro:
# Contructor de libro, con las variables introducidas | __XX = privado
def __init__(self, isbn = "", titulo = "", autor = "", genero = "", portada = "", sinopsis = "", ejemplares = 0):
self._... |
def powerset_of_set(aset):
set_list = [x for x in aset]
final_set = set()
for catchnum in range(len(set_list)):
print(catchnum)
for index in range(catchnum, len(set_list)):
b = "{}".format(set_list[index:])
if b not in final_set:
final_set.add(b)
... |
# Fungsi enkripsi
def encrypt(plain,password):
plainIntVector = []
for i in range(len(plain)):
plainIntVector.append(ord(plain[i]))
passwordIntVector = []
# inisiasi variabel baru untuk membuat setiap perubahan yang terjadi pada
# password akan menyebabkan avalanche effect
# variabel in... |
class solve_day(object):
with open('inputs/day08.txt', 'r') as f:
data = f.readlines()
data = [d.strip() for d in data]
def part1(self):
accumulator = 0
i = 0
index_tracker = []
index_visited = set()
index_tracker.append(i)
index_visited.add(i... |
class Marker(object):
def __init__(self):
self._body = None
def make(self):
raise NotImplementedError
def update(self, marker):
pass
def show(self):
if self._body is None:
self._body = self.make()
self.update(self._body)
def hide(self):
... |
"""
Дан список my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], выведите все элементы, которые меньше 5.
"""
my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in my_list:
if i < 5:
print(i)
|
# Bubble Sort-values of a dictionary as a list
#Time Complexity = O(N)
def bubbleSort(k):
for i in range(1,len(k)):
for j in range(len(k)-i):
if k[j] > k[j+1]:
k[j],k[j+1] = k[j+1],k[j]
return k
dict = {"a":1, "c":3, "f":6, "e":5, "d":4, "b":2}
k = list(dict.values())
prin... |
class Dog:
def eat(self, food):
print(self.color, '的', self.kinds, '正在吃', food)
dog1 = Dog()
dog1.kinds = '京巴'
dog1.color = '白色'
dog1.color = '黄色' # this line will overwrite the color-attribute of dog1
dog1.eat('骨头')
dog2 = Dog()
dog2.kinds = '牧羊犬'
dog2.color = '灰色'
dog2.eat('屎') |
saisie_debut = input("le debut :")
debut = int(saisie_debut)
#si l'utilisateur saisit un chiffre impair
if debut % 2 != 0 :
debut += 1
saisie_fin = input("la fin :")
fin = int(saisie_fin)
indice = 1
for elem in range(debut, fin, 2):
print("element ", indice," = ", elem)
indice += 1
|
var = """A multi-line
docstring"""
var = """A multi-line
docstring
"""
|
# -*- coding: utf-8 -*-
"""Top-level package for Python Missing Data Strategies."""
__author__ = """Aris Tritas"""
__email__ = "a.tritas@gmail.com"
__version__ = "0.0.1"
imputation_strategies = ("mean", "median", "most_frequent", "infer", "fill")
|
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2020
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terce... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 7 10:17:36 2020
@author: teja
"""
s = '12asdbkFWS(#@!qde'
cn = 0
ca = 0
cspl = 0
for i in range(len(s)):
if s[i].isalpha():
ca+=1
elif s[i].isnumeric():
cn+=1
else:
cspl+=1
print(str(cn) + " " + str(ca) + " " + str(cspl) + " ") |
#faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possiveis sobre ela
b = input("digite algo ")
print(" o tipo primitivo desse valor é: ", type(b))
print("so tem espaços?", b.isspace())
print(" é um número ? ",b.isnumeric())
print(" é um alfabeto ?", b.isa... |
SMTP_SERVICE_BLOCK = 'smtp-service'
SMTP_HOST = 'smtp_host'
SMTP_PORT = 'smtp_port'
SMTP_USERNAME = 'smtp_username'
SMTP_PASSWORD = 'smtp_password'
SMTP_USE_TLS = 'smtp_use_tls'
SMTP_LEVEL = 'smtp_level'
SMTP_DEFAULT_VALUES = {
SMTP_HOST: '127.0.0.1',
SMTP_PORT: '25',
SMTP_USERNAME: None,
SMTP_PASSWORD... |
"""Constants for pyskyqremote."""
# SOAP/UPnP Constants
SKY_PLAY_URN = "urn:nds-com:serviceId:SkyPlay"
SKYCONTROL = "SkyControl"
SOAP_ACTION = '"urn:schemas-nds-com:service:SkyPlay:2#{0}"'
SOAP_CONTROL_BASE_URL = "http://{0}:49153{1}"
SOAP_DESCRIPTION_BASE_URL = "http://{0}:49153/description{1}.xml"
SOAP_PAYLOAD = """<... |
# 输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。
#
#
#
# 示例:
#
# 给定一个链表: 1->2->3->4->5, 和 k = 2.
#
# 返回链表 4->5.
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注... |
"""
Создайте лямбда-функцию по следующему описанию:
Введите строку с клавиатуры. Удалите из нее все буквы алфавита, идущие после буквы "и".
Подсказка: воспользуйтесь генератором. Вы можете сравнивать буквы как числа. Чем дальше
буква в алфавите, тем она "больше".
"""
my_string = input("Введите строку: ")
new_string = ... |
'''
Little Jhool and psychic powers
Little Jhool always wanted to have some psychic powers so that he could showoff his skills, and magic to people and impress them. (Specially, his girlfriend Big Jhool!) But, in spite all his efforts, hardwork, dedication, Googling, watching youtube videos he couldn't garner any psyc... |
"""
if elif else
"""
NUMBER = 17
value = int(input("input a value: "))
if value == NUMBER:
print("Winner!!!")
elif value > NUMBER:
print("your number is greater")
else:
print("your number is lower")
|
class ValidatedDictLike:
"""
This a dict with a `validate` method that may raise any exception.
The dict it validation on initialization and any time its contents
are changed. If a change is illegal, it is reverted an the exception
from `validate` is raised. Thus, it is impossible to put the dict
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Defines constants for use in the performance testing framework."""
class DataTypes:
"""Data types"""
TABULAR = 'tabular'
IMAGE = 'image'
TEXT = 'text'
class Algorithms:
"""Algorithms"""
SVM = ... |
def test_logout(ui):
driver = ui.driver
driver.find_element_by_css_selector(".user-dropdown").click()
driver.find_element_by_css_selector(".logout-button").click()
assert driver.find_element_by_css_selector('.login-form')
def test_recorded_sessions_visible(ui_session):
assert ui_session is not Non... |
#
# @lc app=leetcode.cn id=14 lang=python3
#
# [14] 最长公共前缀
#
# https://leetcode-cn.com/problems/longest-common-prefix/description/
#
# algorithms
# Easy (32.10%)
# Total Accepted: 59.9K
# Total Submissions: 185.1K
# Testcase Example: '["flower","flow","flight"]'
#
# 编写一个函数来查找字符串数组中的最长公共前缀。
#
# 如果不存在公共前缀,返回空字符串 ""。
... |
#!/usr/bin/env python
#coding: utf-8
class CMake(object):
def __init__(self, cmake_version='3.15', project_name='project', tab=' '):
self.txt = []
self.txt.append('CMAKE_MINIMUM_REQUIRED(VERSION {:s})'.format(cmake_version))
self.txt.append('')
self.txt.append('project({:s})'.forma... |
# -*- encoding: utf-8 -*-
"""
constant
储存各种常量,保证常量的统一性
"""
DEFAULT_SPEED = 120 # 默认速度
DEFAULT_TONE = "Sine" # 默认音色
DEFAULT_VOLUME = 0.02 # 默认音量
MAX_VOLUME = 1.0 # 最大音量
MIN_VOLUME = 0.0 # 最小音量
NO_LENGTH = -1 # 用来表示当前音乐没有长度的标记
def getBeatLengthBySpeed(speed): # 根据当前的速度,计算每一拍... |
user_input = 999
while user_input != "0":
user_input = input("십진수 숫자를 입력해주세요 : ")
try:
decimal_number = int(user_input)
print(bin(decimal_number))
except ValueError as e:
print(e)
print("Error - 10진수 숫자만 입력해주시기 바랍니다.")
|
d = {}
x = input('Please enter your name: ') # נשמור במשתנה name את הערך מהמשתמש
d['Name'] = x # {'Name' : 'David'}
d['Name'] = x + x # {'Name' : 'DavidDavid'} עידכנו את הערך השייך למפתח
print(d.get('Name'))
|
"""
https://github.com/parzival-roethlein/prmaya
# DESCRIPTION
Manage objectSet members (add, remove, reorder, export, import)
# USAGE
import prmaya.scripts.prObjectSetUi.utils
prmaya.scripts.prObjectSetUi.utils.ui()
# TODO
- export / import members
- avoid unwanted maya behavior (clean solutions only possible with ... |
texts = {
# App
'app.description': 'A toolkit for configuring X-Road security servers',
'app.label': 'xrdsst',
# Root application parameters
'root.parameter.configfile.description': "Specify configuration file to use instead of default 'config/xrdsst.yml'",
# Controllers
'auto.controller.d... |
def longest_palindromic_substring(s):
t = '^#'+'#'.join(s)+'#$'
n = len(t)
p = [0]*n
c = r = cm = rm = 0
for i in range (1, n-1):
p[i] = min(r-i, p[2*c-i]) if r > i else 0
while t[i-p[i]-1] == t[i+p[i]+1]: p[i] += 1
if p[i]+i > r: c, r = i, p[i]+i
... |
def stringCompression(string=''):
'''
Solution 1
Complexity Analysis
O(n) time | O(1) space
Perform basic string compression
string: string
return: string
'''
# Gracefully handle type and Falsy values
if (not isinstance(string, str) or string == ''):
print('Arguments s... |
# create a Blender service, we'll call it ... blender
blender = Runtime.start("blender","Blender")
# connect it to Blender - blender must be running the Blender.py
# or easier yet, start blender with the Blender.blend file
# select game mode then press p with cursor over the rendering screen
if not blender.connect():
... |
class Candidate:
_inner_id = 0
def __init__(self, name=""):
self._id = Candidate._inner_id
self.name = name
Candidate._inner_id += 1
CandidateList.append(self)
@staticmethod
def reset_id():
Candidate._inner_id = 0
class CandidateList:
"""
CandidateList... |
class CloudWatchEvent:
def __init__(self,
schedule_expression: str,
is_active: bool,
name: str =None):
self.name = name
self.schedule_expression = schedule_expression
self.is_active = is_active
|
# increasing paths in an array
def f1_3(array): # O(N^2)
if len(array) <= 1:
return
ans = []
start_idx, idx = 0, 1
prenum = array[start_idx]
while idx < len(array):
if array[idx] >= prenum:
for i in range(start_idx, idx):
ans.append(array[i:idx + 1])... |
class Movie(object):
def __init__(self):
self.title = ""
self.id = ""
self.plot = ""
self.year = ""
def __str__(self):
return str(self.__dict__)
|
'''2. Write a Python program that accepts six numbers as input and sorts them in descending order.
Input:
Input consists of six numbers n1, n2, n3, n4, n5, n6 (-100000 = n1, n2, n3, n4, n5, n6 = 100000). The six numbers are separated by a space.
Input six integers:
15 30 25 14 35 40
After sorting the said integers:
40 ... |
def list_squared(m, n):
data=[[1, 1], [42, 2500], [246, 84100],[287, 84100],[728, 722500], [1434, 2856100], [1673, 2856100], [1880, 4884100],[4264, 24304900],[6237, 45024100], [9799, 96079204], [9855, 113635600]]
result=[]
index=0
while True:
if m<=data[index][0]<=n:
result.append(da... |
# Array, two pointers
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height or len(height) < 3:
return 0
left_max = right_max = 0
ans = left = 0
right = len(height) - 1
while left < right:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.