content stringlengths 7 1.05M |
|---|
#
# @lc app=leetcode id=205 lang=python3
#
# [205] Isomorphic Strings
#
# https://leetcode.com/problems/isomorphic-strings/description/
#
# algorithms
# Easy (40.89%)
# Likes: 2445
# Dislikes: 520
# Total Accepted: 402.9K
# Total Submissions: 974.8K
# Testcase Example: '"egg"\n"add"'
#
# Given two strings s and ... |
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
... |
"""
programa que leia vários numeros inteiros pelo teclado. O programa só vai parar quando o usuário digitar 999
que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles
(desconsiderando o flag(999))
"""
numero = contador = soma = 0
while numero != 999:
numero = i... |
# event manager permissions are set to expire this many days after event ends
CBAC_VALID_AFTER_EVENT_DAYS = 180
# when a superuser overrides permissions, this is how many minutes the temporary permissions last
CBAC_SUDO_VALID_MINUTES = 20
# these claims are used, if present, when sudoing. Note that sudo cannot give y... |
"""This module contains the filter and regressor managers used by
task to apply the filters and regressors. Both those classes use a
side operation manager that implement the generic functions. This
allow to apply the filters and regressors as early as possible during
the triplet generation to optimise the performances... |
def is_isogram(string):
found = []
for letter in string.lower():
if letter in found:
return False
if letter.isalpha():
found.append(letter)
return True
|
class speedadjustclass():
def __init__(self):
self.speedadjust = 1.0
return
def speedincrease(self):
self.speedadjust = round(min(3.0, self.speedadjust + 0.05), 2)
print("In speedincrease",self.speedadjust)
def speeddecrease(self):
self.speedadjust = round(max(0.5, ... |
# getting input from user and pars it to the integer
your_weight = input("Enter your Weight in kg: ")
print(type(your_weight))
# to parse value of variable, we have to put it in seperate line or put it equal new variable
int_weight_parser = int(your_weight)
print(type(int_weight_parser))
# formatted String
first_... |
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first = second = third = -math.inf
for num in nums:
if num > first:
first, second, third = num, first, second
elif num != first and num > second... |
"""
This is a collection of default transaction data used to test various components.
"""
UNIT = 100000000
"""This structure is used throughout the test suite to populate transactions with standardized and tested data."""
#removed pubkey hash, may need to be re-added.
DEFAULT_PARAMS = {
'addresses': [
['U... |
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True") |
# Time: O(m + n)
# Space: O(m + n)
# 445
# You are given two linked lists representing two non-negative numbers.
# The most significant digit comes first and each of their nodes contain
# a single digit.
# Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leadin... |
# MetaPrint.py
# Copyright (c) 2008-2017 Chris Gonnerman
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list... |
# Copyright 2014 Google Inc. 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/LICENSE-2.0
#
# Unless required by applicable law or ag... |
#print is function when we want to print something on output
print("My name is Dhruv")
#You will notice something strange if you try to print any directory
#print("C:\Users\dhruv\Desktop\dhruv.github.io")
#Yes unicodeescape error
# Remember i told about escape character on previous tutorial
# yes it causing prob... |
SECRET_KEY = '-dummy-key-'
INSTALLED_APPS = [
'pgcomments',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
},
}
|
names = ["libquadmath0", "libssl1.0.0"]
status = {"libquadmath0":
{"Name": "libquadmath0",
"Dependencies": ["gcc-5-base", "libc6"],
"Description": "GCC Quad-Precision Math Library<br/> A library, which provides quad-precision mathematical functions on targets<br/> supporting the __float1... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# dfs search
... |
"""Exceptions"""
class LibvirtConnectionError(Exception):
"""Error to indicate something went wrong with the LibvirtConnection class"""
pass
class DomainNotFoundError(Exception):
"""Error to indicate something went wrong with the LibvirtConnection class"""
pass
|
S = input()
scale_list = ["Do", "", "Re", "", "Mi", "Fa", "", "So", "", "La", "", "Si"]
order = "WBWBWWBWBWBW" * 3
print(scale_list[order.find(S)])
|
class Solution:
def solve(self, nums):
uniques = set()
j = 0
ans = 0
for i in range(len(nums)):
while j < len(nums) and nums[j] not in uniques:
uniques.add(nums[j])
j += 1
ans = max(ans, len(uniques))
... |
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0: return 0
min_price, max_profit = prices[0], 0
for i in prices[1:]:
min_price = min(min_price, i)
profit = i - min_price
... |
"""
patterns - Package of different software patterns.
Provided patterns:
* `abstractf` - abstract factory
* `threetier` - 3-tier software architecture
Use:
Each submodule is self-contained. If you don't want the whole package, you can
take the files you need. Usage examples are in the examples directory.
"""
__autho... |
#!/usr/bin/python3
def append_after(filename="", search_string="", new_string=""):
"""appends after search string instances in file
"""
with open(filename, 'r', encoding='utf-8') as myFile:
lines = myFile.readlines()
for i, line in enumerate(lines):
if search_string in line:
... |
MUSHISHI_ID = 457
FULLMETAL_ID = 25
GINKO_ID = 425
KANA_HANAZAWA_ID = 185
YEAR = 2018
SEASON = "winter"
DAY = "monday"
TYPE = "anime"
SUBTYPE = "tv"
GENRE = 1
PRODUCER = 37
MAGAZINE = 83
USERNAME = "Nekomata1037"
CLUB_ID = 379
|
"""
A Mapping module
"""
class DataMapping:
"""DataMapping"""
def __init__(self, data: dict, keys_map: dict):
"""__init__
:param data:
:type data: dict
:param keys_map:
:type keys_map: dict
data = {'username': 'John', 'email': 'john@example.com'}
keys_... |
def setup():
size(500,500)
smooth()
background(50)
strokeWeight(5)
stroke(250)
noLoop()
cx=250
cy=250
cR=200
i=0
def draw():
global cx,cy, cR, i
while i < 2*PI:
i +=PI/6
x1 = cos(i)*cR+cx
y1 = sin(i)*cR+cy
line(x1,y1,x1,y1)
... |
BUCKET_NAME = "o43-gpnhack-data-hh"
MANTICORE_URL = "http://manticore:9308"
ELASTICSEARCH_URL = "http://elasticsearch:9200"
QDRANT_URL = 'http://qdrant:6333'
# 113 - Россия, 1 - Москва, 83 - Смоленск
DEFAULT_HH_AREAS = [113]
|
# Here is the code from the generators2.py file
# From the demo
# Can you refactor any or all of it to use comprehensions?
# More chaining
# Courtesy of my friend Jim Prior
def gen_fibonacci():
a, b = 0, 1
while True:
a, b = b, a + b
yield b
def gen_even(gen):
return (number for number in ... |
#from models import HVAC
class HvacBuildingTracker():
""" Creates a tracker that will manage the data that the hvac building generates
"""
def __init__(self):
"""Creates an instance of the hvac building tracker
"""
self.__HouseTempArr = []
self.__OutsideTempArr = []
self.__AvgPowerPerSecArr = []
def ... |
def main():
value = 1
if value == 0:
print("False")
elif value == 1:
print("True")
else:
print("Undefined")
if __name__ == "__main__":
main()
|
# -*- coding: UTF-8 -*-
logger.info("Loading 16 objects to table ledger_matchrule...")
# fields: id, account, journal
loader.save(create_ledger_matchrule(1,2,1))
loader.save(create_ledger_matchrule(2,2,2))
loader.save(create_ledger_matchrule(3,4,3))
loader.save(create_ledger_matchrule(4,2,4))
loader.save(create_ledger_... |
#!/bin/python3
# https://www.hackerrank.com/challenges/py-check-subset/problem
# Author : Sagar Malik (sagarmalik@gmail.com)
n = int(input())
for _ in range(n):
K = int(input())
first = set(input().split())
t = int(input())
second = set(input().split())
print(len(first-second) == 0)
|
class Pipelines(object):
def __init__(self, client):
self._client = client
def get_pipeline(self, pipeline_id, **kwargs):
url = 'pipelines/{}'.format(pipeline_id)
return self._client._get(self._client.BASE_URL + url, **kwargs)
def get_all_pipelines(self, **kwargs):
url = 'p... |
def grow_plants(db, messenger, object):
#
# grow plant
db.increment_property_of_component('plant', object['entity'], 'growth', object['growth_rate'])
return []
def ripen_fruit(db, messenger, object):
db.increment_property_of_component('plant', object['entity'], 'fruit_growth', object['fruit_growt... |
for c in range(1,50):
if c%2==0:
print('.',end='')
print(c,end=' ')
|
__author__ = 'khomitsevich'
ATTRIBUTES_COUNT: int = 14
class Metrics:
""" Metrics data class. """
# TODO: Initialization process should be more clearer, better to pass dict with keys as class parameter titles
def __init__(self, filepath:str, filename:str, args:list):
self.__argument_count_val... |
# input sell price
a = input("Input Final Sale Price")
# input P&P cost
b = input("Input P&P Costs")
# add a & b together to get total
# fees = total * 0.128 + 0.3 //12.8% + 30p
# total - fees = profit
# output total
# output fees
# output profit
# output description explaining forumla
# output note explaining that fe... |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/11178/B
#need a state machine to be clear!
#state: 'S', 'W', 'WO'
#trans:
# 1. 'S---meet vv--->W';
# 2. 'W---meet vv--->W'; #update w,wow
# 3. 'W---meet o--->WO'; #update wo
# 4. 'WO--meet o--->WO'; #update wo
# 5. 'WO--meet vv--->W'; #update... |
class ValidationError(Exception):
""" Base class """
pass
class AppStoreValidationError(ValidationError):
message = None
def __init__(
self,
message: str
):
self.message = message
super().__init__(message)
def __str__(self) -> str:
return self.messag... |
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (not x % 10 and x):
return False
rev = 0
while x > rev:
rev = rev * 10 + x % 10
x //= 10
return rev == x or rev//10 == x
|
valorc = float(input('Qual o valor da Casa? R$ '))
salario = float(input('Qual o valor do salario? R$'))
anos = int(input('Em quantos anos deseja pagar? '))
prest = valorc / (anos * 12)
if prest > (salario * (30/100)):
print('Fincanciamento Negado')
else:
print('Financiamento Autorizado')
|
'''
Unit tests module for PaPaS module
'''
__all__ = []
|
"""
EM PYTHON TUDO É UM OBJETO: incluindo classes
Metaclasses são as "classes" que criam classes.
type é uma metaclasse (!!!???)
"""
# Criando uma metaclasse que define como as classes que a herdarem devem
# funcionar
class Meta(type):
def __new__(mcs, name, bases, namespace):
"""
mcs = Metaclasse... |
termo = int(input('Quantos termos vocêr quer da Sequeência Fibonacci: '))
t1 = 0
t2 = 1
print('{} - {} - '.format(t1, t2), end='')
c = 3
while c <= termo:
t3 = t1 + t2
print(t3, end=' - ')
t1 = t2
t2 = t3
c += 1
print('Fim')
|
N = int(input())
for i in range(N):
n, k = map(int, input().split())
ranges = {n: 1}
max_range = 0
while k > 0:
max_range, count_range = max(ranges.items())
if k > count_range:
k -= count_range
del ranges[max_range]
range_1, range_2 = (max_range ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 18 12:51:41 2019
@author: barnafi
"""
class PhysicalParameters:
def __init__(self, **kwargs):
keys = kwargs.keys()
def setter(_x, default): return kwargs[_x] if _x in keys else default
# Simluation specifications
... |
"""
While thinking abou this problem,
many might come up with a DP algorithm.
But this problem is much easier than DP problem.
First, scan the input string,
and store the maximum occurance index of every leter.
Then, scan the input string again,
considering the maximum occurance of each letter.While scanning,
if you e... |
alpha_num_dict = {
'a':1,
'b':2,
'c':3
} |
# Creating an empty Tuple
Tuple1 = (Hello)
print("Initial empty Tuple: ")
print(Tuple1)
A=(1,2,3,4)
B=('a','b','c')
C=(5,6,7,8)
#second tuple
print(A,'length= ',len(A))
print(B,'length= ',len(B))
print(A<C)
print(A+C)
print(max(A))
print(min(B))
tuple('hey')
'good'*3 |
#
# PySNMP MIB module DSA-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/DSA-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:11:07 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( Integer, Obj... |
# basic model configuration related and data and training (model specific configuration is declared with Notebook)
args = {
"batch_size":128,
"lr":1e-3,
"epochs":10,
} |
#
# @lc app=leetcode id=103 lang=python
#
# [103] Binary Tree Zigzag Level Order Traversal
#
# https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/
#
# algorithms
# Medium (40.48%)
# Likes: 957
# Dislikes: 59
# Total Accepted: 222.2K
# Total Submissions: 530.4K
# Testcase Example: ... |
marks = [[1,2,3],[4,5,6],[7,8,9]]
rotate = [[False for i in range(len(marks[0]))] for j in range(len(marks))]
for row, items in enumerate(marks):
for col, val in enumerate(items):
rotate[col][row] = val
for row in marks:
print(row)
for row in rotate:
print(row)
|
# do a bunch of ternary operations on an NA object
x = 1 / 0
assert type(x) is NA
assert type(pow(x, 2)) is NA
assert type(pow(2, x)) is NA
assert type(x ** 2) is NA
assert type(2 ** x) is NA
|
# first line: 10
@memory.cache
def read_wav():
wav = dl.data.get_smashing_baby()
return wavfile.read(wav)
|
#!/usr/bin/python3
# 3-print_reversed_list_integer.py
def print_reversed_list_integer(my_list=[]):
"""Print all integers of a list in reverse order."""
if isinstance(my_list, list):
my_list.reverse()
for i in my_list:
print("{:d}".format(i))
|
# coding: utf-8
#########################################################################
# 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> #
# author yeeku.H.lee kongyeeku@163.com #
# #
# version... |
class Config:
BASE_DIR = "/usr/local/lib/python3.9/site-packages"
FACEBOOK_PACKAGE = "facebook_business"
ADOBJECT_DIR = "adobjects"
# https://github.com/facebook/facebook-python-business-sdk/tree/master/facebook_business/adobjects
FULL_PATH = f"{BASE_DIR}/{FACEBOOK_PACKAGE}/{ADOBJECT_DIR}"
... |
__version__ = "2.0.1"
__version_info__ = tuple(int(num) for num in __version__.split("."))
default_app_config = "dbfiles.apps.DBFilesConfig"
|
fo = open("list.txt", "r")
lines = fo.readlines()
outf = open("out.txt", "w")
for line in lines:
l = line.replace("\n","")
ls = l.split(",")
pl = "first: " + ls[0] + " second: " + ls[1] + " third: " + ls[2]
outf.write(pl)
outf.close()
|
# coding: utf-8
# created by Martin Haese, Tel FRM 10763
# last modified 01.02.2018
# to call it
# ssh -X refsans@refsansctrl01 oder 02
# cd /refsanscontrol/src/nicos-core
# INSTRUMENT=nicos_mlz.refsans bin/nicos-monitor -S monitor_scatgeo
description = 'REFSANS scattering geometry monitor'
group = 'special'
# Legen... |
#!/usr/bin/env python
'''
--- Day 12: Passage Pathing ---
With your submarine's subterranean subsystems subsisting suboptimally, the only way you're getting
out of this cave anytime soon is by finding a path yourself. Not just a path - the only way to
know if you've found the best path is to find all of them.
Fortun... |
intervals = [(2, 15), (36, 45), (9, 29), (16, 23), (4, 9)]
def room_num(intervals):
intervals_sorted = sorted(intervals, key=lambda x: x[0])
rooms = 1
room_open_time = [intervals_sorted[0][1]]
for interval in intervals_sorted[1:]:
if interval[0] < min(room_open_time):
rooms += 1
... |
"""
Given an array of integers and an integer k, find out whether there are two distinct indices i and j
in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
"""
class Solution():
def contains_dups(self, nums, k):
nhash = {}
for i in range(len(nums)):
... |
def web_page_wifi():
html = """<!DOCTYPE html><html lang="de">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="/get">
<h1>Wifi configuration</h1>
<br>
<a href= "mail... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-----------------------------------------
@Author: isky
@Email: 19110240019@fudan.edu.cn
@Created: 2019/11/19
------------------------------------------
@Modify: 2019/11/19
------------------------------------------
@Description:
""" |
def merge(pic_1, pic_2):
return {
'id': pic_1['id'] + pic_2['id'],
'tags': pic_1['tags'] | pic_2['tags'],
}
def get_score_table(pics):
score_table = {}
for i in range(len(pics)):
for j in range(i + 1, len(pics)):
r = len(pics[i]['tags'] & pics[j]['tags'])
... |
def for_E():
"""We are creating user defined function for alphabetical pattern of capital E with "*" symbol"""
row=7
col=5
for i in range(row):
for j in range(col):
if i==0 or i==3 or i==6 or j==0:
print("*",end=" ")
else:
print(" ... |
def part1(inp):
drawn_numbers = [int(x) for x in inp.pop(0).split(",")]
boards = []
for i in range(len(inp) // 6):
inp.pop(0)
board = [[int(x) for x in inp.pop(0).split()] for j in range(5)]
boards.append(board)
for num in drawn_numbers:
for board in boards:
... |
"""
Purpose: stackoverflow solution.
Date created: 2021-03-04
Title: How to generate a lists of lists or nested from user input while outputting amount of times a word is stated?
URL: https://stackoverflow.com/questions/66483811/how-to-generate-a-lists-of-lists-or-nested-from-user-input-while-outputting-amou/66484266... |
print('\n========= R$ =========')
val = float(input('Digite o valor da moéda: -> '))
print('\n========= U$ =========')
dol = float(input('Digite o valor do dólar: -> '))
conv = val / dol
print('\n======= conversão =======')
print('O valor da conversão é U$: {:.2f}'.format(conv))
print('\n=========================... |
class Version(str):
SEPARATOR = '.'
def __new__(cls, version=""):
obj = str.__new__(cls, version)
obj._list = None
return obj
@property
def list(self):
if self._list is None:
self._list = []
for item in self.split(Version.SEPARATOR):
... |
class Solution:
"""
@param nums: an array of integers
@param k: an integer
@return: the number of unique k-diff pairs
"""
def findPairs(self, nums, k):
ans = 0
num_set = set(nums)
if k == 0:
num_dict = dict([(num, 0) for num in num_set])
... |
# MEDIUM
# this is like Word Break => DFS + Memoization
# define a lambda x,y: x {+,-,*} y
# scan the string s:
# break at operators "+-*" => left = s[:operator] right = s[operator+1:]
# recurse each left, right:
# try every possible operations of left and right
# Time O(N!) Space O(N)
class Solut... |
#!/usr/bin/env python3
# day007.py
# By Sebastian Raaphorst, 2019.
# We memoize the auxiliary internal function in calculate_decodings, because the recursion explodes into
# already-solved sub-problems.
# For the last test, without memoization, it takes
class Memoize:
def __init__(self, f):
self.f = f
... |
"""
-The zip functions takes some iterators and
zips Them on Tuples.
- Used to parallel iterations
- Retun a zip object which is an iterators of zip.
the zip function takes the len of the shortest zip
ands used it as main path to zip to the other zip.
"""
countries = "Ecuador"
capitals = "Quito"
countries_cap... |
git_response = {
"login": "dimddev",
"id": 57534,
"node_id": "MdQ6VXnlc4U3NTM0NDA=",
"avatar_url": "https://avatars1.githubusercontent.com/u/5753440?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dimddev",
"html_url": "https://github.com/dimddev",
"followers_url": "https:/... |
continuar = ''
countwomen = 0
countmen = 0
maioridade = 0
while continuar != 'N':
print('\033[1;34mCadastre uma Pessoa\033[m')
print('===' * 10)
idade = int(input('Idade: '))
if idade > 18:
maioridade = maioridade + 1
sexo = str(input('Digite o sexo[M/F]: ').upper().strip())
if sexo == '... |
#
# user-statistician: Github action for generating a user stats card
#
# Copyright (c) 2021 Vincent A Cicirello
# https://www.cicirello.org/
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal... |
class Node:
def __init__(self, element, parent, left_child, right_child):
self.element = element
self.parent = parent
self.left_child = left_child
self.right_child = right_child
def getElement(self):
return self.element
def getParent(self):
return self.parent
... |
# These default settings initally apply to all installations of the config_app.
#
# This file _is_ and should remain under version control.
#
DEBUG = False
SQLALCHEMY_ECHO = False
SECRET_KEY = b'default_SECRET_KEY'
#
# IMPORTANT: Do _not_ edit this file.
# Instead, over-ride with settings in the instance/c... |
class Solution:
def getHint(self, secret: str, guess: str) -> str:
index = 0
secret = list(secret)
guess = list(guess)
A = 0
while index < len(secret):
# count A
if secret[index] == guess[index]:
secret = secret[:index] + secret[index +... |
#Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior.
def maior(*num):
maximo=max(num)
print(f'dos numeros {num}',end=' ')
print(f'foram informados {len(num)}')
print(f"O ma... |
COLOMBIA_PLACES_FILTERS = [
# Colombia
{'country': 'CO', 'location': 'Bogota'},
{'country': 'CO', 'location': 'Medellin'},
# TODO: solve issue, meetup is not returning results for cali even though it actually exist a django group
{'country': 'CO', 'location': 'Cali'},
{'country': 'CO', 'location... |
# -*- coding: utf-8 -*-
n = int(input())
t = []
for _ in range(n):
t.append(int(input()))
for i in range(n):
if i > 0 and i < n - 1:
print(sum(t[i - 1:i + 2]))
elif i == 0:
print(sum(t[:2]))
else:
print(sum(t[i - 1:])) |
N = int(input())
lst = [list(map(int,input().split())) for i in range(N)]
for i in range(N-2):
for j in range(i+1,N-1):
for k in range(j+1,N):
x0,y0 = lst[i]
x1,y1 = lst[j]
x2,y2 = lst[k]
x0 -= x2
x1 -= x2
y0 -= y2
y1 -= y2... |
class ConsoleLine:
body = None
current_character = None
type = None
|
class KeyExReturn:
def __init__(self):
self._status_code = None
self._msg = None
def __call__(self):
return self._msg, self._status_code
def status_code(self):
return self._status_code
def message(self):
return self._msg
class OK(KeyExReturn):
def __init_... |
# Radix sort in Python
def counting_sort(array, place):
size = len(array)
output = [0] * size
count = [0] * 10
for i in range(0, size):
index = array[i] // place
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = size - 1
while i >= 0:
... |
class Fields:
#rearrange the field order at will
#if renaming or adding additional fields modifying target.csv is required
values = ['Timestamp', 'Transaction Id', 'Payment ID', 'Note', 'Receive/Send Address', 'Debit', 'Credit', 'Network Fee', 'Balance', 'Currency']
|
fixed_answers = {
'how_to': [
{'values': {'product': 'mister proper'}, 'expected_response': 'Two cups per 5 litres of water should do it!'},
{'values': {'product': 'Braun'}, 'expected_response': 'First of all, plug the trimmer to the electric current. Secondly, turn it on by pressing the upper botto... |
TABLES = ["departments", "dept_manager", "dept_emp", "titles", "salaries"]
QUERYLIST_CREATE_STRUCTURE = [
"DROP TABLE IF EXISTS dept_emp, dept_manager, titles, salaries, employees, departments;",
"""CREATE TABLE employees (
emp_no INT NOT NULL,
birth_date DATE NOT NULL,
... |
lista_numeros = [1, 4, 7, 9]
numero_usuario = 10
while numero_usuario < 0 and numero_usuario > 9:
numero_usuario = int(input('Ingresa tu numero del 0-9'))
if numero_usuario in lista_numeros:
print('El numero está dentro de la lista')
else:
print('El numero no está dentro de la lista')
|
"""
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths
would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,... |
'''
URL: https://leetcode.com/problems/basic-calculator/
Time complexity: O(n)
Space complexity: O(n)
'''
class Solution:
def _get_next_num(self, i, s):
curr_num = ""
while i < len(s) and s[i].isdigit():
curr_num += s[i]
i += 1
return i-1, int(curr_num)
def cal... |
FILENAME = "input.txt"
class Expression:
def __init__(self, expression_str: str):
expression_list = expression_str.split()
if len(expression_list) == 1:
self.parse_expression(None, None, expression_list[0])
elif len(expression_list) == 2:
self.parse_expression(Non... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/workspace/src/ros_control/controller_manager_msgs/msg/ControllerState.msg;/workspace/src/ros_control/controller_manager_msgs/msg/ControllerStatistics.msg;/workspace/src/ros_control/controller_manager_msgs/msg/ControllersStatistics.msg;/workspace/src/... |
a=[]
while True:
b=input("Enter Number(Break Using String):")
if b.isalpha():
break
else:
a.append(int(b))
continue
c=a[0]
for x in a:
if c>x:
c=x
else:
continue
d=0
if c in a:
d=a.index(c)
print ("Index:",d)
print ("Number:",c)
|
'''
PROBLEM: Length of Last Word
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maxima... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.