content
stringlengths 7
1.05M
|
|---|
# -*- coding: utf-8 -*-
__all__=['glottal', 'phonation', 'articulation', 'prosody', 'replearning']
|
# creating a function to calculate the density.
def calc_density(mass, volume):
# arithmetic calculation to determine the density.
density = mass / volume
density = round(density, 2)
# returning the value of the density.
return density
# receiving input from the user regarding the mass and volume of the substance.
mass = float(input("Enter the mass of the substance in grams please: "))
volume = float(input("Enter the volume of the substance please: "))
# printing the final output which indicates the density.
print("The density of the object is:", calc_density(mass, volume), "g/cm^3")
|
class documentmodel:
def getDocuments(self):
document_tokens1 = "China has a strong economy that is growing at a rapid pace. However politically it differs greatly from the US Economy."
document_tokens2 = "At last, China seems serious about confronting an endemic problem: domestic violence and corruption."
document_tokens3 = "Japan's prime minister, Shinzo Abe, is working towards healing the economic turmoil in his own country for his view on the future of his people."
document_tokens4 = "Vladimir Putin is working hard to fix the economy in Russia as the Ruble has tumbled."
document_tokens5 = "What's the future of Abenomics? We asked Shinzo Abe for his views"
document_tokens6 = "Obama has eased sanctions on Cuba while accelerating those against the Russian Economy, even as the Ruble's value falls almost daily."
document_tokens7 = "Vladimir Putin is riding a horse while hunting deer. Vladimir Putin always seems so serious about things - even riding horses. Is he crazy?"
documents = []
documents.append(document_tokens1)
documents.append(document_tokens2)
documents.append(document_tokens3)
documents.append(document_tokens4)
documents.append(document_tokens5)
documents.append(document_tokens6)
documents.append(document_tokens7)
return documents
|
# For internal use. Please do not modify this file.
def setup():
return
def extra_make_option():
return ""
|
def collatz(number):
if number%2==0:
number=number//2
else:
number=3*number+1
print(number)
return number
print('enter an integer')
num=int(input())
a=0
a=collatz(num)
while a!=1:
a=collatz(a)
|
# CONVERSION OF UNITS
# Python 3
# Using Jupyter Notebook
# If using Visual Studio then change .ipynb to .py
# This program aims to convert units from miles to km and from km to ft.
# 1 inch = 2.54 cm, 1 km = 1000m, 1 m = 100 cm, 12 inches = 1 ft, 1 mile = 5280 ft
# ------- Start -------
# Known Standard Units of Conversion
# Refer to a conversion table if you don't know where to find it.
# But I placed it at the top for reference
inToCm = 2.54
kmToM = 1000
mToCm = 100
inToFt = 1/12
miToFt = 5280
# Input your number to be converted using this command
num = float(input("Enter your number (in miles): "))
# Conversion formula
# Don't get overwhelmed, if you have the conversion table you'll be fine.
# Otherwise get your pen and paper, and write before coding!
miToFt = num * miToFt
inToFt = miToFt * (1/inToFt)
inToCm = inToFt * inToCm
mToCm = inToCm * (1/mToCm)
kmToM = mToCm * (1/kmToM)
# Print the answer
print()
print(num, " mile(s) is",miToFt," feet")
print(miToFt, " feet(s) is",inToFt," inch(es)")
print(inToFt, " inch(es) is",inToCm," centimeter(s)")
print(inToCm, " centmeter(s) is",mToCm," meter(s)")
print(mToCm, " meter(s) is",kmToM," kilometer(s)")
# ------- End -------
# For a shorter version
#CONVERSION OF UNITS
#This program aims to convert units from miles to km and from km to ft.
# 1 inch = 2.54 cm, 1 km = 1000m, 1 m = 100 cm, 12 inches = 1 ft, 1 mile = 5280 ft
inToCm = 2.54
kmToM = 1000
mToCm = 100
inToFt = 1/12
miToFt = 5280
num = float(input("Enter your number (in miles): "))
convertedNum = num * miToFt * (1/inToFt) * inToCm * (1/mToCm) * (1/kmToM)
print(num, " mile(s) is",convertedNum,"kilometers")
|
# 🚨 Don't change the code below 👇
age = input("What is your current age?")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
age = int(age)
days_left = (90*365) - (age*365)
weeks_left = (90*52) - (age*52)
months_left = (90*12) - (age*12)
print(f"You have {days_left} days, {weeks_left} weeks left, and {months_left} months left.")
|
'''constants.py
Various constants that are utilized in different modules across the whole program'''
#Unicode characters for suits
SUITS = [
'\u2660',
'\u2663',
'\u2665',
'\u2666'
]
#A calculation value and a face value for the cards
VALUE_PAIRS = [
(1, 'A'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
(6, '6'),
(7, '7'),
(8, '8'),
(9, '9'),
(10, '10'),
(11, 'J'),
(12, 'Q'),
(13, 'K')
]
#Colors: Tuples with RGB values from 0 to 255
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (50, 150, 255)
GRAY = (115, 115, 115)
GREEN = (0, 255, 0)
|
def is_overlap(arr1, arr2):
if arr2[0] <= arr1[0] <= arr2[1]:
return True
if arr2[0] <= arr1[1] <= arr2[1]:
return True
if arr1[0] <= arr2[0] <= arr1[1]:
return True
if arr1[0] <= arr2[1] <= arr1[1]:
return True
return False
def merge_2_arrays(arr1, arr2):
l = min(min(arr1), min(arr2))
r = max(max(arr1), max(arr2))
return [l, r]
def rain_drop(rain):
if not rain:
return -1
r = sorted(rain)
covered = r[0]
for i in range(1, len(r)):
if not is_overlap(covered, r[i]):
return -1
covered = merge_2_arrays(covered, r[i])
print(covered)
if covered[1] >= 1:
return i + 1
return -1
if __name__ == '__main__':
rains = [[0, 0.3],[0.3, 0.6],[0.5, 0.8], [0.67, 1], [0, 0.4] ,[0.5, 0.75]]
print(rain_drop(rains))
|
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
def fib3(n):
if n == 1 or n == 2 or n == 3:
return 1
else:
return fib3(n - 1) + fib3(n - 2) + fib3(n - 3)
def fib_mult(n):
if n == 1:
return 1
if n == 2:
return 2
else:
return fib_mult(n - 1) * fib_mult(n - 2)
def fib_skip(n):
if n == 1 or n == 2 or n == 3:
return 1
else:
return fib_skip(n - 1) + fib_skip(n - 3)
def joynernacci(n):
if n == 1 or n == 2:
return 1
else:
if n % 2 ==0:
return joynernacci(n - 1) + joynernacci(n - 2)
else:
return abs(joynernacci(n - 1) - joynernacci(n - 2))
|
"""Given a linked list of co-ordinates where adjacent points either form a vertical line or a horizontal line.
Delete points from the linked list which are in the middle of a horizontal or vertical line."""
"""Input: (0,10)->(1,10)->(5,10)->(7,10)
|
(7,5)->(20,5)->(40,5)
Output: Linked List should be changed to following
(0,10)->(7,10)
|
(7,5)->(40,5) """
# Node class
class Node:
# Constructor to initialise (x, y) coordinates and next
def __init__(self, x=None, y=None):
self.x = x
self.y = y
self.next = None
class SinglyLinkedList:
# Constructor to initialise head
def __init__(self):
self.head = None
# Function to find middle node of a linked list
def delete_middle_nodes(self):
current = self.head
# iterate while the next of the next node is not none
while current and current.next and current.next.next is not None:
# assign variables for next and next of next nodes
next = current.next
next_next = current.next.next
# if x coordinates are equal of current and next node i.e. horizontal line
if current.x == next.x:
# check if there are more than 2 nodes in the horizontal line
# if yes then delete the middle node and update next and next_next
while next_next is not None and next.x == next_next.x:
current.next = next_next
next = next_next
next_next = next_next.next
# if y coordinates are equal of current and next node i.e. vertical line
elif current.y == next.y:
# check if there are more than 2 nodes in the vertical line
# if yes then delete the middle node and update next and next_next
while next_next is not None and next.y == next_next.y:
current.next = next_next
next = next_next
next_next = next_next.next
# updated the current node to next node for checking the next line nodes
current = current.next
# Function to Insert data at the beginning of the linked list
def insert_at_beg(self, x, y):
node = Node(x, y)
node.next = self.head
self.head = node
# Function to print the linked list
def print_data(self):
current = self.head
while current is not None:
print('(',current.x, ',', current.y, ') -> ', end='')
current = current.next
print('None')
if __name__ == '__main__':
linked_list = SinglyLinkedList()
linked_list.insert_at_beg(40,5)
linked_list.insert_at_beg(20,5)
linked_list.insert_at_beg(7,5)
linked_list.insert_at_beg(7,10)
linked_list.insert_at_beg(5,10)
linked_list.insert_at_beg(1,10)
linked_list.insert_at_beg(0,10)
# print the linked list representing vertical and horizontal lines
linked_list.print_data()
# call the delete_middle_nodes function
linked_list.delete_middle_nodes()
# print the new linked list
linked_list.print_data()
|
__author__ = 'JPaschoal'
__version__ = '1.0.1'
__email__ = 'jonfisik@hotmail.com'
__date__ = '08/05/2021'
'''
Qualquer número natural de quatro algarismos pode ser dividido
em duas dezenas formadas pelos seus dois primeiros e dois
últimos dígitos.
Exemplos:
1297: 12 e 97
5314: 53 e 14
Escreva um programa que imprime todos os milhares (4 algarismos), 1000 <= n < 10000, cuja raiz quadrada seja a soma das dezenas formadas pela divisão acima.
Exemplo: raiz de 9801 = 99 = 98 + 01
Portanto 9801 é um dos números a ser impresso.
'''
# 1000 --> 10 00 --> 10 + 00 = 10 --> 10**2 = 100 == 1000 [V/F] imprimir 1000
# 1001 --> 10 01 --> 10 + 01 = 11 --> 11**2 = 121 == 1001 [V/F] imprimir 1001
# .
# .
# .
# 9801 --> 98 01 --> 98 + 01 = 99 --> 99**2 = 9801 == 9801 [V/F] imprimir 9801
#--------------------------------------------
def traco():
return print('-----'*10)
print('')
print("TESTE MILHARES 1000 - 10 000")
traco()
# váriaveis
num = 1000
while num < 10000:
aux = num
dois_ultm = aux%100
aux //= 100
dois_prim = aux%100
if (dois_ultm + dois_prim)**2 == num:
print(f'>>> {num}')
num += 1
traco()
print('')
# END
|
"""
==========
Exceptions
==========
Module containing framework-wide exception definitions. Exceptions for
particular subsystems are defined in their respective modules.
"""
class VivariumError(Exception):
"""Generic exception raised for errors in ``vivarium`` simulations."""
pass
|
"""
Python program to find the n'th number in the tribonacci series
Tribonacci series is a generalization of the Fibonacci sequence, in which the current term
is the sum of the previous three terms.
"""
def find_tribonacci(n):
dp = [0] * n
dp[0] = 0
dp[1] = 0
dp[2] = 1
# Compute the sum of the previous three terms
for i in range(3,n):
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
return dp[n-1]
if __name__ == '__main__':
print("Enter the value of n?, where you need the n'th number in the tribonacci sequence. ", end="")
n = int(input())
if (n <= 0):
print("The given value of n is invalid.", end="")
exit()
res = find_tribonacci(n)
print("The {}'th term in the tribonacci series is {}.".format(n, res))
"""
Time Complexity - O(n)
Space Complexity - O(n)
SAMPLE INPUT AND OUTPUT
SAMPLE I
Enter the value of n?, where you need the n'th number in the tribonacci sequence. 12
The 12'th term in the tribonacci series is 149.
SAMPLE II
Enter the value of n?, where you need the n'th number in the tribonacci sequence. 1254
The 1254'th term in the tribonacci series is 4020147461713125140.
"""
|
__author__ = 'Dmitriy Korsakov'
def main():
pass
|
# Python - 3.4.3
def problem(a):
try:
return float(a) * 50 + 6
except:
return 'Error'
|
"""
bluew.daemon
~~~~~~~~~~~~~~~~~
This module provides a Daemon object that tries its best to keep connections
alive, and has the ability to reproduce certain steps when a reconnection is
needed.
:copyright: (c) 2017 by Ahmed Alsharif.
:license: MIT, see LICENSE for more details.
"""
def daemonize(func):
"""
A function wrapper that checks daemon flags. This wrapper as it is assumes
that the calling class has a daemon attribute.
"""
def _wrapper(self, *args, d_init=False, **kwargs):
if d_init:
self.daemon.d_init.append((func, self, args, kwargs))
return func(self, *args, **kwargs)
return _wrapper
class Daemon(object):
"""The bluew daemon."""
def __init__(self):
self.d_init = []
def run_init_funcs(self):
"""
This function iterates through the functions added to d_init, and
runs them in the same order they were added in.
"""
for func, self_, args, kwargs in self.d_init:
func(self_, *args, **kwargs)
|
class TransportModesProvider(object):
TRANSPORT_MODES = {
'0': None,
# High speed train
'1': {
'node': [('railway','station'),('train','yes')],
'way': ('railway','rail'),
'relation': ('route','train')
},
# Intercity train
'2': {
'node': [('railway','station'),('train','yes')],
'way': ('railway','rail'),
'relation': ('route','train')
},
# Commuter rail
'3': {
'node': [('railway','station'),('train','yes')],
'way': ('railway','rail'),
'relation': ('route','train')
},
# Metro/Subway: default
'4': {
'node':[('railway','station'),('subway','yes')],
'way': [('railway','subway'),('tunnel','yes')],
'relation': ('route','subway')
},
# Light rail
'5': {
'node':[('railway','station'),('light_rail','yes')],
'way': ('railway','light_rail'),
'relation': ('route','light_rail')
},
# BRT
'6': {
'node':('highway','bus_stop'),
'way': ('busway','lane'),
'relation': ('route','bus')
},
# People mover
'7': None,
# Bus
'8': {
'node':('highway','bus_stop'),
'way': None,
'relation': ('route','bus')
},
# Tram
'9': {
'node':[('railway','station'),('tram','yes')],
'way': ('railway','tram'),
'relation': ('route','tram')
},
# Ferry
'10': {
'node':[('ferry','yes'),('amenity','ferry_terminal')],
'way': ('route','ferry'),
'relation': ('route','ferry')
}
}
def __init__(self, lines_info):
self._lines = {}
for line in lines_info:
self._lines[line['url_name']] = line
def tags(self, line_url_name, element_type):
transport_mode_id = self._lines[line_url_name]['transport_mode_id']
mode = self.TRANSPORT_MODES[str(transport_mode_id)] or self.TRANSPORT_MODES['4']
tags = mode[element_type]
if not isinstance(tags, list):
tags = [tags]
# We remove Nones from list
tags = list(filter(None, tags))
return tags
|
# current = -4.036304473876953
def convert(time):
pos = True if time >= 0 else False
time = abs(time)
time_hours = time/3600
time_h = int(time_hours)
time_remaining = time_hours - time_h
time_m = int(time_remaining*60)
time_sec = time_remaining - time_m/60
time_s = int(time_sec*3600)
time_format = f'{time_m}:{time_s}' if pos else f'-{time_m}:{time_s}'
if abs(time_h) > 0:
time_format = f'{time_h}:{time_m}:{time_s}' if pos else f'-{time_h}:{time_m}:{time_s}'
return time_format
# time = convert(current)
# print(time)
|
"""
Define redistricting.management as a Python package.
This file serves the purpose of defining a Python package for
this folder. It is intentionally left empty.
This file is part of The Public Mapping Project
https://github.com/PublicMapping/
License:
Copyright 2010-2012 Micah Altman, Michael McDonald
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author:
Andrew Jennings, David Zwarg
"""
|
def composite_value(value):
if ';' in value:
items = []
first = True
for tmp in value.split(';'):
if not first and tmp.startswith(' '):
tmp = tmp[1:]
items.append(tmp)
first = False
else:
items = [value]
return items
|
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# actionLog : Get Action/Audit Logs
def get_audit_log(
self,
start_time: int,
end_time: int,
limit: int,
log_level: int = 1,
ne_pk: str = None,
username: str = None,
) -> list:
"""Get audit log details filtered by specified query parameters
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- GET
- /action
:param start_time: Long(Signed 64 bits) value of seconds since EPOCH
time indicating the starting time boundary of data time range
:type start_time: int
:param end_time: Long(Signed 64 bits) value of seconds since EPOCH
time indicating the ending time boundary of data time range
:type end_time: int
:param limit: Limit the number of rows to retrieve from audit log
:type limit: int
:param log_level: ``0`` for Debug, ``1`` for Info, ``2`` for Error.
Defaults to 1
:type log_level: int, optional
:param ne_pk: Filter for specific appliance with Network Primary Key
(nePk) of appliance, e.g. ``3.NE``
:type ne_pk: str, optional
:param username: Filter for specific user
:type username: str, optional
:return: Returns list of dictionaries \n
[`dict`]: Audit log line \n
* keyword **id** (`int`): Id of the log entry
* keyword **user** (`str`): User who performed this action
* keyword **ipAddress** (`str`): IP Address who performed
this action
* keyword **nepk** (`str`): Primary key of the appliance on
which this action was performed
* keyword **name** (`str`): Name of the action
* keyword **description** (`str`): Description of the action
* keyword **taskStatus** (`str`): Status of the action
* keyword **startTime** (`int`): Start time of the action in
milliseconds since epoch
* keyword **endTime** (`int`): End time of the action in
milliseconds since epoch
* keyword **queuedTime** (`int`): Original queued time of
the action in milliseconds since epoch
* keyword **percentComplete** (`int`): Percentage completion
of the action
* keyword **completionStatus** (boolean): Show if action
succeeded or failed
* keyword **result** (`str`): Opaque blob of data related to
action. Typically, this is the result of the action.
* keyword **intTaskStatus** (`int`): Status of the action in
integer enum format
* keyword **guid** (`str`): GUID of a group of related
actions
:rtype: list
"""
path = "/action?startTime={}&endTime={}&limit={}&logLevel={}".format(
start_time, end_time, limit, log_level
)
if ne_pk is not None:
path = path + "&appliance={}".format(ne_pk)
if username is not None:
path = path + "&username={}".format(username)
return self._get(path)
def get_audit_log_task_status(
self,
action_key: str,
) -> dict:
"""Certain actions like appliance upgrade, appliance restore etc.,
return a key as in response. Check for status of such operations
using the key
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- GET
- /action/status
:param action_key: GUID of task to retrieve status for
:type action_key: str
:return: Returns dictionary of specified task details \n
* keyword **id** (`int`): Id of the log entry
* keyword **user** (`str`): User who performed this action
* keyword **ipAddress** (`str`): IP Address who performed
this action
* keyword **nepk** (`str`): Primary key of the appliance on
which this action was performed
* keyword **name** (`str`): Name of the action
* keyword **description** (`str`): Description of the action
* keyword **taskStatus** (`str`): Status of the action
* keyword **startTime** (`int`): Start time of the action in
milliseconds since epoch
* keyword **endTime** (`int`): End time of the action in
milliseconds since epoch
* keyword **queuedTime** (`int`): Original queued time of
the action in milliseconds since epoch
* keyword **percentComplete** (`int`): Percentage completion
of the action
* keyword **completionStatus** (boolean): Show if action
succeeded or failed
* keyword **result** (`str`): Opaque blob of data related to
action. Typically, this is the result of the action.
* keyword **intTaskStatus** (`int`): Status of the action in
integer enum format
* keyword **guid** (`str`): GUID of a group of related
actions
:rtype: list
"""
return self._get("/action/status?key={}".format(action_key))
def cancel_audit_log_task(
self,
action_key: str,
) -> bool:
"""Certain actions like appliance upgrade, appliance restore etc.,
return a key as in response. Cancel the action referenced by
provided key.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - actionLog
- POST
- /action/cancel
:param action_key: GUID of task to retrieve status for
:type action_key: str
:return: Returns True/False based on successful call
:rtype: bool
"""
return self._get("/action/status?key={}".format(action_key))
|
#!/usr/bin/env python
# iGoBot - a GO game playing robot
#
# ##############################
# # GO stone board coordinates #
# ##############################
#
# Project website: http://www.springwald.de/hi/igobot
#
# Licensed under MIT License (MIT)
#
# Copyright (c) 2018 Daniel Springwald | daniel@springwald.de
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
class Board():
_released = False
Empty = 0;
Black = 1;
White = 2;
_boardSize = 0; # 9, 13, 19
_fields = [];
# Stepper motor positions
_13x13_xMin = 735;
_13x13_xMax = 3350;
_13x13_yMin = 100;
_13x13_yMax = 2890;
_9x9_xMin = 1120;
_9x9_xMax = 2940;
_9x9_yMin = 560;
_9x9_yMax = 2400;
StepperMinX = 0;
StepperMaxX = 0;
StepperMinY = 0;
StepperMaxY = 0;
def __init__(self, boardSize):
self._boardSize = boardSize;
if (boardSize == 13):
#print("Board: size " , boardSize, "x", boardSize);
self.StepperMinX = self._13x13_xMin;
self.StepperMaxX = self._13x13_xMax
self.StepperMinY = self._13x13_yMin;
self.StepperMaxY = self._13x13_yMax;
else:
if (boardSize == 9):
#print("Board: size " , boardSize, "x", boardSize);
self.StepperMinX = self._9x9_xMin;
self.StepperMaxX = self._9x9_xMax
self.StepperMinY = self._9x9_yMin;
self.StepperMaxY = self._9x9_yMax;
else:
throw ("unknown board size " , boardSize, "x", boardSize);
# init board dimensions with 0 values (0=empty, 1=black, 2= white)
self._fields = [[0 for i in range(boardSize)] for j in range(boardSize)]
@staticmethod
def FromStones(boardSize, blackStones, whiteStones):
# create a new board and fill it with the given black and white stones
board = Board(boardSize)
if (blackStones != None and len(blackStones) > 0 and blackStones[0] != ''):
for black in Board.EnsureXyNotation(blackStones):
board.SetField(black[0],black[1],Board.Black);
if (whiteStones != None and len(whiteStones) > 0 and whiteStones[0] != ''):
for white in Board.EnsureXyNotation(whiteStones):
board.SetField(white[0],white[1],Board.White);
return board;
@staticmethod
def Differences(board1, board2):
# find all coordinates, where the second board is other
if (board1 == None): throw ("board1 == None");
if (board2 == None): throw ("board2 == None");
if (board1._boardSize != board2._boardSize): throw ("different board sizes: " , board1._boardSize, " vs. ", board2._boardSize);
result = [];
for x in range(0, board1._boardSize):
for y in range(0, board1._boardSize):
if (board1.GetField(x,y) != board2.GetField(x,y)):
result.extend([[x,y]])
return result;
def RemovedStones(board1, board2):
# find all coordinates, where the stones from board1 are not on board2
if (board1 == None): throw ("board1 == None");
if (board2 == None): throw ("board2 == None");
if (board1._boardSize != board2._boardSize): throw ("different board sizes: " , board1._boardSize, " vs. ", board2._boardSize);
result = [];
for x in range(0, board1._boardSize):
for y in range(0, board1._boardSize):
if (board1.GetField(x,y) != Board.Empty):
if (board2.GetField(x,y) == Board.Empty):
result.extend([[x,y]])
return result;
@staticmethod
def EnsureXyNotation(stones):
#ensures that this is a list of [[x,y],[x,y]] and not like ["A1","G2]
result = [];
for stone in stones:
#print(">>>1>>>", stone);
if (isinstance(stone, str) and stone !=''):
#print(">>>2>>>", Board.AzToXy(stone));
result.extend([Board.AzToXy(stone)])
else:
#print(">>>3>>>", stones);
return stones; # already [x,y] format
return result;
@staticmethod
def XyToAz(x,y):
# converts x=1,y=2 to A1
if (x > 7):
x=x+1; # i is not defined, jump to j
return chr(65+x)+str(y+1);
@staticmethod
def AzToXy(azNotation):
# converts A1 to [0,0]
if (len(azNotation) != 2 and len(azNotation) != 3):
print ("board.AzToXy for '" + azNotation + "' is not exact 2-3 chars long");
return None;
x = ord(azNotation[0])-65;
if (x > 7):
x=x-1; # i is not defined, jump to h
y = int(azNotation[1:])-1;
return [x,y]
def Print(self):
# draw the board to console
for y in range(0, self._boardSize):
line = "";
for x in range(0, self._boardSize):
stone = self.GetField(x,y);
if (stone==0):
line = line + "."
elif (stone==Board.Black):
line = line + "*";
elif (stone==Board.White):
line = line + "O";
print(line);
def GetField(self,x,y):
return self._fields[x][y];
def SetField(self,x,y, value):
self._fields[x][y] = value;
def GetNewStones(self, detectedStones, color=Black):
# what are the new black/whites stones in the list, not still on the board?
newStones = [];
for stone in detectedStones:
if (self.GetField(stone[0],stone[1]) != color):
newStones.extend([[stone[0],stone[1]]])
return newStones;
def GetStepperXPos(self, fieldX):
return self.StepperMinX + int(fieldX * 1.0 * ((self.StepperMaxX-self.StepperMinX) / (self._boardSize-1.0)));
def GetStepperYPos(self, fieldY):
return self.StepperMinY + int(fieldY * 1.0 * ((self.StepperMaxY-self.StepperMinY) / (self._boardSize-1.0)));
if __name__ == '__main__':
board = Board(13)
print (board._fields)
print (Board.AzToXy("A1"))
board.SetField(0,0,board.Black);
board.SetField(12,12,board.Black);
print(board.GetField(0,0));
print(board.GetField(0,0) == board.Black);
for x in range(0,13):
f = board.XyToAz(x,x);
print([x,x],f, Board.AzToXy(f));
board2 = Board.FromStones(boardSize=13, blackStones=[[0,0],[1,1]], whiteStones=[[2,0],[2,1]]);
board2.Print();
print(Board.Differences(board,board2));
print(Board.RemovedStones(board,board2));
|
def compare(a: int, b: int):
printNums(a, b)
if a > b:
msg = "a > b"
a += 1
elif a < b:
msg = "a < b"
b += 1
else:
msg = "a == b"
a += 1
b += 1
print(msg)
printNums(a, b)
print()
def printNums(a, b):
print(f"{a = }, {b = }")
def main():
for a in range(1, 4):
for b in range(1, 4):
compare(a, b)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
"""quicksort.py: Program to implement quicksort"""
__author__ = 'Rohit Sinha'
def quick_sort(alist):
quick_sort_helper(alist, 0, len(alist) - 1)
def quick_sort_helper(alist, start, end):
if start < end:
pivot = partition(alist, start, end)
quick_sort_helper(alist, start, pivot - 1)
quick_sort_helper(alist, pivot + 1, end)
def partition(alist, start, end):
pivot_value = alist[start]
left_pointer = start+1
right_pointer = end
done = False
while not done:
while left_pointer <= right_pointer and alist[left_pointer] <= pivot_value:
left_pointer += 1
while right_pointer >= left_pointer and alist[right_pointer] >= pivot_value:
right_pointer -= 1
if left_pointer > right_pointer:
done = True
else:
alist[left_pointer], alist[right_pointer] = alist[right_pointer], alist[left_pointer]
alist[right_pointer], alist[start] = alist[start], alist[right_pointer]
return right_pointer
if __name__ == '__main__':
alist = [84, 69, 76, 86, 94, 91]
quick_sort(alist)
print(alist)
|
latest_block_redis_key = "latest_block_from_chain"
latest_block_hash_redis_key = "latest_blockhash_from_chain"
most_recent_indexed_block_redis_key = "most_recently_indexed_block_from_db"
most_recent_indexed_block_hash_redis_key = "most_recently_indexed_block_hash_from_db"
most_recent_indexed_ipld_block_redis_key = "most_recent_indexed_ipld_block_redis_key"
most_recent_indexed_ipld_block_hash_redis_key = (
"most_recent_indexed_ipld_block_hash_redis_key"
)
trending_tracks_last_completion_redis_key = "trending:tracks:last-completion"
trending_playlists_last_completion_redis_key = "trending-playlists:last-completion"
challenges_last_processed_event_redis_key = "challenges:last-processed-event"
user_balances_refresh_last_completion_redis_key = "user_balances:last-completion"
latest_sol_play_tx_key = "latest_sol_play_tx_key"
index_eth_last_completion_redis_key = "index_eth:last-completion"
|
class CountryExclude(object):
@staticmethod
def validate(data: str) -> None:
"""
Check is country should be excluded
:param data: string to validate
:return: None
:raise: ValueError on failure
"""
# Exclude these countries/islands
if data in [
'an',
'nf', # North Folks
'tf', # French Southern Territories
'aq', # Antarctica
'aw', # Aruba
'eh', # Western Sahara
'gu', # Guam
'hk', # Hong Kong SAR China
'mo', # Macao SAR China
'pr', # Puerto Rico
'ps', # Palestinian Territory
'pf', # French Polynesia
'mf', # St. Martin
'bl', # St. Barthélemy
'ax', # Åland Islands
'bv', # Bouvet Island
'cx', # Christmas Island
'hm', # Heard Island and MaxDonald
'mp', # Northern Mariana Islands
'sj', # Svalbard & Jan Mayen
'um', # U.S. Outlying Islands
'vi', # U.S. Virgin Islands
'yt', # Mayotte
'ph', # Philippines
'va', # Vatican City
'cc', # Cocos (Keeling) Islands
'dm', # Dominica
'mq', # Martinique
'gf', # French Guiana
'gp', # Guadeloupe
'nc', # New Caledonia
're', # Réunion
'pm', # St. Pierre & Miquelon
'wf', # Wallis & Futuna
'cw', # Curaçao
'sx', # Sint Maarten
'fk', # Falkland Island
'mm', # Myanmar
]:
raise ValueError("Country {} is in the exclude list!")
|
a = 'abcdefghijklmnopqrstuvwxyz'
b = 'pvwdgazxubqfsnrhocitlkeymj'
trans = str.maketrans(b, a)
src = 'Wxgcg txgcg ui p ixgff, txgcg ui p epm. I gyhgwt mrl lig txg ixgff wrsspnd tr irfkg txui hcrvfgs, nre, hfgpig tcm liunz txg crt13 ra "ixgff" tr gntgc ngyt fgkgf.'
print(src.translate(trans))
|
def get_level_1_news():
news1 = 'Stars Wars movie filming is canceled due to high electrical energy used. Turns out' \
'those lasers don\'t power themselves'
news2 = 'Pink Floyd Tour canceled after first show used up the whole energy city had for' \
'the whole month. The band says they\'ll be happy to play on the dark side of the town'
news3 = 'A public poll shows people are spending more energy on electric heaters after the ' \
'start of the cold war'
news4 = "9 in 10 people of your country do not know what the cold war is. The one who knows " \
"is in the military"
news5 = "Scientists says that world temperatures are rising due to high number of home " \
"refrigerators being used worldwide. According to Mr. Midgley, all the earth's" \
" cold is being trapped inside 4 billion refrigerators"
news6 = "Mr. Midgley published a new research where he's proved that ceiling and wall fans" \
" are causing hurricanes"
news7 = "Mr. Midgley, again, says he's discovered a way to revert climate change: everybody" \
" should throw their refrigerator's ice cubes into the ocean"
news8 = "After a whole year of snow falling almost in every corner of the world, Mr. " \
"Midgley says he knows nothing and announced his retirement"
news9 = "Free nuclear fusion energy is a reality, says scientist, we just need to learn " \
"how to do it"
news10 = "RMS Titanic reaches its destiny safely after hitting a small chunk of ice in" \
" the ocean"
news11 = "All the Ice Sculptures business worldwide have declared bankruptcy, says" \
" World Bank"
news12 = "After 'Star Wars: The Phantom Menace' script was leaked people are happy the " \
"franchise got canceled 30 years ago"
news13 = "Microsoft's head says Windows95 will be the last one to ever be launched due to its" \
" low energy use"
news14 = "Programmers for Climate Change Convention ends in confusion after fight over using" \
" tabs or spaces"
news15 = "The series finale of Game of Thrones lowered the Public Well being index of your" \
" nation by x%"
news16 = "Drake's song 'Hotline Bling' is under investigation for being related to higher" \
" temperatures in the US this year"
news17 = "The blockbuster 'Mad Max: Fury Road' shows a sequel of the world we live in, " \
"says director"
news18 = "Lost's last episode is an homage to our own world, which will also have a crappy " \
"ending, says fan"
news19 = "Pearl Harbor movie filming canceled due to the harbor being flooded by the " \
"advancing ocean"
news20 = "Award winning Dwight Schrute's movie 'Recyclops' to gain sequels: 'Recyclops " \
"Reloaded' and 'Recyclops Revolution'"
news21 = "The Simpsons predicted nuclear power scandal in episode where Homer pushes big" \
" red button for no reason"
news = {
'news1': news1,
'news2': news2,
'news3': news3,
'news4': news4,
'news5': news5,
'news6': news6,
'news7': news7,
'news8': news8,
'news9': news9,
'news10': news10,
'news11': news11,
'news12': news12,
'news13': news13,
'news14': news14,
'news15': news15,
'news16': news16,
'news17': news17,
'news18': news18,
'news19': news19,
'news20': news20,
'news21': news21
}
return news
def get_level_2_news():
news1 = "Your X index is up Y% and your N index is down because of Z"
news2 = "President PLAYER_NAME canceled Formula 1 race to save fuel, Public well being, " \
"acceptance and co2 emissions are down x%"
news = {
'news1': news1,
'news2': news2
}
return news
def get_level_3_news():
news1 = "Your X index is down Y% because of Z"
news2 = "In order to save energy, President PLAYER_NAME sanctions law that prohibits people " \
"of ever ironing their clothes. People are so happy that public well being index is" \
" up x% and energy use is down y%"
news = {
'news1': news1,
'news2': news2
}
return news
def get_level_4_news():
news1 = "Your X index is down Y% and it also affected your Z index which is down N%"
news = {
'news1': news1
}
return news
def get_level_5_news():
news1 = "Your X index is down X%, XYZ thing just happened"
news2 = "The Amazon River, the biggest in the world, dries up and becomes the world's " \
"biggest desert"
news3 = "Plants can no longer recognize what season we are on. They now bloom at random " \
"moments of the year"
news = {
'news1': news1,
'news2': news2,
'news3': news3
}
return news
|
user_num = int(input("which number would you like to check?"))
def devisible_by_both():
if user_num %3 == 0 and user_num %5 == 0:
print("your number is divisible by both")
else:
print("your number is not divisible by both")
|
class PyQtSociusError(Exception):
pass
class WrongInputFileTypeError(PyQtSociusError):
__module__ = 'pyqtsocius'
def __init__(self, input_file: str, expected_file_extension: str, extra_message: str = None):
self.file = input_file
self.file_ext = '.' + input_file.split('.')[-1]
self.expected_ext = expected_file_extension
self.message = f"File '{self.file}' with extension '{self.file_ext}', has wrong File type. expected extension --> '{self.expected_ext}'\n"
if extra_message is not None:
self.message += extra_message
super().__init__(self.message)
class FeatureNotYetImplemented(PyQtSociusError):
__module__ = 'pyqtsocius'
def __init__(self, requested_feature):
super().__init__(f"the feature '{requested_feature}' is currently not yet implemented")
|
base_rf.fit(X_train, y_train)
under_rf.fit(X_train, y_train)
over_rf.fit(X_train, y_train)
plot_roc_and_precision_recall_curves([
("original", base_rf),
("undersampling", under_rf),
("oversampling", over_rf),
])
|
# The view that is shown for normal use of this app
# Button name for front page
SUPERUSER_SETTINGS_VIEW = 'twitterapp.views.site_setup'
|
# Stwórz zmienną my_family zawierającą drzewo genealogiczne twojej rodziny.
# Zacznij od siebie - opisując imię, nazwisko, datę urodzenia
# każdej osoby oraz jej rodziców.
# Podpowiedź: rodzice będą listami, zawierającymi w sobie kolejne słowniki.
my_family = {
"first_name": "Mikołaj",
"last_name": "Lewandowski",
"birth_date": "23-11-1991",
"parents": [
{
"first_name": "Jan",
"last_name": "Lewandowski",
"birth_date": "15-11-1961",
"parents": [
{
"first_name": "Piotr",
"last_name": "Lewandowski",
"birth_date": "15-11-1931",
"parents": [],
},
{
"first_name": "Beata",
"last_name": "Lewandowska",
"birth_date": "15-11-1931",
"parents": [],
},
]
},
{
"first_name": "Alicja",
"last_name": "Lewandowski",
"birth_date": "15-11-1961",
"parents": [
{
"first_name": "Paweł",
"last_name": "Kowalski",
"birth_date": "15-11-1931",
"parents": [],
},
{
"first_name": "Anna",
"last_name": "Kowalska",
"birth_date": "15-11-1931",
"parents": [],
},
]
}
],
}
print("Drzewo genealogiczne", my_family)
|
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
self.word = str
class Trie:
def __init__(self):
self.root = TrieNode()
def add_word(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_word = True
node.word = word
class Solution:
"""
@param words: a set of stirngs
@param target: a target string
@param k: An integer
@return: output all the strings that meet the requirements
"""
def kDistance(self, words, target, k):
trie = Trie()
for word in words:
trie.add_word(word)
n = len(target)
dp = [i for i in range(n + 1)]
result = []
self.find(trie.root, target, k, dp, result)
return result
def find(self, node, target, k, dp, result):
n = len(target)
if node.is_word:
print(node.word, dp[n])
if node.is_word and dp[n] <= k:
result.append(node.word)
next = [0 for i in range(n + 1)]
for c in node.children:
next[0] = dp[0] + 1
for i in range(1, n + 1):
if target[i - 1] == c:
# print(target[i - 1], c)
next[i] = min(dp[i - 1], min(dp[i] + 1, next[i - 1] + 1))
else:
next[i] = min(dp[i - 1] + 1, dp[i] + 1, next[i - 1] + 1)
self.find(node.children[c], target, k, next, result)
|
class MoonBoard():
"""
Class that encapsulates Moonboard layout info for a specific year.
:param year_layout: Year in which this board layout was published
:type year_layout: int
:param image: Path to the image file for this board layout
:type image: str
:param rows: Number of rows of the board. Defaults to 18
:type rows: int, optional
:param cols: Number of columns of the board. Defaults to 11
:type cols: int, optional
"""
def __init__(self, year_layout: int, image: str, rows: int = 18, cols: int = 11) -> None:
"""
Initialize a MoonBoard object.
"""
self._year_layout = year_layout
self._image = image
self._rows = rows
self._cols = cols
def __str__(self) -> str:
"""Get a user friendly string representation of the MoonBoard class
:return: User firendly string representation if this Moonboard object
:rtype: str
"""
return f"{__class__.__name__} for {self._moonboard.get_year_layout()} layout"
def __hash__(self) -> int:
"""
Compute hash from the year, image path
"""
return hash(self._year_layout) ^ hash(self._image) ^ hash(self._rows) ^ hash(self._cols)
def __eq__(self, __o: object) -> bool:
"""
Test for equality between two MoonBoard objects
"""
if hash(self) != hash(__o): # if hashes are not equal, objects cannot be equal
return False
return self._year_layout == __o._year_layout and self._image == __o._image and self._rows == __o._rows and self._cols == __o._cols
def get_rows(self) -> int:
"""
Get number of rows of the board
:return: Number of rows of the board
:rtype: int
"""
return self._rows
def get_cols(self) -> int:
"""
Get number of columns of the board
:return: Number of columns of the board
:rtype: int
"""
return self._cols
def get_year_layout(self) -> int:
"""
Get the year in which this board layout was published
:return: Year in which this board layout was published
:rtype: int
"""
return self._year_layout
def get_image(self) -> str:
"""
Get the path to the image file for this board layout
:return: Image path
:rtype: str
"""
return self._image
def get_moonboard(year: int) -> MoonBoard:
"""
Factory function. Given a year, return a Moonboard object encapsulating the
Moonboard layout info of that year.
:param year: Year of the desired Moonboard layout
:type year: int
:return: Moonboard object encapsulating the Moonboard layout info
:rtype: MoonBoard
:raises ValueError: Year is not a valid Moonboard year
"""
if year == 2016:
return MoonBoard(2016, 'moonboards/2016.jpg')
elif year == 2017:
return MoonBoard(2017, 'moonboards/2017.jpg')
elif year == 2019:
return MoonBoard(2019, 'moonboards/2019.jpg')
elif year == 2020:
return MoonBoard(2020, 'moonboards/2020.jpg', rows=12)
raise ValueError('Invalid year')
|
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 19:42:35 2020
@author: Administrator
"""
"""
给定一个矩阵序列,找到最有效的方式将这些矩阵相乘在一起.给定表示矩阵链的数组p,使得第i个矩阵Ai的维数为p[i-1]*p[i].
编写一个函数MatrixChainOrder(),该函数应该返回乘法运算所需的最小乘法数.
输入:p=(40,20,30,10,30)
输出:26000
有四个大小为40*20,20*30,30*10和10*30的矩阵.假设这四个矩阵为A,B,C和D,该函数的执行方法可以执行乘法运算的次数最少.
"""
def MatrixChainOrder(p , minMulti):
lens = len(p) - 1
if lens == 2:
minMulti = p[0] * p[1] * p[2]
return minMulti
elif lens > 2:
minMulti = min(MatrixChainOrder(p[0:-1] , minMulti) + p[0] * p[-2] * p[-1] , \
MatrixChainOrder(p[1:] , minMulti) + p[0] * p[1] * p[-1])
return minMulti
if __name__ == "__main__":
p = [40 , 20 , 30 , 10 , 30]
minMulti = 2 ** 10
minMulti = MatrixChainOrder(p , minMulti)
print("The minimum multiple times is : " , minMulti)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
############################
# File Name: calc.py
# Author: One Zero
# Mail: zeroonegit@gmail.com
# Created Time: 2015-12-28 00:22:01
############################
# 定义函数
def add(x, y):
'''相加'''
return x + y
def subtract(x, y):
'''相减'''
return x - y
def multiply(x, y):
'''相乘'''
return x * y
def divide(x, y):
'''相除'''
return x / y
# 用户输入
print('选择运算: ')
print('1、相加')
print('2、相减')
print('3、相乘')
print('4、相除')
choice = input('输入你的选择(1/2/3/4): ')
num1 = int(input('输入第一个数字: '))
num2 = int(input('输入第二个数字: '))
if choice == '1':
print('{} + {} = {}'.format(num1, num2, add(num1, num2)))
elif choice == '2':
print('{} - {} = {}'.format(num1, num2, subtract(num1, num2)))
elif choice == '3':
print('{} * {} = {}'.format(num1, num2, multiply(num1, num2)))
elif choice == '4':
print('{} / {} = {}'.format(num1, num2, divide(num1, num2)))
else:
print('非法输入')
|
'''Write a Python program to empty a variable without destroying it.
Sample data: n=20
d = {"x":200}
Expected Output : 0
{}'''
n = 20
d = {"x":200}
print(type(n)())
print(type(d)())
|
{
"name": "Module Wordpess Mysql",
"author": "Tedezed",
"version": "0.1",
"frontend": "wordpress",
"backend": "mysql",
"check_app": True,
"update_app_password": True,
"update_secret": True,
"executable": False,
}
|
"""
@author : udisinghania
@date : 24/12/2018
"""
string1 = input()
string2 = input()
a = 0
if len(string1)!=len(string2):
print("Strings are of different length")
else:
for i in range (len(string1)):
if string1[i]!=string2[i]:
a+=1
print(a)
|
AGENDA = {}
def exibir_contatos():
if len(AGENDA) > 0:
for contato in AGENDA:
buscar_contato(contato)
print('-' * 30)
else:
print('\nA sua agenda está vazia. Adicione alguns contatos!\n')
def buscar_contato(contato):
try:
print(f'Nome: {contato}')
print('Celular:', AGENDA[contato]['celular'])
print('E-mail:', AGENDA[contato]['email'])
except KeyError:
print(f'\nO contato {contato} não existe na agenda.\n')
except:
print('\nDesculpe, aconteceu um erro inesperado.\n')
# Verifica se o nome do contato digitado já existe na agenda. Linha 87 e 97 #
def verificando_se_existe(contato):
if contato in AGENDA:
return True
return False
def incluir_contato(contato, celular, email, verificacao_incluir_editar = True):
AGENDA[contato] = {
'celular': celular,
'email': email
}
# Verificação para retornar a mensagem correta. #
if verificacao_incluir_editar:
print(f'\nO contato {contato} foi incluido.\n')
else:
print(f'\nO contato {contato} foi editado.\n')
def editar_contato(contato, celular, email):
incluir_contato(contato, celular, email, verificacao_incluir_editar = False)
def deletar_contato(contato):
try:
AGENDA.pop(contato)
print(f'\nO contato {contato} foi deletado.\n')
except KeyError:
print(f'\nO contato {contato} não existe na agenda.\n')
# Função que exporta contatos para um arquivo txt #
def exportar_contatos():
try:
with open('agenda.txt', 'w') as arquivo:
arquivo.write('Nome, Celular, E-mail\n')
for contato in AGENDA:
celular = AGENDA[contato]['celular']
email = AGENDA[contato]['email']
arquivo.write(f'{contato}, {celular}, {email}\n')
print('\nSua agenda foi exportada com sucesso!\n')
except Exception as error:
print('\nDesculpe, aconteceu um erro inesperado.\n')
def imprimir_menu():
print('\n1 - Exibir contatos')
print('2 - Buscar um contato')
print('3 - Incluir um contato')
print('4 - Editar um contato')
print('5 - Deletar um contato')
print('6 - Exportar agenda para um arquivo txt')
print('0 - Fechar agenda\n')
while True:
imprimir_menu()
action = (input('Digite o que deseja fazer: '))
print()
if action == '1':
exibir_contatos()
elif action == '2':
contato = input('Digite o nome do contato: ')
print('-' * 30)
buscar_contato(contato)
print('-' * 30)
elif action == '3':
contato = input('Digite o nome do contato: ')
if verificando_se_existe(contato):
print(f'\nO contato {contato} já existe na agenda. Tente adicioná-lo com outro nome ou sobrenome.\n')
else:
celular = input('Digite o número do celular do contato: ')
email = input('Digite o e-mail do contato: ')
incluir_contato(contato, celular, email)
elif action == '4':
contato = input('Digite o nome do contato que deseja editar: ')
if verificando_se_existe(contato):
celular = input('Digite o número do celular do contato: ')
email = input('Digite o e-mail do contato: ')
editar_contato(contato, celular, email)
else:
print(f'\nO contato {contato} não existe na agenda.\n')
elif action == '5':
contato = input('Digite o nome do contato que deseja deletar: ')
deletar_contato(contato)
elif action == '6':
exportar_contatos()
elif action == '0':
print('A agenda foi fechada.')
break
else:
print('Por favor, dhigite um comando válido.')
|
"""Minimize_sum_Of_array!!!, CodeWars Kata, level 7."""
def minimize_sum(arr):
"""Minimize sum of array.
Find pairs of to multiply then add the product of those multiples
to find the minimum possible sum
input = integers, in a list
output = integer, the minimum sum of those products
ex: minSum(5,4,2,3) should return 22, 5*2 +3*4 = 22
ex: minSum(12,6,10,26,3,24) should return 342, 26*3 + 24*6 + 12*10 = 342
"""
x = len(arr)
res = []
arr1 = sorted(arr)
for i in range(x // 2):
minprod = arr1[0] * arr1[-1]
arr1.pop()
arr1.pop(0)
res.append(minprod)
return sum(res)
|
# Copyright (c) 2011-2020 Eric Froemling
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# -----------------------------------------------------------------------------
# This file was automatically generated from "doom_shroom.ma"
# pylint: disable=all
points = {}
# noinspection PyDictCreation
boxes = {}
boxes['area_of_interest_bounds'] = (0.4687647786, 2.320345088,
-3.219423694) + (0.0, 0.0, 0.0) + (
21.34898078, 10.25529817, 14.67298352)
points['ffa_spawn1'] = (-5.828122667, 2.301094498,
-3.445694701) + (1.0, 1.0, 2.682935578)
points['ffa_spawn2'] = (6.496252674, 2.397778847, -3.573241388) + (1.0, 1.0,
2.682935578)
points['ffa_spawn3'] = (0.8835145921, 2.307217208,
-0.3552854962) + (4.455517747, 1.0, 0.2723037175)
points['ffa_spawn4'] = (0.8835145921, 2.307217208,
-7.124335491) + (4.455517747, 1.0, 0.2723037175)
points['flag1'] = (-7.153737138, 2.251993091, -3.427368878)
points['flag2'] = (8.103769491, 2.320591215, -3.548878069)
points['flag_default'] = (0.5964565429, 2.373456481, -4.241969517)
boxes['map_bounds'] = (0.4566560559, 1.332051421, -3.80651373) + (
0.0, 0.0, 0.0) + (27.75073129, 14.44528216, 22.9896617)
points['powerup_spawn1'] = (5.180858712, 4.278900266, -7.282758712)
points['powerup_spawn2'] = (-3.236908759, 4.159702067, -0.3232556512)
points['powerup_spawn3'] = (5.082843398, 4.159702067, -0.3232556512)
points['powerup_spawn4'] = (-3.401729203, 4.278900266, -7.425891191)
points['shadow_lower_bottom'] = (0.5964565429, -0.2279530265, 3.368035253)
points['shadow_lower_top'] = (0.5964565429, 0.6982784189, 3.368035253)
points['shadow_upper_bottom'] = (0.5964565429, 5.413250948, 3.368035253)
points['shadow_upper_top'] = (0.5964565429, 7.891484473, 3.368035253)
points['spawn1'] = (-5.828122667, 2.301094498, -3.445694701) + (1.0, 1.0,
2.682935578)
points['spawn2'] = (6.496252674, 2.397778847, -3.573241388) + (1.0, 1.0,
2.682935578)
|
#!/usr/bin/python
# -*- utf-8 -*-
class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
copy = [e for e in nums]
l = len(nums)
k = l - k % l
for i in range(l):
nums[i] = copy[(k + i) % l]
def rotate2(self, nums, k):
if not nums:
return
l = len(nums)
for i in range(k % l):
last = nums[-1]
for j in range(l-1, 0, -1):
nums[j] = nums[j-1]
nums[0] = last
def rotate3(self, nums, k):
# Todo third method
# Fixme rotate([1, 2, 3, 4, 5, 6], 2)
if not nums:
return
l = len(nums)
k = k % l
if k == 0:
return
last = nums[0]
cur = k
for e in nums:
nums[cur], last = last, nums[cur]
cur = (cur + k) % l
if __name__ == '__main__':
s = Solution()
l = [1, 2, 3, 4, 5, 6, 7]
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 0)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 3)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 6)
print(l)
l = [1, 2, 3, 4, 5, 6, 7]
s.rotate(l, 9)
print(l)
l = [1, 2, 3, 4, 5, 6]
s.rotate(l, 2)
print(l)
|
# Enter your code for "camelCase" here.
def to_camel(ident):
def a(x):
return x
def b(x):
return x[0].upper() + x[1::]
def c():
yield a
while True:
yield b
d = c()
return "".join(d.__next__()(x) for x in ident.split("_"))
|
# Write a program that asks the user to input any positive integer
# and outputs the successive values of the following calculation.
# At each step calculate the next value by taking the current value and,
# if it is even, divide it by two, but if it is odd, multiply it by three and add one.
# Have the program end if the current value is one.
# There is an ambiguity in the question, however:
# What if the user enters one?
# I chose not to end the program immediately in this case.
# In order not to end the program immediately if the user
# enters one, a 'while (x != 1)': loop will not work.
# Instead, a 'while true:' loop can be used, which breaks
# once 'x = 1'. I appreciate that 'while true:' is not
# generally considered best practice, but the absence of
# of a 'do-while' loop in python makes this unavoidable.
# Store the user's input as an integer.
x = int(input("Enter a positive integer and see what happens: "))
print(x)
# As there is no do-while loop built into Python,
# Use a 'while-true' loop that ends (with 'break') once the relevant variable equals one.
while True:
# To calculate the variable's next value, use an if-else block:
# to determine if the variable is even, use the modulus operator (x % 2 = 0);
# in all other cases the variable is odd.
if x % 2 == 0:
# use floor division '//' so that an integer rather than a float results.
x = x // 2
print(x)
else:
x = (x * 3) + 1
print(x)
if x == 1:
break
|
class ModelPermissionsMixin(object):
"""
Defines the permissions methods that most models need,
:raises NotImplementedError: if they have not been overridden.
"""
@classmethod
def can_create(cls, user_obj):
"""
CreateView needs permissions at class (table) level.
We'll try it at instance level for a while and see how it goes.
"""
raise NotImplementedError
@classmethod
def can_view_list(cls, user_obj):
"""
ListView needs permissions at class (table) level.
We'll try it at instance level for a while and see how it goes.
"""
raise NotImplementedError
def can_update(self, user_obj):
"""
UpdateView needs permissions at instance (row) level.
"""
raise NotImplementedError
def can_view(self, user_obj):
"""
DetailView needs permissions at instance (row) level.
"""
raise NotImplementedError
def can_delete(self, user_obj):
"""
DeleteView needs permissions at instance (row) level.
"""
raise NotImplementedError
|
class BatmanQuotes(object):
@staticmethod
def get_quote(quotes, hero):
index = int(sorted(hero)[0])
return {'B':'Batman: ','R':'Robin: ','J':'Joker: '}[hero[0]] + quotes[index]
|
class Node:
starting = True
ending = False
name = ""
weight = [1, 20]
active = True
edge_length = 0
nodes = []
def __init__(self, name, grid, posX, posY, active):
self.name = name # Name of the node
self.grid = grid # Which grid the node will be placed
self.posX = posX # Position X on the grid
self.posY = posY # Position Y on the grid
self.active = active # Is active
pass
def add(self, newNode):
#To DO
self.nodes.append(newNode)
print("Added new node")
pass
def remove(self, node):
#To DO
self.nodes = []
print("The node has been removed")
pass
def update(self, index, node):
self.nodes.pop(index)
self.nodes.insert(index, node)
print("The node has been updated")
pass
|
#!/usr/bin/env python3
dna = "ATGCAGGGGAAACATGATTCAGGAC"
#Make all lowercase
lowerDNA = dna.lower()
#Replace the complementary ones
complA = lowerDNA.replace('a','T')
complAT = complA.replace('t','A')
complATG = complAT.replace('g','C')
complATGC = complATG.replace('c','G')
#reverse the complement
revDNA = complATGC[::-1]
#Print out the answers
print("Original Sequence\t5'",dna,"5'")
print("Complement\t\t3'",complATGC,"5'")
print("Reverse Complement\t5'",revDNA,"3'")
|
# with open("ReadMe.txt",'r') as file:
# print(file.read()) # Hello from Python 201
# # Running after adding the second line to the .txt file
# with open("ReadMe.txt",'r') as file:
# print(file.read()) # Hello from Python 201
# # This is a new line
# # Running after adding the second line to the .txt file
# with open("ReadMe.txt",'r') as file:
# pass
# print(file.read()) # Traceback (most recent call last):
# # File "ReadingFiles.py", line 15, in <module>
# # print(file.read())
# # ValueError: I/O operation on closed file.
# Assigning the content to a variable and then reading the file
with open("ReadMe.txt",'r') as file:
content = file.read()
# python has closed the file
print("The content is", content) # The content is Hello from Python 201
# This is a new line
|
OCTICON_LAW = """
<svg class="octicon octicon-law" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M8.75.75a.75.75 0 00-1.5 0V2h-.984c-.305 0-.604.08-.869.23l-1.288.737A.25.25 0 013.984 3H1.75a.75.75 0 000 1.5h.428L.066 9.192a.75.75 0 00.154.838l.53-.53-.53.53v.001l.002.002.002.002.006.006.016.015.045.04a3.514 3.514 0 00.686.45A4.492 4.492 0 003 11c.88 0 1.556-.22 2.023-.454a3.515 3.515 0 00.686-.45l.045-.04.016-.015.006-.006.002-.002.001-.002L5.25 9.5l.53.53a.75.75 0 00.154-.838L3.822 4.5h.162c.305 0 .604-.08.869-.23l1.289-.737a.25.25 0 01.124-.033h.984V13h-2.5a.75.75 0 000 1.5h6.5a.75.75 0 000-1.5h-2.5V3.5h.984a.25.25 0 01.124.033l1.29.736c.264.152.563.231.868.231h.162l-2.112 4.692a.75.75 0 00.154.838l.53-.53-.53.53v.001l.002.002.002.002.006.006.016.015.045.04a3.517 3.517 0 00.686.45A4.492 4.492 0 0013 11c.88 0 1.556-.22 2.023-.454a3.512 3.512 0 00.686-.45l.045-.04.01-.01.006-.005.006-.006.002-.002.001-.002-.529-.531.53.53a.75.75 0 00.154-.838L13.823 4.5h.427a.75.75 0 000-1.5h-2.234a.25.25 0 01-.124-.033l-1.29-.736A1.75 1.75 0 009.735 2H8.75V.75zM1.695 9.227c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L3 6.327l-1.305 2.9zm10 0c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L13 6.327l-1.305 2.9z"></path></svg>
"""
|
__all__ = ['__author__', '__license__', '__version__', '__credits__', '__maintainer__']
__author__ = 'Henrik Nyman'
__license__ = 'MIT'
__version__ = '0.1'
__credits__ = ['Henrik Nyman']
__maintainer__ = 'Henrik Nyman'
|
print("Primeira e Última String\n")
frase = str(input("Digite a frase: ")).strip().upper()
print("A letra A aparece {} vezes na frase\n".format(frase.count('A')))
print(f"A primeira letra A aparece na posição: {frase.find('A')+1}\n")
print(f"A última letra A aparece na posição: {frase.rfind('A')+1}\n")
|
def projectData(X, U, K):
"""computes the projection of
the normalized inputs X into the reduced dimensional space spanned by
the first K columns of U. It returns the projected examples in Z.
"""
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the projection of the data using only the top K
# eigenvectors in U (first K columns).
# For the i-th example X(i,:), the projection on to the k-th
# eigenvector is given as follows:
# x = X(i, :)'
# projection_k = x' * U(:, k)
#
# =============================================================
return Z
|
def ssort(array):
for i in range(len(array)):
indxMin = i
for j in range(i+1, len(array)):
if array[j] < array[indxMin]:
indxMin = j
tmp = array[indxMin]
array[indxMin] = array[i]
array[i] = tmp
return array
|
# _*_ conding:utf8-
'''
# 如果要有默认参数,那么一定统一塞到最后面
def test(name1,name2='Joker',name3='Joker2'):
print(name1,name2,name3)
test('h','h','j')
# * 强制命名,*后面的所有参数,在传参过程中必须要带上
# 参数名防止传参错误
def NB(name1,*,name2='Joker',name3='Joker2'):
print(name1,name2,name3)
# 1. 位置参数,可以不带参数名
# 2. 带参数名的传参方式
NB('Joker3',name2='hahah',name3='heihei')
# 匿名函数,装逼函数,只能完成一些简单的问题
# : 前面,是装逼函数的输入量,后面是装逼函数的输出量
func = lambda x,y,z=1000:print(x+y+z)
func(100,100)
# 装逼函数完全体
(lambda x,y,z=1000:print(x+y+z))(100,100)
# 不定长参数 *args 下水道::你来多少,我装多少
# * 只是一个标示,意味着后面的参数是一个不定长参数,所以args可以更改成别的你喜欢的参数名
# 但是约定俗成的是args
# 传参的方式是:单个元素,不能带参数名
def AGS(*args):
print(args) # 返回的叫元组
# AGS(1,2,3,4,5,7,89,0,43,2,4,67,8,5,123,1,231)
# ---------------------
# ** 也是一个标示,所以kwargs也是可以更换的,但是约定俗成是kwargs
# 传参形式一定要是带参数名的(实际上是一个键值对)
# 返回的是一个字典
def KWargs(**kwargs):
print(kwargs)
# KWargs(a = '100',b = 100,c = True)
# 终极用法在Python中,完整的不定长函数
#----------------
def argsKw(*args,**kwargs):
print(args)
print(kwargs)
# 全局变量 Mist
# 使用全局变量的时候,必须要声明全局变量,
# 否则无法更改全局变量
Mist = 0
def test4():
global Mist
Mist += 10
print(Mist)
test4()
print(Mist)
globals() #返回运行开始到现在为止所有的全局变量表
locals() # 返回运行开始到现在为止所有的局部变量表
'''
|
depl_user = 'darulez'
depl_group = 'docker'
# defaults file for ansible-docker-apps-generator
assembly_path = 'apps-assembly'
apps_path = './apps-universe'
stacks_path = './stacks-universe'
default_docker_network = 'hoa_network'
docker_main_sections = ['docker_from', 'docker_init', 'docker_reqs', 'docker_core', 'docker_post']
|
class Solution:
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# bfs
# corner case
if root is None:
return 0
queue = list()
queue.append((root, 0))
level = 1
while len(queue) > 0:
length = len(queue)
tmp = list()
for _ in range(length):
curr, x = queue.pop(0)
tmp.append(x)
if curr.left:
queue.append((curr.left, 2*x))
if curr.right:
queue.append((curr.right, 2*x+1))
level = max(level, max(tmp)-min(tmp)+1)
return level
|
class TrieNode(object):
__slots__ = ('children', 'isWord')
def __init__(self):
self.children = {}
self.isWord = False
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
root = self.root
for c in word:
if c not in root.children:
root.children[c] = TrieNode()
root = root.children[c]
root.isWord = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
root = self.root
for c in word:
root = root.children.get(c)
if root is None:
return False
return root.isWord
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
root = self.root
for c in prefix:
root = root.children.get(c)
if root is None:
return False
return True
|
nomemv = ''
media = m20 = mv = 0
for i in range(4):
nome = input('Digite o nome da pessoa {}: '.format(i))
idade = int(input('Digite a idade do(a) {}: '.format(nome)))
sexo = input('Digite o sexo do(a) {}: '.format(nome))
media = media + idade
if(sexo=='f'):
if(idade<20):
m20 = m20+1
else:
if(idade > mv):
nomemv=nome
mv = idade
print(nomemv,' é o homem mais velho')
print('A media de idades do grupo é ',media/4)
print('Existem {} mulheres com menos de 20 anos'.format(m20))
|
class FastLabelException(Exception):
def __init__(self, message, errcode):
super(FastLabelException, self).__init__(
"<Response [{}]> {}".format(errcode, message)
)
self.code = errcode
class FastLabelInvalidException(FastLabelException, ValueError):
pass
|
'''ALUMNA: HUAMANI TACOMA ANDY
EJERCICIO : PAINT DASH GRIDS-DFS-RECURSIVE'''
# DESCRIPCION: IMPLEMENTACION DE DFS-RECURSIVE PARA PINTAR LOS DASH GRIDS DE UNA MATRIZ
def dfs_recursive(matrix, startX, startY, simbVisited, simbPared):
# TABLERO, POSICION INICIALX, POSICION INICIALY, SIMBOLO VISITADO, SIMBOLO PARED
try:
if(matrix[startX][startY] != simbPared): # SI EL ELEMENTO NO ES PARED
matrix[startX][startY] = simbVisited # SE CAMBIA POR EL SIMBOLO VISITADO
else: # SI ES PARED NO SE VISITA
print("es pared, no se pude pintar") # SE IMPRIME
return matrix # SE RETORNA LA MATRIZ
except: # SI LA POSICION ESTA FUERA DE LOS LIMITES
print("Fuera del os limites") # SE IMPRIME
return matrix # SE RETORNA LA MATRIZ
print("Punto Central: (" + str(startX)+","+str(startY)+")") # SE IMPRIME LA POSICION DEL PUNTO CENTRAL
dx = [-1,0,1,0] # VECTOR DE MOVIMIENTO EN X
dy = [0,1,0,-1] # VECTOR DE MOVIMIENTO EN Y
for i in range(4): # SE REALIZA EL RECORRIDO EN TODAS LAS DIRECCIONES
nx = dx[i] + startX # SE OBTIENE LA POSICION EN X
ny = dy[i] + startY # SE OBTIENE LA POSICION EN Y
if((nx >= 0 and nx < len(matrix)) and (ny >= 0 and ny < len(matrix[startX]))): # SI LA POSICION ESTA DENTRO DEL TABLERO
if(matrix[nx][ny] != simbVisited and matrix[nx][ny] != simbPared): # SI EL ELEMENTO NO ESTA VISITADO Y NO ES PARED
dfs_recursive(matrix, nx, ny, simbVisited, simbPared) # SE LLAMA AL METODO RECURSIVO
return matrix # SE RETORNA LA MATRIZ
# IMPRIMIR LA MATRIZ
def printMatrix(matrix):
for i in matrix:
for j in i:
print(" " , j , end=" ")
print()
# CASO DE PRUEBA
# MATRIZ
matrix = [
["#","#","#","#","#","#"],
["#","-","-","-","-","#"],
["#","-","-","-","-","#"],
["#","-","-","-","-","#"],
["#","-","-","-","#","-"],
["#","#","#","#","-","-"],
]
# PRUEBA 01
# MATRIZ INICIAL
printMatrix(matrix)
# MATRIZ DE VISITADOS
printMatrix(dfs_recursive(matrix, 1, 2, "o", "#"))
print("\n---------------------------------------------------------")
# PRUEBA 02
# MATRIZ INICIAL
printMatrix(matrix)
# MATRIZ DE VISITADOS
printMatrix(dfs_recursive(matrix, 5, 5, "o", "#"))
|
__all__ = ["PACK_HEADER_MAX"]
# max scanned length of packet header
PACK_HEADER_MAX = 60
|
'''We sort a large sublist of a given list and go on reducing the size of the list until all elements are sorted.'''
def shellSort(input_list):
mid = len(input_list) // 2
while mid > 0:
for i in range(mid, len(input_list)):
temp = input_list[i]
j = i
# Sort the sub list for this gap
while j >= mid and input_list[j - mid] > temp:
input_list[j] = input_list[j - mid]
j = j - mid
input_list[j] = temp
# Reduce the gap for the next element
mid = mid // 2
list = [25, 2, 30, 1, 45, 39, 11, 110, 29]
shellSort(list)
print(list)
|
# some basic settings
ph = 350 # pageheight
pw = ph * 2 # pagewidth
steps = 180 # how many pages / steps to draw
dot_s = 8 # size of the dots at the end of the radius
radius = ph/2 * .75
angle = 2*pi/steps
gap = radius / (steps - 1) * 2 # used to draw the dots of the sine wave
sin_vals = [sin(i*angle) for i in range(steps)] # calculate and store the sine values once
def base_page(i):
'''basic stuff that gets drawn and used on every page'''
newPage(pw, ph)
fill(1)
rect(0, 0, pw, ph)
fill(0)
translate(0, ph/2)
fontSize(8)
for j in range(-10, 11, 2):
text('%.1f' % (j/10), (pw/2, radius/10 * j), align = 'right')
fill(.5)
rect(ph/2 * .25, -ph/2, 1, ph)
rect(ph/2 * .25 + 2 * radius, -ph/2, 1, ph)
# drawing of the sine wave
with savedState():
translate((ph - radius *2)/2, 0)
for st in range(steps):
sin_val = sin_vals[ (st+i+1) % steps]
oval(st * gap - 2, sin_val * radius - 2, 4, 4)
translate(ph + ph/2, 0)
fill(None)
stroke(.5)
strokeWidth(1)
oval(-radius, -radius, radius*2, radius*2)
line((-ph/2 * 3, 0), (ph/2, 0))
line((0, -ph/2), (0, ph/2))
fontSize(14)
for i in range(steps):
base_page(i)
cos_val = cos(i * angle)
sin_val = sin(i * angle)
x = cos_val * radius
y = sin_val * radius
stroke(.75)
line((x, max(0, y)),(x, -radius))
line((max(x, 0), y),(- pw/2 + radius, y))
strokeWidth(2)
# radius
stroke(0, 0, 1)
line((0, 0),(x, y))
# cosine distance
stroke(1, 0, 0)
line((0, 0),(x, 0))
# sine distance
stroke(0, .5, 0)
line((0, 0),(0, y))
stroke(None)
fill(0, 0, 1, .2)
pth = BezierPath()
pth.moveTo((0, 0))
pth.lineTo((radius/4, 0))
pth.arc((0, 0), radius/4, 0, degrees(i * angle), clockwise = False)
pth.closePath()
drawPath(pth)
fill(0)
text('cos(θ)', (x/2, -18), align = 'center')
text('sin(θ)', (8, y/2 + 4))
text('%d°' % (i * degrees(angle)), (radius/4 + 4, 8))
text('%.3f' % cos_val, (x, -radius - 16), align = 'center')
text('%.3f' % sin_val, (- pw/2 + radius - 4, y), align = 'right')
fill(.5)
oval(-dot_s/2, -dot_s/2, dot_s, dot_s)
oval(x-dot_s/2, y-dot_s/2, dot_s, dot_s)
# saveImage('sine.gif')
|
"""
PASSENGERS
"""
numPassengers = 2341
passenger_arriving = (
(3, 12, 4, 1, 1, 0, 2, 7, 5, 7, 0, 0), # 0
(4, 12, 2, 2, 4, 0, 2, 5, 3, 3, 2, 0), # 1
(3, 2, 3, 2, 2, 0, 6, 7, 5, 5, 2, 0), # 2
(1, 10, 4, 2, 1, 0, 6, 5, 1, 4, 1, 0), # 3
(3, 3, 2, 5, 4, 0, 9, 6, 7, 3, 5, 0), # 4
(5, 7, 4, 2, 3, 0, 5, 7, 4, 5, 0, 0), # 5
(2, 9, 4, 1, 2, 0, 7, 5, 5, 4, 0, 0), # 6
(4, 6, 13, 3, 2, 0, 5, 5, 3, 4, 2, 0), # 7
(1, 2, 7, 4, 3, 0, 2, 6, 4, 6, 3, 0), # 8
(4, 7, 5, 2, 3, 0, 4, 2, 4, 6, 0, 0), # 9
(3, 3, 3, 3, 2, 0, 2, 5, 4, 5, 0, 0), # 10
(2, 2, 4, 3, 2, 0, 4, 2, 6, 0, 4, 0), # 11
(3, 10, 7, 0, 2, 0, 2, 5, 3, 1, 4, 0), # 12
(3, 9, 6, 2, 0, 0, 4, 10, 3, 4, 1, 0), # 13
(5, 6, 6, 3, 1, 0, 5, 6, 3, 4, 0, 0), # 14
(1, 7, 8, 1, 3, 0, 3, 6, 4, 4, 1, 0), # 15
(7, 5, 6, 0, 1, 0, 3, 8, 4, 6, 2, 0), # 16
(0, 4, 5, 3, 4, 0, 4, 6, 6, 3, 3, 0), # 17
(6, 8, 6, 3, 1, 0, 5, 2, 6, 1, 1, 0), # 18
(3, 8, 8, 2, 2, 0, 5, 7, 9, 2, 0, 0), # 19
(3, 5, 6, 4, 2, 0, 8, 8, 4, 3, 2, 0), # 20
(6, 9, 4, 1, 3, 0, 7, 8, 4, 2, 3, 0), # 21
(3, 4, 4, 3, 3, 0, 3, 11, 3, 3, 1, 0), # 22
(3, 8, 3, 2, 0, 0, 4, 4, 4, 4, 2, 0), # 23
(2, 5, 7, 5, 2, 0, 3, 9, 6, 4, 2, 0), # 24
(3, 7, 3, 2, 1, 0, 4, 11, 3, 5, 2, 0), # 25
(0, 12, 5, 0, 2, 0, 3, 6, 4, 2, 2, 0), # 26
(4, 7, 5, 1, 2, 0, 4, 5, 6, 1, 5, 0), # 27
(4, 3, 6, 1, 1, 0, 4, 4, 4, 5, 3, 0), # 28
(1, 8, 6, 3, 3, 0, 4, 5, 5, 6, 1, 0), # 29
(5, 4, 4, 0, 1, 0, 3, 5, 5, 8, 2, 0), # 30
(4, 6, 5, 4, 0, 0, 5, 4, 3, 1, 1, 0), # 31
(4, 10, 4, 2, 0, 0, 3, 2, 7, 6, 1, 0), # 32
(3, 4, 4, 2, 4, 0, 6, 5, 3, 3, 1, 0), # 33
(7, 3, 2, 2, 2, 0, 4, 7, 3, 5, 0, 0), # 34
(5, 8, 6, 3, 3, 0, 7, 7, 3, 4, 0, 0), # 35
(2, 8, 3, 1, 0, 0, 6, 4, 3, 3, 3, 0), # 36
(6, 8, 6, 2, 1, 0, 8, 7, 8, 0, 3, 0), # 37
(0, 6, 4, 5, 0, 0, 2, 7, 3, 2, 2, 0), # 38
(4, 2, 3, 3, 1, 0, 6, 8, 7, 3, 0, 0), # 39
(3, 5, 2, 3, 1, 0, 5, 3, 10, 4, 3, 0), # 40
(6, 5, 7, 2, 0, 0, 6, 4, 1, 4, 4, 0), # 41
(7, 8, 5, 5, 0, 0, 4, 13, 1, 3, 1, 0), # 42
(3, 10, 8, 2, 2, 0, 8, 4, 9, 4, 4, 0), # 43
(4, 6, 7, 4, 0, 0, 8, 7, 4, 0, 0, 0), # 44
(3, 7, 7, 2, 2, 0, 9, 6, 4, 2, 1, 0), # 45
(2, 14, 5, 2, 2, 0, 3, 8, 1, 1, 2, 0), # 46
(8, 4, 2, 1, 2, 0, 8, 6, 2, 3, 0, 0), # 47
(4, 5, 6, 1, 0, 0, 5, 7, 3, 2, 1, 0), # 48
(4, 4, 3, 1, 1, 0, 3, 5, 2, 6, 2, 0), # 49
(1, 9, 5, 6, 0, 0, 7, 5, 5, 1, 2, 0), # 50
(5, 3, 6, 2, 1, 0, 8, 3, 6, 3, 1, 0), # 51
(2, 8, 6, 9, 1, 0, 12, 1, 8, 3, 2, 0), # 52
(4, 8, 7, 3, 0, 0, 8, 8, 5, 4, 0, 0), # 53
(5, 7, 2, 1, 0, 0, 4, 8, 0, 5, 2, 0), # 54
(1, 9, 9, 3, 0, 0, 2, 9, 4, 7, 1, 0), # 55
(2, 8, 6, 3, 4, 0, 3, 11, 5, 4, 3, 0), # 56
(6, 5, 3, 2, 1, 0, 5, 6, 4, 1, 2, 0), # 57
(3, 6, 6, 3, 2, 0, 3, 3, 4, 4, 2, 0), # 58
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # 59
)
station_arriving_intensity = (
(2.649651558384548, 6.796460700757575, 7.9942360218509, 6.336277173913043, 7.143028846153846, 4.75679347826087), # 0
(2.6745220100478, 6.872041598712823, 8.037415537524994, 6.371564387077295, 7.196566506410256, 4.7551721391908215), # 1
(2.699108477221734, 6.946501402918069, 8.07957012282205, 6.406074879227053, 7.248974358974359, 4.753501207729468), # 2
(2.72339008999122, 7.019759765625, 8.120668982969152, 6.4397792119565205, 7.300204326923078, 4.7517809103260875), # 3
(2.747345978441128, 7.091736339085298, 8.160681323193373, 6.472647946859904, 7.350208333333334, 4.750011473429951), # 4
(2.7709552726563262, 7.162350775550646, 8.199576348721793, 6.504651645531401, 7.39893830128205, 4.748193123490338), # 5
(2.794197102721686, 7.231522727272727, 8.237323264781493, 6.535760869565218, 7.446346153846154, 4.746326086956522), # 6
(2.817050598722076, 7.299171846503226, 8.273891276599542, 6.565946180555556, 7.492383814102565, 4.744410590277778), # 7
(2.8394948907423667, 7.365217785493826, 8.309249589403029, 6.595178140096618, 7.537003205128205, 4.7424468599033816), # 8
(2.8615091088674274, 7.429580196496212, 8.343367408419024, 6.623427309782609, 7.580156249999999, 4.740435122282609), # 9
(2.8830723831821286, 7.492178731762065, 8.376213938874606, 6.65066425120773, 7.621794871794872, 4.738375603864734), # 10
(2.9041638437713395, 7.55293304354307, 8.407758385996857, 6.676859525966184, 7.661870993589743, 4.736268531099034), # 11
(2.92476262071993, 7.611762784090908, 8.437969955012854, 6.7019836956521734, 7.700336538461538, 4.734114130434782), # 12
(2.944847844112769, 7.668587605657268, 8.46681785114967, 6.726007321859903, 7.737143429487181, 4.731912628321256), # 13
(2.9643986440347283, 7.723327160493828, 8.494271279634388, 6.748900966183574, 7.772243589743589, 4.729664251207729), # 14
(2.9833941505706756, 7.775901100852272, 8.520299445694086, 6.770635190217391, 7.8055889423076925, 4.7273692255434785), # 15
(3.001813493805482, 7.826229078984287, 8.544871554555842, 6.791180555555555, 7.8371314102564105, 4.725027777777778), # 16
(3.019635803824017, 7.874230747141554, 8.567956811446729, 6.810507623792271, 7.866822916666667, 4.722640134359904), # 17
(3.03684021071115, 7.919825757575757, 8.589524421593831, 6.82858695652174, 7.894615384615387, 4.72020652173913), # 18
(3.053405844551751, 7.962933762538579, 8.609543590224222, 6.845389115338164, 7.9204607371794875, 4.717727166364734), # 19
(3.0693118354306894, 8.003474414281705, 8.62798352256498, 6.860884661835749, 7.944310897435898, 4.71520229468599), # 20
(3.084537313432836, 8.041367365056816, 8.644813423843189, 6.875044157608696, 7.9661177884615375, 4.712632133152174), # 21
(3.099061408643059, 8.076532267115601, 8.660002499285918, 6.887838164251208, 7.985833333333332, 4.710016908212561), # 22
(3.1128632511462295, 8.108888772709737, 8.673519954120252, 6.899237243357488, 8.003409455128205, 4.707356846316426), # 23
(3.125921971027217, 8.138356534090908, 8.685334993573264, 6.909211956521739, 8.018798076923076, 4.704652173913043), # 24
(3.1382166983708903, 8.164855203510802, 8.695416822872037, 6.917732865338165, 8.03195112179487, 4.701903117451691), # 25
(3.1497265632621207, 8.188304433221099, 8.703734647243644, 6.9247705314009655, 8.042820512820512, 4.699109903381642), # 26
(3.160430695785777, 8.208623875473483, 8.710257671915166, 6.930295516304349, 8.051358173076924, 4.696272758152174), # 27
(3.1703082260267292, 8.22573318251964, 8.714955102113683, 6.934278381642512, 8.057516025641025, 4.69339190821256), # 28
(3.1793382840698468, 8.239552006611252, 8.717796143066266, 6.936689689009662, 8.061245993589743, 4.690467580012077), # 29
(3.1875, 8.25, 8.71875, 6.9375, 8.0625, 4.6875), # 30
(3.1951370284526854, 8.258678799715907, 8.718034948671496, 6.937353656045752, 8.062043661347518, 4.683376259786773), # 31
(3.202609175191816, 8.267242897727273, 8.715910024154589, 6.93691748366013, 8.06068439716312, 4.677024758454107), # 32
(3.2099197969948845, 8.275691228693182, 8.712405570652175, 6.936195772058824, 8.058436835106383, 4.66850768365817), # 33
(3.217072250639386, 8.284022727272728, 8.70755193236715, 6.935192810457517, 8.05531560283688, 4.657887223055139), # 34
(3.224069892902813, 8.292236328124998, 8.701379453502415, 6.933912888071895, 8.051335328014185, 4.645225564301183), # 35
(3.23091608056266, 8.300330965909092, 8.69391847826087, 6.932360294117648, 8.046510638297873, 4.630584895052474), # 36
(3.2376141703964194, 8.308305575284091, 8.68519935084541, 6.9305393178104575, 8.040856161347516, 4.614027402965184), # 37
(3.2441675191815853, 8.31615909090909, 8.675252415458937, 6.9284542483660125, 8.034386524822695, 4.595615275695485), # 38
(3.250579483695652, 8.323890447443182, 8.664108016304347, 6.926109375, 8.027116356382978, 4.57541070089955), # 39
(3.2568534207161126, 8.331498579545455, 8.651796497584542, 6.923508986928105, 8.019060283687942, 4.5534758662335495), # 40
(3.26299268702046, 8.338982421874999, 8.638348203502416, 6.920657373366013, 8.010232934397163, 4.529872959353657), # 41
(3.269000639386189, 8.34634090909091, 8.62379347826087, 6.917558823529411, 8.000648936170213, 4.504664167916042), # 42
(3.2748806345907933, 8.353572975852272, 8.608162666062801, 6.914217626633987, 7.990322916666666, 4.477911679576878), # 43
(3.2806360294117645, 8.360677556818182, 8.591486111111111, 6.910638071895424, 7.979269503546099, 4.449677681992337), # 44
(3.286270180626598, 8.367653586647727, 8.573794157608697, 6.906824448529411, 7.967503324468085, 4.420024362818591), # 45
(3.291786445012788, 8.374500000000001, 8.555117149758455, 6.902781045751634, 7.955039007092199, 4.389013909711811), # 46
(3.297188179347826, 8.381215731534091, 8.535485431763284, 6.898512152777777, 7.941891179078015, 4.356708510328169), # 47
(3.3024787404092075, 8.387799715909091, 8.514929347826087, 6.894022058823529, 7.928074468085106, 4.323170352323839), # 48
(3.307661484974424, 8.39425088778409, 8.493479242149759, 6.889315053104576, 7.91360350177305, 4.288461623354989), # 49
(3.312739769820972, 8.40056818181818, 8.471165458937199, 6.884395424836602, 7.898492907801418, 4.252644511077794), # 50
(3.317716951726343, 8.406750532670454, 8.448018342391304, 6.879267463235294, 7.882757313829787, 4.215781203148426), # 51
(3.322596387468031, 8.412796875, 8.424068236714975, 6.87393545751634, 7.86641134751773, 4.177933887223055), # 52
(3.3273814338235295, 8.41870614346591, 8.39934548611111, 6.868403696895425, 7.849469636524823, 4.139164750957854), # 53
(3.332075447570333, 8.424477272727271, 8.373880434782608, 6.8626764705882355, 7.831946808510638, 4.099535982008995), # 54
(3.336681785485933, 8.430109197443182, 8.347703426932366, 6.856758067810458, 7.813857491134752, 4.05910976803265), # 55
(3.341203804347826, 8.435600852272726, 8.320844806763285, 6.8506527777777775, 7.795216312056738, 4.017948296684991), # 56
(3.345644860933504, 8.440951171875001, 8.29333491847826, 6.844364889705882, 7.77603789893617, 3.9761137556221886), # 57
(3.3500083120204605, 8.44615909090909, 8.265204106280192, 6.837898692810458, 7.756336879432624, 3.9336683325004165), # 58
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 59
)
passenger_arriving_acc = (
(3, 12, 4, 1, 1, 0, 2, 7, 5, 7, 0, 0), # 0
(7, 24, 6, 3, 5, 0, 4, 12, 8, 10, 2, 0), # 1
(10, 26, 9, 5, 7, 0, 10, 19, 13, 15, 4, 0), # 2
(11, 36, 13, 7, 8, 0, 16, 24, 14, 19, 5, 0), # 3
(14, 39, 15, 12, 12, 0, 25, 30, 21, 22, 10, 0), # 4
(19, 46, 19, 14, 15, 0, 30, 37, 25, 27, 10, 0), # 5
(21, 55, 23, 15, 17, 0, 37, 42, 30, 31, 10, 0), # 6
(25, 61, 36, 18, 19, 0, 42, 47, 33, 35, 12, 0), # 7
(26, 63, 43, 22, 22, 0, 44, 53, 37, 41, 15, 0), # 8
(30, 70, 48, 24, 25, 0, 48, 55, 41, 47, 15, 0), # 9
(33, 73, 51, 27, 27, 0, 50, 60, 45, 52, 15, 0), # 10
(35, 75, 55, 30, 29, 0, 54, 62, 51, 52, 19, 0), # 11
(38, 85, 62, 30, 31, 0, 56, 67, 54, 53, 23, 0), # 12
(41, 94, 68, 32, 31, 0, 60, 77, 57, 57, 24, 0), # 13
(46, 100, 74, 35, 32, 0, 65, 83, 60, 61, 24, 0), # 14
(47, 107, 82, 36, 35, 0, 68, 89, 64, 65, 25, 0), # 15
(54, 112, 88, 36, 36, 0, 71, 97, 68, 71, 27, 0), # 16
(54, 116, 93, 39, 40, 0, 75, 103, 74, 74, 30, 0), # 17
(60, 124, 99, 42, 41, 0, 80, 105, 80, 75, 31, 0), # 18
(63, 132, 107, 44, 43, 0, 85, 112, 89, 77, 31, 0), # 19
(66, 137, 113, 48, 45, 0, 93, 120, 93, 80, 33, 0), # 20
(72, 146, 117, 49, 48, 0, 100, 128, 97, 82, 36, 0), # 21
(75, 150, 121, 52, 51, 0, 103, 139, 100, 85, 37, 0), # 22
(78, 158, 124, 54, 51, 0, 107, 143, 104, 89, 39, 0), # 23
(80, 163, 131, 59, 53, 0, 110, 152, 110, 93, 41, 0), # 24
(83, 170, 134, 61, 54, 0, 114, 163, 113, 98, 43, 0), # 25
(83, 182, 139, 61, 56, 0, 117, 169, 117, 100, 45, 0), # 26
(87, 189, 144, 62, 58, 0, 121, 174, 123, 101, 50, 0), # 27
(91, 192, 150, 63, 59, 0, 125, 178, 127, 106, 53, 0), # 28
(92, 200, 156, 66, 62, 0, 129, 183, 132, 112, 54, 0), # 29
(97, 204, 160, 66, 63, 0, 132, 188, 137, 120, 56, 0), # 30
(101, 210, 165, 70, 63, 0, 137, 192, 140, 121, 57, 0), # 31
(105, 220, 169, 72, 63, 0, 140, 194, 147, 127, 58, 0), # 32
(108, 224, 173, 74, 67, 0, 146, 199, 150, 130, 59, 0), # 33
(115, 227, 175, 76, 69, 0, 150, 206, 153, 135, 59, 0), # 34
(120, 235, 181, 79, 72, 0, 157, 213, 156, 139, 59, 0), # 35
(122, 243, 184, 80, 72, 0, 163, 217, 159, 142, 62, 0), # 36
(128, 251, 190, 82, 73, 0, 171, 224, 167, 142, 65, 0), # 37
(128, 257, 194, 87, 73, 0, 173, 231, 170, 144, 67, 0), # 38
(132, 259, 197, 90, 74, 0, 179, 239, 177, 147, 67, 0), # 39
(135, 264, 199, 93, 75, 0, 184, 242, 187, 151, 70, 0), # 40
(141, 269, 206, 95, 75, 0, 190, 246, 188, 155, 74, 0), # 41
(148, 277, 211, 100, 75, 0, 194, 259, 189, 158, 75, 0), # 42
(151, 287, 219, 102, 77, 0, 202, 263, 198, 162, 79, 0), # 43
(155, 293, 226, 106, 77, 0, 210, 270, 202, 162, 79, 0), # 44
(158, 300, 233, 108, 79, 0, 219, 276, 206, 164, 80, 0), # 45
(160, 314, 238, 110, 81, 0, 222, 284, 207, 165, 82, 0), # 46
(168, 318, 240, 111, 83, 0, 230, 290, 209, 168, 82, 0), # 47
(172, 323, 246, 112, 83, 0, 235, 297, 212, 170, 83, 0), # 48
(176, 327, 249, 113, 84, 0, 238, 302, 214, 176, 85, 0), # 49
(177, 336, 254, 119, 84, 0, 245, 307, 219, 177, 87, 0), # 50
(182, 339, 260, 121, 85, 0, 253, 310, 225, 180, 88, 0), # 51
(184, 347, 266, 130, 86, 0, 265, 311, 233, 183, 90, 0), # 52
(188, 355, 273, 133, 86, 0, 273, 319, 238, 187, 90, 0), # 53
(193, 362, 275, 134, 86, 0, 277, 327, 238, 192, 92, 0), # 54
(194, 371, 284, 137, 86, 0, 279, 336, 242, 199, 93, 0), # 55
(196, 379, 290, 140, 90, 0, 282, 347, 247, 203, 96, 0), # 56
(202, 384, 293, 142, 91, 0, 287, 353, 251, 204, 98, 0), # 57
(205, 390, 299, 145, 93, 0, 290, 356, 255, 208, 100, 0), # 58
(205, 390, 299, 145, 93, 0, 290, 356, 255, 208, 100, 0), # 59
)
passenger_arriving_rate = (
(2.649651558384548, 5.43716856060606, 4.79654161311054, 2.534510869565217, 1.428605769230769, 0.0, 4.75679347826087, 5.714423076923076, 3.801766304347826, 3.1976944087403596, 1.359292140151515, 0.0), # 0
(2.6745220100478, 5.497633278970258, 4.822449322514997, 2.5486257548309177, 1.439313301282051, 0.0, 4.7551721391908215, 5.757253205128204, 3.8229386322463768, 3.2149662150099974, 1.3744083197425645, 0.0), # 1
(2.699108477221734, 5.557201122334455, 4.8477420736932295, 2.562429951690821, 1.4497948717948717, 0.0, 4.753501207729468, 5.799179487179487, 3.8436449275362317, 3.23182804912882, 1.3893002805836137, 0.0), # 2
(2.72339008999122, 5.6158078125, 4.872401389781491, 2.575911684782608, 1.4600408653846155, 0.0, 4.7517809103260875, 5.840163461538462, 3.863867527173912, 3.2482675931876606, 1.403951953125, 0.0), # 3
(2.747345978441128, 5.673389071268238, 4.896408793916024, 2.589059178743961, 1.4700416666666667, 0.0, 4.750011473429951, 5.880166666666667, 3.883588768115942, 3.2642725292773487, 1.4183472678170594, 0.0), # 4
(2.7709552726563262, 5.729880620440516, 4.919745809233076, 2.6018606582125603, 1.47978766025641, 0.0, 4.748193123490338, 5.91915064102564, 3.9027909873188404, 3.279830539488717, 1.432470155110129, 0.0), # 5
(2.794197102721686, 5.785218181818181, 4.942393958868895, 2.614304347826087, 1.4892692307692306, 0.0, 4.746326086956522, 5.957076923076922, 3.9214565217391306, 3.294929305912597, 1.4463045454545453, 0.0), # 6
(2.817050598722076, 5.83933747720258, 4.964334765959725, 2.626378472222222, 1.498476762820513, 0.0, 4.744410590277778, 5.993907051282052, 3.939567708333333, 3.309556510639817, 1.459834369300645, 0.0), # 7
(2.8394948907423667, 5.89217422839506, 4.985549753641817, 2.638071256038647, 1.5074006410256409, 0.0, 4.7424468599033816, 6.0296025641025635, 3.9571068840579704, 3.3236998357612113, 1.473043557098765, 0.0), # 8
(2.8615091088674274, 5.943664157196969, 5.006020445051414, 2.649370923913043, 1.5160312499999997, 0.0, 4.740435122282609, 6.064124999999999, 3.9740563858695652, 3.3373469633676094, 1.4859160392992423, 0.0), # 9
(2.8830723831821286, 5.993742985409652, 5.025728363324764, 2.660265700483092, 1.5243589743589743, 0.0, 4.738375603864734, 6.097435897435897, 3.990398550724638, 3.3504855755498424, 1.498435746352413, 0.0), # 10
(2.9041638437713395, 6.042346434834456, 5.044655031598114, 2.6707438103864733, 1.5323741987179484, 0.0, 4.736268531099034, 6.129496794871794, 4.0061157155797105, 3.3631033543987425, 1.510586608708614, 0.0), # 11
(2.92476262071993, 6.089410227272726, 5.062781973007712, 2.680793478260869, 1.5400673076923075, 0.0, 4.734114130434782, 6.16026923076923, 4.021190217391304, 3.375187982005141, 1.5223525568181815, 0.0), # 12
(2.944847844112769, 6.134870084525814, 5.080090710689802, 2.690402928743961, 1.547428685897436, 0.0, 4.731912628321256, 6.189714743589744, 4.035604393115942, 3.386727140459868, 1.5337175211314535, 0.0), # 13
(2.9643986440347283, 6.1786617283950624, 5.096562767780632, 2.699560386473429, 1.5544487179487176, 0.0, 4.729664251207729, 6.217794871794871, 4.049340579710144, 3.397708511853755, 1.5446654320987656, 0.0), # 14
(2.9833941505706756, 6.220720880681816, 5.112179667416451, 2.708254076086956, 1.5611177884615384, 0.0, 4.7273692255434785, 6.2444711538461535, 4.062381114130434, 3.408119778277634, 1.555180220170454, 0.0), # 15
(3.001813493805482, 6.26098326318743, 5.126922932733505, 2.716472222222222, 1.5674262820512819, 0.0, 4.725027777777778, 6.2697051282051275, 4.074708333333333, 3.4179486218223363, 1.5652458157968574, 0.0), # 16
(3.019635803824017, 6.299384597713242, 5.140774086868038, 2.724203049516908, 1.5733645833333332, 0.0, 4.722640134359904, 6.293458333333333, 4.0863045742753625, 3.4271827245786914, 1.5748461494283106, 0.0), # 17
(3.03684021071115, 6.3358606060606055, 5.153714652956299, 2.7314347826086958, 1.578923076923077, 0.0, 4.72020652173913, 6.315692307692308, 4.097152173913043, 3.435809768637532, 1.5839651515151514, 0.0), # 18
(3.053405844551751, 6.370347010030863, 5.165726154134533, 2.738155646135265, 1.5840921474358973, 0.0, 4.717727166364734, 6.336368589743589, 4.107233469202898, 3.4438174360896885, 1.5925867525077158, 0.0), # 19
(3.0693118354306894, 6.402779531425363, 5.1767901135389875, 2.7443538647342995, 1.5888621794871793, 0.0, 4.71520229468599, 6.355448717948717, 4.11653079710145, 3.4511934090259917, 1.6006948828563408, 0.0), # 20
(3.084537313432836, 6.433093892045452, 5.186888054305913, 2.750017663043478, 1.5932235576923073, 0.0, 4.712632133152174, 6.372894230769229, 4.125026494565217, 3.4579253695372754, 1.608273473011363, 0.0), # 21
(3.099061408643059, 6.46122581369248, 5.19600149957155, 2.7551352657004826, 1.5971666666666662, 0.0, 4.710016908212561, 6.388666666666665, 4.132702898550725, 3.464000999714367, 1.61530645342312, 0.0), # 22
(3.1128632511462295, 6.487111018167789, 5.204111972472151, 2.759694897342995, 1.6006818910256408, 0.0, 4.707356846316426, 6.402727564102563, 4.139542346014493, 3.4694079816481005, 1.6217777545419472, 0.0), # 23
(3.125921971027217, 6.5106852272727265, 5.211200996143958, 2.763684782608695, 1.6037596153846152, 0.0, 4.704652173913043, 6.415038461538461, 4.1455271739130435, 3.474133997429305, 1.6276713068181816, 0.0), # 24
(3.1382166983708903, 6.531884162808641, 5.217250093723222, 2.7670931461352657, 1.606390224358974, 0.0, 4.701903117451691, 6.425560897435896, 4.150639719202899, 3.4781667291488145, 1.6329710407021603, 0.0), # 25
(3.1497265632621207, 6.550643546576878, 5.222240788346187, 2.7699082125603858, 1.6085641025641022, 0.0, 4.699109903381642, 6.434256410256409, 4.154862318840579, 3.4814938588974575, 1.6376608866442195, 0.0), # 26
(3.160430695785777, 6.566899100378786, 5.226154603149099, 2.772118206521739, 1.6102716346153847, 0.0, 4.696272758152174, 6.441086538461539, 4.158177309782609, 3.484103068766066, 1.6417247750946966, 0.0), # 27
(3.1703082260267292, 6.580586546015712, 5.228973061268209, 2.7737113526570045, 1.6115032051282048, 0.0, 4.69339190821256, 6.446012820512819, 4.160567028985507, 3.4859820408454727, 1.645146636503928, 0.0), # 28
(3.1793382840698468, 6.591641605289001, 5.230677685839759, 2.7746758756038647, 1.6122491987179486, 0.0, 4.690467580012077, 6.448996794871794, 4.162013813405797, 3.487118457226506, 1.6479104013222503, 0.0), # 29
(3.1875, 6.6, 5.23125, 2.775, 1.6124999999999998, 0.0, 4.6875, 6.449999999999999, 4.1625, 3.4875, 1.65, 0.0), # 30
(3.1951370284526854, 6.606943039772726, 5.230820969202898, 2.7749414624183006, 1.6124087322695035, 0.0, 4.683376259786773, 6.449634929078014, 4.162412193627451, 3.4872139794685983, 1.6517357599431814, 0.0), # 31
(3.202609175191816, 6.613794318181818, 5.229546014492753, 2.7747669934640515, 1.6121368794326238, 0.0, 4.677024758454107, 6.448547517730495, 4.162150490196078, 3.4863640096618354, 1.6534485795454545, 0.0), # 32
(3.2099197969948845, 6.620552982954545, 5.227443342391305, 2.774478308823529, 1.6116873670212764, 0.0, 4.66850768365817, 6.446749468085105, 4.161717463235294, 3.4849622282608697, 1.6551382457386363, 0.0), # 33
(3.217072250639386, 6.627218181818182, 5.224531159420289, 2.7740771241830067, 1.6110631205673758, 0.0, 4.657887223055139, 6.444252482269503, 4.16111568627451, 3.4830207729468596, 1.6568045454545455, 0.0), # 34
(3.224069892902813, 6.633789062499998, 5.220827672101449, 2.773565155228758, 1.6102670656028368, 0.0, 4.645225564301183, 6.441068262411347, 4.160347732843137, 3.480551781400966, 1.6584472656249996, 0.0), # 35
(3.23091608056266, 6.6402647727272734, 5.2163510869565215, 2.7729441176470586, 1.6093021276595745, 0.0, 4.630584895052474, 6.437208510638298, 4.159416176470589, 3.477567391304347, 1.6600661931818184, 0.0), # 36
(3.2376141703964194, 6.6466444602272725, 5.211119610507246, 2.7722157271241827, 1.6081712322695032, 0.0, 4.614027402965184, 6.432684929078013, 4.158323590686274, 3.474079740338164, 1.6616611150568181, 0.0), # 37
(3.2441675191815853, 6.652927272727272, 5.205151449275362, 2.7713816993464047, 1.6068773049645388, 0.0, 4.595615275695485, 6.427509219858155, 4.157072549019607, 3.4701009661835744, 1.663231818181818, 0.0), # 38
(3.250579483695652, 6.659112357954545, 5.198464809782608, 2.7704437499999996, 1.6054232712765955, 0.0, 4.57541070089955, 6.421693085106382, 4.155665625, 3.4656432065217384, 1.6647780894886361, 0.0), # 39
(3.2568534207161126, 6.6651988636363635, 5.191077898550724, 2.7694035947712417, 1.6038120567375882, 0.0, 4.5534758662335495, 6.415248226950353, 4.154105392156863, 3.4607185990338163, 1.6662997159090909, 0.0), # 40
(3.26299268702046, 6.671185937499998, 5.1830089221014495, 2.768262949346405, 1.6020465868794325, 0.0, 4.529872959353657, 6.40818634751773, 4.152394424019608, 3.455339281400966, 1.6677964843749995, 0.0), # 41
(3.269000639386189, 6.677072727272728, 5.174276086956522, 2.767023529411764, 1.6001297872340425, 0.0, 4.504664167916042, 6.40051914893617, 4.150535294117646, 3.4495173913043478, 1.669268181818182, 0.0), # 42
(3.2748806345907933, 6.682858380681817, 5.164897599637681, 2.7656870506535944, 1.5980645833333331, 0.0, 4.477911679576878, 6.3922583333333325, 4.148530575980392, 3.4432650664251203, 1.6707145951704543, 0.0), # 43
(3.2806360294117645, 6.688542045454545, 5.154891666666667, 2.7642552287581696, 1.5958539007092198, 0.0, 4.449677681992337, 6.383415602836879, 4.146382843137254, 3.4365944444444443, 1.6721355113636363, 0.0), # 44
(3.286270180626598, 6.694122869318181, 5.144276494565218, 2.7627297794117642, 1.593500664893617, 0.0, 4.420024362818591, 6.374002659574468, 4.144094669117647, 3.4295176630434785, 1.6735307173295453, 0.0), # 45
(3.291786445012788, 6.6996, 5.133070289855073, 2.761112418300653, 1.5910078014184397, 0.0, 4.389013909711811, 6.364031205673759, 4.14166862745098, 3.4220468599033818, 1.6749, 0.0), # 46
(3.297188179347826, 6.704972585227273, 5.12129125905797, 2.759404861111111, 1.588378235815603, 0.0, 4.356708510328169, 6.353512943262412, 4.139107291666666, 3.4141941727053133, 1.6762431463068181, 0.0), # 47
(3.3024787404092075, 6.710239772727273, 5.108957608695651, 2.757608823529411, 1.5856148936170211, 0.0, 4.323170352323839, 6.3424595744680845, 4.136413235294117, 3.4059717391304343, 1.6775599431818182, 0.0), # 48
(3.307661484974424, 6.715400710227271, 5.096087545289855, 2.75572602124183, 1.5827207003546098, 0.0, 4.288461623354989, 6.330882801418439, 4.133589031862745, 3.3973916968599034, 1.6788501775568176, 0.0), # 49
(3.312739769820972, 6.720454545454543, 5.082699275362319, 2.7537581699346405, 1.5796985815602835, 0.0, 4.252644511077794, 6.318794326241134, 4.130637254901961, 3.388466183574879, 1.6801136363636358, 0.0), # 50
(3.317716951726343, 6.725400426136363, 5.068811005434783, 2.7517069852941174, 1.5765514627659571, 0.0, 4.215781203148426, 6.306205851063829, 4.127560477941176, 3.3792073369565214, 1.6813501065340908, 0.0), # 51
(3.322596387468031, 6.730237499999999, 5.054440942028985, 2.7495741830065357, 1.573282269503546, 0.0, 4.177933887223055, 6.293129078014184, 4.124361274509804, 3.3696272946859898, 1.6825593749999999, 0.0), # 52
(3.3273814338235295, 6.7349649147727275, 5.039607291666666, 2.7473614787581697, 1.5698939273049646, 0.0, 4.139164750957854, 6.279575709219858, 4.121042218137255, 3.359738194444444, 1.6837412286931819, 0.0), # 53
(3.332075447570333, 6.739581818181817, 5.024328260869565, 2.745070588235294, 1.5663893617021276, 0.0, 4.099535982008995, 6.2655574468085105, 4.117605882352941, 3.3495521739130427, 1.6848954545454542, 0.0), # 54
(3.336681785485933, 6.744087357954545, 5.008622056159419, 2.7427032271241827, 1.5627714982269503, 0.0, 4.05910976803265, 6.251085992907801, 4.114054840686275, 3.3390813707729463, 1.6860218394886362, 0.0), # 55
(3.341203804347826, 6.74848068181818, 4.9925068840579705, 2.740261111111111, 1.5590432624113475, 0.0, 4.017948296684991, 6.23617304964539, 4.110391666666667, 3.328337922705314, 1.687120170454545, 0.0), # 56
(3.345644860933504, 6.752760937500001, 4.976000951086956, 2.7377459558823527, 1.5552075797872338, 0.0, 3.9761137556221886, 6.220830319148935, 4.106618933823529, 3.317333967391304, 1.6881902343750002, 0.0), # 57
(3.3500083120204605, 6.756927272727271, 4.959122463768115, 2.7351594771241827, 1.5512673758865245, 0.0, 3.9336683325004165, 6.205069503546098, 4.102739215686275, 3.3060816425120767, 1.6892318181818178, 0.0), # 58
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 59
)
passenger_allighting_rate = (
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 0
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 1
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 2
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 3
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 4
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 5
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 6
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 7
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 8
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 9
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 10
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 11
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 12
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 13
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 14
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 15
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 16
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 17
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 18
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 19
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 20
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 21
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 22
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 23
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 24
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 25
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 26
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 27
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 28
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 29
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 30
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 31
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 32
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 33
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 34
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 35
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 36
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 37
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 38
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 39
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 40
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 41
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 42
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 43
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 44
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 45
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 46
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 47
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 48
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 49
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 50
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 51
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 52
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 53
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 54
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 55
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 56
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 57
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 58
(0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1, 0, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 1), # 59
)
"""
parameters for reproducibiliy. More information: https://numpy.org/doc/stable/reference/random/parallel.html
"""
#initial entropy
entropy = 258194110137029475889902652135037600173
#index for seed sequence child
child_seed_index = (
1, # 0
38, # 1
)
|
"""
Project Euler Problem 12: Highly divisible triangular number
"""
# What is the value of the first triangle number to have over five hundred divisors?
# A simple solution is to not worry about generating primes, and just test odd numbers for divisors
# Since we have to test a lot of numbers, it probably is worth generating a list of primes
START = 1
number_divisors = 0
i = 0
while number_divisors < 500:
i += 1
powers = []
tri_number = (START+i)*(START+i+1)/2
power = 0
while tri_number % 2 == 0:
power += 1
tri_number /= 2
if power > 0:
powers.append(power)
factor = 3
while tri_number > 1:
power = 0
while tri_number % factor == 0:
power += 1
tri_number /= factor
factor += 2
if power > 0:
powers.append(power)
number_divisors = 1
for p in powers:
number_divisors *= p + 1
print((START+i)*(START+i+1)//2)
|
#
"""Make a function map that works the same way as the built-in map function:"""
def square(n):
return n * n
def map(square, list1):
return [ square(num) for num in list1 ]
|
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def check(s, t):
word_map = {}
for i, v in enumerate(s):
tmp = word_map.get(t[i])
if tmp is None:
word_map[t[i]] = s[i]
tmp = s[i]
t = t[:i] + tmp + t[i + 1:]
return s == t
return check(s, t) and check(t, s)
s = 'title'
t = 'paper'
# t = 'title'
# s = 'paler'
print(Solution().isIsomorphic(s, t))
|
num = [[], []]
for c in range(0, 7):
n = (int(input(f'Digite o {c + 1}° valor: ')))
if n % 2 == 0:
num[0].append(n)
else:
num[1].append(n)
print('-=' * 24)
num[0].sort()
num[1].sort()
print(f'Os valores pares digitados foram: {num[0]}')
print(f'Os valores ímpares digitados foram: {num[1]}')
|
class Docs:
helps = """
:shrimp:새우 봇의 명령어 입니다!
새우야 도움말 <명령어>로 상세히 볼 수 있습니다!
**새우야**
새우 봇이 온라인인지 확인합니다!
**도움말**
새우 봇의 명령어를 알려줍니다!
**밥**
GSM의 급식을 알려줍니다!
**초대**
새우 봇을 초대할 수 있는 링크를 줍니다!
**커스텀**
새우 봇에게 새로운 명령어를 추가합니다!
**통계**
이 서버 내에서 새우 봇에게 내렸던 명령들의 횟수를 보여줍니다!
"""
ping = """
새우 봇이 온라인인지 확인합니다!
그리고 반갑게 인사:wave: 해줍니다!
사용법 예시: `새우야`, `ㅎㅇ`, `안녕`
"""
help = """
새우 봇의 명령어를 알려줍니다!
새우야 도움말 <명령어>를 통해 상세히 볼 수 있습니다!
사용법 예시: `새우야 도움말`, `새우야 명령어`, `새우야 help`
"""
hungry = """
GSM의 급식을 알려줍니다!
앞에 새우야를 붙이지 않아도 작동합니다! (밥은 예외)
사용법 예시: `새우야 밥`, `새우야 배고파`, `qorhvk`, `헝그리`
"""
invite_link = """
새우 봇을 초대할 수 있는 링크를 줍니다!
새우 봇은 15초후 초대 링크를 가지고 달아납니다!
사용법 예시: `새우야 초대`
"""
custom = """
새우 봇에게 새로운 명령어를 추가합니다!
`새우야 커맨드 추가 <명령어> <대답할 메시지>`를 통해 추가합니다!
`새우야 커맨드 삭제 <명령어>`를 통해 등록된 명령어를 모두 삭제합니다!
`새우야 커맨드 목록`은 서버에 등록된 명령어를 알려줍니다!
사용법 예시: `새커추 새우 새우는 맛있어!`, `새커삭 새우`, `새커목`
"""
statistic = """
이 서버 내에서 새우 봇에게 내렸던 명령들의 횟수를 보여줍니다!
사용법 예시: `새우야 통계`
"""
|
# -*- coding: utf-8 -*-
# see LICENSE.rst
# ----------------------------------------------------------------------------
#
# TITLE : data
# PROJECT : astronat
#
# ----------------------------------------------------------------------------
"""Data Management.
Often data is packaged poorly and it can be difficult to understand how
the data should be read.
DON`T PANIC.
This module provides functions to read the contained data.
Routine Listings
----------------
read_constants
__all_constants__
"""
__author__ = "Nathaniel Starkman"
__all__ = [
"read_constants",
"__all_constants__",
]
###############################################################################
# IMPORTS
###############################################################################
# CODE
###############################################################################
def read_constants():
"""Read SI Constants."""
data = {
"G": {
"name": "Gravitational constant",
"value": 6.6743e-11,
"uncertainty": 1.5e-15,
"unit": "m3 / (kg s2)",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"N_A": {
"name": "Avogadro's number",
"value": 6.02214076e23,
"uncertainty": 0.0,
"unit": "1 / mol",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"R": {
"name": "Gas constant",
"value": 8.31446261815324,
"uncertainty": 0.0,
"unit": "J / (K mol)",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"Ryd": {
"name": "Rydberg constant",
"value": 10973731.56816,
"uncertainty": 2.1e-05,
"unit": "1 / m",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"a0": {
"name": "Bohr radius",
"value": 5.29177210903e-11,
"uncertainty": 8e-21,
"unit": "m",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"alpha": {
"name": "Fine-structure constant",
"value": 0.0072973525693,
"uncertainty": 1.1e-12,
"unit": "",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"atm": {
"name": "Standard atmosphere",
"value": 101325,
"uncertainty": 0.0,
"unit": "Pa",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"b_wien": {
"name": "Wien wavelength displacement law constant",
"value": 0.0028977719551851727,
"uncertainty": 0.0,
"unit": "K m",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"c": {
"name": "Speed of light in vacuum",
"value": 299792458.0,
"uncertainty": 0.0,
"unit": "m / s",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"e": {
"name": "Electron charge",
"value": 1.602176634e-19,
"uncertainty": 0.0,
"unit": "C",
"source": "EMCODATA2018",
},
"eps0": {
"name": "Vacuum electric permittivity",
"value": 8.8541878128e-12,
"uncertainty": 1.3e-21,
"unit": "F / m",
"reference": "CODATA 2018",
"source": "EMCODATA2018",
},
"g0": {
"name": "Standard acceleration of gravity",
"value": 9.80665,
"uncertainty": 0.0,
"unit": "m / s2",
"source": "CODATA2018",
},
"h": {
"name": "Planck constant",
"value": 6.62607015e-34,
"uncertainty": 0.0,
"unit": "J s",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"hbar": {
"name": "Reduced Planck constant",
"value": 1.0545718176461565e-34,
"uncertainty": 0.0,
"unit": "J s",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"k_B": {
"name": "Boltzmann constant",
"value": 1.380649e-23,
"uncertainty": 0.0,
"unit": "J / K",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"m_e": {
"name": "Electron mass",
"value": 9.1093837015e-31,
"uncertainty": 2.8e-40,
"unit": "kg",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"m_n": {
"name": "Neutron mass",
"value": 1.67492749804e-27,
"uncertainty": 9.5e-37,
"unit": "kg",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"m_p": {
"name": "Proton mass",
"value": 1.67262192369e-27,
"uncertainty": 5.1e-37,
"unit": "kg",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"mu0": {
"name": "Vacuum magnetic permeability",
"value": 1.25663706212e-06,
"uncertainty": 1.9e-16,
"unit": "N / A2",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"muB": {
"name": "Bohr magneton",
"value": 9.2740100783e-24,
"uncertainty": 2.8e-33,
"unit": "J / T",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"sigma_T": {
"name": "Thomson scattering cross-section",
"value": 6.6524587321e-29,
"uncertainty": 6e-38,
"unit": "m2",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"sigma_sb": {
"name": "Stefan-Boltzmann constant",
"value": 5.6703744191844314e-08,
"uncertainty": 0.0,
"unit": "W / (K4 m2)",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"u": {
"name": "Atomic mass",
"value": 1.6605390666e-27,
"uncertainty": 5e-37,
"unit": "kg",
"reference": "CODATA 2018",
"source": "CODATA2018",
},
"GM_earth": {
"name": "Nominal Earth mass parameter",
"value": 398600400000000.0,
"uncertainty": 0.0,
"unit": "m3 / s2",
"source": "IAU2015",
},
"GM_jup": {
"name": "Nominal Jupiter mass parameter",
"value": 1.2668653e17,
"uncertainty": 0.0,
"unit": "m3 / s2",
"source": "IAU2015",
},
"GM_sun": {
"name": "Nominal solar mass parameter",
"value": 1.3271244e20,
"uncertainty": 0.0,
"unit": "m3 / s2",
"source": "IAU2015",
},
"L_bol0": {
"name": "Luminosity for absolute bolometric magnitude 0",
"value": 3.0128e28,
"uncertainty": 0.0,
"unit": "W",
"source": "IAU2015",
},
"L_sun": {
"name": "Nominal solar luminosity",
"value": 3.828e26,
"uncertainty": 0.0,
"unit": "W",
"reference": "IAU 2015 Resolution B 3",
"source": "IAU2015",
},
"M_earth": {
"name": "Earth mass",
"value": 5.972167867791379e24,
"uncertainty": 1.3422009501651213e20,
"unit": "kg",
"reference": "IAU 2015 Resolution B 3 + CODATA 2018",
"source": "IAU2015",
},
"M_jup": {
"name": "Jupiter mass",
"value": 1.8981245973360505e27,
"uncertainty": 4.26589589320839e22,
"unit": "kg",
"reference": "IAU 2015 Resolution B 3 + CODATA 2018",
"source": "IAU2015",
},
"M_sun": {
"name": "Solar mass",
"value": 1.988409870698051e30,
"uncertainty": 4.468805426856864e25,
"unit": "kg",
"reference": "IAU 2015 Resolution B 3 + CODATA 2018",
"source": "IAU2015",
},
"R_earth": {
"name": "Nominal Earth equatorial radius",
"value": 6378100.0,
"uncertainty": 0.0,
"unit": "m",
"reference": "IAU 2015 Resolution B 3",
"source": "IAU2015",
},
"R_jup": {
"name": "Nominal Jupiter equatorial radius",
"value": 71492000.0,
"uncertainty": 0.0,
"unit": "m",
"reference": "IAU 2015 Resolution B 3",
"source": "IAU2015",
},
"R_sun": {
"name": "Nominal solar radius",
"value": 695700000.0,
"uncertainty": 0.0,
"unit": "m",
"reference": "IAU 2015 Resolution B 3",
"source": "IAU2015",
},
"au": {
"name": "Astronomical Unit",
"value": 149597870700.0,
"uncertainty": 0.0,
"unit": "m",
"reference": "IAU 2012 Resolution B2",
"source": "IAU2015",
},
"kpc": {
"name": "Kiloparsec",
"value": 3.0856775814671917e19,
"uncertainty": 0.0,
"unit": "m",
"reference": "Derived from au",
"source": "IAU2015",
},
"pc": {
"name": "Parsec",
"value": 3.0856775814671916e16,
"uncertainty": 0.0,
"unit": "m",
"reference": "Derived from au",
"source": "IAU2015",
},
}
return data
# /def
# ------------------------------------------------------------------------
__all_constants__ = frozenset(read_constants().keys())
###############################################################################
# END
|
def constrict(maxc,minc,dell):
# Garante que as coordenadas de dell estão dentro dos limites
#
# next = constrict(maxc,minc,dell)
#
# next: vetor avaliado (com coordenadas dentro dos limites)
# maxc: valor máximo das coordenadas
# minc: valor mímimo das coordenadas
# dell: vetor a ser avaliado
for i in range(len(maxc)):
if dell[i]>maxc[i]:
dell[i]=maxc[i]
if dell[i]<minc[i]:
dell[i]=minc[i]
next = dell
return next
|
#Esta es la respuesta del control
def sumarLista(lista, largo):
if (largo == 0):
return 0
else:
return lista[largo - 1] + sumarLista(lista, largo - 1)
def Desglosar(numero:int,lista=[]):
def rev(l):
if len(l) == 0: return []
return [l[-1]] + rev(l[:-1])
if numero==0:
reversa=rev(lista)
return reversa
else:
lista.append(numero)
return Desglosar(numero-1,lista)
def combinar(lista, contador = 0, listaaux = []):
if contador == len(lista):
return [listaaux]
x = combinar(lista, contador + 1, listaaux)
y = combinar(lista, contador + 1, listaaux + [lista[contador]])
return x + y
n=int(input("Ingrese N:"))
k=int(input("Ingrese K:"))
if n<1 or k<1:
print("Debe ser un valor entero positivo")
else:
desglosar=Desglosar(n)
combinar=combinar(desglosar)
contador=0
while contador < len(combinar):
if sumarLista(combinar[contador], len(combinar[contador])) == k:
print(*combinar[contador])
contador = contador + 1
|
# Utility functions for incrementing counts in dictionaries or appending to a list of values
def add_to_dict_num(D, k, v=1):
if k in D:
D[k] += v
else:
D[k] = v
def add_to_dict_list(D, k, v):
if k in D:
D[k].append(v)
else:
D[k] = [v]
def report(min_verbosity, *args):
if report.verbosity >= min_verbosity:
print(f'[{report.context}]', *args)
|
s = input()
sort_s = sorted(s)
print(sort_s)
# str型の文字列を直接sorted()に入れると
# str型の文字列を1文字ずつに分割したlist型として認識して
# それをソートしたlist型を取得できる。
|
# coding=utf-8
#
# @lc app=leetcode id=821 lang=python
#
# [821] Shortest Distance to a Character
#
# https://leetcode.com/problems/shortest-distance-to-a-character/description/
#
# algorithms
# Easy (62.75%)
# Likes: 658
# Dislikes: 57
# Total Accepted: 42K
# Total Submissions: 65.7K
# Testcase Example: '"loveleetcode"\n"e"'
#
# Given a string S and a character C, return an array of integers representing
# the shortest distance from the character C in the string.
#
# Example 1:
#
#
# Input: S = "loveleetcode", C = 'e'
# Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
#
#
#
#
# Note:
#
#
# S string length is in [1, 10000].
# C is a single character, and guaranteed to be in string S.
# All letters in S and C are lowercase.
#
#
#
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
cp = []
for i, s in enumerate(S):
if s == C:
cp.append(i)
result = []
for i, s in enumerate(S):
result.append(min(map(lambda x: abs(i-x), cp)))
return result
|
'''
Created on Mar 19, 2022
@author: mballance
'''
class ActivityBlockMetaT(type):
def __init__(self, name, bases, dct):
pass
def __enter__(self):
print("ActivityBlockMetaT.__enter__")
def __exit__(self, t, v, tb):
pass
|
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2020-01-14 00:47
# @Author : Fabrice LI
# @File : 20200113_667_longest_palindromic_subsequence.py
# @User : liyihao
# @Software : PyCharm
# @Description: Given a string s, find the longest palindromic subsequence's length in s.
# You may assume that the maximum length of s is 1000.
#Reference:**********************************************
"""
Input: "bbbab"
Output: 4
Explanation:
One possible longest palindromic subsequence is "bbbb".
Input: "bbbbb"
Output: 5
"""
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
if not s:
return 0
if len(s) == 1:
return 1
size = len(s)
dp = [[0 for _ in range(size)] for _ in range(size)]
for i in range(size - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, size):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return max(dp[0])
if __name__ == '__main__':
s = Solution()
st = 'b'
print(s.longestPalindromeSubseq(st))
|
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
if len(s)==0:
return s
s = list(s)
def flip(s,start,end):
for i in range(start,(start+end)//2 + 1):
s[i],s[end-i+start] = s[end - i+start],s[i]
return s
n %= len(s)
s = flip(s,0,n-1)
s = flip(s,n,len(s)-1)
s = flip(s,0,len(s)-1)
return "".join(s)
|
list1=[1,2,3,5,7,12,19] #数字列表
list2=['strawberry','watermelon','mango'] #字符串列表
student=['55122005100','李明','男',19] #学生列表
print(student)
list4=[i for i in range(1,20,2)] #list4是1到19的奇数
print(list4)
#向列表中添加元素
list3=list1+list2 #列表合并(连接)
print(list3)
list1.append(31) #在list1中朝最后一个位置添加元素
print(list1)
list1.insert(1,2) #在list1中朝下标为1的位置添加元素2
print(list1)
#删除列表中的元素
list2.pop(2) #删除list2中下标为2的元素
list2.remove('watermelon') #去除list2中的'watermelon'元素
print(list2)
#del list2
print(list2)
#修改列表中的元素
student[2]='女'
print(student)
student[1:3]=['李华','男','18']
print(student)
student[1::]=['李丽'] #原列表未被取代的元素都会被删掉
print(student)
student[1::]=['李刚','男','20'] #多个元素会延长列表长度
print(student)
#取最大、最小值和平均值
#方法一:用max、min
print(max(list1))
print(min(list1))
#方法二:用循环实现
ma=list1[0]
mi=list1[0]
average=0
sum=0
for k in list1:
if ma<k:
ma=k
if mi>k:
mi=k
sum+=k
average=sum/len(list1)
print(ma)
print(mi)
print(average)
|
'''
question link- https://leetcode.com/problems/sum-of-all-subset-xor-totals/
Sum of All Subset XOR Totals
Question statement:
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.
For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.
'''
def subsetXORSum(self, nums):
l = len(nums)
res = 0
stack = [(0, 0)]
while stack:
pos, xor = stack.pop()
res+=xor
for i in range(pos, l):
stack.append((i+1, xor^nums[i]))
return res
|
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
ans = [1]*n
for i in range(1,m):
for j in range(1,n):
ans[j] = ans[j-1] + ans[j]
return ans[-1] if m and n else 0
|
'''
Write a Python program to compute the sum of all items of a
given array of integers where each integer is multiplied by its
index. Return 0 if there is no number.
Sample Input:
[1,2,3,4]
[-1,-2,-3,-4]
[]
Sample Output:
20
-20
0
'''
def sum_index_multiplier(nums):
# use enumerate to return count and value
#single line of return statement with for
return sum(j*i for i, j in enumerate(nums))
print(sum_index_multiplier([1,2,3,4]))
print(sum_index_multiplier([-1,-2,-3,-4]))
print(sum_index_multiplier([]))
|
# ## Leap Year
# # 💪This is a Difficult Challenge 💪
# # Instructions
# Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February. The reason why we have leap years is really fascinating, this video does it more justice:
# [https://www.youtube.com/watch?v=xX96xng7sAE](https://www.youtube.com/watch?v=xX96xng7sAE)
# This is how you work out whether if a particular year is a leap year.
# > `on every year that is evenly divisible by 4
# > **except** every year that is evenly divisible by 100
# > **unless** the year is also evenly divisible by 400`
# e.g. The year 2000:
# 2000 ÷ 4 = 500 (Leap)
# 2000 ÷ 100 = 20 (Not Leap)
# 2000 ÷ 400 = 5 (Leap!)
# So the year 2000 is a leap year.
# But the year 2100 is not a leap year because:
# 2100 ÷ 4 = 525 (Leap)
# 2100 ÷ 100 = 21 (Not Leap)
# 2100 ÷ 400 = 5.25 (Not Leap)
# **Warning** your output should match the Example Output format exactly, even the positions of the commas and full stops.
# # Example Input 1
# ```
# 2400
# ```
# # Example Output 1
# ```
# Leap year.
# ```
# # Example Input 2
# ```
# 1989
# ```
# # Example Output 2
# ```
# Not leap year.
# ```
# e.g. When you hit **run**, this is what should happen:
# 
# # Hint
# 1. Try to visualise the rules by creating a flow chart on www.draw.io
# 2. If you really get stuck, you can see the flow chart I created:
# https://bit.ly/36BjS2D
#
#
# https://replit.com/@appbrewery/day-3-3-exercise
#
#
# 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
if year % 400 == 0:
print("Leap year.")
elif year % 100 == 0:
print("Not leap year.")
elif year % 4 == 0:
print("Leap year.")
else:
print("Not leap year.")
|
class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = Node(root)
def display(self, start, traversal=""):
if start != None:
traversal += (str(start.data) + " ")
traversal = self.display(start.left, traversal)
traversal = self.display(start.right, traversal)
return traversal
def is_bst(self):
start = self.root
traversal = ""
if start.data != None:
if start.left.data > start.data:
return False
if start.right.data < start.data:
return False
self.display(start.left, traversal)
self.display(start.right, traversal)
return True
def highest_value(self, start, traversal):
if start != None:
if start.data > traversal:
traversal = start.data
traversal = self.highest_value(start.left, traversal)
traversal = self.highest_value(start.right, traversal)
return traversal
def lowest_value(self, start, traversal):
if start != None:
if start.data < traversal:
traversal = start.data
traversal = self.lowest_value(start.left, traversal)
traversal = self.lowest_value(start.right, traversal)
return traversal
|
class Solution:
def expandFromMiddle(self, s:str, l:int, r:int):
while (l >= 0 and r < len(s) and s[l] == s[r]):
l -= 1
r += 1
return (r - l - 1)
def longestPalindrome(self, s: str) -> str:
if len(s) < 1: return 0
start = 0
end = 0
for i in range(len(s)):
l1 = self.expandFromMiddle(s, i, i)
l2 = self.expandFromMiddle(s, i, i+1)
ls = max(l1,l2)
if ls > end - start:
start = i - ((ls - 1)//2)
end = i + (ls//2)
return s[start: end+1]
if __name__ == "__main__":
sol = Solution()
s = "babab"
s = "cbbd"
# s = 'bb'
# s = "babc"
# s = "aca"
# s = "defggbac"
# s = 'a'
s = "babad"
# s = "ccc"
s = "abb"
# s = "reifadyqgztixemwswtccodfnchcovrmiooffbbijkecuvlvukecutasfxqcqygltrogrdxlrslbnzktlanycgtniprjlospzhhgdrqcwlukbpsrumxguskubokxcmswjnssbkutdhppsdckuckcbwbxpmcmdicfjxaanoxndlfpqwneytatcbyjmimyawevmgirunvmdvxwdjbiqszwhfhjmrpexfwrbzkipxfowcbqjckaotmmgkrbjvhihgwuszdrdiijkgjoljjdubcbowvxslctleblfmdzmvdkqdxtiylabrwaccikkpnpsgcotxoggdydqnuogmxttcycjorzrtwtcchxrbbknfmxnonbhgbjjypqhbftceduxgrnaswtbytrhuiqnxkivevhprcvhggugrmmxolvfzwadlnzdwbtqbaveoongezoymdrhywxcxvggsewsxckucmncbrljskgsgtehortuvbtrsfisyewchxlmxqccoplhlzwutoqoctgfnrzhqctxaqacmirrqdwsbdpqttmyrmxxawgtjzqjgffqwlxqxwxrkgtzqkgdulbxmfcvxcwoswystiyittdjaqvaijwscqobqlhskhvoktksvmguzfankdigqlegrxxqpoitdtykfltohnzrcgmlnhddcfmawiriiiblwrttveedkxzzagdzpwvriuctvtrvdpqzcdnrkgcnpwjlraaaaskgguxzljktqvzzmruqqslutiipladbcxdwxhmvevsjrdkhdpxcyjkidkoznuagshnvccnkyeflpyjzlcbmhbytxnfzcrnmkyknbmtzwtaceajmnuyjblmdlbjdjxctvqcoqkbaszvrqvjgzdqpvmucerumskjrwhywjkwgligkectzboqbanrsvynxscpxqxtqhthdytfvhzjdcxgckvgfbldsfzxqdozxicrwqyprgnadfxsionkzzegmeynye"
print(sol.longestPalindrome(s))
|
class Paddle():
def __init__(self, x1, x2 , y1, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
#private method
def __setPaddleRight(self):
self.x1 = 4
self.x2 = 4
self.y1 = 0
self.y2 = 1
display.set_pixel(self.x1, self.y1, 9)
display.set_pixel(self.x2, self.y2, 9)
#private method
def __setPaddleLeft(self):
self.x1 = 0
self.x2 = 0
self.y1 = 4
self.y2 = 3
display.set_pixel(self.x1, self.y1, 9)
display.set_pixel(self.x2, self.y2, 9)
def startGame(self):
self.__setPaddleLeft()
self.__setPaddleRight()
def moveUp(self):
self.y1 -= 1
self.y2 -= 1
if self.y1 or self.y2 == 0:
return self.y1, self.y2
def moveDown(self):
self.y += 1
self.y += 1
if self.y1 or self.y2 == 0:
return self.y1, self.y2
def getCurrentPosition(self):
return self.x1, self.y1, self.x2, self.y2
def update(self):
display.set_pixel(self.x1, self.y1, 9)
display.set_pixel(self.x2, self.y2, 9)
|
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
minBuy = 999999 # probably should use sys.maxint
maxProfits = 0
for i in xrange(len(prices)):
minBuy = min(minBuy, prices[i])
maxProfits = max(maxProfits, prices[i] - minBuy)
return maxProfits
|
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
def log(message, log_class, log_level):
"""Log information to the console.
If you are angry about having to use Enums instead of typing the classes and levels in, look up how any logging facility works.
Arguments:
message -- the relevant information to be logged
log_class -- the category of information to be logged. Must be within util.log.LogClass
log_level -- the severity of the information being logged. Must be within util.log.LogLevel
"""
assert log_class in LogClass
assert log_level in LogLevel
print("%s/%s: %s" % (log_level, log_class, message))
LogClass = Enum(["CV", "GRAPHICS", "GENERAL"])
LogLevel = Enum(["VERBOSE", "INFO", "WARNING", "ERROR"])
|
class Solution:
def findContestMatch(self, n):
"""
:type n: int
:rtype: str
"""
ans = list(range(1, n + 1))
while len(ans) > 1:
ans = ["({},{})".format(ans[i], ans[~i]) for i in range(len(ans) // 2)]
return ans[0]
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Создайте класс с именем _Person_, содержащий три поля для хранения имени, фамилии и отчества.
# В классе создайте функцию _show_data()_, выводящую на экран имя, фамилию и отчество.
# Далее от класса _Person_ с помощью наследования создайте два класса: _Student_, _Professor_.
# К классу _Student_ добавьте дополнительное поле, содержащее средний бал студента.
# К классу _Professor_ три поля:
# 1. число публикаций профессора,
# 2. должность (тип - перечисление) - преподаватель, старший преподаватель, доцент, профессор,
# 3. возраст.
# Для каждого производного класса переопределите метод _show_data()_.
# В основной программе определите массив.
# Далее в цикле нужно организовать ввод студентов и профессоров вперемешку.
# Когда ввод будет закончен, нужно вывести информацию с помощью метода _show_data()_ обо всех людях.
class Person:
name = ""
fname = ""
tname = ""
def show_data(self):
print("ФИО {} {} {}".format(self.name, self.fname, self.tname))
class Student(Person):
grade = 0
def show_data(self):
print("ФИО {} {} {}, средний бал {}".format(self.name, self.fname, self.tname, self.grade))
class Professor(Person):
pub_count = 0
position = ""
age = 0
def show_data(self):
print("ФИО {} {} {} число публикаций {}, должность {}, возраст {}".format(self.name, self.fname, self.tname, self.pub_count, self.position, self.age))
list = [Student(), Student(), Professor(), Professor(), Student()]
for p in list:
p.show_data()
|
N, C, S, *l = map(int, open(0).read().split())
c = 0
S -= 1
ans = 0
for i in l:
ans += c == S
c = (c+i+N)%N
ans += c == S
print(ans)
|
"""Question: https://leetcode.com/problems/palindrome-number/
"""
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
copy, reverse = x, 0
while copy:
reverse *= 10
reverse += copy % 10
copy = copy // 10
return x == reverse
def isPalindrome_using_str(self, x: int) -> bool:
return str(x) == str(x)[::-1]
if __name__ == '__main__':
x = 121
output = Solution().isPalindrome(x)
print(f'x: {x}\toutput: {output}')
x = -121
output = Solution().isPalindrome(x)
print(f'x: {x}\toutput: {output}')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Sandip Dutta
"""
# To implement simple tree algorithms
# DFS on Binary Tree,
# Problem Stateent : sum of all leaf nodes
#number of nodes of tree
n = 10
'''we take starting node to be 0th node'''
''' tree is a directed graph here'''
tree = [[1, 2],#0
[3, 5],#1
[7, 8],#2
[4],#3
[],#4
[6],#5
[],#6
[],#7
[9],#8
[]]#9
#Records if visited or not
visited = [False] * n
def isLeafNode(neighbour):
'''checks if leaf node or not'''
#[] evaluates to False
# if tree[neighbour] is [], return True
return not tree[neighbour]
def sum_of_leaf_nodes():
'''sum of leaf nodes calculated'''
# Empty tree
if tree == None:
return 0
# Set 0 as visited
visited[0] = True
# total of all leaf nodes
total = 0
# Traverses the tree
for node in range(n):
# Get neighbours
for neighbour in tree[node]:
# If not visited neighbours, then go inside
if not visited[neighbour]:
# Mark as visited
visited[neighbour] = True
# if leaf node, add that value to total
if isLeafNode(neighbour):
total += neighbour
# Return the total
return total
# Print the sum of the root nodesz
print("sum is {}".format(sum_of_leaf_nodes()))
# =============================================================================
# Make sure to turn visited to all False values as we will be reusing that
# array again
# =============================================================================
# Recursive version of the above function
def sum_of_leaf_nodes_R(node):
# Empty tree
if tree == None:
return 0
total = 0
# Set 0 as visited
visited[node] = True
# If leaf node, return the value of the node
if isLeafNode(node):
return node
# checks for all neighbours
for neighbour in tree[node]:
# If unvisited neighbours, visit
if not visited[neighbour]:
# Add leaf node sum to total
total += sum_of_leaf_nodes_R(neighbour)
# Return the total
return total
# Print the sum of the root nodesz
print("sum is {}".format(sum_of_leaf_nodes_R(0)))
|
def mensagem(cor='', msg='', firula='', tamanho=0):
if '\n' in msg:
linha = msg.find('\n')
else:
linha = len(msg)
limpa = '\033[m'
if tamanho == 0:
tamanho = firula * (linha + 4)
if firula == '':
print(f'{cor} {msg} {limpa}')
else:
print(f'{cor}{tamanho}{limpa}')
print(f'{cor} {msg} \033[m')
print(f'{cor}{tamanho}{limpa}')
|
n1 = int(input('Digite o 1° número: '))
n2 = int(input('Digite o 2° número: '))
s = n1 + n2
print('{} + {} = {}'.format(n1, n2, s))
|
'''
Leetcode Problem number 687.
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
'''
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
self.max_path = 0;
if(root is None or (root.left is None and root.right is None )):
pass
else:
self.find_max_path(root)
return self.max_path
def set_max_value(self,new_val)-> None:
self.max_path = new_val
def find_max_path(self, root: TreeNode) -> int:
'''
finds longest path of 1 value and updates the overall maximum value.
return : current node's maximum matching value
'''
if(root is None or (root.left is None and root.right is None )):
return 0
cur_length=0
left_is_same = False
left_max_path = 0
right_max_path = 0
if(root.left):
left_max_path = self.find_max_path(root.left)
if(root.left.val == root.val ):
cur_length += 1 + left_max_path;
left_is_same = True
else:
cur_length = 0;
if(root.right):
right_max_path = self.find_max_path(root.right)
if(root.right.val == root.val and left_is_same):
self.set_max_value(max(self.max_path, cur_length + 1 + right_max_path))
if(root.right.val == root.val):
cur_length = max(1 + right_max_path, cur_length);
self.set_max_value(max(self.max_path,cur_length))
return cur_length
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.