content
stringlengths 7
1.05M
|
---|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **unimportable data submodule.**
This submodule exercises dynamic importability by providing an unimportable
submodule defining an arbitrary attribute. External unit tests are expected to
dynamically import this attribute from this submodule.
'''
# ....................{ EXCEPTIONS }....................
raise ValueError(
'Can you imagine a fulfilled society? '
'Whoa, what would everyone do?'
)
|
while True:
print("hello")
if 2<1:
2
print('hi')
|
# Copyright 2016 by Raytheon BBN Technologies Corp. All Rights Reserved
"""
Names and descriptions of attributes that may be
added to AST nodes to represent information used
by the preprocessor.
Attribute names are typically used literally (except
when checking for the presence of an attribute by name)
so the purpose of this file is primarily documentation.
"""
class QGL2Ast(object):
"""
Attribute names and their descriptions
"""
# The name of the source file associated with this node
#
# All AST nodes that the preprocessor uses should have this
# attribute. When the preprocessor inserts new nodes, this
# attribute should be added
#
qgl_fname = 'qgl_fname'
# this attribute, if present, denotes the set of qbits
# referenced by descendants of this node (or None if there
# are no referenced qbits)
#
qgl_qbit_ref = 'qgl_qbit_ref'
# An attribute present on FunctionDef nodes that are marked
# as QGL2 functions
#
qgl_func = 'qgl_func'
# An attribute present on FunctionDef nodes that are marked
# as QGL2 stub functions. Stub functions are defined elsewhere
# (usually in QGL1) but the stub definition contains information
# about the type signature of the function
#
qgl_stub = 'qgl_stub'
# If a function call has been inlined, then the call node
# in the original AST is given an attribute that refers to
# the inlined version of the call
#
qgl_inlined = 'qgl_inlined'
|
# Słownik tylko do reprezentacji "graficznej" liter UTF-8 do latin1
characters_dict = {
"ą": "±",
"ę": "ê",
"ź": "¼",
"ś": "¶",
"ł": ("³", "£"),
"ń": "ñ",
"ż": "¿"
}
unused_words = ("<tr>",
"</>",
"tr",
"td",
"nobr",
"lekcja",
"opis",
"zastępca",
"uwagi",
"class")
def repair_line(line):
utf8 = ("ą", "ę", "ź", "ś", "ł", "ł", "ń", "ż")
latin1 = ("±", "ê", "¼", "¶", "³", "£", "ñ", "¿")
for number in range(0, 7):
new_line = line.replace(latin1[number], utf8[number])
if new_line != line:
line = repair_line(new_line)
return line
def file_converter(path_to_file):
new_file = []
with open("{}.txt".format(path_to_file), "r") as f:
file = f.readlines()
for line in file:
new_file.append(repair_line(line))
with open("{}_utf-8.txt".format(path_to_file), "w") as f:
for line in new_file:
for number, word in enumerate(unused_words):
if line.count(word) and not line.count("colspan"):
break
else:
if number == 9:
f.writelines(line)
|
'''
A submodule for doing basic error analysis for experimental
physics results.
'''
def average(values):
# TODO: add documentation
pass
def percent_diff(expected, actual):
# TODO: add documentation
pass
|
# A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist)
# You access the list items by referring to the index number
# Print the second item of the list
print("The second element of list are:" + thislist[1]);
# Negative indexing means beginning from the end, -1 refers to the last item,
# -2 refers to the second last item etc.
# Print the last item of the list
print("The last element of list are:" + thislist[-1] );
# You can specify a range of indexes by specifying where to start and where to end the range.
# When specifying a range, the return value will be a new list with the specified items.
# Return the third, fourth, and fifth item
print("The 3rd 4th and 5th item of list are:");
print(thislist[2:5]);
# This example returns the items from the beginning to "orange"
print(thislist[:4]);
# This example returns the items from "cherry" and to the en
print(thislist[2:]);
# Specify negative indexes if we want to start the search from the end of the list
print(thislist[-4:-1]);
# To change the value of a specific item, refer to the index number
thislist[1] = "blackcurrant";
print(thislist);
# You can loop through the list items by using a for loop
for item in thislist:
print(item);
# To determine if a specified item is present in a list use the in keyword
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
else:
print("No, 'apple' is not in the fruits list")
#To determine how many items a list has, use the len() function
txt = "The length of list are {}";
length = len(thislist);
print(txt.format(length));
# To add an item to the end of the list, use the append() method
thislist.append("pineapple");
print(thislist);
# To add an item at the specified index, use the insert() method
thislist.insert(0,"Delicious Apple");
print(thislist);
# The remove() method removes the specified item
thislist.remove("orange");
print(thislist);
# The pop() method removes the specified index, (or the last item if index is not specified
thislist.pop();
print(thislist);
# The del keyword removes the specified index
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
# The del keyword can also delete the list completely
del thislist;
# print(thislist);
# The clear() method empties the list
thislist = ["apple", "banana", "cherry"];
thislist.clear();
print(thislist);
# You cannot copy a list simply by typing list2 = list1,
# because: list2 will only be a reference to list1,
# and changes made in list1 will automatically also be made in list2.
# There are ways to make a copy, one way is to use the built-in List method copy().
# Make a copy of a list with the copy() method
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
# Another way to make a copy is to use the built-in method list()
# Make a copy of a list with the list() method
mylist = list(thislist)
print(mylist)
# There are several ways to join, or concatenate, two or more lists in Python.
# One of the easiest ways are by using the + operator.
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
# Another way to join two lists are by appending all the items from list2 into list1, one by one:
list1 = ["a", "b" , "c"]
list2 = [5, 6, 7]
for x in list2:
list1.append(x)
print(list1)
# you can use the extend() method, which purpose is to add elements from one list to another list
list1 = ["a", "b" , "c"]
list2 = [8, 9, 10]
list1.extend(list2)
print(list1)
# It is also possible to use the list() constructor to make a new list
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
# we can sort the list using the sort() method
print(thislist.sort());
|
#codeing=utf-8
# @Time : 2017-11-08
# @Author : J.sky
# @Mail : [email protected]
# @Site : www.17python.com
# @Title : 实战:利用Django开发部署自己的个人博客(2)视图/路由
# @Url : http://www.17python.com/blog/53
# @Details : 实战:利用Django开发部署自己的个人博客(2)视图/路由
# @Other : OS X 10.11.6
# Python 3.6.1
# VSCode 1.15.1
###################################
# 实战:利用Django开发部署自己的个人博客(2)视图/路由
###################################
'''
`Django`的强大之处上节我们已经体验过了,虽然上线部署还有一段距离,但一个好的开始就是预示成功即将到来。。。
## `Django`的配置文件
`blog01.settings.py`是你的项目配置文件,这里可以配置的网站常用的选项。
+ `BASE_DIR` 表示当前网站的根目录,当然你也可以添加并设置其它目录的常量
+ `DEBUG=True`的时候是开发模式,当上线部署在生产模式时这里应该设置为False
+ `INSTALLED_APPS` 这里设置你建好并启用的app 比如添加我们创建的`'myblog',`,直接添加到后边即可,记得那个逗号。
+ `MIDDLEWARE Django`中需要的模块,如果需要Django新功能模块,需要在这里添加。
+ `ROOT_URLCONF = 'blog01.urls'` 这个表示一个默认的路由,可以在这里设置一些路由的跳转
+ `DATABASES` 设置数据库,这里我们使用默认的数据库`sqlite3`即可。
还有一些其它设置项,我们会在后边用到的时候介绍,另外你也可以参考官方网站的相关文档。
我们先设置一下项目配置文件,启用新项目myblog:
`INSTALLED_APPS` 这里设置你建好并启用的app 比如添加我们创建的`'myblog',`,直接添加到后边即可,记得那个逗号。
![配图]()
接下来我们就可以设置路由
## 配置路由
路由是什么东东?假设你有一个网站域名`17python.com`,在主域名下的/blog或/news是单独一个app,
这时你就可以使用路由,单独指向自己的空间方便区分。设置我们的blog路由:
在`blog01/urls.py`中设置如下代码:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/', include('myblog.urls')),
]
这样设置路由就是把blog/下边的路由都交给`myblog.usrs.py`中来设置了。我们继续设置一个视图,验证一下我们的路由是否成功
## 编写视图
视图与路由是对好兄弟,一般都是相互存在的。我们来设置一下`blog`的主页。
先编写`myblog.views.py`中视图代码:
from django.http import HttpResponse, HttpResponseRedirect
def index(request):
return HttpResponse('你好,Django,江哥?')
设置`myblog.urls.py`中的路:
urlpatterns = [
url(r'^$', v.index),#项目首页
]
设置到这里,我们就可以启动服务器测试了,还记得服务器启动命令不?
python3 manage.py runserver
![]()
如果显示和上图一样的话,那么恭喜你!配置成功!
'''
|
#Faça um programa utilizando um dict que leia dados de entrada do usuário. O usuário deve entrar
#com os dados de uma pessoa como nome, idade e cidade onde mora (fique livre para acrescentar
#outros). Após isso, você deve imprimir os dados como o exemplo abaixo:
#nome: João
#dade: 20
#idade: São Paulo
#(Opcional) Utilize o exercício anterior e adicione a pessoa em uma lista. Pergunte ao usuário se ele
#deseja adicionar uma nova pessoa. Após adicionar dados de algumas pessoas, você deve imprimir
#todos os dados de cada pessoa de forma organizada.
dados = dict(nome=input("Digite o seu nome: "), idade=input("Idade: "), cidade=input("Cidade: "))
lista = []
adiciona = str(input('Deseja adicionar os dados na lista?\n s - sim\n n - não\n').strip().lower())
adiciona = True
if adiciona == True:
for adiciona in range(1, 2):
dados = dict(nome=input("Digite o seu nome: "), idade=input("Idade: "), cidade=input("Cidade: "))
lista.append(dados)
lista = lista + lista
#print(dados)
print(lista)
|
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="gprpy",
version="1.0.8",
author="Alain Plattner",
author_email="[email protected]",
description="GPRPy - open source ground penetrating radar processing and visualization",
entry_points={'console_scripts': ['gprpy = gprpy.__main__:main']},
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/NSGeophysics/GPRPy",
packages=['gprpy'],
package_data={'gprpy': ['exampledata/GSSI/*.DZT',
'exampledata/GSSI/*.txt',
'exampledata/SnS/ComOffs/*.xyz',
'exampledata/SnS/ComOffs/*.DT1',
'exampledata/SnS/ComOffs/*.HD',
'exampledata/SnS/WARR/*.DT1',
'exampledata/SnS/WARR/*.HD',
'exampledata/pickedSurfaceData/*.txt',
'examplescripts/*.py',
'toolbox/splashdat/*.png',
'toolbox/*.py',
'irlib/*.py',
'irlib/external/*.py']},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
install_requires=['tqdm','numpy','scipy','matplotlib','Pmw','pyevtk']
)
|
class _Emojis:
def __init__(self):
self.key = "\U0001F511"
self.link = "\U0001F4CE"
self.alert = "\U0001F6A8"
self.ghost = "\U0001F47B"
self.package = "\U0001F4E6"
self.folder = "\U0001F5C2"
self.bell = "\U0001F514"
self.dissy = "\U0001F4AB"
self.genie = "\U0001F9DE"
self.linked_paperclip = "\U0001F587"
self.file_cabinet = "\U0001F5C3"
self.graduation_cap = "\U0001F393"
self.safety_helmet = "\U000026D1"
self.grinning_cat1 = "\U0001F638"
self.fire = "\U0001F525"
self.pan = "\U0001F373"
Emojis = _Emojis()
|
icu_sources = [
'utypes.cpp',
'uloc.cpp',
'ustring.cpp',
'ucase.cpp',
'ubrk.cpp',
'brkiter.cpp',
'filteredbrk.cpp',
'ucharstriebuilder.cpp',
'uobject.cpp',
'resbund.cpp',
'servrbf.cpp',
'servlkf.cpp',
'serv.cpp',
'servnotf.cpp',
'servls.cpp',
'servlk.cpp',
'servslkf.cpp',
'stringtriebuilder.cpp',
'uvector.cpp',
'ustrenum.cpp',
'uenum.cpp',
'unistr.cpp',
'appendable.cpp',
'rbbi.cpp',
'rbbi_cache.cpp',
'cstring.cpp',
'umath.cpp',
'charstr.cpp',
'rbbidata.cpp',
'ustrfmt.cpp',
'ucharstrie.cpp',
'uloc_keytype.cpp',
'uhash.cpp',
'locdispnames.cpp',
'brkeng.cpp',
'dictionarydata.cpp',
'udataswp.cpp',
'uinvchar.cpp',
'uresbund.cpp',
'uresdata.cpp', # modified due to duplicate symbol `gEmptyString2`
'resource.cpp',
'locavailable.cpp',
'utrie2.cpp',
'ucol_swp.cpp',
'utrie_swap.cpp',
'schriter.cpp',
'uchriter.cpp',
'locid.cpp', # modified due to duplicate include `bytesinkutil.h`
'locbased.cpp',
'chariter.cpp',
'uvectr32.cpp',
'bytestrie.cpp',
'ustack.cpp',
'umutex.cpp',
'uniset.cpp', # modified due to duplicate symbol `compareUnicodeString2`
'stringpiece.cpp',
'locutil.cpp',
'unifilt.cpp',
'util.cpp', # modified due to duplicate symbol `BACKSLASH2`, `UPPER_U2`, and `LOWER_U2`
'bmpset.cpp',
'unifunct.cpp',
'unisetspan.cpp',
'uniset_props.cpp', # modified due to duplicate include `_dbgct2`
'patternprops.cpp',
'bytesinkutil.cpp', # modified due to duplicate include `bytesinkutil.h`
'dictbe.cpp',
'rbbirb.cpp',
'utext.cpp', # modified due to duplicate symbol `gEmptyString3`
'utf_impl.cpp',
'propsvec.cpp',
'locmap.cpp',
'loclikely.cpp',
'uloc_tag.cpp',
'ustrtrns.cpp',
'udatamem.cpp',
'putil.cpp',
'uhash_us.cpp',
'uprops.cpp',
'uchar.cpp', # modified due to duplicate symbol `_enumPropertyStartsRange2`
'parsepos.cpp',
'ruleiter.cpp',
'rbbitblb.cpp',
'edits.cpp',
'rbbinode.cpp',
'bytestream.cpp',
'rbbiscan.cpp',
'loadednormalizer2impl.cpp',
'characterproperties.cpp',
'locresdata.cpp',
'normalizer2impl.cpp', # modified due to duplicate include `bytesinkutil.h`
'normalizer2.cpp',
'rbbisetb.cpp',
'rbbistbl.cpp',
'unistr_case.cpp',
'unames.cpp', # modified due to duplicate symbol `DATA_TYPE2`
'propname.cpp',
'ustrcase.cpp',
'ustrcase_locale.cpp',
'ubidi.cpp',
'ucptrie.cpp',
'umutablecptrie.cpp', # modified due to duplicate symbol `getRange2` and `OVERFLOW2`
'cmemory.cpp',
'utrie2_builder.cpp', # modified due to duplicate symbol `writeBlock2`
'uscript.cpp',
'uscript_props.cpp',
'utrie.cpp', # modified due to duplicate symbol `equal_uint322` and `enumSameValue2`
'ucmndata.cpp',
'uarrsort.cpp',
'umapfile.cpp',
'ucln_cmn.cpp', # modified due to duplicate include `ucln_imp.h`
'uregex.cpp', # modified due to duplicate symbol `BACKSLASH3`
'ucol.cpp',
'coll.cpp', # modified due to duplicate symbol `gService2`, `getService2`, `initService2`, `hasService2`, `availableLocaleList2`
'collation.cpp',
'ucoleitr.cpp',
'rematch.cpp', # modified due to duplicate symbol `BACKSLASH4`
'regexcmp.cpp',
'repattrn.cpp',
'collationroot.cpp',
'ucol_res.cpp',
'collationbuilder.cpp',
'coleitr.cpp',
'sharedobject.cpp',
'collationdata.cpp',
'uiter.cpp',
'ucln_in.cpp', # modified due to duplicate symbol `copyright2` and duplicate include `ucln_imp.h`
'uniset_closure.cpp',
'unifiedcache.cpp', # modified due to duplicate symbol `gCacheInitOnce2`
'regexst.cpp',
'collationweights.cpp',
'caniter.cpp',
'collationiterator.cpp',
'collationfastlatin.cpp',
'collationtailoring.cpp',
'usetiter.cpp',
'collationdatareader.cpp',
'collationruleparser.cpp',
'collationdatabuilder.cpp',
'regeximp.cpp',
'collationsets.cpp',
'utf16collationiterator.cpp',
'uvectr64.cpp',
'rulebasedcollator.cpp',
'collationrootelements.cpp',
'ucol_sit.cpp', # modified due to duplicate symbol `internalBufferSize2`
'ulist.cpp',
'uset.cpp',
'regextxt.cpp',
'ucharstrieiterator.cpp',
'collationfcd.cpp',
'collationkeys.cpp',
'unistr_case_locale.cpp',
'collationsettings.cpp',
'collationcompare.cpp',
'utf8collationiterator.cpp',
'uitercollationiterator.cpp',
'collationfastlatinbuilder.cpp',
'collationdatawriter.cpp',
'uset_props.cpp',
'utrace.cpp',
'sortkey.cpp',
'unistr_titlecase_brkiter.cpp',
'ubidi_props.cpp', # modified due to duplicate symbol `_enumPropertyStartsRange3`
'bocsu.cpp',
'ubidiln.cpp',
'ubidiwrt.cpp',
'ustr_titlecase_brkiter.cpp',
'wintz.cpp',
'stubdata.cpp',
'udata.cpp',
# modified due to to comment out `extern "C" const DataHeader U_DATA_API
# U_ICUDATA_ENTRY_POINT;` and cast `(const DataHeader*)` due to
# stubdata.cpp being added
]
# Other modifications:
# Modify: regexcst.h
# Replace the header gaurd with:
# #ifndef REGEXCST_H
# #define REGEXCST_H
# Modify: regexcmp.h
# Replace the header gaurd with:
# #ifndef REGEXCMP_H
# #define REGEXCMP_H
# Modify: regexcst.h
# Append '2' to every enum in Regex_PatternParseAction
# Replace all of the references to those enums in regexcst.h and regexcmp.cpp
# Modify: regexcst.h
# Replace: `gRuleParseStateTable` symbol with `gRuleParseStateTable2`
# Replace with `gRuleParseStateTable` in regexcmp.cpp
|
while(True):
try:
x, a, y, b = map(int, input().split())
if(x * b == a * y):
print("=")
elif (x * b > a * y):
print(">")
else:
print("<")
except:
exit()
|
class Graph(object):
def __init__(self, graph={}):
""" create the graph dictionary. use empty dictionary if no input. """
self.graph = graph
def vertex(self, v):
""" add new vertex. checks to see if vertex is already present before adding. """
if v not in self.graph:
self.graph[v] = []
def vertices(self):
""" returns vertices of graph, the keys of the dictionary, as list. """
return list(self.graph.keys())
def edge(self, edge):
""" edge data is in format vertex 1, vertex 2, weight. checks to see if origin vertex is present before adding. """
(v1, v2, w) = tuple(edge)
if v1 in self.graph:
self.graph[v1].append([v2,w])
def adjacency(self):
return sorted(self.graph)
def edges(self):
""" return the edges connecting vertices. list of edges, """
edges = []
for v1 in self.graph:
for v2 in self.graph[v1]:
if [v2, v1] not in edges:
edges.append([v1, v2])
return sorted(edges)
def dfs(graph, start):
""" depth first search. uses a stack, first in last out. """
x = graph.edges()
path = []
stack = [start]
""" while there are elements in the stack, if the vertex has not been visited, add it to the visited list and remove it from the stack. if the vertex has any edges look in the edges and add destination nodes to the stack. repeat until there are no more items in the stack. """
while stack:
v = stack.pop()
if v not in visited:
visited.append(v)
for i in x:
if v in i:
stack.append(i[1][0])
return visited
def bfs(graph, start):
""" breadth first search. uses a queue, first in first out. """
x = graph.edges()
path = []
queue = [start]
""" while there are elements in the queue, if the vertex has not been visited, add it to the visited list and remove it from the queue. if the vertex has any edges look in the edges and add destination nodes to the queue. repeat until there are no items in the queue. """
while queue:
v = queue.pop(0)
if v not in visited:
visited.append(v)
for i in x:
if v in i:
queue.append(i[1][0])
return visited
""" write to file """
def save_file(graph, start):
f = open('search.txt','w')
f.write("DFS: ")
f.write(str(dfs(graph, start)))
f.write("\n")
f.write("BFS : ")
f.write(str(bfs(graph, start)))
f.close()
|
META = [{
'lookup': 'city',
'tag': 'city',
'path': ['names','en'],
},{
'lookup': 'continent',
'tag': 'continent',
'path': ['names','en'],
},{
'lookup': 'continent_code',
'tag': 'continent',
'path': ['code'],
},{
'lookup': 'country',
'tag': 'country',
'path': ['names','en'],
},{
'lookup': 'iso_code',
'tag': 'country',
'path': ['iso_code'],
},{
'lookup': 'latitude',
'tag': 'location',
'path': ['latitude'],
},{
'lookup': 'longitude',
'tag': 'location',
'path': ['longitude'],
},{
'lookup': 'metro_code',
'tag': 'location',
'path': ['metro_code'],
},{
'lookup': 'postal_code',
'tag': 'postal',
'path': ['code'],
}]
PORTMAP = {
0:"DoS", # Denial of Service
1:"ICMP", # ICMP
20:"FTP", # FTP Data
21:"FTP", # FTP Control
22:"SSH", # SSH
23:"TELNET", # Telnet
25:"EMAIL", # SMTP
43:"WHOIS", # Whois
53:"DNS", # DNS
80:"HTTP", # HTTP
88:"AUTH", # Kerberos
109:"EMAIL", # POP v2
110:"EMAIL", # POP v3
115:"FTP", # SFTP
118:"SQL", # SQL
143:"EMAIL", # IMAP
156:"SQL", # SQL
161:"SNMP", # SNMP
220:"EMAIL", # IMAP v3
389:"AUTH", # LDAP
443:"HTTPS", # HTTPS
445:"SMB", # SMB
636:"AUTH", # LDAP of SSL/TLS
1433:"SQL", # MySQL Server
1434:"SQL", # MySQL Monitor
3306:"SQL", # MySQL
3389:"RDP", # RDP
5900:"RDP", # VNC:0
5901:"RDP", # VNC:1
5902:"RDP", # VNC:2
5903:"RDP", # VNC:3
8080:"HTTP", # HTTP Alternative
}
|
# Example: Fetch single bridge by ID
my_bridge = api.get_bridge('brg-bridgeId')
print(my_bridge)
## { 'bridgeAudio': True,
## 'calls' : 'https://api.catapult.inetwork.com/v1/users/u-123/bridges/brg-bridgeId/calls',
## 'createdTime': '2017-01-26T01:15:09Z',
## 'id' : 'brg-bridgeId',
## 'state' : 'created'}
print(my_bridge["state"])
## created
|
# partisan.tests
# Tests for the complete partisan package.
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Sat Jul 16 11:36:08 2016 -0400
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: __init__.py [80822db] [email protected] $
"""
Tests for the complete partisan package.
"""
##########################################################################
## Imports
##########################################################################
|
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
l = len(num)
for i in range(1, (2 * l) // 3):
for j in range(0, i):
if num[0] == "0" and j + 1 != 1:
break
if num[j + 1] == "0" and i - j != 1:
continue
lst1, lst2 = int(num[0: j + 1]), int(num[j + 1: i + 1])
cur = i + 1
flag = 1
while cur < l:
nxt = lst1 + lst2
ll = len(str(nxt))
if ll + cur > l or int(num[cur: cur + ll]) != nxt:
flag = 0
break
cur += ll
lst1, lst2 = lst2, nxt
if not flag:
continue
else:
return True
return False
|
class Solution:
def findBestValue(self, arr: List[int], target: int) -> int:
ln = len(arr)
arr.sort()
arr.insert(0, 0)
arr_sum = arr.copy()
for i in range(1, ln + 1): arr_sum[i] += arr_sum[i - 1]
# 二不二分其实无所谓, 时间复杂度的大头是排序 O(nlogn), 下面用遍历也就 O(n)
# for i in range(ln): # 本来应该是 ln - 1, 但是 insert 了一个 0, 于是刚好是 ln
# v = (target - arr_sum[i]) // (ln - i)
# if v < arr[i + 1]:
# d1 = abs(target - arr_sum[i] - v * (ln - i))
# d2 = abs(target - arr_sum[i] - (v + 1) * (ln - i))
# return min(arr[ln], v + (1 if d1 > d2 else 0))
# return arr[ln]
# 但是还是写了个二分版本 (——,——), 结果提交上去时间果然完全没区别 (都是64ms)
l, r = 0, ln
while True:
m = l + r >> 1
v = (target - arr_sum[m]) // (ln - m)
if v < arr[m]: r = m
elif v >= arr[m + 1] and m < ln -1: l = m
else:
d1 = abs(target - arr_sum[m] - v * (ln - m))
d2 = abs(target - arr_sum[m] - (v + 1) * (ln - m))
return min(arr[ln], v + (1 if d1 > d2 else 0))
return arr[ln]
|
# Database Config
config = {
'MYSQL_DATABASE_USER' : 'root', #Username for mysql
'MYSQL_DATABASE_DB' : 'CoveServices',
'MYSQL_DATABASE_PASSWORD' : 'root', # Password to connect to mysql
'MYSQL_DATABASE_HOST' : 'localhost',
'USERNAME' : '',
'USERID' :'',
}
|
nota1 = float(input())
while nota1 > 10 or nota1 < 0:
print('nota invalida')
nota1 = float(input())
nota2 = float(input())
while nota2 > 10 or nota2 < 0:
print('nota invalida')
nota2 = float(input())
media = (nota1+nota2)/2
print('media = %.2f'%media)
|
players = """
-- Name; Case Race; Beer Ball; Flip 50;
Nicole;1;2;2;
Jenna;2;2;5;
Krendan;4;3;3;
Dylan;4;3;3;
Luke;5;5;3;
Jason;5;4;3;
Brendan;5;4;3;
James E;3;3;3;
Aidan;3;4;5;
Daniel;4;5;4;
Maya;3;3;5;
James C;3;3;3;
Kayvan;3;2;2;
Steph;3;2;4;
Kevin;3;3;3;
"""
|
km = float(input('Digite a distância da sua viagem: '))
if km <= 200:
print(f'Como a sua viagem é de {km} o preço da sua passagem será R${0.5*km}')
else:
print(f'Como a sua viagem é mais longa que 200km, o preço da sua passagem sera de R${0.45*km}')
print('Boa Viagem!')
|
# -*- coding: utf-8 -*-
# TODO: deprecated
URL_DID_SIGN_IN = '/api/v2/did/signin'
URL_DID_AUTH = '/api/v2/did/auth'
URL_DID_BACKUP_AUTH = '/api/v2/did/backup_auth'
URL_BACKUP_SERVICE = '/api/v2/internal_backup/service'
URL_BACKUP_FINISH = '/api/v2/internal_backup/finished_confirmation'
URL_BACKUP_FILES = '/api/v2/internal_backup/files'
URL_BACKUP_FILE = '/api/v2/internal_backup/file'
URL_BACKUP_PATCH_HASH = '/api/v2/internal_backup/patch_hash'
URL_BACKUP_PATCH_DELTA = '/api/v2/internal_backup/patch_delta'
URL_BACKUP_PATCH_FILE = '/api/v2/internal_backup/patch_file'
URL_RESTORE_FINISH = '/api/v2/internal_restore/finished_confirmation'
# TODO: deprecated
URL_IPFS_BACKUP_PIN_CIDS = '/api/v2/ipfs-backup-internal/pin_cids'
URL_IPFS_BACKUP_GET_CIDS = '/api/v2/ipfs-backup-internal/get_cids'
URL_IPFS_BACKUP_GET_DBFILES = '/api/v2/ipfs-backup-internal/get_dbfiles'
URL_IPFS_BACKUP_STATE = '/api/v2/ipfs-backup-internal/state'
URL_VAULT_BACKUP_SERVICE_BACKUP = '/api/v2/vault-backup-service/backup'
URL_VAULT_BACKUP_SERVICE_RESTORE = '/api/v2/vault-backup-service/restore'
URL_VAULT_BACKUP_SERVICE_STATE = '/api/v2/vault-backup-service/state'
BACKUP_FILE_SUFFIX = '.backup'
DID = 'did'
USR_DID = 'user_did'
APP_DID = 'app_did'
OWNER_ID = 'owner_id'
CREATE_TIME = 'create_time'
MODIFY_TIME = 'modify_time'
SIZE = 'size'
STATE = 'state'
STATE_RUNNING = 'running'
STATE_FINISH = 'finish'
STATE_FAILED = 'failed'
ORIGINAL_SIZE = 'original_size'
IS_UPGRADED = 'is_upgraded'
CID = 'cid'
COUNT = 'count'
COL_ORDERS = 'vault_order'
COL_ORDERS_SUBSCRIPTION = 'subscription'
COL_ORDERS_PRICING_NAME = 'pricing_name'
COL_ORDERS_ELA_AMOUNT = 'ela_amount'
COL_ORDERS_ELA_ADDRESS = 'ela_address'
COL_ORDERS_PROOF = 'proof'
COL_ORDERS_STATUS = 'status'
COL_ORDERS_STATUS_NORMAL = 'normal'
COL_ORDERS_STATUS_PAID = 'paid'
COL_ORDERS_STATUS_ARCHIVE = 'archive'
COL_RECEIPTS = 'vault_receipt'
COL_RECEIPTS_ID = 'receipt_id'
COL_RECEIPTS_ORDER_ID = 'order_id'
COL_RECEIPTS_TRANSACTION_ID = 'transaction_id'
COL_RECEIPTS_PAID_DID = 'paid_did'
COL_IPFS_FILES = 'ipfs_files'
COL_IPFS_FILES_PATH = 'path'
COL_IPFS_FILES_SHA256 = 'sha256'
COL_IPFS_FILES_IS_FILE = 'is_file'
COL_IPFS_FILES_IPFS_CID = 'ipfs_cid'
COL_IPFS_CID_REF = 'ipfs_cid_ref'
COL_IPFS_BACKUP_CLIENT = 'ipfs_backup_client'
COL_IPFS_BACKUP_SERVER = 'ipfs_backup_server'
BACKUP_TARGET_TYPE = 'type'
BACKUP_TARGET_TYPE_HIVE_NODE = 'hive_node'
BACKUP_TARGET_TYPE_GOOGLE_DRIVER = 'google_driver'
BACKUP_REQUEST_ACTION = 'action'
BACKUP_REQUEST_ACTION_BACKUP = 'backup'
BACKUP_REQUEST_ACTION_RESTORE = 'restore'
BACKUP_REQUEST_STATE = 'state'
BACKUP_REQUEST_STATE_STOP = 'stop'
BACKUP_REQUEST_STATE_INPROGRESS = 'process'
BACKUP_REQUEST_STATE_SUCCESS = 'success'
BACKUP_REQUEST_STATE_FAILED = 'failed'
BACKUP_REQUEST_STATE_MSG = 'state_msg'
BACKUP_REQUEST_TARGET_HOST = 'target_host'
BACKUP_REQUEST_TARGET_DID = 'target_did'
BACKUP_REQUEST_TARGET_TOKEN = 'target_token'
# For backup subscription.
BKSERVER_REQ_ACTION = 'req_action'
BKSERVER_REQ_STATE = 'req_state'
BKSERVER_REQ_STATE_MSG = 'req_state_msg'
BKSERVER_REQ_CID = 'req_cid'
BKSERVER_REQ_SHA256 = 'req_sha256'
BKSERVER_REQ_SIZE = 'req_size'
def get_unique_dict_item_from_list(dict_list: list):
if not dict_list:
return list()
return list({frozenset(item.items()): item for item in dict_list}.values())
|
"""
.. module: lemur.plugins.utils
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <[email protected]>
"""
def get_plugin_option(name, options):
"""
Retrieve option name from options dict.
:param options:
:return:
"""
for o in options:
if o.get('name') == name:
return o['value']
|
def input(channel):
pass
def wait_for_edge(channel, edge_type, timeout=None):
pass
def add_event_detect(channel, edge_type, callback=None, bouncetime=None):
pass
def add_event_callback(channel, callback, bouncetime=None):
pass
def event_detected(channel):
pass
def remove_event_detect(channel):
pass
|
n = input('digite alguma coisa: ')
print('o Caracter',n, 'é ',n.isalpha())
print('o Caracter é Alfa numérico ? ',n.isalpha())
print(' ele é um número ? ',n.isalnum())
print('ele é número decimal ? ',n.isdecimal())
|
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
st = []
res = []
def backtracking(op ,cl):
if op == cl == n :
res.append("".join(st))
return
if op < n :
st.append("(")
backtracking(op+1,cl)
st.pop()
if cl < op :
st.append(")")
backtracking(op,cl+1)
st.pop()
backtracking(0,0)
return res
|
#!/usr/bin/env python
# coding=utf-8
# [email protected]
# create=20160518
"""
* Author Dave
* Version 1.0
* 此文件中包含的方法属于常用方法,一些复用多的方法。
"""
def normalize_url(target, https=False):
# 标准化 Target 信息
if not target:
return
elif target.startswith(('http://', 'https://')):
return target
if not https:
target = 'http://' + target
else:
target = 'https://' + target
return target
|
general_desc = """
<div><span class="bold">$name</span><span>: $desc</span></div>
"""
general_head = """
<html>
<body>
"""
general_foot = """
</html>
</body>
"""
not_srd = """
<!DOCTYPE html>
<html>
<head>
<style>
.name {
font-size:225%;
font-family:Georgia, serif;
font-variant:small-caps;
font-weight:bold;
color:#A73335;
</style>
</head>
<body>
<div contenteditable="false" style="width:310px; font-family:Arial,Helvetica,sans-serif;font-size:17px;">
<div class="name"> $name is not SRD :( </div>
"""
item_dict = dict(
header="""
<!DOCTYPE html>
<html>
<head>
<style>
.gradient {
margin:10px 0px;
}
.name {
font-size:225%;
font-family:Georgia, serif;
font-variant:small-caps;
font-weight:bold;
color:#A73335;
}
.description {
font-style:italic;
}
.bold {
font-weight:bold;
}
.red {
color:#A73335;
}
table {
width:100%;
border:0px;
border-collapse:collapse;
color:#A73335;
}
th, td {
width:50px;
text-align:center;
}
.actions {
font-size:175%;
font-variant:small-caps;
margin:17px 0px 0px 0px;
}
.hr {
background: #A73335;
height:2px;
}
.attack_odd {
margin:10px 0px;
color: black;
}
.attack_even {
margin:10px 0px;
color: white;
}
.bolditalic {
font-weight:bold;
font-style:italic;
}
</style>
</head>
<body>
<div contenteditable="true" style="width:310px; font-family:Arial,Helvetica,sans-serif;font-size:17px;">
""",
gradient="""
<div class="gradient"><img scr="assets/linear_gradient.png;" /></div>
""",
name="""
<div class="name"> $desc </div>
""",
desc="""
<div><span class="bold">$name</span><span> $desc</span></div>
""",
dmg="""
<div><span class="bold">Damage</span><span> $dmg1 $dmgType</span></div>
""",
dmg_vers="""
<div><span class="bold">Damage</span><span> $dmg1($dmg2) $dmgType</span></div>
""",
text="""
<div><span> $text</span></div>
""",
foot="""
</div>
</body>
</html>
""",
body35="""
No description available
"""
)
spell_dict = dict(
entire="""
<!DOCTYPE html>
<html>
<head>
<style>
.gradient {
margin:10px 0px;
}
.name {
font-size:225%;
font-family:Georgia, serif;
font-variant:small-caps;
font-weight:bold;
color:#A73335;
}
.description {
font-style:italic;
}
.bold {
font-weight:bold;
}
.red {
color:#A73335;
}
table {
width:100%;
border:0px;
border-collapse:collapse;
color:#A73335;
}
th, td {
width:50px;
text-align:center;
}
.actions {
font-size:175%;
font-variant:small-caps;
margin:17px 0px 0px 0px;
}
.hr {
background: #A73335;
height:2px;
}
.attack_odd {
margin:10px 0px;
color: black;
}
.attack_even {
margin:10px 0px;
color: white;
}
.bolditalic {
font-weight:bold;
font-style:italic;
}
</style>
</head>
<body>
<div contenteditable="true" style="width:310px; font-family:Arial,Helvetica,sans-serif;font-size:17px;">
<div class="name"> $name </div>
<div class="description">$level $school</div>
<div class="gradient"><img scr="assets/linear_gradient.png;" /></div>
<br>
<div><span class="bold">Casting Time:</span><span> $time</span></div>
<div><span class="bold">Range:</span><span> $range</span></div>
<div><span class="bold">Component:</span><span> $components</span></div>
<div><span class="bold">Duration:</span><span> $duration</span></div>
<br>
<div><span class="bold">$classes</span></div>
<br>
<div><span>$text</span></div>
</div>
</body>
</html>
"""
)
monster_dict = dict(
first="""
<!DOCTYPE html>
<html>
<head>
<style>
.gradient {
margin:10px 0px;
}
.name {
font-size:225%;
font-family:Georgia, serif;
font-variant:small-caps;
font-weight:bold;
color:#A73335;
}
.description {
font-style:italic;
}
.bold {
font-weight:bold;
}
.red {
color:#A73335;
}
table {
width:100%;
border:0px;
border-collapse:collapse;
color:#A73335;
}
th, td {
width:50px;
text-align:center;
}
.actions {
font-size:175%;
font-variant:small-caps;
margin:17px 0px 0px 0px;
}
.hr {
background: #A73335;
height:2px;
}
.attack_odd {
margin:10px 0px;
color: black;
}
.attack_even {
margin:10px 0px;
color: white;
}
.bolditalic {
font-weight:bold;
font-style:italic;
}
</style>
</head>
<body>
<div contenteditable="true" style="width:310px; font-family:Arial,Helvetica,sans-serif;font-size:17px;">
<div class="name"> $name </div>
<div class="description">$size $type, $alignment</div>
<div class="gradient"><img scr="assets/linear_gradient.png;" /></div>
<div class="red">
<div ><span class="bold red">Armor Class</span><span> $armor_class </span></div>
<div><span class="bold red">Hit Points</span><span> $hit_points</span></div>
<div><span class="bold red">Speed</span><span> $speed</span></div>
</div>
<div class="gradient"><img scr="assets/linear_gradient.png;" /></div>
<table cellspacing = "0">
<tr><th>STR</th> <th>DEX</th><th>CON</th><th>INT</th><th>WIS</th><th>CHA</th></tr>
<tr><td style="padding: 0 10px;">$str ($str_mod)</td> <td style="padding: 0 10px;">$dex ($dex_mod)</td>
<td style="padding: 0 10px;">$con ($con_mod)</td><td style="padding: 0 10px;">$int ($int_mod)</td>
<td style="padding: 0 10px;">$wis ($wis_mod)</td><td style="padding: 0 10px;">$cha ($cha_mod)</td></tr>
</table>
<br>
""",
desc="""
<div><span class="bold">$name</span><span> $desc</span></div>
""",
cr="""
<div><span class="bold">Challenge Rating</span><span> $cr</span><span class="description"> ($xp XP)</span></div>
""",
gradient="""
<div class="gradient"><img scr="assets/linear_gradient.png;" /></div>
""",
special_abilities="""
<div><span class="bolditalic">$name</span><span> $desc</span></div>
""",
second="""
<div class="actions red">Actions</div>
<div class="gradient"><img scr="assets/linear_gradient.png;" /></div>
""",
action_odd="""
<div class="hr"></div>
<div class="attack_even"><span class="bolditalic">$name</span><span> $text</span></div>
""",
action_even="""
<div class="attack_odd"><span class="bolditalic">$name</span><span> $text</span></div>
""",
legendary_header="""
<div class="actions red">Legendary Actions</div>
<div class="gradient"><img scr="assets/linear_gradient.png;" /></div>
""",
rest="""
</div>
</body>
</html>
""")
|
"""
Eugene
"""
__all__ = ["Config", "Primatives", "Node", "Tree", "Individual", "Population", "Util"]
__version__ = '0.1.1'
__date__ = '2015-08-07 07:09:00 -0700'
__author__ = 'tmthydvnprt'
__status__ = 'development'
__website__ = 'https://github.com/tmthydvnprt/eugene'
__email__ = '[email protected]'
__maintainer__ = 'tmthydvnprt'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, eugene'
__credits__ = ''
"""
Eugene
Operators:
===========
Unary:
-------
o.abs(a) - Same as abs(a).
o.inv(a) - Same as ~a.
o.neg(a) - Same as -a.
o.pos(a) - Same as +a.
Binary:
--------
o.or_(a, b) - Same as a | b.
o.add(a, b) - Same as a + b.
o.and_(a, b) - Same as a & b.
o.div(a, b) - Same as a / b when __future__.division is not in effect.
o.eq(a, b) - Same as a==b.
o.floordiv(a, b) - Same as a // b.
o.ge(a, b) - Same as a>=b.
o.gt(a, b) - Same as a>b.
o.le(a, b) - Same as a<=b.
o.lt(a, b) - Same as a<b.
o.mod(a, b) - Same as a % b.
o.mul(a, b) - Same as a * b.
o.ne(a, b) - Same as a!=b.
o.pow(a, b) - Same as a ** b.
o.sub(a, b) - Same as a - b.
o.truediv(a, b) - Same as a / b when __future__.division is in effect.
o.xor(a, b) - Same as a ^ b.
Functions:
===========
Unary:
-------
np.acos(x) - Return the arc cosine (measured in radians) of x.
np.acosh(x) - Return the hyperbolic arc cosine (measured in radians) of x.
np.asin(x) - Return the arc sine (measured in radians) of x.
np.asinh(x) - Return the hyperbolic arc sine (measured in radians) of x.
np.atan(x) - Return the arc tangent (measured in radians) of x.
np.atanh(x) - Return the hyperbolic arc tangent (measured in radians) of x.
np.ceil(x) - Return the ceiling of x as a float. This is the smallest integral value >= x.
np.cos(x) - Return the cosine of x (measured in radians).
np.cosh(x) - Return the hyperbolic cosine of x.
np.degrees(x) - Convert angle x from radians to degrees.
sp.erf(x) - Error function at x.
sp.erfc(x) - Complementary error function at x.
np.exp(x) - Return e raised to the power of x.
np.expm1(x) - Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
np.fabs(x) - Return the absolute value of the float x.
sm.factorial(x) - Find x!. Raise a ValueError if x is negative or non-integral. -> Integral
np.floor(x) - Return the floor of x as a float. This is the largest integral value <= x.
sp.gamma(x) - Gamma function at x.
np.isinf(x) - Check if float x is infinite (positive or negative). -> bool
np.isnan(x) - Check if float x is not a number (NaN). -> bool
sp.lgamma(x) - Natural logarithm of absolute value of Gamma function at x.
np.log10(x) - Return the base 10 logarithm of x.
np.log2(x) - Return the base 2 logarithm of x.
np.log1p(x) - Return the natural logarithm of 1+x (base e). The result is computed in a way which is accurate for x near zero.
np.log(x) - Return the natural logarithm of x.
np.radians(x) - Convert angle x from degrees to radians.
np.sin(x) - Return the sine of x (measured in radians).
np.sinh(x) - Return the hyperbolic sine of x.
np.sqrt(x) - Return the square root of x.
np.tan(x) - Return the tangent of x (measured in radians).
np.tanh(x) - Return the hyperbolic tangent of x.
np.trunc(x:Real) - Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method. -> Integral
Binary:
--------
np.atan2(y, x) - Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered.
np.copysign(x, y) - Return x with the sign of y.
np.fmod(x, y) - Return fmod(x, y), according to platform C. x % y may differ.
np.hypot(x, y) - Return the Euclidean distance, sqrt(x*x + y*y).
np.ldexp(x, i) - Return x * (2**i).
np.pow(x, y) - Return x**y (x to the power of y).
np.round(x[, y]) - Return the floating point value x rounded to y digits after the decimal point.
N-ary:
--------
np.max(x, y, ...) - Return the largest item in an iterable or the largest of two or more arguments.
np.min(x, y, ...) - Return the smallest item in an iterable or the smallest of two or more arguments.
np.fsum([x,y,...]) - Return an accurate floating point sum of values in the iterable.
np.prod([x,y,...]) - Return an accurate floating point product of values in the iterable.
Constants:
===========
np.p - The mathematical constant pi = 3.141592..., to available precision.
np.e - The mathematical constant e = 2.718281..., to available precision.
Ephemeral Variables : - once created stay constant, only can be used during initialization or mutation
=====================
r.random() - Returns x in the interval [0, 1).
r.randint(a, b) - Returns integer x in range [a, b].
r.uniform(a, b) - Returns number x in the range [a, b) or [a, b] depending on rounding.
r.normalvariate(mu, sigma) - Returns number x from Normal distribution. mu is the mean, and sigma is the standard deviation.
Variables:
===========
a, b, c, ..., x, y, z - whatever you need, define in `eugene.Config.VAR`
To add:
========
pd.shift()
removed:
=========
o.not_() - can't operate on array, but o.inv() can & produces the same result
"""
|
#About using of list
# 列表的定义 有序的 可以承载各种数据(变量)类型
# 格式: 列表名 = [元素1, 元素2, 元素n]
# my_list = [1, 3.14, "hello", True]
# print(my_list)
# 定义一个空的列表
# my_list1 = []
# <class 'list'>
# print(type(my_list1))
# my_list2 = list()
# 如果看是否是一个空列表呢?
# l = len(my_list2)
# print(l)
# 定义一个列表
# my_list = ["a", "b", "c", "d"]
my_list = list("abcde")
# print(my_list)
# for循环
# for value in my_list:
# print(value)
# while循环
# 定义一个变量 记录列表中的下标索引
# i = 0
# while i < len(my_list):
# # 通过下标获取对应的元素
# value = my_list[i]
# print(value)
# i += 1
# 列表添加元素("增"append, extend, insert)
# 定义一个列表 -> 列表是可变的
my_list = [1, 2, 3]
# append -> 追加
# my_list.append([2, 4, 6])
# print(my_list)
# extend, 可迭代对象
# my_list.extend("abcd")
# print(my_list)
# insert
# my_list.insert(100, [1, 2])
# print(my_list)
# 列表越界
# value = my_list[20]
# print(value)
# 字符串越界
# s = "abc"
# value = s[100]
# print(value)
|
#!/usr/bin/python3
"""
__slots__魔法
Python是一门动态语言
动态语言允许我们在程序运行时给对象绑定新的属性或方法,当然也可以对已经绑定的属性和方法进行解绑定。
如果我们需要限定自定义类型的对象只能绑定某些属性,可以通过在类中定义__slots__变量来进行限定。
需要注意的是__slots__的限定只对当前类的对象生效,对子类并不起任何作用。
version: 0.1
author: icro
"""
class Person(object):
# 限定Person对象只能绑定_name, _age和_gender属性
__slots__ = ("_name", "_age", "_gender")
def __init__(self, name, age):
self._name = name
self._age = age
# 访问器 - getter方法
@property
def name(self):
return self._name
@property
def age(self):
return self._age
# 修改器 - setter方法
@age.setter
def age(self, age):
self._age = age
def watch_tv(self):
if self.age < 18:
print("%s只能看动画片" % self.name)
else:
print("%s可以看美国大片" % self.name)
def main():
person = Person("icro", 12)
person.watch_tv()
person.age = 22
person._gender = "男"
person.watch_tv()
# AttributeError: 'Person' object has no attribute '_is_gay'
# person._is_gay = True
if __name__ == "__main__":
main()
|
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def glog():
http_archive(
name="glog" ,
sha256="bae42ec37b50e156071f5b92d2ff09aa5ece56fd8c58d2175fc1ffea85137664" ,
strip_prefix="glog-0a2e5931bd5ff22fd3bf8999eb8ce776f159cda6" ,
urls = [
"https://github.com/Unilang/glog/archive/0a2e5931bd5ff22fd3bf8999eb8ce776f159cda6.tar.gz",
], repo_mapping = {
"@com_github_gflags_gflags" : "@gflags",
},
)
|
p = float(input('digite o preço normal'))
o = int(input('Digite\n [1] para dinheiro ou cheque\n [2] para a vista\n [3] em 2x\n [4] em 3x '))
if o == 1:
print('o preço com desconto será de R${:.2f}' .format(p-p*.1))
elif o == 2:
print ('o preço com desconto será de R${:.2f}' .format (pp*.05))
elif o == 3:
print ('o preço será de R${:.2f}' .format (p))
elif o == 4:
print ('o preço com desconto será de R${:.2f}' .format (p+p*.2))
else:
print('forma de pagamento invalida')
|
'''
Created on 14.10.2019
@author: JM
'''
class TMC2130_register_variant:
" ===== TMC2130 register variants ===== "
"..."
|
condicao = str(input('Deseja iniciar programa [S/N]? ')).upper()
ac = 0
contador = 0
media = 0
maior = menor = 0
while condicao != 'N':
if condicao == 'S':
n = int(input('Digite um número inteiro: '))
ac = ac + n
contador = contador + 1
media = ac / contador
condicao = str(input('Deseja continuar [S/N]? ')).upper()
if contador == 1:
maior = menor = n
else:
if n > maior:
maior = n
if n < menor:
menor = n
else:
condicao = str(input('Deseja continuar [S/N]? ')).upper()
print(f'Foram lidos {contador} números. A soma entre eles é de {ac}. A média é {media:.2f}')
print(f'Maior: {maior}')
print(f'Menor: {menor}')
|
# Rainbow Grid handgezeichnet
add_library('handy')
def setup():
global h
h = HandyRenderer(this)
size(600, 600)
this.surface.setTitle("Rainbow Grid Handy")
rectMode(CENTER)
h.setRoughness(1)
h.setFillWeight(0.9)
h.setFillGap(0.9)
def draw():
colorMode(RGB)
background(235, 215, 182)
colorMode(HSB)
translate(12, 12)
for x in range(20):
for y in range(20):
d = dist(30*x, 30*y, mouseX, mouseY)
fill(0.5*d, 255, 255)
h.rect(x*30 + 3, y*30 + 3, 24, 24)
|
set_name(0x800A0CD8, "VID_OpenModule__Fv", SN_NOWARN)
set_name(0x800A0D98, "InitScreens__Fv", SN_NOWARN)
set_name(0x800A0E88, "MEM_SetupMem__Fv", SN_NOWARN)
set_name(0x800A0EB4, "SetupWorkRam__Fv", SN_NOWARN)
set_name(0x800A0F44, "SYSI_Init__Fv", SN_NOWARN)
set_name(0x800A1050, "GM_Open__Fv", SN_NOWARN)
set_name(0x800A1074, "PA_Open__Fv", SN_NOWARN)
set_name(0x800A10AC, "PAD_Open__Fv", SN_NOWARN)
set_name(0x800A10F0, "OVR_Open__Fv", SN_NOWARN)
set_name(0x800A1110, "SCR_Open__Fv", SN_NOWARN)
set_name(0x800A1140, "DEC_Open__Fv", SN_NOWARN)
set_name(0x800A13B4, "GetVersionString__FPc", SN_NOWARN)
set_name(0x800A1488, "GetWord__FPc", SN_NOWARN)
set_name(0x800A1164, "StrDate", SN_NOWARN)
set_name(0x800A1170, "StrTime", SN_NOWARN)
set_name(0x800A117C, "Words", SN_NOWARN)
set_name(0x800A1354, "MonDays", SN_NOWARN)
|
__title__ = "Django REST framework Caching Tools"
__version__ = "1.0.3"
__author__ = "Vincent Wantchalk"
__license__ = "MIT"
__copyright__ = "Copyright 2011-2019 xsudo.com"
# Version synonym
VERSION = __version__
# Header encoding (see RFC5987)
HTTP_HEADER_ENCODING = "iso-8859-1"
default_app_config = "drf_cache.apps.DOTConfig"
|
# Generate input data for EM 514, Homework Problem 8
def DefineInputs():
area = 200.0e-6
nodes = [{'x': 0.0e0, 'y': 0.0e0, 'z': 0.0e0, 'xflag': 'd', 'xbcval': 0.0, 'yflag': 'd', 'ybcval': 0.0e0, 'zflag': 'd', 'zbcval': 0.0e0}]
nodes.append({'x': 3.0e0, 'y': 0.0e0, 'z': 0.0e0, 'xflag': 'f', 'xbcval': 0.0, 'yflag': 'f', 'ybcval': 0.0e0, 'zflag': 'd', 'zbcval': 0.0e0})
nodes.append({'x': 6.0e0, 'y': 0.0e0, 'z': 0.0e0, 'xflag': 'f', 'xbcval': 0.0, 'yflag': 'f', 'ybcval': 0.0e0, 'zflag': 'd', 'zbcval': 0.0e0})
nodes.append({'x': 3.0e0, 'y': -4.0e0, 'z': 0.0e0, 'xflag': 'f', 'xbcval': 0.0, 'yflag': 'f', 'ybcval': -9.0e3, 'zflag': 'd', 'zbcval': 0.0e0})
nodes.append({'x': 6.0e0, 'y': -4.0e0, 'z': 0.0e0, 'xflag': 'f', 'xbcval': 0.0, 'yflag': 'f', 'ybcval': -15.0e3, 'zflag': 'd', 'zbcval': 0.0e0})
nodes.append({'x': 9.0e0, 'y': -4.0e0, 'z': 0.0e0, 'xflag': 'f', 'xbcval': 0.0, 'yflag': 'd', 'ybcval': 0.0e0, 'zflag': 'd', 'zbcval': 0.0e0})
members = [{'start': 0, 'end': 1, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6}]
members.append({'start': 1, 'end': 2, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6})
members.append({'start': 0, 'end': 3, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6})
members.append({'start': 1, 'end': 3, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6})
members.append({'start': 2, 'end': 3, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6})
members.append({'start': 3, 'end': 4, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6})
members.append({'start': 2, 'end': 4, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6})
members.append({'start': 2, 'end': 5, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6})
members.append({'start': 4, 'end': 5, 'E': 200.0e9, 'A': area, 'sigma_yield': 36.0e6, 'sigma_ult': 66.0e6})
return nodes, members
|
n = int(input('Valor do produto: '))
val = (n*5) / 100
res = val
print('O VALOR FINAL COM 5% DE DESCONTO VAI SER ${}:'.format(val))
|
quarter = (dta.inspection_date.dt.month - 1) // 3
quarter_size = dta.groupby((quarter, violation_num)).size()
axes = quarter_size.unstack(level=0).plot.bar(
figsize=(14, 8),
)
|
# ########################1. 基本使用 ###########################
'''
# ##### 基本写法
class SuperBase:
def f3(self):
print('f3')
class Base(SuperBase): # 父类,基类
def f2(self):
print('f2')
class Foo(Base): # 子类,派生类
def f1(self):
print('f1')
obj = Foo()
obj.f1()
obj.f2()
obj.f3()
# 原则:先在自己类中找,没有就去父类
'''
# ##### 为何有继承? 为了提高代码重用性
"""
class Base:
def f1(self):
pass
class Foo(Base):
def f2(self):
pass
class Bar(Base):
def f3(self):
pass
"""
# ########################2. 多继承 ###########################
'''
class Base1:
def show(self):
print('Base1.show')
class Base2:
def show(self):
print('Base2.show')
class Foo(Base1,Base2):
pass
obj = Foo()
obj.show()
# 左边更亲
'''
# ############################### 练习题 #############################
###### 习题1
# class Base:
# def f1(self):
# print('base.f1')
#
# class Foo(Base):
# def f2(self):
# print('foo.f2')
#
# # 1. 是否执行
# obj = Foo()
# obj.f2()
# obj.f1()
#
# # 2. 是否执行
# obj = Base()
# obj.f1()
# obj.f2() # 错
##### 习题2:
# class Base:
# def f1(self):
# print('base.f1')
#
# class Foo(Base):
# def f3(self):
# print('foo.f3')
#
# def f2(self):
# print('foo.f2')
# self.f3() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
#
# obj = Foo()
# obj.f2() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
##### 习题3:
# class Base:
# def f1(self):
# print('base.f1')
#
# def f3(self):
# print('foo.f3')
#
# class Foo(Base):
#
# def f2(self):
# print('foo.f2')
# self.f3() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
#
# obj = Foo()
# obj.f2() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
##### 习题4:
# class Base:
# def f1(self):
# print('base.f1')
#
# def f3(self):
# self.f1() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
# print('foo.f3')
#
# class Foo(Base):
# def f2(self):
# print('foo.f2')
# self.f3() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
#
# obj = Foo()
# obj.f2() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
##### 习题5:
# class Base:
# def f1(self):
# print('base.f1')
#
# def f3(self):
# self.f1() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
# print('base.f3')
#
# class Foo(Base):
# def f1(self):
# print('foo.f1')
#
# def f2(self):
# print('foo.f2')
# self.f3() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
#
# obj = Foo()
# obj.f2() # obj是哪一个类(Foo),那么执行方法时,就从该类开始找.
# obj2 = Base()
# obj2.f3()
# 总结: self是哪个类的对象,那么就从该类开始找(自己没有就找父类)
##### 习题6:
# class Base1:
# def f1(self):
# print('base1.1')
# def f2(self):
# print('base1.f2')
#
# class Base2:
# def f1(self):
# print('base2.f1')
# def f2(self):
# print('base2.f2')
# def f3(self):
# print('base2.f3')
# self.f1()
#
# class Foo(Base1, Base2):
#
# def f0(self):
# print('foo.f0')
# self.f3()
# # # 1. 多继承先找左边
# # # 2. self到底是谁,self是哪个类的对象,那么就从该类开始找(自己没有就找父类)
# obj = Foo()
# obj.f0()
|
# pin numbers
# http://micropython-on-wemos-d1-mini.readthedocs.io/en/latest/setup.html
# https://forum.micropython.org/viewtopic.php?t=2503
D0 = 16 # wake
D5 = 14 # sck
D6 = 12 # miso
D7 = 13 # mosi
D8 = 15 # cs PULL-DOWN 10k
D4 = 2 # boot PULL-UP 10k
D3 = 0 # flash PULL-UP 10k
D2 = 4 # sda
D1 = 5 # scl
RX = 3 # rx
TX = 1 # tx
# note: D4 is also used to control the builtin blue led, but it's reversed
# (when D4 is 1, the led is off)
LED = D4
|
CENTRALIZED = False
EXAMPLE_PAIR = "ZRX-WETH"
USE_ETHEREUM_WALLET = True
FEE_TYPE = "FlatFee"
FEE_TOKEN = "ETH"
DEFAULT_FEES = [0, 0.00001]
|
'''
154. Find Minimum in Rotated Sorted Array II
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
similar problem: "153. Find Minimum in Rotated Sorted Array"
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
'''
# correct:
class Solution:
def findMin(self, nums: List[int]) -> int:
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] > nums[hi]:
lo = mid + 1
else:
hi = mid if nums[hi] != nums[mid] else hi - 1
return nums[lo]
# reference:
# https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/48908/Clean-python-solution
'''
wrong:
class Solution:
def findMin(self, nums: List[int]) -> int:
lo, hi = 0, len(nums)-1
while lo < hi:
mid = lo + (hi - lo) // 2
# if nums[mid] < nums[hi]: wrong! should use >
hi = mid if nums[hi] != nums[mid] else hi -1
else:
lo = mid + 1
return nums[lo]
'''
|
# coding: utf8
"""
题目链接: https://leetcode.com/problems/count-complete-tree-nodes/description.
题目描述:
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last
level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
# 满二叉树, 直接返回
# 不然, leetcode大数据样例通不过测试
lh = self.left_tree_height(root)
rh = self.right_tree_height(root)
if lh == rh:
return pow(2, lh) - 1
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
def left_tree_height(self, root):
if not root:
return 0
return 1 + self.left_tree_height(root.left)
def right_tree_height(self, root):
if not root:
return 0
return 1 + self.right_tree_height(root.right)
|
def self_powers(final:int):
sum_pows = 0
for integer in range(1, final + 1):
power = 1
for _ in range(integer):
power = (power * integer) % (10**11)
sum_pows += power
return sum_pows % (10 ** 10)
if __name__ == "__main__":
print(self_powers(1000))
|
SP500 = {'A.O. Smith Corp': 'AOS',
'Abbott Laboratories': 'ABT',
'AbbVie Inc.': 'ABBV',
'Accenture plc': 'ACN',
'Activision Blizzard': 'ATVI',
'Acuity Brands Inc': 'AYI',
'Adobe Systems Inc': 'ADBE',
'Advance Auto Parts': 'AAP',
'Advanced Micro Devices Inc': 'AMD',
'AES Corp': 'AES',
'Aetna Inc': 'AET',
'Affiliated Managers Group Inc': 'AMG',
'AFLAC Inc': 'AFL',
'Agilent Technologies Inc': 'A',
'Air Products & Chemicals Inc': 'APD',
'Akamai Technologies Inc': 'AKAM',
'Alaska Air Group Inc': 'ALK',
'Albemarle Corp': 'ALB',
'Alexandria Real Estate Equities Inc': 'ARE',
'Alexion Pharmaceuticals': 'ALXN',
'Align Technology': 'ALGN',
'Allegion': 'ALLE',
'Alliance Data Systems': 'ADS',
'Alliant Energy Corp': 'LNT',
'Allstate Corp': 'ALL',
'Alphabet Inc Class A': 'GOOGL',
'Alphabet Inc Class C': 'GOOG',
'Altria Group Inc': 'MO',
'Amazon.com Inc.': 'AMZN',
'Ameren Corp': 'AEE',
'American Airlines Group': 'AAL',
'American Electric Power': 'AEP',
'American Express Co': 'AXP',
'American International Group Inc.': 'AIG',
'American Tower Corp A': 'AMT',
'American Water Works Company Inc': 'AWK',
'Ameriprise Financial': 'AMP',
'AmerisourceBergen Corp': 'ABC',
'AMETEK Inc.': 'AME',
'Amgen Inc.': 'AMGN',
'Amphenol Corp': 'APH',
'Andeavor': 'ANDV',
'ANSYS': 'ANSS',
'Anthem Inc.': 'ANTM',
'Aon plc': 'AON',
'Apache Corporation': 'APA',
'Apartment Investment & Management': 'AIV',
'Apple Inc.': 'AAPL',
'Applied Materials Inc.': 'AMAT',
'Aptiv Plc': 'APTV',
'Archer-Daniels-Midland Co': 'ADM',
'Arconic Inc.': 'ARNC',
'Arthur J. Gallagher & Co.': 'AJG',
'Assurant Inc.': 'AIZ',
'AT&T Inc.': 'T',
'Autodesk Inc.': 'ADSK',
'Automatic Data Processing': 'ADP',
'AutoZone Inc': 'AZO',
'AvalonBay Communities Inc.': 'AVB',
'Avery Dennison Corp': 'AVY',
'Baker Hughes a GE Company': 'BKR',
'Ball Corp': 'BLL',
'Bank of America Corp': 'BAC',
'Baxter International Inc.': 'BAX',
'Becton Dickinson': 'BDX',
'Berkshire Hathaway': 'BRK.A',
'Best Buy Co. Inc.': 'BBY',
'Biogen Inc.': 'BIIB',
'BlackRock': 'BLK',
'Block H&R': 'HRB',
'Boeing Company': 'BA',
'Booking Holdings Inc': 'BKNG',
'BorgWarner': 'BWA',
'Boston Properties': 'BXP',
'Boston Scientific': 'BSX',
'Brighthouse Financial Inc': 'BHF',
'Bristol-Myers Squibb': 'BMY',
'Broadcom': 'AVGO',
'Brown-Forman Corp.': 'BF.B',
'C. H. Robinson Worldwide': 'CHRW',
'CA Inc.': 'CA',
'Cabot Oil & Gas': 'COG',
'Cadence Design Systems': 'CDNS',
'Campbell Soup': 'CPB',
'Capital One Financial': 'COF',
'Cardinal Health Inc.': 'CAH',
'Carmax Inc': 'KMX',
'Carnival Corp.': 'CCL',
'Caterpillar Inc.': 'CAT',
'Cboe Global Markets': 'CBOE',
'CBRE Group': 'CBRE',
'Centene Corporation': 'CNC',
'CenterPoint Energy': 'CNP',
'CenturyLink Inc': 'CTL',
'Cerner': 'CERN',
'CF Industries Holdings Inc': 'CF',
'Charles Schwab Corporation': 'SCHW',
'Charter Communications': 'CHTR',
'Chevron Corp.': 'CVX',
'Chipotle Mexican Grill': 'CMG',
'Chubb Limited': 'CB',
'Church & Dwight': 'CHD',
'CIGNA Corp.': 'CI',
'Cimarex Energy': 'XEC',
'Cincinnati Financial': 'CINF',
'Cintas Corporation': 'CTAS',
'Cisco Systems': 'CSCO',
'Citigroup Inc.': 'C',
'Citizens Financial Group': 'CFG',
'Citrix Systems': 'CTXS',
'CME Group Inc.': 'CME',
'CMS Energy': 'CMS',
'Coca-Cola Company (The)': 'KO',
'Cognizant Technology Solutions': 'CTSH',
'Colgate-Palmolive': 'CL',
'Comcast Corp.': 'CMCSA',
'Comerica Inc.': 'CMA',
'Conagra Brands': 'CAG',
'Concho Resources': 'CXO',
'ConocoPhillips': 'COP',
'Consolidated Edison': 'ED',
'Constellation Brands': 'STZ',
'Corning Inc.': 'GLW',
'Costco Wholesale Corp.': 'COST',
'Coty Inc': 'COTY',
'Crown Castle International Corp.': 'CCI',
'CSRA Inc.': 'CSRA',
'CSX Corp.': 'CSX',
'Cummins Inc.': 'CMI',
'CVS Health': 'CVS',
'D. R. Horton': 'DHI',
'Danaher Corp.': 'DHR',
'Darden Restaurants': 'DRI',
'DaVita Inc.': 'DVA',
'Deere & Co.': 'DE',
'Delta Air Lines Inc.': 'DAL',
'Dentsply Sirona': 'XRAY',
'Devon Energy Corp.': 'DVN',
'Digital Realty Trust Inc': 'DLR',
'Discover Financial Services': 'DFS',
'Discovery Inc. Class A': 'DISCA',
'Discovery Inc. Class C': 'DISCK',
'Dish Network': 'DISH',
'Dollar General': 'DG',
'Dollar Tree': 'DLTR',
'Dominion Energy': 'D',
'Dover Corp.': 'DOV',
'DTE Energy Co.': 'DTE',
'Duke Energy': 'DUK',
'Duke Realty Corp': 'DRE',
'DXC Technology': 'DXC',
'E*Trade': 'ETFC',
'Eastman Chemical': 'EMN',
'Eaton Corporation': 'ETN',
'eBay Inc.': 'EBAY',
'Ecolab Inc.': 'ECL',
'Edison International': 'EIX',
'Edwards Lifesciences': 'EW',
'Electronic Arts': 'EA',
'Emerson Electric Company': 'EMR',
'Entergy Corp.': 'ETR',
'Envision Healthcare': 'EVHC',
'EOG Resources': 'EOG',
'EQT Corporation': 'EQT',
'Equifax Inc.': 'EFX',
'Equinix': 'EQIX',
'Equity Residential': 'EQR',
'Essex Property Trust Inc.': 'ESS',
'Estee Lauder Cos.': 'EL',
'Everest Re Group Ltd.': 'RE',
'Eversource Energy': 'ES',
'Exelon Corp.': 'EXC',
'Expedia Inc.': 'EXPE',
'Expeditors International': 'EXPD',
'Express Scripts': 'ESRX',
'Extra Space Storage': 'EXR',
'Exxon Mobil Corp.': 'XOM',
'F5 Networks': 'FFIV',
'Facebook Inc.': 'FB',
'Fastenal Co': 'FAST',
'Federal Realty Investment Trust': 'FRT',
'FedEx Corporation': 'FDX',
'Fidelity National Information Services': 'FIS',
'Fifth Third Bancorp': 'FITB',
'FirstEnergy Corp': 'FE',
'Fiserv Inc': 'FISV',
'FLIR Systems': 'FLIR',
'Flowserve Corporation': 'FLS',
'Fluor Corp.': 'FLR',
'FMC Corporation': 'FMC',
'Foot Locker Inc': 'FL',
'Ford Motor': 'F',
'Fortive Corp': 'FTV',
'Fortune Brands Home & Security': 'FBHS',
'Franklin Resources': 'BEN',
'Freeport-McMoRan Inc.': 'FCX',
'Gap Inc.': 'GPS',
'Garmin Ltd.': 'GRMN',
'Gartner Inc': 'IT',
'General Dynamics': 'GD',
'General Electric': 'GE',
'General Growth Properties Inc.': 'GGP',
'General Mills': 'GIS',
'General Motors': 'GM',
'Genuine Parts': 'GPC',
'Gilead Sciences': 'GILD',
'Global Payments Inc.': 'GPN',
'Goldman Sachs Group': 'GS',
'Goodyear Tire & Rubber': 'GT',
'Grainger (W.W.) Inc.': 'GWW',
'Halliburton Co.': 'HAL',
'Hanesbrands Inc': 'HBI',
'Harley-Davidson': 'HOG',
'Hartford Financial Svc.Gp.': 'HIG',
'Hasbro Inc.': 'HAS',
'HCA Holdings': 'HCA',
'Helmerich & Payne': 'HP',
'Henry Schein': 'HSIC',
'Hess Corporation': 'HES',
'Hewlett Packard Enterprise': 'HPE',
'Hilton Worldwide Holdings Inc': 'HLT',
'Hologic': 'HOLX',
'Home Depot': 'HD',
'Honeywell International Inc.': 'HON',
'Hormel Foods Corp.': 'HRL',
'Host Hotels & Resorts': 'HST',
'HP Inc.': 'HPQ',
'Humana Inc.': 'HUM',
'Huntington Bancshares': 'HBAN',
'Huntington Ingalls Industries': 'HII',
'IDEXX Laboratories': 'IDXX',
'IHS Markit Ltd.': 'INFO',
'Illinois Tool Works': 'ITW',
'Illumina Inc': 'ILMN',
'Incyte': 'INCY',
'Ingersoll-Rand PLC': 'IR',
'Intel Corp.': 'INTC',
'Intercontinental Exchange': 'ICE',
'International Business Machines': 'IBM',
'International Paper': 'IP',
'Interpublic Group': 'IPG',
'Intl Flavors & Fragrances': 'IFF',
'Intuit Inc.': 'INTU',
'Intuitive Surgical Inc.': 'ISRG',
'Invesco Ltd.': 'IVZ',
'IPG Photonics Corp.': 'IPGP',
'IQVIA Holdings Inc.': 'IQV',
'Iron Mountain Incorporated': 'IRM',
'J. B. Hunt Transport Services': 'JBHT',
'Jacobs Engineering Group': 'J',
'JM Smucker': 'SJM',
'Johnson & Johnson': 'JNJ',
'Johnson Controls International': 'JCI',
'JPMorgan Chase & Co.': 'JPM',
'Juniper Networks': 'JNPR',
'Kansas City Southern': 'KSU',
'Kellogg Co.': 'K',
'KeyCorp': 'KEY',
'Kimberly-Clark': 'KMB',
'Kimco Realty': 'KIM',
'Kinder Morgan': 'KMI',
'KLA-Tencor Corp.': 'KLAC',
'Kohls Corp.': 'KSS',
'Kraft Heinz Co': 'KHC',
'Kroger Co.': 'KR',
'L Brands Inc.': 'LB',
'Laboratory Corp. of America Holding': 'LH',
'Lam Research': 'LRCX',
'Leggett & Platt': 'LEG',
'Lennar Corp.': 'LEN',
'Lilly (Eli) & Co.': 'LLY',
'Lincoln National': 'LNC',
'LKQ Corporation': 'LKQ',
'Lockheed Martin Corp.': 'LMT',
'Loews Corp.': 'L',
'Lowes Cos.': 'LOW',
'LyondellBasell': 'LYB',
'M&T Bank Corp.': 'MTB',
'Macerich': 'MAC',
'Macys Inc.': 'M',
'Marathon Oil Corp.': 'MRO',
'Marathon Petroleum': 'MPC',
'Marriott International.': 'MAR',
'Marsh & McLennan': 'MMC',
'Martin Marietta Materials': 'MLM',
'Masco Corp.': 'MAS',
'Mastercard Inc.': 'MA',
'Mattel Inc.': 'MAT',
'McCormick & Co.': 'MKC',
'McDonalds Corp.': 'MCD',
'McKesson Corp.': 'MCK',
'Medtronic plc': 'MDT',
'Merck & Co.': 'MRK',
'MetLife Inc.': 'MET',
'Mettler Toledo': 'MTD',
'MGM Resorts International': 'MGM',
'Microchip Technology': 'MCHP',
'Micron Technology': 'MU',
'Microsoft Corp.': 'MSFT',
'Mid-America Apartments': 'MAA',
'Mohawk Industries': 'MHK',
'Molson Coors Brewing Company': 'TAP',
'Mondelez International': 'MDLZ',
'Monsanto Co.': 'MON',
'Monster Beverage': 'MNST',
'Moodys Corp': 'MCO',
'Morgan Stanley': 'MS',
'Motorola Solutions Inc.': 'MSI',
'Mylan N.V.': 'MYL',
'Nasdaq Inc.': 'NDAQ',
'National Oilwell Varco Inc.': 'NOV',
'Navient': 'NAVI',
'Nektar Therapeutics': 'NKTR',
'NetApp': 'NTAP',
'Netflix Inc.': 'NFLX',
'Newell Brands': 'NWL',
'Newmont Mining Corporation': 'NEM',
'News Corp. Class A': 'NWSA',
'News Corp. Class B': 'NWS',
'NextEra Energy': 'NEE',
'Nielsen Holdings': 'NLSN',
'Nike': 'NKE',
'NiSource Inc.': 'NI',
'Noble Energy Inc': 'NBL',
'Nordstrom': 'JWN',
'Norfolk Southern Corp.': 'NSC',
'Northern Trust Corp.': 'NTRS',
'Northrop Grumman Corp.': 'NOC',
'Norwegian Cruise Line': 'NCLH',
'NRG Energy': 'NRG',
'Nucor Corp.': 'NUE',
'Nvidia Corporation': 'NVDA',
'OReilly Automotive': 'ORLY',
'Occidental Petroleum': 'OXY',
'Omnicom Group': 'OMC',
'ONEOK': 'OKE',
'Oracle Corp.': 'ORCL',
'PACCAR Inc.': 'PCAR',
'Packaging Corporation of America': 'PKG',
'Parker-Hannifin': 'PH',
'Paychex Inc.': 'PAYX',
'PayPal': 'PYPL',
'Pentair Ltd.': 'PNR',
'Peoples United Financial': 'PBCT',
'PepsiCo Inc.': 'PEP',
'PerkinElmer': 'PKI',
'Perrigo': 'PRGO',
'Pfizer Inc.': 'PFE',
'PG&E Corp.': 'PCG',
'Philip Morris International': 'PM',
'Phillips 66': 'PSX',
'Pinnacle West Capital': 'PNW',
'Pioneer Natural Resources': 'PXD',
'PNC Financial Services': 'PNC',
'Polo Ralph Lauren Corp.': 'RL',
'PPG Industries': 'PPG',
'PPL Corp.': 'PPL',
'Principal Financial Group': 'PFG',
'Procter & Gamble': 'PG',
'Progressive Corp.': 'PGR',
'Prologis': 'PLD',
'Prudential Financial': 'PRU',
'Public Serv. Enterprise Inc.': 'PEG',
'Public Storage': 'PSA',
'Pulte Homes Inc.': 'PHM',
'PVH Corp.': 'PVH',
'Qorvo': 'QRVO',
'QUALCOMM Inc.': 'QCOM',
'Quanta Services Inc.': 'PWR',
'Quest Diagnostics': 'DGX',
'Range Resources Corp.': 'RRC',
'Raymond James Financial Inc.': 'RJF',
'Realty Income Corporation': 'O',
'Regency Centers Corporation': 'REG',
'Regeneron': 'REGN',
'Regions Financial Corp.': 'RF',
'Republic Services Inc': 'RSG',
'ResMed': 'RMD',
'Robert Half International': 'RHI',
'Rockwell Automation Inc.': 'ROK',
'Rockwell Collins': 'COL',
'Roper Technologies': 'ROP',
'Ross Stores': 'ROST',
'Royal Caribbean Cruises Ltd': 'RCL',
'S&P Global Inc.': 'SPGI',
'Salesforce.com': 'CRM',
'SBA Communications': 'SBAC',
'SCANA Corp': 'SCG',
'Schlumberger Ltd.': 'SLB',
'Seagate Technology': 'STX',
'Sealed Air': 'SEE',
'Sempra Energy': 'SRE',
'Sherwin-Williams': 'SHW',
'Simon Property Group Inc': 'SPG',
'Skyworks Solutions': 'SWKS',
'SL Green Realty': 'SLG',
'Snap-On Inc.': 'SNA',
'Southern Co.': 'SO',
'Southwest Airlines': 'LUV',
'Stanley Black & Decker': 'SWK',
'Starbucks Corp.': 'SBUX',
'State Street Corp.': 'STT',
'Stericycle Inc': 'SRCL',
'Stryker Corp.': 'SYK',
'SVB Financial': 'SIVB',
'Synchrony Financial': 'SYF',
'Synopsys Inc.': 'SNPS',
'Sysco Corp.': 'SYY',
'T. Rowe Price Group': 'TROW',
'Take-Two Interactive': 'TTWO',
'Tapestry Inc.': 'TPR',
'Target Corp.': 'TGT',
'TE Connectivity Ltd.': 'TEL',
'TechnipFMC': 'FTI',
'Texas Instruments': 'TXN',
'Textron Inc.': 'TXT',
'The Bank of New York Mellon Corp.': 'BK',
'The Clorox Company': 'CLX',
'The Cooper Companies': 'COO',
'The Hershey Company': 'HSY',
'The Mosaic Company': 'MOS',
'The Travelers Companies Inc.': 'TRV',
'The Walt Disney Company': 'DIS',
'Thermo Fisher Scientific': 'TMO',
'Tiffany & Co.': 'TIF',
'Time Warner Inc.': 'TWX',
'TJX Companies Inc.': 'TJX',
'Tractor Supply Company': 'TSCO',
'TransDigm Group': 'TDG',
'TripAdvisor': 'TRIP',
'Twenty-First Century Fox Class A': 'FOXA',
'Twenty-First Century Fox Class B': 'FOX',
'Tyson Foods': 'TSN',
'U.S. Bancorp': 'USB',
'UDR Inc': 'UDR',
'Ulta Beauty': 'ULTA',
'Under Armour Class A': 'UAA',
'Under Armour Class C': 'UA',
'Union Pacific': 'UNP',
'United Continental Holdings': 'UAL',
'United Health Group Inc.': 'UNH',
'United Parcel Service': 'UPS',
'United Rentals Inc.': 'URI',
'Universal Health Services Inc.': 'UHS',
'Unum Group': 'UNM',
'V.F. Corp.': 'VFC',
'Valero Energy': 'VLO',
'Varian Medical Systems': 'VAR',
'Ventas Inc': 'VTR',
'Verisign Inc.': 'VRSN',
'Verisk Analytics': 'VRSK',
'Verizon Communications': 'VZ',
'Vertex Pharmaceuticals Inc': 'VRTX',
'Viacom Inc.': 'VIAC',
'Visa Inc.': 'V',
'Vornado Realty Trust': 'VNO',
'Vulcan Materials': 'VMC',
'Wal-Mart Stores': 'WMT',
'Walgreens Boots Alliance': 'WBA',
'Waste Management Inc.': 'WM',
'Waters Corporation': 'WAT',
'Wec Energy Group Inc': 'WEC',
'Wells Fargo': 'WFC',
'Welltower Inc.': 'WELL',
'Western Digital': 'WDC',
'Western Union Co': 'WU',
'WestRock Company': 'WRK',
'Weyerhaeuser Corp.': 'WY',
'Whirlpool Corp.': 'WHR',
'Williams Cos.': 'WMB',
'Willis Towers Watson': 'WLTW',
'Wynn Resorts Ltd': 'WYNN',
'Xcel Energy Inc': 'XEL',
'Xerox Corp.': 'XRX',
'Xilinx Inc': 'XLNX',
'XL Capital': 'XL',
'Xylem Inc.': 'XYL',
'Yum! Brands Inc': 'YUM',
'Zimmer Biomet Holdings': 'ZBH',
'Zions Bancorp': 'ZION',
'Zoetis': 'ZTS'}
ISO3 = {'Afghanistan': 'AFG',
'Albania': 'ALB',
'Algeria': 'DZA',
'Angola': 'AGO',
'Antigua and Barbuda': 'ATG',
'Argentina': 'ARG',
'Armenia': 'ARM',
'Aruba': 'ABW',
'Australia': 'AUS',
'Austria': 'AUT',
'Azerbaijan': 'AZE',
'Bahamas': 'BHS',
'Bahrain': 'BHR',
'Bangladesh': 'BGD',
'Barbados': 'BRB',
'Belarus': 'BLR',
'Belgium': 'BEL',
'Belize': 'BLZ',
'Benin': 'BEN',
'Bhutan': 'BTN',
'Bolivia': 'BOL',
'Bosnia and Herzegovina': 'BIH',
'Botswana': 'BWA',
'Brazil': 'BRA',
'Brunei Darussalam': 'BRN',
'Bulgaria': 'BGR',
'Burkina Faso': 'BFA',
'Burundi': 'BDI',
'Cabo Verde': 'CPV',
'Cambodia': 'KHM',
'Cameroon': 'CMR',
'Canada': 'CAN',
'Chad': 'TCD',
'Chile': 'CHL',
'China': 'CHN',
'Colombia': 'COL',
'Comoros': 'COM',
'Congo Dem. Rep.': 'COD',
'Congo Rep.': 'COG',
'Costa Rica': 'CRI',
'Cote dIvoire': 'CIV',
'Croatia': 'HRV',
'Cyprus': 'CYP',
'Czech Republic': 'CZE',
'Denmark': 'DNK',
'Djibouti': 'DJI',
'Dominica': 'DMA',
'Dominican Republic': 'DOM',
'Ecuador': 'ECU',
'Egypt Arab Rep.': 'EGY',
'El Salvador': 'SLV',
'Equatorial Guinea': 'GNQ',
'Eritrea': 'ERI',
'Estonia': 'EST',
'Ethiopia': 'ETH',
'Fiji': 'FJI',
'Finland': 'FIN',
'France': 'FRA',
'Gabon': 'GAB',
'Gambia': 'GMB',
'Georgia': 'GEO',
'Germany': 'DEU',
'Ghana': 'GHA',
'Greece': 'GRC',
'Grenada': 'GRD',
'Guatemala': 'GTM',
'Guinea': 'GIN',
'Guinea-Bissau': 'GNB',
'Guyana': 'GUY',
'Haiti': 'HTI',
'Honduras': 'HND',
'Hong Kong SAR China': 'HKG',
'Hungary': 'HUN',
'Iceland': 'ISL',
'India': 'IND',
'Indonesia': 'IDN',
'Iran Islamic Rep.': 'IRN',
'Iraq': 'IRQ',
'Ireland': 'IRL',
'Israel': 'ISR',
'Italy': 'ITA',
'Jamaica': 'JAM',
'Japan': 'JPN',
'Jordan': 'JOR',
'Kazakhstan': 'KAZ',
'Kenya': 'KEN',
'Kiribati': 'KIR',
'Korea Rep': 'KOR',
'Kuwait': 'KWT',
'Kyrgyz Republic': 'KGZ',
'Lao PDR': 'LAO',
'Latvia': 'LVA',
'Lebanon': 'LBN',
'Lesotho': 'LSO',
'Liberia': 'LBR',
'Libya': 'LBY',
'Lithuania': 'LTU',
'Luxembourg': 'LUX',
'Macao SAR China': 'MAC',
'Macedonia FYR': 'MKD',
'Madagascar': 'MDG',
'Malawi': 'MWI',
'Malaysia': 'MYS',
'Maldives': 'MDV',
'Mali': 'MLI',
'Malta': 'MLT',
'Marshall Islands': 'MHL',
'Mauritania': 'MRT',
'Mauritius': 'MUS',
'Mexico': 'MEX',
'Micronesia Fed. Sts.': 'FSM',
'Moldova': 'MDA',
'Mongolia': 'MNG',
'Montenegro': 'MNE',
'Morocco': 'MAR',
'Mozambique': 'MOZ',
'Myanmar': 'MMR',
'Namibia': 'NAM',
'Nepal': 'NPL',
'Netherlands': 'NLD',
'New Zealand': 'NZL',
'Nicaragua': 'NIC',
'Niger': 'NER',
'Nigeria': 'NGA',
'Norway': 'NOR',
'Oman': 'OMN',
'Pakistan': 'PAK',
'Palau': 'PLW',
'Panama': 'PAN',
'Papua New Guinea': 'PNG',
'Paraguay': 'PRY',
'Peru': 'PER',
'Philippines': 'PHL',
'Poland': 'POL',
'Portugal': 'PRT',
'Puerto Rico': 'PRI',
'Qatar': 'QAT',
'Romania': 'ROU',
'Russian Federation': 'RUS',
'Rwanda': 'RWA',
'Samoa': 'WSM',
'San Marino': 'SMR',
'Sao Tome and Principe': 'STP',
'Saudi Arabia': 'SAU',
'Senegal': 'SEN',
'Serbia': 'SRB',
'Seychelles': 'SYC',
'Sierra Leone': 'SLE',
'Singapore': 'SGP',
'Slovak Republic': 'SVK',
'Slovenia': 'SVN',
'Solomon Islands': 'SLB',
'South Africa': 'ZAF',
'South Sudan': 'SSD',
'Spain': 'ESP',
'Sri Lanka': 'LKA',
'St. Kitts and Nevis': 'KNA',
'St. Lucia': 'LCA',
'St. Vincent and the Grenadines': 'VCT',
'Sudan': 'SDN',
'Suriname': 'SUR',
'Swaziland': 'SWZ',
'Sweden': 'SWE',
'Switzerland': 'CHE',
'Syrian Arab Republic': 'SYR',
'Tajikistan': 'TJK',
'Tanzania': 'TZA',
'Thailand': 'THA',
'Timor-Leste': 'TLS',
'Togo': 'TGO',
'Tonga': 'TON',
'Trinidad and Tobago': 'TTO',
'Tunisia': 'TUN',
'Turkey': 'TUR',
'Turkmenistan': 'TKM',
'Tuvalu': 'TUV',
'Uganda': 'UGA',
'Ukraine': 'UKR',
'United Arab Emirates': 'ARE',
'United Kingdom': 'GBR',
'United States': 'USA',
'Uruguay': 'URY',
'Uzbekistan': 'UZB',
'Vanuatu': 'VUT',
'Venezuela RB': 'VEN',
'Vietnam': 'VNM',
'Yemen Rep.': 'YEM',
'Zambia': 'ZMB',
'Zimbabwe': 'ZWE'}
|
a= int(input())
if (a%4 == 0) and (a%100 != 0):
print(1)
elif a%400 ==0:
print(1)
else:
print(0)
|
# encoding: utf-8
# module cv2.optflow
# from /home/davtoh/anaconda3/envs/rrtools/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so
# by generator 1.144
# no doc
# no imports
# Variables with simple values
DISOpticalFlow_PRESET_FAST = 1
DISOpticalFlow_PRESET_MEDIUM = 2
DISOpticalFlow_PRESET_ULTRAFAST = 0
DISOPTICAL_FLOW_PRESET_FAST = 1
DISOPTICAL_FLOW_PRESET_MEDIUM = 2
DISOPTICAL_FLOW_PRESET_ULTRAFAST = 0
GPC_DESCRIPTOR_DCT = 0
GPC_DESCRIPTOR_WHT = 1
__loader__ = None
__spec__ = None
# functions
# real signature unknown; restored from __doc__
def calcOpticalFlowSF(from_, to, layers, averaging_block_size, max_flow, flow=None):
""" calcOpticalFlowSF(from, to, layers, averaging_block_size, max_flow[, flow]) -> flow or calcOpticalFlowSF(from, to, layers, averaging_block_size, max_flow, sigma_dist, sigma_color, postprocess_window, sigma_dist_fix, sigma_color_fix, occ_thr, upscale_averaging_radius, upscale_sigma_dist, upscale_sigma_color, speed_up_thr[, flow]) -> flow """
pass
# real signature unknown; restored from __doc__
def calcOpticalFlowSparseToDense(from_, to, flow=None, grid_step=None, k=None, sigma=None, use_post_proc=None, fgs_lambda=None, fgs_sigma=None):
""" calcOpticalFlowSparseToDense(from, to[, flow[, grid_step[, k[, sigma[, use_post_proc[, fgs_lambda[, fgs_sigma]]]]]]]) -> flow """
pass
def createOptFlow_DeepFlow(): # real signature unknown; restored from __doc__
""" createOptFlow_DeepFlow() -> retval """
pass
def createOptFlow_DIS(preset=None): # real signature unknown; restored from __doc__
""" createOptFlow_DIS([, preset]) -> retval """
pass
def createOptFlow_Farneback(): # real signature unknown; restored from __doc__
""" createOptFlow_Farneback() -> retval """
pass
def createOptFlow_PCAFlow(): # real signature unknown; restored from __doc__
""" createOptFlow_PCAFlow() -> retval """
pass
def createOptFlow_SimpleFlow(): # real signature unknown; restored from __doc__
""" createOptFlow_SimpleFlow() -> retval """
pass
def createOptFlow_SparseToDense(): # real signature unknown; restored from __doc__
""" createOptFlow_SparseToDense() -> retval """
pass
def createVariationalFlowRefinement(): # real signature unknown; restored from __doc__
""" createVariationalFlowRefinement() -> retval """
pass
def readOpticalFlow(path): # real signature unknown; restored from __doc__
""" readOpticalFlow(path) -> retval """
pass
def writeOpticalFlow(path, flow): # real signature unknown; restored from __doc__
""" writeOpticalFlow(path, flow) -> retval """
pass
# no classes
|
c = 0
while(True):
c+=1
inp = input()
if(inp == '0'):
break
n = int(inp)
inp = input().split(' ')
su = 0
for j in range(0,len(inp)):
su += int(inp[j])
av = int(su / len(inp))
count = 0
for j in range(0,len(inp)):
count += abs(av - int(inp[j]))
print('Set #' + str(c))
print('The minimum number of moves is ' + str(int(count/2)) + '.')
print('')
|
# cook your dish here
def highestPowerOf2(n):
return (n & (~(n - 1)))
for t in range(int(input())):
ts=int(input())
sum=0
if ts%2==1:
print((ts-1)//2)
else:
x=highestPowerOf2(ts)
print(ts//((x*2)))
|
"""Functions to help edit essay homework using string manipulation."""
def capitalize_title(title):
"""Convert the first letter of each word in the title to uppercase if needed.
:param title: str - title string that needs title casing.
:return: str - title string in title case (first letters capitalized).
"""
return title.title()
def check_sentence_ending(sentence):
"""Check the ending of the sentence to verify that a period is present.
:param sentence: str - a sentence to check.
:return: bool - is the sentence punctuated correctly?
"""
return sentence.endswith(".")
def clean_up_spacing(sentence):
"""Trim any leading or trailing whitespace from the sentence.
:param sentence: str - a sentence to clean of leading and trailing space characters.
:return: str - a sentence that has been cleaned of leading and trailing space characters.
"""
clean_sentence = sentence.strip()
return clean_sentence
def replace_word_choice(sentence, old_word, new_word):
"""Replace a word in the provided sentence with a new one.
:param sentence: str - a sentence to replace words in.
:param old_word: str - word to replace.
:param new_word: str - replacement word.
:return: str - input sentence with new words in place of old words.
"""
better_sentence = sentence.replace(old_word, new_word)
return better_sentence
|
'''rig pipeline prototype
by Ben Barker, copyright (c) 2015
[email protected]
for license info see license.txt
'''
|
def main():
# Manage input file
input = open(r"C:\Users\lawht\Desktop\Github\ROSALIND\Bioinformatics Stronghold\(2) Transcribing DNA into RNA\(2) Transcribing DNA into RNA\rosalind_rna.txt","r");
DNA_string = input.readline(); # take first line of input file for counting
# Take in input file of DNA string and print out its corresponding RNA sequence
print(DNA_to_RNA(DNA_string));
input.close();
# Given: A DNA string t having length at most 1000 nt.
# Return: The transcribed RNA string of t.
def DNA_to_RNA(s):
rna = "";
for n in s:
if n == "T":
rna = rna + "U";
else:
rna = rna + n;
return rna;
# Manually call main() on the file load
if __name__ == "__main__":
main();
|
class Solution:
def minDifference(self, nums: List[int]) -> int:
# pick three values
if len(nums) <= 4:
return 0
nums.sort()
ans = nums[-1] - nums[0]
for i in range(4):
ans = min(nums[-1 - (3 - i)] - nums[i], ans)
return ans
|
'''https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1
https://www.geeksforgeeks.org/bottom-view-binary-tree/
Bottom View of Binary Tree
Medium Accuracy: 45.32% Submissions: 90429 Points: 4
Given a binary tree, print the bottom view from left to right.
A node is included in bottom view if it can be seen when we look at the tree from bottom.
20
/ \
8 22
/ \ \
5 3 25
/ \
10 14
For the above tree, the bottom view is 5 10 3 14 25.
If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottommost nodes at horizontal distance 0, we need to print 4.
20
/ \
8 22
/ \ / \
5 3 4 25
/ \
10 14
For the above tree the output should be 5 10 4 14 25.
Example 1:
Input:
1
/ \
3 2
Output: 3 1 2
Explanation:
First case represents a tree with 3 nodes
and 2 edges where root is 1, left child of
1 is 3 and right child of 1 is 2.
Thus nodes of the binary tree will be
printed as such 3 1 2.
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output: 40 20 60 30
Your Task:
This is a functional problem, you don't need to care about input, just complete the function bottomView() which takes the root node of the tree as input and returns an array containing the bottom view of the given tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 105
1 <= Data of a node <= 105'''
# Python3 program to print Bottom
# View of Binary Tree
# Tree node class
class Node:
def __init__(self, key):
self.data = key
self.hd = 1000000
self.left = None
self.right = None
# Method that prints the bottom view.
def bottomView(root):
if (root == None):
return
# Initialize a variable 'hd' with 0
# for the root element.
hd = 0
# TreeMap which stores key value pair
# sorted on key value
m = dict()
# Queue to store tree nodes in level
# order traversal
q = []
# Assign initialized horizontal distance
# value to root node and add it to the queue.
root.hd = hd
# In STL, append() is used enqueue an item
q.append(root)
# Loop until the queue is empty (standard
# level order loop)
while (len(q) != 0):
temp = q[0]
# In STL, pop() is used dequeue an item
q.pop(0)
# Extract the horizontal distance value
# from the dequeued tree node.
hd = temp.hd
# Put the dequeued tree node to TreeMap
# having key as horizontal distance. Every
# time we find a node having same horizontal
# distance we need to replace the data in
# the map.
m[hd] = temp.data
# If the dequeued node has a left child, add
# it to the queue with a horizontal distance hd-1.
if (temp.left != None):
temp.left.hd = hd - 1
q.append(temp.left)
# If the dequeued node has a right child, add
# it to the queue with a horizontal distance
# hd+1.
if (temp.right != None):
temp.right.hd = hd + 1
q.append(temp.right)
# Traverse the map elements using the iterator.
for i in sorted(m.keys()):
print(m[i], end=' ')
# Driver Code
if __name__ == '__main__':
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(5)
root.left.right = Node(3)
root.right.left = Node(4)
root.right.right = Node(25)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
print("Bottom view of the given binary tree :")
bottomView(root)
# Using Hash Map
# Python3 program to print Bottom
# View of Binary Tree
class Node:
def __init__(self, key=None,
left=None,
right=None):
self.data = key
self.left = left
self.right = right
def printBottomView(root):
# Create a dictionary where
# key -> relative horizontal distance
# of the node from root node and
# value -> pair containing node's
# value and its level
d = dict()
printBottomViewUtil(root, d, 0, 0)
# Traverse the dictionary in sorted
# order of their keys and print
# the bottom view
for i in sorted(d.keys()):
print(d[i][0], end=" ")
def printBottomViewUtil(root, d, hd, level):
# Base case
if root is None:
return
# If current level is more than or equal
# to maximum level seen so far for the
# same horizontal distance or horizontal
# distance is seen for the first time,
# update the dictionary
if hd in d:
if level >= d[hd][1]:
d[hd] = [root.data, level]
else:
d[hd] = [root.data, level]
# recur for left subtree by decreasing
# horizontal distance and increasing
# level by 1
printBottomViewUtil(root.left, d, hd - 1,
level + 1)
# recur for right subtree by increasing
# horizontal distance and increasing
# level by 1
printBottomViewUtil(root.right, d, hd + 1,
level + 1)
# Driver Code
if __name__ == '__main__':
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(5)
root.left.right = Node(3)
root.right.left = Node(4)
root.right.right = Node(25)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
print("Bottom view of the given binary tree :")
printBottomView(root)
|
print('\033[1;93m-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[m')
print('\033[1;31m DADOS EM UMA TUPLA\033[m')
print('\033[1;93m-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[m')
num = (int(input('Digite um número: ')), int(input('Digite outro número: ')),
int(input('Digite mais um número: ')), int(input('Digite o último número: ')))
impar = 0
print(f'Você digitou os números: {num}')
print(f'O número 9 apareceu {num.count(9)} vezes')
try:
print(f'O números 3 foi digitado na {num.index(3)+1}ª posição')
except:
print('Não foi digitado número 3')
print('Os valores pares digitados foram: ', end='')
for n in num:
if n % 2 != 0:
impar += 1
if impar == 4:
print('Não foi digitado nenhum número par')
else:
for n in num:
if n % 2 == 0:
print(n, end=' ')
|
class dotControlObject_t(object):
# no doc
aName = None
Color = None
Extension = None
IsMagnetic = None
ModelObject = None
Plane = None
|
"""
For a given positive integer n determine
if it can be represented as
a sum of two Fibonacci numbers (possibly equal).
Example
For n = 1, the output should be
fibonacciSimpleSum2(n) = true.
Explanation: 1 = 0 + 1 = F0 + F1.
For n = 11, the output should be
fibonacciSimpleSum2(n) = true.
Explanation: 11 = 3 + 8 = F4 + F6.
For n = 60, the output should be
fibonacciSimpleSum2(n) = true.
Explanation: 11 = 5 + 55 = F5 + F10.
For n = 66, the output should be
fibonacciSimpleSum2(n) = false.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer n
Guaranteed constraints:
1 ≤ n ≤ 2 · 109.
[output] boolean
true if n can be represented as
Fi + Fj, false otherwise.
"""
def fibonacciSimpleSum2(n):
fib = [0, 1]
# set range so 0(1)
# populate fibonacciSequence
for i in range(2, 700):
fib.append(fib[i - 1] + fib[i -2])
# Solution 1:
for i in range(0, len(fib)):
# check the condition
if n - fib[i] in fib:
return True
#otherwise return False
return False
n = 1
print(fibonacciSimpleSum2(n)) # = true.
#Explanation: 1 = 0 + 1 = F0 + F1.
n = 11
print(fibonacciSimpleSum2(n)) # = true.
#Explanation: 11 = 3 + 8 = F4 + F6.
n = 60
print(fibonacciSimpleSum2(n)) # = true.
#Explanation: 11 = 5 + 55 = F5 + F10.
n = 66
print(fibonacciSimpleSum2(n)) # = false.
|
#Ask User for his role and save it in a variable
role = input ("Are you an administrator, teacher, or student?: ")
#If role "administrator or teacher" print they have keys
if role == "administrator" or role == "teacher":
print ("Administrators and teachers get keys!")
#If role "Student" print they dont get keys
elif role == "student":
print ("Students do not get keys")
#Else of the options, say the roles that can be used
else:
print("You can only be an administrator, teacher, or student!")
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( k , s1 , s2 ) :
n = len ( s1 )
m = len ( s2 )
lcs = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ]
cnt = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ]
for i in range ( 1 , n + 1 ) :
for j in range ( 1 , m + 1 ) :
lcs [ i ] [ j ] = max ( lcs [ i - 1 ] [ j ] , lcs [ i ] [ j - 1 ] )
if ( s1 [ i - 1 ] == s2 [ j - 1 ] ) :
cnt [ i ] [ j ] = cnt [ i - 1 ] [ j - 1 ] + 1 ;
if ( cnt [ i ] [ j ] >= k ) :
for a in range ( k , cnt [ i ] [ j ] + 1 ) :
lcs [ i ] [ j ] = max ( lcs [ i ] [ j ] , lcs [ i - a ] [ j - a ] + a )
return lcs [ n ] [ m ]
#TOFILL
if __name__ == '__main__':
param = [
(4,'aggayxysdfa','aggajxaaasdfa',),
(2,'55571659965107','390286654154',),
(3,'01011011100','0000110001000',),
(5,'aggasdfa','aggajasdfaxy',),
(2,'5710246551','79032504084062',),
(3,'0100010','10100000',),
(3,'aabcaaaa','baaabcd',),
(1,'1219','3337119582',),
(2,'111000011','011',),
(2,'wiC oD','csiuGOUwE',)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param)))
|
name = 'Zed A. Shaw'
age = 35
height = 74
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} pounds heavy.")
print("Actually it's not too heavy")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are usually {teeth} depending on the coffee.")
total = age + weight + height
print(f"If I add {age}, {height}, and {weight} I get {total}")
#Study Drills:
print("Conversion from lbs to kg")
print("=" * 20) #Writes = 20 times on same line
customLBS = 200
kg = round(customLBS / 2.2046226218488, 2)
print(f"{customLBS} is {kg} kg")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
- Escribe un programa que calcule el valor neto de una cuenta de banco basado
en las transacciones que se ingresan en la consola de comandos.
Ej:
D 200
D 250
P 300
D 100
P 200
Donde:
D = Deposito
P = Pago
Resultado
50
"""
|
def get_data(path):
try:
file_handler = open(path, "r")
except:
return 0
data = []
for line in file_handler:
values = line.strip().split(" ")
data.append([int(values[1]), int(values[2]), int(values[3])])
return data
def sensortxt_parser(path):
order = ['lu', 'ru', 'lu', 'ru']
order2 = ['ld', 'rd', 'ld', 'rd']
dict1 = {} # walker1
dict2 = {} # walker2
with open(path, 'r') as f:
c = 0
for line in f:
if c == 2:
sensors = []
for elem in line.strip().split("\t"):
if elem == ' ':
sensors.append("x")
else:
sensors.append(int(elem))
if len(line.strip().split("\t")) == 3:
sensors.append("x")
for i in range(len(sensors)):
if i > 1:
dict2[order[i]] = sensors[i]
else:
dict1[order[i]] = sensors[i]
if c == 3:
sensors = []
for elem in line.strip().split("\t"):
if elem == ' ':
sensors.append("x")
else:
sensors.append(int(elem))
if len(line.strip().split("\t")) == 3:
sensors.append("x")
for i in range(len(sensors)):
if i > 1:
dict2[order2[i]] = sensors[i]
else:
dict1[order2[i]] = sensors[i]
c += 1
return dict1, dict2
|
# -*- coding: utf-8 -*-
# Copyright (C) 2018 by
# Marta Grobelna <[email protected]>
# Petre Petrov <[email protected]>
# Rudi Floren <[email protected]>
# Tobias Winkler <[email protected]>
# All rights reserved.
# BSD license.
#
# Authors: Marta Grobelna <[email protected]>
# Petre Petrov <[email protected]>
# Rudi Floren <[email protected]>
# Tobias Winkler <[email protected]>
# Gets a list of probabilities
# Gets a random_function
# Returns the index or the size of the probabiliy.
# Acts as Bernoulli for len(probabilites) == 2
def bern_choice(probabilities, random_function) -> int:
"""Draws a random value with random_function and returns
the index of a probability which the random value undercuts.
The list is theoretically expanded to include 1-p
"""
assert type(probabilities) is list
random_value = random_function()
for index in range(len(probabilities)):
if random_value <= probabilities[index]:
return index
return len(probabilities)
def poiss(p) -> int:
pass
|
r"""
*************************
Text rendering With LaTeX
*************************
Matplotlib can use LaTeX to render text. This is activated by setting
``text.usetex : True`` in your rcParams, or by setting the ``usetex`` property
to True on individual `.Text` objects. Text handling through LaTeX is slower
than Matplotlib's very capable :doc:`mathtext </tutorials/text/mathtext>`, but
is more flexible, since different LaTeX packages (font packages, math packages,
etc.) can be used. The results can be striking, especially when you take care
to use the same fonts in your figures as in the main document.
Matplotlib's LaTeX support requires a working LaTeX_ installation. For the
\*Agg backends, dvipng_ is additionally required; for the PS backend, psfrag_,
dvips_ and Ghostscript_ are additionally required. The executables for these
external dependencies must all be located on your :envvar:`PATH`.
There are a couple of options to mention, which can be changed using
:doc:`rc settings </tutorials/introductory/customizing>`. Here is an example
matplotlibrc file::
font.family : serif
font.serif : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman
font.sans-serif : Helvetica, Avant Garde, Computer Modern Sans Serif
font.cursive : Zapf Chancery
font.monospace : Courier, Computer Modern Typewriter
text.usetex : true
The first valid font in each family is the one that will be loaded. If the
fonts are not specified, the Computer Modern fonts are used by default. All of
the other fonts are Adobe fonts. Times and Palatino each have their own
accompanying math fonts, while the other Adobe serif fonts make use of the
Computer Modern math fonts. See the PSNFSS_ documentation for more details.
To use LaTeX and select Helvetica as the default font, without editing
matplotlibrc use::
import matplotlib.pyplot as plt
plt.rcParams.update({
"text.usetex": True,
"font.family": "sans-serif",
"font.sans-serif": ["Helvetica"]})
# for Palatino and other serif fonts use:
plt.rcParams.update({
"text.usetex": True,
"font.family": "serif",
"font.serif": ["Palatino"],
})
Here is the standard example,
:file:`/gallery/text_labels_and_annotations/tex_demo`:
.. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_tex_demo_001.png
:target: ../../gallery/text_labels_and_annotations/tex_demo.html
:align: center
:scale: 50
Note that display math mode (``$$ e=mc^2 $$``) is not supported, but adding the
command ``\displaystyle``, as in the above demo, will produce the same results.
Non-ASCII characters (e.g. the degree sign in the y-label above) are supported
to the extent that they are supported by inputenc_.
.. note::
Certain characters require special escaping in TeX, such as::
# $ % & ~ _ ^ \ { } \( \) \[ \]
Therefore, these characters will behave differently depending on
:rc:`text.usetex`.
PostScript options
==================
In order to produce encapsulated PostScript (EPS) files that can be embedded
in a new LaTeX document, the default behavior of Matplotlib is to distill the
output, which removes some PostScript operators used by LaTeX that are illegal
in an EPS file. This step produces results which may be unacceptable to some
users, because the text is coarsely rasterized and converted to bitmaps, which
are not scalable like standard PostScript, and the text is not searchable. One
workaround is to set :rc:`ps.distiller.res` to a higher value (perhaps 6000)
in your rc settings, which will produce larger files but may look better and
scale reasonably. A better workaround, which requires Poppler_ or Xpdf_, can
be activated by changing :rc:`ps.usedistiller` to ``xpdf``. This alternative
produces PostScript without rasterizing text, so it scales properly, can be
edited in Adobe Illustrator, and searched text in pdf documents.
.. _usetex-hangups:
Possible hangups
================
* On Windows, the :envvar:`PATH` environment variable may need to be modified
to include the directories containing the latex, dvipng and ghostscript
executables. See :ref:`environment-variables` and
:ref:`setting-windows-environment-variables` for details.
* Using MiKTeX with Computer Modern fonts, if you get odd \*Agg and PNG
results, go to MiKTeX/Options and update your format files
* On Ubuntu and Gentoo, the base texlive install does not ship with
the type1cm package. You may need to install some of the extra
packages to get all the goodies that come bundled with other latex
distributions.
* Some progress has been made so matplotlib uses the dvi files
directly for text layout. This allows latex to be used for text
layout with the pdf and svg backends, as well as the \*Agg and PS
backends. In the future, a latex installation may be the only
external dependency.
.. _usetex-troubleshooting:
Troubleshooting
===============
* Try deleting your :file:`.matplotlib/tex.cache` directory. If you don't know
where to find :file:`.matplotlib`, see :ref:`locating-matplotlib-config-dir`.
* Make sure LaTeX, dvipng and ghostscript are each working and on your
:envvar:`PATH`.
* Make sure what you are trying to do is possible in a LaTeX document,
that your LaTeX syntax is valid and that you are using raw strings
if necessary to avoid unintended escape sequences.
* :rc:`text.latex.preamble` is not officially supported. This
option provides lots of flexibility, and lots of ways to cause
problems. Please disable this option before reporting problems to
the mailing list.
* If you still need help, please see :ref:`reporting-problems`
.. _dvipng: http://www.nongnu.org/dvipng/
.. _dvips: https://tug.org/texinfohtml/dvips.html
.. _Ghostscript: https://ghostscript.com/
.. _inputenc: https://ctan.org/pkg/inputenc
.. _LaTeX: http://www.tug.org
.. _Poppler: https://poppler.freedesktop.org/
.. _PSNFSS: http://www.ctan.org/tex-archive/macros/latex/required/psnfss/psnfss2e.pdf
.. _psfrag: https://ctan.org/pkg/psfrag
.. _Xpdf: http://www.xpdfreader.com/
"""
|
# first line: 1
@mem.cache
def get_data(filename):
data=load_svmlight_file(filename)
return data[0],data[1]
|
# 示例 1
# width = input("请输入长方形的宽:")
# height = input("请输入长方形的高:")
# area = int(width) * int(height)
# print("长方形的面积为:", area)
# 示例 2
# weight = input("请输入当前的体重:")
#
# if float(weight) >= 200:
# print("你和加菲猫一样肥!!")
# else:
# print("你还是很苗条的么!!")
# 示例 3
# weight = input("请输入您当前的体重:")
#
# if float(weight) >= 200:
# print("你和加菲猫一样肥!!")
# elif float(weight) >= 100:
# print("你的身材真棒!!")
# else:
# print("有点瘦哦,要多吃肉!!")
# 示例 4
gender = input("请输入您的性别(M或者F):")
height = input("请输入您的身高:")
if gender == 'M':
if float(height) >= 185:
print("海拔太高了,可能会导致缺氧!!!")
elif float(height) >= 175:
print("男神身高!!!")
else:
print("哥们,该补钙了!!!")
else:
if float(height) >= 175:
print("您可以去当模特了!!!")
elif float(height) >= 165:
print("女神身高,您是一位美丽的女孩子!!!")
else:
print("美女,多晒晒太阳吧!!!")
|
"""
Defines an Indexer Object with different methods to index data, look up, add, remove etc
Extremely useful across all NLP tasks
Author: Greg Durrett
Contact: [email protected]
"""
class Indexer(object):
"""
Bijection between objects and integers starting at 0. Useful for mapping
labels, features, etc. into coordinates of a vector space.
Attributes:
objs_to_ints
ints_to_objs
"""
def __init__(self):
self.objs_to_ints = {}
self.ints_to_objs = {}
def __repr__(self):
return str([str(self.get_object(i)) for i in range(0, len(self))])
def __str__(self):
return self.__repr__()
def __len__(self):
return len(self.objs_to_ints)
def get_object(self, index):
"""
:param index: integer index to look up
:return: Returns the object corresponding to the particular index or None if not found
"""
if index not in self.ints_to_objs:
return None
else:
return self.ints_to_objs[index]
def contains(self, object):
"""
:param object: object to look up
:return: Returns True if it is in the Indexer, False otherwise
"""
return self.index_of(object) != -1
def index_of(self, object):
"""
:param object: object to look up
:return: Returns -1 if the object isn't present, index otherwise
"""
if object not in self.objs_to_ints:
return -1
else:
return self.objs_to_ints[object]
def add_and_get_index(self, object, add=True):
"""
Adds the object to the index if it isn't present, always returns a nonnegative index
:param object: object to look up or add
:param add: True by default, False if we shouldn't add the object. If False, equivalent to index_of.
:return: The index of the object
"""
if not add:
return self.index_of(object)
if object not in self.objs_to_ints:
new_idx = len(self.objs_to_ints)
self.objs_to_ints[object] = new_idx
self.ints_to_objs[new_idx] = object
return self.objs_to_ints[object]
|
tour_es = 'Madrid', 'Paris', 'Lóndres', 'Berlín', 'Alpes austríacos', 'Dublín', 'Atenas', 'Ámsterdam', 'Moscú', \
'Zurich', 'Roma', 'Lisboa', 'Nueva York', 'Los Angeles', 'Ciudad de México', 'Acapulco', 'Ciudad de Panama', \
'Gran Caiman', 'Kingston', 'Dubai', 'Tel Aviv', 'Jerusalen', 'Bangkoko', 'Tokio'
tour_en = 'Madrid', 'Paris', 'London', 'Berlin', 'Austrian Alps', 'Dublin', 'Athens', 'Amsterdam', 'Moscow', \
'Zurich', 'Rome', 'Lisbon', 'New York', 'Los Angeles', 'Mexico City', 'Acapulco', 'Panama City', \
'Grand Cayman', 'Kingston', 'Dubai', 'Tel Aviv', 'Jerusalem', 'Bangkok', 'Tokyo'
a = '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3'
b = '2', '2', '4', '1', '1', '3', '2', '4', '5', '5', '3', '4', '3', '3', '4', '4', '4', '3', '4', '2', '3', '3', '5', '3'
c = '5', '8', '11', '2', '5', '3', '11', '8', '3', '7', '6', '10', '1', '1', '3', '3', '5', '7', '1', '2', '2', '2', '3', '3'
d = '4', '4', '4', '1', '1', '4', '1', '1', '2', '5', '4', '4', '4', '3', '1', '1', '3', '1', '1', '2', '5', '3', '1', '5'
e = '2', '22', '1', '12', '1', '5', '3', '3', '24', '4', '14', '1', '92', '230', '12', '1', '3', '1', '2', '2', '1', '2', '3', '9'
|
#
# Copyright 2017, Data61
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# ABN 41 687 119 230.
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(DATA61_BSD)
#
'''
Helpers for accessing architecture-specific information
'''
def is_64_bit_arch(arch):
return arch in ('x86_64', 'aarch64')
def min_untyped_size(arch):
return 4
def max_untyped_size(arch):
if is_64_bit_arch(arch):
return 47
else:
return 29
|
def find_num_1(response_list):
responses = []
for r in response_list:
responses.extend([i for i in r])
responses = list(set(responses))
return len(responses)
def find_num_2(response_list):
if len(response_list) == 0:
return 0
responses = set(response_list[0])
if len(response_list) == 1:
print(str(list(responses)) + "\t" + str(len(responses)))
return len(list(responses))
responses = list(responses.intersection(*response_list[1:]))
print(str(responses) + "\t" + str(len(responses)))
return len(responses)
def parse_file(input_file):
responses = []
family = []
for r in input_file:
if not r.strip():
responses.append(family)
family = []
else:
family.append(r)
responses.append(family)
return responses
file = "input_day6.txt"
with open(file, "r") as input:
input_file = input.read().splitlines()
parsed_input_file = parse_file(input_file)
num_1 = 0
num_2 = 0
for family in parsed_input_file:
num_1 += find_num_1(family)
num_2 += find_num_2(family)
print("Number of exceptions, pt1:\t"+str(num_1))
print("Number of exceptions, pt2:\t"+str(num_2))
|
LOWER_PRIORITY = 100
LOW_PRIORITY = 75
DEFAULT_PRIORITY = 50
HIGH_PRIORITY = 25
HIGHEST_PRIORITY = 0
|
class Config(object):
data = './'
activation='Relu'#Swish,Relu,Mish,Selu
init = "kaiming"#kaiming
save = './checkpoints'#save best model dir
arch = 'resnet'
depth = 50 #resnet-50
gpu_id = '0,1' #gpu id
train_data = '/home/daixiangzi/dataset/cifar-10/files/train.txt'# train file
test_data = '/home/daixiangzi/dataset/cifar-10/files/test.txt'# test file
train_batch=512
test_batch=512
epochs= 150
lr = 0.1#0.003
gamma =0.1#'LR is multiplied by gamma on schedule.
drop = 0
momentum = 0.9
fre_print=2
weight_decay = 1e-4
schedule = [60,100,125]
seed = 666
workers=4
num_classes=10 #classes
resume = None #path to latest checkpoint
#label_smoothing
label_smooth = False
esp = 0.1
# warmming_up
warmming_up = False
decay_epoch=1000
#mix up
mix_up= True
alpha = 0.5#0.1
# Cutout
cutout = False #set cutout flag
cutout_n = 5
cutout_len = 5
evaluate=False #wether to test
start_epoch = 0
optim = "SGD" #SGD,Adam,RAdam,AdamW
#lookahead
lookahead = False
la_steps=5
la_alpha=0.5
logs = './logs/'+arch+str(depth)+optim+str(lr)+("_lookahead" if lookahead else "")+"_"+activation+"_"+init+("_cutout" if cutout else "")+("_mix_up"+str(alpha) if mix_up else "")+("_warmup"+str(decay_epoch) if warmming_up else "")+str('_label_smooth'+str(esp) if label_smooth else "")
|
# Make an xor function
# Truth table
# | left | right | Result |
# |-------|-------|--------|
# | True | True | False |
# | True | False | True |
# | False | True | True |
# | False | False | False |
# def xor(left, right):
# return left != right
xor = lambda left, right: left != right
print(xor(True, True)) # > False
print(xor(True, False)) # > True
print(xor(False, True)) # > True
print(xor(False, False)) # > False
def print_powers_of(base, exp=1):
i = 1
while i <= exp:
print(base ** i)
i += 1
# We are not hoisting the function declaration, we need to invoke after declared
print_powers_of(15)
print_powers_of(exp=6, base=7)
print_powers_of(2, 5)
print_powers_of(3, 5)
print_powers_of(10, 5)
if True:
x = 10
print(x)
print(i)
|
class Users:
'''
Class that generates new instances of users
'''
users_list = []
def save_users(self):
'''
This method will save all users to the user list
'''
Users.users_list.append(self)
def __init__ (self,user_name,first_name,last_name,birth_month,password):
'''
This is a blueprint that every user instance must conform to
'''
self.user_name = user_name
self.first_name = first_name
self.last_name = last_name
self.birth_month = birth_month
self.password = password
@classmethod
def find_user_byPassword(cls,password):
'''
This method will take in a password and check if the password exists to find the user
'''
for user in cls.users_list:
if user.password == password:
return user
@classmethod
def user_registered(cls,user_name,password):
'''
Method that checks if a user exists in the user list.Will help in authentication
'''
for user in cls.users_list:
if user.user_name == user_name and user.password == password:
return True
return False
|
PREDEFINED_TORQUE_INPUTS = [
"$torque.environment.id",
"$torque.environment.virtual_network_id",
"$torque.environment.public_address",
"$torque.repos.current.current",
"$torque.repos.current.url",
"$torque.repos.current.token"
]
|
def iterate(days):
with open("inputs/day6.txt") as f:
input = [int(x) for x in f.readline().strip().split(",")]
fish = {}
for f in input:
fish[f] = fish.get(f, 0) + 1
for day in range(1, days+1):
new_fish = {}
for x in fish:
if x == 0:
new_fish[6] = new_fish.get(6,0) + fish[x]
new_fish[8] = fish[x]
else:
new_fish[x-1] = new_fish.get(x-1, 0) + fish[x]
fish = new_fish
fish_count = sum(fish.values())
return fish_count
print("part1:", iterate(80))
print("part2:", iterate(256))
|
rows, cols = [int(x) for x in input().split()]
line = input()
index = 0
matrix = []
for row in range(rows):
matrix.append([None]*cols)
for col in range(cols):
if row % 2 == 0:
matrix[row][col] = line[index]
else:
matrix[row][cols - 1 - col] = line[index]
index = (index +1 ) % len(line)
for el in matrix:
print(''.join(el))
|
v1 = float(input('Qual a velocidade do carro (km/h)? '))
m = (v1 - 80)*7
if v1 > 80:
print(f'Sua velocidade foi de {v1}km/h e está acima do limte de velocidade que é de 80km\h. \nVocê foi multado em R${m:.2f}.')
else:
print('Tenha um bom dia! Dirija com segurança!')
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 21 08:25:14 2021
@author: ASUS
"""
|
class SplendaException(Exception):
def __init__(self, method_name, fake_class, spec_class):
self.fake_class = fake_class
self.spec_class = spec_class
self.method_name = method_name
def __str__(self):
spec_name = self.spec_class.__name__
fake_name = self.fake_class.__name__
return self.message.format(
fake_name=fake_name,
method_name=self.method_name,
spec_name=spec_name)
|
def ficha(nome='<desconhecido>', gols=0):
return f'O jogador {nome} fez {gols} gol(s) no campeonato.'
# main
n = str(input('Nome do Jogador: ')).capitalize()
g = str(input('Número de gols: '))
if g.isnumeric():
g = int(g)
else:
g = 0
if n.strip() == '':
print(ficha(gols=g))
else:
print(ficha(n, g))
|
def count_circle_lattice_points(cx: int, cy: int, r: int, k: int) -> int:
"""
count up integer point (x, y) in the circle or on it.
centered at (cx, cy) with radius r.
and both x and y are multiple of k.
"""
assert r >= 0 and k >= 0
cx %= k
cy %= k
def is_ok(dx: int, dy: int) -> bool:
return dx * dx + dy * dy <= r * r
def count_right(cx: int, cy: int, x0: int) -> int:
assert x0 == 0 or x0 == k
y0, y1 = 0, 1
count = 0
for x in range((cx + r) // k * k, x0 - 1, -k):
while is_ok(x - cx, y0 * k - cy):
y0 -= 1
while is_ok(x - cx, y1 * k - cy):
y1 += 1
count += y1 - y0 - 1
return count
return count_right(cx, cy, k) + count_right(-cx, cy, 0)
def count_circle_lattice_points_binary_search(
cx: int,
cy: int,
r: int,
k: int,
) -> int:
assert r >= 0 and k >= 0
def count_up_y(x: int) -> int:
assert x % k == 0
rhs = r * r - (x - cx) ** 2
if rhs < 0:
return 0
def is_ok(y: int) -> bool:
return (y - cy) ** 2 <= rhs
def search_max() -> int:
lo, hi = cy, cy + r + 1
while hi - lo > 1:
y = (lo + hi) >> 1
if is_ok(y):
lo = y
else:
hi = y
return lo // k * k
def search_min() -> int:
lo, hi = cy - r - 1, cy
while hi - lo > 1:
y = (lo + hi) >> 1
if is_ok(y):
hi = y
else:
lo = y
return (hi + k - 1) // k * k
return (search_max() - search_min()) // k + 1
x0 = (cx - r + k - 1) // k * k
x1 = (cx + r) // k * k
return sum(count_up_y(x) for x in range(x0, x1 + 1, k))
|
# TODO
class ICM20948_SETTINGS(object):
"""
ICM20948 Settings class
: param blabla: asfdasg
: return: ICM20938 Settings object
: rtype: Object
"""
def __init__(self):
pass
def parse_config_file(self, filepath):
pass
# Gyro full scale range options [_AGB2_REG_GYRO_CONFIG_1]
_gyroscope_sensitivity = {
'250dps' : 0x00,
'500dps' : 0x01,
'1000dps' : 0x02,
'2000dps' : 0x03,
}
# Gyro scaling factors
_gyroscope_scale = {
'250dps' : 131.0,
'500dps' : 65.5,
'1000dps' : 32.8,
'2000dps' : 16.4
}
# Accelerometer full scale range options [_AGB2_REG_ACCEL_CONFIG]
_accelerometer_sensitivity = {
'2g' : 0x00,
'4g' : 0x01,
'8g' : 0x02,
'16g' : 0x03,
}
# Accelerometer scaling factors depending on accelerometer sensitivity
_accelerometer_scale = {
'2g' : 16384.0,
'4g' : 8192.0,
'8g' : 4096.0,
'16g' : 2048.0,
}
# Accelerometer low pass filter configuration options
# Format is dAbwB_nXbwY - A is the integer part of 3db BW, B is the fraction.
# X is integer part of nyquist bandwidth, Y is the fraction
acc_d246bw_n265bw = 0x00
acc_d246bw_n265bw_1 = 0x01
acc_d111bw4_n136bw = 0x02
acc_d50bw4_n68bw8 = 0x03
acc_d23bw9_n34bw4 = 0x04
acc_d11bw5_n17bw = 0x05
acc_d5bw7_n8bw3 = 0x06
acc_d473bw_n499bw = 0x07
# Gryo low pass filter configuration options
# Format is dAbwB_nXbwZ - A is integer part of 3db BW, B is fraction. X is integer part of nyquist bandwidth, Y is fraction
gyr_d196bw6_n229bw8 = 0x00
gyr_d151bw8_n187bw6 = 0x01
gyr_d119bw5_n154bw3 = 0x02
gyr_d51bw2_n73bw3 = 0x03
gyr_d23bw9_n35bw9 = 0x04
gyr_d11bw6_n17bw8 = 0x05
gyr_d5bw7_n8bw9 = 0x06
gyr_d361bw4_n376bw5 = 0x07
|
# Time: O(n)
# Space: O(1)
# 856
# Given a balanced parentheses string S,
# compute the score of the string based on the following rule:
#
# () has score 1
# AB has score A + B, where A and B are balanced parentheses strings.
# (A) has score 2 * A, where A is a balanced parentheses string.
#
# Example 1:
#
# Input: "()"
# Output: 1
# Example 2:
#
# Input: "(())"
# Output: 2
# Example 3:
#
# Input: "()()"
# Output: 2
# Example 4:
#
# Input: "(()(()))"
# Output: 6
#
# Note:
# - S is a balanced parentheses string, containing only ( and ).
# - 2 <= S.length <= 50
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
'''
Count Cores: USE THIS
Intuition
The final sum will be a sum of powers of 2, as every core (a substring (), with score 1=2**0) will have
it's score multiplied by 2 for each exterior set of parentheses that contains that core. The answer
is the sum of these multiplied core values (powers of 2).
Algorithm
Keep track of the DEPTH of the string (# of ( minus # of ) ). For every core ("()"),
the answer is 1 << depth, as depth is the number of exterior set of parentheses surrounding this core.
e.g. (()(())) equals to (())+((())); it contains 2 cores: first core then multiply 2^1,
second core then multiply 2^2.
'''
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
result, depth = 0, 0
for i in xrange(len(S)):
if S[i] == '(':
depth += 1
else:
depth -= 1
if S[i-1] == '(': # find a core
result += 2**depth
return result
# Time: O(n)
# Space: O(h) size of stack
'''
Every position in the string has a depth - some number of matching parentheses surrounding it. For example,
the dot in (()(.())) has depth 2, because of these parentheses: (__(.__))
Our goal is to maintain the score at the current depth we are on. When we see an opening bracket, we increase
our depth, and our score at the new depth is 0. When we see a closing bracket, we add twice the score of
the previous deeper part - except when counting (), which has a score of 1.
For example, when counting (()(())), our stack will look like this:
[0, 0] after parsing (
[0, 0, 0] after (
[0, 1] after )
[0, 1, 0] after (
[0, 1, 0, 0] after (
[0, 1, 1] after )
[0, 3] after )
[6] after )
'''
class Solution2(object):
def scoreOfParentheses(self, S: str) -> int: # Ming's stack
stk = []
for c in S:
if c == '(':
stk.append(c)
else:
# see ): pop stack, if (, push 1; if int, accumulate then multiplied by 2
n = 0
while stk[-1] != '(':
n += stk.pop()
stk.pop()
v = 2 * n if n > 0 else 1
stk.append(v)
return sum(stk)
# another stack implementation
def scoreOfParentheses2(self, S):
stack = [0]
for c in S:
if c == '(':
stack.append(0)
else:
last = stack.pop()
stack[-1] += max(1, 2*last)
return stack[0]
'''
Partition (Divide and Conquer)
Time Complexity: O(n^2), where n is the length of S. An example worst case is (((((((....))))))).
Space Complexity: O(n), the size of the implied call stack.
Intuition
Split the string into S = A + B where A and B are balanced parentheses strings, and A is the smallest possible
non-empty prefix of S.
Algorithm
Call a balanced string primitive if it cannot be partitioned into two non-empty balanced strings.
By partition whenever balance (the # of ( minus the number of ) ) is zero, we can partition S
into primitive substrings S = P_1 + P_2 + ... + P_n. Then, score(S) = score(P_1) + score(P_2) + ... + score(P_n), by definition.
For each primitive substring (S[i], S[i+1], ..., S[k]), if the string is length 2, then the score of this string
is 1. Otherwise, it's twice the score of the inner substring (S[i+1], S[i+2], ..., S[k-1]).
'''
class Solution3(object):
def scoreOfParentheses(self, S):
def F(i, j):
#Score of balanced string S[i:j]
ans = bal = 0
#Split string into primitives
for k in xrange(i, j):
bal += 1 if S[k] == '(' else -1
if bal == 0:
if k - i == 1:
ans += 1
else:
ans += 2 * F(i+1, k)
i = k+1
return ans
return F(0, len(S))
print(Solution().scoreOfParentheses("()")) #1
print(Solution().scoreOfParentheses("(())")) #2
print(Solution().scoreOfParentheses("()()")) #2
print(Solution().scoreOfParentheses("(()(()))")) #6
|
#########################
# Custom Error Classes
#########################
class LexerClass:
def __init__(self,lexicon,ukToken):
'''
Steps through rule strings searching for
high-level rule string components.
Searches for the following high-level tokens
in order:
- Reaction Token
- Constraint Token
- Entity Token
- Plurality Token (uncertainty)
- Logical AND/OR Tokens
'''
self.lexicon=lexicon
self.ukToken=ukToken
def search_cur_pos(self,inputString,idx):
'''
Finds matches at current position of inputString
using token library
'''
#Start reading rule string from current index:
inputString_frag=inputString[idx:]
#Search the current token libraries:
goodTokens=[]
for tok_c in self.lexicon:
try:
tok_i=tok_c(inputString_frag)
except:
continue
if tok_i.detectFun():
goodTokens.append(tok_i)
return(goodTokens)
def parseMain(self,inputString):
'''
Main method to parse rule string into a list of
tokens.
Uses ruleString input and increments along the
ruleString to identify tokens.
If no tokens are identified, the current index
is incremented by 1 until a match is found.
Portions of the rule string that aren't recognized
are returned as "unknownTokens". Warnings are
returned if this is the case.
'''
#Current index initialized to 0
idx=0
#Resolution flag: are we recognizing the string
# currently?
resolved=True
#Unknown location lists for error logging:
m_start=[]
m_end=[]
#Output Token List:
tokens=[]
while idx<len(inputString):
#Call the token search function:
tokList=self.search_cur_pos(inputString,idx)
# Confirm the token list has one
# element.
# - Cases where two tokens are matched
# will result in an error.
# - An empty list will trigger an
# increment of +1 to the current index:
if len(tokList)>1:
raise MultipleTokensError(idx,tokList)
elif len(tokList)==0:
#Catalog the position where no
# match was found:
# Increment by 1, then search again
if resolved==True:
m_start.append(idx)
resolved=False
idx+=1
else:
# If a match was found after
# not being resolved, set
# resolved to True and append
# the current index to the uk_end
# list.
if resolved is False:
resolved=True
m_end.append(idx)
if self.ukToken is not None:
tok=self.ukToken(inputString[m_start[-1]:m_end[-1]])
tokens.append(tok)
else:
tokens.append(None)
#Get matched token:
tok=tokList[0]
#Mark the match start:
m_start.append(idx)
#Get matched position using token matchFun method:
sch=tok.matchFun()
sch_end=sch.end()
### Branching check for 2nd stub:
# If the last added mono has left square bracket
# and current mono has right bracket, set the mono
# "isextendbranch" to "True"
#if len(tokens)>0:
# if tokens[-1].__name__=='reactionToken':
# if tok.token.__name__=='monoToken':
# if tokens[-1].token.ligand_token[0].token.branching['leftBracket'] and tok.token.branching['rightBracket']:
# tok.token.isextendbranch=True
#Append the found token to the token list:
tokens.append(tok)
#Mark the match end:
m_end.append(idx+sch_end)
#Increment starting position by
# distnace to the end of match
idx+=sch_end
#If uk_start has an index and uk_end
# is missing a paired index, means the
# end of the string was reached. End
# index is also unknown:
if len(m_start)>len(m_end):
m_end.append(idx)
tok=self.ukToken(inputString[m_start[-1]:m_end[-1]])
tokens.append(tok)
#If there were any unknown regions
# in the ruleString, raise a
# ruleStringParsingError.
#Otherwise, return the list of tokens
if None in tokens:
#Find where the None token is
# then report error:
missingLocs=[i for x,i in enumerate(tokens) if x is None]
uk_start,uk_end=[[m_start[i],m_end[i]] for i in missingLocs]
raise ruleStringParsingError(self.ruleString,uk_start,uk_end)
else:
return(tokens)
def __call__(self,inputString):
return(self.parseMain(inputString))
class MultipleTokensError(Exception):
def __init__(self,idx,toks):
self.index=idx
self.tokenList=toks
self.message="""Multiple tokens matched at position %d in ruleString.\nTokens: %s""" %(self.index,self.tokenList)
super().__init__(self.message)
class ruleStringParsingError(Exception):
def __init__(self,ruleString,uk_startList,uk_endList):
self.ruleString=ruleString
self.uk_start=uk_startList
self.uk_end=uk_endList
#Build message using interal method:
self.message=self.error_message()
super().__init__(self.message)
def error_message(self):
msg_top="Couldn\'t understand underlined parts of ruleString:"
msg_ruleString=self.ruleString
msg_error=self.error_underline()
msg='\n'.join([msg_top,'\n',msg_ruleString,msg_error])
return(msg)
def error_underline(self):
errorStringList=[' ']*len(self.ruleString)
for s,e in zip(self.uk_start,self.uk_end):
for i in range(s,e):
errorStringList[i]='~'
errorString=''.join(errorStringList)
return(errorString)
|
class DataTypeGenerator:
"""DataType生成器"""
def __init__(self, filename: str, prefix: str):
"""Constructor"""
self.filename: str = filename
self.prefix: str = prefix
self.count: int = 0
self.in_enum: bool = False
self.enum_value: int = 0
def run(self):
"""主函数"""
self.f_cpp = open(self.filename, "r", encoding="UTF-8")
self.f_define = open(f"{self.prefix}_constant.py", "w", encoding="UTF-8")
self.f_typedef = open(f"{self.prefix}_typedef.py", "w", encoding="UTF-8")
for line in self.f_cpp:
self.process_line(line)
self.f_cpp.close()
self.f_define.close()
self.f_typedef.close()
print("DataType生成完毕")
def process_line(self, line: str):
"""处理每行"""
line = line.replace("\n", "")
line = line.replace(";", "")
line = line.replace("\t", " ")
# 注释行
if line[:3] == "///":
return
# 常量定义
elif line.startswith("#define"):
self.process_define(line)
# 枚举定义
elif "enum" in line:
self.process_enum(line)
# 枚举结束
elif "}" in line:
self.in_enum = False
# 枚举内容
elif self.in_enum and "XTP_" in line:
self.process_content(line)
# 类型定义
elif line.startswith("typedef"):
self.process_typedef(line)
# # 枚举值内容
# elif "//<" in line:
# if "=" in line:
# name = line.split("=")[0].strip()
# elif "," in line:
# name = line.split(",")[0].strip()
# else:
# name = line.split("///")[0].strip()
# py_type = "int"
# new_line = f" \"{name}\": \"{py_type}\",\n"
# self.f_struct.write(new_line)
def process_enum(self, line: str):
"""处理枚举值定义"""
line = line.replace("\n", " ")
line = line.replace("\r", " ")
line = line.replace("typedef", "")
line = line.replace("{", "")
content = line.split(" ")
content = [c for c in content if c]
name = content[-1]
type_ = content[0]
new_line = f"{name} = \"{type_}\"\n"
self.f_typedef.write(new_line)
self.in_enum = True
def process_define(self, line: str):
"""处理常量定义"""
words = line.split(" ")
words = [word for word in words if word]
if len(words) < 3:
return
name = words[1]
value = words[2]
new_line = f"{name} = {value}\n"
self.f_define.write(new_line)
def process_typedef(self, line: str):
"""处理类型定义"""
word = line.split(" ")[2]
name = word.split("[")[0]
typedef = line.split(" ")[1]
new_line = f"{name} = \"{typedef}\"\n"
self.f_typedef.write(new_line)
def process_content(self, line: str):
"""处理枚举值内容"""
if "," in line:
line = line[:line.index(",")]
if "///" in line:
line = line[:line.index("///")]
line = line.replace(" ", "")
if "=" in line:
content = line.split("=")
name = content[0]
value = content[1]
self.enum_value = int(value)
else:
name = line
self.enum_value += 1
value = self.enum_value
new_line = f"{name} = {value}\n"
self.f_define.write(new_line)
if __name__ == "__main__":
generator = DataTypeGenerator("../include/xtp/xtp_api_data_type.h", "xtp")
generator.run()
|
#!/usr/bin/env python3
# Write a program that prints the reverse-complement of a DNA sequence
# You must use a loop and conditional
dna = 'ACTGAAAAAAAAAAA'
r = dna[::-1]
for i in range(len(r)):
a = r[i]
if a == 'A': print('T', end='')
elif a == 'C': print('G', end='')
elif a == 'T': print('A', end='')
elif a == 'G': print('C', end='')
"""
python3 23anti.py
TTTTTTTTTTTCAGT
"""
|
def chooseformat():
print("1.) fnamelname")
print("2.) fname.lname")
print("3.) fname_lname")
print("4.) finitlname")
print("5.) finit.lname")
print("6.) finit_lname")
print("7.) fname")
input("Choose a format to begin with: ")
|
info = {
"UNIT_NUMBERS": {
"nul": 0,
"nulste": 0,
"een": 1,
"eerste": 1,
"twee": 2,
"tweede": 2,
"derde": 3,
"drie": 3,
"vier": 4,
"vijf": 5,
"zes": 6,
"zeven": 7,
"acht": 8,
"negen": 9
},
"DIRECT_NUMBERS": {
"tien": 10,
"elf": 11,
"twaalf": 12,
"dertien": 13,
"veertien": 14,
"vijftien": 15,
"zestien": 16,
"zeventien": 17,
"achttien": 18,
"negentien": 19
},
"TENS": {},
"HUNDREDS": {},
"BIG_POWERS_OF_TEN": {
"miljoen": 1000000,
"miljard": 1000000000,
"biljoen": 1000000000000,
"biljard": 1000000000000000
},
"SKIP_TOKENS": [],
"USE_LONG_SCALE": True
}
|
class Director(object):
def __init__(self, builder):
self._builder = builder
def build_computer(self):
self._builder.new_computer()
self._builder.get_case()
self._builder.build_mainboard()
self._builder.install_mainboard()
self._builder.install_hard_drive()
self._builder.install_video_card()
def get_computer(self):
return self._builder.get_computer()
|
#4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y.
# Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
# Подсказка: попробуйте решить задачу двумя способами.
# Первый — возведение в степень с помощью оператора **.
# Второй — более сложная реализация без оператора **, предусматривающая использование цикла.
def my_func(x, y):
res = x*1
for i in range(abs(y)-1):
res = res * x
if(y < 0):
res = 1/res
return res
print("Привет, эта программа возводит x в степень y")
print("Введите 2 числа через пробел, затем Enter\n")
while True:
a=input("Введите 2 числа или Enter для завершения: ")
if(len(a) == 0):
break
list=a.split(" ")
if(len(list) == 2):
f_x = float(list[0])
int_y = int(list[1])
res = my_func(f_x, int_y)
print(res)
continue
|
#openfi
#escape char in the olxlo produced file will need substitute at later date
#for runtime on the second loop of instantiation self.populate
dxpone = {
"name":"dxpone",
"refapione":"dxponeapione --- Hi and welcome to the text case scenario that will be used to insert \
towards a discord or something similar to justify the text that will be written t it as an extsion \
for demonstaration purposes that will become more prevelant in the future useages of this written programme",
"refapitwo":"dxponeapitwo",
"com":["""###codeblockhere###"""]
}
#closefi
|
a=2
if a<0:
print("the number is negative")
if a>0:
print("the numner is positive")
|
class Item():
def __init__(self, name, description):
# name and description
self.name = name
self.description = description
def __str__(self):
# print item's name and description
return f"{self.name}: {self.description}"
|
#####1. Write e Python program to create e set.
# e=set()
# print(type(e))
####################################################
####2. Write e Python program to iteration over sets.
# e={'e','b','c','t'}
# for i in e:
# print(i)
####################################################
###3. Write e Python program to add member(s) in e set.
# e={344,434,43,43,44}
# b={3124,4,34,34,3,43,43,4,4}
# e.union(b)
# y=e.update(b)
# e.add(True)
# print(e)
# print(y)
################################################################333
####4. Write e Python program to remove item(s) from e given set.
# e={222222,344,534534,455555,554534,3534,44}
# e.remove('sajv')
# e.discard(False)
# e.pop()
# print(e)
################################################################
#####5. Write e Python program to remove an item from e set if it is present in the set.
# e={222222,344,534534,455555,554534,3534,44}
# e.remove(44)
# e.pop()
# print(e)
################################################################
#####6. Write e Python program to create an intersection of sets.
# e={344,434,43,43,44,True}
# b={3124,4,34,34,3,43,43,4,4,True,False}
# print(b.intersection(e))
###############################################################
#####7. Write e Python program to create e union of sets.
# e={344,434,43,43,44,True}
# b={3124,4,34,34,3,43,43,4,4,True,False}
# x=e.union(b)
# print(x)
###############################################################
######8. Write e Python program to create set difference.
# e={344,434,43,43,44,True}
# b={3124,4,34,34,3,43,43,4,4,True,False}
# print(e.difference(b))
# print(b.difference(e))
###############################################################
####9. Write e Python program to create e symmetric difference.
# e={344,434,43,43,44,True,False}
# b={3124,4,34,34,3,43,43,4,4,True,False}
# print(e.symmetric_difference(b))
###############################################################
####10. Write e Python program to checv if e set is e subset of another set.
# e={344,434,43,43,44,True,False}
# b={3124,4,34,34,3,43,43,4,4,True,False}
# print(b.issubset(e))
###############################################################
####11. Write e Python program to create e shallow copy of sets.
# e={344,434,43,43,44,True,False}
# b=e.copy()
# print(b)
###############################################################
#####12. Write e Python program to remove all elements from e given set.
# e={344,434,43,43,44,True,False}
# print(e.clear())
###############################################################
#####13. Write e Python program to use of frozensets.
e=frozenset((358,434,53344,33442,423,42))
print(e)
###############################################################
######14. Write e Python program to find maximum and the minimum value in e set.
# e={358,434,53344,33442889,423,42,42,42}
# s=0
# for i in e:
# if i>s:
# s=i
# print(s)
###############################################################
####15. Write e Python program to find the length of e set
e={358,434,53344,33442889,423,42,42,42}
print(len(e))
###############################################################
######16. Write e Python program to checv if e given value is present in e set or not.
|
# DFS
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.check(root.left, root.right)
def check(self, Node1, Node2):
if Node1 == None and Node2 == None:
return True
if Node1 == None or Node2 == None:
return False
return Node1.val == Node2.val and self.check(Node1.left, Node2.right) and self.check(Node1.right, Node2.left)
'''
or
'''
# BFS
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
queue = []
if not root:
return True
queue.append(root.left)
queue.append(root.right)
while queue:
left_node = queue.pop(0)
right_node = queue.pop(0)
if not left_node and not right_node:
continue
if not left_node or not right_node:
return False
if left_node.val != right_node.val:
return False
queue.append(left_node.left,)
queue.append(right_node.right)
queue.append(left_node.right)
queue.append(right_node.left)
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.