content
stringlengths 7
1.05M
|
---|
with open('input.txt') as f:
lines = f.readlines()
ans = 0
for line in lines:
input, output = line.split(" | ")
for word in output.split():
length = len(word)
if length == 2 or length == 4 or length == 3 or length == 7:
ans += 1
print(ans)
|
def fibonacci_iterative(num):
a = 0
b = 1
total = 0
for _ in range(2, num + 1):
total = a + b
a = b
b = total
return total
def fibonacci_recursive(num):
if num < 2:
return num
return fibonacci_recursive(num-1) + fibonacci_recursive(num-2)
print(fibonacci_iterative(10))
print(fibonacci_recursive(10))
|
data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
def makedict(**kwargs):
return kwargs
data = makedict(red=1, green=2, blue=3)
print(data)
def dodict(*args, **kwds):
d = {}
for k, v in args: d[k] = v
d.update(kwds)
return d
tada = dodict(yellow=2, green=4, *data.items())
print(tada)
|
class CicloCompleto:
def run(self):
print('Lavando...')
print('Enjuagando...')
print('Centrifugando...')
print('Finalizado!')
class SoloCentrifugado:
def run(self):
print('Centrifugando...')
print('Finalizado!')
#Fachada que instancia código "complejo"
class LavadoraFacade:
def __init__(self):
self._ciclo_completo = CicloCompleto()
self._solo_centrifugado = SoloCentrifugado()
def ciclo_completo(self):
self._ciclo_completo.run()
def solo_centrifugado(self):
self._solo_centrifugado.run()
def main():
LavadoraFacade().ciclo_completo()
LavadoraFacade().solo_centrifugado()
if __name__ == "__main__":
main() |
"""69. Sqrt(x)"""
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
#####Practice
###############
l = 0
r = x
while l <= r:
mid = l + (r - l)//2
if mid*mid <= x < (mid+1)*(mid+1):
return mid
elif mid*mid > x:
r = mid - 1
else:
l = mid + 1
### short way
r = x
while r*r > x:
r = (r + x/r)//2
return r
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2014 Tech Receptives (<http://techreceptives.com>)
{
'name': 'Singapore - Accounting',
'author': 'Tech Receptives',
'website': 'http://www.techreceptives.com',
'category': 'Localization',
'description': """
Singapore accounting chart and localization.
=======================================================
After installing this module, the Configuration wizard for accounting is launched.
* The Chart of Accounts consists of the list of all the general ledger accounts
required to maintain the transactions of Singapore.
* On that particular wizard, you will be asked to pass the name of the company,
the chart template to follow, the no. of digits to generate, the code for your
account and bank account, currency to create journals.
* The Chart of Taxes would display the different types/groups of taxes such as
Standard Rates, Zeroed, Exempted, MES and Out of Scope.
* The tax codes are specified considering the Tax Group and for easy accessibility of
submission of GST Tax Report.
""",
'depends': ['base', 'account'],
'data': [
'data/l10n_sg_chart_data.xml',
'data/account_tax_data.xml',
'data/account_chart_template_data.yml',
],
}
|
# A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number
# of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
# For example, take 153 (3 digits):
# 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
# and 1634 (4 digits):
# 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
# The Challenge:
# Your code must return true or false depending upon whether the given number is a Narcissistic number in base 10.
# Error checking for text strings or other invalid inputs is not required, only valid integers will be passed into the function.
#https://www.codewars.com/kata/narcissistic-numbers/train/python
def is_narcissistic(num):
if 0:
return False
n = num
exponente = len(str(num))
sum = 0
while n > 0:
sum += pow(int(n % 10), exponente)
n = int(n/10)
return sum == num
print (is_narcissistic(12))
print (is_narcissistic(153))
print (is_narcissistic(1634)) |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Hello(object):
def hello(self, name='world'):
print('Hello, %s.' % name) |
class Solution:
"""
@param n: an integer
@param k: an integer
@return: how many problem can you accept
"""
def canAccept(self, n, k):
n = int(n / k)
start = 0
end = n
while start + 1 < end:
mid = start + int((end - start) / 2)
fact = ((1 + mid) * mid) / 2
if fact <= n:
start = mid
else:
end = mid
if ((1 + end) * end) / 2 <= n:
return end
return start |
#!/usr/bin/env python3
# 2020暑期排位5K_生日谜题
# https://codeforces.com/group/H9K9zY8tcT/contest/286081/problem/K
# bit-operation? 不适合python? 也能做
# 还能用dfs来做!?
t = input()
l = list(map(int,input().split()))
nob = 20 #as ai<10^5
n = len(l)
counts = [sum([(1<<i)&x == 0 for x in l]) for i in range(nob)] #count zero for each bit!
total = sum([((1 << n) - (1 << counts[i])) << i for i in range(nob)])
print(total)
|
# Note that we can only test things here all implementations must support
valid_data = [
("acceptInsecureCerts", [
False, None,
]),
("browserName", [
None,
]),
("browserVersion", [
None,
]),
("platformName", [
None,
]),
("pageLoadStrategy", [
None,
"none",
"eager",
"normal",
]),
("proxy", [
None,
]),
("timeouts", [
None, {},
{"script": 0, "pageLoad": 2.0, "implicit": 2**53 - 1},
{"script": 50, "pageLoad": 25},
{"script": 500},
]),
("unhandledPromptBehavior", [
"dismiss",
"accept",
None,
]),
("test:extension", [
None, False, "abc", 123, [],
{"key": "value"},
]),
]
invalid_data = [
("acceptInsecureCerts", [
1, [], {}, "false",
]),
("browserName", [
1, [], {}, False,
]),
("browserVersion", [
1, [], {}, False,
]),
("platformName", [
1, [], {}, False,
]),
("pageLoadStrategy", [
1, [], {}, False,
"invalid",
"NONE",
"Eager",
"eagerblah",
"interactive",
" eager",
"eager "]),
("proxy", [
1, [], "{}",
{"proxyType": "SYSTEM"},
{"proxyType": "systemSomething"},
{"proxy type": "pac"},
{"proxy-Type": "system"},
{"proxy_type": "system"},
{"proxytype": "system"},
{"PROXYTYPE": "system"},
{"proxyType": None},
{"proxyType": 1},
{"proxyType": []},
{"proxyType": {"value": "system"}},
{" proxyType": "system"},
{"proxyType ": "system"},
{"proxyType ": " system"},
{"proxyType": "system "},
]),
("timeouts", [
1, [], "{}", False,
{"invalid": 10},
{"PAGELOAD": 10},
{"page load": 10},
{" pageLoad": 10},
{"pageLoad ": 10},
{"pageLoad": None},
{"pageLoad": False},
{"pageLoad": []},
{"pageLoad": "10"},
{"pageLoad": 2.5},
{"pageLoad": -1},
{"pageLoad": 2**53},
{"pageLoad": {"value": 10}},
{"pageLoad": 10, "invalid": 10},
]),
("unhandledPromptBehavior", [
1, [], {}, False,
"DISMISS",
"dismissABC",
"Accept",
" dismiss",
"dismiss ",
])
]
invalid_extensions = [
"firefox",
"firefox_binary",
"firefoxOptions",
"chromeOptions",
"automaticInspection",
"automaticProfiling",
"platform",
"version",
"browser",
"platformVersion",
"javascriptEnabled",
"nativeEvents",
"seleniumProtocol",
"profile",
"trustAllSSLCertificates",
"initialBrowserUrl",
"requireWindowFocus",
"logFile",
"logLevel",
"safari.options",
"ensureCleanSession",
]
|
class CodesDict(object):
def __init__(self, codes):
self.__dict__.update(codes)
_codes = {
'waiting': 1,
'analysis': 2,
'paid': 3,
'available': 4,
'dispute': 5,
'returned': 6,
'canceled': 7,
}
codes = CodesDict(_codes)
|
class Monitor:
def __init__(self, controller, redis_address):
self.controller = controller
self.redis_address = redis_address
def _schedule(self, gid, nid, domain, name, args={}, cron='@every 1m'):
"""
Schedule the given jumpscript (domain/name) to run on the specified node according to cron specs
:param gid: Grid id
:param nid: Node id
:param domain: jumpscript domain
:param name: jumpscript name
:param args: jumpscript arguments
:param cron: cron specs according to https://godoc.org/github.com/robfig/cron#hdr-CRON_Expression_Format
:return:
"""
args = args.update({'redis': self.redis_address})
#
# key = '.'.join([str(gid), str(nid), domain, name])
# self.controller.schedule()
def _unschedule(self, gid, nid, domain, name):
"""
Unschedule the given jumpscript
:param gid: Grid id
:param nid: Node id
:param domain: jumpscript domain
:param name: jumpscript name
:return:
"""
def disk(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the disk monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def virtual_machine(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the vm monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def docker(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the docker monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def nic(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the nic monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def reality(self, gid, nid, args={}, cron='@every 10m'):
"""
Schedule the reality reader on the specified node. Reality jumpscript
will also use the aggregator client to report reality objects.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def logs(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the logs reader on the specified node. Logs jumpscript
will collects logs from various sources and use the aggregator client
to report logs.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
|
senseiraw = {
"name": "SteelSeries Sensei RAW (Experimental)",
"vendor_id": 0x1038,
"product_id": 0x1369,
"interface_number": 0,
"commands": {
"set_logo_light_effect": {
"description": "Set the logo light effect",
"cli": ["-e", "--logo-light-effect"],
"command": [0x07, 0x01],
"value_type": "choice",
"choices": {
"steady": 0x01,
"breath": 0x03,
"off": 0x05,
0: 0x00,
1: 0x01,
2: 0x02,
3: 0x03,
4: 0x04,
5: 0x05,
},
"default": "steady",
},
},
}
|
def ordering_fries():
print("Can I have some fried potatoes please?")
def countries_papagias_preferes():
print("Albania-Bulgaria-Romania...!")
|
"""
Description: find the area of triangle, given breadth and height
"""
# function definition of areatriangle
def areatriangle(breadth,height):
return (breadth*height)/2;
# input breadth and height
b = int(input("Enter the breadth of triangle: "))
h = int(input("Enter teh height of triangle: "))
print("The area of the triangle is: " + str(areatriangle(b,h)))
|
'''
Linked List has 2 parts : A node that stores the data and a pointer to the next Node.
So it is handled in 2 classes:
1. Node class with operations:
1. init function to get the data and next node value
2. get_data function to get the data of the node
3. set_data function to set the data of the node
4. get_next and set_function is again similar to the data function ; it would be to get and set the next node value respectively.
5. has_next fucntion returns a Boolean whether the node has a next pointer or not
2. Linked List class with operations:
1. init function to initilise the nodes
2. get_size to return the size of the Linked List
3. add function to add a node
4. remove function to remove a node
5. print_list to print the linked list
6. sort to sort the linked list
7. find function to find a item in a linked list
'''
class Node(object):
def __init__(self, data, nextNode=None):
self.data = data
self.nextNode = nextNode
def get_next(self):
''' get the next node value'''
return self.nextNode
def set_next(self, nextNode):
''' point the node to next node'''
self.nextNode = nextNode
def get_data(self):
return self.data
def set_data(self, data):
self.data = data
def has_next(self):
if self.nextNode == None:
return False
else:
return True
class LinkedList(object):
def __init__(self, r=None):
self.root = r
self.size = 0
def get_size(self):
return f"Size of the Linked List is : {self.size}"
def add(self, data):
newNode = Node(data, self.root)
self.root = newNode
self.size += 1
def remove(self, data):
r_node = self.root
prev_node = None
while r_node:
if r_node.get_data() == data:
if prev_node:
prev_node.set_next(r_node.get_next())
else:
self.root = r_node.get_next()
self.size -= 1
return True
else:
prev_node = r_node
r_node = r_node.get_next()
return False # item not found
def find(self, data):
find_data = self.root
while find_data:
if find_data.get_data() == data:
return f"Data found {data}"
elif find_data.get_next() == None:
return False # item not in list
else:
find_data = find_data.get_next()
return None
def print_list(self):
pass
def sort_list():
pass
linked = LinkedList()
linked.add(4)
linked.add(5)
linked.add(7)
linked.add(1)
print(linked.get_size())
print(str(linked.find(5)))
linked.add(9)
linked.add(0)
print(linked.get_size())
print(linked.find(0))
print(linked.remove(4))
print(linked.get_size())
print(linked.find(4))
|
"""
create by hanxiao on
"""
__author__ = "hanxiao"
PRE_PAGE = 15
BEANS_UPLOAD_ONE_BOOK = 0.5
|
class Foo():
def __init__(self, msg):
self.msg = msg
def show(self):
print(self.msg)
@classmethod
def foo_class_method(cls):
print(f"我是{cls.__name__}类, 但是我在调用自己的静态方法哦~ ", end='')
cls.foo_static_method()
@staticmethod
def foo_static_method():
print("Foo的静态方法")
if __name__ == '__main__':
foo = Foo("哈哈哈")
foo.show()
foo.foo_class_method()
foo.foo_static_method()
|
# This file was generated by wxPython's wscript.
VERSION_STRING = '4.0.7.post2'
MAJOR_VERSION = 4
MINOR_VERSION = 0
RELEASE_NUMBER = 7
BUILD_TYPE = 'release'
VERSION = (MAJOR_VERSION, MINOR_VERSION, RELEASE_NUMBER, '.post2')
|
## TASK 1 - here are the expected letter frequencies in the english language - convert them to a byte frequency table
expected_letter_frequencies = {'a': 8.167, 'b': 1.492, 'c': 2.782, 'd': 4.253, 'e': 12.702, 'f': 2.228, 'g': 2.015, 'h': 6.094, 'i': 6.966, 'j': 0.153, 'k': 0.772, 'l': 4.025, 'm': 2.406, 'n': 6.749, 'o': 7.507, 'p': 1.929, 'q': 0.095, 'r': 5.987, 's': 6.327, 't': 9.056, 'u': 2.758, 'v': 0.978, 'w': 2.361, 'x': 0.150, 'y': 1.974, 'z': 0.074}
expected_byte_frequencies = {}
for letter, frequency in expected_letter_frequencies.items():
byte = letter.encode('latin1')[0]
expected_byte_frequencies[byte] = frequency
|
def bracket_check(brackets):
'''function for checking a string of brackets'''
o = [ '{', '[', '(' ]
c = [ '}', ']', ')' ]
l = []
check = 0
for i in brackets:
if i in o:
check += 1
if i in c:
check -= 1
if check == 0:
print('yep')
else:
print('nah')
bracket_check('8x8y[E(x,y) ! [(P(x) ! P(y)) ! (P(y) ! P(a)]]')
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class TextTaskV2(object):
def __init__(self, dataId=None, content=None, title=None, dataType=None, callback=None, publishTime=None, callbackUrl=None):
"""
:param dataId: (Optional) 数据唯一标识,能够根据该值定位到该条数据
:param content: (Optional) 待检测文本,最长10000个字符, 用户发表内容,建议对内容中JSON、表情符、HTML标签、UBB标签等做过滤,只传递纯文本,以减少误判概率。请注意为了检测效果和性能,如果该字段长度超过10000字符,会截取前面10000字符进行检测和存储。该字段不能为空,如果为空会返回参数错误。
:param title: (Optional) 内容标题,适用于贴子、博客的文章标题等场景,建议抄送,辅助机审策略精准调优
:param dataType: (Optional) 子数据类型
:param callback: (Optional) 数据回调参数,调用方根据业务情况自行设计,当调用文本离线结果获取接口时,该接口会原样返回该字段,详细见文本离线检测结果获取。作为数据处理标识,因此该字段应该设计为能唯一定位到该次请求的数据结构,如对用户的昵称进行检测,dataId可设为用户标识(用户ID),用户修改多次,每次请求数据的dataId可能一致,但是callback参数可以设计成定位该次请求的数据结构,比如callback字段设计成json,包含dataId和请求的时间戳等信息,当然如果不想做区分,也可以直接把callback设置成dataId的值
:param publishTime: (Optional) 用户发表时间,UNIX 时间戳(毫秒值)
:param callbackUrl: (Optional) 人工审核结果回调通知到客户的URL。主动回调数据接口超时时间设置为2s,为了保证顺利接收数据,需保证接收接口性能稳定并且保证幂等性业务扩展参数
"""
self.dataId = dataId
self.content = content
self.title = title
self.dataType = dataType
self.callback = callback
self.publishTime = publishTime
self.callbackUrl = callbackUrl
|
class Utils:
@staticmethod
def fastModuloPow(num: int, pow: int, modulo: int) -> int:
result = 1
while pow:
if pow % 2 == 0:
num = (num ** 2) % modulo
pow = pow // 2
else:
result = (num * result) % modulo
pow -= 1
return result
|
# https://leetcode.com/problems/satisfiability-of-equality-equations
class UnionFind:
def __init__(self):
self.node2par = {chr(i + 97): chr(i + 97) for i in range(26)}
def find_par(self, x):
if self.node2par[x] == x:
return x
par = self.find_par(self.node2par[x])
return par
def unite(self, x, y):
x, y = self.find_par(x), self.find_par(y)
if x == y:
return
if x < y:
self.node2par[y] = x
else:
self.node2par[x] = y
class Solution:
def equationsPossible(self, equations):
uf = UnionFind()
neqs = []
for eq in equations:
if eq[1] == "=":
uf.unite(eq[0], eq[-1])
else:
neqs.append(eq)
for neq in neqs:
if uf.find_par(neq[0]) == uf.find_par(neq[-1]):
return False
return True
|
#
# PySNMP MIB module A3COM-HUAWEI-DHCPSNOOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-DHCPSNOOP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:04:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
hwdot1qVlanIndex, = mibBuilder.importSymbols("A3COM-HUAWEI-LswVLAN-MIB", "hwdot1qVlanIndex")
h3cCommon, = mibBuilder.importSymbols("A3COM-HUAWEI-OID-MIB", "h3cCommon")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Gauge32, Counter64, ModuleIdentity, Unsigned32, ObjectIdentity, Counter32, iso, Bits, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, IpAddress, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Counter64", "ModuleIdentity", "Unsigned32", "ObjectIdentity", "Counter32", "iso", "Bits", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "IpAddress", "TimeTicks", "Integer32")
TextualConvention, MacAddress, RowStatus, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "MacAddress", "RowStatus", "DisplayString", "TruthValue")
h3cDhcpSnoop = ModuleIdentity((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36))
if mibBuilder.loadTexts: h3cDhcpSnoop.setLastUpdated('200501140000Z')
if mibBuilder.loadTexts: h3cDhcpSnoop.setOrganization('Huawei-3com Technologies Co.,Ltd.')
if mibBuilder.loadTexts: h3cDhcpSnoop.setContactInfo('Platform Team Beijing Institute Huawei-3com Tech, Inc. Http:\\\\www.huawei-3com.com E-mail:[email protected]')
if mibBuilder.loadTexts: h3cDhcpSnoop.setDescription('The private mib file includes the DHCP Snooping profile.')
h3cDhcpSnoopMibObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1))
h3cDhcpSnoopEnable = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopEnable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopEnable.setDescription('DHCP Snooping status (enable or disable).')
h3cDhcpSnoopTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2), )
if mibBuilder.loadTexts: h3cDhcpSnoopTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTable.setDescription("The table containing information of DHCP clients listened by DHCP snooping and it's enabled or disabled by setting h3cDhcpSnoopEnable node.")
h3cDhcpSnoopEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1), ).setIndexNames((0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopClientIpAddressType"), (0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopClientIpAddress"))
if mibBuilder.loadTexts: h3cDhcpSnoopEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopEntry.setDescription('An entry containing information of DHCP clients.')
h3cDhcpSnoopClientIpAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 1), InetAddressType().clone('ipv4'))
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddressType.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddressType.setDescription("DHCP clients' IP addresses type (IPv4 or IPv6).")
h3cDhcpSnoopClientIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 2), InetAddress())
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddress.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddress.setDescription("DHCP clients' IP addresses collected by DHCP snooping.")
h3cDhcpSnoopClientMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 3), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientMacAddress.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientMacAddress.setDescription("DHCP clients' MAC addresses collected by DHCP snooping.")
h3cDhcpSnoopClientProperty = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("static", 1), ("dynamic", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientProperty.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientProperty.setDescription('Method of getting IP addresses collected by DHCP snooping.')
h3cDhcpSnoopClientUnitNum = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientUnitNum.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientUnitNum.setDescription('IRF (Intelligent Resilient Fabric) unit number via whom the clients get their IP addresses. The value 0 means this device does not support IRF.')
h3cDhcpSnoopTrustTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3), )
if mibBuilder.loadTexts: h3cDhcpSnoopTrustTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustTable.setDescription('A table is used to configure and monitor port trusted status.')
h3cDhcpSnoopTrustEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: h3cDhcpSnoopTrustEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustEntry.setDescription('An entry containing information about trusted status of ports.')
h3cDhcpSnoopTrustStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("untrusted", 0), ("trusted", 1))).clone('untrusted')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopTrustStatus.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustStatus.setDescription('Trusted status of current port which supports both get and set operation.')
h3cDhcpSnoopVlanTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4), )
if mibBuilder.loadTexts: h3cDhcpSnoopVlanTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanTable.setDescription('A table is used to configure and monitor DHCP Snooping status of VLANs.')
h3cDhcpSnoopVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1), ).setIndexNames((0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopVlanIndex"))
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEntry.setDescription('The entry information about h3cDhcpSnoopVlanTable.')
h3cDhcpSnoopVlanIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647)))
if mibBuilder.loadTexts: h3cDhcpSnoopVlanIndex.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanIndex.setDescription('Current VLAN index.')
h3cDhcpSnoopVlanEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEnable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEnable.setDescription('DHCP Snooping status of current VLAN.')
h3cDhcpSnoopTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2))
h3cDhcpSnoopTrapsPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0))
h3cDhcpSnoopTrapsObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1))
h3cDhcpSnoopSpoofServerMac = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 1), MacAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerMac.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerMac.setDescription('MAC address of the spoofing server and it is derived from link-layer header of offer packet. If the offer packet is relayed by dhcp relay entity, it may be the MAC address of relay entity. ')
h3cDhcpSnoopSpoofServerIP = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 2), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerIP.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerIP.setDescription("IP address of the spoofing server and it is derived from IP header of offer packet. A tricksy host may send offer packet use other host's address, so this address can not always be trust. ")
h3cDhcpSnoopSpoofServerDetected = NotificationType((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0, 1)).setObjects(("IF-MIB", "ifIndex"), ("A3COM-HUAWEI-LswVLAN-MIB", "hwdot1qVlanIndex"), ("A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopSpoofServerMac"), ("A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopSpoofServerIP"))
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerDetected.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerDetected.setDescription('To detect unauthorized DHCP servers on a network, the DHCP snooping device sends DHCP-DISCOVER messages through its downstream port (which is connected to the DHCP clients). If any response (DHCP-OFFER message) is received from the downstream port, an unauthorized DHCP server is considered present, and then the device sends a trap. With unauthorized DHCP server detection enabled, the interface sends a DHCP-DISCOVER message to detect unauthorized DHCP servers on the network. If this interface receives a DHCP-OFFER message, the DHCP server which sent it is considered unauthorized. ')
mibBuilder.exportSymbols("A3COM-HUAWEI-DHCPSNOOP-MIB", h3cDhcpSnoopClientProperty=h3cDhcpSnoopClientProperty, h3cDhcpSnoopTraps=h3cDhcpSnoopTraps, h3cDhcpSnoopTrapsObject=h3cDhcpSnoopTrapsObject, h3cDhcpSnoopVlanEnable=h3cDhcpSnoopVlanEnable, h3cDhcpSnoopEnable=h3cDhcpSnoopEnable, h3cDhcpSnoopClientIpAddress=h3cDhcpSnoopClientIpAddress, h3cDhcpSnoopVlanEntry=h3cDhcpSnoopVlanEntry, h3cDhcpSnoopEntry=h3cDhcpSnoopEntry, PYSNMP_MODULE_ID=h3cDhcpSnoop, h3cDhcpSnoopTrapsPrefix=h3cDhcpSnoopTrapsPrefix, h3cDhcpSnoopClientIpAddressType=h3cDhcpSnoopClientIpAddressType, h3cDhcpSnoopSpoofServerMac=h3cDhcpSnoopSpoofServerMac, h3cDhcpSnoopTrustEntry=h3cDhcpSnoopTrustEntry, h3cDhcpSnoopSpoofServerIP=h3cDhcpSnoopSpoofServerIP, h3cDhcpSnoop=h3cDhcpSnoop, h3cDhcpSnoopTrustStatus=h3cDhcpSnoopTrustStatus, h3cDhcpSnoopClientUnitNum=h3cDhcpSnoopClientUnitNum, h3cDhcpSnoopTable=h3cDhcpSnoopTable, h3cDhcpSnoopTrustTable=h3cDhcpSnoopTrustTable, h3cDhcpSnoopSpoofServerDetected=h3cDhcpSnoopSpoofServerDetected, h3cDhcpSnoopVlanIndex=h3cDhcpSnoopVlanIndex, h3cDhcpSnoopClientMacAddress=h3cDhcpSnoopClientMacAddress, h3cDhcpSnoopMibObject=h3cDhcpSnoopMibObject, h3cDhcpSnoopVlanTable=h3cDhcpSnoopVlanTable)
|
#Copyright (c) 2020 Jan Kiefer
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
class ChatUsr:
def __init__(self, utfmsg):
self.wob_id = utfmsg.get_int_arg(1)
self.message = utfmsg.get_string_arg(2)
self.type = utfmsg.get_int_list_arg(0)[2]
self.mode = 0 if utfmsg.get_arg_count() <= 3 else utfmsg.get_int_arg(3)
self.overheard = False if utfmsg.get_arg_count() <= 4 else utfmsg.get_boolean_arg(4)
class ChatSrv:
def __init__(self, utfmsg):
self.message = utfmsg.get_string_arg(1) |
ast = int(input("Ingrese numero de asteroides"))
nom =input("Ingrese nombre de asteroides")
print("Los",ast,"asteroides",nom,"caen del cielo") |
#!/usr/bin/env python
compsys={
'Artisan':{
'db':'file-store',
'objects':['Artisan','Product','Order','Customer'],
},
'Central Office user':{
'db':'file-store',
'objects':['Artisan','Product','Order','Customer'],
},
}
|
def main():
my_integ_loop.getIntegrator( trick.Runge_Kutta_2, 4)
trick.stop(300.0)
if __name__ == "__main__":
main()
|
# Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento:
# - à vista dinheiro/cheque: 10% de desconto
# - à vista no cartão: 5% de desconto
# - em até 2x no cartão: preço normal
# - 3x ou mais no cartão: 20% de juros
print('-' * 100)
print('{: ^100}'.format('EXERCÍCIO 044 - GERENCIADOR DE PAGAMENTOS'))
print('-' * 100)
preco = float(input('Preço total das compras: R$ '))
print('\nFormas de pagamento:\n[ 1 ] À vista - dinheiro/cheque \n[ 2 ] À vista - cartão \n[ 3 ] 2x - cartão \n[ 4 ] mais de 2x - cartão\n')
opcao = int(input('Digite sua opção: '))
parcelas = 0
desconto = 0
juros = 0
if opcao in range(1,5):
if opcao == 1:
preco_final = preco - (preco * 0.10)
desconto = preco * 0.10
elif opcao == 2:
preco_final = preco - (preco * 0.05)
desconto = preco * 0.05
elif opcao == 3:
preco_final = preco
parcelas = preco_final / 2
elif opcao == 4:
tot_parcelas = int(input('Quantas parcelas? '))
if tot_parcelas > 2:
preco_final = preco * 1.20
parcelas = preco_final / tot_parcelas
juros = preco * 0.20
else:
preco_final = 0
print('\nOPÇÃO INVÁLIDA!')
print(f'\nValor das parcelas: R$ {parcelas:.2f} \nDesconto: R$ {desconto:.2f} \nJuros: R$ {juros:.2f} \nPreço final: R$ {preco_final:.2f}')
else:
print('Opção inválida! Tente novamente mais tarde...')
print('-' * 100)
input('Pressione ENTER para sair...')
|
S_ASK_DOWNLOAD = 0
C_ANSWER_YES = 1
C_ANSWER_NO = 2
S_ASK_UPLOAD = 3
S_ASK_WAIT = 4
S_BEGIN = 5
|
#!/usr/bin/env python3
n = 4
A = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2],
[2, 0.00001, 1, 0.4]]
b = [0, 1, 2, 3]
# Gauss elim
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print("A:", A)
print("b:", b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print("x:", x)
# External stability
print("External stability")
A = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2],
[2, 0.00001, 1, 0.4]]
db = 0.3
da = 0.3
dA = [[da for j in range(n)] for i in range(n)]
b = [db for i in range(n)]
for i in range(n):
for j in range(n):
b[i] -= dA[i][j] * x[j]
print("new b:", b)
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print("A:", A)
print("b:", b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print("x:", x)
|
depends = ["unittest"]
description = """
Plug and play integration with the Jenkins Coninuous Integration server.
For more information, visit:
http://www.jenkins-ci.org/
""" |
def keyExtract(array, key):
"""Returns values of specific key from list of dicts.
Args:
array (list): List to be processed.
key (str): Key to extract.
Returns:
list: List of extracted values.
Example:
>>> keyExtract([
{'a': 0, ...}, {'a': 1, ...}, {'a': 2, ...}, ...
], 'a')
<<< [0, 1, 2]
"""
res = list()
for item in array:
res.append(item[key])
return res
def unduplicate(words):
"""Deletes duplicates from list.
Args:
words (list): List of hashable data.
Returns:
list: Unduplicated list.
Raises:
TypeError: Data of the list is not hashable (list, for example).
"""
return list(
set(words)
)
def reorder(li: list, a: int, b: int):
"""Reorder li[a] with li[b].
Args:
li (list): List to process.
a (int): Index of first item.
b (int): Index of second item.
Returns:
list: List of reordered items.
Example:
>>> reorder([a, b, c], 0, 1)
<<< [b, a, c]
"""
li[a], li[b] = li[b], li[a]
return li
def isSupsetTo(d: dict, what: dict):
"""Check whether one `d` dict is supset or equal to `what` dict. This means
that all the items from `what` is equal to `d`.
Args:
d, what (dict): Dicts to compare.
Returns:
bool: True if d > what, False otherwise.
"""
for key, value in what.items():
if d[key] != value:
return False
return True
def findIn(d: dict, equal):
"""Find and return record in dictionary which is associated with `equal`.
May be useful for searching unique objects in large amounts of data.
Args:
d (dict): Dictionary where to search in.
equal (*): What to look for. If it's a dict, item which is supset for
the given will be found.
Returns:
namedtuple: DictItem(key=..., item=...)
Example:
>>> findIn({'a': 0, 'b': 1}, 1)
<<< DictItem(key='b', item=1)
>>> findIn({'a': {'b': 'c', 'd': 'e'}}, {'d': 'e'})
<<< DictItem(key='a', item={'b': 'c', 'd': 'e'})
"""
for key, item in d.items():
if (
type(equal) is dict and isSupsetTo(item, equal)
) or item == equal:
return {"key": key, "item": item}
raise KeyError("Value was not found")
|
#Pat McDonald - 8/2/2018
#Exercise 3: Collatz conjecture
#Week 3 of Programming and Scripting
#Inspired by Reddit!: https://www.reddit.com/r/Python/comments/57r6bf/collatz_conjecture_program/?st=jdhil1j5&sh=ba8fd995
n = int(input("Type an integer: "))
print(n)
while n != 1:
if (n % 2 == 0):
#(n / 2) outputs a float , so I tried //
n = n // 2
print(n)
else:
n = (3 * n) + 1
print(n)
|
n = int(input())
lista = [int(x) for x in input().split()]
qtde = lista.count(0)
indice = []
for i in range(0,qtde):
indice.append(lista.index(0))
lista[indice[i]] = 2
for i in range(0,n):
menor = 100000
for j in range(0,len(indice)):
temp = abs(i - indice[j])
if(temp < menor):
menor = temp
if menor >= 9:
print("9",end=" ")
else:
print(menor,end=" ")
|
"""Codewars: Happy Numbers
6 kyu
URL:https://www.codewars.com/kata/59d53c3039c23b404200007e/train/python
Math geeks and computer nerds love to anthropomorphize numbers and
assign emotions and personalities to them. Thus there is defined the
concept of a "happy" number. A happy number is defined as an integer
in which the following sequence ends with the number 1.
Start with the number itself.
Calculate the sum of the square of each individual digit.
If the sum is equal to 1, then the number is happy. If the sum is not
equal to 1, then repeat steps 1 and 2. A number is considered unhappy
once the same number occurs multiple times in a sequence because this
means there is a loop and it will never reach 1.
For example, the number 7 is a "happy" number:
(7 ** 2)
7^2 = 49 --> 42 + 92 = 97 --> 92 + 72 = 130 --> 12 + 32 + 02 =
10 --> 12 + 02 = 1
Once the sequence reaches the number 1, it will stay there forever
since 12 = 1
On the other hand, the number 6 is not a happy number as the sequence
that is generated is the following: 6, 36, 45, 41, 17, 50, 25, 29,
85, 89, 145, 42, 20, 4, 16, 37, 52, 29
Once the same number occurs twice in the sequence, the sequence is
guaranteed to go on infinitely, never hitting the number 1, since it
repeat this cycle.
Your task is to write a program which will print a list of all happy
numbers between 1 and x (both inclusive), where:
2 <= x <= 5000
"""
def _sum_squares(num):
ss = 0
while num > 0:
div, digit = num // 10, num % 10
ss += digit * digit
num = div
return ss
def _is_happy_number(num):
# Check if num is happy number.
seens = set()
while num > 1: # stop when num == 1
ss = _sum_squares(num)
if ss in seens:
return False
seens.add(ss)
num = ss
return True
def happy_numbers(n):
result = []
for num in range(1, n + 1):
# Check if a num is happy number.
if _is_happy_number(num):
result.append(num)
return result
def main():
# Output: [1, 7, 10]
n = 10
print(happy_numbers(n))
# assert happy_numbers(10) == [1, 7, 10]
# assert happy_numbers(50) == [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]
# assert happy_numbers(100) == [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]
if __name__ == '__main__':
main()
|
N = int(input())
S = str(input())
flag = False
half = (N+1) // 2
if S[:half] == S[half:N]:
flag = True
if flag:
print("Yes")
else:
print("No") |
#!/usr/bin/env python
weight = input("your weight is? ")
height = input("your height is? ")
bmi = float(weight) / ( float(height) ** 2 )
print(f"your bmi: {bmi:.2f}")
if bmi <= 18.5:
print("you are so thin!")
elif bmi <= 25 and bmi > 18.5:
print("well, you are fit.")
elif bmi <= 28 and bmi > 25:
print("it looks you are a little heavy.")
elif bmi <= 32 and bmi > 28:
print("you are fat, what about doing exercise?")
else:
print("i dont want to tell the truth, but could you active? otherwise you may die of you fat")
|
#!/usr/bin/env conda-execute
# conda execute
# env:
# - python ==3.5
# - conda-build
# - pygithub >=1.29
# - pyyaml
# - requests
# - setuptools
# - tqdm
# channels:
# - conda-forge
# run_with: python
# TODO take package or list of packages
# TODO take github url or github urls
# TODO If user doesn't have a fork of conda-forge create one
# TODO if user doesn't have a branch for this package, create one
# TODO run conda smithy pypi package
# TODO If successful, parse generated meta.yaml
# TODO Drop any meta.yaml build reqs
# TODO Drop any test reqs
# TODO Add sections to bring in line with the standard template
# TODO Add variable to bring in line with the standard template
# TODO change the setup script based on whether or not setuptools is required
# TODO deal with license file
# TODO commit the modified meta.yaml to user/staged-recipes:branch
# TODO submit pull request to conda-forge/staged-recipes:master as a new recipe.
def main():
return
if __init__ == "__main__":
main()
|
class SvResponseBase:
def __init__(self, cl_request):
self.cl_request = cl_request
def payload():
""" OVERRIDE THIS TO IMPLEMENT """
raise
|
#! env\bin\python
# Ryan Simmons
# Coffee Machine Project
class CoffeeMachine:
# the values in supplies refers to 1-1 with this
supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
def __init__(self, supplies):
self.supplies = supplies
def supply_checker(self, drink):
# Money is represented as the value taken (negative) there always less than and should not cause an error
for i in range(len(drink)):
if drink[i] > self.supplies[i]:
print(f'Sorry not enough {self.supply_str[i]} !')
break
else:
for i in range(len(drink)):
self.supplies[i] -= drink[i] # Completes the transaction for the drink
print('I have enough resources, making you a coffee!')
def drink_maker(self):
drink = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ")
# Inputs the value for particular drinks into supply_checker()
if drink == '1':
espresso = [250, 0, 16, 1, -4]
self.supply_checker(espresso)
elif drink == '2':
latte = [350, 75, 20, 1, -7]
self.supply_checker(latte)
elif drink == '3':
cappuccino = [200, 100, 12, 1, -6]
self.supply_checker(cappuccino)
else:
return
def filler(self):
# supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
self.supplies[0] += int(input(f'Write how many ml of {self.supply_str[0]} do you want to add: '))
self.supplies[1] += int(input(f'Write how many ml of {self.supply_str[1]} do you want to add: '))
self.supplies[2] += int(input(f'Write how many grams of {self.supply_str[2]} do you want to add: '))
self.supplies[3] += int(input(f'Write how many {self.supply_str[3]} of coffee do you want to add: '))
def remaining(self):
# supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
print('The coffee machine has:')
for i in range(len(self.supplies)):
print(f'{self.supplies[i]} of {self.supply_str[i]}')
# Only method that user should have to interact with, Like a real cafe!
def barista(self):
while True:
action = input('Write action (buy, fill, take, remaining, exit): ')
if action == 'buy':
self.drink_maker()
elif action == 'fill':
self.filler()
elif action == 'take':
print(f'I gave you ${self.supplies[4]}')
self.supplies[4] = 0
elif action == 'remaining':
self.remaining()
elif action == 'exit':
break
print()
# Debugging
my_supplies = [400, 540, 120, 9, 550]
my_coffee = CoffeeMachine(my_supplies)
my_coffee.barista()
|
"""
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of
favorite restaurants represented by strings. You need to help them find out their common interest
with the least list index sum. If there is a choice tie between answers, output all of them with
no order requirement. You could assume there always exists an answer.
Example 1:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index
sum 1 (0+1).
Note:
1. The length of both lists will be in the range of [1, 1000].
2. The length of strings in both lists will be in the range of [1, 30].
3. The index is starting from 0 to the list length minus 1.
4. No duplicates in both lists.
"""
class Solution:
def findRestaurant(self, list1, list2):
d = {}
for i, x in enumerate(list1):
d[x] = i
res = {}
for j, y in enumerate(list2):
if y in d:
res[y] = d[y] + j
tmp = sorted(res, key=res.get)
return [x for x in tmp if res[x] == res[tmp[0]]]
|
# Write a program to print the pattern
def pattern(a):
print("Output :")
for i in range(1, a+1):
c = 1
for k in range(a, i, -1):
print(" ", end="")
for j in range(1, 2*i):
if j < i:
print(c, end="")
c += 1
else:
print(c, end="")
c -= 1
print()
a = int(input("Input : "))
pattern(a)
|
# O(n ^ 4)
# class Solution:
# def countQuadruplets(self, nums: List[int]) -> int:
# n = len(nums)
# ans = 0
# for a in range(n - 3):
# for b in range(a + 1, n - 2):
# for c in range(b + 1, n -1):
# for d in range(c + 1, n):
# if nums[a] + nums[b] + nums[c] == nums[d]:
# ans += 1
# return ans
# O(n ^ 3)
# class Solution:
# def countQuadruplets(self, nums: List[int]) -> int:
# n = len(nums)
# cnt = defaultdict(int)
# ans = 0
# for c in range(n - 2, 1, -1):
# cnt[nums[c + 1]] += 1
# for a in range(c - 1):
# for b in range(a + 1, c):
# ans += cnt[nums[a] + nums[b] + nums[c]]
# return ans
# O(n ^ 2)
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
n = len(nums)
cnt = defaultdict(int)
ans = 0
for b in range(n - 3, 0, -1):
for d in range(b + 2, n):
cnt[nums[d] - nums[b + 1]] += 1
for a in range(b):
ans += cnt[nums[a] + nums[b]]
return ans
|
# Constants
#
# Device Variables
VAR_BILLINGPERIODDURATION = 'zigbee:BillingPeriodDuration'
VAR_BILLINGPERIODSTART = 'zigbee:BillingPeriodStart'
VAR_BLOCK1PRICE = 'zigbee:Block1Price'
VAR_BLOCK1THRESHOLD = 'zigbee:Block1Threshold'
VAR_BLOCK2PRICE = 'zigbee:Block2Price'
VAR_BLOCK2THRESHOLD = 'zigbee:Block2Threshold'
VAR_BLOCK3PRICE = 'zigbee:Block3Price'
VAR_BLOCK3THRESHOLD = 'zigbee:Block3Threshold'
VAR_BLOCK4PRICE = 'zigbee:Block4Price'
VAR_BLOCK4THRESHOLD = 'zigbee:Block4Threshold'
VAR_BLOCK5PRICE = 'zigbee:Block5Price'
VAR_BLOCK5THRESHOLD = 'zigbee:Block5Threshold'
VAR_BLOCK6PRICE = 'zigbee:Block6Price'
VAR_BLOCK6THRESHOLD = 'zigbee:Block6Threshold'
VAR_BLOCK7PRICE = 'zigbee:Block7Price'
VAR_BLOCK7THRESHOLD = 'zigbee:Block7Threshold'
VAR_BLOCK8PRICE = 'zigbee:Block8Price'
VAR_BLOCK8THRESHOLD = 'zigbee:Block8Threshold'
VAR_BLOCKNPRICE = 'zigbee:Block{}Price'
VAR_BLOCKNTHRESHOLD = 'zigbee:Block{}Threshold'
VAR_BLOCKPERIODCONSUMPTION = 'zigbee:BlockPeriodConsumption'
VAR_BLOCKPERIODDURATION = 'zigbee:BlockPeriodDuration'
VAR_BLOCKPERIODNUMBEROFBLOCKS = 'zigbee:BlockPeriodNumberOfBlocks'
VAR_BLOCKPERIODSTART = 'zigbee:BlockPeriodStart'
VAR_BLOCKTHRESHOLDDIVISOR = 'zigbee:BlockThresholdDivisor'
VAR_BLOCKTHRESHOLDMULTIPLIER = 'zigbee:BlockThresholdMultiplier'
VAR_CURRENCY = 'zigbee:Currency'
VAR_CURRENTSUMMATIONDELIVERED = 'zigbee:CurrentSummationDelivered'
VAR_CURRENTSUMMATIONRECEIVED = 'zigbee:CurrentSummationReceived'
VAR_DIVISOR = 'zigbee:Divisor'
VAR_INSTANTANEOUSDEMAND = 'zigbee:InstantaneousDemand'
VAR_MESSAGE = 'zigbee:Message'
VAR_MESSAGECONFIRMATIONREQUIRED = 'zigbee:MessageConfirmationRequired'
VAR_MESSAGECONFIRMED = 'zigbee:MessageConfirmed'
VAR_MESSAGEDURATIONINMINUTES = 'zigbee:MessageDurationInMinutes'
VAR_MESSAGEID = 'zigbee:MessageId'
VAR_MESSAGEPRIORITY = 'zigbee:MessagePriority'
VAR_MESSAGESTARTTIME = 'zigbee:MessageStartTime'
VAR_MULTIPLIER = 'zigbee:Multiplier'
VAR_PRICE = 'zigbee:Price'
VAR_PRICEDURATION = 'zigbee:PriceDuration'
VAR_PRICESTARTTIME = 'zigbee:PriceStartTime'
VAR_PRICETIER = 'zigbee:PriceTier'
VAR_RATELABEL = 'zigbee:RateLabel'
VAR_TRAILINGDIGITS = 'zigbee:TrailingDigits'
|
# Bit manipulation
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
for i in range(1 << len(nums)):
tmp = []
for j in range(len(nums)):
if i >> j & 1:
tmp.append(nums[j])
result.append(tmp)
return result
# Backtrack
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
self.backtrack(result, 0, nums, [])
return result
def backtrack(self, result, idx, nums, path):
result.append(path)
for i in range(idx, len(nums)):
self.backtrack(result, i + 1, nums, path + [nums[i]])
|
"""Utility queries for create, drop tables and insert data."""
# DROP TABLES
songplay_table_drop = "drop table if exists songplays"
user_table_drop = "drop table if exists users"
song_table_drop = "drop table if exists songs"
artist_table_drop = "drop table if exists artists"
time_table_drop = "drop table if exists time"
# CREATE TABLES
songplay_table_create = """
create table if not exists songplays
(
songplay_id bigserial NOT NULL -- bigserial == default nextval('fact_songplays_id')
,start_time bigint
,user_id integer REFERENCES users (user_id)
,level varchar(4) -- paid or free
,song_id varchar(30) NULL REFERENCES songs (song_id)
,artist_id varchar(30) NULL REFERENCES artists (artist_id)
,session_id integer
,location varchar(60)
,user_agent varchar(400)
,PRIMARY KEY (songplay_id)
);
"""
user_table_create = """
create table if not exists users
(
user_id integer -- can have up to 2.147.483.647 users
,first_name varchar(60)
,last_name varchar(60)
,gender varchar(1)
,level varchar(4) -- paid or free
,PRIMARY KEY (user_id)
);
"""
song_table_create = """
create table if not exists songs
(
song_id varchar(30)
,title varchar(60)
,artist_id varchar(30)
,year smallint
,duration numeric(9,6) -- ex: 218.93179
,PRIMARY KEY (song_id)
);
"""
artist_table_create = """
create table if not exists artists
(
artist_id varchar(30)
,name varchar(120)
,location varchar(120)
,latitude numeric(9,6) -- ex: 35.14968
,longitude numeric(9,6) -- ex: -90.04892
,PRIMARY KEY (artist_id)
);
"""
time_table_create = """
create table if not exists time
(
start_time bigint not null -- represent the timestamp where one song was played
,hour smallint not null
,day smallint not null
,week smallint not null
,month smallint not null
,year smallint not null
,weekday smallint not null
,PRIMARY KEY (start_time)
);
"""
# INSERT RECORDS
songplay_table_insert = """
INSERT INTO songplays
(start_time, user_id, "level", song_id, artist_id, session_id, "location", user_agent)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s);
"""
user_table_insert = """
INSERT INTO users
(user_id, first_name, last_name, gender, "level")
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT (user_id) DO UPDATE
SET first_name=EXCLUDED.first_name
,last_name=EXCLUDED.last_name
,gender=EXCLUDED.gender
,"level"=EXCLUDED."level"
"""
# artist_id artist_latitude artist_location artist_longitude artist_name duration num_songs song_id title year
# ('ARD7TVE1187B99BFB1', '', 'California - LA', '', 'Casual', 218.93179, 1, 'SOMZWCG12A8C13C480', "I Didn't Mean To", 0)
song_table_insert = """
INSERT INTO songs
(song_id, title, artist_id, "year", duration)
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT (song_id) DO UPDATE
SET title=EXCLUDED.title
,artist_id=EXCLUDED.artist_id
,"year"=EXCLUDED.year
,duration=EXCLUDED.duration
"""
artist_table_insert = """
INSERT INTO artists
(artist_id, "name", "location", latitude, longitude)
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT (artist_id) DO UPDATE
SET name=EXCLUDED.name
,location=EXCLUDED.location
,latitude=EXCLUDED.latitude
,longitude=EXCLUDED.longitude
"""
"""
-- https://www.postgresql.org/docs/13/sql-insert.html
INSERT INTO distributors (did, dname)
VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;
"""
time_table_insert = """
INSERT INTO "time"
(start_time, "hour", "day", week, "month", "year", weekday)
VALUES(%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (start_time) DO UPDATE
SET hour=EXCLUDED.hour
,day=EXCLUDED.day
,week=EXCLUDED.week
,month=EXCLUDED.month
,year=EXCLUDED.year
,weekday=EXCLUDED.weekday
;
"""
# FIND SONGS
# Implement the song_select query in sql_queries.py to find the song ID and artist ID based on the title, artist name, and duration of a song.
# Select the timestamp, user ID, level, song ID, artist ID, session ID, location, and user agent and set to songplay_data
# get songid and artistid from song and artist tables
song_select = """
select s.song_id, s.artist_id from songs s
join artists a on a.artist_id=s.artist_id
where s.title=%s and a.name=%s and s.duration=%s
"""
# to check if etl run ok
count_tables = """
SELECT count(0), 'songplays' as "table" FROM public.songplays
UNION all
SELECT count(0), 'songplays_with_song_id' as "table" FROM public.songplays where song_id is not null
UNION ALL
SELECT count(0), 'artists' as "table" FROM public.artists
UNION ALL
SELECT count(0), 'artists' as "table" FROM public.songs
UNION ALL
SELECT count(0), 'users' as "table" FROM public.users
UNION ALL
SELECT count(0), 'time' as "table" FROM public.time
;
"""
# QUERY LISTS
create_table_queries = [
user_table_create,
song_table_create,
artist_table_create,
time_table_create,
songplay_table_create,
]
drop_table_queries = [
songplay_table_drop,
user_table_drop,
song_table_drop,
artist_table_drop,
time_table_drop,
]
|
def load_file_list(f_list):
lines=[]
for fp in f_list:
with open(fp,'r',encoding='utf-8') as f:
for line in f:
strs=line.strip().split('\t')
lines.append([float(strs[0]),len(lines),strs[1]])
return lines
def build_id_dict(list):
dic={}
for l in list:
dic[len(dic)]=l
return dic
def select_data_by_lm_score(inf_path,fm_path,top_rate=0.1,bottom_rate=0.1,suffix='.filtered_by_lm'):
inf_ori=load_file_list([inf_path])
fm_ori=load_file_list([fm_path])
inf_dic=build_id_dict(inf_ori)
fm_dic=build_id_dict(fm_ori)
inf_sorted=sorted(inf_ori,key=lambda x:x[0],reverse=True)
fm_sorted = sorted(fm_ori, key=lambda x: x[0], reverse=True)
data_num=len(inf_ori)
start_id=int(top_rate*data_num)
end_id=int((1-bottom_rate)*data_num)
fm_top_score=fm_sorted[start_id][0]
fm_bottom_score=fm_sorted[end_id-1][0]
selected_inf=inf_sorted[start_id:end_id]
fw_inf=open(inf_path+suffix,'w',encoding='utf-8')
fw_fm=open(fm_path+suffix,'w',encoding='utf-8')
for item in selected_inf:
fm_item=fm_dic[item[1]]
if fm_item[0]>=fm_bottom_score and fm_item[0]<=fm_top_score:
fw_inf.write(item[2]+'\n')
fw_fm.write(fm_item[2]+'\n')
fw_inf.close()
fw_fm.close()
if __name__=='__main__':
select_data_by_lm_score('../new_exp_fr/add_data/informal.add.rule.bpe.bpe_len_filtered.score',
'../new_exp_fr/add_data/formal.add.rule.bpe.bpe_len_filtered.score')
print('all work has finished')
|
# -------------
# netrecon info
# --------------
__name__ = 'netrecon'
__version__ = 0.19
__author__ = 'Avery Rozar: [email protected]'
|
def read_puzzle(path):
with open(path, 'r+') as file:
return file.read().split('\n')
class Submarine:
horizontal = 0
depth = 0
aim = 0
def forward(self, x):
self.horizontal = self.horizontal + x
self.depth = self.depth + self.aim * x
def down(self, y):
self.aim = self.aim + y
def up(self, y):
self.aim = self.aim - y
def get_multiplied(self):
return self.horizontal * self.depth
if __name__ == "__main__":
submarine = Submarine()
content = read_puzzle("puzzle_input.txt")
for line in content:
commands = line.split(" ")
if commands[0] == "forward":
submarine.forward(int(commands[1]))
elif commands[0] == "down":
submarine.down(int(commands[1]))
elif commands[0] == "up":
submarine.up(int(commands[1]))
print("Final location of the submarine: Horizontal: " + str(submarine.horizontal) + ", Depth: " + str(submarine.depth) +
", Multiplied: " + str(submarine.get_multiplied()))
|
class FieldDimension:
def __init__(self, dimension, indexes):
self.dimension = dimension
self.indexes = indexes
@classmethod
def to_index(cls, t):
"""
:param t: t look like "1" or "4-7"
:return: tuple either size of 1 or 2 (1) or (4, 7)
"""
a = t.split('-')
return tuple((int(i) for i in a))
@classmethod
def to_field_dimension(cls, dimension_str, v_str):
dimension = int(dimension_str)
indexes = [cls.to_index(t) for t in v_str.split(',')]
return FieldDimension(dimension, indexes)
def __str__(self):
return "%s:%s" % (self.indexes, self.dimension) |
for t in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
counter = 0
flag = False
result = True
for i in A:
if i == 1 and not flag:
counter = 1
flag = True
elif i == 1 and counter < 6 :
result = False
break
elif i == 1 and counter >= 6:
counter = 1
else:
counter += 1
if result:
print("YES")
else:
print("NO")
|
"""
Topic modeling is a type of statistical modeling for discovering the abstract 'topics' that occur in
a collection of documents, Latent Dirichlet Allocation is an example of topic model and is used to
classify text in a document to a particular topic. It builds a topic per document model and words per
topic model, modeled as Dirichlet distributions.
""" |
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
s = 0
while n > 0:
if n % 2 == 1:
s += 1
n = n // 2
return s
def test_0():
assert Solution().hammingWeight(11) == 3
assert Solution().hammingWeight(128) == 1
|
"""
NAME : DIBANSA, RAHMANI P.
NAME : BELGA, EMJAY
COURSE : BSCPE 2-2
ACADEMIC YEAR : 2019-2020
PROGRAM'S SUMMARY: THIS PROGRAM WOULD MIMIC A STACK OF NOTEBOOKS THAT WOULD BE CHECKED. THIS PROGRAM RECORDS THE NAME
OF THE NOTEBOOK'S OWNER AND ADDS THE NOTEBOOK ON THE TOP OF THE STACK. AS THE USER CHECKS THE STACK, THE NOTEBOOK AT
THE TOP OF THE STACK WOULD BE REMOVED. FURTHERMORE, THE USER COULD ALSO OPT FOR THE 'CHECK ALL' BUTTON THAT REMOVES
EVERY NOTEBOOK IN THE STACK. IN ADDITION, THE USER COULD ALSO PEEK AT THE NOTEBOOK ON TOP OF THE STACK.
"""
# This stack class mimics a stack of notebooks.
class stcks:
# The program would be initializing the allocated storage for the notebook's stack and the truth value
# of isStackEmpty.
def __init__( self ) :
self.stackStorage = []
self.isStackEmpty = True
# This function checks if the stack is empty or not.
# The program would be updating the truth value of isStackEmpty depending on the result of the process.
def is_empty ( self ) :
self.tempLen = len ( self.stackStorage )
if self.tempLen == 0:
self.isStackEmpty = True
else:
self.isStackEmpty = False
# This function adds another book on top of the stack.
def addNotebook ( self , ownerName ) :
self.ownerName = ownerName
self.stackStorage.append ( self.ownerName )
# If the notebook stack isn't empty, this function would remove the last added notebook in the stack.
def checkNotebook ( self ) :
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.stackStorage.pop ( len ( self.stackStorage ) - 1 )
# If the notebook stack isn't empty, this function would take the name of the owner of the last inputted
# notebook in the stack, and the program would return the name of the notebook's owner back to wherever it has
# been called.
def peekAtNotebook ( self ) :
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.notebookOwner = self.stackStorage[ len ( self.stackStorage ) - 1 ]
return self.notebookOwner
# If the notebook stack isn't empty, this function would take all the names of the notebook owners and record it
# following the order of the stack.
def checkAll ( self ) :
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.result = ""
self.tempStackStorage = self.stackStorage.copy()
for i in range ( len ( self.tempStackStorage ) ) :
if i != ( len( self.tempStackStorage) - 1 ) :
self.result += self.tempStackStorage[i] + ", "
else:
self.result += self.tempStackStorage[i] + "."
return self.result
# This is an extension of the checkAll function above, all this does is remove all the elements within the
# program's stack.
def checkedAll ( self ) :
self.stackStorage = []
|
# https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/
class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
dp = [0] * len(word)
dic = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
dp[0] = 1 if word[0] == 'a' else 0
for i in range(1, len(word)):
if 0 <= dic[word[i]] - dic[word[i - 1]] <= 1 and dp[i - 1] > 0:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1 if word[i] == 'a' else 0
res = [v for i, v in enumerate(dp) if word[i] == 'u']
return max([v for i, v in enumerate(dp) if word[i] == 'u'], default=0)
s = Solution()
print(s.longestBeautifulSubstring('uuuuu')) # 0
print(s.longestBeautifulSubstring('aeiaaioaaaaeiiiiouuuooaauuaeiu')) # 13
print(s.longestBeautifulSubstring('aeeeiiiioooauuuaeiou')) # 5
|
# IF COM ESTRUTURA ANHINHADOS
idade = 18
if idade > 17:
print('Você pode dirigir ')
nome = 'Bob'
print()
print('Testando condição aninhada.....')
if idade > 13:
if nome == 'Bob':
print('Ok Bob, você esta autorizado a entrar ')
else:
print("Desculpe, mas você não pode entrar! ")
print()
print('Utilizando operador logico (AND)')
if idade >= 13 and nome == 'Bob':
print('Ok Bob, você esta autorizado a entrar...')
print()
print('Utilizando operador logico (OR)')
if (idade <= 13) or (nome == 'Bob'):
print('Ok Bob, você esta autorizado a entrar... ') |
# flake8: noqa
def foo():
def inner():
x = __test_source()
__test_sink(x)
def inner_with_model():
return __test_source()
|
"""A collection of command-related exceptions."""
__all__ = ('CommandError', 'ArgumentError', 'MissingArgumentError', 'UnusedArgumentsError', 'AuthorizationError',
'ComplexityError')
class CommandError(Exception):
"""Raised on any command processing error."""
class ArgumentError(CommandError):
"""Raised when there is something wrong with user input."""
class MissingArgumentError(ArgumentError):
"""Raised when the user has not provided enough arguments."""
class UnusedArgumentsError(ArgumentError):
"""Raised when there are unused arguments."""
class AuthorizationError(Exception):
"""Raised when the user does not have sufficient permissions."""
class ComplexityError(Exception):
"""Raised if a command is too complex to complete completely."""
|
with open("3.txt") as f:
nums = [x for x in f.read().split("\n")]
totals = [0] * len(nums[0])
for n in nums:
for i, c in enumerate(n):
totals[i] += 1 if c == "1" else -1
gamma = int("".join(map(lambda x: "1" if x > 0 else "0", totals)), 2)
epsilon = int("".join(map(lambda x: "1" if x <= 0 else "0", totals)), 2)
print("part 1: {}".format(gamma * epsilon))
nums = sorted(nums)
def process(nums, flip):
for i in range(len(nums[0])):
index = next((j for j, n in enumerate(nums) if n[i] == "1"), len(nums))
cmp = index > len(nums) / 2 if flip else index <= len(nums) / 2
nums = nums[index:] if cmp else nums[:index]
if len(nums) == 1:
return int(nums[0], 2)
print("part 2: {}".format(process(nums, True) * process(nums, False)))
|
"""
This problem was asked by Lyft.
Given a list of integers and a number K, return which contiguous elements of the list sum to K.
For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9.
"""
# solved through caterpillar method
def get_contigous_sum(k, arr):
front = 0
total = 0
for back in range(len(arr)):
while front < len(arr) and total + arr[front] <= k:
total += arr[front]
front += 1
if total == k:
return arr[back:front]
total -= arr[back]
return None
if __name__ == '__main__':
print(get_contigous_sum(9, [1, 2, 3, 4, 5])) # [2, 3, 4]
print(get_contigous_sum(12, [6, 2, 7, 4, 1, 3, 6])) # [7, 4, 1] |
# define variables
# dont change
fdd = 79
daynames = ['شنبه', 'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنج شنبه', 'جمعه']
monthname = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند']
grgdayofmonthleap = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
grgdayofmonth = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
# check leap year
def isleap(year):
if ((year % 100 == 0) and (year % 400 == 0)) or ((year % 100 != 0) and (year % 4 == 0)):
return True
else:
return False
# convert gregorian date to persian(shamsi) date
# @param year is gregorian year
# @param month is gregorian month
# @param day is gregorian day
# return persian(shamsi) date in dict format
def topersia(year, month, day):
if isleap(year):
daycount = grgdayofmonthleap[month - 1] + day
else:
daycount = grgdayofmonth[month - 1] + day
if isleap(year - 1):
dd = 11
else:
dd = 10
if daycount > fdd:
daycount = daycount - fdd
if daycount <= 186:
if daycount % 31 == 0:
prmonth = daycount / 31
prday = 31
else:
prmonth = (daycount / 31) + 1
prday = daycount % 31
pryear = daycount - 621
else:
daycount = daycount - 186
if daycount % 30 == 0:
prmonth = (daycount / 30) + 6
prday = 30
else:
prmonth = (daycount / 30) + 7
prday = (daycount % 30)
pryear = year - 621
else:
daycount = daycount + dd
if daycount % 30 == 0:
prmonth = (daycount / 30) + 9
prday = (daycount % 30)
else:
prmonth = (daycount / 30) + 10
prday = (daycount % 30)
pryear = year - 622
return {
'year': pryear,
'month': int(prmonth),
'day': prday,
'dayname': daynames[((prday % 7) - 1)],
'monthname': monthname[(int(prmonth) - 1)]
}
|
e = int(input('Digite até que número você quer fazer a soma dos ímpares multiplos de 3: '))
s = 0
for c in range(0, e+1):
if c % 3 == 0 and c % 2 != 0:
s = s + c
print('A soma de todos é {}.'.format(s))
|
# define inception block layer
def InceptBlock(filters, strides):
"""InceptNet convolutional striding block.
filters: tuple: (f1,f2,f3)
filters1: for conv1x1
filters2: for conv1x1,conv3x3
filters3L for conv1x1,conv5x5"""
filters1, filters2, filters3 = filters
conv1x1 = stax.serial(stax.Conv(filters1, (1,1), strides, padding="SAME"))
conv3x3 = stax.serial(stax.Conv(filters1, (1,1), strides=None, padding="SAME"),
stax.Conv(filters2, (3,3), strides, padding="SAME"))
conv5x5 = stax.serial(stax.Conv(filters1, (1,1), strides=None, padding="SAME"),
stax.Conv(filters3, (5,5), strides, padding="SAME"))
return stax.serial(
stax.FanOut(2), # should num=3 or 2 here ?
stax.parallel(conv1x1, conv3x3, conv5x5),
stax.FanInConcat(), stax.LeakyRelu)
def InceptBlock2(filters, strides, dims=2, do_5x5=True, do_3x3=True):
"""InceptNet convolutional striding block.
filters: tuple: (f1,f2,f3)
filters1: for conv1x1
filters2: for conv1x1,conv3x3
filters3L for conv1x1,conv5x5"""
filters1, filters2, filters3 = filters
#strides = ()
dim_nums = ("NCHWZ", "OIHWZ", "NCHWZ")
conv1x1 = stax.serial(stax.GeneralConv(dim_nums,
filters1,
filter_shape=(1,)*dims,
strides=strides, padding="SAME"))
filters4 = filters2
conv3x3 = stax.serial(stax.GeneralConv(dim_nums,
filters2,
filter_shape=(1,)*dims,
strides=None, padding="SAME"),
stax.GeneralConv(dim_nums,
filters4,
filter_shape=(3,)*dims,
strides=strides, padding="SAME"))
filters5 = filters3
conv5x5 = stax.serial(stax.GeneralConv(dim_nums,
filters3,
filter_shape=(1,)*dims,
strides=None, padding="SAME"),
stax.GeneralConv(dim_nums,
filters5,
filter_shape=(5,)*dims,
strides=strides, padding="SAME"))
maxpool = stax.serial(stax.MaxPool((3,)*dims, padding="SAME"),
stax.GeneralConv(dim_nums,
filters4,
filter_shape=(1,)*dims,
strides=strides, padding="SAME"))
if do_3x3:
if do_5x5:
return stax.serial(
stax.FanOut(4), # should num=3 or 2 here ?
stax.parallel(conv1x1, conv3x3, conv5x5, maxpool),
stax.FanInConcat(),
stax.LeakyRelu)
else:
return stax.serial(
stax.FanOut(3), # should num=3 or 2 here ?
stax.parallel(conv1x1, conv3x3, maxpool),
stax.FanInConcat(),
stax.LeakyRelu)
else:
return stax.serial(
stax.FanOut(2), # should num=3 or 2 here ?
stax.parallel(conv1x1, maxpool),
stax.FanInConcat(),
stax.LeakyRelu)
dim_nums = ("NCHWZ", "OIHWZ", "NCHWZ")
model = stax.serial(
InceptBlock2((fs,fs,fs), strides=(4,4,4), dims=3, do_5x5=False), # output: 8,8
#InceptBlock2((fs,fs,fs), strides=(2,2,2), dims=3), # output: 2,2
InceptBlock2((fs,fs,fs), strides=(4,4,4), dims=3, do_5x5=False), # output: 2,2
#InceptBlock2((fs,fs,fs), strides=(2,2,2), dims=3, do_5x5=False, do_3x3=False), # output 2,2
InceptBlock2((fs,fs,fs), strides=(2,2,2), dims=3, do_5x5=False, do_3x3=False), # output 1,1
stax.GeneralConv(dim_nums, n_summaries,
filter_shape=(1,1,1),
strides=(1,1,1), padding="SAME"),
stax.Flatten
) |
'''
In ChessLand there is a small but proud chess bishop with a recurring dream. In the dream the bishop finds itself on an n × m chessboard with mirrors along each edge, and it is not a bishop but a ray of light. This ray of light moves only along diagonals (the bishop can't imagine any other types of moves even in its dreams), it never stops, and once it reaches an edge or a corner of the chessboard it reflects from it and moves on.
Given the initial position and the direction of the ray, find its position after k steps where a step means either moving from one cell to the neighboring one or reflecting from a corner of the board.
Example
For boardSize = [3, 7], initPosition = [1, 2],
initDirection = [-1, 1] and k = 13, the output should be
chessBishopDream(boardSize, initPosition, initDirection, k) = [0, 1].
Here is the bishop's path:
[1, 2] -> [0, 3] -(reflection from the top edge)-> [0, 4] ->
[1, 5] -> [2, 6] -(reflection from the bottom right corner)-> [2, 6] ->
[1, 5] -> [0, 4] -(reflection from the top edge)-> [0, 3] ->
[1, 2] -> [2, 1] -(reflection from the bottom edge)-> [2, 0] -(reflection from the left edge)->
[1, 0] -> [0, 1]
'''
def chessBishopDream(boardSize, initPosition, initDirection, k):
rowMov = k % (boardSize[0]*2)
colMov = k % (boardSize[1]*2)
# move rows
for i in range(rowMov):
newPos = initPosition[0] + initDirection[0]
if newPos < boardSize[0] and newPos >= 0:
initPosition[0] = newPos
else:
initDirection[0] *= -1
# move cols
for i in range(colMov):
newPos = initPosition[1] + initDirection[1]
if newPos < boardSize[1] and newPos >= 0:
initPosition[1] = newPos
else:
initDirection[1] *= -1
return initPosition
|
# Orden de ejecución de operaciones aritméticas
a = (3+1) + 4**2 * 2 # 36 => () => ** => * => +
a = 4 * 5 + 6 - 3 # 23 => * => + => -
a = 4 * 5 * 6 - 3 # 117 => * => * => -
a = 4 * 5 * (6 - 3) # 60 => (-) => * => *
a = 9 / (3 * 2 + 3) # 1 (* => +) => /
a = 9 / 3 * 2 + 3 # 9 / => * => +
print("Final") |
class PackageInstaller(object):
"""
Installs packages
"""
def __init__(self, connector, packages)-> None:
self.__packages_installed = 0
self.__packages = packages
self.__bash_connector = connector
for package in self.__packages:
self.__run_package_installer(package)
@classmethod
def found_char(cls, string: str, char: str)-> bool:
"""
It is looking for a particular char
in a string
:param string: the string
:param char: the char it is looking for
:return: boolean
"""
str_version = str(string)
# try to find substring
find = str_version.find(char)
if find == -1:
# if not found
return False
else:
# found
return True
@classmethod
def split_string(cls, string: str, char: str)-> str:
"""
Splits string and returns
the first part
:param string: the string to be split
:param char: delimiter
:return: the first part of the string
"""
string = string.split(char, 1)[0]
return string
@classmethod
def sanitize_str(cls, string: str)-> str:
"""
Removes 'b' and ' from a string
:param string: the string to be sanitized
:return: newly created string
"""
# convert to string
string = str(string)
# remove "b"
string = string.replace("b'", "")
# remove '
string = string.replace("'", "")
return string
@classmethod
def remove_chars(cls, string: str)-> str:
"""
Removes unnecessary characters from
the string.
:param string: the string to be manipulated
:return: newly created string
"""
# sanitize the string
string = cls.sanitize_str(string)
# remove unnecessary things
if cls.found_char(string, "-"):
string = string.split("-", 1)[0]
elif cls.found_char(string, "ubuntu"):
string = string.split("ubuntu", 1)[0]
if cls.found_char(string, "+"):
string = string.split("+", 1)[0]
return string
def __install(self, package)-> None:
"""
Wrapper around install_package
:param package: json object representing package
:return: void
"""
i = 0
for command in package['commands']:
i += 1
print("Command Description " + str(i) + ": " + str(command['commandDescription']))
print("Command :" + str(command['command']))
self.__bash_connector.install_package(command)
# increment the number of installed packages
self.__packages_installed = self.__packages_installed + 1
@classmethod
def __is_installed(cls, version: str)-> bool:
"""
Checks if package is installed.
:param version: string version of the package
:return: boolean true/false
"""
if not version or version == "'b'":
return False
is_non_in_version = cls.found_char(version, "none")
if is_non_in_version:
return False
return True
@classmethod
def __extract_version(cls, output: str):
"""
Gets the version of the package
:param output: string containing the version
or 'b if there is none
:return: the version of the package
"""
# split the output and extract the
# installed part as:
# Installed: 1.6-2
if not output:
return 0
tmp = output.split()
version = tmp[2]
return version
@classmethod
def __print_info(cls, package)-> None:
# print some info
print("###################################################")
print("Installing : " + package['name'])
print("Comments : " + package['comment'])
print("Version : " + package['version'])
def __run_package_installer(self, package):
if not package:
return
# print info
PackageInstaller.__print_info(package)
# execute apt-cache
output = self.__bash_connector.apt_cache(package)
# get the version
version = self.__extract_version(output)
# check if installed
if not self.__is_installed(version):
# if not, installed it
self.__bash_connector.update()
self.__install(package)
else:
# else, just address the user
# remove certain chars
version = PackageInstaller.remove_chars(version)
print("This Package is already installed! Version is " + version + "\n")
def get_num_installed_packages(self)-> int:
return self.__packages_installed
|
count = 0
count2 = 0
while True:
questions = set()
# 2nd part
everyone = set()
fst = True
try:
person = input()
while person != "":
for x in person:
questions.add(x)
if fst:
for x in person:
everyone.add(x)
else:
this = set()
for x in person:
this.add(x)
everyone = everyone.intersection(this)
person = input()
fst = False
count += len(questions)
count2 += len(everyone)
except:
break
#print(questions)
count += len(questions)
count2 += len(everyone)
print(count)
print(count2) |
class SerializerError(Exception):
def __init__(self, message):
self._message = message
class ValidationError(SerializerError):
pass
class InvalidSerializer(SerializerError):
pass
|
n = int(input())
a = [['' for j in range(n)] for i in range(n)]
for i in range(n):
f = 0
for j in range(i, n):
a[i][j] = str(f)
f += 1
f = i
for j in range(i):
a[i][j] = str(f)
f -= 1
for row in a:
print(' '.join(row))
# For the record, I feel dumb because it could be
# done with a single line of code
# a = [[abs(i - j) for j in range(n)] for i in range(n)]
|
#!/usr/bin/env python3
# https://abc102.contest.atcoder.jp/tasks/abc102_b
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
print(a[-1] - a[0])
|
# Spiegelmann (9071005) | In Monster Park Maps
response = sm.sendAskYesNo("Do you want to leave?")
if response:
sm.warpInstanceOut(951000000)
|
#!/usr/local/bin/python3
def main():
# Test suite
tests = [
[None, None], # Should throw a TypeError
[-1, None], # Should throw a ValueError
[0, 0],
[9, 9],
[138, 3],
[65536, 7]
]
print('Testing add_digits')
for item in tests:
try:
temp_result = add_digits(item[0])
if temp_result == item[1]:
print('PASSED: add_digits({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
print('\nTesting add_digits_digital_root')
for item in tests:
try:
temp_result = add_digits_digital_root(item[0])
if temp_result == item[1]:
print('PASSED: add_digits_digital_root({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits_digital_root({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
return 0
def add_digits(val):
'''
Sums the digits of an integer until it reduces to one digit
Input: val is non-negative integer
Output: single digit integer
Assumes no other data structure can be used
'''
# Check inputs
if type(val) is not int:
raise TypeError('Input must be an integer')
if val < 0:
raise ValueError('Input must be non-negative')
digit_sum = val
while digit_sum > 9:
# Sum the digits in integer
temp_sum = 0
while digit_sum > 0:
temp_sum += digit_sum % 10
digit_sum = digit_sum // 10
digit_sum = temp_sum
return digit_sum
def add_digits_digital_root(val):
'''
This is a digital root, can be solved taking % 9
Time: O(1)
Complexity: O(1)
'''
# Check inputs
if type(val) is not int:
raise TypeError('Input must be an integer')
if val < 0:
raise ValueError('Input must be non-negative')
if val == 0:
return 0
elif val % 9 == 0:
return 9
else:
return val % 9
if __name__ == '__main__':
main()
|
"""
Rules for representing package from package managers.
"""
_PACKAGE_JSON_TEMPLATE = "\"package\": \"{package}\", \"version\": \"{version}\", \"sum\": \"{sum}\""
def _package_json_impl(ctx):
ctx.actions.write(
output = ctx.outputs.manifest,
content = "{" + _PACKAGE_JSON_TEMPLATE.format(
package = ctx.attr.package,
version = ctx.attr.version,
sum = ctx.attr.sum,
) + "}",
)
package_json = rule(
implementation = _package_json_impl,
attrs = {
"package": attr.string(mandatory = True),
"version": attr.string(mandatory = True),
"sum": attr.string(mandatory = True),
},
outputs = {"manifest": "%{name}.json"},
)
|
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Most digits
#Problem level: 7 kyu
def find_longest(arr):
return arr[[len(str(x)) for x in arr].index(max([len(str(x)) for x in arr]))]
|
#!/usr/bin/env python3
def main():
# initialize round counter to 0 and answer to blank
round = 0
answer = " "
# set up loop
while round < 3 and (answer.lower() != "brian" and answer.lower() != "shrubbery"):
# increment round
round += 1
answer = input("Finish the movie title, \"Monty Python\'s The Life of ______: ")
# correct answer given
if answer.lower() == 'brian':
print('Correct')
elif answer.lower() == "shrubbery":
print("You gave the super secret answer")
# reached end of game with no correct answer
elif round==3:
print("Sorry, the answer was Brian.")
# loop back to beginning of while loop
else:
print("Sorry! Try again!")
main()
|
def sentence_maker(phrase):
interrogatives = ("why","how","what")
capitalized = phrase.capitalize()
#startswith function checks whether the string starts with the given values
if phrase.startswith(interrogatives):
return f"{capitalized}?"
else:
return f"{capitalized}."
conversation = []
while True:
userInput = input("Say something: ")
if userInput == "\end":
if conversation.__len__() >= 0:
break
else:
conversation.append(sentence_maker(userInput))
print(" ".join(conversation)) |
"""
For in Python
Iterando Strings com for
Função range(start=0, stop, step)
"""
texto = 'Python'
for letra in texto:
print(letra)
for n in range(0, 100, 8): # Acha os múltiplos de 8
print(n)
# continue - pula para o próximo laço.
# brake - termina o laço.
|
# https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix
# O(n + m) time | O(1) space
# where 'n' is the length of row and 'm' is the length on column
def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < row:
row += 1
else:
return [row, col]
return [-1, -1]
|
def get_variables():
return {
'SPECIAL_FUNC': {'hoge': 'fuga'}
}
|
n=int(input())
numSwaps=0
a=list(map(int, input().strip().split()))
for i in range(n-1):
for j in range(n-i-1):
if (a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
numSwaps+=1
print(f"Array is Sorted in {numSwaps} swaps")
print(f"First Element: {a[j]}")
print(f"Last Element: {a[j-1]}") |
"""
https://leetcode.com/problems/roman-to-integer/
"""
def roman_to_integer(s):
"""
This implementation passed all tests on submission January 18, 2022.
There's not too much any other way of implementing this, am I right? You
really just have encode each of the rules that are stated.
"""
o = list()
did_a_skip = False
for index, item in enumerate(s):
if did_a_skip:
did_a_skip = not did_a_skip
continue
if item == 'V':
o.append(5)
elif item == 'L':
o.append(50)
elif item == 'D':
o.append(500)
if item == 'I':
if (index+1) != len(s):
next_value = s[index+1]
if next_value == 'V':
o.append(4)
did_a_skip = True
elif next_value == 'X':
o.append(9)
did_a_skip = True
else:
o.append(1)
else:
o.append(1)
elif item == 'X':
if (index+1) != len(s):
next_value = s[index+1]
if next_value == 'L':
o.append(40)
did_a_skip = True
elif next_value == 'C':
o.append(90)
did_a_skip = True
else:
o.append(10)
else:
o.append(10)
elif item == 'C':
if (index+1) != len(s):
next_value = s[index+1]
if next_value == 'D':
o.append(400)
did_a_skip = True
elif next_value == 'M':
o.append(900)
did_a_skip = True
else:
o.append(100)
else:
o.append(100)
elif item == 'M':
o.append(1000)
return sum(o)
if __name__ == '__main__':
assert roman_to_integer("III") == 3
assert roman_to_integer("MCMXCIV") == 1994
assert roman_to_integer("DCXXI") == 621
|
# Has the same id
a = [1, 2, 3]
c = a
print(id(a), id(c))
# Has a different id
b = 42
print(id(b))
b = '42'
print(id(b))
|
class Score:
def __init__(self, name, loader):
self.name = name
self.metrics = ['F', 'M']
self.highers = [1, 0]
self.scores = [0. if higher else 1. for higher in self.highers]
self.best = self.scores
self.best_epoch = [0] * len(self.scores)
self.present = self.scores
def update(self, scores, epoch):
self.present = scores
self.epoch = epoch
self.best = [max(best, score) if self.highers[idx] else min(best, score) for idx, (best, score) in enumerate(zip(self.best, scores))]
self.best_epoch = [epoch if present == best else best_epoch for present, best, best_epoch in zip(self.present, self.best, self.best_epoch)]
saves = [epoch == best_epoch for best_epoch in self.best_epoch]
return saves
def print_present(self):
m_str = '{} : {:.4f}, {} : {:.4f} on ' + self.name
m_list = []
for metric, present in zip(self.metrics, self.present):
m_list.append(metric)
m_list.append(present)
print(m_str.format(*m_list))
def print_best(self):
m_str = 'Best score: {}_{} : {:.4f}, {}_{} : {:.4f} on ' + self.name
m_list = []
for metric, best, best_epoch in zip(self.metrics, self.best, self.best_epoch):
m_list.append(metric)
m_list.append(best_epoch)
m_list.append(best)
print(m_str.format(*m_list))
|
mysql = {
'user': 'scott',
'password': 'password',
'host': '127.0.0.1',
'database': 'employees',
'raise_on_warnings': True,
}
|
# Author: allannozomu
# Runtime: 544 ms
# Memory: 19.8 MB
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if (A[0] < A[-1]):
ordered = sorted(A)
else:
ordered = sorted(A, reverse = True)
return ordered == A
|
def szyfr(slowa):
wynik = []
for slowo in slowa:
wynik.append(slimak(slowo))
return wynik
def slimak(slowo):
ukl = [[" " for _ in range(len(slowo))] for _ in range(len(slowo))]
kon = [1,2,2,2] + [j for j in range(3, 20)] + [j for j in range(3, 20)]
kon.sort()
pivot = int(len(slowo) / 2)
i = 0
x = pivot
y = pivot
while len(slowo):
elem = slowo[:kon[i]]
for j in range(len(elem)):
ukl[y][x] = elem[j]
ii = i
if j == len(elem) - 1 and i != 0:
ii += 1
if ii % 4 == 0:
y += 1
elif ii % 4 == 1:
x += 1
elif ii % 4 == 2:
y -= 1
elif ii % 4 == 3:
x -= 1
slowo = slowo[kon[i]:]
i += 1
wynik = ""
for line in ukl[::-1]:
for l in line:
if l != ' ':
wynik += l
return wynik
|
class Vessel:
def __init__(self, name: str):
"""
Initializing class instance with vessel name
:param name:
"""
self.name = name
self.fuel = 0.0
# list of dicts with passenger attributes
self.passengers = []
def __getattr__(self, item):
"""
Called when unknown attribute is about to be fetched
:param item:
:return:
"""
# Always raise this error in common situations
raise AttributeError
def __getattribute__(self, item):
"""
Called when any attribute is about to be fetched
:param item:
:return:
"""
# You can get attributes in a different way here
# When an unknown attribute called, this method calls the above method
print(f'Getting {item}')
return object.__getattribute__(self, item)
def __setattr__(self, key, value):
"""
Setting the attribute with key - value
:param key:
:param value:
:return:
"""
print(f'Setting {key} with {value}')
super().__setattr__(key, value)
def __delattr__(self, item):
"""
Removes attribute from the class instance
:param item:
:return:
"""
# This method will be called on "del attribute_name"
super().__delattr__(item)
# Vessel methods
def pump_in_fuel(self, quantity: float):
self.fuel += quantity
def pump_out_fuel(self):
self.fuel = 0.0
def discharge_passengers(self):
self.passengers = []
if __name__ == '__main__':
# Runtime tests will be here
vsl = Vessel('Casandra')
vsl.pump_in_fuel(10.5)
vsl.passengers = [
{
'name': 'Peter'
},
{
'name': 'Jessika'
}
]
|
class Error(Exception):
pass
class InvalidTypeError(Error):
pass
class InvalidArgumentError(Error):
pass
|
# 重み付きUnion-Find
class WeightedUnionFind:
def __init__(self, n: int) -> None:
self.n = n
self.par = list(range(n))
self.rank = [0] * n
self.weight = [0] * n
def find(self, x: int) -> int:
if self.par[x] == x:
return x
else:
y = self.find(self.par[x])
self.weight[x] += self.weight[self.par[x]]
self.par[x] = y
return y
def unite(self, x: int, y: int, w: int) -> None:
p, q = self.find(x), self.find(y)
if self.rank[p] < self.rank[q]:
self.par[p] = q
self.weight[p] = w - self.weight[x] + self.weight[y]
else:
self.par[q] = p
self.weight[q] = -w - self.weight[y] + self.weight[x]
if self.rank[p] == self.rank[q]:
self.rank[p] += 1
def same(self, x: int, y: int) -> bool:
return self.find(x) == self.find(y)
def diff(self, x: int, y: int) -> int:
return self.weight[x] - self.weight[y] |
# -*- coding: utf-8 -*-
"""
Created on May 4 - 2019
---Based on the 2-stage stochastic program structure
---Assumption: RHS is random
---read stoc file (.sto)
---save the distributoin of the random variables and return the
---random variables
@author: Siavash Tabrizian - [email protected]
"""
class readstoc:
def __init__(self, name):
self.name = name + ".sto"
self.rv = list()
self.dist = list()
self.cumul_dist = list()
self.rvnum = 0
## Read the stoc file
def readfile(self):
with open(self.name, "r") as f:
data = f.readlines()
count = 0
cumul = 0
for line in data:
words = line.split()
#print words
if len(words) > 2:
if words[0] != "RHS":
print("ERROR: Randomness is not on the RHS")
else:
#store the name of the random variables
if words[1] not in self.rv:
cumul = 0
self.rv.append(words[1])
tmp = list()
tmp.append({float(words[2]):float(words[3])})
self.dist.append(tmp)
tmp = list()
tmp.append({float(words[2]):float(words[3])})
self.cumul_dist.append(tmp)
count += 1
else:
cumul += float(words[3])
tmp = list()
tmp.append({float(words[2]):float(words[3])})
rvidx = self.rv.index(words[1])
self.dist[rvidx].append(tmp)
tmp = list()
tmp.append({float(words[2]):cumul})
self.cumul_dist[rvidx].append(tmp)
#count contains the number of rvs
self.rvnum = count
|
#********************************************************************
# Filename: FibonacciSearch.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the fibonacci search algorithm.
#*********************************************************************
def fibonacci_search(arr, val):
fib_N_2 = 0
fib_N_1 = 1
fibNext = fib_N_1 + fib_N_2
length = len(arr)
if length == 0:
return 0
while fibNext < len(arr):
fib_N_2 = fib_N_1
fib_N_1 = fibNext
fibNext = fib_N_1 + fib_N_2
index = -1
while fibNext > 1:
i = min(index + fib_N_2, (length - 1))
if arr[i] < val:
fibNext = fib_N_1
fib_N_1 = fib_N_2
fib_N_2 = fibNext - fib_N_1
index = i
elif arr[i] > val:
fibNext = fib_N_2
fib_N_1 = fib_N_1 - fib_N_2
fib_N_2 = fibNext - fib_N_1
else:
return i
if (fib_N_1 and index < length - 1) and (arr[index + 1] == val):
return index + 1
return -1
if __name__ == "__main__":
collection = [1, 6, 7, 0, 0, 0]
print("List numbers: %s\n" % repr(collection))
target_input = input("Enter a single number to be found in the list:\n")
target = int(target_input)
result = fibonacci_search(collection, target)
if result > 0:
print("%s found at positions: %s" % (target, result))
else:
print("Number not found in list")
|
class HostAssignedStorageVolumes(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_assigned_volumes(idx_name)
class HostAssignedStorageVolumesColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts()
|
class Input:
"""
Input prototype
"""
def __init__(self, mod_opts=None):
self.name = ""
self.pretty_name = ""
self.help = ""
self.image_large = ""
self.image_small = ""
self.opts = mod_opts
if mod_opts:
if 'name' in mod_opts:
self.name = mod_opts['name']
self.parse_options()
def List(self):
pass
def parse_options(self):
if self.opts:
# If this module has defined module options
if self.module_options:
self.module_options.parse_dict(self.opts) |
def checkBingo(c):
for x in range(5):
if c[(x * 5) + 0] == c[(x * 5) + 1] == c[(x * 5) + 2] == c[(x * 5) + 3] == c[(x * 5) + 4] == True:
return True
if c[x + 0] == c[x + 5] == c[x + 10] == c[x + 15] == c[x + 20] == True:
return True
return False
def part2(path):
p_input = []
with open(path) as input:
for l in input:
p_input.append(l)
drawing = [int(x) for x in p_input[0].split(",")]
p_input = p_input[2:]
card = 0
cards = [[]]
ticked = [[]]
for l in p_input:
if l == "\n":
card += 1
cards.append([])
ticked.append([])
else:
# print(l[0:2])
cards[card].append(int(l[0:2]))
ticked[card].append(False)
# print(l[3:5])
cards[card].append(int(l[3:5]))
ticked[card].append(False)
# print(l[6:8])
cards[card].append(int(l[6:8]))
ticked[card].append(False)
# print(l[9:11])
cards[card].append(int(l[9:11]))
ticked[card].append(False)
# print(l[12:15])
cards[card].append(int(l[12:15]))
ticked[card].append(False)
cards_won = 0
won_cards = set()
for n in drawing:
for i, x in enumerate(cards):
for j, y in enumerate(x):
if y == n:
ticked[i][j] = True
for i in range(len(cards)):
if i not in won_cards and checkBingo(ticked[i]):
# print(i)
cards_won += 1
won_cards.add(i)
if cards_won == len(cards):
sum_unmarked = 0
for x in range(25):
if not ticked[i][x]:
sum_unmarked += cards[i][x]
# print(n)
return sum_unmarked * n |
# 207-course-schedule.py
#
# Copyright (C) 2019 Sang-Kil Park <[email protected]>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# Make skeleton vertex graph.
graph = {k[1]: [] for k in prerequisites}
for pr in prerequisites:
graph[pr[1]].append(pr[0])
visited = set() # Visited vertex set for permanent storage
traced = set() # Traced vertex set for temporary storage.
def visit(vertex):
if vertex in visited:
return False
traced.add(vertex)
visited.add(vertex)
if vertex in graph:
for neighbour in graph[vertex]:
if neighbour in traced or visit(neighbour):
return True # cyclic!
traced.remove(vertex)
return False
for v in graph:
if visit(v):
return False
return True
|
def main():
n = int(input("Enter a number: "))
for i in range(3, n + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime: print(f"{i} ", end="")
print()
if __name__ == '__main__':
main()
|
class Registry(object):
def __init__(self, name):
super(Registry, self).__init__()
self._name = name
self._module_dict = dict()
@property
def name(self):
return self._name
@property
def module_dict(self):
return self._module_dict
def __len__(self):
return len(self.module_dict)
def get(self, key):
return self._module_dict[key]
def register_module(self, module=None):
if module is None:
raise TypeError('fail to register None in Registry {}'.format(self.name))
module_name = module.__name__
if module_name in self._module_dict:
raise KeyError('{} is already registry in Registry {}'.format(module_name, self.name))
self._module_dict[module_name] = module
return module
DATASETS = Registry('dataset')
BACKBONES = Registry('backbone')
NETS = Registry('nets')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.