content
stringlengths 7
1.05M
|
---|
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
|
{
"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()
|
# -*- coding: utf-8 -*-
TITLE = "SUUUUPPPEEERRR Paper Plane v01"
HOME_OPTION_PLAY = "Jouer"
HOME_OPTION_PLAY_LVL = "Niveau"
HOME_OPTION_PLAY_SHORT_LVL = "NIV"
HOME_OPTION_OPTIONS = "Options"
HOME_OPTION_OPTIONS_COLOR = "Couleur"
HOME_OPTION_OPTIONS_COLOR_BLUE = "Bleu"
HOME_OPTION_OPTIONS_COLOR_BLACK = "Noir"
HOME_OPTION_OPTIONS_COLOR_BROWN = "Marron"
HOME_OPTION_OPTIONS_COLOR_RED = "Rouge"
HOME_OPTION_OPTIONS_COLOR_ORANGE = "Orange"
HOME_OPTION_OPTIONS_DISPLAY = u"Résolution"
HOME_OPTION_OPTIONS_DISPLAY_WINDOWED = u"Fenêtré"
HOME_OPTION_OPTIONS_DISPLAY_FULLSCREEN = u"Plein écran"
HOME_OPTION_OPTIONS_LANG = "Langues"
HOME_OPTION_QUIT = "Quitter"
GAME_CRASHED_NONHIGHSCORE = u"Espèce de loooooser !"
GAME_CRASHED_NEWHIGHSCORE = u"Est le nouveau meilleur score"
GAME_CRASHED_BUTTON_ESCAPE = u"<ÉCHAPE> Menu principale"
GAME_CRASHED_BUTTON_RETRY = u"<ENTRER> Réessayer"
GAME_PAUSE = "Jeu en Pause"
GAME_PAUSE_BUTTON_CONTINUE = u"Appuyez sur <p> pour continue la partie... looser !"
DONE = "Fait !"
RESTART_REQUIRED = u"Un redémarage est nécéssaire"
|
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'
|
"""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()
|
# -*- 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',
}
|
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}'
|
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))
|
#! /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__ = "[email protected]"
__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 )
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
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
|
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"
|
#ARGUMENTOS OPCIONAIS
def somar(a = 0, b = 0, c = 0): #INICIALIZA COM ZERO PARA SER OPCIONAL
"""
-> Faz a soma de três valores e mostra o resultado na tela
:param a: primeiro valor
:param b: segundo valor
:param c: terceiro valor
"""
s = a + b + c
print(f'A soma vale {s}')
somar(3, 2, 5)
somar(3, 2)
somar()
somar(3, 4, 5)
|
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
|
# 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())
|
"""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
|
# BEGIN LINEITEM_V2_PROP_FACTORY_FUNCTION
def quantity(storage_name): # <1> 이 argument가 프로퍼티를 어디에 저장할 지 결정
def qty_getter(instance): # <2> instance는 LineItem 객체를 가르킴
return instance.__dict__[storage_name] # <3> 그 객체에서 attribute를 직접 가져온다
def qty_setter(instance, value): # <4> instance는 LineItem 객체를 가르킴
if value > 0:
instance.__dict__[storage_name] = value # <5> 객체 attribute에 value를 저장
else:
raise ValueError('value must be > 0')
return property(qty_getter, qty_setter) # <6> 사용자정의 프로퍼티 객체를 생성해서 반환
# END LINEITEM_V2_PROP_FACTORY_FUNCTION
# BEGIN LINEITEM_V2_PROP_CLASS
# 프로퍼티 팩토리 : 두개의 세터/게터를 직접 구현하지 않고도 속성이 0이상만 받을 수 있게하는 법
class LineItem:
weight = quantity('weight') # <1> 프로퍼티 팩토리로생성한 프로퍼티 객체를 class attribute에 저장
price = quantity('price') # <2> 프로퍼티 팩토리로생성한 프로퍼티 객체를 class attribute에 저장
def __init__(self, description, weight, price):
self.description = description
self.weight = weight # <3> 0이나 음이되지않게 보장
self.price = price
def subtotal(self):
return self.weight * self.price # <4> 객체에 저장된 값 가져오기
# END LINEITEM_V2_PROP_CLASS
if __name__=='__main__':
nutmeg = LineItem('Moluccan nutmeg', 8, 13.95)
nutmeg.weight, nutmeg.price # <1>
sorted(vars(nutmeg).items()) # <2> vars는 안의 attribute조사하는 함수
|
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)
|
# 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..")
|
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="")
|
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")
|
# 和 518 题相同
class Solution:
def waysToChange(self, n: int) -> int:
dp = [1] + [0] * n
coins = [25, 10, 5, 1]
for coin in coins:
for col in range(coin, n + 1):
dp[col] += dp[col - coin]
return dp[-1] % (10**9 + 7)
|
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
|
# -*- 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'
|
'''
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))
|
# QUANTIDADE DE TINTA EMUMA DETERMINADA PAREDE
largura = float(input("Largura da parede: "))
altura = float(input("Altura da parede: "))
area_da_parede = largura * altura
tinta_em_litros = area_da_parede * 2
print("A quantidade de tinta em litros será: {:.1f}L".format(tinta_em_litros))
|
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
|
"""Quiz: List Indexing
Use list indexing to determine how many days are in a particular month based on the integer variable month, and store that value in the integer variable num_days. For example, if month is 8, num_days should be set to 31, since the eighth month, August, has 31 days.
Remember to account for zero-based indexing!
"""
month = 8
days_in_month = [31, 28, 31,30,31,30,31,31,30,31,30,31]
num_days = days_in_month[month - 1]
print(num_days)
"""Quiz: Slicing Lists
Select the three most recent dates from this list using list slicing notation. Hint: negative indexes work in slices!
"""
eclipse_dates = ['June 21, 2001', 'December 4, 2002', 'November 23, 2003',
'March 29, 2006', 'August 1, 2008', 'July 22, 2009',
'July 11, 2010', 'November 13, 2012', 'March 20, 2015',
'March 9, 2016']
print(eclipse_dates[-3:])
#This slice uses a negative index to begin slicing three elements from the end of the list. The end index can be omitted because this slice continues until the end of the list.
"""Suppose we have the following two expressions, sentence1 and sentence2:
sentence1 = "I wish to register a complaint."
sentence2 = ["I", "wish", "to", "register", "a", "complaint", "."]
Match the Python code below with the value of the modified sentence1 or sentence2. If the code results in an error, match it with “Error”.
- sentence2[6] = "!" → ["I", "wish", "to", "register", "a", "complaint", "!"]
- sentence2[0] = "Our Majesty" → ["Our Majesty", "wish", "to", "register", "a", "complaint", "."]
- sentence1[30] = "!" → Error() TypeError: 'str' object does not support item assignment
- sentence2[0:2] = ["We", "want"] → ["We", "want", "to", "register", "a", "complaint", "."]
→ sentence1 is a string, and is therefore an immutable object. That means that while you can refer to individual characters in sentence1 (e.g., you can write things like sentence1[5]) you cannot assign value to them (you cannot write things like sentence1[5] = 'a'). Therefore the third expression will result in an error.
→ sentence2 is a list, and lists are mutable, meaning that you can change the value of individual items in sentence2:
- In the first expression we changed the value of the last item in sentence2 from "." to "!".
- In the second expression we changed the value of the first item in sentence2 from "I" to "Our Majesty".
- In the last expression we used slicing to simultaneously change the value of both the first and the second item in sentence2 from "I" and "wish" to "We" and "want".
"""
"""
Check for Understanding
Data types and data structures are tricky but important concepts to master! Let's pause and make sure you understand the distinction between them.
→ Data Structures arre containers tha can include different data types
→ A list is an example od a data structure
→ All data structure are data types
→ A data type is just a type that classifies data. This can include primitive (basic) data types like integers, booleans, and strings, as well as data structures, such as lists.
→ Data structures are containers that organize and group data types together in different ways. For example, some of the elements that a list can contain are integers, strings, and even other lists!
→ Properties os Lists:
- Mutable
- Ordered data structures
"""
|
'''
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()
|
# OpenWeatherMap API Key
weather_api_key = "8915eee544f1c9b3ef5fa102f5edeb66"
# Google API Key
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)
|
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
|
# -*- 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)
'''
|
def arrayMap(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
|
'''show=[]
for cont in range(0,3):
show.append(input('Digite os shows que mais gosta: ').upper())
for c,v in enumerate(show):
print(f'Artista....',(c+1))
print('=-'*30)
print(f'Os shows que mais gosta é \033[0;31m{v}\033[m')
print('=-'*30)
print('Cheguei ao final da lista')'''
#Exercicio feito para relembrar LISTAS, então improvisei montando shows.
a=[2,4,7,9]
b=a[:]#CÓPIA
b[1]=83#ACRESCENTAMOS O VALOR,dai muda na posição,[1] ou [2] ou [3],a qual voce preferir.
print(f'Lista A: {a}')
print(f'Lista B: {b}')
'''Quando se coloca normal assim, sem o [:](cópia),ele repete as duas listas,para acrescentar o valor,devemos fazer
sempre uma cópia, então para não copiar,colocamos o fatiamento,[:].'''
|
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 square(): # function header
new_value=4 ** 2 # function body
print(new_value)
square()
|
num1 = int(input("Digite um número:"))
num2 = int(input("Digite outro número:"))
if num1 > num2 :
print("O número {} é maior que o {}".format(num1, num2))
elif num1 == num2:
print(("Os dois números são iguais!!"))
else:
print("O número {} é maior que o {}" .format(num2, num1))
|
#!/usr/bin/python
#-*- coding: utf-8 -*-
'''
'''
__author__ = 'wpxiao'
class Page(object):
def __init__(self,user_data,current_page,per_page_row,page_num,base_url):
'''
current_page 当前页
per_page_row 每页显示的条数
page_num 分页显示的页码数
'''
self.user_data = user_data
self.page_error = ''
if not current_page.isdigit():
self.page_error = "页码必须为数字"
self.current_page = 1
else:
self.current_page = int(current_page)
self.per_page_row = int(per_page_row)
self.page_num = int(page_num)
self.base_url = base_url
#数据的总页数
@property
def total_page(self):
total_page, mod = divmod(len(self.user_data), self.per_page_row)
if mod != 0:
total_page = total_page + 1
if self.current_page > total_page:
self.page_error = "页码超出范围"
self.current_page = 1
return total_page
#分页显示时当前页面的第一条数
@property
def start(self):
start = (self.current_page - 1) * self.per_page_row
return start
#分页显示时当前页面的最后一条数据
@property
def end(self):
end = self.current_page * self.per_page_row
return end
def page_str(self):
'''
分页逻辑:
当总页数大于等于11时
如果当前页 小于等于6时
开始页 = 1
结束页 = 11 +1
如果当前页 大于6时
开始页 = 当前页 - 5
如果当前页+5 > 总页数
结束页 = 总页数 +1
否则
结束页 = 当前页 + 5+1
当总页数小于11时,
开始页 = 1
结束页 = 总页数+1
'''
if self.total_page < self.page_num:
start_page = 1
end_page = self.total_page + 1
else:
if self.current_page <= (self.page_num + 1) / 2:
start_page = 1
end_page = self.page_num + 1
else:
start_page = int(self.current_page - (self.page_num - 1) / 2)
if self.current_page + (self.page_num - 1) / 2 > self.total_page:
end_page = self.total_page + 1
else:
end_page = int(self.current_page + (self.page_num + 1) / 2)
page_list = []
if self.current_page == 1:
a_tag = '''
<a class="selected" href="javascript:void(0)">上一页</a>
'''
else:
a_tag = '''
<a class="selected" href="%s?p=%s">上一页</a>
''' % (self.base_url,self.current_page - 1,)
page_list.append(a_tag)
for i in range(start_page, end_page):
if i < 10:
i_text = "0" + str(i)
else:
i_text = str(i)
if self.current_page == i:
a_tag = '''
<a class="selected" href="%s?p=%s">%s</a>
''' % (self.base_url,i, i_text)
else:
a_tag = '''
<a href="%s?p=%s">%s</a>
''' % (self.base_url,i, i_text)
page_list.append(a_tag)
if self.current_page == self.total_page:
a_tag = '''
<a class="selected" href="javascript:void(0)">下一页</a>
'''
else:
a_tag = '''
<a class="selected" href="%s?p=%s">下一页</a>
''' % (self.base_url,self.current_page + 1,)
page_list.append(a_tag)
input_tag = '''
<input size='5px' id="jump_page" type="text" name="jump_page" placeholder='页码' />
<input type="button" id="jump_btn" onclick="JumpTo(this,'%s?p=');" value="GO" />
<script>
function JumpTo(ths,base_url){
var val = ths.previousElementSibling.value;
location.href = base_url+ val;
}
</script>
'''%(self.base_url,)
page_list.append(input_tag)
page_list = "".join(page_list)
return page_list
if __name__ == "__main__":
p = Page([1,2,3,4,5,6],'2','2','10')
print(p.page_str())
|
# -*- 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))
|
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
|
# Dividindo valores em várias listas
'''Crie um programa que vai ler VÁRIOS NÚMEROS
e colocar em uma LISTA. Depois disso, crie DUAS
LISTAS EXTRAS que vão conter apenas os valores
PARES e os valores ÍMPARES digitados, respectivamente.
Ao final, mostre o conteúdo das TRÊS LISTAS geradas'''
numeros = []
pares = []
impares = []
while True:
numeros.append(int(input('Digite um número: ')))
resp = str(input('Quer continuar? \033[1:37m''[S/N] \033[m'))
if resp in 'Nn':
break
print('\033[1:35m''-=''\033[m' * 30)
print(f'A lista completa é {numeros}')
for n in numeros:
if n % 2 == 0:
pares.append(n)
if n % 2 == 1:
impares.append(n)
print(f'A lista de pares é {pares}')
print(f'A lista de ímpares é {impares}')
|
_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))
|
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 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
|
# Exercício Python 087: Aprimore o desafio anterior, mostrando no final:
# A) A soma de todos os valores pares digitados.
# B) A soma dos valores da terceira coluna.
# C) O maior valor da segunda linha.
somap = somat = maior = 0
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for c in range(0, 3):
for j in range(0, 3):
matriz[c][j] = int(input(f'Digite um valor para [{c}, {j}]: '))
if matriz[c][j] % 2 == 0:
somap += matriz[c][j]
if c == 1 and j == 0:
maior = matriz[c][j]
else:
if c == 1 and matriz[c][j] > maior:
maior = matriz[c][j]
for c in range(0, 3):
somat += matriz[c][2]
for c in range(0, 3):
for n in range(0, 3):
print(f'[{matriz[c][n]:^3}]', end=' ')
print()
print(f'A soma de todos os valores pares é {somap}')
print(f'A soma de todos os valoers da terceira coluna é {somat}')
print(f'O maior valor da segunda linha é {maior}')
|
'''
Globals that are used throughout CheckAPI
'''
# Whether to output debugging statements
debug = False
# The model's current working directory
workingdir = "/"
|
#!/usr/bin/env python
"""
Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
https://leetcode.com/problems/search-insert-position/
"""
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
if length == 0:
return 1
result = 0
for index in range(len(nums)):
result = index
if target <= nums[index]:
break
else:
result = index + 1
return result
|
#!/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()
|
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'
|
'''
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]
|
# 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"
}"""
|
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 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()"
|
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')
|
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)
|
#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'))
|
# 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))
|
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
|
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)
|
"""
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
|
"""
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"
|
class SmallArray():
def __init__(self) -> None:
self.clusters = 0
self.cluster_size = 0
|
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'
}
|
# #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 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
|
DEBUG = True
TEMPLATE_DEBUG = DEBUG
STATIC_DEBUG = DEBUG
CRISPY_FAIL_SILENTLY = not DEBUG
ADMINS = (
('Dummy', '[email protected]'),
)
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@'
|
"""
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
]
}
]
}
|
# -*- 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)
|
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
|
# -*- 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__ = "[email protected]"
__maintainer__ = "unknown maintainer"
__maintainer_email__ = "[email protected]"
__github_username__ = "fuwiak"
|
def func1(a):
a += 1
def funct2(b):
val = 1+b
return val
return funct2(a)
print(func1(5))
|
"""
第一步 安装包 >pip install hokuyolx
运行下面示例 输出数据如下
(array([2853, 2854, 2853, ..., 147, 143, 139], dtype=uint32), 1623898425874, 0)
array中包含1080个数据0 到1079 对应-135度到135度 值为mm 0 2853对应为 -135度方向障碍物距离为2.853m
示例
###########
from hokuyolx import HokuyoLX
import matplotlib.pyplot as plt
DMAX = 10000
laser = HokuyoLX()
timestamp, scan = laser.get_dist()
print(laser.get_filtered_dist())
for timestamp in laser.iter_dist():
print(timestamp)
##################
"""
|
# 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))
|
#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
|
# 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)
|
#
# 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"
|
"""Initialisation des modulesce
ce fichier est nécessaire pour pouvoir importer
directement l'ensemble des modules contenu dans ce paquet
"""
__all__ = ["fibonacci"]
|
def countWaysToChangeDigit(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
|
"""
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.