content stringlengths 7 1.05M |
|---|
"""import numpy as np
import matplotlib.pyplot as plt
class Grid:
def __init__(self, height, weight, start):
self.height = height
self.weight = weight
self.i = start[0]
self.j = start[1]
def set(self, rewards, actions):
self.rewards = rewards
self.ac... |
'''
Represents the different HTTP status codes
returned from the API to indicate errors.
http://docs.veritranspay.co.id/sandbox/status_code.html
'''
# 20x - successful submission to api
SUCCESS = 200 # NOTE: this is returned when manually cancelled too!
CHALLENGE = 201
PENDING = 201 # NOTE: returned when payment typ... |
N = 4
board = [input() for _ in range(4)]
for i in range(N):
for j in range(N):
cand = []
if j + 2 < N:
cand.append([board[i][j+k] for k in range(3)])
if i + 2 < N:
cand.append([board[i+k][j] for k in range(3)])
if i + 2 < N and j + 2 < N:
cand.app... |
LOG_FILE = 'temperature.log'
ZONE_ID = 'ZoneId'
MAX_TEMP = 'MaximumTemperature'
TRIGGERED = 'Triggered'
INCORRECT_CREDENTIALS = 'Incorrect Credentials.'
INCORRECT_ARGUEMENTS = 'Incorrect arguments provided - IP username password'
TEMPERATURE_API = 'http://{}/axis-cgi/temperature_alarm/getzonestatus.cgi?'
DATE_TIME... |
def coroutine(seq):
count = 0
while count < 200:
count += yield
seq.append(count)
seq = []
c = coroutine(seq)
next(c)
___assertEqual(seq, [])
c.send(10)
___assertEqual(seq, [10])
c.send(10)
___assertEqual(seq, [10, 20]) |
def active_message(domain, uidb64, token):
return f"아래 링크를 클릭하시면 인증이 완료되며, 바로 로그인하실 수 있습니다.\n\n링크 : https://{domain}/activate/{uidb64}/{token}\n\n감사합니다."
def reset_message(domain, uidb64, token):
return f"아래 링크를 클릭하시면 비밀번호 변경을 진행하실 수 있습니다.\n\n링크 : https://{domain}/reset/{uidb64}/{token}\n\n감사합니다."
|
# Make sure you follow the order of reaction
# output should be H2O,CO2,CH4
def burner(c,h,o):
water = co2 = methane = 0
if h >= 2 and o >= 1:
if 2 * o >= h:
water = h // 2
o -= water
h -= 2*water
else:
water = o
o -= water
... |
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return "0"
num, neg = (num, False) if num > 0 else (-num, True)
res = []
while num:
num, r = divmod(num, 7)
res.append(r)
if neg:
res.append("-")
re... |
fin = open("Crime.csv")
for line in fin:
word = line.split()
def crime():
print(" Crime Type | Crime ID | Crime Count")
if (word == "ASSAULT" and word =="ROBBERY" and word == "THEFT OF VEHICLE" and word == "BREAK AND ENTER"):
print (word)
lst = []
for i in word:
lst.append(i)
crime
|
n = 1
par = impar = 0
while n != 0:
n = int(input('Digite um número: '))
if n != 0:
if n % 2 == 0:
par += 1
else:
impar += 1
print(f'Tem {par} número(s) par(es) e {impar} número(s) ímpar(es).')
|
def reduce_polymer(orig, to_remove=None, max_len=-1):
polymer = []
for i in range(len(orig)):
# We save a lot of processing time for Part 2
# if we cut off the string building once the
# array is too long
if max_len > 0 and len(polymer) >= max_len: return None
# The te... |
# 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");... |
na, nb = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = set(a)
b = set(b)
t = len(a & b)
t2 = len(a.union(b))
print(t/t2)
|
#
# PySNMP MIB module MPLS-LC-FR-STD-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/MPLS-LC-FR-STD-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:21:02 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... |
# O(n^2) overall
def get_longest_increasing_subsequence(nums):
l = len(nums)
# reverse adjacency list O(n^2)
reverse_adjacency = {i:set() for i in range(l)}
for i,n in enumerate(nums):
for j,e in enumerate(nums[i+1:], i +1):
if n < e:
reverse_adjacency[j].add(i)
# dynam... |
"""
Variables for configuration of zoom meetings using SCA Room Assign Tool
"""
N = 1
SESSION_PATH = "session_info.obj"
CHROME_PATH = "C:/ChromeDriver/chromedriver.exe"
existing_meeting_id = None # either a valid meeting ID or None, e.g. "860 1959 8282"
username = ""
password ... |
# This is how we print something
print("Hello!")
# Let's use python3 hello.py to run the program
# We can set variables
my_variable = 5
print(my_variable)
# We can make a list
my_list = [1, 2, 3]
print(my_list) |
def perm_coord(
self,
perm_coord_list=[0, 1, 2],
):
"""Permute coordinates of Mesh Solution in place
Parameters
----------
self : MeshSolution
a MeshSolution object
perm_coord_list : list
list of the coordinates to be permuted
"""
# swap mesh solution
for sol i... |
class DisjointSets:
"""
Disjoint-set union data structure in which each element contributes an
arbitrary measure.
"""
__slots__ = ('_parents', '_ranks', '_measures')
def __init__(self, measures):
"""
Constructs DisjointSets with a fixed number of elements, each initiall... |
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
A = [i*i for i in A]
return sorted(A)
|
class Variable(object):
def __init__(self, _id , offset):
self._id = _id
self.offset = offset
def __str__(self):
s = str(self._id)
if self.offset:
s = s + "/%d" % self.offset
return s
class VariableLimited(object):
def __init__(self, _id , offset, size):... |
vm = float(input("Digite um volume em metros cubicos: "))
lc = 1000 * vm
print("O volume digitado é de {} metros cubicos, esse valor convertido é em volume {:.2f} litros " .format(vm,lc)) |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# [mysql数据库配置信息]
db_mysql_host = "127.0.0.1"
db_mysql_port = 3306
db_mysql_user = 'root'
db_mysql_password = '123456'
db_mysql_database = 'matrix'
db_mysql_charset = 'utf8'
|
# -*- coding: utf-8 -*-
# texttaglib's package version information
__author__ = "Le Tuan Anh"
__email__ = "tuananh.ke@gmail.com"
__copyright__ = "Copyright (c) 2018, texttaglib, Le Tuan Anh"
__credits__ = []
__license__ = "MIT License"
__description__ = "Python library for managing and annotating text corpuses in diff... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# https://github.com/michielkauwatjoe/Meta
class CubicBezier:
def __init__(self, bezierId=None, points=None, parent=None, isClosed=False):
u"""
Stores points of the cubic Bézier curve.
"""
self.bezierId = bezierId
self.points ... |
numero = int(input('Digite um numero: '))
menor = numero -1
maior = numero + 1
print(f'Analisando o numero {numero}, seu antecessor {menor} e o sucessor é {maior}') |
# General things:
RIGHT = 1
LEFT = 2
TOP = 3
BOTTOM = 4
# Names of layers
class Layers:
game_actors = 4
main = 3
sticky_background = 2
background = 1
background_color = 0
# Message names: (MSGNs)
class MSGN:
COLLISION_SIDES = 0
VELOCITY = 1
STATE = 100
LOOKDIRECTION = 101
STATESTACK = 102
# Warios states... |
# -*- coding: utf-8 -*-
account = {
'email': 'YOUR EMAIL',
'password': 'YOUR PASSWORD'
}
op = "Login"
form_id = "packt_user_login_form"
frequency = 8 |
tabby_dog="\tI'm tabbed in";
persian_dog="I'm split\non s line."
backslash_dog="i'm \\ a \\ dog"
fat_dog="I'll do a list:\t* dog food \t* Fishies \t* Catnip\n\t* Grass"
print(tabby_dog)
print(persian_dog)
print(backslash_dog)
print(fat_dog)
|
# Change these to your instagram login credentials.
username = "Username"
password = "Password"
|
#!chuck_extends project/urls.py
#!chuck_appends URLS
urlpatterns += patterns('',
url(r'^', include('filer.server.urls')),
url(r'^', include('cms.urls')),
)
#!end
|
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome = None, idade = 35):#---->Aqui são parâmetros(None,35)para os valores(nome, idade).
self.idade = idade #----> Existem também os atributos de dados(que podem ser chamados também atributos de obje-
self.nome = nome #to) que são de... |
# Easy horntail gem
sm.spawnMob(8810202, 95, 260, False)
sm.spawnMob(8810203, 95, 260, False)
sm.spawnMob(8810204, 95, 260, False)
sm.spawnMob(8810205, 95, 260, False)
sm.spawnMob(8810206, 95, 260, False)
sm.spawnMob(8810207, 95, 260, False)
sm.spawnMob(8810208, 95, 260, False)
sm.spawnMob(8810209, 95, 260, False)
sm.s... |
#https://codeforces.com/contest/1343/problem/C
for _ in range(int(input())):
n = int(input())
l = input().split()
new = []
sn=[]
nn=[]
ans=0
for i in l:
if i[0]!='-':
sn.append(int(i))
if(nn!=[]):
new.append(nn)
nn=[]
el... |
def in_bounds(matrix, i, j):
rows = len(matrix)
cols = len(matrix[0])
if i < 0 or i >= rows or j < 0 or j >= cols:
return False
return True
def read_matrix():
matrix = []
while row := input():
matrix.append([int(num) for num in list(row)])
return matrix
def pretty_print(ma... |
#in=5
#in=10
#in=11
#in=20
#in=22
#in=30
#in=33
#in=40
#in=44
#in=50
#in=55
#golden=6050
n = input_int()
out = 0
while (n > 0):
x = input_int()
y = input_int()
out = out + x * y
n = n - 1
print(out)
|
for _ in range(int(input())):
n=int(input())
if n%2==0:
check=0
while n%2==0:
n=n//2
check+=1
if n<=1:
if check%2:
print("Bob")
else:
print("Alice")
else:
print("Alice")
else:
... |
class Solution:
def isOneEditDistance(self, s, t):
l1, l2, cnt, i, j = len(s), len(t), 0, 0, 0
while i < l1 and j < l2:
if s[i] != t[j]:
cnt += 1
if l1 < l2:
i -= 1
elif l1 > l2:
j -= 1
i ... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class NasSourceThrottlingParams(object):
"""Implementation of the 'NasSourceThrottlingParams' model.
Specifies the NAS specific source throttling parameters during source
registration or during backup of the source.
Attributes:
max_para... |
#辞書型
print("辞書型")
profile = {
"name": "tani",
"email": "kazunori-t@cyberbra.in"
}
print(profile["name"])
# 新しく要素を追加
profile["gender"] = "male"
# 新しく要素を追加した辞書型(profile)を出力
print(profile)
print(profile["gender"])
|
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = "3.10"
_lr_method = "LALR"
_lr_signature = "A AFTER_TOMORROW AM AT BEFORE_YESTERDAY COLON DATE_END DAY MINUS MONTH NUMBER OF ON PAST_PHRASE PHRASE PLUS PM THE TIME TODAY TOMORROW WORD_NUMBER YEAR YESTERDAY\n da... |
def fakulteta(n):
if n == 0:
return 1
else:
return n * fakulteta(n - 1)
def vsota_stevk_fakultete(n):
seznam = [int(d) for d in str(fakulteta(n))]
vsota = 0
for i in range(0, len(seznam)):
vsota = vsota + seznam[i]
return(vsota)
print(vsota_stevk_fakultete(100)) |
class Motor:
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade = max(0, self.velocidade)
NORTE = 'Norte'
SUL = 'Sul'
LESTE = 'Leste'
OESTE = 'Oeste'
class Direcao:
rotacao_a_direita_dc... |
# 1.
# import math
# # a,b,c = map(float,input('Enter a,b,c:').split(','))
# a,b,c = eval(input('Enter a,b,c:'))
# sum=b*b-4*a*c
# if sum >0:
# r1=(-b+math.sqrt(sum))/2*a
# r2=(-b-math.sqrt(sum))/2*a
# print('The roots are %.2f and %.2f'%(r1,r2))
# elif sum == 0:
# r1=r2=(-b+math.sqrt(sum))/2... |
# -*- coding: utf-8 -*-
"""
.. _Docutils Configuration: http://docutils.sourceforge.net/docs/user/config.html
.. _registry-intro:
Configuration registry
======================
Registry store configurations by the way of its interface.
Default global registry is available at ``rstview.registry.rstview_registry``
an... |
# ** potência ou pow(4,3)
# // divisão inteira
nom = input('Comment vous vous appellez? ')
print('Cest un plaisir de vous conaitre {:20}!'.format(nom))
print('Cest un plaisir de vous conaitre {:>20}!'.format(nom))
print('Cest un plaisir de vous conaitre {:^20}!'.format(nom))
print('Cest un plaisir de vous conaitre {:=^... |
# (C) Datadog, Inc. 2010-2017
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
PORT = 11211
SERVICE_CHECK = 'memcache.can_connect'
|
PI = 3.1415 # Globale Variable
def kreisumfang(radius):
kreisumfang = 2 * PI * radius
return kreisumfang
def zylinder(radius, hoehe):
return hoehe * kreisumfang(radius)
print(zylinder(50, 20)) |
"""
A python package to update stuff.
This code is released under the terms of the MIT license. See the LICENSE
file for more details.
"""
|
def help_normalize_variations(variations: list[dict]) -> list[dict]:
list_normalized = []
obj_normalized = {}
list_obj_normalized = []
last_color = ""
count = 0
for element in variations:
if last_color == element.color or last_color == "":
list_normalized.append(
... |
#!/usr/bin/env python
def construct_fip_id(subscription_id, group_name, lb_name, fip_name):
"""Build the future FrontEndId based on components name.
"""
return ('/subscriptions/{}'
'/resourceGroups/{}'
'/providers/Microsoft.Network'
'/loadBalancers/{}'
'/fron... |
class aSumPrint:
def run(self, context): #include context
a_sum = context["aSum"] #to extract from shared dictionary
print(f'a_sum = {a_sum}')
def __call__(self, context):
self.run(context) #to run the function
|
"""
Beautiful Arrangement
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:
perm[i] is divisible by i.
i is divisible by perm[i].
Given an integer n, return t... |
#set following variables
types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
#print variables "x" and "y" to create sentences
print(x)
print(y)
#print f-strings, notated with "f" in initial position.
#Using... |
comida = ["tacos", "pozole", "pan de muerto", "pastel", "spaghetti", "gorditas"]
print("Acceder a los elementos de la lista individualmente")
print(comida[0])
print(comida[2])
print(comida[5])
print("Mostrar todos los elementos")
print(comida)
print()
print("Eliminar algun elemento")
del comida[3]
comida.pop()
print... |
class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
def helper(current, depth):
res = 0
for item in current:
if item.isInteger():
res += item.getInteger() * depth
else:
res += helper(it... |
"""
Constants that are used throughout Zen.
"""
# Graph directedness
DIRECTED = 'directed'
UNDIRECTED = 'undirected'
# Direction constants
BOTH_DIR = 'both_dir'
IN_DIR = 'in_dir'
OUT_DIR = 'out_dir'
# Constants for specifying how weights should be merged.
# These values are accepted by the DiGraph.skeleton function.... |
argv = ['']
def exit(n):
pass
exit(0)
stdout = open("/dev/null")
stderr = open("/dev/null")
stdin = open("/dev/null")
|
class Eval:
"""
Eval
"""
def __init__(self):
self.predict_num = 0
self.correct_num = 0
self.gold_num = 0
self.precision = 0
self.recall = 0
self.fscore = 0
def clear(self):
"""
:return:
"""
self.predict_num = 0
... |
"""
1부터 N까지 모든 자연수의 합을 구하시오
S(N) = N + S(N-1)
"""
def get_sum(num):
if num == 1:
return 1
else:
return num + get_sum(num-1)
res = get_sum(10)
print(res)
|
x = int(input())
n = int(input())
a = []
for y in range(n):
a.append(input().split())
for y in range(n):
if x >= int(a[y][0]) and x <= int(a[y][1]):
print(a[y][2])
|
print("Sartu zenbakiak...")
a=int(input("Sartu lehenengoa: "))
b=int(input("sartu bigarrena: "))
def baino_haundiagoa(a, b):
if a > b:
return("Lehenengo zenbakia haundiagoa da.")
elif a < b:
return("Bigarren zenbakia haundiagoa da.")
else:
return("Zenbaki berdina sartu dezu.")
pr... |
'''
@author: Kittl
'''
def exportSubstations(dpf, exportProfile, tables, colHeads):
# Get the index in the list of worksheets
if exportProfile is 2:
cmpStr = "Substation"
elif exportProfile is 3:
cmpStr = ""
idxWs = [idx for idx,val in enumerate(tables[exportProfile-1]) if val == cm... |
array=list(map(int,input().split()))
print('Your Array :',array)
for i in range(0,len(array)-1):
if(array[i+1]<array[i]):
temp=array[i+1]
j=i
while(temp<array[j] and j>=0):
array[j+1]=array[j]
j-=1
array[j+1]=temp
print('Sorted Array : ',array) |
ENDINGS = ['.', '!', '?', ';']
def count_sentences(text):
text = text.strip()
if len(text) == 0:
return 0
split_result = None
for ending in ENDINGS:
separator = f'{ending} '
if split_result is None:
split_result = text.split(separator)
else:
split_result = [y for x in split_result for y in x.spli... |
# %% [1013. Partition Array Into Three Parts With Equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/)
# 問題:3つのグループの和が等しくなるように2箇所で区切れるかを返せ
# 解法:和の1/3に等しい回数を数える
class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
s = sum(A)
c, cs, s3 = 0, 0, s ... |
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
... |
# Under MIT License, see LICENSE.txt
__author__ = 'RoboCupULaval'
class TaskController:
"""Class added by composition to any task,
to keep track of the Task state
and logic flow.
This state-control class is separated
from the Task class so the Decorators
have a chance at compile-time security... |
'''
Get an undefined numbers of values and put them in a list.
In the end, show all the unique values in ascendent order.
'''
values = []
while True:
number = int(input('Choose a number: '))
if number not in values:
print(f'\033[32mAdd the number {number} to the list.\033[m')
values.ap... |
class Context(dict):
"""Model the execution context for a Resource.
"""
def __init__(self, request):
"""Takes a Request object.
"""
self.website = None # set in dynamic_resource.py
self.body = request.body
self.headers = request.headers
self.cooki... |
VOWELS = { c for c in "aeouiAEOUI" }
def swap_vowel_case_char(c :str) -> str:
return c.swapcase() if c in VOWELS else c
def swap_vowel_case(st: str) -> str:
return "".join(swap_vowel_case_char(c) for c in st)
|
# Marcelo Campos de Medeiros
# ADS UNIFIP
# REVISÃO DE PYTHON
# AULA 13 LAÇO DE REPETIÇÃO FOR ---> GUSTAVO GUANABARA
'''
Faça um Programa que leia o peso de cinco pessoas. No final mostre qual
foi maior e o menor peso lidos.
'''
print('='*30)
print('{:§^30}'.format(' PESO '))
print('='*30)
print()
#contadores os doi... |
"""Base classes for pipelines and pipeline blocks."""
class Block(object):
"""Base class for all blocks.
Notes
-----
Blocks should take their parameters in ``__init__`` and provide at least
the ``process`` method for taking in data and returning some result.
"""
def __init__(self, name=N... |
PuzzleInput = "PuzzleInput.txt"
f = open(PuzzleInput)
txt = f.readlines()
sums = []
k=0
for j in range(len(txt)):
for i in range(25):
for k in range(25):
if i == k:
continue
else:
sums.append(int(txt[i])+int(txt[k]))
if int(txt[25])... |
if __name__ == '__main__':
# Creating a tuple
x = ()
x = (1, )
print(type(x))
x = (1)
print(type(x))
x = (1, 2, 3, "Apple", True, 4.0)
x = ((1, 2, 3), (4, 5, 6))
#Accessing Tuple
x = (1, 2, 3, "Apple", True, (7, 7, 7), 4.0)
print(x[3])
print(x[-2])
print(x[1:2])... |
#
# @lc app=leetcode id=108 lang=python3
#
# [108] Convert Sorted Array to Binary Search Tree
#
# @lc code=start
# 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... |
class DecorationRepository:
def __init__(self):
self.decorations = []
@staticmethod
def get_obj_by_type(objects, obj_type):
result = [obj for obj in objects if obj.__class__.__name__ == obj_type]
return result
def add(self, decoration):
self.decorations.append(decoratio... |
class Envelope:
"""
Envelope to add metadata to a message.
This is an internal type and is not part of the public API.
:param message: the message to send
:type message: any
:param reply_to: the future to reply to if there is a response
:type reply_to: :class:`pykka.Future`
"""
# ... |
#Rost,B. and Sander,C. (1994) Conservation and prediction of solvent accessibility in
#protein families. Proteins, 20, 216–226.
macc = {}
macc['A'] = 106
macc['C'] = 135
macc['D'] = 163
macc['E'] = 194
macc['F'] = 197
macc['G'] = 84
macc['H'] = 184
macc['I'] = 169
macc['K'] = 205
macc['L'] = 164
macc['M'] = 188
macc['... |
class Libro:
def __init__(self, titulo, autor, isbn, genero ):
self.autor = autor
self.titulo = titulo
self.isbn = isbn
self.genero = genero
def descripcion(self):
print("El nombre del libro es " + self.titulo + " y es del género " + self.genero)
print("Su autor e... |
class NotValidAttributeException(Exception):
def __init__(self, message, errors):
super(NotValidAttributeException, self).__init__(message)
self.errors = errors
class NoReportFoundException(Exception):
def __init__(self, message, errors):
super(NoReportFoundException, self... |
# Desenvolva um programa que leia o primeiro termos e a razão de uma PA.
# No final, mostre os 10 primeiros termos dessa progressão.
# an = a1 + (n - 1) . r
# Onde,
# an : termo que queremos calcular
# a1: primeiro termo da P.A.
# n: posição do termo que queremos descobrir
# r: razão*/
print("=======================... |
n = int (input('Enter a number for prime number series : '))
for i in range(2,n):
for j in range(2,i):
if i % j == 0:
print(i,"is not a prime number because",j,"*",i//j,"=",i)
break
else:
print(i,"is a prime number") |
# -*- coding: utf-8 -*-
#################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# All Rights Reserved.
#
#
#
# This program is copyright property of the author mentioned abo... |
"""
Implement an algorithm to delete a node in the middle (ie., any node but the first and last node,
not necessarily the exact middle) of a singly linked list, given only access to that node.
Input: the node c from the linked list a -> b -> c -> d -> e -> f
Result: nothing is returned, but the new linked list looks ... |
class Solution:
def threeSumClosest(self, num, target):
num = sorted(num)
best_sum = num[0] + num[1] + num[2]
for i in range(len(num)):
j = i + 1
k = len(num) - 1
while j < k:
current_sum = num[i] + num[j] + num[k]
... |
'''
__iter__
如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法
__getitem__
使实例可以像list一样通过下标获取元素
'''
class demo02:
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器a,b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self):
if self.a != 0:... |
# -*- coding: utf-8 -*-
"""
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
empty_tuple = tuple()
print(empty_tuple)
# %%
amazon = ('Amazon', 'USA', 'Technology', 1)
google = ('Google', 'USA', 'Technology', 2)
# %%
name_google = google[0]
# %%
data = (amazon, google)
print(data)
# %%
a = ('Pawel', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#======================================================================
# Code for solving day 8 of AoC 2018
#======================================================================
VERBOSE = True
#------------------------------------------------------------------
#-----... |
flag=[0]*35
box = [
253, 194, 15, 13, 82,
129, 244, 80, 193, 233,
36, 54, 199, 69, 219,
74, 136, 6, 190, 144,
68, 57, 156, 153, 240,
65, 95, 135, 61, 179,
159, 183, 182, 130, 107]
target = [
174, 178, 102, 127, 22,
245, 143, 226, 245, 131,
65, 105, 135, 48, 94,
21, 185, 188, 225, 211,
116, 11,... |
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
i = 0
while 2**i <n:
i+=1
if 2**i==n:
return True
return False |
widget_defaults = dict(
font="FiraCode Nerd Font",
fontsize = 21,
padding = 2,
background=colors[2]
)
extension_defaults = widget_defaults.copy()
def init_widgets_list():
prompt = "{0}@{1}: ".format(os.environ["USER"], socket.gethostname())
widgets_list = [
widget.Sep(
... |
def feast(beast, dish):
x = len(beast)
y = len(dish)
if beast[0] == dish[0]:
if beast[x-1] == dish[y-1]:
return True
else:
return False
else:
return False
def feast1(beast, dish):
return beast[0]==dish[0] and dish[-1]==beast[-1] |
# encoding: utf-8
"""
location.py
Created by Thomas Mangin on 2014-06-22.
Copyright (c) 2014-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
# ===================================================================== Location
# file location
class Location(object):
def __... |
"""
https://edabit.com/challenge/FGzWE8vNyxtTrw3Qg
Number of Separate Regions
The function is given a rectangular matrix consisting of zeros and ones. Count the number of different regions and return the result. A separate region is a collection of ones interconnected horizontally and vertically. A region can have hol... |
# Every non-negative integer N has a binary representation, for example, 8 can be represented as “1000” in binary and 7 as “0111” in binary.
# The complement of a binary representation is the number in binary that we get when we change every 1 to a 0 and every 0 to a 1. For example, the binary complement of “1010” is ... |
#Dictionary is key value pairs.
d1 = {}
print(type(d1))
d2 ={ "Jiggu":"Burger", "Rohan":"Fish", "Ravi":"Roti"}
#print(d2["Jiggu"]) case sensitive,tell about there syn...
#we can make dictionary inside a dictionary
d3 = {"Jiggu":"Burger", "Rohan":"Fish", "Ravi":"Roti",
"Pagal":{"B":"Oats","L": "Rice","D":"C... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isValidBST(root):
arr = []
def inOrderTraversal(root):
if not root: return
if root.left: inOrderTraversal(root.left)
arr.append(root.val)
if root.right: inOrde... |
class CycleSetupCommon:
"""
realization needs self.h_int, self.gloc, self.g0, self.se, self.mu, self.global_moves,
self.quantum_numbers
"""
def initialize_cycle(self):
return {'h_int': self.h_int,'g_local': self.gloc, 'weiss_field': self.g0,
'self_energy': self.se, 'mu': self... |
__info__ = dict(
project = "PyCAMIA",
package = "<main>",
author = "Yuncheng Zhou",
create = "2021-12",
fileinfo = "File of string operations. "
)
__all__ = """
str_len
str_slice
find_all
sorted_dict_repr
enclosed_object
tokenize
""".split()
def str_len(str_:str, r:int=2):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.