content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def calculation(filepath,down,across):
with open(filepath) as file:
rows = [x.strip() for x in file.readlines()]
end = len(rows)
currentrow = 0
currentcolumn = 0
count = 0
while currentrow < (end-1):
currentrow = currentrow+down
currentcolumn = (currentcolumn+across)%len(rows[0])
if rows[currentrow][currentcolumn] == "#":
count+=1
return count
def main(filepath):
a = calculation(filepath,1,1)
b = calculation(filepath,1,3)
c = calculation(filepath,1,5)
d = calculation(filepath,1,7)
e = calculation(filepath,2,1)
print("Part a solution: "+ str(b))
print("Part b solution: "+ str(a*b*c*d*e))
return
| def calculation(filepath, down, across):
with open(filepath) as file:
rows = [x.strip() for x in file.readlines()]
end = len(rows)
currentrow = 0
currentcolumn = 0
count = 0
while currentrow < end - 1:
currentrow = currentrow + down
currentcolumn = (currentcolumn + across) % len(rows[0])
if rows[currentrow][currentcolumn] == '#':
count += 1
return count
def main(filepath):
a = calculation(filepath, 1, 1)
b = calculation(filepath, 1, 3)
c = calculation(filepath, 1, 5)
d = calculation(filepath, 1, 7)
e = calculation(filepath, 2, 1)
print('Part a solution: ' + str(b))
print('Part b solution: ' + str(a * b * c * d * e))
return |
class Student:
def __init__(self, firstname, lastname, major, gpa):
self.firstname = firstname
self.lastname = lastname
self.major = major
self.gpa = gpa
@property # property decorator # access this method as an attribute
def fullname(self):
return f'{self.firstname} {self.lastname}'
@fullname.setter # setter decorator # set the attribute
def fullname(self, fullname):
first, last = fullname.split(' ')
self.firstname = firstname
self.lastname = lastname
@fullname.deleter # deleter decorator # set an attribute to None
def fullname(self):
self.firstname = None
self.lastname = None
| class Student:
def __init__(self, firstname, lastname, major, gpa):
self.firstname = firstname
self.lastname = lastname
self.major = major
self.gpa = gpa
@property
def fullname(self):
return f'{self.firstname} {self.lastname}'
@fullname.setter
def fullname(self, fullname):
(first, last) = fullname.split(' ')
self.firstname = firstname
self.lastname = lastname
@fullname.deleter
def fullname(self):
self.firstname = None
self.lastname = None |
{
"targets": [
{
"target_name": "simpleTest",
"sources": [ "simpleTest.cc" ]
},
{
"target_name": "simpleTest2",
"sources": [ "simpleTest.cc" ]
},
{
"target_name": "simpleTest3",
"sources": [ "simpleTest.cc" ]
}
]
} | {'targets': [{'target_name': 'simpleTest', 'sources': ['simpleTest.cc']}, {'target_name': 'simpleTest2', 'sources': ['simpleTest.cc']}, {'target_name': 'simpleTest3', 'sources': ['simpleTest.cc']}]} |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 12700.py
# Description: UVa Online Judge - 12700
# =============================================================================
def run():
N = int(input())
line = input()
countB = sum(map(lambda x: x == "B", line))
countW = sum(map(lambda x: x == "W", line))
countT = sum(map(lambda x: x == "T", line))
if countT == 0 and countW == 0 and countB == 0:
print("ABANDONED")
elif countT == 0 and countW == 0 and countB:
print("BANGLAWASH")
elif countT == 0 and countB == 0 and countW:
print("WHITEWASH")
elif countW == countB:
print("DRAW {} {}".format(countW, countT))
elif countW > countB:
print("WWW {} - {}".format(countW, countB))
else:
print("BANGLADESH {} - {}".format(countB, countW))
if __name__ == "__main__":
T = int(input())
for i in range(T):
print("Case {}: ".format(i + 1), end="")
run()
| def run():
n = int(input())
line = input()
count_b = sum(map(lambda x: x == 'B', line))
count_w = sum(map(lambda x: x == 'W', line))
count_t = sum(map(lambda x: x == 'T', line))
if countT == 0 and countW == 0 and (countB == 0):
print('ABANDONED')
elif countT == 0 and countW == 0 and countB:
print('BANGLAWASH')
elif countT == 0 and countB == 0 and countW:
print('WHITEWASH')
elif countW == countB:
print('DRAW {} {}'.format(countW, countT))
elif countW > countB:
print('WWW {} - {}'.format(countW, countB))
else:
print('BANGLADESH {} - {}'.format(countB, countW))
if __name__ == '__main__':
t = int(input())
for i in range(T):
print('Case {}: '.format(i + 1), end='')
run() |
DEBUG = True
PORT = 5000
UPLOAD_FOLDER = 'sacapp/static/tmp'
MODEL_FOLDER = 'model/'
DRUG2ID_FILE = 'model/drug2id.txt'
GENE2ID_FILE = 'model/gene2idx.txt'
IC50_DRUGS_FILE = 'model/ic50_drugid.txt'
IC50_DRUG2ID_FILE = 'model/ic50_drug2idx.txt'
IC50_GENES_FILE = 'model/ic50_genes.txt'
PERT_DRUGS_FILE = 'model/pert_drugid.txt'
PERT_DRUG2ID_FILE = 'model/pert_drug2idx.txt'
CCLE_RPKM_FILE = 'model/ccle_rpkm.csv'
CELL_LINES_FILE = 'model/cell_lines.txt'
GDSC_FILE = 'model/ccle_gdsc.csv'
| debug = True
port = 5000
upload_folder = 'sacapp/static/tmp'
model_folder = 'model/'
drug2_id_file = 'model/drug2id.txt'
gene2_id_file = 'model/gene2idx.txt'
ic50_drugs_file = 'model/ic50_drugid.txt'
ic50_drug2_id_file = 'model/ic50_drug2idx.txt'
ic50_genes_file = 'model/ic50_genes.txt'
pert_drugs_file = 'model/pert_drugid.txt'
pert_drug2_id_file = 'model/pert_drug2idx.txt'
ccle_rpkm_file = 'model/ccle_rpkm.csv'
cell_lines_file = 'model/cell_lines.txt'
gdsc_file = 'model/ccle_gdsc.csv' |
"""Advent of Code 2019 Day 1."""
def main(file_input='input.txt'):
masses = [int(num.strip()) for num in get_file_contents(file_input)]
needed_fuel = get_needed_fuel(masses, module_fuel)
print(f'Fuel requirement: {needed_fuel}')
needed_fuel_with_fuel_mass = get_needed_fuel(masses, module_fuel_with_fuel)
print('Fuel requirement, including mass of the added fuel '
f'{needed_fuel_with_fuel_mass}')
def get_needed_fuel(masses, fuel_calculator):
"""Get needed fuel for masses using fuel_calculator function."""
return sum(fuel_calculator(mass) for mass in masses)
def module_fuel(mass):
"""Calculate needed fuel for mass."""
return mass // 3 - 2
def module_fuel_with_fuel(mass):
"""Calculate needed fuel for mass, including fuel mass."""
total_fuel = 0
while mass > 0:
mass = module_fuel(mass)
total_fuel += mass if mass > 0 else 0
return total_fuel
def get_file_contents(file):
"""Read all lines from file."""
with open(file) as f:
return f.readlines()
if __name__ == '__main__':
main()
| """Advent of Code 2019 Day 1."""
def main(file_input='input.txt'):
masses = [int(num.strip()) for num in get_file_contents(file_input)]
needed_fuel = get_needed_fuel(masses, module_fuel)
print(f'Fuel requirement: {needed_fuel}')
needed_fuel_with_fuel_mass = get_needed_fuel(masses, module_fuel_with_fuel)
print(f'Fuel requirement, including mass of the added fuel {needed_fuel_with_fuel_mass}')
def get_needed_fuel(masses, fuel_calculator):
"""Get needed fuel for masses using fuel_calculator function."""
return sum((fuel_calculator(mass) for mass in masses))
def module_fuel(mass):
"""Calculate needed fuel for mass."""
return mass // 3 - 2
def module_fuel_with_fuel(mass):
"""Calculate needed fuel for mass, including fuel mass."""
total_fuel = 0
while mass > 0:
mass = module_fuel(mass)
total_fuel += mass if mass > 0 else 0
return total_fuel
def get_file_contents(file):
"""Read all lines from file."""
with open(file) as f:
return f.readlines()
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Point of Sale',
'version': '1.0.1',
'category': 'Sales/Point of Sale',
'sequence': 40,
'summary': 'User-friendly PoS interface for shops and restaurants',
'description': "",
'depends': ['stock_account', 'barcodes', 'web_editor', 'digest'],
'data': [
'security/point_of_sale_security.xml',
'security/ir.model.access.csv',
'data/default_barcode_patterns.xml',
'data/digest_data.xml',
'wizard/pos_box.xml',
'wizard/pos_details.xml',
'wizard/pos_payment.xml',
'views/pos_assets_common.xml',
'views/pos_assets_index.xml',
'views/pos_assets_qunit.xml',
'views/point_of_sale_report.xml',
'views/point_of_sale_view.xml',
'views/pos_order_view.xml',
'views/pos_category_view.xml',
'views/product_view.xml',
'views/account_journal_view.xml',
'views/pos_payment_method_views.xml',
'views/pos_payment_views.xml',
'views/pos_config_view.xml',
'views/pos_session_view.xml',
'views/point_of_sale_sequence.xml',
'views/customer_facing_display.xml',
'data/point_of_sale_data.xml',
'views/pos_order_report_view.xml',
'views/account_statement_view.xml',
'views/res_config_settings_views.xml',
'views/digest_views.xml',
'views/res_partner_view.xml',
'views/report_userlabel.xml',
'views/report_saledetails.xml',
'views/point_of_sale_dashboard.xml',
],
'demo': [
'data/point_of_sale_demo.xml',
],
'installable': True,
'application': True,
'qweb': [
'static/src/xml/Chrome.xml',
'static/src/xml/debug_manager.xml',
'static/src/xml/Screens/ProductScreen/ProductScreen.xml',
'static/src/xml/Screens/ClientListScreen/ClientLine.xml',
'static/src/xml/Screens/ClientListScreen/ClientDetailsEdit.xml',
'static/src/xml/Screens/ClientListScreen/ClientListScreen.xml',
'static/src/xml/Screens/OrderManagementScreen/ControlButtons/InvoiceButton.xml',
'static/src/xml/Screens/OrderManagementScreen/ControlButtons/ReprintReceiptButton.xml',
'static/src/xml/Screens/OrderManagementScreen/OrderManagementScreen.xml',
'static/src/xml/Screens/OrderManagementScreen/MobileOrderManagementScreen.xml',
'static/src/xml/Screens/OrderManagementScreen/OrderManagementControlPanel.xml',
'static/src/xml/Screens/OrderManagementScreen/OrderList.xml',
'static/src/xml/Screens/OrderManagementScreen/OrderRow.xml',
'static/src/xml/Screens/OrderManagementScreen/OrderDetails.xml',
'static/src/xml/Screens/OrderManagementScreen/OrderlineDetails.xml',
'static/src/xml/Screens/OrderManagementScreen/ReprintReceiptScreen.xml',
'static/src/xml/Screens/TicketScreen/TicketScreen.xml',
'static/src/xml/Screens/PaymentScreen/PSNumpadInputButton.xml',
'static/src/xml/Screens/PaymentScreen/PaymentScreenNumpad.xml',
'static/src/xml/Screens/PaymentScreen/PaymentScreenElectronicPayment.xml',
'static/src/xml/Screens/PaymentScreen/PaymentScreenPaymentLines.xml',
'static/src/xml/Screens/PaymentScreen/PaymentScreenStatus.xml',
'static/src/xml/Screens/PaymentScreen/PaymentMethodButton.xml',
'static/src/xml/Screens/PaymentScreen/PaymentScreen.xml',
'static/src/xml/Screens/ProductScreen/Orderline.xml',
'static/src/xml/Screens/ProductScreen/OrderSummary.xml',
'static/src/xml/Screens/ProductScreen/OrderWidget.xml',
'static/src/xml/Screens/ProductScreen/NumpadWidget.xml',
'static/src/xml/Screens/ProductScreen/ActionpadWidget.xml',
'static/src/xml/Screens/ProductScreen/CategoryBreadcrumb.xml',
'static/src/xml/Screens/ProductScreen/CashBoxOpening.xml',
'static/src/xml/Screens/ProductScreen/CategoryButton.xml',
'static/src/xml/Screens/ProductScreen/CategorySimpleButton.xml',
'static/src/xml/Screens/ProductScreen/HomeCategoryBreadcrumb.xml',
'static/src/xml/Screens/ProductScreen/ProductsWidgetControlPanel.xml',
'static/src/xml/Screens/ProductScreen/ProductItem.xml',
'static/src/xml/Screens/ProductScreen/ProductList.xml',
'static/src/xml/Screens/ProductScreen/ProductsWidget.xml',
'static/src/xml/Screens/ReceiptScreen/WrappedProductNameLines.xml',
'static/src/xml/Screens/ReceiptScreen/OrderReceipt.xml',
'static/src/xml/Screens/ReceiptScreen/ReceiptScreen.xml',
'static/src/xml/Screens/ScaleScreen/ScaleScreen.xml',
'static/src/xml/ChromeWidgets/CashierName.xml',
'static/src/xml/ChromeWidgets/ProxyStatus.xml',
'static/src/xml/ChromeWidgets/SyncNotification.xml',
'static/src/xml/ChromeWidgets/OrderManagementButton.xml',
'static/src/xml/ChromeWidgets/HeaderButton.xml',
'static/src/xml/ChromeWidgets/SaleDetailsButton.xml',
'static/src/xml/ChromeWidgets/TicketButton.xml',
'static/src/xml/SaleDetailsReport.xml',
'static/src/xml/Misc/Draggable.xml',
'static/src/xml/Misc/NotificationSound.xml',
'static/src/xml/Misc/SearchBar.xml',
'static/src/xml/ChromeWidgets/DebugWidget.xml',
'static/src/xml/Popups/ErrorPopup.xml',
'static/src/xml/Popups/ErrorBarcodePopup.xml',
'static/src/xml/Popups/ConfirmPopup.xml',
'static/src/xml/Popups/TextInputPopup.xml',
'static/src/xml/Popups/TextAreaPopup.xml',
'static/src/xml/Popups/ErrorTracebackPopup.xml',
'static/src/xml/Popups/SelectionPopup.xml',
'static/src/xml/Popups/EditListInput.xml',
'static/src/xml/Popups/EditListPopup.xml',
'static/src/xml/Popups/NumberPopup.xml',
'static/src/xml/Popups/OfflineErrorPopup.xml',
'static/src/xml/Popups/OrderImportPopup.xml',
'static/src/xml/Popups/ProductConfiguratorPopup.xml',
'static/src/xml/Screens/ProductScreen/ControlButtons/SetPricelistButton.xml',
'static/src/xml/Screens/ProductScreen/ControlButtons/SetFiscalPositionButton.xml',
'static/src/xml/ChromeWidgets/ClientScreenButton.xml',
'static/src/xml/Misc/MobileOrderWidget.xml',
],
'website': 'https://www.odoo.com/page/point-of-sale-shop',
'license': 'LGPL-3',
}
| {'name': 'Point of Sale', 'version': '1.0.1', 'category': 'Sales/Point of Sale', 'sequence': 40, 'summary': 'User-friendly PoS interface for shops and restaurants', 'description': '', 'depends': ['stock_account', 'barcodes', 'web_editor', 'digest'], 'data': ['security/point_of_sale_security.xml', 'security/ir.model.access.csv', 'data/default_barcode_patterns.xml', 'data/digest_data.xml', 'wizard/pos_box.xml', 'wizard/pos_details.xml', 'wizard/pos_payment.xml', 'views/pos_assets_common.xml', 'views/pos_assets_index.xml', 'views/pos_assets_qunit.xml', 'views/point_of_sale_report.xml', 'views/point_of_sale_view.xml', 'views/pos_order_view.xml', 'views/pos_category_view.xml', 'views/product_view.xml', 'views/account_journal_view.xml', 'views/pos_payment_method_views.xml', 'views/pos_payment_views.xml', 'views/pos_config_view.xml', 'views/pos_session_view.xml', 'views/point_of_sale_sequence.xml', 'views/customer_facing_display.xml', 'data/point_of_sale_data.xml', 'views/pos_order_report_view.xml', 'views/account_statement_view.xml', 'views/res_config_settings_views.xml', 'views/digest_views.xml', 'views/res_partner_view.xml', 'views/report_userlabel.xml', 'views/report_saledetails.xml', 'views/point_of_sale_dashboard.xml'], 'demo': ['data/point_of_sale_demo.xml'], 'installable': True, 'application': True, 'qweb': ['static/src/xml/Chrome.xml', 'static/src/xml/debug_manager.xml', 'static/src/xml/Screens/ProductScreen/ProductScreen.xml', 'static/src/xml/Screens/ClientListScreen/ClientLine.xml', 'static/src/xml/Screens/ClientListScreen/ClientDetailsEdit.xml', 'static/src/xml/Screens/ClientListScreen/ClientListScreen.xml', 'static/src/xml/Screens/OrderManagementScreen/ControlButtons/InvoiceButton.xml', 'static/src/xml/Screens/OrderManagementScreen/ControlButtons/ReprintReceiptButton.xml', 'static/src/xml/Screens/OrderManagementScreen/OrderManagementScreen.xml', 'static/src/xml/Screens/OrderManagementScreen/MobileOrderManagementScreen.xml', 'static/src/xml/Screens/OrderManagementScreen/OrderManagementControlPanel.xml', 'static/src/xml/Screens/OrderManagementScreen/OrderList.xml', 'static/src/xml/Screens/OrderManagementScreen/OrderRow.xml', 'static/src/xml/Screens/OrderManagementScreen/OrderDetails.xml', 'static/src/xml/Screens/OrderManagementScreen/OrderlineDetails.xml', 'static/src/xml/Screens/OrderManagementScreen/ReprintReceiptScreen.xml', 'static/src/xml/Screens/TicketScreen/TicketScreen.xml', 'static/src/xml/Screens/PaymentScreen/PSNumpadInputButton.xml', 'static/src/xml/Screens/PaymentScreen/PaymentScreenNumpad.xml', 'static/src/xml/Screens/PaymentScreen/PaymentScreenElectronicPayment.xml', 'static/src/xml/Screens/PaymentScreen/PaymentScreenPaymentLines.xml', 'static/src/xml/Screens/PaymentScreen/PaymentScreenStatus.xml', 'static/src/xml/Screens/PaymentScreen/PaymentMethodButton.xml', 'static/src/xml/Screens/PaymentScreen/PaymentScreen.xml', 'static/src/xml/Screens/ProductScreen/Orderline.xml', 'static/src/xml/Screens/ProductScreen/OrderSummary.xml', 'static/src/xml/Screens/ProductScreen/OrderWidget.xml', 'static/src/xml/Screens/ProductScreen/NumpadWidget.xml', 'static/src/xml/Screens/ProductScreen/ActionpadWidget.xml', 'static/src/xml/Screens/ProductScreen/CategoryBreadcrumb.xml', 'static/src/xml/Screens/ProductScreen/CashBoxOpening.xml', 'static/src/xml/Screens/ProductScreen/CategoryButton.xml', 'static/src/xml/Screens/ProductScreen/CategorySimpleButton.xml', 'static/src/xml/Screens/ProductScreen/HomeCategoryBreadcrumb.xml', 'static/src/xml/Screens/ProductScreen/ProductsWidgetControlPanel.xml', 'static/src/xml/Screens/ProductScreen/ProductItem.xml', 'static/src/xml/Screens/ProductScreen/ProductList.xml', 'static/src/xml/Screens/ProductScreen/ProductsWidget.xml', 'static/src/xml/Screens/ReceiptScreen/WrappedProductNameLines.xml', 'static/src/xml/Screens/ReceiptScreen/OrderReceipt.xml', 'static/src/xml/Screens/ReceiptScreen/ReceiptScreen.xml', 'static/src/xml/Screens/ScaleScreen/ScaleScreen.xml', 'static/src/xml/ChromeWidgets/CashierName.xml', 'static/src/xml/ChromeWidgets/ProxyStatus.xml', 'static/src/xml/ChromeWidgets/SyncNotification.xml', 'static/src/xml/ChromeWidgets/OrderManagementButton.xml', 'static/src/xml/ChromeWidgets/HeaderButton.xml', 'static/src/xml/ChromeWidgets/SaleDetailsButton.xml', 'static/src/xml/ChromeWidgets/TicketButton.xml', 'static/src/xml/SaleDetailsReport.xml', 'static/src/xml/Misc/Draggable.xml', 'static/src/xml/Misc/NotificationSound.xml', 'static/src/xml/Misc/SearchBar.xml', 'static/src/xml/ChromeWidgets/DebugWidget.xml', 'static/src/xml/Popups/ErrorPopup.xml', 'static/src/xml/Popups/ErrorBarcodePopup.xml', 'static/src/xml/Popups/ConfirmPopup.xml', 'static/src/xml/Popups/TextInputPopup.xml', 'static/src/xml/Popups/TextAreaPopup.xml', 'static/src/xml/Popups/ErrorTracebackPopup.xml', 'static/src/xml/Popups/SelectionPopup.xml', 'static/src/xml/Popups/EditListInput.xml', 'static/src/xml/Popups/EditListPopup.xml', 'static/src/xml/Popups/NumberPopup.xml', 'static/src/xml/Popups/OfflineErrorPopup.xml', 'static/src/xml/Popups/OrderImportPopup.xml', 'static/src/xml/Popups/ProductConfiguratorPopup.xml', 'static/src/xml/Screens/ProductScreen/ControlButtons/SetPricelistButton.xml', 'static/src/xml/Screens/ProductScreen/ControlButtons/SetFiscalPositionButton.xml', 'static/src/xml/ChromeWidgets/ClientScreenButton.xml', 'static/src/xml/Misc/MobileOrderWidget.xml'], 'website': 'https://www.odoo.com/page/point-of-sale-shop', 'license': 'LGPL-3'} |
BASE_URL = 'https://www.instagram.com/'
LOGIN_URL = BASE_URL + 'accounts/login/ajax/'
LOGOUT_URL = BASE_URL + 'accounts/logout/'
MEDIA_URL = BASE_URL + '{0}/media'
STORIES_URL = 'https://i.instagram.com/api/v1/feed/user/{0}/reel_media/'
STORIES_UA = 'Instagram 9.5.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.00; 750x1334) AppleWebKit/420+'
STORIES_COOKIE = 'ds_user_id={0}; sessionid={1};'
TAGS_URL = BASE_URL + 'explore/tags/{0}/?__a=1'
LOCATIONS_URL = BASE_URL + 'explore/locations/{0}/?__a=1'
QUERY_URL = BASE_URL + 'query/'
VIEW_MEDIA_URL = BASE_URL + 'p/{0}/?__a=1'
QUERY_HASHTAG = ' '.join("""
ig_hashtag(%s) {
media.after(%s, 50) {
count,
nodes {
caption,
code,
comments {
count
},
comments_disabled,
date,
dimensions {
height,
width
},
display_src,
id,
is_video,
likes {
count
},
owner {
id
},
thumbnail_src,
video_views
},
page_info
}
}
""".split())
QUERY_LOCATION = ' '.join("""
ig_location(%s) {
media.after(%s, 50) {
count,
nodes {
caption,
code,
comments {
count
},
comments_disabled,
date,
dimensions {
height,
width
},
display_src,
id,
is_video,
likes {
count
},
owner {
id
},
thumbnail_src,
video_views
},
page_info
}
}
""".split())
SEARCH_URL = BASE_URL + 'web/search/topsearch/?context=blended&query={0}'
QUERY_COMMENTS = BASE_URL + 'graphql/query/?query_id=17852405266163336&first=100&shortcode={0}&after={1}'
| base_url = 'https://www.instagram.com/'
login_url = BASE_URL + 'accounts/login/ajax/'
logout_url = BASE_URL + 'accounts/logout/'
media_url = BASE_URL + '{0}/media'
stories_url = 'https://i.instagram.com/api/v1/feed/user/{0}/reel_media/'
stories_ua = 'Instagram 9.5.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.00; 750x1334) AppleWebKit/420+'
stories_cookie = 'ds_user_id={0}; sessionid={1};'
tags_url = BASE_URL + 'explore/tags/{0}/?__a=1'
locations_url = BASE_URL + 'explore/locations/{0}/?__a=1'
query_url = BASE_URL + 'query/'
view_media_url = BASE_URL + 'p/{0}/?__a=1'
query_hashtag = ' '.join('\n ig_hashtag(%s) { \n media.after(%s, 50) {\n count,\n nodes {\n caption,\n code,\n comments {\n count\n },\n comments_disabled,\n date,\n dimensions {\n height,\n width\n },\n display_src,\n id,\n is_video,\n likes {\n count\n },\n owner {\n id\n },\n thumbnail_src,\n video_views\n },\n page_info\n } \n }\n '.split())
query_location = ' '.join('\n ig_location(%s) {\n media.after(%s, 50) {\n count,\n nodes {\n caption,\n code,\n comments {\n count\n },\n comments_disabled,\n date,\n dimensions {\n height,\n width\n },\n display_src,\n id,\n is_video,\n likes {\n count\n },\n owner {\n id\n },\n thumbnail_src,\n video_views\n },\n page_info\n }\n }\n '.split())
search_url = BASE_URL + 'web/search/topsearch/?context=blended&query={0}'
query_comments = BASE_URL + 'graphql/query/?query_id=17852405266163336&first=100&shortcode={0}&after={1}' |
class Problem(Exception):
"""
User-visible exception
"""
def __init__(self, message, code=None, icon=':exclamation:'):
"""
:param message: The error message
:type message: str
:param code: An internal error code, for ease of testing
:type code: str|None
:param icon: The slack emoji to prepend to the message
:type icon: str
"""
super(Problem, self).__init__(message)
self.code = code
self.icon = icon
def as_slack(self):
return "%s %s" % (
self.icon,
str(self),
)
| class Problem(Exception):
"""
User-visible exception
"""
def __init__(self, message, code=None, icon=':exclamation:'):
"""
:param message: The error message
:type message: str
:param code: An internal error code, for ease of testing
:type code: str|None
:param icon: The slack emoji to prepend to the message
:type icon: str
"""
super(Problem, self).__init__(message)
self.code = code
self.icon = icon
def as_slack(self):
return '%s %s' % (self.icon, str(self)) |
"""
Binary search in list.
List must be sorted.
speed - O(log2N)
"""
def binary_search(a, key):
"""
a - sorted list
key - value for search
returs: index or None
"""
left = 0
right = len(a)
while left < right:
middle = (left + right) // 2
if key < a[middle]:
right = middle
elif key > a[middle]:
left = middle + 1
else:
return middle
return None
def test_binary_search():
""" Tests """
assert(binary_search([1, 2, 3, 4, 5, 6, 7, 8], 4) == 3)
if __name__ == '__main__':
print('Binary search of 8 in list [1, 2, 3, 4, 5, 6, 7, 8]. Index is ', binary_search([1, 2, 3, 4, 5, 6, 7, 8], 8))
| """
Binary search in list.
List must be sorted.
speed - O(log2N)
"""
def binary_search(a, key):
"""
a - sorted list
key - value for search
returs: index or None
"""
left = 0
right = len(a)
while left < right:
middle = (left + right) // 2
if key < a[middle]:
right = middle
elif key > a[middle]:
left = middle + 1
else:
return middle
return None
def test_binary_search():
""" Tests """
assert binary_search([1, 2, 3, 4, 5, 6, 7, 8], 4) == 3
if __name__ == '__main__':
print('Binary search of 8 in list [1, 2, 3, 4, 5, 6, 7, 8]. Index is ', binary_search([1, 2, 3, 4, 5, 6, 7, 8], 8)) |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Dexter Scott Belmont"
__credits__ = [ "Dexter Scott Belmont" ]
__tags__ = [ "Maya", "Virus", "Removal" ]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Dexter Scott Belmont"
__email__ = "dexter@kerneloid.com"
__status__ = "alpha"
#jobs = cmds.scriptJob(lj=True)
#for job in jobs:
found = False
for job in cmds.scriptJob( lj=True ) :
if "leukocyte.antivirus()" in job :
id = job.split( ":" )[ 0 ]
if id.isdigit() :
cmds.scriptJob( k=int(id), f=True )
if found == False :
found = True
print( "Virus Found" )
script_nodes = cmds.ls( "vaccine_gene", type="script" )
if script_nodes :
if found == False :
found = True
print( "Virus Found" )
cmds.delete( script_nodes ) | __author__ = 'Dexter Scott Belmont'
__credits__ = ['Dexter Scott Belmont']
__tags__ = ['Maya', 'Virus', 'Removal']
__license__ = 'MIT'
__version__ = '0.1'
__maintainer__ = 'Dexter Scott Belmont'
__email__ = 'dexter@kerneloid.com'
__status__ = 'alpha'
found = False
for job in cmds.scriptJob(lj=True):
if 'leukocyte.antivirus()' in job:
id = job.split(':')[0]
if id.isdigit():
cmds.scriptJob(k=int(id), f=True)
if found == False:
found = True
print('Virus Found')
script_nodes = cmds.ls('vaccine_gene', type='script')
if script_nodes:
if found == False:
found = True
print('Virus Found')
cmds.delete(script_nodes) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 17:21:13 2018
@author: gykovacs
"""
__version__= '0.3.0' | """
Created on Fri Dec 28 17:21:13 2018
@author: gykovacs
"""
__version__ = '0.3.0' |
__all__ = ['Mine']
class Mine(object):
'''A mine object.
Attributes:
x (int): the mine position in X.
y (int): the mine position in Y.
owner (int): the hero's id that owns this mine.
'''
def __init__(self, x, y):
'''Constructor.
Args:
x (int): the mine position in X.
y (int): the mine position in Y.
'''
self.x = x
self.y = y
self.owner = None
| __all__ = ['Mine']
class Mine(object):
"""A mine object.
Attributes:
x (int): the mine position in X.
y (int): the mine position in Y.
owner (int): the hero's id that owns this mine.
"""
def __init__(self, x, y):
"""Constructor.
Args:
x (int): the mine position in X.
y (int): the mine position in Y.
"""
self.x = x
self.y = y
self.owner = None |
INVALID_EMAIL = "invalid_email"
INVALID_EMAIL_CHANGE = "invalid_email_change"
MISSING_EMAIL = "missing_email"
MISSING_NATIONALITY = "missing_nationality"
DUPLICATE_EMAIL = "unique"
REQUIRED = "required"
INVALID_SUBSCRIBE_TO_EMPTY_EMAIL = "invalid_subscribe_to_empty_email"
| invalid_email = 'invalid_email'
invalid_email_change = 'invalid_email_change'
missing_email = 'missing_email'
missing_nationality = 'missing_nationality'
duplicate_email = 'unique'
required = 'required'
invalid_subscribe_to_empty_email = 'invalid_subscribe_to_empty_email' |
min_temp = None
max_temp = None
# factor = 2.25
factor = 0
HUE_MAX = 240 / 360
HUE_MIN = 0
HUE_GOOD = 120 / 360
HUE_WARNING = 50/360
HUE_DANGER = 0
#comfort ranges
TEMP_LOW = 16
TEMP_HIGH = 24
HUMIDITY_LOW = 30
HUMIDITY_HIGHT = 60 | min_temp = None
max_temp = None
factor = 0
hue_max = 240 / 360
hue_min = 0
hue_good = 120 / 360
hue_warning = 50 / 360
hue_danger = 0
temp_low = 16
temp_high = 24
humidity_low = 30
humidity_hight = 60 |
# C100--- python classes
class Student(object):
"""
blueprint for Student
"""
def __init__(self, nameInput, ageInput, genderInput, levelInput, gradesInput):
self.name = nameInput
self.age = ageInput
self.gender = genderInput
self.level = levelInput
self.grades = gradesInput or {}
def setGrade(self, courseInput, gradesInput):
self.grades[courseInput] = gradesInput
def getGrade(self, courseInput):
return self.grades[courseInput]
def getGPA(self):
return sum(self.grades.values())/len(self.grades)
# Define some students
john = Student("John", 12, "male", 6, {"math": 3.3})
jane = Student("Jane", 12, "female", 6, {"math": 3.5})
# calling/triggering functions
print("The grades of john are: "+john.getGPA())
print("The grades of john are: "+jane.getGPA())
| class Student(object):
"""
blueprint for Student
"""
def __init__(self, nameInput, ageInput, genderInput, levelInput, gradesInput):
self.name = nameInput
self.age = ageInput
self.gender = genderInput
self.level = levelInput
self.grades = gradesInput or {}
def set_grade(self, courseInput, gradesInput):
self.grades[courseInput] = gradesInput
def get_grade(self, courseInput):
return self.grades[courseInput]
def get_gpa(self):
return sum(self.grades.values()) / len(self.grades)
john = student('John', 12, 'male', 6, {'math': 3.3})
jane = student('Jane', 12, 'female', 6, {'math': 3.5})
print('The grades of john are: ' + john.getGPA())
print('The grades of john are: ' + jane.getGPA()) |
"""Constants for terminal formatting"""
colors = 'dark', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray'
FG_COLORS = dict(list(zip(colors, list(range(30, 38)))))
BG_COLORS = dict(list(zip(colors, list(range(40, 48)))))
STYLES = dict(list(zip(('bold', 'dark', 'underline', 'blink', 'invert'), [1,2,4,5,7])))
FG_NUMBER_TO_COLOR = dict(zip(FG_COLORS.values(), FG_COLORS.keys()))
BG_NUMBER_TO_COLOR = dict(zip(BG_COLORS.values(), BG_COLORS.keys()))
NUMBER_TO_STYLE = dict(zip(STYLES.values(), STYLES.keys()))
RESET_ALL = 0
RESET_FG = 39
RESET_BG = 49
def seq(num):
return '[%sm' % num
| """Constants for terminal formatting"""
colors = ('dark', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray')
fg_colors = dict(list(zip(colors, list(range(30, 38)))))
bg_colors = dict(list(zip(colors, list(range(40, 48)))))
styles = dict(list(zip(('bold', 'dark', 'underline', 'blink', 'invert'), [1, 2, 4, 5, 7])))
fg_number_to_color = dict(zip(FG_COLORS.values(), FG_COLORS.keys()))
bg_number_to_color = dict(zip(BG_COLORS.values(), BG_COLORS.keys()))
number_to_style = dict(zip(STYLES.values(), STYLES.keys()))
reset_all = 0
reset_fg = 39
reset_bg = 49
def seq(num):
return '\x1b[%sm' % num |
MAX_PIXEL_VALUE = 255
LAPLAS_FACTOR = 0.5
LAPLAS_1 = [[0,1,0],[1,-4,1],[0,1,0]]
LAPLAS_2 = [[1,1,1],[1,-8,1],[1,1,1]]
LAPLAS_3 = [[0,-1,0],[-1,4,-1],[0,-1,0]]
LAPLAS_4 = [[-1,-1,-1],[-1,8,-1],[-1,-1,-1]]
LAPLAS_5 = [[0,-1,0],[-1,5,-1],[0,-1,0]]
LAPLAS_6 = [[-1,-1,-1],[-1,9,-1],[-1,-1,-1]]
LAPLAS_7 = [[0,-1,0],[-1,LAPLAS_FACTOR + 4,-1],[0,-1,0]]
LAPLAS_8 = [[-1,-1,-1],[-1,LAPLAS_FACTOR + 8,-1],[-1,-1,-1]] | max_pixel_value = 255
laplas_factor = 0.5
laplas_1 = [[0, 1, 0], [1, -4, 1], [0, 1, 0]]
laplas_2 = [[1, 1, 1], [1, -8, 1], [1, 1, 1]]
laplas_3 = [[0, -1, 0], [-1, 4, -1], [0, -1, 0]]
laplas_4 = [[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]
laplas_5 = [[0, -1, 0], [-1, 5, -1], [0, -1, 0]]
laplas_6 = [[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]
laplas_7 = [[0, -1, 0], [-1, LAPLAS_FACTOR + 4, -1], [0, -1, 0]]
laplas_8 = [[-1, -1, -1], [-1, LAPLAS_FACTOR + 8, -1], [-1, -1, -1]] |
class ListExtension(object):
@staticmethod
def split_list_in_n_parts(my_list, number_chunks):
k, m = len(my_list) / number_chunks, len(my_list) % number_chunks
return list(my_list[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(number_chunks))
@staticmethod
def convert_list_to_string(my_list, separator=' '):
return separator.join(list(map(str, my_list)))
if __name__ == '__main__':
my_list = [(1,2), (3,4), (5,6)]
res = ListExtension.convert_list_to_string(my_list)
print(res) | class Listextension(object):
@staticmethod
def split_list_in_n_parts(my_list, number_chunks):
(k, m) = (len(my_list) / number_chunks, len(my_list) % number_chunks)
return list((my_list[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(number_chunks)))
@staticmethod
def convert_list_to_string(my_list, separator=' '):
return separator.join(list(map(str, my_list)))
if __name__ == '__main__':
my_list = [(1, 2), (3, 4), (5, 6)]
res = ListExtension.convert_list_to_string(my_list)
print(res) |
# Violet Cube Fragment
FRAGMENT = 2434125
REWARD1 = 5062009 # red cube
REWARD2 = 5062010 # black cube
q = sm.getQuantityOfItem(FRAGMENT)
if q >= 10:
if sm.canHold(REWARD2):
sm.giveItem(REWARD2)
sm.consumeItem(FRAGMENT, 10)
else:
sm.systemMessage("Make sure you have enough space in your inventory..")
elif q >= 5:
if sm.canHold(REWARD1):
sm.giveItem(REWARD1)
sm.consumeItem(FRAGMENT, 5)
else:
sm.systemMessage("Make sure you have enough space in your inventory..")
else:
sm.systemMessage("One must have at least 5 fragments to unleash the magic powers..") | fragment = 2434125
reward1 = 5062009
reward2 = 5062010
q = sm.getQuantityOfItem(FRAGMENT)
if q >= 10:
if sm.canHold(REWARD2):
sm.giveItem(REWARD2)
sm.consumeItem(FRAGMENT, 10)
else:
sm.systemMessage('Make sure you have enough space in your inventory..')
elif q >= 5:
if sm.canHold(REWARD1):
sm.giveItem(REWARD1)
sm.consumeItem(FRAGMENT, 5)
else:
sm.systemMessage('Make sure you have enough space in your inventory..')
else:
sm.systemMessage('One must have at least 5 fragments to unleash the magic powers..') |
num = {}
for i in range(97,123):
num[chr(i)] = i-96
L = int(input())
data = list(input().rstrip())
res = 0
M = 1234567891
for idx,val in enumerate(data):
res += (31**idx)*num[val]
res %= M
print(res) | num = {}
for i in range(97, 123):
num[chr(i)] = i - 96
l = int(input())
data = list(input().rstrip())
res = 0
m = 1234567891
for (idx, val) in enumerate(data):
res += 31 ** idx * num[val]
res %= M
print(res) |
class f:
def __init__(self,s,i):
self.s=s;self.i=i
r=""
for _ in range(int(__import__('sys').stdin.readline())):
n=int(__import__('sys').stdin.readline())
a=__import__('sys').stdin.readline().split()
b=__import__('sys').stdin.readline().split()
o=[-1]*n
for i in range(n):
for j in range(n):
if b[i]==a[j]:
o[i]=j;break
t=""
c=__import__('sys').stdin.readline().split()
for i in range(n):
o[i]=f(c[i],o[i])
o.sort(key=lambda x:x.i)
for x in o:
t+=x.s+' '
r+=t+'\n'
print(r,end="")
| class F:
def __init__(self, s, i):
self.s = s
self.i = i
r = ''
for _ in range(int(__import__('sys').stdin.readline())):
n = int(__import__('sys').stdin.readline())
a = __import__('sys').stdin.readline().split()
b = __import__('sys').stdin.readline().split()
o = [-1] * n
for i in range(n):
for j in range(n):
if b[i] == a[j]:
o[i] = j
break
t = ''
c = __import__('sys').stdin.readline().split()
for i in range(n):
o[i] = f(c[i], o[i])
o.sort(key=lambda x: x.i)
for x in o:
t += x.s + ' '
r += t + '\n'
print(r, end='') |
n = int(input())
even = 0
odd = 0
for i in range(1, n + 1):
number = int(input())
if i % 2 == 0:
even += number
else:
odd += number
if even == odd:
print(f"Yes\nSum = {even}")
else:
print(f"No\nDiff = {abs(even - odd)}")
| n = int(input())
even = 0
odd = 0
for i in range(1, n + 1):
number = int(input())
if i % 2 == 0:
even += number
else:
odd += number
if even == odd:
print(f'Yes\nSum = {even}')
else:
print(f'No\nDiff = {abs(even - odd)}') |
def diff():
print("Diff Diff")
def patch():
print("Patch")
| def diff():
print('Diff Diff')
def patch():
print('Patch') |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = [
'userprofile',
]
USER_PROFILE_MODULE = 'userprofile.Profile'
| databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
installed_apps = ['userprofile']
user_profile_module = 'userprofile.Profile' |
class Solution:
def equalSubstring(self, s: str, t: str, mx: int) -> int:
i = 0
for j in range(len(s)):
mx -= abs(ord(s[j]) - ord(t[j]))
if mx < 0:
mx += abs(ord(s[i]) - ord(t[i]))
i += 1
return j - i + 1 | class Solution:
def equal_substring(self, s: str, t: str, mx: int) -> int:
i = 0
for j in range(len(s)):
mx -= abs(ord(s[j]) - ord(t[j]))
if mx < 0:
mx += abs(ord(s[i]) - ord(t[i]))
i += 1
return j - i + 1 |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CompressionPolicyVaultEnum(object):
"""Implementation of the 'CompressionPolicy_Vault' enum.
Specifies whether to send data to the Vault in a
compressed format.
'kCompressionNone' indicates that data is not compressed.
'kCompressionLow' indicates that data is compressed using LZ4 or Snappy.
'kCompressionHigh' indicates that data is compressed in Gzip.
Attributes:
KCOMPRESSIONNONE: TODO: type description here.
KCOMPRESSIONLOW: TODO: type description here.
KCOMPRESSIONHIGH: TODO: type description here.
"""
KCOMPRESSIONNONE = 'kCompressionNone'
KCOMPRESSIONLOW = 'kCompressionLow'
KCOMPRESSIONHIGH = 'kCompressionHigh'
| class Compressionpolicyvaultenum(object):
"""Implementation of the 'CompressionPolicy_Vault' enum.
Specifies whether to send data to the Vault in a
compressed format.
'kCompressionNone' indicates that data is not compressed.
'kCompressionLow' indicates that data is compressed using LZ4 or Snappy.
'kCompressionHigh' indicates that data is compressed in Gzip.
Attributes:
KCOMPRESSIONNONE: TODO: type description here.
KCOMPRESSIONLOW: TODO: type description here.
KCOMPRESSIONHIGH: TODO: type description here.
"""
kcompressionnone = 'kCompressionNone'
kcompressionlow = 'kCompressionLow'
kcompressionhigh = 'kCompressionHigh' |
'''
Problem:
Given an array A of n integers, in sorted order, and an integer x,
design an O(n)-time complexity algorithm to determine whether there
are 2 integers in A whose sum is exactly x.
'''
def sum(target, x):
lookup = set()
# Build a lookup table.
for item in target:
lookup.add(x - item)
# Check for a hit.
for item in target:
if item in lookup:
return '%d + %d' % (item, x - item)
return None
x = 7
test = [1, 2, 3, 4, 5]
print(sum(test, x))
x = 15
print(sum(test, x))
| """
Problem:
Given an array A of n integers, in sorted order, and an integer x,
design an O(n)-time complexity algorithm to determine whether there
are 2 integers in A whose sum is exactly x.
"""
def sum(target, x):
lookup = set()
for item in target:
lookup.add(x - item)
for item in target:
if item in lookup:
return '%d + %d' % (item, x - item)
return None
x = 7
test = [1, 2, 3, 4, 5]
print(sum(test, x))
x = 15
print(sum(test, x)) |
class Televisao():
def __init__(self, c):
self.ligada = False
self.canal = c
self.marca = 'SAMSUNG'
self.tamanho = '43'
def muda_canal_cima(self):
if self.canal < 50:
self.canal += 1
else:
self.canal = 1
def muda_canal_baixo(self):
if self.canal > 1:
self.canal -= 1
else:
self.canal = 50
tv_quarto = Televisao(48)
print(tv_quarto.canal)
tv_quarto.muda_canal_cima()
tv_quarto.muda_canal_cima()
tv_quarto.muda_canal_cima()
tv_quarto.muda_canal_cima()
tv_quarto.muda_canal_cima()
print(tv_quarto.canal)
tv_quarto.canal = 5
print(tv_quarto.canal)
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
print(tv_quarto.canal)
| class Televisao:
def __init__(self, c):
self.ligada = False
self.canal = c
self.marca = 'SAMSUNG'
self.tamanho = '43'
def muda_canal_cima(self):
if self.canal < 50:
self.canal += 1
else:
self.canal = 1
def muda_canal_baixo(self):
if self.canal > 1:
self.canal -= 1
else:
self.canal = 50
tv_quarto = televisao(48)
print(tv_quarto.canal)
tv_quarto.muda_canal_cima()
tv_quarto.muda_canal_cima()
tv_quarto.muda_canal_cima()
tv_quarto.muda_canal_cima()
tv_quarto.muda_canal_cima()
print(tv_quarto.canal)
tv_quarto.canal = 5
print(tv_quarto.canal)
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
tv_quarto.muda_canal_baixo()
print(tv_quarto.canal) |
def test_numbers():
assert 1234 == 1234
def test_hello_world():
assert "hello" + "world" == "helloworld"
def test_foobar():
assert True
| def test_numbers():
assert 1234 == 1234
def test_hello_world():
assert 'hello' + 'world' == 'helloworld'
def test_foobar():
assert True |
'''
SPDX-License-Identifier: Apache-2.0
Copyright 2021 Keylime Authors
'''
async def execute(revocation):
try:
value = revocation['hello']
print(value)
except Exception as e:
raise Exception(
"The provided dictionary does not contain the 'hello' key")
| """
SPDX-License-Identifier: Apache-2.0
Copyright 2021 Keylime Authors
"""
async def execute(revocation):
try:
value = revocation['hello']
print(value)
except Exception as e:
raise exception("The provided dictionary does not contain the 'hello' key") |
# local scope
def my_func():
x = 300
print(x)
def my_inner_func():
print(x)
my_inner_func()
my_func()
| def my_func():
x = 300
print(x)
def my_inner_func():
print(x)
my_inner_func()
my_func() |
# OpenWeatherMap API Key
weather_api_key = "8915eee544f1c9b3ef5fa102f5edeb66"
# Google API Key
g_key = "AIzaSyDgD7ZgpyA4MuuVfr3Ep8G2-uCEx37joSE"
| weather_api_key = '8915eee544f1c9b3ef5fa102f5edeb66'
g_key = 'AIzaSyDgD7ZgpyA4MuuVfr3Ep8G2-uCEx37joSE' |
"""
Entradas
valor_mercancia-->float-->valor_mercancia
Salidas
cantidad_extraida_de_fondos-->float-->cantidad_fondos
cantidad_credito-->float-->cantidad_credito
banco_prestamo-->float-->banco_prestamo
"""
valor_mercancia=float(input("Digite el costo de los insumos "))
if(valor_mercancia>=5000001):
cantidad_fondos=valor_mercancia*0.55
print("La cantidad utilizada de los fondos de la empresa es ",cantidad_fondos)
cantidad_credito=(valor_mercancia*0.15)
cantidad_credito_intereses=(cantidad_credito*0.2)+cantidad_credito
print("La cantidad total a pagar a credito es ",cantidad_credito_intereses)
banco_prestamo=valor_mercancia*0.3
print("La cantidad prestada por el banco es ",banco_prestamo)
elif(valor_mercancia<5000000):
cantidad_fondos=valor_mercancia*0.7
print("La cantidad utilizada de los fondos de la empresa es ",cantidad_fondos)
cantidad_credito=(valor_mercancia*0.3)
cantidad_credito_intereses=(cantidad_credito*0.2)+cantidad_credito
print("La cantidad total a pagar a credito es ",cantidad_credito_intereses) | """
Entradas
valor_mercancia-->float-->valor_mercancia
Salidas
cantidad_extraida_de_fondos-->float-->cantidad_fondos
cantidad_credito-->float-->cantidad_credito
banco_prestamo-->float-->banco_prestamo
"""
valor_mercancia = float(input('Digite el costo de los insumos '))
if valor_mercancia >= 5000001:
cantidad_fondos = valor_mercancia * 0.55
print('La cantidad utilizada de los fondos de la empresa es ', cantidad_fondos)
cantidad_credito = valor_mercancia * 0.15
cantidad_credito_intereses = cantidad_credito * 0.2 + cantidad_credito
print('La cantidad total a pagar a credito es ', cantidad_credito_intereses)
banco_prestamo = valor_mercancia * 0.3
print('La cantidad prestada por el banco es ', banco_prestamo)
elif valor_mercancia < 5000000:
cantidad_fondos = valor_mercancia * 0.7
print('La cantidad utilizada de los fondos de la empresa es ', cantidad_fondos)
cantidad_credito = valor_mercancia * 0.3
cantidad_credito_intereses = cantidad_credito * 0.2 + cantidad_credito
print('La cantidad total a pagar a credito es ', cantidad_credito_intereses) |
def to_polar(x, y):
'Rectangular to polar conversion using ints scaled by 100000. Angle in degrees.'
theta = 0
for i, adj in enumerate((4500000, 2656505, 1403624, 712502, 357633, 178991, 89517, 44761)):
sign = 1 if y < 0 else -1
x, y, theta = x - sign*(y >> i) , y + sign*(x >> i), theta - sign*adj
return theta, x * 60726 // 100000
def to_rect(r, theta):
'Polar to rectangular conversion using ints scaled by 100000. Angle in degrees.'
x, y = 60726 * r // 100000, 0
for i, adj in enumerate((4500000, 2656505, 1403624, 712502, 357633, 178991, 89517, 44761)):
sign = 1 if theta > 0 else -1
x, y, theta = x - sign*(y >> i) , y + sign*(x >> i), theta - sign*adj
return x, y
if __name__ == '__main__':
print(to_rect(471700, 5799460)) # r=4.71700 theta=57.99460
print(to_polar(250000, 400000)) # x=2.50000 y=4.00000
| def to_polar(x, y):
"""Rectangular to polar conversion using ints scaled by 100000. Angle in degrees."""
theta = 0
for (i, adj) in enumerate((4500000, 2656505, 1403624, 712502, 357633, 178991, 89517, 44761)):
sign = 1 if y < 0 else -1
(x, y, theta) = (x - sign * (y >> i), y + sign * (x >> i), theta - sign * adj)
return (theta, x * 60726 // 100000)
def to_rect(r, theta):
"""Polar to rectangular conversion using ints scaled by 100000. Angle in degrees."""
(x, y) = (60726 * r // 100000, 0)
for (i, adj) in enumerate((4500000, 2656505, 1403624, 712502, 357633, 178991, 89517, 44761)):
sign = 1 if theta > 0 else -1
(x, y, theta) = (x - sign * (y >> i), y + sign * (x >> i), theta - sign * adj)
return (x, y)
if __name__ == '__main__':
print(to_rect(471700, 5799460))
print(to_polar(250000, 400000)) |
# -*- coding: utf-8 -*-
description = 'common detector devices provided by QMesyDAQ'
group = 'lowlevel'
devices = dict(
timer = device('nicos.devices.generic.VirtualTimer',
description = 'QMesyDAQ timer',
lowlevel = True,
unit = 's',
fmtstr = '%.1f',
),
mon1 = device('nicos.devices.generic.VirtualCounter',
description = 'QMesyDAQ monitor 1',
type = 'monitor',
lowlevel = True,
fmtstr = '%d',
),
# mon2 = device('nicos.devices.generic.VirtualCounter',
# type = 'monitor',
# lowlevel = True,
# fmtstr = '%d',
# ),
det1 = device('nicos.devices.generic.VirtualCounter',
type = 'counter',
lowlevel = True,
fmtstr = '%d',
),
det2 = device('nicos.devices.generic.VirtualCounter',
type = 'counter',
lowlevel = True,
fmtstr = '%d',
),
det3 = device('nicos.devices.generic.VirtualCounter',
type = 'counter',
lowlevel = True,
fmtstr = '%d',
),
# det4 = device('nicos.devices.generic.VirtualCounter',
# type = 'counter',
# lowlevel = True,
# fmtstr = '%d',
# ),
# det5 = device('nicos.devices.generic.VirtualCounter',
# type = 'counter',
# lowlevel = True,
# fmtstr = '%d',
# ),
events = device('nicos.devices.generic.VirtualCounter',
description = 'QMesyDAQ Events channel',
type = 'counter',
lowlevel = True,
fmtstr = '%d',
),
image = device('nicos.devices.generic.VirtualImage',
description = 'QMesyDAQ Image',
fmtstr = '%d',
pollinterval = 86400,
lowlevel = True,
sizes = (1, 5),
),
det = device('nicos.devices.generic.Detector',
# description = 'Puma detector device (5 counters)',
description = 'Puma detector QMesydaq device (3 counters)',
timers = ['timer'],
# monitors = ['mon1', 'mon2'],
monitors = ['mon1'],
# counters = ['det1', 'det2', 'det3', 'det4', 'det5'],
counters = ['det1', 'det2', 'det3'],
images = [],
maxage = 1,
pollinterval = 1,
),
)
startupcode = '''
SetDetectors(det)
'''
| description = 'common detector devices provided by QMesyDAQ'
group = 'lowlevel'
devices = dict(timer=device('nicos.devices.generic.VirtualTimer', description='QMesyDAQ timer', lowlevel=True, unit='s', fmtstr='%.1f'), mon1=device('nicos.devices.generic.VirtualCounter', description='QMesyDAQ monitor 1', type='monitor', lowlevel=True, fmtstr='%d'), det1=device('nicos.devices.generic.VirtualCounter', type='counter', lowlevel=True, fmtstr='%d'), det2=device('nicos.devices.generic.VirtualCounter', type='counter', lowlevel=True, fmtstr='%d'), det3=device('nicos.devices.generic.VirtualCounter', type='counter', lowlevel=True, fmtstr='%d'), events=device('nicos.devices.generic.VirtualCounter', description='QMesyDAQ Events channel', type='counter', lowlevel=True, fmtstr='%d'), image=device('nicos.devices.generic.VirtualImage', description='QMesyDAQ Image', fmtstr='%d', pollinterval=86400, lowlevel=True, sizes=(1, 5)), det=device('nicos.devices.generic.Detector', description='Puma detector QMesydaq device (3 counters)', timers=['timer'], monitors=['mon1'], counters=['det1', 'det2', 'det3'], images=[], maxage=1, pollinterval=1))
startupcode = '\nSetDetectors(det)\n' |
def arrayMap(f):
def app(arr):
return tuple(f(e) for e in arr)
return app
| def array_map(f):
def app(arr):
return tuple((f(e) for e in arr))
return app |
"""
LeetCode 163. Missing Ranges
# https://www.goodtecher.com/leetcode-163-missing-ranges/
Description
https://leetcode.com/problems/missing-ranges/
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.
A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.
Each range [a,b] in the list should be output as:
"a->b" if a != b
"a" if a == b
Example 1:
Input: nums = [0,1,3,50,75], lower = 0, upper = 99
Output: ["2","4->49","51->74","76->99"]
Explanation: The ranges are:
[2,2] --> "2"
[4,49] --> "4->49"
[51,74] --> "51->74"
[76,99] --> "76->99"
Example 2:
Input: nums = [], lower = 1, upper = 1
Output: ["1"]
Explanation: The only missing range is [1,1], which becomes "1".
Example 3:
Input: nums = [], lower = -3, upper = -1
Output: ["-3->-1"]
Explanation: The only missing range is [-3,-1], which becomes "-3->-1".
Example 4:
Input: nums = [-1], lower = -1, upper = -1
Output: []
Explanation: There are no missing ranges since there are no missing numbers.
Example 5:
Input: nums = [-1], lower = -2, upper = -1
Output: ["-2"]
Constraints:
-109 <= lower <= upper <= 109
0 <= nums.length <= 100
lower <= nums[i] <= upper
All the values of nums are unique.
"""
# V0
# IDEA : 2 POINTERS
class Solution(object):
def findMissingRanges(self, nums, lower, upper):
l, r = lower, lower
res = []
for i in range(len(nums)):
# if NO missing interval
if nums[i] == r:
l, r = nums[i] + 1, nums[i] + 1
# if missing interval
elif nums[i] > r:
r = max(r, nums[i] - 1)
if r != l:
res.append(str(l) + "->" + str(r))
else:
res.append(str(l))
l, r = nums[i] + 1, nums[i] + 1
# deal with remaining part
if l < upper:
res.append(str(l) + "->" + str(upper))
elif l == upper:
res.append(str(l))
return res
# V1
# https://blog.csdn.net/qq_32424059/article/details/94437790
# IDEA : DOUBLE POINTERS
class Solution(object):
def findMissingRanges(self, nums, lower, upper):
start, end = lower, lower
res = []
for i in range(len(nums)):
if nums[i] == end: # if NO missing interval
start, end = nums[i] + 1, nums[i] + 1
elif nums[i] > end: # if there missing interval
end = max(end, nums[i] - 1)
if end != start:
res.append(str(start) + "->" + str(end))
else:
res.append(str(start))
start, end = nums[i] + 1, nums[i] + 1
if start < upper: # deal with the remaining part
res.append(str(start) + "->" + str(upper))
elif start == upper:
res.append(str(start))
return res
# V1'
# https://github.com/qiyuangong/leetcode/blob/master/python/163_Missing_Ranges.py
class Solution(object):
def findMissingRanges(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: List[str]
"""
ranges = []
prev = lower - 1
for i in range(len(nums) + 1):
if i == len(nums):
curr = upper + 1
else:
curr = nums[i]
if curr - prev > 2:
ranges.append("%d->%d" % (prev + 1, curr - 1))
elif curr - prev == 2:
ranges.append("%d" % (prev + 1))
prev = curr
return ranges
# V1''
# Missing Ranges - Leetcode Challenge - Python Solution - Poopcode
class Solution(object):
def findMissingRanges(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: List[str]
"""
ranges = []
prev = lower - 1
for i in range(len(nums) + 1):
if i == len(nums):
curr = upper + 1
else:
curr = nums[i]
if curr - prev > 2:
ranges.append("%d->%d" % (prev + 1, curr - 1))
elif curr - prev == 2:
ranges.append("%d" % (prev + 1))
prev = curr
return ranges
# V1'''
# https://www.goodtecher.com/leetcode-163-missing-ranges/
class Solution:
def findMissingRanges(self, nums, lower, upper):
results = []
if not nums:
gap = self.helper(lower, upper)
results.append(gap)
return results
prev = lower - 1
for num in nums:
if prev + 1 != num:
gap = self.helper(prev + 1, num - 1)
results.append(gap)
prev = num
if nums[-1] < upper:
gap = self.helper(nums[-1] + 1, upper)
results.append(gap)
return results
def helper(self, left, right):
if left == right:
return str(left)
return str(left) + "->" + str(right)
# V1'
# https://www.cnblogs.com/grandyang/p/5184890.html
# IDEA : C++
# class Solution {
# public:
# vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
# vector<string> res;
# for (int num : nums) {
# if (num > lower) res.push_back(to_string(lower) + (num - 1 > lower ? ("->" + to_string(num - 1)) : ""));
# if (num == upper) return res;
# lower = num + 1;
# }
# if (lower <= upper) res.push_back(to_string(lower) + (upper > lower ? ("->" + to_string(upper)) : ""));
# return res;
# }
# };
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def findMissingRanges(self, nums, lower, upper):
def getRange(lower, upper):
if lower == upper:
return "{}".format(lower)
else:
return "{}->{}".format(lower, upper)
ranges = []
pre = lower - 1
for i in range(len(nums) + 1):
if i == len(nums):
cur = upper + 1
else:
cur = nums[i]
if cur - pre >= 2:
ranges.append(getRange(pre + 1, cur - 1))
pre = cur
return ranges | """
LeetCode 163. Missing Ranges
# https://www.goodtecher.com/leetcode-163-missing-ranges/
Description
https://leetcode.com/problems/missing-ranges/
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.
A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.
Each range [a,b] in the list should be output as:
"a->b" if a != b
"a" if a == b
Example 1:
Input: nums = [0,1,3,50,75], lower = 0, upper = 99
Output: ["2","4->49","51->74","76->99"]
Explanation: The ranges are:
[2,2] --> "2"
[4,49] --> "4->49"
[51,74] --> "51->74"
[76,99] --> "76->99"
Example 2:
Input: nums = [], lower = 1, upper = 1
Output: ["1"]
Explanation: The only missing range is [1,1], which becomes "1".
Example 3:
Input: nums = [], lower = -3, upper = -1
Output: ["-3->-1"]
Explanation: The only missing range is [-3,-1], which becomes "-3->-1".
Example 4:
Input: nums = [-1], lower = -1, upper = -1
Output: []
Explanation: There are no missing ranges since there are no missing numbers.
Example 5:
Input: nums = [-1], lower = -2, upper = -1
Output: ["-2"]
Constraints:
-109 <= lower <= upper <= 109
0 <= nums.length <= 100
lower <= nums[i] <= upper
All the values of nums are unique.
"""
class Solution(object):
def find_missing_ranges(self, nums, lower, upper):
(l, r) = (lower, lower)
res = []
for i in range(len(nums)):
if nums[i] == r:
(l, r) = (nums[i] + 1, nums[i] + 1)
elif nums[i] > r:
r = max(r, nums[i] - 1)
if r != l:
res.append(str(l) + '->' + str(r))
else:
res.append(str(l))
(l, r) = (nums[i] + 1, nums[i] + 1)
if l < upper:
res.append(str(l) + '->' + str(upper))
elif l == upper:
res.append(str(l))
return res
class Solution(object):
def find_missing_ranges(self, nums, lower, upper):
(start, end) = (lower, lower)
res = []
for i in range(len(nums)):
if nums[i] == end:
(start, end) = (nums[i] + 1, nums[i] + 1)
elif nums[i] > end:
end = max(end, nums[i] - 1)
if end != start:
res.append(str(start) + '->' + str(end))
else:
res.append(str(start))
(start, end) = (nums[i] + 1, nums[i] + 1)
if start < upper:
res.append(str(start) + '->' + str(upper))
elif start == upper:
res.append(str(start))
return res
class Solution(object):
def find_missing_ranges(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: List[str]
"""
ranges = []
prev = lower - 1
for i in range(len(nums) + 1):
if i == len(nums):
curr = upper + 1
else:
curr = nums[i]
if curr - prev > 2:
ranges.append('%d->%d' % (prev + 1, curr - 1))
elif curr - prev == 2:
ranges.append('%d' % (prev + 1))
prev = curr
return ranges
class Solution(object):
def find_missing_ranges(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: List[str]
"""
ranges = []
prev = lower - 1
for i in range(len(nums) + 1):
if i == len(nums):
curr = upper + 1
else:
curr = nums[i]
if curr - prev > 2:
ranges.append('%d->%d' % (prev + 1, curr - 1))
elif curr - prev == 2:
ranges.append('%d' % (prev + 1))
prev = curr
return ranges
class Solution:
def find_missing_ranges(self, nums, lower, upper):
results = []
if not nums:
gap = self.helper(lower, upper)
results.append(gap)
return results
prev = lower - 1
for num in nums:
if prev + 1 != num:
gap = self.helper(prev + 1, num - 1)
results.append(gap)
prev = num
if nums[-1] < upper:
gap = self.helper(nums[-1] + 1, upper)
results.append(gap)
return results
def helper(self, left, right):
if left == right:
return str(left)
return str(left) + '->' + str(right)
class Solution(object):
def find_missing_ranges(self, nums, lower, upper):
def get_range(lower, upper):
if lower == upper:
return '{}'.format(lower)
else:
return '{}->{}'.format(lower, upper)
ranges = []
pre = lower - 1
for i in range(len(nums) + 1):
if i == len(nums):
cur = upper + 1
else:
cur = nums[i]
if cur - pre >= 2:
ranges.append(get_range(pre + 1, cur - 1))
pre = cur
return ranges |
n = int(input())
arr = [int(e) for e in input().split()]
for inicio in range(1, n):
i = inicio
while i >= 1 and arr[i] < arr[i-1]:
arr[i], arr[i-1] = arr[i-1], arr[i]
i -= 1
for i in range(8):
print(arr[i], end=" ")
print()
| n = int(input())
arr = [int(e) for e in input().split()]
for inicio in range(1, n):
i = inicio
while i >= 1 and arr[i] < arr[i - 1]:
(arr[i], arr[i - 1]) = (arr[i - 1], arr[i])
i -= 1
for i in range(8):
print(arr[i], end=' ')
print() |
def area_for_polygon(polygon):
result = 0
imax = len(polygon) - 1
for i in range(0, imax):
result += (polygon[i][1] * polygon[i + 1][0]) - (polygon[i + 1][1] * polygon[i][0])
result += (polygon[imax][1] * polygon[0][0]) - (polygon[0][1] * polygon[imax][0])
return result / 2.
def centroid_for_polygon(polygon):
area = area_for_polygon(polygon)
imax = len(polygon) - 1
result_x = 0
result_y = 0
for i in range(0, imax):
result_x += (polygon[i][1] + polygon[i + 1][1]) * ((polygon[i][1] *
polygon[i + 1][0]) - (polygon[i + 1][1] * polygon[i][0]))
result_y += (polygon[i][0] + polygon[i + 1][0]) * ((polygon[i][1] *
polygon[i + 1][0]) - (polygon[i + 1][1] * polygon[i][0]))
result_x += (polygon[imax][1] + polygon[0][1]) * \
((polygon[imax][1] * polygon[0][0]) - (polygon[0][1] * polygon[imax][0]))
result_y += (polygon[imax][0] + polygon[0][0]) * \
((polygon[imax][1] * polygon[0][0]) - (polygon[0][1] * polygon[imax][0]))
result_x /= (area * 6.0)
result_y /= (area * 6.0)
return result_y, result_x
| def area_for_polygon(polygon):
result = 0
imax = len(polygon) - 1
for i in range(0, imax):
result += polygon[i][1] * polygon[i + 1][0] - polygon[i + 1][1] * polygon[i][0]
result += polygon[imax][1] * polygon[0][0] - polygon[0][1] * polygon[imax][0]
return result / 2.0
def centroid_for_polygon(polygon):
area = area_for_polygon(polygon)
imax = len(polygon) - 1
result_x = 0
result_y = 0
for i in range(0, imax):
result_x += (polygon[i][1] + polygon[i + 1][1]) * (polygon[i][1] * polygon[i + 1][0] - polygon[i + 1][1] * polygon[i][0])
result_y += (polygon[i][0] + polygon[i + 1][0]) * (polygon[i][1] * polygon[i + 1][0] - polygon[i + 1][1] * polygon[i][0])
result_x += (polygon[imax][1] + polygon[0][1]) * (polygon[imax][1] * polygon[0][0] - polygon[0][1] * polygon[imax][0])
result_y += (polygon[imax][0] + polygon[0][0]) * (polygon[imax][1] * polygon[0][0] - polygon[0][1] * polygon[imax][0])
result_x /= area * 6.0
result_y /= area * 6.0
return (result_y, result_x) |
def square(): # function header
new_value=4 ** 2 # function body
print(new_value)
square()
| def square():
new_value = 4 ** 2
print(new_value)
square() |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 2 00:25:26 2017
@author: Roberto Piga
"""
# Paste your code into this box
# define variables like in the example, below
balance = 3329; annualInterestRate = 0.2
minimumFixed = 0
f = True
initialBalance = balance
while balance > 0:
balance = initialBalance
minimumFixed += 10
for month in range(1,13):
unpaidBalance = balance - minimumFixed
balance = unpaidBalance + round(annualInterestRate/12.0 * unpaidBalance)
print("Lowest Payment:", round(minimumFixed))
| """
Created on Thu Feb 2 00:25:26 2017
@author: Roberto Piga
"""
balance = 3329
annual_interest_rate = 0.2
minimum_fixed = 0
f = True
initial_balance = balance
while balance > 0:
balance = initialBalance
minimum_fixed += 10
for month in range(1, 13):
unpaid_balance = balance - minimumFixed
balance = unpaidBalance + round(annualInterestRate / 12.0 * unpaidBalance)
print('Lowest Payment:', round(minimumFixed)) |
class MockDbQuery(object):
def __init__(self, responses):
self.responses = responses
def get(self, method, **kws):
resp = None
if method in self.responses:
resp = self.responses[method].pop(0)
if 'validate' in resp:
checks = resp['validate']['checks']
resp = resp['validate']['data']
for check in checks:
assert check in kws
expected_value = checks[check]
assert expected_value == kws[check]
return resp
class MockHTTPResponse(object):
def __init__(self, status_code, text):
self.status_code = status_code
self.text = text
| class Mockdbquery(object):
def __init__(self, responses):
self.responses = responses
def get(self, method, **kws):
resp = None
if method in self.responses:
resp = self.responses[method].pop(0)
if 'validate' in resp:
checks = resp['validate']['checks']
resp = resp['validate']['data']
for check in checks:
assert check in kws
expected_value = checks[check]
assert expected_value == kws[check]
return resp
class Mockhttpresponse(object):
def __init__(self, status_code, text):
self.status_code = status_code
self.text = text |
_tol = 1e-5
def sim(a,b):
if (a==b):
return True
elif a == 0 or b == 0:
return False
if (a<b):
return (1-a/b)<=_tol
else:
return (1-b/a)<=_tol
def nsim(a,b):
if (a==b):
return False
elif a == 0 or b == 0:
return True
if (a<b):
return (1-a/b)>_tol
else:
return (1-b/a)>_tol
def gsim(a,b):
if a >= b:
return True
return (1-a/b)<=_tol
def lsim(a,b):
if a <= b:
return True
return (1-b/a)<=_tol
def set_tol(value=1e-5):
r"""Set Error Tolerance
Set the tolerance for detriming if two numbers are simliar, i.e
:math:`\left|\frac{a}{b}\right| = 1 \pm tolerance`
Parameters
----------
value: float
The Value to set the tolerance to show be very small as it respresents the
percentage of acceptable error in detriming if two values are the same.
"""
global _tol
if isinstance(value,float):
_tol = value
else:
raise TypeError(type(value)) | _tol = 1e-05
def sim(a, b):
if a == b:
return True
elif a == 0 or b == 0:
return False
if a < b:
return 1 - a / b <= _tol
else:
return 1 - b / a <= _tol
def nsim(a, b):
if a == b:
return False
elif a == 0 or b == 0:
return True
if a < b:
return 1 - a / b > _tol
else:
return 1 - b / a > _tol
def gsim(a, b):
if a >= b:
return True
return 1 - a / b <= _tol
def lsim(a, b):
if a <= b:
return True
return 1 - b / a <= _tol
def set_tol(value=1e-05):
"""Set Error Tolerance
Set the tolerance for detriming if two numbers are simliar, i.e
:math:`\\left|\\frac{a}{b}\\right| = 1 \\pm tolerance`
Parameters
----------
value: float
The Value to set the tolerance to show be very small as it respresents the
percentage of acceptable error in detriming if two values are the same.
"""
global _tol
if isinstance(value, float):
_tol = value
else:
raise type_error(type(value)) |
class ContextMixin(object):
"""Defines a ``GET`` method that invokes :meth:`get_rendering_context()`
and returns its result to the client.
"""
def get_rendering_context(self, *args, **kwargs):
raise NotImplementedError("Subclasses must override this method.")
| class Contextmixin(object):
"""Defines a ``GET`` method that invokes :meth:`get_rendering_context()`
and returns its result to the client.
"""
def get_rendering_context(self, *args, **kwargs):
raise not_implemented_error('Subclasses must override this method.') |
class BaseModel:
def __init__(self):
pass
def predict(self, data):
"""
Get prediction on the data.
Parameters
----------
data : optional
Data on which prediction should be done.
Returns
-------
None
"""
pass
def predict_proba(self, data):
"""
Get probabilities of prediction for the data.
Parameters
----------
data : optional
Data on which prediction should be done.
Returns
-------
None
"""
pass
def fit(self, data):
"""
Method to fit the data to the model.
Parameters
----------
data : optional
Data which the model should fit to.
Returns
-------
None
"""
pass
def save_model(self, save_path):
"""
Method to save the model to the path provided.
Parameters
----------
save_path : str
Path where the model should be saved
Returns
-------
None
"""
pass
def load_model(self, load_path):
"""
Method to load the model from the given path.
Parameters
----------
load_path : str
Path of the model which should be loaded for the current instance.
Returns
-------
None
"""
pass
| class Basemodel:
def __init__(self):
pass
def predict(self, data):
"""
Get prediction on the data.
Parameters
----------
data : optional
Data on which prediction should be done.
Returns
-------
None
"""
pass
def predict_proba(self, data):
"""
Get probabilities of prediction for the data.
Parameters
----------
data : optional
Data on which prediction should be done.
Returns
-------
None
"""
pass
def fit(self, data):
"""
Method to fit the data to the model.
Parameters
----------
data : optional
Data which the model should fit to.
Returns
-------
None
"""
pass
def save_model(self, save_path):
"""
Method to save the model to the path provided.
Parameters
----------
save_path : str
Path where the model should be saved
Returns
-------
None
"""
pass
def load_model(self, load_path):
"""
Method to load the model from the given path.
Parameters
----------
load_path : str
Path of the model which should be loaded for the current instance.
Returns
-------
None
"""
pass |
'''
Globals that are used throughout CheckAPI
'''
# Whether to output debugging statements
debug = False
# The model's current working directory
workingdir = "/"
| """
Globals that are used throughout CheckAPI
"""
debug = False
workingdir = '/' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
"""
def fib(x):
if x <= 1:
return 1
if x == 2:
return 2
return fib(x - 1) + fib(x - 2)
def main():
x = 0
f = 2
i = 2
while f < 4000000:
if f % 2 == 0:
x += f
f = fib(i)
i += 1
print(x)
if __name__ == '__main__':
main() | """
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
"""
def fib(x):
if x <= 1:
return 1
if x == 2:
return 2
return fib(x - 1) + fib(x - 2)
def main():
x = 0
f = 2
i = 2
while f < 4000000:
if f % 2 == 0:
x += f
f = fib(i)
i += 1
print(x)
if __name__ == '__main__':
main() |
class SuperPalmTree:
def __init__(self, a: int, b: int, c: float):
self.a = a
self.b = b
self.c = c
def __call__(self, x):
return (self.a + self.b) * x / self.c
def unpack(self):
yield self.a
yield self.b
yield self.c
def param_tuple(self):
return (self.a, self.b, self.c)
| class Superpalmtree:
def __init__(self, a: int, b: int, c: float):
self.a = a
self.b = b
self.c = c
def __call__(self, x):
return (self.a + self.b) * x / self.c
def unpack(self):
yield self.a
yield self.b
yield self.c
def param_tuple(self):
return (self.a, self.b, self.c) |
# functions
def yes_or_no(): # Returns 'yes' or 'no' based on first letter of user input.
while True:
item = input()
if not item or item[0] not in ['y', 'n']:
print('(y)es or (n)o are valid answers')
continue
elif item[0].lower() == 'y':
return 'yes'
elif item[0].lower() == 'n':
return 'no'
| def yes_or_no():
while True:
item = input()
if not item or item[0] not in ['y', 'n']:
print('(y)es or (n)o are valid answers')
continue
elif item[0].lower() == 'y':
return 'yes'
elif item[0].lower() == 'n':
return 'no' |
'''
Author : MiKueen
Level : Medium
Problem Statement : Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
'''
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
res = [[False] * len(s) for i in range(len(s))]
max_sublen = 0
max_indice = (0,0)
for j in range(len(s)):
for i in range(j+1):
res[i][j] = s[i] == s[j] and (j - i < 2 or res[i+1][j-1])
if res[i][j] and max_sublen < j - i + 1:
max_sublen = j - i + 1
max_indice = (i,j)
return s[max_indice[0]:max_indice[1]+1]
| """
Author : MiKueen
Level : Medium
Problem Statement : Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class Solution(object):
def longest_palindrome(self, s):
"""
:type s: str
:rtype: str
"""
res = [[False] * len(s) for i in range(len(s))]
max_sublen = 0
max_indice = (0, 0)
for j in range(len(s)):
for i in range(j + 1):
res[i][j] = s[i] == s[j] and (j - i < 2 or res[i + 1][j - 1])
if res[i][j] and max_sublen < j - i + 1:
max_sublen = j - i + 1
max_indice = (i, j)
return s[max_indice[0]:max_indice[1] + 1] |
# flake8: noqa
RESPONSE_NO_DEPS = """
{
"category": "storage",
"changelog": "created",
"created_at": "2019-05-31T20:06:53.963000Z",
"description": "Extra slots in inventory.",
"downloads_count": 4110,
"homepage": "",
"license": {
"description": "A permissive license that is short and to the point. It lets people do anything with your code with proper attribution and without warranty.",
"name": "mit",
"title": "MIT",
"url": "https://opensource.org/licenses/MIT"
},
"name": "1000BagSize",
"owner": "szojusz",
"releases": [
{
"download_url": "/download/1000BagSize/5cf1895dc6cc70000dafedae",
"file_name": "1000BagSize_0.0.1.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-05-31T20:06:53.960000Z",
"sha1": "8e0a79a21e17969c28c0ed9ace418beb4d5e511b",
"version": "0.0.1"
},
{
"download_url": "/download/1000BagSize/5cf18d3bc6cc70000c7fad41",
"file_name": "1000BagSize_0.1.0.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0"
],
"factorio_version": "0.17.45"
},
"released_at": "2019-05-31T20:23:23.951000Z",
"sha1": "2669b3799cea4d6f93ee7a3a3c0cc70044b562c0",
"version": "0.1.0"
}
],
"score": 0.1333333333333333,
"summary": "Increase the player bag size.",
"tag": {
"name": "storage"
},
"thumbnail": "/assets/.thumb.png",
"title": "1000 Inventory Size",
"updated_at": "2019-05-31T20:23:23.951000Z"
}"""
FULL_RESPONSE = """
{
"name": "bobelectronics",
"owner": "Bobingabout",
"releases": [
{
"download_url": "/download/bobelectronics/5a5f1ae6adcc441024d728b5",
"file_name": "bobelectronics_0.13.0.zip",
"info_json": {
"dependencies": [
"base >= 0.13.0",
"boblibrary >= 0.13.0",
"? bobplates >= 0.13.0"
],
"factorio_version": "0.13"
},
"released_at": "2016-06-28T16:35:32.724000Z",
"sha1": "de8bf6e800a9b32e579211002029f45750897d28",
"version": "0.13.0"
},
{
"download_url": "/download/bobelectronics/5a5f1ae6adcc441024d73340",
"file_name": "bobelectronics_0.13.1.zip",
"info_json": {
"dependencies": [
"base >= 0.13.0",
"boblibrary >= 0.13.0",
"? bobplates >= 0.13.0"
],
"factorio_version": "0.13"
},
"released_at": "2016-06-29T19:09:23.390000Z",
"sha1": "4ddaf71b38f8a661bfd454c3e669e1c10dad4d2c",
"version": "0.13.1"
},
{
"download_url": "/download/bobelectronics/5a5f1ae6adcc441024d741fc",
"file_name": "bobelectronics_0.14.0.zip",
"info_json": {
"dependencies": [
"base >= 0.14.0",
"boblibrary >= 0.14.0",
"? bobplates >= 0.14.0"
],
"factorio_version": "0.14"
},
"released_at": "2016-08-27T20:18:05.636000Z",
"sha1": "62ea63655d9c92e17f22fcd99e529b7c4806d4b8",
"version": "0.14.0"
},
{
"download_url": "/download/bobelectronics/5a5f1ae6adcc441024d731c8",
"file_name": "bobelectronics_0.15.0.zip",
"info_json": {
"dependencies": [
"base >= 0.15.0",
"boblibrary >= 0.15.0",
"? bobplates >= 0.15.0"
],
"factorio_version": "0.15"
},
"released_at": "2017-04-29T18:47:15.715000Z",
"sha1": "aaffbd6025e40d7a7891068c6507f81515086605",
"version": "0.15.0"
},
{
"download_url": "/download/bobelectronics/5a5f1ae6adcc441024d7331e",
"file_name": "bobelectronics_0.15.1.zip",
"info_json": {
"dependencies": [
"base >= 0.15.0",
"boblibrary >= 0.15.0",
"? bobplates >= 0.15.0"
],
"factorio_version": "0.15"
},
"released_at": "2017-05-14T21:13:42.090000Z",
"sha1": "6f8c4bd80ddd7b86878b695dc5132bf29a05d964",
"version": "0.15.1"
},
{
"download_url": "/download/bobelectronics/5a5f1ae6adcc441024d738c9",
"file_name": "bobelectronics_0.15.2.zip",
"info_json": {
"dependencies": [
"base >= 0.15.0",
"boblibrary >= 0.15.0",
"? bobplates >= 0.15.0"
],
"factorio_version": "0.15"
},
"released_at": "2017-05-20T14:42:42.868000Z",
"sha1": "cf7a82579254983ef11e8f5a2e1110c8fcb69d9a",
"version": "0.15.2"
},
{
"download_url": "/download/bobelectronics/5a5f1ae6adcc441024d742d5",
"file_name": "bobelectronics_0.15.3.zip",
"info_json": {
"dependencies": [
"base >= 0.15.0",
"boblibrary >= 0.15.0",
"? bobplates >= 0.15.0"
],
"factorio_version": "0.15"
},
"released_at": "2017-07-03T18:20:58.384000Z",
"sha1": "5a12e7648d55a62750a7c926cf93e3e827947026",
"version": "0.15.3"
},
{
"download_url": "/download/bobelectronics/5a5f1ae6adcc441024d74762",
"file_name": "bobelectronics_0.16.0.zip",
"info_json": {
"dependencies": [
"base >= 0.16.0",
"boblibrary >= 0.16.0",
"? bobplates >= 0.16.0"
],
"factorio_version": "0.16"
},
"released_at": "2017-12-19T00:11:47.165000Z",
"sha1": "ade852984dabf1799d107cf8f36c9bb9281408fb",
"version": "0.16.0"
},
{
"download_url": "/download/bobelectronics/5c75a75ef7e0a9000c2e7c1f",
"file_name": "bobelectronics_0.17.0.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0",
"boblibrary >= 0.17.0",
"? bobplates >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-02-26T20:53:50.274000Z",
"sha1": "0ea84ab2a19199f47f35faa173e48e1824a14381",
"version": "0.17.0"
},
{
"download_url": "/download/bobelectronics/5c86de5f6df489000d878b61",
"file_name": "bobelectronics_0.17.1.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0",
"boblibrary >= 0.17.0",
"? bobplates >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-03-11T22:17:03.873000Z",
"sha1": "94d90a053757a220d04a4ed4f6f31afb8c07b4b2",
"version": "0.17.1"
},
{
"download_url": "/download/bobelectronics/5c941ddfc5acfd000db887f1",
"file_name": "bobelectronics_0.17.2.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0",
"boblibrary >= 0.17.0",
"? bobplates >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-03-21T23:27:27.804000Z",
"sha1": "3c5436d555ba28f8785b73aed69f720337e996f8",
"version": "0.17.2"
},
{
"download_url": "/download/bobelectronics/5cbde4e407f02d000b34fc34",
"file_name": "bobelectronics_0.17.3.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0",
"boblibrary >= 0.17.0",
"? bobplates >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-04-22T15:59:32.535000Z",
"sha1": "dc1d63818a1f38bfcdd160cf51f07b9a5d3d00a2",
"version": "0.17.3"
},
{
"download_url": "/download/bobelectronics/5cca056381d85c000c2b0eb9",
"file_name": "bobelectronics_0.17.4.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0",
"boblibrary >= 0.17.0",
"? bobplates >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-05-01T20:45:23.082000Z",
"sha1": "9f96b76c301002fd1c3b947bfb145c2bdbf8317f",
"version": "0.17.4"
},
{
"download_url": "/download/bobelectronics/5cdee0d4b98c6f000d653e12",
"file_name": "bobelectronics_0.17.5.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0",
"boblibrary >= 0.17.0",
"? bobplates >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-05-17T16:27:00.442000Z",
"sha1": "3a5d3b919147a810822643bcf116c22dd64a5d66",
"version": "0.17.5"
},
{
"download_url": "/download/bobelectronics/5d4c528d0f9321000d769b01",
"file_name": "bobelectronics_0.17.6.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0",
"boblibrary >= 0.17.0",
"? bobplates >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-08-08T16:49:17.945000Z",
"sha1": "dc56d82043d4f0058a2919bab1769855e588aacd",
"version": "0.17.6"
},
{
"download_url": "/download/bobelectronics/5da3191250a256000da5bcd5",
"file_name": "bobelectronics_0.17.7.zip",
"info_json": {
"dependencies": [
"base >= 0.17.0",
"boblibrary >= 0.17.0",
"? bobplates >= 0.17.0"
],
"factorio_version": "0.17"
},
"released_at": "2019-10-13T12:31:14.946000Z",
"sha1": "38173d2ae7b6c967c9494f160641fa24c0772e8b",
"version": "0.17.7"
},
{
"download_url": "/download/bobelectronics/5e299eb5893605000c04c835",
"file_name": "bobelectronics_0.18.0.zip",
"info_json": {
"dependencies": [
"base >= 0.18.0",
"boblibrary >= 0.18.0",
"? bobplates >= 0.18.0"
],
"factorio_version": "0.18"
},
"released_at": "2020-01-23T13:25:09.901000Z",
"sha1": "d77bc717810c295c08de29571c0200eb2e338777",
"version": "0.18.0"
},
{
"download_url": "/download/bobelectronics/5e6aa8f2d1a668000ef958cf",
"file_name": "bobelectronics_0.18.1.zip",
"info_json": {
"dependencies": [
"base >= 0.18.0",
"boblibrary >= 0.18.0",
"? bobplates >= 0.18.0"
],
"factorio_version": "0.18"
},
"released_at": "2020-03-12T21:26:10.482000Z",
"sha1": "4dfd7c77dd29593b2de2c5f74cd3a2ce7547752b",
"version": "0.18.1"
},
{
"download_url": "/download/bobelectronics/5f39ac552e266cbb29961683",
"file_name": "bobelectronics_1.0.0.zip",
"info_json": {
"dependencies": [
"base >= 1.0.0",
"boblibrary >= 0.18.0",
"? bobplates >= 0.18.0"
],
"factorio_version": "1.0"
},
"released_at": "2020-08-16T21:59:49.725000Z",
"sha1": "eb63d5887343fcec93f053cc86426c1305e73e30",
"version": "1.0.0"
},
{
"download_url": "/download/bobelectronics/5fbe8e08bdbc78df511824b4",
"file_name": "bobelectronics_1.1.0.zip",
"info_json": {
"dependencies": [
"base >= 1.1.0",
"boblibrary >= 1.1.0",
"? bobplates >= 1.1.0"
],
"factorio_version": "1.1"
},
"released_at": "2020-11-25T17:02:00.194000Z",
"sha1": "dd0dd00f1b0ced6760e70dbcf0e4b8dbf417e90d",
"version": "1.1.0"
},
{
"download_url": "/download/bobelectronics/5fbfe31f3e5a8fb3b48a4ccd",
"file_name": "bobelectronics_1.1.1.zip",
"info_json": {
"dependencies": [
"base >= 1.1.0",
"boblibrary >= 1.1.0",
"? bobplates >= 1.1.0"
],
"factorio_version": "1.1"
},
"released_at": "2020-11-26T17:17:19.569000Z",
"sha1": "82e6c38d500c63083011a8e04ad4caea4363df8a",
"version": "1.1.1"
},
{
"download_url": "/download/bobelectronics/5fcd528b0d257a3d1e87dbc4",
"file_name": "bobelectronics_1.1.2.zip",
"info_json": {
"dependencies": [
"base >= 1.1.0",
"boblibrary >= 1.1.0",
"? bobplates >= 1.1.0"
],
"factorio_version": "1.1"
},
"released_at": "2020-12-06T21:52:11.886000Z",
"sha1": "27dd8734f5b914c23ee539b761811101d2abae09",
"version": "1.1.2"
},
{
"download_url": "/download/bobelectronics/5fd61a4f65308f55c5bddf27",
"file_name": "bobelectronics_1.0.1.zip",
"info_json": {
"dependencies": [
"base >= 1.0.0",
"boblibrary >= 0.18.0",
"? bobplates >= 0.18.0"
],
"factorio_version": "1.0"
},
"released_at": "2020-12-13T13:42:39.652000Z",
"sha1": "3cc2144f3e185e5bcee8a56fda2b79d986526735",
"version": "1.0.1"
},
{
"download_url": "/download/bobelectronics/600f5ef0732755af120479e9",
"file_name": "bobelectronics_1.1.3.zip",
"info_json": {
"dependencies": [
"base >= 1.1.0",
"boblibrary >= 1.1.0",
"? bobplates >= 1.1.0"
],
"factorio_version": "1.1"
},
"released_at": "2021-01-26T00:14:40.738000Z",
"sha1": "61563e18e5a5a12e11702a737eab3aa6cc58223e",
"version": "1.1.3"
}
],
"score": -525.9666666666668,
"summary": "Adds a whole new electronics production chain.",
"tag": {
"name": "general"
},
"thumbnail": "/assets/03232a436469546d2209b4675de2f460d84815f5.thumb.png",
"title": "Bob's Electronics",
"updated_at": "2021-01-26T00:14:40.741000Z"
}"""
| response_no_deps = '\n{\n\n "category": "storage",\n "changelog": "created",\n "created_at": "2019-05-31T20:06:53.963000Z",\n "description": "Extra slots in inventory.",\n "downloads_count": 4110,\n "homepage": "",\n "license": {\n "description": "A permissive license that is short and to the point. It lets people do anything with your code with proper attribution and without warranty.",\n "name": "mit",\n "title": "MIT",\n "url": "https://opensource.org/licenses/MIT"\n },\n "name": "1000BagSize",\n "owner": "szojusz",\n "releases": [\n {\n "download_url": "/download/1000BagSize/5cf1895dc6cc70000dafedae",\n "file_name": "1000BagSize_0.0.1.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-05-31T20:06:53.960000Z",\n "sha1": "8e0a79a21e17969c28c0ed9ace418beb4d5e511b",\n "version": "0.0.1"\n },\n {\n "download_url": "/download/1000BagSize/5cf18d3bc6cc70000c7fad41",\n "file_name": "1000BagSize_0.1.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0"\n ],\n "factorio_version": "0.17.45"\n },\n "released_at": "2019-05-31T20:23:23.951000Z",\n "sha1": "2669b3799cea4d6f93ee7a3a3c0cc70044b562c0",\n "version": "0.1.0"\n }\n ],\n "score": 0.1333333333333333,\n "summary": "Increase the player bag size.",\n "tag": {\n "name": "storage"\n },\n "thumbnail": "/assets/.thumb.png",\n "title": "1000 Inventory Size",\n "updated_at": "2019-05-31T20:23:23.951000Z"\n\n}'
full_response = '\n{\n "name": "bobelectronics",\n "owner": "Bobingabout",\n "releases": [\n {\n "download_url": "/download/bobelectronics/5a5f1ae6adcc441024d728b5",\n "file_name": "bobelectronics_0.13.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.13.0",\n "boblibrary >= 0.13.0",\n "? bobplates >= 0.13.0"\n ],\n "factorio_version": "0.13"\n },\n "released_at": "2016-06-28T16:35:32.724000Z",\n "sha1": "de8bf6e800a9b32e579211002029f45750897d28",\n "version": "0.13.0"\n },\n {\n "download_url": "/download/bobelectronics/5a5f1ae6adcc441024d73340",\n "file_name": "bobelectronics_0.13.1.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.13.0",\n "boblibrary >= 0.13.0",\n "? bobplates >= 0.13.0"\n ],\n "factorio_version": "0.13"\n },\n "released_at": "2016-06-29T19:09:23.390000Z",\n "sha1": "4ddaf71b38f8a661bfd454c3e669e1c10dad4d2c",\n "version": "0.13.1"\n },\n {\n "download_url": "/download/bobelectronics/5a5f1ae6adcc441024d741fc",\n "file_name": "bobelectronics_0.14.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.14.0",\n "boblibrary >= 0.14.0",\n "? bobplates >= 0.14.0"\n ],\n "factorio_version": "0.14"\n },\n "released_at": "2016-08-27T20:18:05.636000Z",\n "sha1": "62ea63655d9c92e17f22fcd99e529b7c4806d4b8",\n "version": "0.14.0"\n },\n {\n "download_url": "/download/bobelectronics/5a5f1ae6adcc441024d731c8",\n "file_name": "bobelectronics_0.15.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.15.0",\n "boblibrary >= 0.15.0",\n "? bobplates >= 0.15.0"\n ],\n "factorio_version": "0.15"\n },\n "released_at": "2017-04-29T18:47:15.715000Z",\n "sha1": "aaffbd6025e40d7a7891068c6507f81515086605",\n "version": "0.15.0"\n },\n {\n "download_url": "/download/bobelectronics/5a5f1ae6adcc441024d7331e",\n "file_name": "bobelectronics_0.15.1.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.15.0",\n "boblibrary >= 0.15.0",\n "? bobplates >= 0.15.0"\n ],\n "factorio_version": "0.15"\n },\n "released_at": "2017-05-14T21:13:42.090000Z",\n "sha1": "6f8c4bd80ddd7b86878b695dc5132bf29a05d964",\n "version": "0.15.1"\n },\n {\n "download_url": "/download/bobelectronics/5a5f1ae6adcc441024d738c9",\n "file_name": "bobelectronics_0.15.2.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.15.0",\n "boblibrary >= 0.15.0",\n "? bobplates >= 0.15.0"\n ],\n "factorio_version": "0.15"\n },\n "released_at": "2017-05-20T14:42:42.868000Z",\n "sha1": "cf7a82579254983ef11e8f5a2e1110c8fcb69d9a",\n "version": "0.15.2"\n },\n {\n "download_url": "/download/bobelectronics/5a5f1ae6adcc441024d742d5",\n "file_name": "bobelectronics_0.15.3.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.15.0",\n "boblibrary >= 0.15.0",\n "? bobplates >= 0.15.0"\n ],\n "factorio_version": "0.15"\n },\n "released_at": "2017-07-03T18:20:58.384000Z",\n "sha1": "5a12e7648d55a62750a7c926cf93e3e827947026",\n "version": "0.15.3"\n },\n {\n "download_url": "/download/bobelectronics/5a5f1ae6adcc441024d74762",\n "file_name": "bobelectronics_0.16.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.16.0",\n "boblibrary >= 0.16.0",\n "? bobplates >= 0.16.0"\n ],\n "factorio_version": "0.16"\n },\n "released_at": "2017-12-19T00:11:47.165000Z",\n "sha1": "ade852984dabf1799d107cf8f36c9bb9281408fb",\n "version": "0.16.0"\n },\n {\n "download_url": "/download/bobelectronics/5c75a75ef7e0a9000c2e7c1f",\n "file_name": "bobelectronics_0.17.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0",\n "boblibrary >= 0.17.0",\n "? bobplates >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-02-26T20:53:50.274000Z",\n "sha1": "0ea84ab2a19199f47f35faa173e48e1824a14381",\n "version": "0.17.0"\n },\n {\n "download_url": "/download/bobelectronics/5c86de5f6df489000d878b61",\n "file_name": "bobelectronics_0.17.1.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0",\n "boblibrary >= 0.17.0",\n "? bobplates >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-03-11T22:17:03.873000Z",\n "sha1": "94d90a053757a220d04a4ed4f6f31afb8c07b4b2",\n "version": "0.17.1"\n },\n {\n "download_url": "/download/bobelectronics/5c941ddfc5acfd000db887f1",\n "file_name": "bobelectronics_0.17.2.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0",\n "boblibrary >= 0.17.0",\n "? bobplates >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-03-21T23:27:27.804000Z",\n "sha1": "3c5436d555ba28f8785b73aed69f720337e996f8",\n "version": "0.17.2"\n },\n {\n "download_url": "/download/bobelectronics/5cbde4e407f02d000b34fc34",\n "file_name": "bobelectronics_0.17.3.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0",\n "boblibrary >= 0.17.0",\n "? bobplates >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-04-22T15:59:32.535000Z",\n "sha1": "dc1d63818a1f38bfcdd160cf51f07b9a5d3d00a2",\n "version": "0.17.3"\n },\n {\n "download_url": "/download/bobelectronics/5cca056381d85c000c2b0eb9",\n "file_name": "bobelectronics_0.17.4.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0",\n "boblibrary >= 0.17.0",\n "? bobplates >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-05-01T20:45:23.082000Z",\n "sha1": "9f96b76c301002fd1c3b947bfb145c2bdbf8317f",\n "version": "0.17.4"\n },\n {\n "download_url": "/download/bobelectronics/5cdee0d4b98c6f000d653e12",\n "file_name": "bobelectronics_0.17.5.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0",\n "boblibrary >= 0.17.0",\n "? bobplates >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-05-17T16:27:00.442000Z",\n "sha1": "3a5d3b919147a810822643bcf116c22dd64a5d66",\n "version": "0.17.5"\n },\n {\n "download_url": "/download/bobelectronics/5d4c528d0f9321000d769b01",\n "file_name": "bobelectronics_0.17.6.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0",\n "boblibrary >= 0.17.0",\n "? bobplates >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-08-08T16:49:17.945000Z",\n "sha1": "dc56d82043d4f0058a2919bab1769855e588aacd",\n "version": "0.17.6"\n },\n {\n "download_url": "/download/bobelectronics/5da3191250a256000da5bcd5",\n "file_name": "bobelectronics_0.17.7.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.17.0",\n "boblibrary >= 0.17.0",\n "? bobplates >= 0.17.0"\n ],\n "factorio_version": "0.17"\n },\n "released_at": "2019-10-13T12:31:14.946000Z",\n "sha1": "38173d2ae7b6c967c9494f160641fa24c0772e8b",\n "version": "0.17.7"\n },\n {\n "download_url": "/download/bobelectronics/5e299eb5893605000c04c835",\n "file_name": "bobelectronics_0.18.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.18.0",\n "boblibrary >= 0.18.0",\n "? bobplates >= 0.18.0"\n ],\n "factorio_version": "0.18"\n },\n "released_at": "2020-01-23T13:25:09.901000Z",\n "sha1": "d77bc717810c295c08de29571c0200eb2e338777",\n "version": "0.18.0"\n },\n {\n "download_url": "/download/bobelectronics/5e6aa8f2d1a668000ef958cf",\n "file_name": "bobelectronics_0.18.1.zip",\n "info_json": {\n "dependencies": [\n "base >= 0.18.0",\n "boblibrary >= 0.18.0",\n "? bobplates >= 0.18.0"\n ],\n "factorio_version": "0.18"\n },\n "released_at": "2020-03-12T21:26:10.482000Z",\n "sha1": "4dfd7c77dd29593b2de2c5f74cd3a2ce7547752b",\n "version": "0.18.1"\n },\n {\n "download_url": "/download/bobelectronics/5f39ac552e266cbb29961683",\n "file_name": "bobelectronics_1.0.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 1.0.0",\n "boblibrary >= 0.18.0",\n "? bobplates >= 0.18.0"\n ],\n "factorio_version": "1.0"\n },\n "released_at": "2020-08-16T21:59:49.725000Z",\n "sha1": "eb63d5887343fcec93f053cc86426c1305e73e30",\n "version": "1.0.0"\n },\n {\n "download_url": "/download/bobelectronics/5fbe8e08bdbc78df511824b4",\n "file_name": "bobelectronics_1.1.0.zip",\n "info_json": {\n "dependencies": [\n "base >= 1.1.0",\n "boblibrary >= 1.1.0",\n "? bobplates >= 1.1.0"\n ],\n "factorio_version": "1.1"\n },\n "released_at": "2020-11-25T17:02:00.194000Z",\n "sha1": "dd0dd00f1b0ced6760e70dbcf0e4b8dbf417e90d",\n "version": "1.1.0"\n },\n {\n "download_url": "/download/bobelectronics/5fbfe31f3e5a8fb3b48a4ccd",\n "file_name": "bobelectronics_1.1.1.zip",\n "info_json": {\n "dependencies": [\n "base >= 1.1.0",\n "boblibrary >= 1.1.0",\n "? bobplates >= 1.1.0"\n ],\n "factorio_version": "1.1"\n },\n "released_at": "2020-11-26T17:17:19.569000Z",\n "sha1": "82e6c38d500c63083011a8e04ad4caea4363df8a",\n "version": "1.1.1"\n },\n {\n "download_url": "/download/bobelectronics/5fcd528b0d257a3d1e87dbc4",\n "file_name": "bobelectronics_1.1.2.zip",\n "info_json": {\n "dependencies": [\n "base >= 1.1.0",\n "boblibrary >= 1.1.0",\n "? bobplates >= 1.1.0"\n ],\n "factorio_version": "1.1"\n },\n "released_at": "2020-12-06T21:52:11.886000Z",\n "sha1": "27dd8734f5b914c23ee539b761811101d2abae09",\n "version": "1.1.2"\n },\n {\n "download_url": "/download/bobelectronics/5fd61a4f65308f55c5bddf27",\n "file_name": "bobelectronics_1.0.1.zip",\n "info_json": {\n "dependencies": [\n "base >= 1.0.0",\n "boblibrary >= 0.18.0",\n "? bobplates >= 0.18.0"\n ],\n "factorio_version": "1.0"\n },\n "released_at": "2020-12-13T13:42:39.652000Z",\n "sha1": "3cc2144f3e185e5bcee8a56fda2b79d986526735",\n "version": "1.0.1"\n },\n {\n "download_url": "/download/bobelectronics/600f5ef0732755af120479e9",\n "file_name": "bobelectronics_1.1.3.zip",\n "info_json": {\n "dependencies": [\n "base >= 1.1.0",\n "boblibrary >= 1.1.0",\n "? bobplates >= 1.1.0"\n ],\n "factorio_version": "1.1"\n },\n "released_at": "2021-01-26T00:14:40.738000Z",\n "sha1": "61563e18e5a5a12e11702a737eab3aa6cc58223e",\n "version": "1.1.3"\n }\n ],\n "score": -525.9666666666668,\n "summary": "Adds a whole new electronics production chain.",\n "tag": {\n "name": "general"\n },\n "thumbnail": "/assets/03232a436469546d2209b4675de2f460d84815f5.thumb.png",\n "title": "Bob\'s Electronics",\n "updated_at": "2021-01-26T00:14:40.741000Z"\n\n}' |
class BinaryTreeNode:
"""
This class represents a node which can be used to create a Binary Tree.
:Authors: pranaychandekar
"""
def __init__(self, data, left=None, right=None, parent=None):
"""
This method initializes a node for Binary Tree.
:param data: The data to be stored in the node.
:param left: The reference to the left child.
:param right: The reference to the right child.
:param parent: The reference to the parent which can be used for reverse traversal.
"""
self.data = data
self.left = left
self.right = right
self.parent = parent
def set_data(self, data):
"""
This method sets the data in the Binary Tree node.
:param data: The data in the node.
"""
self.data = data
def get_data(self):
"""
This method returns the data in the Binary Tree node.
:return: The data in the node.
"""
return self.data
def has_data(self):
"""
This method returns a boolean flag indicating the presence of data in the node.
:return: The boolean flag validating the presence of the data in the node.
"""
return self.data is not None
def set_left(self, left):
"""
This method sets the left child of the Binary Tree node.
:param left: The reference to the left child.
"""
self.left = left
def get_left(self):
"""
This method returns the left child of the Binary Tree node.
:return: The reference to the left child.
"""
return self.left
def has_left(self):
"""
This method returns the boolean flag indicating the presence of a left child in the node.
:return: The boolean flag validating the presence of the left child in the node.
"""
return self.left is not None
def set_right(self, right):
"""
This method sets the right child of the Binary Tree node.
:param right: The reference to the right child.
"""
self.right = right
def get_right(self):
"""
This method returns the right child of the Binary Tree node.
:return: The reference to the right child.
"""
return self.right
def has_right(self):
"""
This method returns the boolean flag indicating the presence of a right child in the node.
:return: The boolean flag validating the presence of the right child in the node.
"""
return self.right is not None
def set_parent(self, parent):
"""
This method sets the parent of the Binary Tree node.
:param parent: The reference to the parent.
"""
self.parent = parent
def get_parent(self):
"""
This method returns the parent of the Binary Tree node.
:return: The reference to the parent.
"""
return self.parent
def has_parent(self):
"""
This method returns the boolean flag indicating the presence of a parent in the node.
:return: The boolean flag indicating the presence of the parent of the node.
"""
return self.parent is not None
| class Binarytreenode:
"""
This class represents a node which can be used to create a Binary Tree.
:Authors: pranaychandekar
"""
def __init__(self, data, left=None, right=None, parent=None):
"""
This method initializes a node for Binary Tree.
:param data: The data to be stored in the node.
:param left: The reference to the left child.
:param right: The reference to the right child.
:param parent: The reference to the parent which can be used for reverse traversal.
"""
self.data = data
self.left = left
self.right = right
self.parent = parent
def set_data(self, data):
"""
This method sets the data in the Binary Tree node.
:param data: The data in the node.
"""
self.data = data
def get_data(self):
"""
This method returns the data in the Binary Tree node.
:return: The data in the node.
"""
return self.data
def has_data(self):
"""
This method returns a boolean flag indicating the presence of data in the node.
:return: The boolean flag validating the presence of the data in the node.
"""
return self.data is not None
def set_left(self, left):
"""
This method sets the left child of the Binary Tree node.
:param left: The reference to the left child.
"""
self.left = left
def get_left(self):
"""
This method returns the left child of the Binary Tree node.
:return: The reference to the left child.
"""
return self.left
def has_left(self):
"""
This method returns the boolean flag indicating the presence of a left child in the node.
:return: The boolean flag validating the presence of the left child in the node.
"""
return self.left is not None
def set_right(self, right):
"""
This method sets the right child of the Binary Tree node.
:param right: The reference to the right child.
"""
self.right = right
def get_right(self):
"""
This method returns the right child of the Binary Tree node.
:return: The reference to the right child.
"""
return self.right
def has_right(self):
"""
This method returns the boolean flag indicating the presence of a right child in the node.
:return: The boolean flag validating the presence of the right child in the node.
"""
return self.right is not None
def set_parent(self, parent):
"""
This method sets the parent of the Binary Tree node.
:param parent: The reference to the parent.
"""
self.parent = parent
def get_parent(self):
"""
This method returns the parent of the Binary Tree node.
:return: The reference to the parent.
"""
return self.parent
def has_parent(self):
"""
This method returns the boolean flag indicating the presence of a parent in the node.
:return: The boolean flag indicating the presence of the parent of the node.
"""
return self.parent is not None |
# selection sorting is an in-place comparison sort
# O(N^2) time, inefficient for large datasets
# best when memory is limited
def selection_sort(lst):
''' Implementation of selection sort. Efficient with space but not time. Finds the smallest unsorted index (index 0 in the first run) and compares it to all other items in the list. if an item has a smaller numeric value than the smallest unsorted index, it swaps with the smallest of all the values that are smaller. Continues until sorted. '''
if len(lst) < 2:
return lst
for item in range(len(lst)):
# smallest unsorted index
smallest_unsorted_index = item
# look at all unsorted items, don't look at ones before index position lst[item]
for i in range(item+1, len(lst)):
# if a new index value is smaller than the current, we want to swap
# there may be multiple values smaller
if lst[smallest_unsorted_index] > lst[i]:
smallest_unsorted_index = i
# when done with inner loop, swap lst[item] and lst[smallest_unsorted_index]
temp_for_swapping = lst[item]
lst[item] = lst[smallest_unsorted_index]
lst[smallest_unsorted_index] = temp_for_swapping
return lst
| def selection_sort(lst):
""" Implementation of selection sort. Efficient with space but not time. Finds the smallest unsorted index (index 0 in the first run) and compares it to all other items in the list. if an item has a smaller numeric value than the smallest unsorted index, it swaps with the smallest of all the values that are smaller. Continues until sorted. """
if len(lst) < 2:
return lst
for item in range(len(lst)):
smallest_unsorted_index = item
for i in range(item + 1, len(lst)):
if lst[smallest_unsorted_index] > lst[i]:
smallest_unsorted_index = i
temp_for_swapping = lst[item]
lst[item] = lst[smallest_unsorted_index]
lst[smallest_unsorted_index] = temp_for_swapping
return lst |
def list_to_string(lst):
string = ''
for item in lst:
string = string + item
return string
def find_rc(rc):
rc = rc[:: -1]
replacements = {"A": "T",
"T": "A",
"G": "C",
"C": "G"}
rc = "".join([replacements.get(c, c) for c in rc])
return rc
def find_palindromes(x):
sequence = list(x.upper())
end_index = 4
palindromes = []
count = 0
for i in range(0, len(sequence) - 1):
rc = find_rc(sequence[i:end_index])
original = sequence[i:end_index]
end_index += 1
if rc == list_to_string(original):
palindromes.append(i)
count += 1
str_palindromes = ''
for item in palindromes[0:len(palindromes) - 1]:
str_palindromes += str(item)
str_palindromes += ', '
return count, str_palindromes
dna = str(input('Enter seq: '))
print('there are', find_palindromes(dna)[0], 'palindromes at places', find_palindromes(dna)[1], '\n')
| def list_to_string(lst):
string = ''
for item in lst:
string = string + item
return string
def find_rc(rc):
rc = rc[::-1]
replacements = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
rc = ''.join([replacements.get(c, c) for c in rc])
return rc
def find_palindromes(x):
sequence = list(x.upper())
end_index = 4
palindromes = []
count = 0
for i in range(0, len(sequence) - 1):
rc = find_rc(sequence[i:end_index])
original = sequence[i:end_index]
end_index += 1
if rc == list_to_string(original):
palindromes.append(i)
count += 1
str_palindromes = ''
for item in palindromes[0:len(palindromes) - 1]:
str_palindromes += str(item)
str_palindromes += ', '
return (count, str_palindromes)
dna = str(input('Enter seq: '))
print('there are', find_palindromes(dna)[0], 'palindromes at places', find_palindromes(dna)[1], '\n') |
"""
==============
Output Metrics
==============
Currently, ``vivarium`` uses the :ref:`values pipeline system <values_concept>`
to produce the results, or output metrics, from a simulation. The metrics
The component here is a normal ``vivarium`` component whose only purpose is
to provide an empty :class:`dict` as the source of the *"Metrics"* pipeline.
It is included by default in all simulations.
"""
class Metrics:
"""This class declares a value pipeline that allows other components to store summary metrics."""
@property
def name(self):
return "metrics"
def setup(self, builder):
self.metrics = builder.value.register_value_producer('metrics', source=lambda index: {})
def __repr__(self):
return "Metrics()"
| """
==============
Output Metrics
==============
Currently, ``vivarium`` uses the :ref:`values pipeline system <values_concept>`
to produce the results, or output metrics, from a simulation. The metrics
The component here is a normal ``vivarium`` component whose only purpose is
to provide an empty :class:`dict` as the source of the *"Metrics"* pipeline.
It is included by default in all simulations.
"""
class Metrics:
"""This class declares a value pipeline that allows other components to store summary metrics."""
@property
def name(self):
return 'metrics'
def setup(self, builder):
self.metrics = builder.value.register_value_producer('metrics', source=lambda index: {})
def __repr__(self):
return 'Metrics()' |
t = int(input())
for _ in range(t):
s = input()
c = 0
for i in range(len(s)-1):
if abs(ord(s[i]) - ord(s[i+1])) != 1:
c += 1
print (c)
| t = int(input())
for _ in range(t):
s = input()
c = 0
for i in range(len(s) - 1):
if abs(ord(s[i]) - ord(s[i + 1])) != 1:
c += 1
print(c) |
# -*- coding: utf-8 -*-
""" Collection of validator methods """
def validate_required(value):
"""
Method to raise error if a required parameter is not passed in.
:param value: value to check to make sure it is not None
:returns: True or ValueError
"""
if value is None:
raise ValueError('Missing value for argument')
return True
def validate_str_or_list(value):
"""
Method to raise error if a value is not a list.
:param value: value to check to make sure it is a string, list, or None
:returns: None or TypeError
"""
if isinstance(value, (str, list)) or value is None:
return True
else:
raise TypeError('Must be a str or list')
| """ Collection of validator methods """
def validate_required(value):
"""
Method to raise error if a required parameter is not passed in.
:param value: value to check to make sure it is not None
:returns: True or ValueError
"""
if value is None:
raise value_error('Missing value for argument')
return True
def validate_str_or_list(value):
"""
Method to raise error if a value is not a list.
:param value: value to check to make sure it is a string, list, or None
:returns: None or TypeError
"""
if isinstance(value, (str, list)) or value is None:
return True
else:
raise type_error('Must be a str or list') |
class CheckResult:
msg: str = ""
def __init__(self, msg) -> None:
self.msg = msg
class Ok(CheckResult):
pass
class Warn(CheckResult):
pass
class Err(CheckResult):
pass
class Unk(CheckResult):
pass
class Probe:
def __init__(self, **kwargs):
for k, v in kwargs.items():
if v is not None and k in self.__class__.__dict__:
setattr(self, k, v)
@classmethod
def get_help(cls):
return cls.__doc__
@classmethod
def get_type(cls):
return cls.__name__.replace("Probe", "").lower()
@classmethod
def get_args(cls):
return [i for i in cls.__dict__.keys() if i[:1] != "_"]
def get_labels(self):
return {k: getattr(self, k) for k in self.__class__.__dict__ if k[:1] != "_"}
def __call__(self) -> CheckResult:
return Unk("No check implemented")
def __repr__(self):
return f"<{self.__class__.__name__}: {self.get_labels()}>"
| class Checkresult:
msg: str = ''
def __init__(self, msg) -> None:
self.msg = msg
class Ok(CheckResult):
pass
class Warn(CheckResult):
pass
class Err(CheckResult):
pass
class Unk(CheckResult):
pass
class Probe:
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
if v is not None and k in self.__class__.__dict__:
setattr(self, k, v)
@classmethod
def get_help(cls):
return cls.__doc__
@classmethod
def get_type(cls):
return cls.__name__.replace('Probe', '').lower()
@classmethod
def get_args(cls):
return [i for i in cls.__dict__.keys() if i[:1] != '_']
def get_labels(self):
return {k: getattr(self, k) for k in self.__class__.__dict__ if k[:1] != '_'}
def __call__(self) -> CheckResult:
return unk('No check implemented')
def __repr__(self):
return f'<{self.__class__.__name__}: {self.get_labels()}>' |
load(":testing.bzl", "asserts", "test_suite")
load("//maven:sets.bzl", "sets")
def new_test(env):
set = sets.new()
asserts.equals(env, 0, len(set))
set = sets.new("a", "b", "c")
asserts.equals(env, 3, len(set))
asserts.equals(env, ["a", "b", "c"], list(set))
def equality_test(env):
a = sets.new()
b = sets.new()
sets.add(a, "foo1")
sets.add(b, "foo1")
asserts.equals(env, a, b)
def inequality_test(env):
a = sets.new()
b = sets.new()
sets.add(a, "foo1")
sets.add(b, "foo1")
asserts.equals(env, a, b)
def add_test(env):
a = sets.new()
sets.add(a, "foo")
asserts.equals(env, "foo", list(a)[0])
def add_all_as_list_test(env):
a = sets.new()
sets.add_all(a, ["foo", "bar", "baz"])
asserts.equals(env, ["foo", "bar", "baz"], list(a))
def add_all_as_dict_test(env):
a = sets.new()
sets.add_all(a, {"foo": "", "bar": "", "baz": ""})
asserts.equals(env, ["foo", "bar", "baz"], list(a))
def add_each_test(env):
a = sets.new()
sets.add_each(a, "foo", "bar", "baz")
asserts.equals(env, ["foo", "bar", "baz"], list(a))
def set_behavior_test(env):
a = sets.new("foo", "bar", "baz")
sets.add(a, "bar")
asserts.equals(env, ["foo", "bar", "baz"], list(a))
def pop_test(env):
a = sets.new("a", "b", "c")
item = sets.pop(a)
asserts.equals(env, 2, len(a))
item = sets.pop(a)
asserts.equals(env, 1, len(a))
item = sets.pop(a)
asserts.equals(env, 0, len(a))
# Can't test failure, as that invokes bazel fail().
def contains_test(env):
a = sets.new("a")
asserts.true(env, sets.contains(a, "a"))
asserts.false(env, sets.contains(a, "b"))
def difference_test(env):
a = sets.new("a", "b", "c")
b = sets.new ("c", "d", "e")
asserts.equals(env, sets.new("d", "e"), sets.difference(a, b))
asserts.equals(env, sets.new("a", "b"), sets.difference(b, a))
def disjoint_test(env):
a = sets.new("a", "b", "c")
b = sets.new ("c", "d", "e")
asserts.equals(env, sets.new("a", "b", "d", "e"), sets.disjoint(a, b))
TESTS = [
new_test,
equality_test,
inequality_test,
pop_test,
add_test,
add_all_as_dict_test,
add_all_as_list_test,
add_each_test,
set_behavior_test,
contains_test,
difference_test,
disjoint_test,
]
# Roll-up function.
def suite():
return test_suite("sets", tests = TESTS)
| load(':testing.bzl', 'asserts', 'test_suite')
load('//maven:sets.bzl', 'sets')
def new_test(env):
set = sets.new()
asserts.equals(env, 0, len(set))
set = sets.new('a', 'b', 'c')
asserts.equals(env, 3, len(set))
asserts.equals(env, ['a', 'b', 'c'], list(set))
def equality_test(env):
a = sets.new()
b = sets.new()
sets.add(a, 'foo1')
sets.add(b, 'foo1')
asserts.equals(env, a, b)
def inequality_test(env):
a = sets.new()
b = sets.new()
sets.add(a, 'foo1')
sets.add(b, 'foo1')
asserts.equals(env, a, b)
def add_test(env):
a = sets.new()
sets.add(a, 'foo')
asserts.equals(env, 'foo', list(a)[0])
def add_all_as_list_test(env):
a = sets.new()
sets.add_all(a, ['foo', 'bar', 'baz'])
asserts.equals(env, ['foo', 'bar', 'baz'], list(a))
def add_all_as_dict_test(env):
a = sets.new()
sets.add_all(a, {'foo': '', 'bar': '', 'baz': ''})
asserts.equals(env, ['foo', 'bar', 'baz'], list(a))
def add_each_test(env):
a = sets.new()
sets.add_each(a, 'foo', 'bar', 'baz')
asserts.equals(env, ['foo', 'bar', 'baz'], list(a))
def set_behavior_test(env):
a = sets.new('foo', 'bar', 'baz')
sets.add(a, 'bar')
asserts.equals(env, ['foo', 'bar', 'baz'], list(a))
def pop_test(env):
a = sets.new('a', 'b', 'c')
item = sets.pop(a)
asserts.equals(env, 2, len(a))
item = sets.pop(a)
asserts.equals(env, 1, len(a))
item = sets.pop(a)
asserts.equals(env, 0, len(a))
def contains_test(env):
a = sets.new('a')
asserts.true(env, sets.contains(a, 'a'))
asserts.false(env, sets.contains(a, 'b'))
def difference_test(env):
a = sets.new('a', 'b', 'c')
b = sets.new('c', 'd', 'e')
asserts.equals(env, sets.new('d', 'e'), sets.difference(a, b))
asserts.equals(env, sets.new('a', 'b'), sets.difference(b, a))
def disjoint_test(env):
a = sets.new('a', 'b', 'c')
b = sets.new('c', 'd', 'e')
asserts.equals(env, sets.new('a', 'b', 'd', 'e'), sets.disjoint(a, b))
tests = [new_test, equality_test, inequality_test, pop_test, add_test, add_all_as_dict_test, add_all_as_list_test, add_each_test, set_behavior_test, contains_test, difference_test, disjoint_test]
def suite():
return test_suite('sets', tests=TESTS) |
#Write a function that accepts a filename as input argument and reads the file and saves each line of the file as an element
#in a list (without the new line ("\n")character) and returns the list. Each line of the file has comma separated values
# Type your code here
def list_from_file(file_name):
# Make a connection to the file
file_pointer = open(file_name, 'r')
# You can use either .read() or .readline() or .readlines()
data = file_pointer.readlines()
# NOW CONTINUE YOUR CODE FROM HERE!!!
final_list = []
for x in data:
final_list.append(x.strip('\n'))
return final_list
file_pointer.close()
print(list_from_file('file_name.txt')) | def list_from_file(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
final_list = []
for x in data:
final_list.append(x.strip('\n'))
return final_list
file_pointer.close()
print(list_from_file('file_name.txt')) |
# Instruction opcodes
_CHAR = 0
_NEWLINE = 1
_FONT = 2
_COLOR = 3
_SHAKE = 4
_WAIT = 5
_CUSTOM = 6
class Graph:
def __init__(self, default_font):
self.instructions = []
self.default_font = default_font
def string(self, s):
'''Adds a string of characters to the passage.'''
for c in s:
self.instructions.append((_CHAR, c))
def draw(self, dst, x, y):
'''Draw the passage.'''
cursor_x = x
cursor_y = y
font = self.default_font
color = (255, 255, 255)
shake = None
char_index = 0 # For shake effects
for op in self.instructions:
if op[0] == _CHAR:
# The character we need to draw
ch = op[1]
# Offset by shake
off_x, off_y = 0, 0
if shake:
off_x, off_y = shake(char_index)
# Draw it
font.draw_glyph(dst, cursor_x+off_x, cursor_y+off_y, color, ch)
# Advance the cursor
cursor_x += font.get_glyph_width(ch)
char_index += 1
elif op[0] == _NEWLINE:
cursor_x = x
cursor_y += font.get_linesize()
elif op[0] == _FONT:
font = op[1]
elif op[0] == _COLOR:
color = (op[1], op[2], op[3])
elif op[0] == _SHAKE:
shake = op[1]
def newline(self):
'''Add a newline to the passage.'''
self.instructions.append((_NEWLINE,))
def font(self, font):
'''Use a new font for this part of the passage.'''
self.instructions.append((_FONT, font))
def color(self, r, g, b):
'''Use a new color for this part of the passage.'''
self.instructions.append((_COLOR, r, g, b))
def shake(self, func):
'''Use a shake function for this part of the passage.'''
self.instructions.append((_SHAKE, func))
class Typewriter:
'''Wraps around a Graph, throttling character output.'''
def __init__(self, view):
self.view = view
self.queue = []
def slow_string(self, delay, s):
'''Queue up a slow string of characters.'''
for c in s:
self.wait(delay)
self.string(c)
def string(self, s):
'''Queue up a string of characters.'''
for c in s:
self.queue.append((_CHAR, c))
def draw(self, dst, x, y):
'''Draw the graph somewhere.'''
self.view.draw(dst, x, y)
def newline(self):
'''Queue up a newline.'''
self.queue.append((_NEWLINE,))
def font(self, surface_list):
'''Queue up a font change.'''
self.queue.append((_FONT, surface_list))
def color(self, r, g, b):
'''Queue up a color change.'''
self.queue.append((_COLOR, r, g, b))
def shake(self, func):
'''Queue up a shake-function change.'''
self.queue.append((_SHAKE, func))
def pulse(self):
'''Executes the queue up to the first printed character.'''
while self.queue:
op = self.queue.pop(0)
if op[0] == _CHAR:
self.view.string(op[1])
break
elif op[0] == _NEWLINE:
self.view.newline()
elif op[0] == _FONT:
self.view.font(op[1])
elif op[0] == _COLOR:
self.view.color(op[1], op[2], op[3])
elif op[0] == _SHAKE:
self.view.shake(op[1])
elif op[0] == _WAIT:
break
elif op[0] == _CUSTOM:
op[1]()
def flush(self):
'''Flush the whole queue.'''
while self.queue:
self.pulse()
def wait(self, n):
'''Queue up a delay.'''
for _ in xrange(n):
self.queue.append((_WAIT,))
def custom(self, func):
'''Queue up a custom function call.'''
self.queue.append((_CUSTOM, func))
| _char = 0
_newline = 1
_font = 2
_color = 3
_shake = 4
_wait = 5
_custom = 6
class Graph:
def __init__(self, default_font):
self.instructions = []
self.default_font = default_font
def string(self, s):
"""Adds a string of characters to the passage."""
for c in s:
self.instructions.append((_CHAR, c))
def draw(self, dst, x, y):
"""Draw the passage."""
cursor_x = x
cursor_y = y
font = self.default_font
color = (255, 255, 255)
shake = None
char_index = 0
for op in self.instructions:
if op[0] == _CHAR:
ch = op[1]
(off_x, off_y) = (0, 0)
if shake:
(off_x, off_y) = shake(char_index)
font.draw_glyph(dst, cursor_x + off_x, cursor_y + off_y, color, ch)
cursor_x += font.get_glyph_width(ch)
char_index += 1
elif op[0] == _NEWLINE:
cursor_x = x
cursor_y += font.get_linesize()
elif op[0] == _FONT:
font = op[1]
elif op[0] == _COLOR:
color = (op[1], op[2], op[3])
elif op[0] == _SHAKE:
shake = op[1]
def newline(self):
"""Add a newline to the passage."""
self.instructions.append((_NEWLINE,))
def font(self, font):
"""Use a new font for this part of the passage."""
self.instructions.append((_FONT, font))
def color(self, r, g, b):
"""Use a new color for this part of the passage."""
self.instructions.append((_COLOR, r, g, b))
def shake(self, func):
"""Use a shake function for this part of the passage."""
self.instructions.append((_SHAKE, func))
class Typewriter:
"""Wraps around a Graph, throttling character output."""
def __init__(self, view):
self.view = view
self.queue = []
def slow_string(self, delay, s):
"""Queue up a slow string of characters."""
for c in s:
self.wait(delay)
self.string(c)
def string(self, s):
"""Queue up a string of characters."""
for c in s:
self.queue.append((_CHAR, c))
def draw(self, dst, x, y):
"""Draw the graph somewhere."""
self.view.draw(dst, x, y)
def newline(self):
"""Queue up a newline."""
self.queue.append((_NEWLINE,))
def font(self, surface_list):
"""Queue up a font change."""
self.queue.append((_FONT, surface_list))
def color(self, r, g, b):
"""Queue up a color change."""
self.queue.append((_COLOR, r, g, b))
def shake(self, func):
"""Queue up a shake-function change."""
self.queue.append((_SHAKE, func))
def pulse(self):
"""Executes the queue up to the first printed character."""
while self.queue:
op = self.queue.pop(0)
if op[0] == _CHAR:
self.view.string(op[1])
break
elif op[0] == _NEWLINE:
self.view.newline()
elif op[0] == _FONT:
self.view.font(op[1])
elif op[0] == _COLOR:
self.view.color(op[1], op[2], op[3])
elif op[0] == _SHAKE:
self.view.shake(op[1])
elif op[0] == _WAIT:
break
elif op[0] == _CUSTOM:
op[1]()
def flush(self):
"""Flush the whole queue."""
while self.queue:
self.pulse()
def wait(self, n):
"""Queue up a delay."""
for _ in xrange(n):
self.queue.append((_WAIT,))
def custom(self, func):
"""Queue up a custom function call."""
self.queue.append((_CUSTOM, func)) |
class DummyField(object):
def __init__(self, value, **kwargs):
self.value = value
for k_, v_ in kwargs.items():
setattr(self, k_, v_)
| class Dummyfield(object):
def __init__(self, value, **kwargs):
self.value = value
for (k_, v_) in kwargs.items():
setattr(self, k_, v_) |
class TempProps:
def __init__(self, start_temperature, grad_temperature, temperature_coefficient):
self.start_temp = start_temperature
self.grad_temp = grad_temperature
self.temp_coeff = temperature_coefficient
def __str__(self):
out_str = ""
out_str += "start temp: " + str(self.start_temp)
out_str += "\tgrad temp: " + str(self.grad_temp)
out_str += "\ttemp coefficient: " + str(self.temp_coeff)
return out_str
def is_empty(self):
if self.start_temp == 0 and self.grad_temp == 0 and self.temp_coeff == 0:
return True
return False
| class Tempprops:
def __init__(self, start_temperature, grad_temperature, temperature_coefficient):
self.start_temp = start_temperature
self.grad_temp = grad_temperature
self.temp_coeff = temperature_coefficient
def __str__(self):
out_str = ''
out_str += 'start temp: ' + str(self.start_temp)
out_str += '\tgrad temp: ' + str(self.grad_temp)
out_str += '\ttemp coefficient: ' + str(self.temp_coeff)
return out_str
def is_empty(self):
if self.start_temp == 0 and self.grad_temp == 0 and (self.temp_coeff == 0):
return True
return False |
def loss_gen(disc, x_fake):
"""Compute the generator loss for `x_fake` given `disc`
Args:
disc: The generator
x_fake (ndarray): An array of shape (N,) that contains the fake samples
Returns:
ndarray: The generator loss
"""
# Loss for fake data
label_fake = 1
loss_fake = label_fake * torch.log(disc.classify(x_fake))
return loss_fake
# add event to airtable
atform.add_event('Coding Exercise 2.3: The generator loss')
disc = DummyDisc()
gen = DummyGen()
x_fake = gen.sample()
## Uncomment below to check your function
lg = loss_gen(disc, x_fake)
with plt.xkcd():
plotting_lg(lg) | def loss_gen(disc, x_fake):
"""Compute the generator loss for `x_fake` given `disc`
Args:
disc: The generator
x_fake (ndarray): An array of shape (N,) that contains the fake samples
Returns:
ndarray: The generator loss
"""
label_fake = 1
loss_fake = label_fake * torch.log(disc.classify(x_fake))
return loss_fake
atform.add_event('Coding Exercise 2.3: The generator loss')
disc = dummy_disc()
gen = dummy_gen()
x_fake = gen.sample()
lg = loss_gen(disc, x_fake)
with plt.xkcd():
plotting_lg(lg) |
"""
2104. Sum of Subarray Ranges
Medium
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,2,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0
[2], range = 2 - 2 = 0
[3], range = 3 - 3 = 0
[1,2], range = 2 - 1 = 1
[2,3], range = 3 - 2 = 1
[1,2,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.
Example 2:
Input: nums = [1,3,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0
[3], range = 3 - 3 = 0
[3], range = 3 - 3 = 0
[1,3], range = 3 - 1 = 2
[3,3], range = 3 - 3 = 0
[1,3,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.
Example 3:
Input: nums = [4,-2,-3,4,1]
Output: 59
Explanation: The sum of all subarray ranges of nums is 59.
Constraints:
1 <= nums.length <= 1000
-109 <= nums[i] <= 109
Follow-up: Could you find a solution with O(n) time complexity?
"""
# V0
# IDEA : BRUTE FORCE
class Solution:
def subArrayRanges(self, nums):
res = 0
for i in range(len(nums)):
curMin = float("inf")
curMax = -float("inf")
for j in range(i, len(nums)):
curMin = min(curMin, nums[j])
curMax = max(curMax, nums[j])
res += curMax - curMin
return res
# V0'
# IDEA : monotonic stack
# https://zhuanlan.zhihu.com/p/444725220
class Solution:
def subArrayRanges(self, nums):
A, s, res = [-float('inf')] + nums + [-float('inf')], [], 0
for i, num in enumerate(A):
while s and num < A[s[-1]]:
j = s.pop()
res -= (i - j) * (j - s[-1]) * A[j]
s.append(i)
A, s = [float('inf')] + nums + [float('inf')], []
for i, num in enumerate(A):
while s and num > A[s[-1]]:
j = s.pop()
res += (i - j) * (j - s[-1]) * A[j]
s.append(i)
return res
# V0''
# IDEA : INCREASING STACK
class Solution:
def subArrayRanges(self, A0):
res = 0
inf = float('inf')
A = [-inf] + A0 + [-inf]
s = []
for i, x in enumerate(A):
while s and A[s[-1]] > x:
j = s.pop()
k = s[-1]
res -= A[j] * (i - j) * (j - k)
s.append(i)
A = [inf] + A0 + [inf]
s = []
for i, x in enumerate(A):
while s and A[s[-1]] < x:
j = s.pop()
k = s[-1]
res += A[j] * (i - j) * (j - k)
s.append(i)
return res
# V1
# IDEA : BRUTE FORCE
# https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624303/python-bruct-foce
class Solution:
def subArrayRanges(self, nums):
res = 0
for i in range(len(nums)):
curMin = float("inf")
curMax = -float("inf")
for j in range(i, len(nums)):
curMin = min(curMin, nums[j])
curMax = max(curMax, nums[j])
res += curMax - curMin
return res
# V1'
# IDEA : 2 POINTERS + stack
# https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624222/JavaC%2B%2BPython-O(n)-solution-detailed-explanation
# IDEA:
# Follow the explanation in 907. Sum of Subarray Minimums
#
# Intuition
# res = sum(A[i] * f(i))
# where f(i) is the number of subarrays,
# in which A[i] is the minimum.
#
# To get f(i), we need to find out:
# left[i], the length of strict bigger numbers on the left of A[i],
# right[i], the length of bigger numbers on the right of A[i].
#
# Then,
# left[i] + 1 equals to
# the number of subarray ending with A[i],
# and A[i] is single minimum.
#
# right[i] + 1 equals to
# the number of subarray starting with A[i],
# and A[i] is the first minimum.
#
# Finally f(i) = (left[i] + 1) * (right[i] + 1)
#
# For [3,1,2,4] as example:
# left + 1 = [1,2,1,1]
# right + 1 = [1,3,2,1]
# f = [1,6,2,1]
# res = 3 * 1 + 1 * 6 + 2 * 2 + 4 * 1 = 17
#
# Explanation
# To calculate left[i] and right[i],
# we use two increasing stacks.
#
# It will be easy if you can refer to this problem and my post:
# 901. Online Stock Span
# I copy some of my codes from this solution.
class Solution:
def subArrayRanges(self, A0):
res = 0
inf = float('inf')
A = [-inf] + A0 + [-inf]
s = []
for i, x in enumerate(A):
while s and A[s[-1]] > x:
j = s.pop()
k = s[-1]
res -= A[j] * (i - j) * (j - k)
s.append(i)
A = [inf] + A0 + [inf]
s = []
for i, x in enumerate(A):
while s and A[s[-1]] < x:
j = s.pop()
k = s[-1]
res += A[j] * (i - j) * (j - k)
s.append(i)
return res
# V1''
# IDEA : monotonic stack
# https://zhuanlan.zhihu.com/p/444725220
class Solution:
def subArrayRanges(self, nums):
A, s, res = [-float('inf')] + nums + [-float('inf')], [], 0
for i, num in enumerate(A):
while s and num < A[s[-1]]:
j = s.pop()
res -= (i - j) * (j - s[-1]) * A[j]
s.append(i)
A, s = [float('inf')] + nums + [float('inf')], []
for i, num in enumerate(A):
while s and num > A[s[-1]]:
j = s.pop()
res += (i - j) * (j - s[-1]) * A[j]
s.append(i)
return res
# V1'''
# IDEA : BRUTE FORCE
# https://blog.csdn.net/sinat_30403031/article/details/122082809
# V1''''
# IDEA : 2 POINTERS
# https://www.codeleading.com/article/65096149220/
class Solution:
def subArrayRanges(self, nums):
count = 0
for i in range(len(nums) - 1):
# set left index = i
max_num = min_num = nums[i]
# here we need to record current max, min. So can count diff sum
for t in range(i+1, len(nums)):
# keep moving left pointer
if nums[t] < min_num:
min_num = nums[t]
if nums[t] > max_num:
max_num = nums[t]
count += max_num - min_num
return count
# V1'''''
# IDEA : sumSubarray
# https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1638345/Python-0(n)
class Solution:
def subArrayRanges(self, nums):
return self.sumSubarray(nums, operator.gt) - self.sumSubarray(nums, operator.lt)
def sumSubarray(self, arr, comp):
n = len(arr)
stack = []
res = 0
for idx in range(n+1):
while stack and (idx == n or comp(arr[idx], arr[stack[-1]])):
curr, prev = stack[-1], stack[-2] if len(stack) > 1 else -1
res = res + (arr[curr] * (idx - curr) * (curr - prev))
stack.pop()
stack.append(idx)
return res
# V1'''''''
# IDEA : DP
# https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624305/Python-DP-Solution
class Solution:
def subArrayRanges(self, nums):
dp = [[(None, None) for i in range(len(nums))] for j in range(len(nums))]
dp[len(nums) -1][len(nums) -1] = (nums[len(nums) -1], nums[len(nums) -1])
res = 0
for i in range(len(nums) -2, -1, -1):
for j in range(i, len(nums)):
if dp[i][j-1] != (None, None):
dp[i][j] = (max(dp[i][j-1][0], nums[j]), min(dp[i][j-1][1], nums[j]))
elif dp[i + 1][j] != (None, None):
dp[i][j] = (max(dp[i + 1][j][0], nums[i]), min(dp[i + 1][j][1], nums[i]))
else:
dp[i][j] = (nums[i], nums[j])
res += dp[i][j][0] - dp[i][j][1]
return res
# V2 | """
2104. Sum of Subarray Ranges
Medium
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,2,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0
[2], range = 2 - 2 = 0
[3], range = 3 - 3 = 0
[1,2], range = 2 - 1 = 1
[2,3], range = 3 - 2 = 1
[1,2,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.
Example 2:
Input: nums = [1,3,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0
[3], range = 3 - 3 = 0
[3], range = 3 - 3 = 0
[1,3], range = 3 - 1 = 2
[3,3], range = 3 - 3 = 0
[1,3,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.
Example 3:
Input: nums = [4,-2,-3,4,1]
Output: 59
Explanation: The sum of all subarray ranges of nums is 59.
Constraints:
1 <= nums.length <= 1000
-109 <= nums[i] <= 109
Follow-up: Could you find a solution with O(n) time complexity?
"""
class Solution:
def sub_array_ranges(self, nums):
res = 0
for i in range(len(nums)):
cur_min = float('inf')
cur_max = -float('inf')
for j in range(i, len(nums)):
cur_min = min(curMin, nums[j])
cur_max = max(curMax, nums[j])
res += curMax - curMin
return res
class Solution:
def sub_array_ranges(self, nums):
(a, s, res) = ([-float('inf')] + nums + [-float('inf')], [], 0)
for (i, num) in enumerate(A):
while s and num < A[s[-1]]:
j = s.pop()
res -= (i - j) * (j - s[-1]) * A[j]
s.append(i)
(a, s) = ([float('inf')] + nums + [float('inf')], [])
for (i, num) in enumerate(A):
while s and num > A[s[-1]]:
j = s.pop()
res += (i - j) * (j - s[-1]) * A[j]
s.append(i)
return res
class Solution:
def sub_array_ranges(self, A0):
res = 0
inf = float('inf')
a = [-inf] + A0 + [-inf]
s = []
for (i, x) in enumerate(A):
while s and A[s[-1]] > x:
j = s.pop()
k = s[-1]
res -= A[j] * (i - j) * (j - k)
s.append(i)
a = [inf] + A0 + [inf]
s = []
for (i, x) in enumerate(A):
while s and A[s[-1]] < x:
j = s.pop()
k = s[-1]
res += A[j] * (i - j) * (j - k)
s.append(i)
return res
class Solution:
def sub_array_ranges(self, nums):
res = 0
for i in range(len(nums)):
cur_min = float('inf')
cur_max = -float('inf')
for j in range(i, len(nums)):
cur_min = min(curMin, nums[j])
cur_max = max(curMax, nums[j])
res += curMax - curMin
return res
class Solution:
def sub_array_ranges(self, A0):
res = 0
inf = float('inf')
a = [-inf] + A0 + [-inf]
s = []
for (i, x) in enumerate(A):
while s and A[s[-1]] > x:
j = s.pop()
k = s[-1]
res -= A[j] * (i - j) * (j - k)
s.append(i)
a = [inf] + A0 + [inf]
s = []
for (i, x) in enumerate(A):
while s and A[s[-1]] < x:
j = s.pop()
k = s[-1]
res += A[j] * (i - j) * (j - k)
s.append(i)
return res
class Solution:
def sub_array_ranges(self, nums):
(a, s, res) = ([-float('inf')] + nums + [-float('inf')], [], 0)
for (i, num) in enumerate(A):
while s and num < A[s[-1]]:
j = s.pop()
res -= (i - j) * (j - s[-1]) * A[j]
s.append(i)
(a, s) = ([float('inf')] + nums + [float('inf')], [])
for (i, num) in enumerate(A):
while s and num > A[s[-1]]:
j = s.pop()
res += (i - j) * (j - s[-1]) * A[j]
s.append(i)
return res
class Solution:
def sub_array_ranges(self, nums):
count = 0
for i in range(len(nums) - 1):
max_num = min_num = nums[i]
for t in range(i + 1, len(nums)):
if nums[t] < min_num:
min_num = nums[t]
if nums[t] > max_num:
max_num = nums[t]
count += max_num - min_num
return count
class Solution:
def sub_array_ranges(self, nums):
return self.sumSubarray(nums, operator.gt) - self.sumSubarray(nums, operator.lt)
def sum_subarray(self, arr, comp):
n = len(arr)
stack = []
res = 0
for idx in range(n + 1):
while stack and (idx == n or comp(arr[idx], arr[stack[-1]])):
(curr, prev) = (stack[-1], stack[-2] if len(stack) > 1 else -1)
res = res + arr[curr] * (idx - curr) * (curr - prev)
stack.pop()
stack.append(idx)
return res
class Solution:
def sub_array_ranges(self, nums):
dp = [[(None, None) for i in range(len(nums))] for j in range(len(nums))]
dp[len(nums) - 1][len(nums) - 1] = (nums[len(nums) - 1], nums[len(nums) - 1])
res = 0
for i in range(len(nums) - 2, -1, -1):
for j in range(i, len(nums)):
if dp[i][j - 1] != (None, None):
dp[i][j] = (max(dp[i][j - 1][0], nums[j]), min(dp[i][j - 1][1], nums[j]))
elif dp[i + 1][j] != (None, None):
dp[i][j] = (max(dp[i + 1][j][0], nums[i]), min(dp[i + 1][j][1], nums[i]))
else:
dp[i][j] = (nums[i], nums[j])
res += dp[i][j][0] - dp[i][j][1]
return res |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/armor"
# docs_base_url = "https://[org_name].github.io/armor"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "Armor"
| """
Configuration for docs
"""
def get_context(context):
context.brand_html = 'Armor' |
class SmallArray():
def __init__(self) -> None:
self.clusters = 0
self.cluster_size = 0 | class Smallarray:
def __init__(self) -> None:
self.clusters = 0
self.cluster_size = 0 |
class ValidationError(Exception):
pass
class empty(Exception):
pass
| class Validationerror(Exception):
pass
class Empty(Exception):
pass |
# 1 and 9
TERMINAL_INDICES = [0, 8, 9, 17, 18, 26]
# dragons and winds
EAST = 27
SOUTH = 28
WEST = 29
NORTH = 30
HAKU = 31
HATSU = 32
CHUN = 33
WINDS = [EAST, SOUTH, WEST, NORTH]
HONOR_INDICES = WINDS + [HAKU, HATSU, CHUN]
FIVE_RED_MAN = 16
FIVE_RED_PIN = 52
FIVE_RED_SOU = 88
AKA_DORA_LIST = [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]
DISPLAY_WINDS = {
EAST: 'East',
SOUTH: 'South',
WEST: 'West',
NORTH: 'North'
}
| terminal_indices = [0, 8, 9, 17, 18, 26]
east = 27
south = 28
west = 29
north = 30
haku = 31
hatsu = 32
chun = 33
winds = [EAST, SOUTH, WEST, NORTH]
honor_indices = WINDS + [HAKU, HATSU, CHUN]
five_red_man = 16
five_red_pin = 52
five_red_sou = 88
aka_dora_list = [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]
display_winds = {EAST: 'East', SOUTH: 'South', WEST: 'West', NORTH: 'North'} |
# #class
class user:
def __init__(self,first_name,last_name,birth,sex): # this is the main class's (attribute)function , self is the main v
self.first_name=first_name
self.last_name=last_name
self.birth=birth
self.sex=sex
def grit(self):
print (f"name: {self.first_name},{self.last_name}, year: {self.birth}")
def calc_age (self, curr_year):
return 2021-self.birth
def calc_avg(self,other): #static
z=(self.calc_age(2021)+other.calc_age(2021))/2
return z
user_data=input(" Enter Ur name , last name , birth year, sex separated by pint: ").split(".")
user1=user("paul" ,"yo" ,1991 ,"male")
# user1.grit()
# print(user1.calc_age(2021))
user2=user("mariam","khoury",1993,"female")
# user2.grit()
# a= user.calc_avg (user1,user2)
# print(a)
user3=user(user_data[0],user_data[1],user_data[2],user_data[3])
user3.grit()
# import math as m # here we call it as new name (m)
# import os #???????
# import antigravity
# # pypi.org
# import random
# import cos
# x=10
# y=m.pow(x,2) #math.cos()
# print(y)
# __name__=="__main__"
# side file
# def printing(name):
# print(f"I am afraid {name}")
# if __name__=="__main__":
# print("wubba lubba DbDub")
# main file
# import my_file
# n=input("enter your friend's name: ")
# my_file.printing(n) | class User:
def __init__(self, first_name, last_name, birth, sex):
self.first_name = first_name
self.last_name = last_name
self.birth = birth
self.sex = sex
def grit(self):
print(f'name: {self.first_name},{self.last_name}, year: {self.birth}')
def calc_age(self, curr_year):
return 2021 - self.birth
def calc_avg(self, other):
z = (self.calc_age(2021) + other.calc_age(2021)) / 2
return z
user_data = input(' Enter Ur name , last name , birth year, sex separated by pint: ').split('.')
user1 = user('paul', 'yo', 1991, 'male')
user2 = user('mariam', 'khoury', 1993, 'female')
user3 = user(user_data[0], user_data[1], user_data[2], user_data[3])
user3.grit() |
class BaseCSSIException(Exception):
"""The base of all CSSI library exceptions."""
pass
class CSSIException(BaseCSSIException):
"""An exception specific to CSSI library"""
pass
| class Basecssiexception(Exception):
"""The base of all CSSI library exceptions."""
pass
class Cssiexception(BaseCSSIException):
"""An exception specific to CSSI library"""
pass |
#$Id$
class ExchangeRate:
"""This class is used to create object for Exchange rate."""
def __init__(self):
"""Initialize parameters for exchange rate."""
self.exchange_rate_id = ''
self.currency_id = ''
self.currency_code = ''
self.effective_date = ''
self.rate = 0.0
def set_exchange_rate_id(self, exchange_rate_id):
"""Set exchange rate id.
Args:
exchange_rate_id(str): Exchange rate id.
"""
self.exchange_rate_id = exchange_rate_id
def get_exchange_rate_id(self):
"""Get exchange rate id.
Returns:
str: Exchange rate id.
"""
return self.exchange_rate_id
def set_currency_id(self, currency_id):
"""Set currency id.
Args:
currency_id(str): Currency id.
"""
self.currency_id = currency_id
def get_currency_id(self):
"""Get currency id.
Returns:
str: Currency id.
"""
return self.currency_id
def set_currency_code(self, currency_code):
"""Set currency code.
Args:
currency_code(str): Currency code.
"""
self.currency_code = currency_code
def get_currency_code(self):
"""Get currency code.
Returns:
str: Currency code.
"""
return self.currency_code
def set_effective_date(self, effective_date):
"""Set effective date.
Args:
effective_date(str): Effective date.
"""
self.effective_date = effective_date
def get_effective_date(self):
"""Get effective date.
Returns:
str: Effective date.
"""
return self.effective_date
def set_rate(self, rate):
"""Set rate.
Args:
rate(float): Rate.
"""
self.rate = rate
def get_rate(self):
"""Get rate.
Returns:
float: Rate.
"""
return self.rate
def to_json(self):
"""This method is used to create json object for exchange rate.
Returns:
dict: Dictionary containing json object for exchange rate.
"""
data = {}
if self.currency_id != '':
data['currency_id'] = self.currency_id
if self.currency_code != '':
data['currency_code'] = self.currency_code
if self.effective_date != '':
data['effective_date'] = self.effective_date
if self.rate > 0:
data['rate'] = self.rate
if self.effective_date != '':
data['effective_date'] = self.effective_date
return data
| class Exchangerate:
"""This class is used to create object for Exchange rate."""
def __init__(self):
"""Initialize parameters for exchange rate."""
self.exchange_rate_id = ''
self.currency_id = ''
self.currency_code = ''
self.effective_date = ''
self.rate = 0.0
def set_exchange_rate_id(self, exchange_rate_id):
"""Set exchange rate id.
Args:
exchange_rate_id(str): Exchange rate id.
"""
self.exchange_rate_id = exchange_rate_id
def get_exchange_rate_id(self):
"""Get exchange rate id.
Returns:
str: Exchange rate id.
"""
return self.exchange_rate_id
def set_currency_id(self, currency_id):
"""Set currency id.
Args:
currency_id(str): Currency id.
"""
self.currency_id = currency_id
def get_currency_id(self):
"""Get currency id.
Returns:
str: Currency id.
"""
return self.currency_id
def set_currency_code(self, currency_code):
"""Set currency code.
Args:
currency_code(str): Currency code.
"""
self.currency_code = currency_code
def get_currency_code(self):
"""Get currency code.
Returns:
str: Currency code.
"""
return self.currency_code
def set_effective_date(self, effective_date):
"""Set effective date.
Args:
effective_date(str): Effective date.
"""
self.effective_date = effective_date
def get_effective_date(self):
"""Get effective date.
Returns:
str: Effective date.
"""
return self.effective_date
def set_rate(self, rate):
"""Set rate.
Args:
rate(float): Rate.
"""
self.rate = rate
def get_rate(self):
"""Get rate.
Returns:
float: Rate.
"""
return self.rate
def to_json(self):
"""This method is used to create json object for exchange rate.
Returns:
dict: Dictionary containing json object for exchange rate.
"""
data = {}
if self.currency_id != '':
data['currency_id'] = self.currency_id
if self.currency_code != '':
data['currency_code'] = self.currency_code
if self.effective_date != '':
data['effective_date'] = self.effective_date
if self.rate > 0:
data['rate'] = self.rate
if self.effective_date != '':
data['effective_date'] = self.effective_date
return data |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
STATIC_DEBUG = DEBUG
CRISPY_FAIL_SILENTLY = not DEBUG
ADMINS = (
('Dummy', 'dummy@example.org'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'NAME': 'sdemo.db',
'ENGINE': 'django.db.backends.sqlite3',
'USER': '',
'PASSWORD': ''
}
}
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin media
# USE TRAILING SLASH
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
# Make this unique, and don't share it with anybody.
# Remember to change this!
SECRET_KEY = 'lic-@(-)mi^b&**h1ggnbyya2qiivaop-@c#3@m3w%m1o73j8@' | debug = True
template_debug = DEBUG
static_debug = DEBUG
crispy_fail_silently = not DEBUG
admins = (('Dummy', 'dummy@example.org'),)
managers = ADMINS
databases = {'default': {'NAME': 'sdemo.db', 'ENGINE': 'django.db.backends.sqlite3', 'USER': '', 'PASSWORD': ''}}
media_root = ''
media_url = ''
static_root = ''
static_url = '/static/'
admin_media_prefix = STATIC_URL + 'admin/'
secret_key = 'lic-@(-)mi^b&**h1ggnbyya2qiivaop-@c#3@m3w%m1o73j8@' |
"""
Reference values for the nwchem test calculations within ExPrESS
All nwchem output values are in hartrees. ExPrESS converts units to eV.
All reference energies are in eV.
"""
TOTAL_ENERGY = -2079.18666382721904
TOTAL_ENERGY_CONTRIBUTION = {
"one_electron": {
"name": "one_electron",
"value": -3350.531714067630674
},
"coulomb": {
"name": "coulomb",
"value": 1275.68347728573713
},
"exchange_correlation": {
"name": "exchange_correlation",
"value": -254.54658374762781
},
"nuclear_repulsion": {
"name": "nuclear_repulsion",
"value": 250.20815670232923
}
}
BASIS = {
"units": "angstrom",
"elements": [
{
"id": 1,
"value": "O"
},
{
"id": 2,
"value": "H"
},
{
"id": 3,
"value": "H"
}
],
"coordinates": [
{
"id": 1,
"value": [
0.00000000,
0.00000000,
0.22143053
]
},
{
"id": 2,
"value": [
0.00000000,
1.43042809,
-0.88572213
]
},
{
"id": 3,
"value": [
0.00000000,
-1.43042809,
-0.88572213
]
}
]
}
| """
Reference values for the nwchem test calculations within ExPrESS
All nwchem output values are in hartrees. ExPrESS converts units to eV.
All reference energies are in eV.
"""
total_energy = -2079.186663827219
total_energy_contribution = {'one_electron': {'name': 'one_electron', 'value': -3350.5317140676307}, 'coulomb': {'name': 'coulomb', 'value': 1275.6834772857371}, 'exchange_correlation': {'name': 'exchange_correlation', 'value': -254.5465837476278}, 'nuclear_repulsion': {'name': 'nuclear_repulsion', 'value': 250.20815670232923}}
basis = {'units': 'angstrom', 'elements': [{'id': 1, 'value': 'O'}, {'id': 2, 'value': 'H'}, {'id': 3, 'value': 'H'}], 'coordinates': [{'id': 1, 'value': [0.0, 0.0, 0.22143053]}, {'id': 2, 'value': [0.0, 1.43042809, -0.88572213]}, {'id': 3, 'value': [0.0, -1.43042809, -0.88572213]}]} |
# -*- coding: utf-8 -*-
"""
Python implementation of Karatsuba's multiplication algorithm
"""
def karatsuba_mutiplication(x, y):
xstr = str(x)
ystr = str(y)
length = max(len(xstr), len(ystr))
if length > 1:
xstr = "0" * (length - len(xstr)) + xstr
ystr = "0" * (length - len(ystr)) + ystr
xh = int(xstr[:length//2])
xl = int(xstr[length//2:])
yh = int(ystr[:length//2])
yl = int(ystr[length//2:])
a = karatsuba_mutiplication(xh, yh)
d = karatsuba_mutiplication(xl, yl)
e = karatsuba_mutiplication(xh + xl, yh + yl) - a - d
base = length - length // 2
xy = a * 10 ** (base * 2) + e * 10 ** base + d
return xy
else:
return int(x) * int(y)
if __name__ == "__main__":
x = 3141592653589793238462643383279502884197169399375105820974944592
y = 2718281828459045235360287471352662497757247093699959574966967627
xy = karatsuba_mutiplication(x, y)
print(xy)
print(xy - x * y)
| """
Python implementation of Karatsuba's multiplication algorithm
"""
def karatsuba_mutiplication(x, y):
xstr = str(x)
ystr = str(y)
length = max(len(xstr), len(ystr))
if length > 1:
xstr = '0' * (length - len(xstr)) + xstr
ystr = '0' * (length - len(ystr)) + ystr
xh = int(xstr[:length // 2])
xl = int(xstr[length // 2:])
yh = int(ystr[:length // 2])
yl = int(ystr[length // 2:])
a = karatsuba_mutiplication(xh, yh)
d = karatsuba_mutiplication(xl, yl)
e = karatsuba_mutiplication(xh + xl, yh + yl) - a - d
base = length - length // 2
xy = a * 10 ** (base * 2) + e * 10 ** base + d
return xy
else:
return int(x) * int(y)
if __name__ == '__main__':
x = 3141592653589793238462643383279502884197169399375105820974944592
y = 2718281828459045235360287471352662497757247093699959574966967627
xy = karatsuba_mutiplication(x, y)
print(xy)
print(xy - x * y) |
def path(current, visited_small_caves, cmap):
if current == 'end':
return [[current]]
next_caves = cmap[current]
paths = []
for next_cave in next_caves:
if next_cave in visited_small_caves:
continue
if next_cave.islower():
next_visited_small_caves = visited_small_caves + [next_cave]
else:
next_visited_small_caves = visited_small_caves
followups = path(next_cave, next_visited_small_caves, cmap)
for followup in followups:
paths.append([current] + followup)
return paths
with open('input.txt') as input:
connections = [(line.split('-')[0], line.strip().split('-')[1]) for line in input.readlines()]
# build connection map
cmap = {}
for s, e in connections:
if s in cmap:
cmap[s].append(e)
else:
cmap[s] = [e]
if e in cmap:
cmap[e].append(s)
else:
cmap[e] = [s]
paths = path('start', ['start'], cmap)
print(len(paths)) # 4754 | def path(current, visited_small_caves, cmap):
if current == 'end':
return [[current]]
next_caves = cmap[current]
paths = []
for next_cave in next_caves:
if next_cave in visited_small_caves:
continue
if next_cave.islower():
next_visited_small_caves = visited_small_caves + [next_cave]
else:
next_visited_small_caves = visited_small_caves
followups = path(next_cave, next_visited_small_caves, cmap)
for followup in followups:
paths.append([current] + followup)
return paths
with open('input.txt') as input:
connections = [(line.split('-')[0], line.strip().split('-')[1]) for line in input.readlines()]
cmap = {}
for (s, e) in connections:
if s in cmap:
cmap[s].append(e)
else:
cmap[s] = [e]
if e in cmap:
cmap[e].append(s)
else:
cmap[e] = [s]
paths = path('start', ['start'], cmap)
print(len(paths)) |
# -*- coding: utf-8 -*-
"""
Package Description.
"""
__version__ = "0.0.1"
__short_description__ = "Numpy/Pandas based module make faster data analysis"
__license__ = "MIT"
__author__ = "fuwiak"
__author_email__ = "poczta130@gmail.com"
__maintainer__ = "unknown maintainer"
__maintainer_email__ = "maintainer@example.com"
__github_username__ = "fuwiak" | """
Package Description.
"""
__version__ = '0.0.1'
__short_description__ = 'Numpy/Pandas based module make faster data analysis'
__license__ = 'MIT'
__author__ = 'fuwiak'
__author_email__ = 'poczta130@gmail.com'
__maintainer__ = 'unknown maintainer'
__maintainer_email__ = 'maintainer@example.com'
__github_username__ = 'fuwiak' |
def func1(a):
a += 1
def funct2(b):
val = 1+b
return val
return funct2(a)
print(func1(5)) | def func1(a):
a += 1
def funct2(b):
val = 1 + b
return val
return funct2(a)
print(func1(5)) |
# You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
# The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".
# Example 1:
# Input: J = "aA", S = "aAAbbbb"
# Output: 3
# Example 2:
# Input: J = "z", S = "ZZ"
# Output: 0
# Note:
# S and J will consist of letters and have length at most 50.
# The characters in J are distinct.
class Solution:
def numJewelsInStones(self, J, S):
count=0
if (J.isalpha() and S.isalpha() and len(J) <= 50 and len(S) <= 50):
for stones in S:
if stones in J:
count +=1
return count
if __name__ == "__main__":
J="aA"
S="aAAbbbb"
print(Solution().numJewelsInStones(J,S)) | class Solution:
def num_jewels_in_stones(self, J, S):
count = 0
if J.isalpha() and S.isalpha() and (len(J) <= 50) and (len(S) <= 50):
for stones in S:
if stones in J:
count += 1
return count
if __name__ == '__main__':
j = 'aA'
s = 'aAAbbbb'
print(solution().numJewelsInStones(J, S)) |
#identify cycles in a linked list
def has_cycle(head):
taboo_list = list()
temp = head
while temp:
if temp not in taboo_list:
taboo_list.append(temp)
temp = temp.next
else:
return 1
return 0
| def has_cycle(head):
taboo_list = list()
temp = head
while temp:
if temp not in taboo_list:
taboo_list.append(temp)
temp = temp.next
else:
return 1
return 0 |
# CAN controls for MQB platform Volkswagen, Audi, Skoda and SEAT.
# PQ35/PQ46/NMS, and any future MLB, to come later.
def create_mqb_steering_control(packer, bus, apply_steer, idx, lkas_enabled):
values = {
"SET_ME_0X3": 0x3,
"Assist_Torque": abs(apply_steer),
"Assist_Requested": lkas_enabled,
"Assist_VZ": 1 if apply_steer < 0 else 0,
"HCA_Available": 1,
"HCA_Standby": not lkas_enabled,
"HCA_Active": lkas_enabled,
"SET_ME_0XFE": 0xFE,
"SET_ME_0X07": 0x07,
}
return packer.make_can_msg("HCA_01", bus, values, idx)
def create_mqb_hud_control(packer, bus, enabled, steering_pressed, hud_alert, left_lane_visible, right_lane_visible,
ldw_stock_values, left_lane_depart, right_lane_depart):
# Lane color reference:
# 0 (LKAS disabled) - off
# 1 (LKAS enabled, no lane detected) - dark gray
# 2 (LKAS enabled, lane detected) - light gray on VW, green or white on Audi depending on year or virtual cockpit. On a color MFD on a 2015 A3 TDI it is white, virtual cockpit on a 2018 A3 e-Tron its green.
# 3 (LKAS enabled, lane departure detected) - white on VW, red on Audi
values = ldw_stock_values.copy()
values.update({
"LDW_Status_LED_gelb": 1 if enabled and steering_pressed else 0,
"LDW_Status_LED_gruen": 1 if enabled and not steering_pressed else 0,
"LDW_Lernmodus_links": 3 if left_lane_depart else 1 + left_lane_visible,
"LDW_Lernmodus_rechts": 3 if right_lane_depart else 1 + right_lane_visible,
"LDW_Texte": hud_alert,
})
return packer.make_can_msg("LDW_02", bus, values)
def create_mqb_acc_buttons_control(packer, bus, buttonStatesToSend, CS, idx):
values = {
"GRA_Hauptschalter": CS.graHauptschalter,
"GRA_Abbrechen": buttonStatesToSend["cancel"],
"GRA_Tip_Setzen": buttonStatesToSend["setCruise"],
"GRA_Tip_Hoch": buttonStatesToSend["accelCruise"],
"GRA_Tip_Runter": buttonStatesToSend["decelCruise"],
"GRA_Tip_Wiederaufnahme": buttonStatesToSend["resumeCruise"],
"GRA_Verstellung_Zeitluecke": 3 if buttonStatesToSend["gapAdjustCruise"] else 0,
"GRA_Typ_Hauptschalter": CS.graTypHauptschalter,
"GRA_Codierung": 2,
"GRA_Tip_Stufe_2": CS.graTipStufe2,
"GRA_ButtonTypeInfo": CS.graButtonTypeInfo
}
return packer.make_can_msg("GRA_ACC_01", bus, values, idx)
def create_mqb_acc_02_control(packer, bus, acc_status, set_speed, speed_visible, lead_visible, idx):
values = {
"ACC_Status_Anzeige": 3 if acc_status == 5 else acc_status,
"ACC_Wunschgeschw": 327.36 if not speed_visible else set_speed,
"ACC_Gesetzte_Zeitluecke": 3,
"ACC_Display_Prio": 3,
"ACC_Abstandsindex": 637 if lead_visible else 0,
}
return packer.make_can_msg("ACC_02", bus, values, idx)
def create_mqb_acc_04_control(packer, bus, acc_04_stock_values, idx):
values = acc_04_stock_values.copy()
# Suppress disengagement alert from stock radar when OP long is in use, but passthru FCW/AEB alerts
if values["ACC_Texte_braking_guard"] == 4:
values["ACC_Texte_braking_guard"] = 0
return packer.make_can_msg("ACC_04", bus, values, idx)
def create_mqb_acc_06_control(packer, bus, enabled, acc_status, accel, acc_stopping, acc_starting,
cb_pos, cb_neg, acc_type, idx):
values = {
"ACC_Typ": acc_type,
"ACC_Status_ACC": acc_status,
"ACC_StartStopp_Info": enabled,
"ACC_Sollbeschleunigung_02": accel if enabled else 3.01,
"ACC_zul_Regelabw_unten": cb_neg,
"ACC_zul_Regelabw_oben": cb_pos,
"ACC_neg_Sollbeschl_Grad_02": 4.0 if enabled else 0,
"ACC_pos_Sollbeschl_Grad_02": 4.0 if enabled else 0,
"ACC_Anfahren": acc_starting,
"ACC_Anhalten": acc_stopping,
}
return packer.make_can_msg("ACC_06", bus, values, idx)
def create_mqb_acc_07_control(packer, bus, enabled, accel, acc_hold_request, acc_hold_release,
acc_hold_type, stopping_distance, idx):
values = {
"ACC_Distance_to_Stop": stopping_distance,
"ACC_Hold_Request": acc_hold_request,
"ACC_Freewheel_Type": 2 if enabled else 0,
"ACC_Hold_Type": acc_hold_type,
"ACC_Hold_Release": acc_hold_release,
"ACC_Accel_Secondary": 3.02, # not using this unless and until we understand its impact
"ACC_Accel_TSK": accel if enabled else 3.01,
}
return packer.make_can_msg("ACC_07", bus, values, idx)
| def create_mqb_steering_control(packer, bus, apply_steer, idx, lkas_enabled):
values = {'SET_ME_0X3': 3, 'Assist_Torque': abs(apply_steer), 'Assist_Requested': lkas_enabled, 'Assist_VZ': 1 if apply_steer < 0 else 0, 'HCA_Available': 1, 'HCA_Standby': not lkas_enabled, 'HCA_Active': lkas_enabled, 'SET_ME_0XFE': 254, 'SET_ME_0X07': 7}
return packer.make_can_msg('HCA_01', bus, values, idx)
def create_mqb_hud_control(packer, bus, enabled, steering_pressed, hud_alert, left_lane_visible, right_lane_visible, ldw_stock_values, left_lane_depart, right_lane_depart):
values = ldw_stock_values.copy()
values.update({'LDW_Status_LED_gelb': 1 if enabled and steering_pressed else 0, 'LDW_Status_LED_gruen': 1 if enabled and (not steering_pressed) else 0, 'LDW_Lernmodus_links': 3 if left_lane_depart else 1 + left_lane_visible, 'LDW_Lernmodus_rechts': 3 if right_lane_depart else 1 + right_lane_visible, 'LDW_Texte': hud_alert})
return packer.make_can_msg('LDW_02', bus, values)
def create_mqb_acc_buttons_control(packer, bus, buttonStatesToSend, CS, idx):
values = {'GRA_Hauptschalter': CS.graHauptschalter, 'GRA_Abbrechen': buttonStatesToSend['cancel'], 'GRA_Tip_Setzen': buttonStatesToSend['setCruise'], 'GRA_Tip_Hoch': buttonStatesToSend['accelCruise'], 'GRA_Tip_Runter': buttonStatesToSend['decelCruise'], 'GRA_Tip_Wiederaufnahme': buttonStatesToSend['resumeCruise'], 'GRA_Verstellung_Zeitluecke': 3 if buttonStatesToSend['gapAdjustCruise'] else 0, 'GRA_Typ_Hauptschalter': CS.graTypHauptschalter, 'GRA_Codierung': 2, 'GRA_Tip_Stufe_2': CS.graTipStufe2, 'GRA_ButtonTypeInfo': CS.graButtonTypeInfo}
return packer.make_can_msg('GRA_ACC_01', bus, values, idx)
def create_mqb_acc_02_control(packer, bus, acc_status, set_speed, speed_visible, lead_visible, idx):
values = {'ACC_Status_Anzeige': 3 if acc_status == 5 else acc_status, 'ACC_Wunschgeschw': 327.36 if not speed_visible else set_speed, 'ACC_Gesetzte_Zeitluecke': 3, 'ACC_Display_Prio': 3, 'ACC_Abstandsindex': 637 if lead_visible else 0}
return packer.make_can_msg('ACC_02', bus, values, idx)
def create_mqb_acc_04_control(packer, bus, acc_04_stock_values, idx):
values = acc_04_stock_values.copy()
if values['ACC_Texte_braking_guard'] == 4:
values['ACC_Texte_braking_guard'] = 0
return packer.make_can_msg('ACC_04', bus, values, idx)
def create_mqb_acc_06_control(packer, bus, enabled, acc_status, accel, acc_stopping, acc_starting, cb_pos, cb_neg, acc_type, idx):
values = {'ACC_Typ': acc_type, 'ACC_Status_ACC': acc_status, 'ACC_StartStopp_Info': enabled, 'ACC_Sollbeschleunigung_02': accel if enabled else 3.01, 'ACC_zul_Regelabw_unten': cb_neg, 'ACC_zul_Regelabw_oben': cb_pos, 'ACC_neg_Sollbeschl_Grad_02': 4.0 if enabled else 0, 'ACC_pos_Sollbeschl_Grad_02': 4.0 if enabled else 0, 'ACC_Anfahren': acc_starting, 'ACC_Anhalten': acc_stopping}
return packer.make_can_msg('ACC_06', bus, values, idx)
def create_mqb_acc_07_control(packer, bus, enabled, accel, acc_hold_request, acc_hold_release, acc_hold_type, stopping_distance, idx):
values = {'ACC_Distance_to_Stop': stopping_distance, 'ACC_Hold_Request': acc_hold_request, 'ACC_Freewheel_Type': 2 if enabled else 0, 'ACC_Hold_Type': acc_hold_type, 'ACC_Hold_Release': acc_hold_release, 'ACC_Accel_Secondary': 3.02, 'ACC_Accel_TSK': accel if enabled else 3.01}
return packer.make_can_msg('ACC_07', bus, values, idx) |
#
# gambit
#
# Configuration file for gravity inversion for use by planeGravInv.py
# mesh has been made with mkGeoWithData2D.py
#
# Inversion constants:
#
# scale between misfit and regularization
mu = 1.e-14
#
# used to scale computed density. kg/m^3
rho_0 = 1.
#
# IPCG tolerance *|r| <= atol+rtol*|r0|* (energy norm)
# absolute tolerance for IPCG interations
atol = 0.
#
# relative tolerance for IPCG iterations
rtol = 1.e-3
#
# tolerance for solving PDEs
# make sure this is not more than the square of rtol
pdetol = 1.e-10
#
# maximum number of IPCG iterations
iter_max = 500
#
# data scale. Program assumes m/s^2,
# converts micrometres/s^2 to m/s^2
data_scale = 1.e-6
#
#
# File names
# mesh file name. This needs to be in msh or fly format
mesh_name = "G_201x338test.fly"
#
# data file name in netcdf format. See readme.md for more details.
data_file = "Gravity_201x338.nc"
#
# output file name for .csv output and silo output
output_name = "G_test_201x338_rho0_{0:1.3e}_mu_{1:1.3e}".format(rho_0,mu)
#
#
# Level for the verbosity of the output, "low", "medium" or "high".
# low:
# screen outputs:
# data range,
# summaries of gravity data and final gravity
# initial, final and difference misfits
# file output:
# silo of final solution
# medium: low outputs +
# screen outputs:
# residual norm from the IPCG iterations
# high: medium outputs +
# screen outputs:
# misfit and smoothing value at each iteration step
# file outputs:
# csv files for misfit and smoothing at each IPCG iteration
# silos at misfit values of 0.05, 0.01, 0.008 and 0.005. (Initial misfit is 0.5.)
VerboseLevel = "low"
#VerboseLevel = "medium"
#VerboseLevel = "high"
| mu = 1e-14
rho_0 = 1.0
atol = 0.0
rtol = 0.001
pdetol = 1e-10
iter_max = 500
data_scale = 1e-06
mesh_name = 'G_201x338test.fly'
data_file = 'Gravity_201x338.nc'
output_name = 'G_test_201x338_rho0_{0:1.3e}_mu_{1:1.3e}'.format(rho_0, mu)
verbose_level = 'low' |
def countWaysToChangeDigit(value):
result = 0
for i in str(value):
result += 9 - int(i)
return result
| def count_ways_to_change_digit(value):
result = 0
for i in str(value):
result += 9 - int(i)
return result |
def product(x):
t = 1
for n in x:
t *= n
return t
| def product(x):
t = 1
for n in x:
t *= n
return t |
"""
Medium puzzle
Algorithm to find scores while climbing the leaderboard
Given 2 sorted lists:
- Scoreboard: [100, 100, 80, 60]
- Alice: [50, 60, 75, 105]
Find the scores of alice
Ans: [3, 2, 2, 1]
"""
def countRankings(arr):
# Gets initial rankings
count = 1
if len(arr) == 1:
return count
for i in range(1, len(arr), 1):
if arr[i] != arr[i - 1]:
count += 1
return count
# Complete the climbingLeaderboard function below.
# Overall algo: time complexity O(nm)
def climbingLeaderboard(scores, alice):
current = countRankings(scores) + 1
ptr = len(scores) - 1
arr = []
prev = 0
# iterate through alice's scores
for alice_score in alice:
# while condition to move pointer
while (ptr >= 0):
if scores[ptr] == prev:
ptr -= 1
continue
# check if larger than score
if scores[ptr] > alice_score:
break
current -= 1
prev = scores[ptr]
ptr -= 1
# once stop moving pointer, append to array
arr.append(current)
return arr
| """
Medium puzzle
Algorithm to find scores while climbing the leaderboard
Given 2 sorted lists:
- Scoreboard: [100, 100, 80, 60]
- Alice: [50, 60, 75, 105]
Find the scores of alice
Ans: [3, 2, 2, 1]
"""
def count_rankings(arr):
count = 1
if len(arr) == 1:
return count
for i in range(1, len(arr), 1):
if arr[i] != arr[i - 1]:
count += 1
return count
def climbing_leaderboard(scores, alice):
current = count_rankings(scores) + 1
ptr = len(scores) - 1
arr = []
prev = 0
for alice_score in alice:
while ptr >= 0:
if scores[ptr] == prev:
ptr -= 1
continue
if scores[ptr] > alice_score:
break
current -= 1
prev = scores[ptr]
ptr -= 1
arr.append(current)
return arr |
# Note: The schema is stored in a .py file in order to take advantage of the
# int() and float() type coercion functions. Otherwise it could easily stored as
# as JSON or another serialized format.
'''This schema has been changed compared to the Udacity schema,
due to missing values for attributes 'user' and 'uid'.
It makes sense to keep them in the schema for use of other OSM data.'''
schema = {
'node': {
'type': 'dict',
'schema': {
'id': {'required': True, 'type': 'integer', 'coerce': int},
'lat': {'required': True, 'type': 'float', 'coerce': float},
'lon': {'required': True, 'type': 'float', 'coerce': float},
'user': {'required': False, 'type': 'string'},
'uid': {'required': False, 'type': 'integer', 'coerce': int},
'version': {'required': True, 'type': 'string'},
'changeset': {'required': True, 'type': 'integer', 'coerce': int},
'timestamp': {'required': True, 'type': 'string'}
}
},
'node_tags': {
'type': 'list',
'schema': {
'type': 'dict',
'schema': {
'id': {'required': True, 'type': 'integer', 'coerce': int},
'key': {'required': True, 'type': 'string'},
'value': {'required': True, 'type': 'string'},
'type': {'required': True, 'type': 'string'}
}
}
},
'way': {
'type': 'dict',
'schema': {
'id': {'required': True, 'type': 'integer', 'coerce': int},
'user': {'required': False, 'type': 'string'},
'uid': {'required': False, 'type': 'integer', 'coerce': int},
'version': {'required': True, 'type': 'string'},
'changeset': {'required': True, 'type': 'integer', 'coerce': int},
'timestamp': {'required': True, 'type': 'string'}
}
},
'way_nodes': {
'type': 'list',
'schema': {
'type': 'dict',
'schema': {
'id': {'required': True, 'type': 'integer', 'coerce': int},
'node_id': {'required': True, 'type': 'integer', 'coerce': int},
'position': {'required': True, 'type': 'integer', 'coerce': int}
}
}
},
'way_tags': {
'type': 'list',
'schema': {
'type': 'dict',
'schema': {
'id': {'required': True, 'type': 'integer', 'coerce': int},
'key': {'required': True, 'type': 'string'},
'value': {'required': True, 'type': 'string'},
'type': {'required': True, 'type': 'string'}
}
}
}
}
| """This schema has been changed compared to the Udacity schema,
due to missing values for attributes 'user' and 'uid'.
It makes sense to keep them in the schema for use of other OSM data."""
schema = {'node': {'type': 'dict', 'schema': {'id': {'required': True, 'type': 'integer', 'coerce': int}, 'lat': {'required': True, 'type': 'float', 'coerce': float}, 'lon': {'required': True, 'type': 'float', 'coerce': float}, 'user': {'required': False, 'type': 'string'}, 'uid': {'required': False, 'type': 'integer', 'coerce': int}, 'version': {'required': True, 'type': 'string'}, 'changeset': {'required': True, 'type': 'integer', 'coerce': int}, 'timestamp': {'required': True, 'type': 'string'}}}, 'node_tags': {'type': 'list', 'schema': {'type': 'dict', 'schema': {'id': {'required': True, 'type': 'integer', 'coerce': int}, 'key': {'required': True, 'type': 'string'}, 'value': {'required': True, 'type': 'string'}, 'type': {'required': True, 'type': 'string'}}}}, 'way': {'type': 'dict', 'schema': {'id': {'required': True, 'type': 'integer', 'coerce': int}, 'user': {'required': False, 'type': 'string'}, 'uid': {'required': False, 'type': 'integer', 'coerce': int}, 'version': {'required': True, 'type': 'string'}, 'changeset': {'required': True, 'type': 'integer', 'coerce': int}, 'timestamp': {'required': True, 'type': 'string'}}}, 'way_nodes': {'type': 'list', 'schema': {'type': 'dict', 'schema': {'id': {'required': True, 'type': 'integer', 'coerce': int}, 'node_id': {'required': True, 'type': 'integer', 'coerce': int}, 'position': {'required': True, 'type': 'integer', 'coerce': int}}}}, 'way_tags': {'type': 'list', 'schema': {'type': 'dict', 'schema': {'id': {'required': True, 'type': 'integer', 'coerce': int}, 'key': {'required': True, 'type': 'string'}, 'value': {'required': True, 'type': 'string'}, 'type': {'required': True, 'type': 'string'}}}}} |
class Port:
def __init__(self, mac_address, ip_address, mtu):
self.mac_address = mac_address
self.ip_address = ip_address
self.mtu = mtu
def __str__(self):
return '(%s - %s - %d)' % (self.mac_address, self.ip_address, self.mtu)
| class Port:
def __init__(self, mac_address, ip_address, mtu):
self.mac_address = mac_address
self.ip_address = ip_address
self.mtu = mtu
def __str__(self):
return '(%s - %s - %d)' % (self.mac_address, self.ip_address, self.mtu) |
class Context:
def __init__(self, **kwargs):
self.message = kwargs.get("message")
self.command = kwargs.get("command")
def print(self, content, *, indent=0, **kwargs):
if indent > 0:
lines = content.split("\n")
for line in lines:
prefix = "| " * indent
print(prefix + line, **kwargs)
else:
print(content, **kwargs)
def print_empty(self, indent=0):
if indent > 0:
print("| " * indent)
else:
print()
| class Context:
def __init__(self, **kwargs):
self.message = kwargs.get('message')
self.command = kwargs.get('command')
def print(self, content, *, indent=0, **kwargs):
if indent > 0:
lines = content.split('\n')
for line in lines:
prefix = '| ' * indent
print(prefix + line, **kwargs)
else:
print(content, **kwargs)
def print_empty(self, indent=0):
if indent > 0:
print('| ' * indent)
else:
print() |
'''
Config! Change as needed.
NOTE: Please make sure that all information (except for authentication keys)
are passed in lower-case!
'''
# Your twitter access tokens. These are your accounts that you will enter giveaways from.
# Add as many users as you want, and please make sure to enter your username in lower case!
access_tokens = {
"user1" : {
'consumer_key' : '',
'consumer_secret' : '',
'access_token' : '',
'access_token_secret' : ''
},
"user2" : {
'consumer_key' : '',
'consumer_secret' : '',
'access_token' : '',
'access_token_secret' : ''
},
"user3" : {
'consumer_key' : '',
'consumer_secret' : '',
'access_token' : '',
'access_token_secret' : ''
}
}
# REQUIRED
# Users that you would like to tag in the giveaway. Add three users here.
tag_users = ["z1rk4", "user2", "user3"]
#REQUIRED
# Keywords that the bot will search for in tweets. Change/add as many as you want!
keywords = ["giveaway", "coding", "python"]
# OPTIONAL
# Account names that you want to specifically search for giveaway tweets.
# Add as many as you want!
account_names = ["giveaway_account1", "giveaway_account2", "giveaway_account3"]
# OPTIONAL
# Add your own custom replies here that are triggered upon a specific keyword.
# NOTE: Program may not be able to send reply if replies are too long! Please be careful
# with how many custom replies you use :)
custom_replies = {
"keyword1" : "reply1",
"keyword2" : "reply2",
"keyword3" : "reply3",
}
'''
Leave the variables below alone if you do not have the respective information.
'''
# OPTIONAL
# Your steam trade link
trade_link = ""
# OPTIONAL
# Your wax trade link
wax_trade_link = ""
# OPTIONAL
# Your DatDrop profile link
datdrop_profile_link = ""
# IGNORE
link_paste_keywords = ["tradelink", "trade link", " tl"] | """
Config! Change as needed.
NOTE: Please make sure that all information (except for authentication keys)
are passed in lower-case!
"""
access_tokens = {'user1': {'consumer_key': '', 'consumer_secret': '', 'access_token': '', 'access_token_secret': ''}, 'user2': {'consumer_key': '', 'consumer_secret': '', 'access_token': '', 'access_token_secret': ''}, 'user3': {'consumer_key': '', 'consumer_secret': '', 'access_token': '', 'access_token_secret': ''}}
tag_users = ['z1rk4', 'user2', 'user3']
keywords = ['giveaway', 'coding', 'python']
account_names = ['giveaway_account1', 'giveaway_account2', 'giveaway_account3']
custom_replies = {'keyword1': 'reply1', 'keyword2': 'reply2', 'keyword3': 'reply3'}
'\nLeave the variables below alone if you do not have the respective information.\n'
trade_link = ''
wax_trade_link = ''
datdrop_profile_link = ''
link_paste_keywords = ['tradelink', 'trade link', ' tl'] |
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for token in tokens:
if token not in "+-*/":
stack.append(int(token))
else:
b = stack.pop()
a = stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
else:
if a * b < 0:
stack.append(-(abs(a) / abs(b)))
else:
stack.append(a / b)
return stack[0]
| class Solution(object):
def eval_rpn(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for token in tokens:
if token not in '+-*/':
stack.append(int(token))
else:
b = stack.pop()
a = stack.pop()
if token == '+':
stack.append(a + b)
elif token == '-':
stack.append(a - b)
elif token == '*':
stack.append(a * b)
elif a * b < 0:
stack.append(-(abs(a) / abs(b)))
else:
stack.append(a / b)
return stack[0] |
n, m = [int(x) for x in input().split()]
edges = [[int(x) for x in input().split()] for _ in range(m)]
if m < n - 1:
print(0)
exit()
paths = []
start = 1
still_possible = True
while still_possible:
passed = [1]
current = start
for i in range(1, n):
for e in edges:
if e[0] == current and e[1] != current and not (e[1] in passed):
for path in paths:
if path[i] == e[1]:
break
else:
passed.append(e[1])
current = e[1]
break
elif e[0] != current and e[1] == current and not (e[0] in passed):
for path in paths:
if path[i] == e[0]:
break
else:
passed.append(e[0])
current = e[0]
break
else: # if e all in edges are not accepted
if passed == [1]:
still_possible = False
break
if len(passed) == n:
paths.append(passed)
print(len(paths))
| (n, m) = [int(x) for x in input().split()]
edges = [[int(x) for x in input().split()] for _ in range(m)]
if m < n - 1:
print(0)
exit()
paths = []
start = 1
still_possible = True
while still_possible:
passed = [1]
current = start
for i in range(1, n):
for e in edges:
if e[0] == current and e[1] != current and (not e[1] in passed):
for path in paths:
if path[i] == e[1]:
break
else:
passed.append(e[1])
current = e[1]
break
elif e[0] != current and e[1] == current and (not e[0] in passed):
for path in paths:
if path[i] == e[0]:
break
else:
passed.append(e[0])
current = e[0]
break
else:
if passed == [1]:
still_possible = False
break
if len(passed) == n:
paths.append(passed)
print(len(paths)) |
def is_unique_points(points=None):
if points is None:
points = {}
points_dict = {}
for key, values in points.items():
new_key = '%s:%s' % tuple(values)
is_exists = points_dict.get(new_key, None)
if is_exists:
return False
else:
points_dict[new_key] = key
return True
| def is_unique_points(points=None):
if points is None:
points = {}
points_dict = {}
for (key, values) in points.items():
new_key = '%s:%s' % tuple(values)
is_exists = points_dict.get(new_key, None)
if is_exists:
return False
else:
points_dict[new_key] = key
return True |
"""
Conditionally Yours
Pseudocode:
"""
# Increase = Current Price - Original Price
# Percent Increase = Increase / Original x 100
# Create integer variable for original_price
# Create integer variable for current_price
# Create float for threshold_to_buy
# Create float for threshold_to_sell
# Create float for portfolio balance
# Create float for balance check
# Create string for recommendation, default will be buy
recommendation = "buy"
# Calculate difference between current_price and original_price
# Calculate percent increase
# Print original_price
print(f"Netflix's original stock price was ${original_price}")
# Print current_price
# Print percent increase
# Determine if stock should be bought or sold
# Print recommendation
print("Recommendation: " + recommendation)
print()
print("But wait a minute... lets check your excess equity first.")
# Challenge
# Declare balance variable as a float
# Declare balance_check variable
balance_check = balance * 5
# Compare balance to recommendation, checking whether or not balance is 5 times more than current_price
print(f"You currently have ${balance} in excess equity available in your portfolio.")
# IF-ELSE Logic to determine recommendation based off of balance check
| """
Conditionally Yours
Pseudocode:
"""
recommendation = 'buy'
print(f"Netflix's original stock price was ${original_price}")
print('Recommendation: ' + recommendation)
print()
print('But wait a minute... lets check your excess equity first.')
balance_check = balance * 5
print(f'You currently have ${balance} in excess equity available in your portfolio.') |
def containsDuplicate(nums):
sorted = sorted(nums)
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False | def contains_duplicate(nums):
sorted = sorted(nums)
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
return True
return False |
def find_max(root):
if not root:
return 0
if not root.left and not root.right:
return root.val
m = [0]
helper(root, m)
return m[0]
def helper(n, m):
if n.val > m[0]:
m[0] = n.val
if n.left:
helper(n.left, m)
if n.right:
helper(n.right, m)
| def find_max(root):
if not root:
return 0
if not root.left and (not root.right):
return root.val
m = [0]
helper(root, m)
return m[0]
def helper(n, m):
if n.val > m[0]:
m[0] = n.val
if n.left:
helper(n.left, m)
if n.right:
helper(n.right, m) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def getMedian(left: ListNode, right: ListNode) -> ListNode:
fast = slow = left
while fast != right and fast.next != right:
fast = fast.next.next
slow = slow.next
return slow
def recursive(left, right):
if left == right: return None
mid = getMedian(left, right)
root = TreeNode(mid.val)
root.left = recursive(left, mid)
root.right = recursive(mid.next, right)
return root
return recursive(head, None)
| class Solution:
def sorted_list_to_bst(self, head: ListNode) -> TreeNode:
def get_median(left: ListNode, right: ListNode) -> ListNode:
fast = slow = left
while fast != right and fast.next != right:
fast = fast.next.next
slow = slow.next
return slow
def recursive(left, right):
if left == right:
return None
mid = get_median(left, right)
root = tree_node(mid.val)
root.left = recursive(left, mid)
root.right = recursive(mid.next, right)
return root
return recursive(head, None) |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 11:06:08 2017
@author: James Jiang
"""
def position(range_firewall, time):
offset = time % (2 * (range_firewall - 1))
if offset > range_firewall - 1:
return(2 * (range_firewall - 1) - offset)
else:
return(offset)
all_lines = [line.rstrip('\n') for line in open('Data.txt')]
ranges = {}
for i in all_lines:
pair = i.split(': ')
ranges[int(pair[0])] = int(pair[1])
severity = 0
for i in ranges:
if position(ranges[i], i) == 0:
severity += ranges[i] * i
print(severity)
| """
Created on Wed Dec 13 11:06:08 2017
@author: James Jiang
"""
def position(range_firewall, time):
offset = time % (2 * (range_firewall - 1))
if offset > range_firewall - 1:
return 2 * (range_firewall - 1) - offset
else:
return offset
all_lines = [line.rstrip('\n') for line in open('Data.txt')]
ranges = {}
for i in all_lines:
pair = i.split(': ')
ranges[int(pair[0])] = int(pair[1])
severity = 0
for i in ranges:
if position(ranges[i], i) == 0:
severity += ranges[i] * i
print(severity) |
#!/usr/bin/env python3
def chdir(path, folder):
return path+"/"+folder
def previous(path):
temp = ""
for i in path.split("/")[1:-1]:
temp += "/"+i
return temp
| def chdir(path, folder):
return path + '/' + folder
def previous(path):
temp = ''
for i in path.split('/')[1:-1]:
temp += '/' + i
return temp |
# Bradley Grose
data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s"
print(format_string % data) | data = ('John', 'Doe', 53.44)
format_string = 'Hello %s %s. Your current balance is $%s'
print(format_string % data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.