content stringlengths 7 1.05M |
|---|
#String Ex1
#----------
### Work in your pynet_test repository ###
#a. Create a python script with three strings representing three names
#b. Print these three names out in a column 30 wide, right aligned
#c. Execute the script verify the output
#d. Add a prompt for a fourth name, print this out as well
#e. check yo... |
n1 = int(input('digite um numero: '))
n2 = int(input('digite um numero: '))
n3 = int(input('digite um numero: '))
menor = n1
maior =n1
if n2 > n1 and n2 > n3:
maior = n2
if n3 > n1 and n3 > n2:
maior = n3
if n2 < n1 and n2 <n3:
menor =n2
if n3 < n1 and n3 < n2:
menor = n3
print('{} é o maior numero ... |
'''
You are given an n x n 2D matrix representing an image,
rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you
have to modify the input 2D matrix directly. DO NOT
allocate another 2D matrix and do the rotation.
Example:
[[1,2,3], ... |
class Solution:
# One Pass (Accepted), O(n) time, O(1) space
def maxScore(self, s: str) -> int:
_max = cur = ones = 0
for i in range(1, len(s)-1):
if s[i] == '0':
cur += 1
_max = max(cur, _max)
else:
cur -= 1
... |
"""
Let's describe some attributes.
:var A: Alpha.
:var B: Beta.
:vartype B: bytes
:var C: Gamma.
:var D: Delta.
:var E: Epsilon.
:vartype E: float
"""
A: int = 0
B: str = "ŧ"
C: bool = True
D = 3.0
E = None
|
class Solution1(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for item in nums:
if item ==target:
return nums.index(target)
return -1
class Solution2(object):
def search(s... |
## Для даного числа n <100 закінчите фразу "На лузі пасеться ..." одним з можливих продовжень: "n корів", "n корова", "n корови", правильно схиляючи слово "корова".
##
## Формат введення
##
## Вводиться натуральне число.
##
## Формат виведення
##
## Програма повинна вивести введене число n і одне зі слів: korov, korova... |
#Sem usar 'for'
print('===== Verificação de Palíndromo =====')#Título
print()#Pular linha
cores = {'vermelho':'\033[1;31m','amarelo':'\033[1;33m'}#Cores
frase = str(input('Digite uma frase: ')).replace(' ','').lower() #Digitar uma frase
contr = frase[::-1]#Frase ao contrário
print(f'A frase "{frase.upper()}" ao contrá... |
# 759. Employee Free Time
# [759] Employee Free Time
# https://leetcode-cn.com/problems/employee-free-time/
# We are given a list schedule of employees, which represents the working time for each employee.
# Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
# Return th... |
K = 132
nominaly = [1, 2, 5, 10, 20, 50]
def change_making_greedy(K, nominaly):
nominaly.sort(reverse = True)
coins = []
for i in nominaly:
while K >= i:
coins.append(i)
K -= i
return coins
print(change_making_greedy(K,nominaly)) |
SPREADSHEET = "books_data"
SHEET_BOOKS = "Books"
SHEET_TODO = "TODO"
PATH_VBOOKS = "/Aplicaciones/vbooks"
COL_DATE = "Date"
COL_PAGES = "Pages"
COL_LANGUAGE = "Language"
COL_AUTHOR = "Author"
COL_SOURCE = "Source"
COL_OWNED = "Owned?"
STATUS_OWNED = "Owned"
STATUS_IN_LIBRARY = "In Library"
STATUS_NOT_OWNED = "Not Ow... |
class XYZAtom:
"""An atom record in an XYZ structure"""
def __init__(self, name, x, y, z):
self.chain = ""
self.resid = None
self.resname = ""
self.name = name
self.x = x
self.y = y
self.z = z
def read(infile):
"""Read an XYZ structure from a filenam... |
# Faça um algoritmo em Python que receba a média de um aluno e o número de exercícios extra-classe que realizou.
# O algorimto deverá exibir a nota do aluno e caso ele tenha realizado mais de 8 exercícios, esta nota devera ser acrescida em 1 ponto na média.
# Dados:
# media - ler
# nr exercicios realizados - ler
# pon... |
[
{
'date': '2016-01-01',
'description': "New Year's Day",
'locale': 'en-CA',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2016-02-15',
'description': 'Family Day',
'locale': 'en-CA',
'notes': '',
'region': 'AB'... |
#!/usr/bin/env python
#coding: utf-8
# VirusTotal
vt_key = ''
# MISP
misp_url = ''
misp_key = ''
misp_verifycert = False
# Twitter
consumer_key = ''
consumer_secret = ''
access_key = ''
access_secret = ''
# Slack
slack_channel = ''
slack_username = ''
slack_url = ''
|
class SkilletLoaderException(BaseException):
pass
class LoginException(BaseException):
pass
class PanoplyException(BaseException):
pass
class NodeNotFoundException(BaseException):
pass
|
MASTER = "127.0.0.1:7070"
ROUTER = "127.0.0.1:8080"
#MASTER = "11.3.146.195:443"
#ROUTER = "11.3.146.195"
|
# -*- coding: utf-8 -*-
"""062 - Progressão Aritmética v2
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1_o5XXKh0Ge_AYEklX_SKZ2g0R2GXpMba
"""
p = int(input('Informe o primeiro termo de uma PA: '))
r = int(input('Informe a razão da PA: '))
resultado ... |
def to_rna(dna_strand):
rna = []
for nuc in dna_strand:
if nuc == 'G':
rna.append('C')
elif nuc == 'C':
rna.append('G')
elif nuc == 'T':
rna.append('A')
elif nuc == 'A':
rna.append('U')
return "".join(rna)
|
def in_test(a, b=None):
if b in a or b is None:
print('yaeeee')
else:
print('oops')
a = [1, 2, 3]
in_test(a, 1)
in_test(a, 4)
in_test(a, None)
|
#
# @lc app=leetcode.cn id=120 lang=python3
#
# [120] triangle
#
None
# @lc code=end |
class Options:
def __init__(self, args: list):
assert isinstance(args, list)
self.args = args
def get(self, key: str, has_value: bool = True):
assert isinstance(key, str)
assert isinstance(has_value, bool)
if has_value:
if (key in self.args[:-1]) and (path_index := self.args[:-1].index(key)) and (val... |
class Solution(object):
def maximumWealth(self, accounts):
"""
:type accounts: List[List[int]]
:rtype: int
"""
banks = len(accounts[0])
cust = {}
for customer_id in range(len(accounts)):
cust[customer_id] = sum(accounts[customer_id])
return... |
"""
Создать новый класс Cat, который имеет все те же атрибуты что и Dog, только заменить метод bark на meow.
"""
class Cat:
def __init__(self, heigth, weight, name, age):
self.heigth = heigth
self.weight = weight
self.name = name
self.age = age
def jump(self):
print(f"... |
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331002300
# School for the Gifted :: 1-1 Classroom
sm.warpInstanceOut(331002000, 2) |
# 2020.09.04
# Problem Statement:
# https://leetcode.com/problems/add-binary/
class Solution:
def addBinary(self, a: str, b: str) -> str:
# make a to be the longer string
if len(a) < len(b):
a, b = b, a
# do early return
if a == "0": return b
if... |
def capitalize(string):
ans = ""
i = 0;
while i < len(string):
ans += string[i].upper()
i += 1
while i < len(string) and ord(string[i]) > 64:
ans += string[i]
i += 1
while i<len(string) and (ord(string[i]) == 32 or ord(string[i]) == 9):
ans += string[i]
i += 1
return ans
string = input()
capital... |
names_scores = (('Amy',82,90),('John',33,64),('Zoe',91,94))
for x,y,z in names_scores:
print(x)
print(y,z)
print('End') |
#
# PySNMP MIB module HP-SN-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-SN-MIBS
# Produced by pysmi-0.3.4 at Wed May 1 13:36:22 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,... |
""""
1. lambda:lambda是Python中一个很有用的语法,它允许你快速定义单行最小函数。类似于C语言中的宏,可以用在任何需要函数的地方
2. filter:filter函数相当于一个过滤器,函数原型为:filter(function,sequence),
表示对sequence序列中的每一个元素依次执行function,这里function是一个bool函数
3. map:map的基本形式为:map(function,sequence),是将function这个函数作用于sequence序列,然后返回一个最终结果序列
4. reduce:reduce函数的形式为:reduce(function,sequence,i... |
"""
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
"""
__author__ = 'Daniel'
class Solution:
def partition(self, s):
"""
:type s: str
:rtype: List[str]
"""
ret = []
self.ba... |
# secret key
SECRET_KEY = 'djangosSecretKey'
# development directory
DEV_DIR = '/path/to/directory/'
# private data
PRIVATE_DATA_STREET = 'Examplestreet 1'
PRIVATE_DATA_PHONE = '0123456789' |
#
# PySNMP MIB module CISCO-SESS-BORDER-CTRLR-CALL-STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SESS-BORDER-CTRLR-CALL-STATS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:55:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4... |
"""
Create three different variables the first variable should use all
lower case characters with underscore ( _ ) as the word separator.
The second variable should use all upper case characters with underscore as the word separator.
The third variable should use numbers, letters, and underscore, but still be a valid v... |
SECRET_KEY = 'test'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.sqlite',
}
}
INSTALLED_APPS = [
'nobot',
]
NOBOT_RECAPTCHA_PRIVATE_KEY = 'privkey'
NOBOT_RECAPTCHA_PUBLIC_KEY = 'pubkey'
|
"""
[2014-11-24] Challenge #190 [Easy] Webscraping sentiments
https://www.reddit.com/r/dailyprogrammer/comments/2nauiv/20141124_challenge_190_easy_webscraping_sentiments/
#Description
Webscraping is the delicate process of gathering information from a website (usually) without the assistance of an API.
Without an API... |
"""Hive Alarm Module."""
class HiveHomeShield:
"""Hive homeshield alarm.
Returns:
object: Hive homeshield
"""
alarmType = "Alarm"
async def getMode(self):
"""Get current mode of the alarm.
Returns:
str: Mode if the alarm [armed_home, armed_away, armed_night]... |
# Problem0020 - Factorial digit sum
#
# https: // github.com/agileshaw/Project-Euler
def digitSum(num):
result = 0
while num:
result, num = result + num % 10, num // 10
return result
if __name__ == "__main__":
factorial = 1
for i in range (1, 101):
factorial *= i
result = digit... |
# Exercise #057 - Data Validation
"""Make a program that reads a person's sex, but only accepts 'M' or 'F' values.
If it is wrong, ask for the typing again until you have a correct value."""
# Create our control variable
control = 0
# Here we start our loop with our control variable equals 0
while control == 0:
... |
class UserNotInGroupException(Exception):
def __init__(self, message):
self.message = f"user is not in group: {message}"
class InvalidRangeException(Exception):
def __init__(self, message):
self.message = message
class NoSuchGroupException(Exception):
def __init__(self, message):
... |
WHATSAPP_CRYPT = '''
Utility for WhatsApp crypt databases decryption.
Encrypted databases are usually located here:
/sdcard/WhatsApp/Databases/
The `key` file must be obtained from the following location:
/data/data/com.whatsapp/files/key
(Must have root permissions to read this file)
Supported crypt files with the ... |
def N(xi, i, enum):
if enum == 1:
if i == 1:
return (2*xi-1)**2
if i == 2:
return -2*xi*(3*xi-2)
if i == 3:
return 2*xi*xi
if enum == 2:
if i == 1:
return (2*xi-2)*(xi-1)
if i == 2:
return -6*xi**2 +... |
#!/usr/bin/python
# coding=utf-8
# Copyright 2019 yaitza. All Rights Reserved.
#
# https://yaitza.github.io/
#
# My Code hope to usefull for you.
# ===================================================================
__author__ = "yaitza"
__date__ = "2019-03-29 16:29"
|
class Wiggle:
def fixedStepParser(self, line):
value = line.strip()
start_position = self.stepIdx * self.parserConfig['step'] + self.parserConfig['start']
stop_position = start_position + self.parserConfig['span'] - 1
self.stepIdx += 1
for position in range(start_position, ... |
# Python Module example
def add(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
return result
|
temp = ['RFC 001', 'RFC 002', 'RFC 003', 'RFC 004', 'RFC 005']
rfcs = True
desc = "Fuck!😂 {}".format(''.join(temp)) if rfcs else ''
print(desc)
|
class Assignment:
def __init__(self, member_id, date_time, _role):
self.assignee_id = member_id
self.target_role = _role
self.assignment_date = date_time
# def __eq__(self, other):
# same_member_id = self.assignee_id == other.assignee_id
# same_role = self.role == other... |
def reverse(head):
""""Reverse a singly linked list."""
# If there is no head.
if not head:
# Return nothing.
return
# Create a nodes list.
nodes = []
# Set node equal to the head node.
node = head
# While node is truthy.
while node:
# Add the node to the ... |
"""
HelperFunctions.py
A list of pretty helpful functions.
"""
# Opens a file safely.
def OpenFileSafely(fileName, mode, raiseError):
try:
# Try to open the file
return open(fileName, mode)
except:
# If the file couldn't have been opened
if raiseError:
print... |
archivo = open("./004 EscribirLeerArchivoTexto/nombres.txt","r")
nombres = []
for linea in archivo:
linea = linea.replace("\n","")
nombres.append(linea)
archivo.close()
print(nombres) |
style = {'base_mpl_style': 'ggplot',
'marketcolors' : {'candle': {'up': '#000000', 'down': '#ff0000'},
'edge' : {'up': '#000000', 'down': '#ff0000'},
'wick' : {'up': '#606060', 'down': '#606060'},
'ohlc' : {'up': '#000000',... |
#!/usr/local/bin/python3
"""Task
A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river.
You are given an array A consisting of N integers r... |
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for i in range(self.V)] for j in range(self.V)]
self.edges = []
def add_edge(self, src: int, dest: int, weight: int):
self.graph[src][dest] = weight
self.graph[dest][src] = weight
self.edges.append([src,dest,... |
# Problem Set 4A
# Name: Gyalpo
# Collaborators:
# Time Spent: 5:30
# Late Days Used: 0
# Part A0: Data representation
# Fill out the following variables correctly.
# If correct, the tests named data_representation should pass.
treeA = [[14,19],[[3,5],0]]
treeB = [[9,3],6] # TODO: change this assignment
treeC = [[7],... |
# -*- coding: ISO-8859-1 -*-
"""Resource phongprecalc_vert (from file phongprecalc.vert)"""
# written by resourcepackage: (1, 0, 1)
source = 'phongprecalc.vert'
package = 'OpenGLContext.resources'
data = "// Vertex-shader pre-calculation for blinn-phong lighting\012vo\
id phong_preCalc( \012 in vec3 vertex_position,... |
'''
Given a list of coins, find the minimum number of coins to get to a certain value
For Example: coins={1,2,3} V=5
Output: 2 (3+2=5)
Note: the list must always contain a coin of value 1, so in the worst case the output will be V*'coin 1'
'''
def minCoin(coins, amount):
return minCoin_(coins, amoun... |
#APRENDIENDO INSTRUCCIONES EN PYTHON
print("funciones basicas de python")
print("-"*28)
print("input:Ingresar Datos")
print("print:Imprimir Datos")
print("MIN: Menor Valor")
print("ROUND:Redondear")
|
{
'targets': [{
'target_name': 'bindings',
'sources': [
'src/serialport.cpp'
],
'include_dirs': [
'<!(node -e "require(\'nan\')")'
],
'variables': {
# Lerna seems to strips environment variables. Workaround: create `packages/bindings/GENERATE_COVERAGE_FILE`
'generate_co... |
"""
This file will contain all utility functions for pulling
insults(and maybe default values?) from configuration files located somewhere.
This increases the modularity and usability of ChaseBot,
and allows for users to easily add content to DIS.
These configuration files will contain lists of chain words and flat ... |
# coding: utf-8
# Try POH
# author: Leonarodne @ NEETSDKASU
##############################################
def gs(*_): return input().strip()
def gi(*_): return int(gs())
def gss(*_): return gs().split()
def gis(*_): return list(map(int, gss()))
def nmapf(n,f): return list(map(f, range(n)))
def ngs(n): return nmapf... |
EARLY_GAME = 36
MIDDLE_GAME = 75
class heuristic:
def __init__(self, board):
self._size = board.get_board_size()
self._weight = [
[200, -100, 100, 50, 50, 50, 50, 100, -100, 200],
[-100, -200, -50, -50, -50, -50, - 50, -50, -200, -100],
[100, -50, 100, 0, 20, 2... |
class Checker:
def __init__(self, hin):
super().__init__()
self.hin = hin
self.chain = []
def conv(self, kernel, stride=1, pad=0, dilation=1):
self.chain.append([0, kernel, stride, pad, dilation, 0])
def convT(self, kernel, stride=1, pad=0, dilation=1, outpad=0):
... |
numAlunos = 7
notaMediaTurma=0
reprovadosFrequencia=0
reprovadosNota=0
entrada=True
for i in range (0,numAlunos+1,1):
matricula = input("Digite a matricula do aluno: ")
frequencia = int(input("Digite o número de aulas frequentadas pelo aluno: "))
nota1 = int(input("Digite a primeira nota do aluno: "))
... |
__all__ = [
'responseclassify',
'responsemorph',
'text_input',
'text_input_classify',
'text_input_tamil',
'url_input',
'url_input_classify',
'api_imagecaption_request',
'api_imagecaption_response',
'api_ner_request',
'api_ner_request_1',
'api_ner_response',
... |
class DocumentViewerAutomationPeer(DocumentViewerBaseAutomationPeer):
"""
Exposes System.Windows.Controls.DocumentViewer types to UI Automation.
DocumentViewerAutomationPeer(owner: DocumentViewer)
"""
def GetPattern(self,patternInterface):
"""
GetPattern(self: DocumentViewerAutomationPeer,patternIn... |
# -*- encoding:utf-8 -*-
"""
company:IT
author:pengjinfu
project:migu
time:2020.5.14
"""
user = 'wind8288@163.com'
pw = 'wind121'
|
# 48. Rotate Image
# https://leetcode.com/problems/rotate-image/
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
for i in range(len(matrix) // 2):
self._rotate_layer(matrix, i)
d... |
class simpAngMo:
def __init__(self, m, r, v):
self.m = m
self.r = r
self.v = v
def getAngVel(self):
return str(self.v/self.r) + ' rad s^(-1)'
def getCentAcc(self):
return str(self.v**2/self.r) + ' m s^(-2)'
def getCentAngAcc(self):
return str(self.magnitud... |
print( "Chocolate Chip Cookies" )
print( "1 cup butter, softened" )
print( "1 cup white sugar" )
print( "1 cup packed brown sugar" )
print( "2 eggs" )
print( "2 teaspoons vanilla extract" )
print( "3 cups all-purpose flour" )
print( "1 teaspoon baking soda" )
print( "2 teaspoons hot water" )
print( "0.5 teaspoons salt"... |
def part1(moves):
h_pos = 0
depth = 0
for direction, unit in moves:
if direction == 'forward':
h_pos += int(unit)
elif direction == 'up':
depth -= int(unit)
elif direction == 'down':
depth += int(unit)
return h_pos * depth
def part2(moves):... |
""" ---- begin number constant ---- """
STATUS_OK = 200
CONNECTION_ABORTED = 10054
REFRESH_TIME_IN_SECONDS = 5
""" ---- end number constant ---- """
""" ---- begin text constant ---- """
# When reading the csv:
# - Place 'r' before the path string to read any special characters, such as '\'
# - Don't forget to put the... |
''' You can find this exercise at the following website: https://www.practicepython.org/
15. Reverse Word Order:
Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type ... |
def test():
assert (
len(doc1.ents) == 2 and len(doc2.ents) == 2 and len(doc3.ents) == 2
), "Devem haver duas entidades em cada exemplo."
assert any(
e.label_ == "PERSON" and e.text == "PewDiePie" for e in doc2.ents
), "Você rotulou PERSON corretamente?"
assert any(
e.label_ ... |
# PySNMP SMI module. Autogenerated from smidump -f python RUCKUS-SCG-SYSTEM-MIB
# by libsmi2pysnmp-0.1.3
# Python version sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)
# pylint:disable=C0302
mibBuilder = mibBuilder # pylint:disable=undefined-variable,used-before-assignment
# Imports
(... |
def accumulate_left(func, acc, collection):
if len(collection) == 0:
return acc
return accumulate_left(func, func(acc, collection[0]), collection[1:])
def accumulate_right(func, acc, collection):
if len(collection) == 0:
return acc
return func(collection[0], accumulate_right(func, acc,... |
SCHEME = 'wss'
HOSTS = ['localhost']
PORT = 8183
MESSAGE_SERIALIZER = 'goblin.driver.GraphSONMessageSerializer'
|
TILEMAP = {
"#": "pavement_1",
"%": "pavement_2",
" ": "road",
"=": "road",
"C": "road_corner",
"T": "road_tint1",
"&": "pavement_1", # precinct
"$": "precinct_path",
"E": "precinct_path_alt",
"O": "ballot_box"
}
NO_ROUTING_TILES = [
"#", "%", "&"
]
SELECTIVE_ROUTING_TILES ... |
'''A very simple program,
showing how short a Python program can be!
Authors: ___, ___
'''
print('Hello world!') #This is a stupid comment after the # mark
|
"Jest testing macro that can compile typescript files for testing as well"
load("@npm//@bazel/typescript:index.bzl", "ts_library")
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary", "nodejs_test")
def jest_test(
srcs,
ts_config,
snapshots = [],
jest_config = None,
#... |
#
# PySNMP MIB module HPN-ICF-PBR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-PBR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:28:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
{
"targets": [
{
"target_name" : "dsfmt_js_nv",
"sources" : [ "src/main.cc", "dSFMT-src-2.2.3/dSFMT.c" ],
"include_dirs": [ 'dSFMT-src-2.2.3' ],
'cflags' : [ '-fexceptions' ],
'cflags_cc' : [ '-fexceptions' ],
'defines' : [ 'DSFMT_MEXP=19937' ]
}
]
}
|
nomecompleto = str(input('digite seu nome completo: '))
print(nomecompleto.upper())
print(nomecompleto.lower())
print(nomecompleto.capitalize())
print(nomecompleto.title())
print(nomecompleto.split())
print(nomecompleto.swapcase())
print(nomecompleto.find("i"))
print(nomecompleto.count('a', 0, 16))
print(len(nomecomple... |
class Solution:
# @param {integer[]} height
# @return {integer}
def largestRectangleArea(self, height):
areas = {}
sorted_height = sorted(list(set(height)))
lh = len(height)
for i in range(lh):
h = height[lh - 1 - i]
areas[lh - 1 - i] = {}
... |
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
alist = [36,38,30,31,38,43,55,38,37,30,48,41,33,25,34,43,37,40,36]
bubbleSort(... |
class HanaError(Exception):
pass
class HanaPluginError(HanaError):
pass
class InvalidPluginsDirectory(HanaError):
pass
class PluginNotFoundError(HanaPluginError):
pass
|
def compress(orginial_list):
compressed_list = []
mark_X = True
if orginial_list == []:
return 0
if len(orginial_list) == 1:
return 1
if len(orginial_list) > 1:
count = 1
for i in range(len(orginial_list) - 1):
begin_pointer = i
if orginial_l... |
class No:
def __init__(self, chave):
self.chave = chave
self.esquerdo = None
self.direito = None
self.pai = None |
'''
Largest Palindrome of two N-digit numbers given
N = 1, 2, 3, 4
'''
def largePali4digit():
answer = 0
for i in range(9999, 1000, -1):
for j in range(i, 1000, -1):
k = i * j
s = str(k)
if s == s[::-1] and k > answer:
return i, j
def largePali3dig... |
"""
Some helpful utility functions.
"""
__author__ = "Levi Borodenko"
__copyright__ = "Levi Borodenko"
__license__ = "mit"
def is_positive_integer(obj, name: str) -> None:
"""Checks if obj is a positive integer and
raises appropriate errors if it isn't.
Arguments:
obj: object to be checked.
... |
# the for loop works based on a Iterable object
# Iterable object is capable of returning values one at a time
# regular for loop
for i in range(5):
print(i)
for i in [1, 3, 5, 7]:
print(i)
for c in 'Hello':
print(c)
for i in [(1,2), (3,4), (5,6)]:
print(i)
# unpack the turple
for i, j in [(1,2), (... |
#Write a short Pyton function that takes a positive integer n and returns
#the sum of the squares of all the positive integers smaller than n.
def sigmaSquareN(n):
list =[]
sum = 0
for i in range(1,n):
sum += i**2
if sum < n:
print ('Sigma of squrae %d=%d'%(i,sum))
lis... |
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
cost.append(0)
n = len(cost)
minArray = [0]*n
minArray[0] = minArray[1] = 0
for i in range(2, n):
minArray[i] = min(minArray[i-1] + cos... |
print('DOBRO TRIPLO RAIZ')
n = int(input('Digite um numero: '))
print(f'DOBRO: {n * 2}')
print(f'TRIPLO: {n * 3}')
print(f'RAIZ: {n ** (1/2):.2f}')
|
"""
Write a Python program that randomizes 7 numbers
and prints their sum total.
If the sum is divisable by 7, also print the word "Boom"
"""
|
class NisDomain(basestring):
"""
NIS Domain
"""
@staticmethod
def get_api_name():
return "nis-domain"
|
# Python3 program to find a triplet
# that sum to a given value
# returns true if there is triplet with
# sum equal to 'sum' present in A[].
# Also, prints the triplet
def find3Numbers(A, arr_size, sum):
# Fix the first element as A[i]
for i in range( 0, arr_size-2):
# Fix the second element as A[j]
for j in r... |
"""Local settings for the db."""
DATABASE = {
'drivername': 'postgres',
'host': 'localhost',
'port': '5432',
'username': 'postgres',
'password': 'wassup89',
'database': 'gardendb',
}
|
# Dynamic Programming
# Runtime: 32 ms, faster than 95.08% of Python3 online submissions for Pascal's Triangle.
# Memory Usage: 13.3 MB, less than 14.94% of Python3 online submissions for Pascal's Triangle.
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = []
for i in range(... |
t = int(input())
for __ in range(t):
n, m = map(int, input().split())
inl = input().split()
iml = input().split()
amps = []
freqs = []
ampsm = []
freqsm = []
c = 0
for i in range(2*n):
if i % 2 == 0:
temp = int(inl[i])
amps.append(temp)
else:
freqs.append(inl[i])
for i in range(2*m):
if i % 2 ... |
#!/usr/bin/python
# encoding: utf-8
"""
@author: Ian
@file: read_config_file.py
@time: 2019-08-06 13:41
"""
def read_config_file(fp: str, mode='r', encoding='utf8', prefix='#') -> dict:
"""
读取文本文件,忽略空行,忽略prefix开头的行,返回字典
:param fp: 配置文件路径
:param mode:
:param encoding:
:param prefix:
:retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.