content stringlengths 7 1.05M |
|---|
"""
Manipulating lists
"""
# numlist = [1, 2, 3, 4, 5]
#
# print(numlist)
#
# numlist.reverse()
# print(numlist)
#
# numlist.sort()
# print(numlist)
#
# for num in numlist:
# print(str(num))
#
# mystring = 'julian'
# mystring_list = list(mystring)
# print(mystring_list)
#
# print(mystring_list[4])
# print(mystring... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 17:56:31 2020
@author: super
"""
|
#Collaborators: None
def rerun(): #Function is here to rerun the program for total of two times
y = 0
while y<2:
yogurtshack()
y += 1
def yogurtshack():
print("Welcome to Yogurt Shack! Please type your order below. ") #Introducing the store and asking for order
print("\n")
fla... |
# coding: utf-8
"""
Demo package.
"""
__version__ = "0.1"
__author__ = "Xavier Dupré"
|
"""
* Factorial of a Number
* Create a program to find the factorial of an integer entered by the user.
* The factorial of a positive integer n is equal to 1 * 2 * 3 * ... * n. For example, the factorial of 4 is 1 * 2 * * 3 * 4 which is 24.
* Take an integer input from the user and assign it to the variable n. We w... |
def print_fun():
print("Heloo")
class bala:
Name = "This is Shifat"
def shit(self):
print("Say my name !")
print("I'm in a class")
def __str__(self):
return self.Name |
"""
Implements a dependency tree. Indices are 1-based.
"""
class Node:
def __init__(self, pair, index):
self.parent_index_, self.label_ = pair.split('/')
self.parent_index_ = int(self.parent_index_)
self.index_ = int(index)
self.parent_ = None
self.children_ = []
def pa... |
'''
This module represents the time stamp when Arelle was last built
@author: Mark V Systems Limited
(c) Copyright 2013 Mark V Systems Limited, All rights reserved.
'''
version = '2013-10-08 05:43 UTC'
|
pedidos = []
def adicionaPedidos(nome, sabor, observacao='None'):
pedido = {}
pedido['nome'] = nome
pedido['sabor'] = sabor
pedido['observacao'] = observacao
return (pedido)
pedidos.append(adicionaPedidos('mario', 'pepperoni'))
pedidos.append(adicionaPedidos('marco', 'portuguesa', 'dobro de presu... |
"""
Ejercicio 20
Un comerciante de computadores ofrece P precio por compra al contado ó 12 cuotas de T COP cada una. Desarrolle
un programa para calcular y mostrar cuál es el porcentaje que se cobra por el recargo en el pago del computador
por cuota.
Entradas
Precio_Compra_Contado --> Float --> P_C_C
Precio_Cuotas -->... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftPAR_ABREPAR_CIERRArightIGUALleftORleftANDleftNO_IGUALnonassocMAYORMENORMAYOR_IGUALMENOR_IGUALleftMASMENOSleftASTERISCODIVISIONMODULOleftPOTENCIArightNOTleftLLAVE_AB... |
# -*- coding: utf-8 -*-
"""
PMLB was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- William La Cava (lacava@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- and many more generous open source contributors
Permission is hereby granted, free of charge, ... |
"""
Define exceptions and warnings for DyNe
Created by: Ankit Khambhati
Change Log
----------
2016/03/10 - Generated __all__ definition
"""
__all__ = ['PipeTypeError',
'PipeLinkError']
class PipeTypeError(TypeError):
"""
Exception class if pipe type is not of a registered type
"""
class Pip... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021-10-23 10:13:19
# @Author : iamwm
class Store:
"""
global shared context
"""
def __init__(self, cls) -> None:
self.class_type = cls
self.context = {}
def get(self, name: str, *args, **kwargs):
"""
get... |
#pangram - sentence with all alphabets
#example - The quick brown fox jumps over the lazy dog
#read the input
myStr = input("Enter a sentence: ").lower()
#eliminating all the spaces
myStr = myStr.replace(" ", "")
#eliminating all commonly used special characters
myStr = myStr.replace("," , "")
myStr = myStr.replace("... |
class UnitGroup(Enum, IComparable, IFormattable, IConvertible):
"""
A group of related unit types,primarily classified by discipline.
enum UnitGroup,values: Common (0),Electrical (3),Energy (5),HVAC (2),Piping (4),Structural (1)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx._... |
__all__ = ["Roll"]
class Roll:
pass
|
class ApiHttpRequest:
GET_METHOD = 'GET'
POST_METHOD = 'POST'
HTTP_METHODS = [GET_METHOD, POST_METHOD]
def __init__(self, api_http_request_method: str, api_url: str, api_http_request_headers: dict = None,
api_http_request_body: str = None) -> None:
self._method = api_http_requ... |
# This code reads a text file from user input, finds words and sorts them by unique count then alphabetically.
# C++ version is named "sortwords.cpp" and uses no built-in maps.
# Dict is like std::map in C++
result = dict()
# Count total number of words
totalWords = 0
for line in open(input("Enter the filename:... |
# Everything in this file is sampled by a Vivado 2019.2
# Recap of variables in this file for convenience
parts = []
# help command stripped of everything except -directive paragraph
place_directives_paragraph = ""
route_directives_paragraph = ""
synth_directives_paragraph = ""
# full help command output
help_synth... |
# https://www.hackerrank.com/challenges/crush/problem?isFullScreen=true
def reduce_x(a, b, c):
mod = 1000000007
return a % mod, b % mod, c % mod
# Main Method
if __name__ == '__main__':
n, m = map(int, input().split())
arr = [0] * (n + 2)
for _ in range(m):
a, b, k = map(int... |
# coding=utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License")... |
#-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Stephan Krause <stephan.krause@eox.at>
# Stephan Meissl <stephan.meissl@eox.at>
#
#-------------------------------------------------------------------------------
# Copyrigh... |
# Exercício Python 17: Escreva um programa que leia dois números inteiros e compare-os. mostrando na tela uma mensagem:
#O primeiro valor é maior
#O segundo valor é maior
#Não existe valor maior, os dois são iguais
n1 = int(input('Insira um número inteiro: '))
n2 = int(input('Insira outro número inteiro: '))
maior = 0... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 3 11:46:11 2018
@author: Simon
"""
def bubble_sort_reverse(array):
bubble_sort(array, lambda x, y: x < y)
def bubble_sort(array, comparator=lambda x, y: x>y):
"""
Sorts an array using a bubble sort algorithm
Inputs:
array: the list to sort
... |
print('======= Desafio 03 =========')
num1 = input('Digite um numero ')
num2 = input('Digite outro para soma ')
soma = float(num1) + float(num2)
print('A soma entre {} e {}, é {}'.format(num1, num2, soma))
print('======= Desafio 04 =========')
n = input('Digite Algo: ')
print(type(n))
if n.isalnum() == True:
print... |
def calcManhattanDist(x1, y1, x2, y2) -> float:
return abs(x1 - x2) + abs(y1 - y2)
def main():
print(calcManhattanDist(2, 5, 10, 14))
if __name__ == "__main__":
main() |
class EventNotFound(Exception):
"""Handles invalid event type provided to
publishers
Attributes:
event_type --> the event that's invalid
message --> additional message to log or print
"""
def __init__(self, event_type: str, message: str ="invalid event"):
... |
def collatz(n):
seq = [n]
while n != 1:
if n % 2 == 0:
n = n / 2
seq.append(int(n))
else:
n = 3 * n + 1
seq.append(int(n))
return len(seq)
i = 1
seqs = []
dictich = {}
while i < 1000000:
length = collatz(i)
dictich[le... |
# DEVELOPER NOTES:
# Copy this file and rename it to config.py
# Replace your client/secret/callback url for each environment below with your specific app details
# (Note: local is mainly for BB2 internal developers)
ConfigType = {
'production' : {
'bb2BaseUrl' : 'https://api.bluebutton.cms.gov',
'... |
# Curso Python 10
# ---Desafio 31---
# Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule
# o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e
# $0,45 parta viagens mais longas.
dist = float(input('Qual a distância da viagem? '))
if dist <= 200:
print(f'Para a viagem... |
class prm:
std = dict(
field_color="mediumseagreen",
field_markings_color="White",
title_color="White",
)
pc = dict(
field_color="White", field_markings_color="black", title_color="black"
)
field_width = 1000
field_height = 700
field_dim = (106.0, 68.0)
... |
assert gradiente('rojo', 'azul') == gradiente('rojo', 'azul')
assert gradiente('rojo', 'azul', inicio='centro') == gradiente('rojo', 'azul')
assert gradiente('rojo', 'azul', inicio='izquierda') == gradiente('rojo', 'azul', inicio='izquierda')
assert gradiente('rojo', 'azul') != gradiente('rojo', 'azul', inicio='izquie... |
# -*- coding: utf-8 -*-
# @Time : 2021/1/1111 7:46 PM
# @Author : agrroc
# @File : py_3_2.py
# 首先输入一个整数 n ,然后程序连续接受输入 n 个数字,最终程序输出 n 个数字的平均值。
n = int(input()) # 输入一个数
total = 0.0
for i in range(n): # 连续输入n个数字
total += float(input())
print(total / n)
|
def foo(y):
x = 5
x / y
def bar():
foo(0)
bar()
|
#tipos de triângulo
seg1 = float(input('Primeiro segmento: '))
seg2 = float(input('Seguno segmento: '))
seg3 = float(input('Terceiro segmento: '))
if seg1 < seg2 + seg3 and seg2 < seg1 + seg3 and seg3 < seg1 + seg2:
print('Podemos formar um triângulo ' , end= (''))
if seg1 == seg2 == seg3:
print('EQUILÁ... |
class Error(Exception):
def __init__(self, message, error):
self.message = message
self.error = error
@property
def code(self):
return 503
@property
def name(self):
return self.__class__.__name__
@property
def description(self):
return self.message
... |
def sixIntegers():
print("Please enter 6 integers:")
i = 0
even = 0
odd = 0
while i < 6:
try:
six = input(">")
six = int(six)
i += 1
if (six % 2) == 0:
even = even + six
elif (six % 2) == 1:
odd = od... |
class YLBaseServer(object):
def name(self):
pass
def handle(self, args):
pass
def startup(self, *args):
pass
def stop(self, *args):
pass
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#
# SYNTAX_DICT is a dictionary representation of operators and other constants of the DSL language
#
#
SYNTAX_DICT = {
'allowed_starts_special_commands': {
'help' : [],
'.docs' : [],
'quit' : [],
'.show' : [],
'.json_compact' :... |
"""
Status codes for Andor cameras.
"""
# Status code -> status message
ANDOR_CODES = {
20001: "DRV_ERROR_CODES",
20002: "DRV_SUCCESS",
20003: "DRV_VXDNOTINSTALLED",
20004: "DRV_ERROR_SCAN",
20005: "DRV_ERROR_CHECK_SUM",
20006: "DRV_ERROR_FILELOAD",
20007: "DRV_UNKNOWN_FUNCTION",
20008... |
#!/usr/local/bin/python3
def checkDriverAge(age=0):
# if not age:
# age = int(input('What is your age?: '))
if int(age) < 18:
print('Sorry, you are too young to drive this car '
'Powering off!')
elif int(age) > 18:
print('Powering On. Enjoy the ride!')
elif int(ag... |
#!/usr/bin/env python3
#encoding=utf-8
#---------------------------------------
# Usage: python3 5-tracer1.py
# Description: Recall from Chapter 30 that the __call__ operator overloading
# method implements a function-call interface for class instances.
# The following code uses this to def... |
class Artist:
def __init__(self, name = 'None', birthYear = 0, deathYear = 0):
self.name = name
self.BirthYear = birthYear
self.deathYear = deathYear
def printInfo(self):
if self.deathYear == str('alive'):
print('Artist: {}, born {}'.format(self.name, self.BirthYear))... |
alert_failure_count = 0
MAX_TEMP_ALLOWED_IN_CELCIUS = 200
def network_alert_stub(celcius):
print(f'ALERT: Temperature is {celcius} celcius')
if(celcius <= MAX_TEMP_ALLOWED_IN_CELCIUS):
# Return 200 for ok
return 200
else:
# Return 500 for not-ok
return 500
def network_a... |
print(' GERADOR DE P.A. ')
print('='*30)
primeiro = int(input('Primeiro termo: '))
razão = int(input('Razão: '))
cont = 1
while cont <= 10:
print(f'{primeiro}', end=' -> ')
primeiro += razão
cont += 1
print('THE END')
|
'''
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
Input:
[1,2,3]
Output:
2
Explanation:
Only two... |
"""
.. module:: reaction_message
:platform: Unix
:synopsis: A module that describes what the reaction should be when receiving a specific message.
.. Copyright 2022 EDF
.. moduleauthor:: Oscar RODRIGUEZ INFANTE, Tony ZHOU, Trang PHAM, Efflam OLLIVIER
.. License:: This source code is licensed under the MIT Li... |
class Spam(object):
def __init__(self, count):
self.count = count
def __eq__(self, other):
return self.count == other.count
|
class Node:
def __init__(self, data=None, pointer=None):
self.data = data
self.pointer = pointer
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_pointer(self, pointer):
self.pointer = pointer
def get_pointer(self):
... |
how_many_snakes = 1
snake_string = """
Bem-vindo ao Python3!
____
/ . .\\
\ ---<
\ /
__________/ /
-=:___________/
<3, Philip e Charlie
"""
print(snake_string * how_many_snakes)
|
ACADEMY_COMING = 'coming'
ACADEMY_ARCHIVE = 'archive'
ACADEMY_LIVE = 'live'
ACADEMY_STATUS_CHOICES = (
(ACADEMY_COMING, 'coming'),
(ACADEMY_ARCHIVE, 'archive'),
(ACADEMY_LIVE, 'live')
)
ACADEMY_CATEGORY_CTF = 'Capture The Flag'
ACADEMY_CATEGORY_NETWORK = 'Сүлжээний аюулгүй байдал'
ACADEMY_CATEGORY_WEB = '... |
def open_group(group, path):
"""Creates or loads the subgroup defined by `path`."""
if path in group:
return group[path]
else:
return group.create_group(path)
|
print('=' * 12 + 'Desafio 48' + '=' * 12)
soma = 0
numeros = 0
print('A soma entre os ímpares múltiplos de 3 entre 1 e 500 é:')
for i in range(1, 501, 2):
if i % 3 == 0:
soma += i
numeros += 1
print(f'{soma} -> Resultado da soma de {numeros} números!')
|
'''
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there is such w... |
def test_message_create_list(test_client, version_header):
payload = {"subject": "heyhey", "message": "testing"}
create_response = test_client.post(
"/messages",
json=payload,
headers=version_header
)
assert create_response.status_code == 201
response = test_client.get("/me... |
# 11. Write a program that asks the user to enter a word that contains the letter a. The program
# should then print the following two lines: On the first line should be the part of the string up
# to and including the the first a, and on the second line should be the rest of the string. Sample
# output is shown below:... |
#!/usr/bin/env python
# coding: utf-8
# # 모음 자료형 1편
# **모음**<font size="2">collection</font> 자료형은
# 여러 개의 값을 하나로 묶어 놓은 값의 유형이다.
# 파이썬은 문자열, 리스트, 튜플, 집합, 사전 등의 모음 자료형을
# 기본으로 제공하며,
# 여러 값을 묶어 둔다는 의미로 모음 자료형의 값을
# **컨테이너**<font size="2">container</font>라고도 부른다.
#
# 모음 자료형은 크게 두 종류로 나뉜다.
#
# - 순차형<font size="2">sequen... |
'''
The floor number we can check given m moves and k eggs.
dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1
'''
class Solution:
def superEggDrop(self, K: int, N: int) -> int:
dp = [0] * (K + 1)
m = 0
while dp[K] < N:
for k in range(K, 0, -1):
dp[k] = dp[k - 1] + d... |
###################################################################################################################
## Risanje grafa
#
# Program narisi_graf_5_2.py naredi datoteko graf_5_2.dot, ki predstavlja graf vseh možnih potez in pozicij v igri.
#
# POZOR! Datoteka graf_5_2.dot se odpira približno 30 minut.
#
###... |
def dfs(node,parent,ptaken):
if dp[node][ptaken]!=-1:
return dp[node][ptaken]
taking,nottaking=1,0
total=0
tways
for neig in graph[node]:
if neig!=parent:
taking+=dfs(neig,node,1)
nottaking+=dfs(neig,node,0)
if ptaken:
dp[node][ptaken]=min(taking,nottaking)
else:
dp[node][ptaken]=taking
return dp... |
# Vicfred
# https://atcoder.jp/contests/abc154/tasks/abc154_a
# simulation
s, t = input().split()
a, b = list(map(int, input().split()))
u = input()
balls = {}
balls[s] = a
balls[t] = b
balls[u] = balls[u] - 1
print(balls[s], balls[t])
|
class Solution:
def longestPalindrome(self, s: str) -> str:
def expand(left:int, right:int) -> str:
while left >= 0 and right <= len(s) and s[left] == s[right-1]:
left -= 1
right += 1
return s[left+1 : right-1]
if len(s) < 2 or s == s[... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "David S. Batista"
__email__ = "dsbatista@inesc-id.pt"
class Seed(object):
def __init__(self, _e1, _e2):
self.e1 = _e1
self.e2 = _e2
def __hash__(self):
return hash(self.e1) ^ hash(self.e2)
def __eq__(self, other):
... |
CONFIG = {
'file_gdb': 'curb_geocoder.gdb',
'input': {
'address_pt': 'ADDRESS_CURB_20141105',
'address_fields': {
'address_id': 'OBJECTID',
'address_full': 'ADDRESS_ID',
'poly_id': 'OBJECTID_1',
},
'streets_lin': 'STREETS_LIN',
'streets_fields': {
'street_name': 'STNAME',
'left_from': 'L_F_... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
bottomleft=root.val
stack=[(... |
#
# PySNMP MIB module AISPY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AISPY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:00:57 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... |
class OrangeRicky():
def __init__(self, rotation):
self.colour = "O"
self.rotation = rotation
if rotation == 0:
self.coords = [[8, 0], [8, 1], [7, 1], [6, 1]]
elif rotation == 1:
self.coords = [[8, 2], [7, 2], [7, 1], [7, 0]]
elif rotat... |
"""
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
You are giving candies to these children subjected to the following requirements:
-Each child must have at least one candy.
-Children with a higher rating get more candies than their neighbors.
Return ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
queue=... |
class AppMetricsError(Exception):
pass
class InvalidMetricsBackend(AppMetricsError):
pass
class MetricError(AppMetricsError):
pass
class TimerError(AppMetricsError):
pass
|
# 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... |
def get_tensor_shape(tensor):
shape = []
for s in tensor.shape:
if s is None:
shape.append(s)
else:
shape.append(s.value)
return tuple(shape)
|
class InstaloaderException(Exception):
"""Base exception for this script.
:note: This exception should not be raised directly."""
pass
class QueryReturnedBadRequestException(InstaloaderException):
pass
class QueryReturnedForbiddenException(InstaloaderException):
pass
class ProfileNotExistsExc... |
#!/usr/bin/python3
f = open("day8-input.txt", "r")
finput = f.read().split("\n")
finput.pop()
def get_instruction_set():
instruction_set = []
for i in finput:
instruction_set.append({
"instruction" : i.split(' ')[0],
"value": int(i.split(' ')[1]),
"order": []
... |
num = []
par = []
impar = []
for i in range(20):
num.append(float(input()))
print(num)
for i in num:
if i % 2 == 0:
par.append(i)
else:
impar.append(i)
print(par)
print(impar)
|
data = '/home/tong.wang001/data/TS/textsimp.train.pt'
save_model = 'textsimp'
train_from_state_dict = ''
train_from = ''
curriculum = True
extra_shuffle = True
batch_size = 64
gpus = [0]
layers = 2
rnn_size = 500
word_vec_size = 500
input_feed = 1
brnn_merge = 'concat'
max_generator_batches = 32
epochs = 13
start_epoch... |
#!/usr/bin/python3
count = 0
with open('./input.txt', 'r') as input:
list_lines = input.read().split('\n\n')
for line in list_lines:
count += len({i:line.replace("\n", "").count(i) for i in line.replace("\n", "")})
print(count)
input.close() |
h, n = map(int, input().split())
a = []
b = []
for _ in range(n):
ai, bi = map(int, input().split())
a.append(ai)
b.append(bi)
dp = [float("inf")] * (h + 1)
dp[0] = 0
for i in range(h):
for j in range(n):
index = min(i + a[j], h)
dp[index] = min(dp[index], dp[i] + b[j])
print(dp[h])
|
test = { 'name': 'q5',
'points': 3,
'suites': [ { 'cases': [ {'code': '>>> abs(kg_to_newtons(100) - 980) < 0.000001\nTrue', 'hidden': False, 'locked': False},
{'code': '>>> abs(kg_to_newtons(3) - 29.4) < 0.000001\nTrue', 'hidden': False, 'locked': False},
... |
__author__ = 'Alex Gusev <alex@flancer64.com>'
"""
Функция состоит из имени и количества параметров к обработке.
"""
class Function(object):
def __init__(self, name, args_count=2):
self._name = name
self._args_count = args_count
@property
def name(self):
return self._name
@na... |
# 04 February 2018 Functions
# Define function using def()
def ratio(x,y):
"""The ratio of 'x' to 'y'."""
return x/y
# Define function that always returns the same thing
def IReturnOne():
"""This returns 1"""
return 1
print(ratio(4,2))
print(IReturnOne())
# Function without return argument
def thin... |
PROCESS_NAME_SET = None
PROCESS_DATA = None
SERVICE_NAME_SET = None
SYSPATH_STR = None
SYSPATH_FILE_SET = None
SYSTEMROOT_STR = None
SYSTEMROOT_FILE_SET = None
DRIVERPATH_STR = None
DRIVERPATH_FILE_SET = None
DRIVERPATH_DATA = None
PROFILE_PATH = None
USER_DIRS_LIST = None
HKEY_USERS_DATA = None
PROGRAM_FILES_STR = No... |
#!/usr/bin/env python
# coding: utf-8
# # Rabbits and Recurrence Relations
# ## Problem
#
# A sequence is an ordered collection of objects (usually numbers), which are allowed to repeat. Sequences can be finite or infinite. Two examples are the finite sequence (π,−2‾√,0,π) and the infinite sequence of odd numbers (1,... |
class ShoppingCartItem:
def __init__(self, id, name, price, quantity):
self.id = id
self.name = name
self.price = price
self.quantity = quantity
@property
def total_price(self):
return self.price * self.quantity |
def sort_(arr, temporary=False, reverse=False):
# Making copy of array if temporary is true
if temporary:
ar = arr[:]
else:
ar = arr
# To blend every element
# in correct position
# length of total array is required
length = len(ar)
# After each iteration ... |
def tagWithMostP(dom, tagMaxP=None):
for child in dom.findChildren(recursive=False):
if child and not child.get('name') == 'p':
numMaxP = 0
if tagMaxP:
numMaxP = len(tagMaxP.find_all('p', recursive=False))
numCurrentP = len(child.find_all('p', recursive=Fa... |
a = [3, 8, 5, 1, 8, 9, 4, 9, 6, 4, 3, 7]
b = list (set (a))
for i in range (len(b)):
for j in range (i+1,len (b)):
if b[i]>b[j]:
b[i] , b[j] = b[j], b[i]
print (b) |
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
bulls = 0
cows = 0
length = len(secret)
indexCounted = []
for index in range(0, length):
if secret[index] == g... |
x = int(input())
case = list(map(int, input().split()))
reverse_case = case[::-1]
increase = [1 for i in range(x)] # 가장 긴 증가하는 부분 수열
decrease = [1 for i in range(x)] # 가장 긴 감소하는 부분 수열(reversed)
for i in range(x):
for j in range(i):
if case[i] > case[j]:
increase[i] = max(increase[i], increase... |
'''
第一个缺失正数
给出一个无序的数列,找出其中缺失的第一个正数,要求复杂度为 O(n)
如:[1,2,0],第一个缺失为3。 如:[3,4,-1,1],第一个缺失为2。
输入
1,2,0
输出
3
输入样例
1,2,0
3,4,-1,1
-1,-3,-5
1,2,3
-1,-10,0
输出样例
3
2
1
4
1
'''
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
def solution(line):
numList = list(map(int, line.strip().split(",")))
numList.sort()
... |
def get_input(path):
with open(path, 'r') as fh:
return fh.read().splitlines()
def isValid_part1(rule, password):
(r, c) = rule.split(" ")
(mini, maxi) = r.split("-")
num_of_occur = password.count(c)
if num_of_occur < int(mini) or num_of_occur > int(maxi):
return False
return T... |
def default():
return {
'columns': [
{'name': 'id', 'type': 'string'},
{'name': 'sku', 'type': 'object'},
{'name': 'name', 'type': 'string'},
{'name': 'type', 'type': 'string'},
{'name': 'kind', 'type': 'string'},
{'name': 'plan', 'type... |
"""Les ensembles en Python."""
X = set('abcd')
Y = set('sbds')
print("ensembles de depart".center(50, '-'))
print("X=", X)
print("Y=", Y)
suite = input('\nTaper "Entree" pour la suite')
print("appartenance".center(50, '-'))
print("'c' appartient a X ?", 'c' in X)
print("'a' appartient a Y ?", 'a' in Y)
... |
# Atstarpes ignorējam,un uzskatam ka lielais burts ir tikpat derīgs kā mazais, t.i. šeit A un a -> a
def is_pangram(mytext, a="abcdefghijklmnopqrstuvwxyz"):
return set(a) <= set(mytext.lower())
# mytext, a = set(mytext.lower()), set(a)
# return mytext >= a # or a <= mytext
print(is_pangram("The qui... |
"""
两种袋子,一种只能装 6 个苹果,一种只能装 8 个苹果,不能小于或者大于
给定 n 个苹果,求最小能用几个袋子装。例如 n=14,可以两个袋子各用一个
如果无法装满两个袋子,例如给了 9 个,返回 -1
n>=1
"""
def min_bags(n: int) -> int:
if n % 2 != 0:
# 奇数肯定装不了
return -1
# 26
# 3*8+2
bag6 = -1
bag8 = int(n / 8) # 下取整
rest = n - bag8 * 8
while bag8 >= 0 and (0 ... |
numbers=[]
while True:
number=input("Enter a number:")
if number=="done":
break
else:
number=float(number)
numbers.append(number)
continue
print("Maximum:",max(numbers))
print("Minimum:",min(numbers)) |
def g_load(file):
print("file {} loaded as BMP v2".format(file))
return None
if __name__ == "__main__":
print("Test Bmp.py")
print(g_load("test.bmp"))
|
# Description: Run the AODBW function from the pymolshortcuts.py file to generate photorealistic effect with carbons colored black and all other atoms colored in grayscale.
# Source: placeHolder
"""
cmd.do('cmd.do("AODBW")')
"""
cmd.do('cmd.do("AODBW")')
|
## Shorty
## Copyright 2009 Joshua Roesslein
## See LICENSE
## @url budurl.com
class Budurl(Service):
def __init__(self, apikey=None):
self.apikey = apikey
def _test(self):
#prompt for apikey
self.apikey = raw_input('budurl apikey: ')
Service._test(self)
def shrink(self, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.