content stringlengths 7 1.05M |
|---|
class Set:
""" Set Implement in Python 3 """
def __init__(self, values=None):
"""this is the constructor it gets called when you create a new Set."""
self.dict = {} # Each instance of set has it's own dict property
if values is not None:
for value in values:
... |
# 可写函数说明
def printme(str):
"打印任何传入的字符串"
print(str)
return
# 调用 printme 函数,不加参数会报错
# printme()
# 函数参数的使用不需要使用指定顺序:
# 可写函数说明
def printinfo(name, age):
"""打印任何传入的字符串"""
print("名字: ", name)
print("年龄: ", age)
return
# 调用printinfo函数
printinfo(age=50, name="runoob")
# 默认参数
# 调用函数时,如果没有传递参数... |
# -*- coding: utf-8 -*-
"""
Think Python: How to Think Like a Computer Scientist
Allen B. Downey
Chapter 3 Functions
Exercise 2
A function object is a value you can assign to a variable or pass as an argument.
For example, do_twice is a function that takes a function object as an argument
and calls it twice:
de... |
{ # pylint: disable=C8101,C8103
'name': 'Odoo Next - ',
'description': 'Enable Tax Calculations',
'version': '14.0.1.0.0',
'category': 'Localization',
'author': 'Code 137',
'license': 'OEEL-1',
'website': 'http://www.code137.com.br',
'contributors': [
'Fábio Luna <fabiocluna@hot... |
def digit_count1(n):
n = str(n)
return int(''.join(str(n.count(i)) for i in n))
def digit_count2(n):
num_counts = dict()
str_n = str(n)
for x in str_n:
if x not in num_counts:
num_counts[x] = 1
else:
num_counts[x] += 1
return int("".join(str(num_counts[x]) for x ... |
DARK_SKY_BASE_URL = 'https://api.darksky.net/forecast'
WEATHER_COLUMNS = [
'time',
'summary',
'icon',
'sunriseTime',
'sunsetTime',
'precipIntensity',
'precipIntensityMax',
'precipProbability',
'precipType',
'temperatureHigh',
'temperatureHighTime',
'temperatureLow',
... |
# Write a procedure, rotate which takes as its input a string of lower case
# letters, a-z, and spaces, and an integer n, and returns the string constructed
# by shifting each of the letters n steps, and leaving the spaces unchanged.
# Note that 'a' follows 'z'. You can use an additional procedure if you
# choose to as... |
# eisagwgh stoixeiwn
my_list = []
# insert the first element
my_list.append(2)
print("This is the new list: ", my_list)
# insert the second element
my_list.append(3)
print("This is the new list: ", my_list)
my_list.append("Names")
print("This is a mixed list, with integers and strings: ", my_list)
# Afairwntas e... |
def save():
"""
For now this function is a placeholder for the eventual function
which will save the state of the FHD program at certain points depending
on community feedback.
"""
print("If you're seeing this, then fhd_save_io hasn't been made yet.")
print("If you have ideas on how we shoul... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# parameters.py
# search query
search_query = 'site:linkedin.com/in/ AND "guide touristique" AND "paris"'
# file were scraped profile information will be stored
file_name = 'candidates.csv'
# login credentials
linkedin_username = 'YOUR EMAIL GOES HERE'
linkedin_password... |
"""Example Zigbee Devices."""
DEVICES = [
{
"endpoints": {
"1": {
"device_type": 2080,
"endpoint_id": 1,
"in_clusters": [0, 3, 4096, 64716],
"out_clusters": [3, 4, 6, 8, 4096, 64716],
"profile_id": 260,
... |
# Start of Lesson 2
#if else - do while(nope) - for loops - switch statements(nope) - conditions
my_list0 = [23, 1.5566, 'fruits', True]
num1 = 10
num2 = 5
#If statements
if num1 > num2:
print('Num1 is greater than Num2')
if num1 == num2:
print('Num1 is equal ')
if num1 < num2:
print('Num1 is less than ... |
# Taken from https://raw.githubusercontent.com/stripe/stripe-python/master/stripe/error.py
# Kudos
# The MIT License
#
# Copyright (c) 2010-2011 Stripe (http://stripe.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Softwa... |
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
temp3 = [[],[],[],[],[],[],[],[],[]] # 粗实线分隔的 3x3 的数组
for i in range(9):
temp1 = [] # 1.数字 1-9 在每一行只能出现一次。
temp2 = [] ... |
'''
Created on Dec 1, 2017
@author: Andrea Graziani - matricola 0189326
@version: 1.0
'''
class binarySearchTreeNode(object):
'''
This class represents a node of a binary search tree.
'''
def __init__(self, key, value):
'''
Constructs a newly allocated 'BinarySearchTreeNode' obje... |
# A tree is symmetric if its data and shape remain unchanged when it is
# reflected about the root node. The following tree is an example:
# 4
# / | \
# 3 5 3
# / \
# 9 9
# Given a k-ary tree, determine whether it is symmetric.
class Node:
def __init__(sel... |
# TODO(dragondriver): add more default configs to here
class DefaultConfigs:
WaitTimeDurationWhenLoad = 0.5 # in seconds
MaxVarCharLengthKey = "max_length"
MaxVarCharLength = 65535
EncodeProtocol = 'utf-8'
IndexName = "_default_idx"
|
#
# PySNMP MIB module Nortel-Magellan-Passport-SnaMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-SnaMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:28:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... |
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.allow_origin = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.token = ''
c.NotebookApp.password = ''
|
functions_str = """AllPlanes
BlackPixel
WhitePixel
ConnectionNumber
DefaultColormap
DefaultDepth
DefaultGC
DefaultRootWindow
DefaultScreenOfDisplay
ScreensOfDisplay
DefaultScreen
DefaultVisual
DisplayCells
DisplayPlanes
DisplayString
LastKnownRequestProcessed
NextRequest
ProtocolVersion
ProtocolRevision
QLength
RootWin... |
n = int(input('Digite um número para \n'
'calcular seu fatorial: '))
f = 1
c = n
print(f'Calculando {n}! = ', end='')
while c > 0:
print(f'{c}', end='')
print(' x ' if c > 1 else ' = ', end='')
f *= c
c -= 1
print(f'{f}') |
"""Message.py: stores a facebook message as a python object."""
class Message:
def __init__(self, name, date, timestamp, content):
self.name = name
self.date = date
self.content = content
self.timestamp = timestamp
|
# import
# Hier kommt ein Kommentar für das erste Programm, geschrieben am iPad.
print("Hello World 1")
# Hier kommt nochmal ein Kommentar.
print("Hallo Welt 2") |
'''input
2
212
1253
'''
total_case = int(input(''))
total = 0
for i in range(0, total_case):
inp = input('')
total += int(inp[:-1])**(int(inp[-1:]))
print(total) |
extensions = ['sphinxcontrib.opencontracting']
exclude_patterns = ['_build']
codelist_headers = {
'en': {'code': 'non-code', 'description': 'non-description'},
}
|
""" lista = ["item1", "item2", "item3"]
print(lista)
print(len(lista))
print(type(lista))
print("*"*10)
tuplas = ("item", "item2", "item3")
print(tuplas)
print(len(tuplas))
print(type(tuplas))
print(tuplas[2])
print(tuplas.count("item1"))
tuplas.append("item4")
print(tuplas)
lista = []
lista.append("item1")
print(lis... |
"""
Lecture about list and set
"""
my_list = [1,2,3,4,5,]
print(my_list)
my_nested_list = [1,2,3,my_list]
print(my_nested_list)
my_list[0]=6
print(my_list)
my_list.append(7)
print(my_list)
my_list.remove(7)
print(my_list)
my_list.sort()
print((my_list))
my_list.reverse()
print(my_list)
print(my_list+[8,9])
my... |
#
# PySNMP MIB module ASCEND-MIBTRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBTRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:28:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 00:51:31 2020
@author: Dilay Ercelik
"""
# Practice
# Return the number of even ints in the given array.
# Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
# Examples:
## count_evens([2, 1, 2, 3, 4]) → 3
## count_evens([2, 2, 0]... |
4.1
#將7這個值指派給變數guess_me,並編寫條件測試式
#當guess_me < 7時印出字串'too low', < 7時印出字串'too high', = 7時印出'just right'
guess_me = 7
if guess_me < 7:
print('too low')
elif guess_me > 7:
print('too high')
else:
print('just right')
4.2
#將7指派給變數guess_me,將1指派給變數start. 寫一個while迴圈來比較start與guess_me.
#在迴圈的結尾遞增start
guess_me = 7
sta... |
# Python
def fib():
a, b = 1, 1
while True:
yield a
a, b = b, a + b
for index, x in enumerate(fib()):
if index == 10:
break
print("%s" % x),
# Python 3
def fib3():
a, b = 1, 1
while True:
yield a
a, b = b, a + b
for index, x in enumerate(fib()):
if... |
def max_sublist_sum(arr):
max_ending_here = 0
max_so_far = 0
for x in arr:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
"""
def max_sublist_sum(arr):
max_ending_here = 0
max_so_far = 0
for x in arr:
... |
print('Hello World!')
print('This is how we print on the screen.')
print()
print('What just happened?')
print('This is a message on this line.', end=' ')
print('This is a message on the same line.')
print('Learning Python is FUN!') |
'''
There are 7 letter(symbols) that are used to represent Roman numerals:
I, V, X, L, C, D and M
Their values are:
I=1
V=5
X=10
L=50
C=100
D=500
M=1000
For example, two is written as II in Roman numeral, just two one's added togethrer.
Thirteen is written as XIII , The number seventeen is written as XVII
Roman numeral... |
class Solution:
def balancedStringSplit(self, s: str) -> int:
count_match = 0
count_L = 0
count_R = 0
for char in s:
if char == "L":
count_L += 1
if char == "R":
count_R += 1
if (count_L == count_R) & (count_L != 0... |
try:
print('test')
xpcall()
print('still going')
except:
print('Error in function')
print('running') |
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
color = image[sr][sc]
if color == newColor: return image
R, C = len(image), len(image[0])
@lru_cache(None)
def dfs(r, c):
if image[r][c] == color:
... |
def update_dictionary(d, key, value):
if d.get(key) != None:
d[key].append(value)
elif d.get(key*2) != None:
d[key*2].append(value)
else:
d[key*2] = [value]
words = input().lower().split(" ")
word={}
for i in words:
if word.get(i) != None:
word[i] = word[i] + 1
els... |
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'f',
'type': 'executable',
'sources': [
'f.c',
],
},
{
'target_na... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Libimagequant(Package):
"""Small, portable C library for high-quality conversion of RGBA images to
8-bit in... |
# Exemplo de entrada
entrada = ["a", "aa", "Essa", "Daqui", "aa", "aaaaa", "a"]
n = 2 # número de palavras consecutivas a serem verificadas
def maior_palavra_consecutiva(entrada, n):
# armazena o tamanho da lista de entrada em uma variável
tamanho_da_entrada = len(entrada)
if 0 <= tamanho_da_entrada <... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : french.py
@Time : 2020/09/07
@Author : flamme-demon
@Version : 0.2
@Contact :
@Desc :
'''
class LangFrench(object):
SETTING = "RÉGLAGES"
VALUE = "VALEUR"
SETTING_DOWNLOAD_PATH = "Emplacement des téléchargement... |
a=input("Enter the array to sort:")
n = len(a)
for i in range(n):
for j in range(0, n-i-1):
if a[j] > a[j+1] :
a[j], a[j+1] = a[j+1], a[j]
print(a) |
# Normal Function syntax
# def name(args):
# return
# Lambda Function syntax
# name = lambda args: return
# Normal
def dob(a):
return a*2
print(f'def 10x2: {dob(10)}')
# Lambda
dobro = lambda b: b*2
print(f'lambda 10x2: {dobro(10)}')
|
# Quick Tester for the logic used to reset the yaw slot count
TOTAL_SLOTS = 10
MAX_ABSOLUTE_ROTATIONS = 10
def round_yaw(current_yaw, target_yaw):
if (abs(current_yaw) >= TOTAL_SLOTS * MAX_ABSOLUTE_ROTATIONS):
target_yaw = target_yaw - current_yaw
current_yaw = 0
return (target_yaw, curren... |
variable = "var"
var2 = "2"
var3 = 3
print(variable)
print("---")
# No newline at the end
print(variable, end="")
print("---")
# More variables
print(variable, var2, var3)
print("---")
# Different separator
print(variable, var2, var3, sep=", ")
print("---")
# Personal recomendation for var printing (bit advanced, ... |
# coding=utf-8
class RequestAdapter:
"""
Helper class help to extract logging-relevant information from HTTP request object
"""
def __new__(cls, *arg, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls)
return cls._instance
@staticmethod... |
class TrieNode:
def __init__(self):
self.edges = dict()
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = TrieNode() # dummy root node
def addWord(self, word: str) -> None:
"""
Adds a word into the da... |
# -*- coding: utf-8 -*-
def get_default_encoding():
return "utf-8"
################################################################################
# 1: str/unicode wrappers used to prevent double-escaping. This is the
# same concept as django.utils.safestring and webhelpers.html.literal
class safe_bytes(str)... |
def get_bit(num, i):
#Return the value of the i-th bit in num.
num = int(to_binary_string(num), 2)
mask = 1 << i
return 1 if num & mask else 0
def set_bit(num, i):
#Sets the i-th bit in num to be 1.
num = int(to_binary_string(num), 2)
mask = 1 << i
return num | mask
def clear_bit(num, ... |
# Another way to access private members
class Student:
def __init__(self,name,age):
self.__name=name
self.__age=age
def display(self):
print('Name',self.__name,' Age',self.__age)
def setName(self,name):
self._Student__name=name #self. _ ClassName _ _ attributeName
st=Studen... |
# Stairway to the Sky II (200010300) => Eliza's Garden
calmEliza = 3112
garden = 920020000
if sm.hasQuest(calmEliza) or sm.hasQuestCompleted(calmEliza):
sm.warp(garden)
else:
sm.chat("Eliza's rage is still permeating the garden. Calm him down first.") |
print("Zakres = <0,50>")
for i in range (50):
if(i%5==0):
print(i)
|
#!/usr/bin/env python
NAME = 'Incapsula (Imperva Inc.)'
def is_waf(self):
if self.matchcookie(r'^incap_ses.*='):
return True
if self.matchcookie(r'^visid_incap.*='):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, respo... |
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
translation = translation + "g"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
|
#implementation of Queue in python3
class Queue:
#initialisation of queue
def __init__(self):
self.queue = []
#add an element
def enqueue(self,item):
self.queue.append(item)
#remove an element
def dequeue(self):
if len(self.queue)<1:
return None
else... |
# File: malwarebazaar_consts.py
#
# Copyright (c) 2021 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
# Define your constants here
ERR_CODE_MSG = "Error code unavailable"
ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action pa... |
def diff_a(a, b):
return list(set(a) - set(b)) + list(set(b) - set(a))
def diff_b(lists):
x = [list(set(i) - set(j)) for i in lists for j in lists]
return list(set([item for sublist in x for item in sublist]))
def main():
a = [1, 2, 3]
b = [1, 2, 5, 4]
c = [1, 3, 5, 6]
print(diff_a(a, b)) # [3, 5, 4]
... |
r"""
___ _ ___ _
/ _ \___ | | / (____ ____(_)
/ // / _ `| |/ / / _ / __/ /
/____/\_,_/|___/_/_//_\__/_/
"""
__title__ = 'Django DaVinci Crawling Project: {{ project_name }}'
__version__ = '0.1.0'
__author__ = 'Javier Alperte'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 BuildGroup Data S... |
kb = 1.381e-23
R = 11e-9
T = 25
e_rheo = 10
def getD(eta, err=0):
dD = 0
D = kb * (T + 273.15) / (6 * np.pi * R * eta)
if err:
dD = D * err / eta
return D, dD
def geteta(D, err=0):
deta = 0
eta = kb * (T + 273.15) / (6 * np.pi * R * D * 1e-18)
if err:
deta = eta * err / D... |
"""
File: boggle.py
Name: Brad
----------------------------------------
User will enter 4 rows of 4 single letters at the beginning,
and this program will start to find out all the
vocabularies composed of letters user entered.
"""
# This is the file name of the dictionary txt file.
# We will be checking if a word ex... |
class SetOfStacks(object):
def __init__(self, capacity=10):
self.stack_set = [[]]
self.cur = 0
self.capacity = capacity
def push(self, val):
if len(self.stack_set[self.cur]) >= self.capacity:
self.stack_set.append([])
self.cur += 1
self.stack_set[... |
class Coordenada:
def __init__(self,x,y):
self.x = x
self.y = y
def distancia(self, otra_coordenada):
x_diff = (self.x - otra_coordenada.x)**2
y_diff = (self.y - otra_coordenada.y)**2
return(x_diff + y_diff)**(1/2)
if __name__ == '__main__':
coord1 = Coordenada... |
n = 15 # change the value to chenge the size
print()
for i in range(0, n):
print('*'*(i+1),end='')
print(' '*(n - i),end='')
print(' '*(n - i - 1),end='')
print('*'*(i + 1),end='')
print('*'*(i),end='')
print(' '*(n - i),end='')
print(' '*(n - i - 1),end='')
print('*'*(i + 1),end='')
... |
# page 100 // homework 2021-01-07
# amended TASK:
# - progam that set total to 100
# - loop 3 times
total = 100
count = 0
# loop 3 times:
while count < 3:
number = input("enter a number: ")
number = int(number)
total -= number # shorter form of 'total = total - number'
... |
""" Params: Old Norse
"""
__author__ = [
"Clément Besnier <clemsciences@aol.com>",
"Patrick J. Burns <patrick@diyclassics.org>",
]
__license__ = "MIT License."
# As far as I know, hyphens were never used for compounds, so the tokenizer treats all hyphens as line-breaks
OldNorseTokenizerPatterns = [(r"\'", r"'... |
#
# PySNMP MIB module SWITCHING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SWITCHING-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:05:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
#
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pyasn1/license.html
#
class PyAsn1Error(Exception):
"""Base pyasn1 exception
`PyAsn1Error` is the base exception class (based on
:class:`Exception`) that repr... |
# a=[1,2,3,4,5,6,7,8,8,9]
# b=[1,2,3,4,5,6,7,8,8,9]
# if a==b:
# print("hello")
# else:
# print("not equal")
# n=int(input())
# for i in range(n):
# x=int(input())
# if x==1:
# print("Yes")
# elif x%2==0:
# print("Yes")
# else:
# print("No")
def pattern(inputv):
if ... |
#!/usr/bin/python
class Project:
def __init__ (self):
#Guarda el registro de ultimo uso
pass
def status (self):
self.activate = True
return self.activate
def AccessPublic():
pass
def AccessPrivar():
pass
class Rep:
def __init__(self, rep_name, access):
self.repositoryname = rep_name
self.typeac... |
# -*- coding: utf-8 -*-
# @Author: Zengjq
# @Date: 2019-02-20 17:07:27
# @Last Modified by: Zengjq
# @Last Modified time: 2019-02-20 19:25:48
# 60% -> 73%
class Solution:
def longestPalindrome(self, s: 'str') -> 'str':
result = ""
for i in range(len(s)):
lpd = self.do_expand(s, i... |
def math():
a, b, c = map(float, input().split())
if ((b + c) > a) and ((a + c) > b) and ((a + b) > c):
perimeter = (a + b + c)
print('Perimetro =', perimeter)
else:
area = (((a + b) / 2) * c).__format__('.1f')
print('Area =', area)
if __name__ == '__main__':
math()
|
dim = (512, 512, 1) # gray images
SEED = 1
multiply_by = 10
# Labels/n_classes
labels = sorted(['gun', 'knife'])
hues_labels = {'gun':0, 'knife': 25, 'background': 45}
# count background
n_classes = len(labels) + 1 # background
# number filters
n_filters = 32
# model name
model_name = '%s_model.hdf5'
# annotation file... |
# Copyright (c) 2017 Yingxin Cheng
#
# 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 agreed to in wr... |
# Group developers into cliques given an adjacency graph. This implementation is based in the recursive algorithm
# proposed by Bron and Kerbosch in 1973 and adapted from the pseudocode in
# https://en.wikipedia.org/wiki/Bron-Kerbosch_algorithm
def bron_kerbosch(r, p, x, graph, cliques):
if not p and not x:
... |
# vim: ts=2 sw=2 sts=2 et :
def mem1(f):
"Caching, simple case, no arguments."
cache = [0] # local memory
def wrapper(*l, **kw):
val = cache[0] = cache[0] or f(*l, **kw)
return val
return wrapper
def memo(f):
cache = {} # initialized at load time
def g(*lst): # called at load time
val = cache[... |
def rot(s):
return s[::-1]
def selfie_and_rot(s):
points = '.' * s.index('\n')
v = s.replace('\n', points + '\n')
k = s[::-1].replace('\n', '\n' + points)
return (points + '\n' + points).join((v, k))
def oper(fct, s):
return fct(s)
def rot2(string):
return string[::-1]
def selfie_and... |
#!/usr/bin/python
if (int(input()) - int(input()) == int(input())):
print("Candy Time")
else:
print("Keep Hunting")
|
class Config(object):
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 12345
CLIENT_HOST = "127.0.0.1"
CLIENT_PORT = 12346
UDP_BUF_SIZE = 1024
|
#Dictionary Keys must be hashable : An object is said to be hashable if it has a hash value that remains the same during its lifetime.
#which means immutable, such as int, string, booleans etc
dict = {
123: [1,2,3],
'A': "ABC",
True: "hello",
}
print(dict[123])
print(dict['A'])
print(dict[True]) |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# if len(s) != len(t):
# return False
char_dict = {}
for i in s:
if i in char_dict:
char_dict[i] += 1
... |
"""
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
"""
class Solution:
def isValid(self, s):
"""
:type s: str
:return bool
"""
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for ch in s:
if ch in mapping:
top_element = stack.po... |
DOCUMENTATION = """
module: test
author: Bradley Thornton (@cidrblock)
short_description: Short description here
description:
- A longer description here
version_added: 0.0.0
options:
param_str:
type: str
description:
- A string param
required: True
params_bool:
type: boo... |
def binarysearch(_list, _v, _min = 0, _max = None):
if _max == None:
_max = len(_list)
if _max == 0:
return False
middle_index = (_min + _max)/2
middle = _list[middle_index]
if _min == _max:
return False
if _min == _max - 1:
if _v == middle:
... |
# Declan Reidy - 23-02-2018
#
# Euler problem 5 - Exercise 4
#
# 2520 is the smallest number divisible by all numbers 1 to 10
i = 2520
for i in range(i,(20*19*18*17*16*15*14*13*12*11),20):
if (i % 20 ==0) and (i % 19 ==0) and (i % 18 ==0) and (i % 17 ==0) and (i % 16 ==0) and (i % 15 ==0) and (i % 14 ==0) and (i ... |
name_first_player = input()
name_second_player = input()
points_first = 0
points_second = 0
is_finished = False
card_first = input()
while card_first != 'End of game':
card_first = int(card_first)
card_second = int(input())
if card_first > card_second:
points_first += card_first - card_second
... |
""" Transitive-Inference model implementation.
"""
def rewardedStimulus(stim, pair):
return min([int(a) for a in pair]) == int(stim)
def sortedPair(pair):
return str(min([int(a) for a in pair])), str(max([int(a) for a in pair]))
def correctReply(pair):
return str(min([int(a) for a in pair]))
|
"""
@author Huaze Shen
@date 2019-10-06
"""
def maximal_rectangle(matrix):
if matrix is None or len(matrix) == 0 or matrix[0] is None or len(matrix[0]) == 0:
return 0
m = len(matrix)
n = len(matrix[0])
heights = [0 for i in range(n)]
result = 0
for i in range(m):
for j in range... |
MONTH_DAYS = {
"1" : 31,
"2" : 28,
"3" : 31,
"4" : 30,
"5" : 31,
"6" : 30,
"7" : 31,
"8" : 31,
"9" : 30,
"10" : 31,
"11" : 30,
"12" : 31,
}
TEMPLATE = "./template.xlsx" |
__author__ = 'julian'
class ProductosLookup(object):
def get_query(self,q,request):
return VProductos.objects.filter(descripcion__icontains=q,fecha_baja=None )
def format_result(self,objeto):
return u"%s" % (objeto.descripcion)
def format_item(self,objeto):
return unicode(objeto.de... |
# coding=utf-8
# 参考wiki
# https://en.m.wikipedia.org/wiki/Mersenne_Twister
# https://cedricvanrompay.gitlab.io/cryptopals/challenges/21.html
# https://zh.wikipedia.org/wiki/%E6%A2%85%E6%A3%AE%E6%97%8B%E8%BD%AC%E7%AE%97%E6%B3%95
class MT19937():
def __init__(self,seed):
self.pos = 0
self.x = list()
... |
def process_command(cmd, lst):
cl = cmd.split(' ')
if len(cl) == 3:
(act, op1, op2) = tuple(cl)
elif len(cl) == 2:
(act, op1) = tuple(cl)
elif len(cl) == 1:
act = cl[0]
# Executing the command
if act == 'insert':
lst.insert(int(op1), int(op2))
elif act == 'pr... |
"""
[09/22/2014] Challenge #181 [Easy] Basic Equations
https://www.reddit.com/r/dailyprogrammer/comments/2h5b2k/09222014_challenge_181_easy_basic_equations/
# [](#EasyIcon) _(Easy)_: Basic Equations
Today, we'll be creating a simple calculator, that we may extend in later challenges. Assuming you have done basic
alge... |
# https://leetcode.com/problems/two-sum/#/description
class Solution(object):
def twoSum(self, nums, target):
hash = {}
for i in range(0, len(nums)):
if not nums[i] in hash:
hash[target - nums[i]] = i
else:
return[hash[nums[i]]... |
class RequestError(Exception):
def __init__(self, status: int, *args):
super().__init__(*args)
self.status = status
|
DATE_FORMAT = 'Y-m-d' # 2018-07-08 # fallback, Django default
IO_DATE_FORMAT = 'Y-m-d' # 2018-07-08 # Default for i/o
LONG_DATE_FORMAT = 'F j, Y' # July 8, 2018
MEDIUM_DATE_FORMAT = 'M j, Y' # Jul 8, 2018 # Default for display
SHORT_DATE_FORMAT = 'n/j/Y' # 7/8/2018
MONTH_YEAR_FORMAT = 'M Y'
ISO_DATETIME = 'Y-m-d\TH:i:s... |
name = input("이름을 입력하세요 : ");
kor = input("국어점수를 입력하세요 : ")
eng = input("영어점수를 입력하세요 : ")
mth = input("수학점수를 입력하세요 : ")
outFp = open("data2.txt", "w", encoding="UTF-8")
outFp.writelines(name + " " + kor + " " + eng + " " + mth)
outFp.close()
print("--- 정상적으로 파일에 씀 ---") |
# Copyright 2017 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 a... |
#Leve modificação na função para além de retornar a lista somada,
#Retornar o score
def somar_adjacentes(linha, direcao):
if direcao == "a":
linha = linha[::-1]
tam_linha = len(linha)
aux = []
excluidos = []
ultimo = linha[-1:][0]
score = 0
# percorrendo do primeiro até o
# pe... |
"""Given a set of different coins denominations S and a total
T, find the smallest combination of coins that add up to total.
Example:
S = {1, 5, 10, 25}, T = 40
result = {5, 10, 25}
S = {1, 5, 9, 20}, T = 27 <- Notice that a greedy algorithm would fail here
result = {9, 9, 9}
"""
def find_number_o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.