content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
n = int(input())
data = []
c1, c2 = 0, 0
flag = 0
for i in range(n):
val = list(map(int, input().split()))
data.append(tuple(val))
c1 += val[0]
c2 += val[1]
if (c1 % 2) != (c2 % 2):
flag = 1
if c1 % 2 == 1 and c2 % 2 == 1 and (c1+c2) % 2 == 0 and n > 1 and flag == 1:
print(1)
elif c1 % 2 == 0 and c2 % 2 == 0:
print(0)
else:
print(-1)
|
n = int(input())
data = []
(c1, c2) = (0, 0)
flag = 0
for i in range(n):
val = list(map(int, input().split()))
data.append(tuple(val))
c1 += val[0]
c2 += val[1]
if c1 % 2 != c2 % 2:
flag = 1
if c1 % 2 == 1 and c2 % 2 == 1 and ((c1 + c2) % 2 == 0) and (n > 1) and (flag == 1):
print(1)
elif c1 % 2 == 0 and c2 % 2 == 0:
print(0)
else:
print(-1)
|
FULL_SCREEN = "FULL_SCREEN"
MOVE_UP = "MOVE_UP"
MOVE_LEFT = "MOVE_LEFT"
MOVE_RIGHT = "MOVE_RIGHT"
MOVE_DOWN = "MOVE_DOWN"
ATTACK = "ATTACK"
INVENTORY = "INVENTORY"
MOVEMENT_ACTION = [
MOVE_DOWN,
MOVE_UP,
MOVE_RIGHT,
MOVE_LEFT,
]
|
full_screen = 'FULL_SCREEN'
move_up = 'MOVE_UP'
move_left = 'MOVE_LEFT'
move_right = 'MOVE_RIGHT'
move_down = 'MOVE_DOWN'
attack = 'ATTACK'
inventory = 'INVENTORY'
movement_action = [MOVE_DOWN, MOVE_UP, MOVE_RIGHT, MOVE_LEFT]
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
current_carry = 0
current = ListNode(0)
head = current
while l1 or l2 or current_carry:
current_val = current_carry
current_val += 0 if l1 is None else l1.val
current_val += 0 if l2 is None else l2.val
if current_val >= 10:
current_val -= 10
current_carry = 1
else:
current_carry = 0
current.next = ListNode(current_val)
current = current.next
if l1 is None and l2 is None:
break
elif l1 is None:
l2 = l2.next
elif l2 is None:
l1 = l1.next
else:
l1 = l1.next
l2 = l2.next
return head.next
|
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
current_carry = 0
current = list_node(0)
head = current
while l1 or l2 or current_carry:
current_val = current_carry
current_val += 0 if l1 is None else l1.val
current_val += 0 if l2 is None else l2.val
if current_val >= 10:
current_val -= 10
current_carry = 1
else:
current_carry = 0
current.next = list_node(current_val)
current = current.next
if l1 is None and l2 is None:
break
elif l1 is None:
l2 = l2.next
elif l2 is None:
l1 = l1.next
else:
l1 = l1.next
l2 = l2.next
return head.next
|
#!/usr/bin/python3
class Node:
def __init__(self, data, lchild=None, rchild=None):
self.data = data
self.lchild = lchild
self.rchild = rchild
def pre_order(root):
if root != None:
print(root.data, end=' ')
pre_order(root.lchild)
pre_order(root.rchild)
def in_order(root):
if root != None:
in_order(root.lchild)
print(root.data, end=' ')
in_order(root.rchild)
def post_order(root):
if root != None:
post_order(root.lchild)
post_order(root.rchild)
print(root.data, end=' ')
def layor_order(root):
if root == None:
return
q = []
p = None
q.append(root)
while len(q) > 0:
p = q.pop(0)
print(p.data, end=' ')
if p.lchild != None:
q.append(p.lchild)
if p.rchild != None:
q.append(p.rchild)
print()
def height(root):
if root == None:
return 0
left_height = height(root.lchild)
right_height = height(root.rchild)
if left_height > right_height:
return left_height + 1
else:
return right_height + 1
if __name__ == "__main__":
a = Node('A', Node('B', Node('D', None, Node('F')), None), Node('C', None, Node('E')))
print("PreOrder:")
pre_order(a)
print()
print("InOder:")
in_order(a)
print()
print("PostOrder:")
post_order(a)
print()
print('LayorOrder:')
layor_order(a)
print("Tree height:", height(a))
|
class Node:
def __init__(self, data, lchild=None, rchild=None):
self.data = data
self.lchild = lchild
self.rchild = rchild
def pre_order(root):
if root != None:
print(root.data, end=' ')
pre_order(root.lchild)
pre_order(root.rchild)
def in_order(root):
if root != None:
in_order(root.lchild)
print(root.data, end=' ')
in_order(root.rchild)
def post_order(root):
if root != None:
post_order(root.lchild)
post_order(root.rchild)
print(root.data, end=' ')
def layor_order(root):
if root == None:
return
q = []
p = None
q.append(root)
while len(q) > 0:
p = q.pop(0)
print(p.data, end=' ')
if p.lchild != None:
q.append(p.lchild)
if p.rchild != None:
q.append(p.rchild)
print()
def height(root):
if root == None:
return 0
left_height = height(root.lchild)
right_height = height(root.rchild)
if left_height > right_height:
return left_height + 1
else:
return right_height + 1
if __name__ == '__main__':
a = node('A', node('B', node('D', None, node('F')), None), node('C', None, node('E')))
print('PreOrder:')
pre_order(a)
print()
print('InOder:')
in_order(a)
print()
print('PostOrder:')
post_order(a)
print()
print('LayorOrder:')
layor_order(a)
print('Tree height:', height(a))
|
DEBUG = False
SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://hlapse:h91040635!@rm-uf6gm31bj3hm81y14to.mysql.rds.aliyuncs.com/rss' + '?charset=utf8mb4'
SQLALCHEMY_TRACK_MODIFICATIONS = False
# JWT
JWT_ERROR_MESSAGE_KEY = "messsage"
JWT_ACCESS_TOKEN_EXPIRES = False
# APScheduler
SCHEDULER_API_ENABLED = True
SCHEDULER_EXECUTORS = {'default': {'type': 'threadpool', 'max_workers': 20}}
|
debug = False
secret_key = b'_5#y2L"F4Q8z\n\xec]/'
sqlalchemy_database_uri = 'mysql+pymysql://hlapse:h91040635!@rm-uf6gm31bj3hm81y14to.mysql.rds.aliyuncs.com/rss' + '?charset=utf8mb4'
sqlalchemy_track_modifications = False
jwt_error_message_key = 'messsage'
jwt_access_token_expires = False
scheduler_api_enabled = True
scheduler_executors = {'default': {'type': 'threadpool', 'max_workers': 20}}
|
UP = 1
DOWN = 2
FLOOR_COUNT = 6
class ElevatorLogic(object):
"""
An incorrect implementation. Can you make it pass all the tests?
Fix the methods below to implement the correct logic for elevators.
The tests are integrated into `README.md`. To run the tests:
$ python -m doctest -v README.md
To learn when each method is called, read its docstring.
To interact with the world, you can get the current floor from the
`current_floor` property of the `callbacks` object, and you can move the
elevator by setting the `motor_direction` property. See below for how this is done.
"""
def __init__(self):
# Feel free to add any instance variables you want.
self.callbacks = None
self.direction = 0
self.called_floors_up = set()
self.called_floors_down = set()
self.selected_floors = set()
def on_called(self, floor, direction):
"""
This is called when somebody presses the up or down button to call the elevator.
This could happen at any time, whether or not the elevator is moving.
The elevator could be requested at any floor at any time, going in either direction.
floor: the floor that the elevator is being called to
direction: the direction the caller wants to go, up or down
"""
called_floors = self.called_floors_up if direction == UP else self.called_floors_down
current_floor = self.callbacks.current_floor
motor_direction = self.callbacks.motor_direction
if not floor in called_floors and (motor_direction != None or floor != current_floor):
called_floors.add(floor)
if self.direction == 0:
self.direction = UP if floor > current_floor else DOWN
def on_floor_selected(self, floor):
"""
This is called when somebody on the elevator chooses a floor.
This could happen at any time, whether or not the elevator is moving.
Any floor could be requested at any time.
floor: the floor that was requested
"""
delta = 1 if self.direction == UP else -1
current_floor = self.callbacks.current_floor
if not floor in self.selected_floors and floor != current_floor:
if self.direction == 0 or delta * (floor - current_floor) > 0:
self.selected_floors.add(floor)
if self.direction == 0:
self.direction = UP if floor > current_floor else DOWN
def on_floor_changed(self):
"""
This lets you know that the elevator has moved one floor up or down.
You should decide whether or not you want to stop the elevator.
"""
called_floors = self.called_floors_up if self.direction == UP else self.called_floors_down
reverse_called_floors = self.called_floors_down if self.direction == UP else self.called_floors_up
current_floor = self.callbacks.current_floor
if current_floor in self.selected_floors:
self.callbacks.motor_direction = None
self.selected_floors.discard(current_floor)
if current_floor in called_floors:
self.callbacks.motor_direction = None
called_floors.discard(current_floor)
elif not self.need_to_go(self.direction) and current_floor in reverse_called_floors:
self.callbacks.motor_direction = None
reverse_called_floors.discard(current_floor)
self.direction = DOWN if self.direction == UP else UP
def on_ready(self):
"""
This is called when the elevator is ready to go.
Maybe passengers have embarked and disembarked. The doors are closed,
time to actually move, if necessary.
"""
reverse_called_floors = self.called_floors_down if self.direction == UP else self.called_floors_up
current_floor = self.callbacks.current_floor
if self.direction != 0:
if self.need_to_go(self.direction):
self.callbacks.motor_direction = self.direction
elif current_floor in reverse_called_floors:
reverse_called_floors.discard(current_floor)
self.direction = DOWN if self.direction == UP else UP
else:
self.direction = 0
if self.direction == 0:
self.called_floors_up.discard(current_floor)
self.called_floors_down.discard(current_floor)
if self.need_to_go(UP):
self.callbacks.motor_direction = UP
self.direction = UP
elif self.need_to_go(DOWN):
self.callbacks.motor_direction = DOWN
self.direction = DOWN
def need_to_go(self, direction):
delta = 1 if direction == UP else -1
floors = self.selected_floors | self.called_floors_up | self.called_floors_down
for floor in floors:
if delta * (floor - self.callbacks.current_floor) > 0:
return True
return False
|
up = 1
down = 2
floor_count = 6
class Elevatorlogic(object):
"""
An incorrect implementation. Can you make it pass all the tests?
Fix the methods below to implement the correct logic for elevators.
The tests are integrated into `README.md`. To run the tests:
$ python -m doctest -v README.md
To learn when each method is called, read its docstring.
To interact with the world, you can get the current floor from the
`current_floor` property of the `callbacks` object, and you can move the
elevator by setting the `motor_direction` property. See below for how this is done.
"""
def __init__(self):
self.callbacks = None
self.direction = 0
self.called_floors_up = set()
self.called_floors_down = set()
self.selected_floors = set()
def on_called(self, floor, direction):
"""
This is called when somebody presses the up or down button to call the elevator.
This could happen at any time, whether or not the elevator is moving.
The elevator could be requested at any floor at any time, going in either direction.
floor: the floor that the elevator is being called to
direction: the direction the caller wants to go, up or down
"""
called_floors = self.called_floors_up if direction == UP else self.called_floors_down
current_floor = self.callbacks.current_floor
motor_direction = self.callbacks.motor_direction
if not floor in called_floors and (motor_direction != None or floor != current_floor):
called_floors.add(floor)
if self.direction == 0:
self.direction = UP if floor > current_floor else DOWN
def on_floor_selected(self, floor):
"""
This is called when somebody on the elevator chooses a floor.
This could happen at any time, whether or not the elevator is moving.
Any floor could be requested at any time.
floor: the floor that was requested
"""
delta = 1 if self.direction == UP else -1
current_floor = self.callbacks.current_floor
if not floor in self.selected_floors and floor != current_floor:
if self.direction == 0 or delta * (floor - current_floor) > 0:
self.selected_floors.add(floor)
if self.direction == 0:
self.direction = UP if floor > current_floor else DOWN
def on_floor_changed(self):
"""
This lets you know that the elevator has moved one floor up or down.
You should decide whether or not you want to stop the elevator.
"""
called_floors = self.called_floors_up if self.direction == UP else self.called_floors_down
reverse_called_floors = self.called_floors_down if self.direction == UP else self.called_floors_up
current_floor = self.callbacks.current_floor
if current_floor in self.selected_floors:
self.callbacks.motor_direction = None
self.selected_floors.discard(current_floor)
if current_floor in called_floors:
self.callbacks.motor_direction = None
called_floors.discard(current_floor)
elif not self.need_to_go(self.direction) and current_floor in reverse_called_floors:
self.callbacks.motor_direction = None
reverse_called_floors.discard(current_floor)
self.direction = DOWN if self.direction == UP else UP
def on_ready(self):
"""
This is called when the elevator is ready to go.
Maybe passengers have embarked and disembarked. The doors are closed,
time to actually move, if necessary.
"""
reverse_called_floors = self.called_floors_down if self.direction == UP else self.called_floors_up
current_floor = self.callbacks.current_floor
if self.direction != 0:
if self.need_to_go(self.direction):
self.callbacks.motor_direction = self.direction
elif current_floor in reverse_called_floors:
reverse_called_floors.discard(current_floor)
self.direction = DOWN if self.direction == UP else UP
else:
self.direction = 0
if self.direction == 0:
self.called_floors_up.discard(current_floor)
self.called_floors_down.discard(current_floor)
if self.need_to_go(UP):
self.callbacks.motor_direction = UP
self.direction = UP
elif self.need_to_go(DOWN):
self.callbacks.motor_direction = DOWN
self.direction = DOWN
def need_to_go(self, direction):
delta = 1 if direction == UP else -1
floors = self.selected_floors | self.called_floors_up | self.called_floors_down
for floor in floors:
if delta * (floor - self.callbacks.current_floor) > 0:
return True
return False
|
ROTATED_PROXY_ENABLED = True
PROXY_STORAGE = 'scrapy_rotated_proxy.extensions.file_storage.FileProxyStorage'
PROXY_FILE_PATH = ''
# PROXY_STORAGE = 'scrapy_rotated_proxy.extensions.mongodb_storage.MongoDBProxyStorage'
PROXY_MONGODB_HOST = '127.0.0.1'
PROXY_MONGODB_PORT = 27017
PROXY_MONGODB_USERNAME = None
PROXY_MONGODB_PASSWORD = None
PROXY_MONGODB_AUTH_DB = 'admin'
PROXY_MONGODB_DB = 'proxy_management'
PROXY_MONGODB_COLL = 'proxy'
PROXY_MONGODB_COLL_INDEX = []
PROXY_SLEEP_INTERVAL = 60*60*24
PROXY_SPIDER_CLOSE_WHEN_NO_PROXY = True
PROXY_RELOAD_ENABLED = False
|
rotated_proxy_enabled = True
proxy_storage = 'scrapy_rotated_proxy.extensions.file_storage.FileProxyStorage'
proxy_file_path = ''
proxy_mongodb_host = '127.0.0.1'
proxy_mongodb_port = 27017
proxy_mongodb_username = None
proxy_mongodb_password = None
proxy_mongodb_auth_db = 'admin'
proxy_mongodb_db = 'proxy_management'
proxy_mongodb_coll = 'proxy'
proxy_mongodb_coll_index = []
proxy_sleep_interval = 60 * 60 * 24
proxy_spider_close_when_no_proxy = True
proxy_reload_enabled = False
|
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
# {
# 'target_name': 'cast_extension_discoverer',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'cast_video_element',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'caster',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'media_manager',
# 'includes': ['../../../compile_js2.gypi'],
# },
],
}
|
{'targets': []}
|
"""Constants for the babydriver CAN protocol."""
# pylint: disable=too-few-public-methods
# Both the C and Python babydriver projects use 15 as the device ID, see can_msg_defs.h.
BABYDRIVER_DEVICE_ID = 15
# The babydriver CAN message has ID 63, see can_msg_defs.h.
BABYDRIVER_CAN_MESSAGE_ID = 63
class BabydriverMessageId:
"""
An enumeration of babydriver IDs, which go in the first uint8 in a babydriver CAN message.
This is the Python equivalent of the enum of the same name in babydriver_msg_defs.h and should
be kept up to date with it.
"""
STATUS = 0
GPIO_SET = 1
GPIO_GET_COMMAND = 2
GPIO_GET_DATA = 3
ADC_READ_COMMAND = 4
ADC_READ_DATA = 5
I2C_READ_COMMAND = 6
I2C_READ_DATA = 7
I2C_WRITE_COMMAND = 8
I2C_WRITE_DATA = 9
SPI_EXCHANGE_METADATA_1 = 10
SPI_EXCHANGE_METADATA_2 = 11
SPI_EXCHANGE_TX_DATA = 12
SPI_EXCHANGE_RX_DATA = 13
GPIO_IT_REGISTER_COMMAND = 14
GPIO_IT_UNREGISTER_COMMAND = 15
GPIO_IT_INTERRUPT = 16
|
"""Constants for the babydriver CAN protocol."""
babydriver_device_id = 15
babydriver_can_message_id = 63
class Babydrivermessageid:
"""
An enumeration of babydriver IDs, which go in the first uint8 in a babydriver CAN message.
This is the Python equivalent of the enum of the same name in babydriver_msg_defs.h and should
be kept up to date with it.
"""
status = 0
gpio_set = 1
gpio_get_command = 2
gpio_get_data = 3
adc_read_command = 4
adc_read_data = 5
i2_c_read_command = 6
i2_c_read_data = 7
i2_c_write_command = 8
i2_c_write_data = 9
spi_exchange_metadata_1 = 10
spi_exchange_metadata_2 = 11
spi_exchange_tx_data = 12
spi_exchange_rx_data = 13
gpio_it_register_command = 14
gpio_it_unregister_command = 15
gpio_it_interrupt = 16
|
def iscomplex(a):
# TODO(beam2d): Implement it
raise NotImplementedError
def iscomplexobj(x):
# TODO(beam2d): Implement it
raise NotImplementedError
def isfortran(a):
# TODO(beam2d): Implement it
raise NotImplementedError
def isreal(x):
# TODO(beam2d): Implement it
raise NotImplementedError
def isrealobj(x):
# TODO(beam2d): Implement it
raise NotImplementedError
|
def iscomplex(a):
raise NotImplementedError
def iscomplexobj(x):
raise NotImplementedError
def isfortran(a):
raise NotImplementedError
def isreal(x):
raise NotImplementedError
def isrealobj(x):
raise NotImplementedError
|
N, K = map(int, input().split())
S = list(input())
S[K-1] = S[K-1].swapcase()
print("".join(S))
|
(n, k) = map(int, input().split())
s = list(input())
S[K - 1] = S[K - 1].swapcase()
print(''.join(S))
|
full_submit = {
'processes' : [
{ 'name': 'mkdir', 'cmd': 'mkdir -p /mnt/mesos/sandbox/sandbox/__jobio/input /mnt/mesos/sandbox/sandbox/__jobio/output' },
{ 'name': 'symlink_in', 'cmd': 'ln -s /mnt/mesos/sandbox/sandbox/__jobio/input /job/input' },
{ 'name': 'symlink_out', 'cmd': 'ln -s /mnt/mesos/sandbox/sandbox/__jobio/output /job/output' },
{ 'name' : "locdown_0", 'cmd' : 'localizer "gs://foo" "/foo"' },
{ 'name' : "locdown_1", 'cmd' : 'localizer "http://bar" "/bar"' },
{ 'name' : "TESTJOB_ps", 'cmd' : 'echo Hello herc! > /baz' },
{ 'name' : "locup_0", 'cmd' : 'localizer "/baz" "gs://baz"' }
],
'finalizers' : [
{ 'name' : "__locup_stdout", 'cmd' : 'localizer ".logs/TESTJOB_ps/0/stdout" "gs://stdout"' },
{ 'name' : "__locup_stderr", 'cmd' : 'localizer ".logs/TESTJOB_ps/0/stderr" "gs://stderr"' }
],
'tasks' : [{ 'name' : 'TESTJOB_task',
'processes' : [ 'mkdir', 'symlink_in', 'symlink_out', "locdown_0", "locdown_1", "TESTJOB_ps", "locup_0", "__locup_stdout", "__locup_stderr" ],
'ordering' : [ 'mkdir', 'symlink_in', 'symlink_out', "locdown_0", "locdown_1", "TESTJOB_ps", "locup_0" ],
'cpus' : 1,
'mem' : 16,
'memunit' : "MB",
'disk' : 1,
'diskunit' : "MB"
}],
'jobs' : [{ 'name' : 'TESTJOB',
'task' : 'TESTJOB_task',
'env' : 'devel',
'cluster' : 'herc',
'hostlimit' : 99999999,
'container' : "python:2.7"
}]
}
|
full_submit = {'processes': [{'name': 'mkdir', 'cmd': 'mkdir -p /mnt/mesos/sandbox/sandbox/__jobio/input /mnt/mesos/sandbox/sandbox/__jobio/output'}, {'name': 'symlink_in', 'cmd': 'ln -s /mnt/mesos/sandbox/sandbox/__jobio/input /job/input'}, {'name': 'symlink_out', 'cmd': 'ln -s /mnt/mesos/sandbox/sandbox/__jobio/output /job/output'}, {'name': 'locdown_0', 'cmd': 'localizer "gs://foo" "/foo"'}, {'name': 'locdown_1', 'cmd': 'localizer "http://bar" "/bar"'}, {'name': 'TESTJOB_ps', 'cmd': 'echo Hello herc! > /baz'}, {'name': 'locup_0', 'cmd': 'localizer "/baz" "gs://baz"'}], 'finalizers': [{'name': '__locup_stdout', 'cmd': 'localizer ".logs/TESTJOB_ps/0/stdout" "gs://stdout"'}, {'name': '__locup_stderr', 'cmd': 'localizer ".logs/TESTJOB_ps/0/stderr" "gs://stderr"'}], 'tasks': [{'name': 'TESTJOB_task', 'processes': ['mkdir', 'symlink_in', 'symlink_out', 'locdown_0', 'locdown_1', 'TESTJOB_ps', 'locup_0', '__locup_stdout', '__locup_stderr'], 'ordering': ['mkdir', 'symlink_in', 'symlink_out', 'locdown_0', 'locdown_1', 'TESTJOB_ps', 'locup_0'], 'cpus': 1, 'mem': 16, 'memunit': 'MB', 'disk': 1, 'diskunit': 'MB'}], 'jobs': [{'name': 'TESTJOB', 'task': 'TESTJOB_task', 'env': 'devel', 'cluster': 'herc', 'hostlimit': 99999999, 'container': 'python:2.7'}]}
|
"""Make Collatz Sequence
This program makes a `Collatz Sequence`_ for a given number.
Write a function named :meth:`collatz` that has one parameter named number.
If number is even, then :meth:`collatz` should print `number // 2` and return this value.
If number is odd, then :meth:`collatz` should print and return `3 * number + 1`.
Then write a program that lets the user type in an integer and that keeps calling
:meth:`collatz` on that number until the function returns the value `1`.
Example:
::
Enter number:
3
10
5
16
8
4
2
1
.. _Collatz Sequence:
https://en.wikipedia.org/wiki/Collatz_conjecture
"""
def collatz(number: int) -> int:
"""Collatz
If number is even, then return `number // 2`.
If number is odd, then return `3 * number + 1`.
Args:
number: Integer to generate a Collatz conjecture term for.
Returns:
Integer that is either a quotient or a product and sum.
"""
if not number % 2:
return number // 2
else:
return 3 * number + 1
def main():
n = int(input("Input a number: "))
while n != 1:
print(n)
n = collatz(n)
print(n) # When n == 1
# If program is run (instead of imported), call main():
if __name__ == "__main__":
main()
|
"""Make Collatz Sequence
This program makes a `Collatz Sequence`_ for a given number.
Write a function named :meth:`collatz` that has one parameter named number.
If number is even, then :meth:`collatz` should print `number // 2` and return this value.
If number is odd, then :meth:`collatz` should print and return `3 * number + 1`.
Then write a program that lets the user type in an integer and that keeps calling
:meth:`collatz` on that number until the function returns the value `1`.
Example:
::
Enter number:
3
10
5
16
8
4
2
1
.. _Collatz Sequence:
https://en.wikipedia.org/wiki/Collatz_conjecture
"""
def collatz(number: int) -> int:
"""Collatz
If number is even, then return `number // 2`.
If number is odd, then return `3 * number + 1`.
Args:
number: Integer to generate a Collatz conjecture term for.
Returns:
Integer that is either a quotient or a product and sum.
"""
if not number % 2:
return number // 2
else:
return 3 * number + 1
def main():
n = int(input('Input a number: '))
while n != 1:
print(n)
n = collatz(n)
print(n)
if __name__ == '__main__':
main()
|
class TreasureMap:
def __init__(self):
self.map = {}
def populate_map(self):
self.map['beach'] = 'sandy shore'
self.map['coast'] = 'ocean reef'
self.map['volcano'] = 'hot lava'
self.map['x'] = 'marks the spot'
return
|
class Treasuremap:
def __init__(self):
self.map = {}
def populate_map(self):
self.map['beach'] = 'sandy shore'
self.map['coast'] = 'ocean reef'
self.map['volcano'] = 'hot lava'
self.map['x'] = 'marks the spot'
return
|
def sum(n):
a = 0
for b in range(1,n+1,4):
a+=b*b # b ** 2
return a
n = int(input('n='))
print(sum(n))
|
def sum(n):
a = 0
for b in range(1, n + 1, 4):
a += b * b
return a
n = int(input('n='))
print(sum(n))
|
# %%
"""
# Exception handling
"""
# %%
"""
Exception handling allows a program to deal with runtime errors and continue its normal execution.
Consider the following instructions:
"""
# %%
a=input("Enter integer: ")
num=int(a)
inverse=1/num
print(number,inverse)
# %%
"""
What happens if the user enters a null or non-numeric value? The program will stop and raise an error as shown below.
"""
# %%
"""
```
Traceback (most recent call last):
File "", line 3, in
<u>ZeroDivisionError: division by zero</u>
```
"""
# %%
"""
```
Traceback (most recent call last):
File "", line 2, in
<b>ValueError: invalid literal for int() with base 10: 'sss'</b>
```
"""
# %%
"""
Error messages provide information about the line that caused the error by tracing back to the function calls that lead to this instruction. The line numbers of the function calls are displayed in the error message to enable quick correction of the code.
An error that occurs during execution is also called an exception. How can you deal with an exception so that the program can catch the error and prompt the user to enter a correct number?
"""
# %%
"""
## try and except
See the difference.
in the first case, the program crashes and the last `print("finished")` instruction did not execute.
"""
# %%
3 / 0
print("Finished")
# %%
"""
If the "try" instruction is used, the error is detected and the program is not interrupted.
"""
# %%
try:
3 / 0
except:
print('Not ok, there is an error')
print("Finished")
# %%
"""
Now, we will try to avoid the exceptions mentioned above by rewriting our code as follows.
We have the ability to capture the type of exception
"""
# %%
try:
3/0
except ZeroDivisionError:
print("Error: You can't divide by zero")
except ValueError:
print("Error: Non-numeric value")
except BaseException:
print("Error: there is a problem")
# %%
try:
3/int('ssss')
except ZeroDivisionError:
print("Error: You can't divide by zero")
except ValueError:
print("Error: Non-numeric value")
except BaseException:
print("Error: there is a problem")
# %%
"""
### Finally and else
try/except can be completed with two other keywords: finally and else.
else is the block executed if no exception is thrown:
"""
# %%
try:
3/3
except ZeroDivisionError:
print("Error: You can't divide by zero")
except ValueError:
print("Error: Non-numeric value")
except BaseException:
print("Error: there is a problem")
else:
print("Everything is ok")
# %%
"""
I'll do executing in the end no matter what.finally is a block that is executed after all other blocks have been executed, regardless of whether there was an exception or not, and **even if the program crashes**.
"""
# %%
try:
3/0
except ZeroDivisionError:
print("Error: You can't divide by zero")
except ValueError:
print("Error: Non-numeric value")
except BaseException:
print("Error: there is a problem")
finally:
print("I'll do executing in the end no matter what..")
# %%
"""
### raise
"""
# %%
"""
It is possible to trigger exceptions ourselves.
"""
# %%
"""
``raise`` a python statement that can trigger any Error. This means that an error is explicitly triggered.
"""
# %%
def division(num, div):
if div == 0:
raise ZeroDivisionError()
else:
return num / div
division(5,0)
# %%
"""
Well we agree, the function ``division()`` is completely useless!
### Creating an exception
As you can imagine, we can create our own executions.
Just create a class that will inherit the "Exception" class.
"""
# %%
class MyError(Exception):
pass
# %%
raise MyError("Hello")
# %%
|
"""
# Exception handling
"""
'\nException handling allows a program to deal with runtime errors and continue its normal execution.\nConsider the following instructions:\n\n'
a = input('Enter integer: ')
num = int(a)
inverse = 1 / num
print(number, inverse)
'\nWhat happens if the user enters a null or non-numeric value? The program will stop and raise an error as shown below.\n'
'\n```\nTraceback (most recent call last):\nFile "", line 3, in\n<u>ZeroDivisionError: division by zero</u>\n```\n'
'\n```\nTraceback (most recent call last):\nFile "", line 2, in\n<b>ValueError: invalid literal for int() with base 10: \'sss\'</b>\n```\n'
'\nError messages provide information about the line that caused the error by tracing back to the function calls that lead to this instruction. The line numbers of the function calls are displayed in the error message to enable quick correction of the code. \n\nAn error that occurs during execution is also called an exception. How can you deal with an exception so that the program can catch the error and prompt the user to enter a correct number?\n\n'
'\n## try and except\nSee the difference. \nin the first case, the program crashes and the last `print("finished")` instruction did not execute. \n'
3 / 0
print('Finished')
'\nIf the "try" instruction is used, the error is detected and the program is not interrupted. \n'
try:
3 / 0
except:
print('Not ok, there is an error')
print('Finished')
'\nNow, we will try to avoid the exceptions mentioned above by rewriting our code as follows. \nWe have the ability to capture the type of exception\n'
try:
3 / 0
except ZeroDivisionError:
print("Error: You can't divide by zero")
except ValueError:
print('Error: Non-numeric value')
except BaseException:
print('Error: there is a problem')
try:
3 / int('ssss')
except ZeroDivisionError:
print("Error: You can't divide by zero")
except ValueError:
print('Error: Non-numeric value')
except BaseException:
print('Error: there is a problem')
'\n### Finally and else\ntry/except can be completed with two other keywords: finally and else. \nelse is the block executed if no exception is thrown:\n'
try:
3 / 3
except ZeroDivisionError:
print("Error: You can't divide by zero")
except ValueError:
print('Error: Non-numeric value')
except BaseException:
print('Error: there is a problem')
else:
print('Everything is ok')
"\nI'll do executing in the end no matter what.finally is a block that is executed after all other blocks have been executed, regardless of whether there was an exception or not, and **even if the program crashes**. \n\n"
try:
3 / 0
except ZeroDivisionError:
print("Error: You can't divide by zero")
except ValueError:
print('Error: Non-numeric value')
except BaseException:
print('Error: there is a problem')
finally:
print("I'll do executing in the end no matter what..")
'\n### raise\n'
'\nIt is possible to trigger exceptions ourselves.\n'
'\n``raise`` a python statement that can trigger any Error. This means that an error is explicitly triggered. \n'
def division(num, div):
if div == 0:
raise zero_division_error()
else:
return num / div
division(5, 0)
'\nWell we agree, the function ``division()`` is completely useless! \n\n### Creating an exception\nAs you can imagine, we can create our own executions. \nJust create a class that will inherit the "Exception" class.\n'
class Myerror(Exception):
pass
raise my_error('Hello')
|
#------------------------------------------------------------------------------
# interpreter/interpreter.py
# Copyright 2011 Joseph Schilz
# Licensed under Apache v2
#------------------------------------------------------------------------------
articles = [" a ", " the "]
def verb(command):
# A function to isolate the verb in a command.
this_verb = ""
the_rest = ""
first_space = command.find(" ")
# If this_input contains a space, the verb is everything before the
# first space.
if first_space > 0:
this_verb = command[0:first_space]
the_rest = command[first_space + 1:len(command)]
# If it doesn't contain a space, the whole thing is the verb.
else:
this_verb = command
# We handle simple verb aliases at this level...
if command[0] == "'":
this_verb = "say"
the_rest = command[1:len(command)]
if command == "north" or command == "n":
this_verb = "go"
the_rest = "north"
elif command == "south" or command == "s":
this_verb = "go"
the_rest = "south"
elif command == "east" or command == "e":
this_verb = "go"
the_rest = "east"
elif command == "west" or command == "w":
this_verb = "go"
the_rest = "west"
elif command == "up" or command == "u":
this_verb = "go"
the_rest = "up"
elif command == "down" or command == "d":
this_verb = "go"
the_rest = "down"
if this_verb == "l":
this_verb = "look"
elif this_verb == "i":
this_verb = "inv"
elif this_verb == "h":
this_verb = "health"
return this_verb, the_rest
def interpret(the_verb, the_rest, transitivity=1):
the_rest = " " + the_rest.lower() + " "
for article in articles:
the_rest = the_rest.replace(article, '')
if transitivity == 1:
the_rest = the_rest.strip().split()
if len(the_rest) > 0:
# This might not be stable.
return [the_rest.pop(), the_rest]
else:
return False
|
articles = [' a ', ' the ']
def verb(command):
this_verb = ''
the_rest = ''
first_space = command.find(' ')
if first_space > 0:
this_verb = command[0:first_space]
the_rest = command[first_space + 1:len(command)]
else:
this_verb = command
if command[0] == "'":
this_verb = 'say'
the_rest = command[1:len(command)]
if command == 'north' or command == 'n':
this_verb = 'go'
the_rest = 'north'
elif command == 'south' or command == 's':
this_verb = 'go'
the_rest = 'south'
elif command == 'east' or command == 'e':
this_verb = 'go'
the_rest = 'east'
elif command == 'west' or command == 'w':
this_verb = 'go'
the_rest = 'west'
elif command == 'up' or command == 'u':
this_verb = 'go'
the_rest = 'up'
elif command == 'down' or command == 'd':
this_verb = 'go'
the_rest = 'down'
if this_verb == 'l':
this_verb = 'look'
elif this_verb == 'i':
this_verb = 'inv'
elif this_verb == 'h':
this_verb = 'health'
return (this_verb, the_rest)
def interpret(the_verb, the_rest, transitivity=1):
the_rest = ' ' + the_rest.lower() + ' '
for article in articles:
the_rest = the_rest.replace(article, '')
if transitivity == 1:
the_rest = the_rest.strip().split()
if len(the_rest) > 0:
return [the_rest.pop(), the_rest]
else:
return False
|
URLs = [
["https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Current version
["https://web.archive.org/web/20220413213804/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 13 - 21:38:04 UTC
["https://web.archive.org/web/20220412213745/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 12 - 21:37:45 UTC
["https://web.archive.org/web/20220411210123/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 11 - 21:01:23 UTC
["https://web.archive.org/web/20220410235550/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 10 - 23:55:50 UTC
["https://web.archive.org/web/20220409233956/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 9 - 23:39:56 UTC
["https://web.archive.org/web/20220408202350/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 8 - 20:23:50 UTC
["https://web.archive.org/web/20220407235250/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 7 - 23:52:50 UTC
["https://web.archive.org/web/20220406205229/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 6 - 20:52:29 UTC
["https://web.archive.org/web/20220405233659/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 5 - 23:36:59 UTC
["https://web.archive.org/web/20220404220900/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 4 - 22:09:00 UTC
["https://web.archive.org/web/20220403225440/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 3 - 22:54:40 UTC
["https://web.archive.org/web/20220402220455/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 2 - 22:04:55 UTC
["https://web.archive.org/web/20220401220928/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 1 - 22:09:28 UTC
["https://web.archive.org/web/20220401002724/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", False], # Mar 31 - (April 01 - 00:27:24 UTC)
["https://web.archive.org/web/20220330234337/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 30 - 23:43:37 UTC
["https://web.archive.org/web/20220329202039/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 29 - 20:20:39 UTC
["https://web.archive.org/web/20220328205313/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 28 - 20:53:13 UTC
["https://web.archive.org/web/20220327235658/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 27 - 23:56:58 UTC
["https://web.archive.org/web/20220326220720/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 26 - 22:07:20 UTC
["https://web.archive.org/web/20220325232201/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 25 - 23:22:01 UTC
["https://web.archive.org/web/20220324235259/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 24 - 23:52:59 UTC
["https://web.archive.org/web/20220323230032/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 23 - 23:00:32 UTC
["https://web.archive.org/web/20220322205154/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 22 - 20:51:54 UTC
["https://web.archive.org/web/20220321235106/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 21 - 23:51:06 UTC
["https://web.archive.org/web/20220320235959/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 20 - 23:59:59 UTC
["https://web.archive.org/web/20220319224651/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 19 - 22:46:51 UTC
["https://web.archive.org/web/20220318215226/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 18 - 21:52:26 UTC
["https://web.archive.org/web/20220317233941/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 17 - 23:39:41 UTC
["https://web.archive.org/web/20220316230757/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 16 - 23:07:57 UTC
["https://web.archive.org/web/20220315235520/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 15 - 23:55:20 UTC
["https://web.archive.org/web/20220315000709/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", False], # Mar 14 - (Mar 15 - 00:07:09 UTC)
["https://web.archive.org/web/20220313230901/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 13 - 23:09:01 UTC
["https://web.archive.org/web/20220312213558/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 12 - 21:35:58 UTC
["https://web.archive.org/web/20220311205005/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 11 - 20:50:05 UTC
["https://web.archive.org/web/20220310235649/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 10 - 23:56:49 UTC
["https://web.archive.org/web/20220309213817/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 9 - 21:38:17 UTC
["https://web.archive.org/web/20220308204303/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 8 - 20:43:03 UTC
["https://web.archive.org/web/20220307220942/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 7 - 22:09:42 UTC
["https://web.archive.org/web/20220306225654/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 6 - 22:56:54 UTC
["https://web.archive.org/web/20220305211400/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 5 - 21:14:00 UTC
["https://web.archive.org/web/20220304235636/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 4 - 23:56:36 UTC
["https://web.archive.org/web/20220303195838/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 3 - 19:58:38 UTC
["https://web.archive.org/web/20220302205559/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 2 - 20:55:59 UTC
["https://web.archive.org/web/20220301185329/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Mar 1 - 18:53:29 UTC
["https://web.archive.org/web/20220228231935/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Feb 28 - 23:19:35 UTC
["https://web.archive.org/web/20220227214345/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Feb 27 - 21:43:45 UTC
["https://web.archive.org/web/20220226185336/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Feb 26 - 18:53:36 UTC
["https://web.archive.org/web/20220225233528/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Feb 25 - 23:35:28 UTC
["https://web.archive.org/web/20220224231142/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Feb 24 - 23:11:42 UTC
]
|
ur_ls = [['https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220413213804/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220412213745/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220411210123/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220410235550/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220409233956/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220408202350/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220407235250/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220406205229/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220405233659/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220404220900/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220403225440/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220402220455/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220401220928/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220401002724/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', False], ['https://web.archive.org/web/20220330234337/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220329202039/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220328205313/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220327235658/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220326220720/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220325232201/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220324235259/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220323230032/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220322205154/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220321235106/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220320235959/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220319224651/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220318215226/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220317233941/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220316230757/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220315235520/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220315000709/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', False], ['https://web.archive.org/web/20220313230901/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220312213558/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220311205005/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220310235649/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220309213817/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220308204303/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220307220942/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220306225654/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220305211400/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220304235636/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220303195838/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220302205559/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220301185329/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220228231935/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220227214345/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220226185336/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220225233528/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True], ['https://web.archive.org/web/20220224231142/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html', True]]
|
#Enquiry Form
name=input('Enter your First Name ')
Class=int(input('Enter your class '))
school=input('Enter your school name ')
address=input('Enter your Address ')
number=int(input('Enter your phone number '))
#print("Name- ",name,"Class- ",Class,"School- ",school,"Address- ",address,"Phone Number- ",number,sep='\n')
print("Name- ",name)
print("Class- ",Class)
print("School- ",school)
print("Address- ",address)
print("Phone number- ",number)
|
name = input('Enter your First Name ')
class = int(input('Enter your class '))
school = input('Enter your school name ')
address = input('Enter your Address ')
number = int(input('Enter your phone number '))
print('Name- ', name)
print('Class- ', Class)
print('School- ', school)
print('Address- ', address)
print('Phone number- ', number)
|
'''ftoc.py - Fahrenheit to Celsius temperature converter'''
def f_to_c(f):
c = (f - 32) * (5/9)
return c
def input_float(prompt):
ans = input(prompt)
return float(ans)
f = input_float("What is the temperature (in degrees Fahrenheit)? ")
c = f_to_c(f)
print("That is", round(c, 1), "degrees Celsius")
|
"""ftoc.py - Fahrenheit to Celsius temperature converter"""
def f_to_c(f):
c = (f - 32) * (5 / 9)
return c
def input_float(prompt):
ans = input(prompt)
return float(ans)
f = input_float('What is the temperature (in degrees Fahrenheit)? ')
c = f_to_c(f)
print('That is', round(c, 1), 'degrees Celsius')
|
class Solution:
# Sort (Accepted), O(n log n) time, O(n) space
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return (nums[-1] * nums[-2]) - (nums[0] * nums[1])
# One Pass (Top Voted), O(n) time, O(1) space
def maxProductDifference(self, nums: List[int]) -> int:
min1 = min2 = float('inf')
max1 = max2 = float('-inf')
for n in nums:
if n <= min1:
min1, min2, = n, min1
elif n < min2:
min2 = n
if n >= max1:
max1, max2 = n, max1
elif n > max2:
max2 = n
return max1*max2-min1*min2
|
class Solution:
def max_product_difference(self, nums: List[int]) -> int:
nums.sort()
return nums[-1] * nums[-2] - nums[0] * nums[1]
def max_product_difference(self, nums: List[int]) -> int:
min1 = min2 = float('inf')
max1 = max2 = float('-inf')
for n in nums:
if n <= min1:
(min1, min2) = (n, min1)
elif n < min2:
min2 = n
if n >= max1:
(max1, max2) = (n, max1)
elif n > max2:
max2 = n
return max1 * max2 - min1 * min2
|
nota = float(input('Digite sua nota, Valor entre "0 e 10": '))
while True:
if nota >= 8.5 and nota <= 10:
print('Nota igual a A')
elif nota >= 7.0 and nota <= 8.4:
print('Nota igual a B')
elif nota >= 5.0 and nota <= 6.9:
print('Nota igual a C')
elif nota >= 4.0 and nota <= 4.9:
print('Nota igual a D')
elif nota >= 0 and nota <= 3.9:
print('Nota igual a E')
else:
print('Nota invalida')
nota = float(input('Digite sua nota, Valor entre "0 e 10": '))
|
nota = float(input('Digite sua nota, Valor entre "0 e 10": '))
while True:
if nota >= 8.5 and nota <= 10:
print('Nota igual a A')
elif nota >= 7.0 and nota <= 8.4:
print('Nota igual a B')
elif nota >= 5.0 and nota <= 6.9:
print('Nota igual a C')
elif nota >= 4.0 and nota <= 4.9:
print('Nota igual a D')
elif nota >= 0 and nota <= 3.9:
print('Nota igual a E')
else:
print('Nota invalida')
nota = float(input('Digite sua nota, Valor entre "0 e 10": '))
|
# Given an array, rotate the array to the right by k steps, where k is
# non-negative.
# Example 1:
# Input: [1,2,3,4,5,6,7] and k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
# Example 2:
# Input: [-1,-100,3,99] and k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
# Note:
# Try to come up as many solutions as you can, there are at least 3 different
# ways to solve this problem.
# Could you do it in-place with O(1) extra space?
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
stack = []
finalArr = []
for i in range(k):
stack.append(nums.pop())
for i in range(len(stack)):
finalArr.append(stack.pop())
for cur in nums:
finalArr.append(cur)
return finalArr
# Rotate Inplace (space complexity - O(1))
# Logic is explained in leetcode solns.
def rotate_inplace(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k %= len(nums) # for edge cases where k > len(nums)
# without this, we get index out of bound error when k > len(nums)
j = 0
for i in range(len(nums) // 2):
temp = nums[i]
nums[i] = nums[len(nums) - 1 - i]
nums[len(nums) - 1 - i] = temp
for i in range(k // 2):
temp = nums[i]
nums[i] = nums[k - 1 - i]
nums[k - 1 - i] = temp
for i in range(k, k + ((len(nums) - k) // 2)):
temp = nums[i]
nums[i] = nums[len(nums) - 1 - j]
nums[len(nums) - 1 - j] = temp
j += 1
|
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
stack = []
final_arr = []
for i in range(k):
stack.append(nums.pop())
for i in range(len(stack)):
finalArr.append(stack.pop())
for cur in nums:
finalArr.append(cur)
return finalArr
def rotate_inplace(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
j = 0
for i in range(len(nums) // 2):
temp = nums[i]
nums[i] = nums[len(nums) - 1 - i]
nums[len(nums) - 1 - i] = temp
for i in range(k // 2):
temp = nums[i]
nums[i] = nums[k - 1 - i]
nums[k - 1 - i] = temp
for i in range(k, k + (len(nums) - k) // 2):
temp = nums[i]
nums[i] = nums[len(nums) - 1 - j]
nums[len(nums) - 1 - j] = temp
j += 1
|
INVALID_VALUE = -9999
def search_in_dictionary_list(dictionary_list, key_name, key_value):
for dictionary in dictionary_list:
if dictionary[key_name] == key_value:
return dictionary
return None
def search_value_in_dictionary_list(dictionary_list, key_name, key_value, value_key):
dictionary = search_in_dictionary_list(dictionary_list, key_name, key_value)
if dictionary is not None:
return dictionary[value_key]
else:
return INVALID_VALUE
|
invalid_value = -9999
def search_in_dictionary_list(dictionary_list, key_name, key_value):
for dictionary in dictionary_list:
if dictionary[key_name] == key_value:
return dictionary
return None
def search_value_in_dictionary_list(dictionary_list, key_name, key_value, value_key):
dictionary = search_in_dictionary_list(dictionary_list, key_name, key_value)
if dictionary is not None:
return dictionary[value_key]
else:
return INVALID_VALUE
|
expected_output = {
"global_drop_stats": {
"Ipv4NoAdj": {"octets": 296, "packets": 7},
"Ipv4NoRoute": {"octets": 7964, "packets": 181},
"PuntPerCausePolicerDrops": {"octets": 184230, "packets": 2003},
"UidbNotCfgd": {"octets": 29312827, "packets": 466391},
"UnconfiguredIpv4Fia": {"octets": 360, "packets": 6},
}
}
|
expected_output = {'global_drop_stats': {'Ipv4NoAdj': {'octets': 296, 'packets': 7}, 'Ipv4NoRoute': {'octets': 7964, 'packets': 181}, 'PuntPerCausePolicerDrops': {'octets': 184230, 'packets': 2003}, 'UidbNotCfgd': {'octets': 29312827, 'packets': 466391}, 'UnconfiguredIpv4Fia': {'octets': 360, 'packets': 6}}}
|
def func(ord_list, num):
result = True if num in ord_list else False
return result
if __name__ == "__main__":
l = [-1,3,5,6,8,9]
# using binary search
def find(ordered_list, element):
start_index = 0
end_index = len(ordered_list) - 1
while True:
middle_index = int((end_index + start_index) / 2)
if middle_index == start_index or middle_index == end_index:
if ordered_list[middle_index] == element or ordered_list[end_index] == element:
return True
else:
return False
middle_element = ordered_list[middle_index]
if middle_element == element:
return True
elif middle_element > element:
end_index = middle_index
else:
start_index = middle_index
if __name__=="__main__":
l = [2, 4, 6, 8, 10]
print(find(l, 8))
|
def func(ord_list, num):
result = True if num in ord_list else False
return result
if __name__ == '__main__':
l = [-1, 3, 5, 6, 8, 9]
def find(ordered_list, element):
start_index = 0
end_index = len(ordered_list) - 1
while True:
middle_index = int((end_index + start_index) / 2)
if middle_index == start_index or middle_index == end_index:
if ordered_list[middle_index] == element or ordered_list[end_index] == element:
return True
else:
return False
middle_element = ordered_list[middle_index]
if middle_element == element:
return True
elif middle_element > element:
end_index = middle_index
else:
start_index = middle_index
if __name__ == '__main__':
l = [2, 4, 6, 8, 10]
print(find(l, 8))
|
# 54. Spiral Matrix
class Solution:
def spiralOrder(self, matrix):
if not matrix: return matrix
m, n = len(matrix), len(matrix[0])
visited = [[False] * n for _ in range(m)]
ans = []
dirs = ((0,1), (1,0), (0,-1), (-1,0))
cur = 0
i = j = 0
while len(ans) < m * n:
if not visited[i][j]:
ans.append(matrix[i][j])
visited[i][j] = True
di, dj = dirs[cur]
ii, jj = i+di, j+dj
if ii<0 or ii>=m or jj<0 or jj>=n or visited[ii][jj]:
cur = (cur+1) % 4
di, dj = dirs[cur]
i, j = i+di, j+dj
return ans
|
class Solution:
def spiral_order(self, matrix):
if not matrix:
return matrix
(m, n) = (len(matrix), len(matrix[0]))
visited = [[False] * n for _ in range(m)]
ans = []
dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
cur = 0
i = j = 0
while len(ans) < m * n:
if not visited[i][j]:
ans.append(matrix[i][j])
visited[i][j] = True
(di, dj) = dirs[cur]
(ii, jj) = (i + di, j + dj)
if ii < 0 or ii >= m or jj < 0 or (jj >= n) or visited[ii][jj]:
cur = (cur + 1) % 4
(di, dj) = dirs[cur]
(i, j) = (i + di, j + dj)
return ans
|
class Solution:
# @param s, a string
# @param wordDict, a set<string>
# @return a boolean
def wordBreak(self, s, wordDict):
n = len(s)
if n == 0:
return True
res = []
chars = ''.join(wordDict)
for i in xrange(n):
if s[i] not in chars:
return False
lw = s[-1]
lw_end = False
for word in wordDict:
if word[-1] == lw:
lw_end = True
if not lw_end:
return False
return self.dfs(s,[],wordDict, res)
def dfs(self, s, path, wordDict,res):
if not s :
res.append(path[:])
return True
for i in xrange(1,len(s)+1):
c = s[:i]
if c in wordDict:
path.append(c)
v = self.dfs(s[i:],path,wordDict,res)
if v:
return True
path.pop()
return False
|
class Solution:
def word_break(self, s, wordDict):
n = len(s)
if n == 0:
return True
res = []
chars = ''.join(wordDict)
for i in xrange(n):
if s[i] not in chars:
return False
lw = s[-1]
lw_end = False
for word in wordDict:
if word[-1] == lw:
lw_end = True
if not lw_end:
return False
return self.dfs(s, [], wordDict, res)
def dfs(self, s, path, wordDict, res):
if not s:
res.append(path[:])
return True
for i in xrange(1, len(s) + 1):
c = s[:i]
if c in wordDict:
path.append(c)
v = self.dfs(s[i:], path, wordDict, res)
if v:
return True
path.pop()
return False
|
clan = {
}
def add_member(tag, name, age, level):
clan[tag] = {
"Name": name,
"age": age,
"level": level
}
return clan
def display_clan():
print(clan)
add_member("Voodoo", "Andre Williams", 26, "Beginner")
display_clan()
|
clan = {}
def add_member(tag, name, age, level):
clan[tag] = {'Name': name, 'age': age, 'level': level}
return clan
def display_clan():
print(clan)
add_member('Voodoo', 'Andre Williams', 26, 'Beginner')
display_clan()
|
class CRSError(Exception):
pass
class DriverError(Exception):
pass
class TransactionError(RuntimeError):
pass
class UnsupportedGeometryTypeError(Exception):
pass
class DriverIOError(IOError):
pass
|
class Crserror(Exception):
pass
class Drivererror(Exception):
pass
class Transactionerror(RuntimeError):
pass
class Unsupportedgeometrytypeerror(Exception):
pass
class Driverioerror(IOError):
pass
|
# Search Part Problem
n = int(input())
part_list = list(map(int, input().split()))
m = int(input())
require_list = list(map(int, input().split()))
def binary_search(array, target, start, end):
mid = (start + end) // 2
if start >= end:
return "no"
if array[mid] == target:
return "yes"
if array[mid] > target:
return binary_search(array, target, start, mid - 1)
else:
return binary_search(array, target, mid + 1, end)
return "no"
part_list = sorted(part_list)
result = [binary_search(part_list, i, 0, n) for i in require_list]
for answer in result:
print(answer, end=" ")
|
n = int(input())
part_list = list(map(int, input().split()))
m = int(input())
require_list = list(map(int, input().split()))
def binary_search(array, target, start, end):
mid = (start + end) // 2
if start >= end:
return 'no'
if array[mid] == target:
return 'yes'
if array[mid] > target:
return binary_search(array, target, start, mid - 1)
else:
return binary_search(array, target, mid + 1, end)
return 'no'
part_list = sorted(part_list)
result = [binary_search(part_list, i, 0, n) for i in require_list]
for answer in result:
print(answer, end=' ')
|
time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400}
def convert_time_to_seconds(time):
try:
return int(time[:-1]) * time_convert[time[-1]]
except:
raise ValueError
|
time_convert = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
def convert_time_to_seconds(time):
try:
return int(time[:-1]) * time_convert[time[-1]]
except:
raise ValueError
|
def loadfile(name):
lines = []
f = open(name, "r")
for x in f:
if x.endswith('\n'):
x = x[:-1]
lines.append(x.split("-"))
return lines
def pathFromPosition (position, graph, path, s, e, goingTwice, bt):
beenThere = bt.copy()
path = path + "-" + position
print(path)
paths = []
if position == e:
return [path]
else:
edges = findEdgesFromPosition(position, graph)
if len(edges) == 0:
print("Doodlopend ", path)
return []
for edge in edges:
if not position[0].isupper():
if goingTwice == False:
graph = removeNodeFromGraph(graph, position)
else:
if position == s:
graph = removeNodeFromGraph(graph, position)
elif position in beenThere:
print(beenThere)
print("hiephoooi", path)
goingTwice = False
for p in beenThere:
graph = removeNodeFromGraph(graph, p)
else:
beenThere.append(position)
print("Beenthere", position, path)
cedge = edge.copy()
cedge.remove(position)
nextNode = cedge[0]
print(goingTwice)
paths.extend(pathFromPosition(nextNode, graph, path, s, e, goingTwice, beenThere))
return paths
def removeNodeFromGraph (graph, position):
g = []
for edge in graph:
if position not in edge:
g.append(edge)
return g
def findEdgesFromPosition (position, graph):
edges = []
for edge in graph:
if position in edge:
edges.append(edge)
return edges
originalGraph = loadfile("test.txt")
print(originalGraph)
endPaths = pathFromPosition("start", originalGraph, "", "start", "end", False, [])
endPaths2 = pathFromPosition("start", originalGraph, "", "start", "end", True, [])
print(endPaths)
print(endPaths2)
endPaths2 = list(dict.fromkeys(endPaths2))
print("Opdracht 12a: ", len(endPaths))
print("Opdracht 12b: ", len(endPaths2))
|
def loadfile(name):
lines = []
f = open(name, 'r')
for x in f:
if x.endswith('\n'):
x = x[:-1]
lines.append(x.split('-'))
return lines
def path_from_position(position, graph, path, s, e, goingTwice, bt):
been_there = bt.copy()
path = path + '-' + position
print(path)
paths = []
if position == e:
return [path]
else:
edges = find_edges_from_position(position, graph)
if len(edges) == 0:
print('Doodlopend ', path)
return []
for edge in edges:
if not position[0].isupper():
if goingTwice == False:
graph = remove_node_from_graph(graph, position)
elif position == s:
graph = remove_node_from_graph(graph, position)
elif position in beenThere:
print(beenThere)
print('hiephoooi', path)
going_twice = False
for p in beenThere:
graph = remove_node_from_graph(graph, p)
else:
beenThere.append(position)
print('Beenthere', position, path)
cedge = edge.copy()
cedge.remove(position)
next_node = cedge[0]
print(goingTwice)
paths.extend(path_from_position(nextNode, graph, path, s, e, goingTwice, beenThere))
return paths
def remove_node_from_graph(graph, position):
g = []
for edge in graph:
if position not in edge:
g.append(edge)
return g
def find_edges_from_position(position, graph):
edges = []
for edge in graph:
if position in edge:
edges.append(edge)
return edges
original_graph = loadfile('test.txt')
print(originalGraph)
end_paths = path_from_position('start', originalGraph, '', 'start', 'end', False, [])
end_paths2 = path_from_position('start', originalGraph, '', 'start', 'end', True, [])
print(endPaths)
print(endPaths2)
end_paths2 = list(dict.fromkeys(endPaths2))
print('Opdracht 12a: ', len(endPaths))
print('Opdracht 12b: ', len(endPaths2))
|
def launch(self, Dialog, **kwargs):
# This is where the magic happens!
# The lx module is persistent so you can store stuff there
# and access it in commands.
lx._widget = Dialog
lx._widgetOptions = kwargs
# widgetWrapper creates whatever widget is set via lx._widget above
# note we're using launchScript which allows for runtime blessing
lx.eval('launchWidget')
try:
return lx._widgetInstance
except:
return None
|
def launch(self, Dialog, **kwargs):
lx._widget = Dialog
lx._widgetOptions = kwargs
lx.eval('launchWidget')
try:
return lx._widgetInstance
except:
return None
|
test = { 'name': 'q1_2',
'points': 1,
'suites': [ { 'cases': [ {'code': '>>> sum(standard_units(make_array(1,2,3,4,5))) == 0\nTrue', 'hidden': False, 'locked': False},
{'code': '>>> np.isclose(standard_units(make_array(1,2,3,4,5))[0], -1.41421356)\nTrue', 'hidden': False, 'locked': False}],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'}]}
|
test = {'name': 'q1_2', 'points': 1, 'suites': [{'cases': [{'code': '>>> sum(standard_units(make_array(1,2,3,4,5))) == 0\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> np.isclose(standard_units(make_array(1,2,3,4,5))[0], -1.41421356)\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
|
x = input()
total = 0
while x != "NoMoreMoney":
money = float(x)
if money > 0:
total += money
print(f"Increase: {money:.2f}")
x = input()
elif money < 0:
print("Invalid operation!")
break
print(f"Total: {total:.2f}")
|
x = input()
total = 0
while x != 'NoMoreMoney':
money = float(x)
if money > 0:
total += money
print(f'Increase: {money:.2f}')
x = input()
elif money < 0:
print('Invalid operation!')
break
print(f'Total: {total:.2f}')
|
#File Locations
EXTRACT_LIST_FILE = "ExtractList.xlsx"
RAW_DATA_FILE = "../../output/WorldBank/WDIData.csv"
OUTPUT_PATH = "../../output/WorldBank/split_output/"
|
extract_list_file = 'ExtractList.xlsx'
raw_data_file = '../../output/WorldBank/WDIData.csv'
output_path = '../../output/WorldBank/split_output/'
|
# https://leetcode.com/problems/lucky-numbers-in-a-matrix
def lucky_numbers(matrix):
all_lucky_numbers, all_mins = [], []
for row in matrix:
found_min, col_index = float('Inf'), -1
for index, column in enumerate(row):
if column < found_min:
found_min = column
col_index = index
all_mins.append([found_min, col_index])
for a_min in all_mins:
[min_value, min_column] = a_min
maximum = float('-Inf')
for index in range(len(matrix)):
num = matrix[index][min_column]
maximum = max(num, maximum)
if maximum == min_value:
all_lucky_numbers.append(min_value)
return all_lucky_numbers
|
def lucky_numbers(matrix):
(all_lucky_numbers, all_mins) = ([], [])
for row in matrix:
(found_min, col_index) = (float('Inf'), -1)
for (index, column) in enumerate(row):
if column < found_min:
found_min = column
col_index = index
all_mins.append([found_min, col_index])
for a_min in all_mins:
[min_value, min_column] = a_min
maximum = float('-Inf')
for index in range(len(matrix)):
num = matrix[index][min_column]
maximum = max(num, maximum)
if maximum == min_value:
all_lucky_numbers.append(min_value)
return all_lucky_numbers
|
[
[float("NaN"), float("NaN"), 66.66666667, 33.33333333, 0.0],
[float("NaN"), float("NaN"), 33.33333333, 66.66666667, 66.66666667],
[float("NaN"), float("NaN"), 0.0, 0.0, 33.33333333],
]
|
[[float('NaN'), float('NaN'), 66.66666667, 33.33333333, 0.0], [float('NaN'), float('NaN'), 33.33333333, 66.66666667, 66.66666667], [float('NaN'), float('NaN'), 0.0, 0.0, 33.33333333]]
|
encrypted_string = 'OMQEMDUEQMEK'
for i in range(1,27):
temp_str = ""
for x in encrypted_string:
int_val = ord(x) + i
if int_val > 90:
# 90 is the numerical value for 'Z'
# 65 is the numerical value for 'A'
# If int_val is greater than Z then
# the number is greater then 90 then
# we must again count the difference
# from A.
int_val = 64 + (int_val - 90)
temp_str += chr(int_val)
print(f"{i} {temp_str}")
|
encrypted_string = 'OMQEMDUEQMEK'
for i in range(1, 27):
temp_str = ''
for x in encrypted_string:
int_val = ord(x) + i
if int_val > 90:
int_val = 64 + (int_val - 90)
temp_str += chr(int_val)
print(f'{i} {temp_str}')
|
"""
Contains methods for easily persisting `Pydantic <https://pydantic-docs.helpmanual.io/>`_ data structures to and from
arbitrary storage back-ends. Contains a base class for the store behavior, as well as subclasses which allow Google
Cloud Firestore or in-memory to be used as the storage back-end. Supports saving, retrieving, and deleting records by
ID, or performing `WHERE equals` clause-based retrieval and deletion. Pydantic models that include numpy array members
are supported out of the box.
"""
|
"""
Contains methods for easily persisting `Pydantic <https://pydantic-docs.helpmanual.io/>`_ data structures to and from
arbitrary storage back-ends. Contains a base class for the store behavior, as well as subclasses which allow Google
Cloud Firestore or in-memory to be used as the storage back-end. Supports saving, retrieving, and deleting records by
ID, or performing `WHERE equals` clause-based retrieval and deletion. Pydantic models that include numpy array members
are supported out of the box.
"""
|
# -*- coding: utf-8 -*-
## \package dbr.moduleaccess
# MIT licensing
# See: docs/LICENSE.txt
## This class allows access to a 'name' attribute
#
# \param module_name
# \b \e unicode|str : Ideally set to the module's __name__ attribute
class ModuleAccessCtrl:
def __init__(self, moduleName):
self.ModuleName = moduleName
## Retrieves the module_name attribute
#
# \return
# \b \e unicode|str : Module's name
def GetModuleName(self):
return self.ModuleName
|
class Moduleaccessctrl:
def __init__(self, moduleName):
self.ModuleName = moduleName
def get_module_name(self):
return self.ModuleName
|
# ternary method
num1 = int(input('Enter the number 1::'))
num2 = int(input('\nEnter the number 2::'))
num3 = int(input('\nEnter the number 3::'))
max = (num1 if (num1 > num2 and num1 > num3) else (num2 if(num2 > num3 and num2 > num1) else num3))
print('\n\nThe maximum number is ::', max)
#with pre-define functions
# a = int(input('Enter the number A::'))
# b = int(input('\nEnter the number B::'))
# c = int(input('\nEnter the number C::'))
# print("\nThe greatest number is :: ", max(a, b, c))
# print("\nThe minimum number is:: ", min(a, b, c))
# simple method
# a = int(input('Enter the number A::'))
# b = int(input('\nEnter the number B::'))
# c = int(input('\nEnter the number C::'))
# if a > b and a > c:
# print('\n\nThe greatest is A',a)
# elif b > c and b > a:
# print('\n\nThe greatest is B::',b)
# else:
# print('\n\nThe greatest is C::', c)
|
num1 = int(input('Enter the number 1::'))
num2 = int(input('\nEnter the number 2::'))
num3 = int(input('\nEnter the number 3::'))
max = num1 if num1 > num2 and num1 > num3 else num2 if num2 > num3 and num2 > num1 else num3
print('\n\nThe maximum number is ::', max)
|
num1 = int(input())
num2 = int(input())
if(num1>=num2):
print(num1)
else:print(num2)
|
num1 = int(input())
num2 = int(input())
if num1 >= num2:
print(num1)
else:
print(num2)
|
"""
Set of test functions
so BeagleBone specific GPIO
functions can be tested
For obvious reasons these values
are ONLY for testing!
TODO:
Expand to use test values instead of set values
"""
def begin():
print("WARNING, not using actual GPIO")
def write(address, a, b):
#print("WARNING, not actual GPIO")
pass
def read(address, start, lenght):
return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
"""
Set of test functions
so BeagleBone specific GPIO
functions can be tested
For obvious reasons these values
are ONLY for testing!
TODO:
Expand to use test values instead of set values
"""
def begin():
print('WARNING, not using actual GPIO')
def write(address, a, b):
pass
def read(address, start, lenght):
return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
tasksDict = collections.Counter(tasks)
heap = []
c = 0
for k, v in tasksDict.items():
heappush(heap, (-v, k))
while heap:
i = 0
stack = []
while i <= n:
if len(heap) > 0:
index, task = heappop(heap)
if index != -1:
stack.append((index + 1, task))
c += 1
if len(heap) == 0 and len(stack) == 0:
break
i += 1
for i in stack:
heappush(heap, i)
return c
|
class Solution:
def least_interval(self, tasks: List[str], n: int) -> int:
tasks_dict = collections.Counter(tasks)
heap = []
c = 0
for (k, v) in tasksDict.items():
heappush(heap, (-v, k))
while heap:
i = 0
stack = []
while i <= n:
if len(heap) > 0:
(index, task) = heappop(heap)
if index != -1:
stack.append((index + 1, task))
c += 1
if len(heap) == 0 and len(stack) == 0:
break
i += 1
for i in stack:
heappush(heap, i)
return c
|
# Written 9/10/14 by dh4gan
# Some useful functions for classifying eigenvalues and defining structure
def classify_eigenvalue(eigenvalues, threshold):
'''Given 3 eigenvalues, and some threshold, returns an integer
'iclass' corresponding to the number of eigenvalues below the threshold
iclass = 0 --> clusters (3 +ve eigenvalues, 0 -ve)
iclass = 1 --> filaments (2 +ve eigenvalues, 1 -ve)
iclass = 2 --> sheet (1 +ve eigenvalues, 2 -ve)
iclass = 3 --> voids (0 +ve eigenvalues, 3 -ve)
'''
iclass = 0
for i in range(3):
if(eigenvalues[i]<threshold):
iclass +=1
return int(iclass)
|
def classify_eigenvalue(eigenvalues, threshold):
"""Given 3 eigenvalues, and some threshold, returns an integer
'iclass' corresponding to the number of eigenvalues below the threshold
iclass = 0 --> clusters (3 +ve eigenvalues, 0 -ve)
iclass = 1 --> filaments (2 +ve eigenvalues, 1 -ve)
iclass = 2 --> sheet (1 +ve eigenvalues, 2 -ve)
iclass = 3 --> voids (0 +ve eigenvalues, 3 -ve)
"""
iclass = 0
for i in range(3):
if eigenvalues[i] < threshold:
iclass += 1
return int(iclass)
|
# -------------------------------------------------------------------------
#
# THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
# EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
# ----------------------------------------------------------------------------------
# The example companies, organizations, products, domain names,
# e-mail addresses, logos, people, places, and events depicted
# herein are fictitious. No association with any real company,
# organization, product, domain name, email address, logo, person,
# places, or events is intended or should be inferred.
# --------------------------------------------------------------------------
# Global constant variables (Azure Storage account/Batch details)
# import "config.py" in "batch_python_tutorial_ffmpeg.py"
# Update the Batch and Storage account credential strings below with the values
# unique to your accounts. These are used when constructing connection strings
# for the Batch and Storage client objects.
_BATCH_ACCOUNT_NAME = ''
_BATCH_ACCOUNT_KEY = ''
_BATCH_ACCOUNT_URL = ''
_STORAGE_ACCOUNT_NAME = ''
_STORAGE_ACCOUNT_KEY = ''
_INPUT_BLOB_PREFIX = '' # E.g. if files in container/READS/ then put 'READS'. Keep blank if files are directly in container and not in a sub-directory
_INPUT_CONTAINER = ''
_OUTPUT_CONTAINER = ''
_POOL_ID = ''
_DEDICATED_POOL_NODE_COUNT = 0
_LOW_PRIORITY_POOL_NODE_COUNT = 1
_POOL_VM_SIZE = 'STANDARD_D64_v3'
_JOB_ID = ''
|
_batch_account_name = ''
_batch_account_key = ''
_batch_account_url = ''
_storage_account_name = ''
_storage_account_key = ''
_input_blob_prefix = ''
_input_container = ''
_output_container = ''
_pool_id = ''
_dedicated_pool_node_count = 0
_low_priority_pool_node_count = 1
_pool_vm_size = 'STANDARD_D64_v3'
_job_id = ''
|
class Solution:
def largeGroupPositions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
return [[m.start(), m.end() - 1] for m in re.finditer(r'(\w)\1{2,}', S)]
|
class Solution:
def large_group_positions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
return [[m.start(), m.end() - 1] for m in re.finditer('(\\w)\\1{2,}', S)]
|
minombre = "NaCho"
minombre = minombre.lower()
print (minombre)
for i in range(100):
print(i)
break
|
minombre = 'NaCho'
minombre = minombre.lower()
print(minombre)
for i in range(100):
print(i)
break
|
"""
Initializing the Python package
"""
__version__ = '0.31'
__all__ = (
'__version__',
)
|
"""
Initializing the Python package
"""
__version__ = '0.31'
__all__ = ('__version__',)
|
"""SQL formatting for Teradata queries."""
class SQLFormattingError(Exception):
"""Custom Exception handling for empty SQL lists."""
pass
def to_sql_list(iterable):
"""
Transform a Python list to a SQL list.
input = [a1, a2]
output = "('a1', 'a2')"
"""
if iterable:
return '(' + ', '.join("'" + str(item) + "'" for item in iterable) + ')'
else:
raise SQLFormattingError('No element in list. Cannot process IN statement.')
|
"""SQL formatting for Teradata queries."""
class Sqlformattingerror(Exception):
"""Custom Exception handling for empty SQL lists."""
pass
def to_sql_list(iterable):
"""
Transform a Python list to a SQL list.
input = [a1, a2]
output = "('a1', 'a2')"
"""
if iterable:
return '(' + ', '.join(("'" + str(item) + "'" for item in iterable)) + ')'
else:
raise sql_formatting_error('No element in list. Cannot process IN statement.')
|
class SceneManager:
def __init__(self):
self.scene_list = {}
self.current_scene = None
def append_scene(self, scene_name, scene):
self.scene_list[scene_name] = scene
def set_current_scene(self, scene_name):
self.current_scene = self.scene_list[scene_name]
class Scene:
def __init__(self, scene_manager):
self.sm = scene_manager
def handle_event(self, event):
pass
def update(self):
pass
def render(self):
pass
|
class Scenemanager:
def __init__(self):
self.scene_list = {}
self.current_scene = None
def append_scene(self, scene_name, scene):
self.scene_list[scene_name] = scene
def set_current_scene(self, scene_name):
self.current_scene = self.scene_list[scene_name]
class Scene:
def __init__(self, scene_manager):
self.sm = scene_manager
def handle_event(self, event):
pass
def update(self):
pass
def render(self):
pass
|
__all__ = ["ICCError", "CmdError", "CommError"]
class ICCError(Exception):
"""A general exception for the ICC.
Anything can throw one, passing a one line error message.
The top-level event loop will close/cleanup/destroy any running command
and return the error message on text.
"""
def __init__(self, error, details=None):
"""Create an ICCError.
Args:
error - one line of text, intended for users. Will be returned on text.
details - optional text, intended for operators/programmers.
Will be returned on debugText.
"""
self.error = error
self.details = details
if details:
self.args = (error, details)
else:
self.args = (error,)
class CmdError(Exception):
"""A exception due to commands sent to the ICC. Anything can throw one, passing a
one line error message. The top-level event loop will close/cleanup/destroy any
running command and return the error message on text.
"""
def __init__(self, error, details=None):
"""Create a CmdError.
Args:
error - one line of text, intended for users. Will be returned on text.
details - optional text, intended for operators/programmers.
Will be returned on debugText.
"""
self.error = error
self.details = details
if details:
self.args = (error, details)
else:
self.args = (error,)
class CommError(Exception):
"""An exception that specifies that a low-level communication error occurred.
These should only be thrown for serious communications errors.
The top-level event loop will close/cleanup/destroy any running command.
The error message will be returned on text.
"""
def __init__(self, device, error, details=None):
"""Create a CommError.
Args:
device - name of the device that had an error.
error - one line of text, intended for users. Will be returned on text.
details - optional text, intended for operators/programmers.
Will be returned on debugText.
"""
self.device = device
self.error = error
self.details = details
if details:
self.args = (device, error, details)
else:
self.args = (device, error)
|
__all__ = ['ICCError', 'CmdError', 'CommError']
class Iccerror(Exception):
"""A general exception for the ICC.
Anything can throw one, passing a one line error message.
The top-level event loop will close/cleanup/destroy any running command
and return the error message on text.
"""
def __init__(self, error, details=None):
"""Create an ICCError.
Args:
error - one line of text, intended for users. Will be returned on text.
details - optional text, intended for operators/programmers.
Will be returned on debugText.
"""
self.error = error
self.details = details
if details:
self.args = (error, details)
else:
self.args = (error,)
class Cmderror(Exception):
"""A exception due to commands sent to the ICC. Anything can throw one, passing a
one line error message. The top-level event loop will close/cleanup/destroy any
running command and return the error message on text.
"""
def __init__(self, error, details=None):
"""Create a CmdError.
Args:
error - one line of text, intended for users. Will be returned on text.
details - optional text, intended for operators/programmers.
Will be returned on debugText.
"""
self.error = error
self.details = details
if details:
self.args = (error, details)
else:
self.args = (error,)
class Commerror(Exception):
"""An exception that specifies that a low-level communication error occurred.
These should only be thrown for serious communications errors.
The top-level event loop will close/cleanup/destroy any running command.
The error message will be returned on text.
"""
def __init__(self, device, error, details=None):
"""Create a CommError.
Args:
device - name of the device that had an error.
error - one line of text, intended for users. Will be returned on text.
details - optional text, intended for operators/programmers.
Will be returned on debugText.
"""
self.device = device
self.error = error
self.details = details
if details:
self.args = (device, error, details)
else:
self.args = (device, error)
|
class Solution:
def binary_search(self, array, val):
index = bisect_left(array, val)
if index != len(array) and array[index] == val:
return index
else:
return -1
def smallestCommonElement(self, mat: List[List[int]]) -> int:
values = mat[0]
mat.pop(0)
for i, val in enumerate(values):
flag = True
for arr in mat:
idx = self.binary_search(arr, val)
if idx == -1:
flag = False
break
if flag:
return val
return -1
|
class Solution:
def binary_search(self, array, val):
index = bisect_left(array, val)
if index != len(array) and array[index] == val:
return index
else:
return -1
def smallest_common_element(self, mat: List[List[int]]) -> int:
values = mat[0]
mat.pop(0)
for (i, val) in enumerate(values):
flag = True
for arr in mat:
idx = self.binary_search(arr, val)
if idx == -1:
flag = False
break
if flag:
return val
return -1
|
# This problem was asked by Facebook.
# Given a binary tree, return all paths from the root to leaves.
# For example, given the tree
# 1
# / \
# 2 3
# / \
# 4 5
# it should return [[1, 2], [1, 3, 4], [1, 3, 5]].
####
class Node:
def __init__(self, val = None, left = None, right = None):
self.val = val
self.left = left
self.right = right
l1 = Node(5)
l2 = Node(3)
l3 = Node(7)
l4 = Node(4)
m1 = Node(2, l1, l2)
m2 = Node(1, l3, l4)
root = Node(6, m1, m2)
####
def paths(root):
# if no node, it does not contribute to the path
if not root:
return []
# if leaf node, return node as is
if not root.left and not root.right:
return [[root.val]]
# generate paths to the left and right of current node
p = paths(root.left) + paths(root.right)
# prepend current value to generated paths
p = [[root.val] + p[i] for i in range(len(p))]
return p
####
print(paths(root))
|
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
l1 = node(5)
l2 = node(3)
l3 = node(7)
l4 = node(4)
m1 = node(2, l1, l2)
m2 = node(1, l3, l4)
root = node(6, m1, m2)
def paths(root):
if not root:
return []
if not root.left and (not root.right):
return [[root.val]]
p = paths(root.left) + paths(root.right)
p = [[root.val] + p[i] for i in range(len(p))]
return p
print(paths(root))
|
class ApiConfig:
api_key = None
api_base = 'https://www.quandl.com/api/v3'
api_version = None
page_limit = 100
|
class Apiconfig:
api_key = None
api_base = 'https://www.quandl.com/api/v3'
api_version = None
page_limit = 100
|
_BEGIN = 0
ZERO=0
RAND=1
_END = 10
|
_begin = 0
zero = 0
rand = 1
_end = 10
|
# -*- coding: utf-8 -*-
def main():
n, d = map(int, input().split())
s = [input() for _ in range(d)]
ans = 0
for i in range(d):
for j in range(i, d):
if i != j:
count = 0
for si, sj in zip(s[i], s[j]):
if si == 'o' or sj == 'o':
count += 1
ans = max(ans, count)
print(ans)
if __name__ == '__main__':
main()
|
def main():
(n, d) = map(int, input().split())
s = [input() for _ in range(d)]
ans = 0
for i in range(d):
for j in range(i, d):
if i != j:
count = 0
for (si, sj) in zip(s[i], s[j]):
if si == 'o' or sj == 'o':
count += 1
ans = max(ans, count)
print(ans)
if __name__ == '__main__':
main()
|
TOPIC = "test.mosquitto.org"
# Temperature and umidity publish interval (seconds)
DATA_PUBLISH_INTERVAL = 5
# Data amount needed to start processing (reset after)
DATA_PROCESS_AMOUNT = 5
# Percentage of mean temperature which will be sent to the air conditioner
AIR_CONDITIONER_PERCENTAGE = 0.8
# Humidity below this level will turn the humidifier on
HUMIDIFIER_LOWER_THRESHOLD = 50
# Humidity above this level will turn the humidifier off
HUMIDIFIER_UPPER_THRESHOLD = 80
|
topic = 'test.mosquitto.org'
data_publish_interval = 5
data_process_amount = 5
air_conditioner_percentage = 0.8
humidifier_lower_threshold = 50
humidifier_upper_threshold = 80
|
PAGINATE_MODULES = {
"Leads": {
"stream_name": "leads",
"module_name": "Leads",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Deals": {
"stream_name": "deals",
"module_name": "Deals",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Contacts": {
"stream_name": "contacts",
"module_name": "Contacts",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Accounts": {
"stream_name": "accounts",
"module_name": "Accounts",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Tasks": {
"stream_name": "tasks",
"module_name": "Tasks",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Events": {
"stream_name": "events",
"module_name": "Events",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Calls": {
"stream_name": "calls",
"module_name": "Calls",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Activities": {
"stream_name": "activities",
"module_name": "Activities",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Visits": {
"stream_name": "visits",
"module_name": "Visits",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Invoices": {
"stream_name": "invoices",
"module_name": "Invoices",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Notes": {
"stream_name": "notes",
"module_name": "Notes",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Attachments": {
"stream_name": "attachments",
"module_name": "Attachments",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
"Lead_Status_History": {
"stream_name": "lead_status_history",
"module_name": "Lead_Status_History",
"params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"},
"bookmark_key": "Modified_Time",
},
}
NON_PAGINATE_MODULES = {
"org": {
"module_name": "org",
"stream_name": "org_settings",
},
"settings/stages": {
"module_name": "settings/stages",
"stream_name": "settings_stages",
"params": {"module": "Deals"},
},
}
KNOWN_SUBMODULES = {
"Deals": [
{
"module_name": "Stage_History",
"stream_name": "deals_stage_history",
"bookmark_key": "Last_Modified_Time",
}
]
}
|
paginate_modules = {'Leads': {'stream_name': 'leads', 'module_name': 'Leads', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Deals': {'stream_name': 'deals', 'module_name': 'Deals', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Contacts': {'stream_name': 'contacts', 'module_name': 'Contacts', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Accounts': {'stream_name': 'accounts', 'module_name': 'Accounts', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Tasks': {'stream_name': 'tasks', 'module_name': 'Tasks', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Events': {'stream_name': 'events', 'module_name': 'Events', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Calls': {'stream_name': 'calls', 'module_name': 'Calls', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Activities': {'stream_name': 'activities', 'module_name': 'Activities', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Visits': {'stream_name': 'visits', 'module_name': 'Visits', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Invoices': {'stream_name': 'invoices', 'module_name': 'Invoices', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Notes': {'stream_name': 'notes', 'module_name': 'Notes', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Attachments': {'stream_name': 'attachments', 'module_name': 'Attachments', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}, 'Lead_Status_History': {'stream_name': 'lead_status_history', 'module_name': 'Lead_Status_History', 'params': {'per_page': 200, 'sort_by': 'Modified_Time', 'sort_order': 'asc'}, 'bookmark_key': 'Modified_Time'}}
non_paginate_modules = {'org': {'module_name': 'org', 'stream_name': 'org_settings'}, 'settings/stages': {'module_name': 'settings/stages', 'stream_name': 'settings_stages', 'params': {'module': 'Deals'}}}
known_submodules = {'Deals': [{'module_name': 'Stage_History', 'stream_name': 'deals_stage_history', 'bookmark_key': 'Last_Modified_Time'}]}
|
for arquivo in os.listdir(caminho):
caminho_completo = os.path.join(caminho, arquivo)
#zip.write(caminho_completo, arquivo)
print(caminho_completo)
|
for arquivo in os.listdir(caminho):
caminho_completo = os.path.join(caminho, arquivo)
print(caminho_completo)
|
class Utils:
def __init__(self, data_immigration=None, data_temp=None, data_us_dem=None, data_airport=None):
self.data_immigration = data_immigration
self.data_temp = data_temp
self.data_us_dem = data_us_dem
self.data_airport = data_airport
@staticmethod
def process_immigration_data(self):
"""
Pre-Process US immigration dataframe and return
"""
total_records = self.count()
print(f'Total records in immigration dataframe: {total_records:,}')
# From EDA we found our certain columns has 80+% missing data points and hence we drop them
drop_cols = ['occup', 'entdepu', 'insnum']
df = self.data_immigration.drop(*drop_cols)
# drop rows where all elements are missing
df.dropna(how='all', inplace=True)
new_total_records = df.count()
print(f'Total records after cleaning immigration data: {new_total_records:,}')
return df
def process_temp_data(self):
"""
Process global temperatures dataset, handle duplicate values for specific columns
"""
# drop rows with missing average temperature
df = self.data_temp.dropna(subset=['AverageTemperature'])
# drop duplicate rows
df.drop_duplicates(subset=['dt', 'City', 'Country'], inplace=True)
return df
def process_us_demographic_data(self):
"""
Clean and preprocess the US demographics dataset
"""
# drop rows with missing values
subset_cols = [
'Male Population',
'Female Population',
'Number of Veterans',
'Foreign-born',
'Average Household Size'
]
df_us_dem = self.data_us_dem.dropna(subset=subset_cols)
# drop duplicate columns
df_us_dem.dropDuplicates(subset=['City', 'State', 'State Code', 'Race'], inplace=True)
rows_dropped_with_duplicates = self.data_us_dem.count() - df_us_dem.count()
print(f"Total no. of Rows removed after preprocessing : {rows_dropped_with_duplicates}")
return df_us_dem
# As we saw from the EDA , Iata_code column has 80% + null values, hence we will be dropping that column
# drop rows with missing values
def process_air_traffic_data(self):
"""
Clean the US demographics dataset
"""
# drop rows with missing values
drop_cols = ["iata_code"]
subset_cols = ['gps_code', 'local_code']
df_airport = self.data_airport
data_airport = self.data_airport.drop_duplicates(subset=subset_cols, inplace=True)
data_airport.drop(labels=drop_cols, axis=1, inplace=True)
print(f"Total number of rows removed after processing data : {df_airport.shape[0] - data_airport.shape[0]}")
return data_airport
|
class Utils:
def __init__(self, data_immigration=None, data_temp=None, data_us_dem=None, data_airport=None):
self.data_immigration = data_immigration
self.data_temp = data_temp
self.data_us_dem = data_us_dem
self.data_airport = data_airport
@staticmethod
def process_immigration_data(self):
"""
Pre-Process US immigration dataframe and return
"""
total_records = self.count()
print(f'Total records in immigration dataframe: {total_records:,}')
drop_cols = ['occup', 'entdepu', 'insnum']
df = self.data_immigration.drop(*drop_cols)
df.dropna(how='all', inplace=True)
new_total_records = df.count()
print(f'Total records after cleaning immigration data: {new_total_records:,}')
return df
def process_temp_data(self):
"""
Process global temperatures dataset, handle duplicate values for specific columns
"""
df = self.data_temp.dropna(subset=['AverageTemperature'])
df.drop_duplicates(subset=['dt', 'City', 'Country'], inplace=True)
return df
def process_us_demographic_data(self):
"""
Clean and preprocess the US demographics dataset
"""
subset_cols = ['Male Population', 'Female Population', 'Number of Veterans', 'Foreign-born', 'Average Household Size']
df_us_dem = self.data_us_dem.dropna(subset=subset_cols)
df_us_dem.dropDuplicates(subset=['City', 'State', 'State Code', 'Race'], inplace=True)
rows_dropped_with_duplicates = self.data_us_dem.count() - df_us_dem.count()
print(f'Total no. of Rows removed after preprocessing : {rows_dropped_with_duplicates}')
return df_us_dem
def process_air_traffic_data(self):
"""
Clean the US demographics dataset
"""
drop_cols = ['iata_code']
subset_cols = ['gps_code', 'local_code']
df_airport = self.data_airport
data_airport = self.data_airport.drop_duplicates(subset=subset_cols, inplace=True)
data_airport.drop(labels=drop_cols, axis=1, inplace=True)
print(f'Total number of rows removed after processing data : {df_airport.shape[0] - data_airport.shape[0]}')
return data_airport
|
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: (x[0], -x[1]))
count = 0
end = -1
for a, b in intervals:
if b > end:
count += 1
end = b
return count
|
class Solution:
def remove_covered_intervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: (x[0], -x[1]))
count = 0
end = -1
for (a, b) in intervals:
if b > end:
count += 1
end = b
return count
|
def comb(n, k):
nCk = 1
MOD = 10**9+7
for i in range(n-k+1, n+1):
nCk *= i
nCk %= MOD
for i in range(1, k+1):
nCk *= pow(i, MOD-2, MOD)
nCk %= MOD
return nCk
n, a, b = map(int, input().split())
mod = 10**9+7
ans = pow(2, n, mod)-1-comb(n, a)-comb(n, b)
print(ans % mod)
|
def comb(n, k):
n_ck = 1
mod = 10 ** 9 + 7
for i in range(n - k + 1, n + 1):
n_ck *= i
n_ck %= MOD
for i in range(1, k + 1):
n_ck *= pow(i, MOD - 2, MOD)
n_ck %= MOD
return nCk
(n, a, b) = map(int, input().split())
mod = 10 ** 9 + 7
ans = pow(2, n, mod) - 1 - comb(n, a) - comb(n, b)
print(ans % mod)
|
dict1={1:"John",2:"Bob",3:"Bill"}
print(dict1)
print(dict1.items())
k=dict1.keys()
for key in k:
print(key)
v=dict1.values()
for value in v:
print(value)
print(dict1[3])
del dict1[2]
print(dict1)
|
dict1 = {1: 'John', 2: 'Bob', 3: 'Bill'}
print(dict1)
print(dict1.items())
k = dict1.keys()
for key in k:
print(key)
v = dict1.values()
for value in v:
print(value)
print(dict1[3])
del dict1[2]
print(dict1)
|
"""
/github/enums/repositorysubscription.py
Copyright (c) 2019-2020 ShineyDev
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.
"""
class RepositorySubscription():
"""
Represents a user's subscription state.
https://developer.github.com/v4/enum/subscriptionstate/
"""
__slots__ = ("_subscription",)
def __init__(self, subscription):
self._subscription = subscription
def __repr__(self) -> str:
return "<{0.__class__.__name__} '{0._subscription}'>".format(self)
@classmethod
def from_data(cls, subscription):
return cls(subscription)
@property
def ignored(self) -> bool:
"""
The user is never notified.
"""
return self._subscription == "IGNORED"
@property
def subscribed(self) -> bool:
"""
The user is notified of all conversations.
"""
return self._subscription == "SUBSCRIBED"
@property
def unsubscribed(self) -> bool:
"""
The user is only notified when participating or mentioned.
"""
return self._subscription == "UNSUBSCRIBED"
|
"""
/github/enums/repositorysubscription.py
Copyright (c) 2019-2020 ShineyDev
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.
"""
class Repositorysubscription:
"""
Represents a user's subscription state.
https://developer.github.com/v4/enum/subscriptionstate/
"""
__slots__ = ('_subscription',)
def __init__(self, subscription):
self._subscription = subscription
def __repr__(self) -> str:
return "<{0.__class__.__name__} '{0._subscription}'>".format(self)
@classmethod
def from_data(cls, subscription):
return cls(subscription)
@property
def ignored(self) -> bool:
"""
The user is never notified.
"""
return self._subscription == 'IGNORED'
@property
def subscribed(self) -> bool:
"""
The user is notified of all conversations.
"""
return self._subscription == 'SUBSCRIBED'
@property
def unsubscribed(self) -> bool:
"""
The user is only notified when participating or mentioned.
"""
return self._subscription == 'UNSUBSCRIBED'
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# lzma_sdk for standalone build.
{
'targets': [
{
'target_name': 'ots_lzma_sdk',
'type': 'static_library',
'defines': [
'_7ZIP_ST', # Disable multi-thread support.
'_LZMA_PROB32', # This could increase the speed on 32bit platform.
],
'sources': [
'Alloc.c',
'Alloc.h',
'LzFind.c',
'LzFind.h',
'LzHash.h',
'LzmaEnc.c',
'LzmaEnc.h',
'LzmaDec.c',
'LzmaDec.h',
'LzmaLib.c',
'LzmaLib.h',
'Types.h',
],
'include_dirs': [
'.',
],
'direct_dependent_settings': {
'include_dirs': [
'../..',
],
},
},
],
}
|
{'targets': [{'target_name': 'ots_lzma_sdk', 'type': 'static_library', 'defines': ['_7ZIP_ST', '_LZMA_PROB32'], 'sources': ['Alloc.c', 'Alloc.h', 'LzFind.c', 'LzFind.h', 'LzHash.h', 'LzmaEnc.c', 'LzmaEnc.h', 'LzmaDec.c', 'LzmaDec.h', 'LzmaLib.c', 'LzmaLib.h', 'Types.h'], 'include_dirs': ['.'], 'direct_dependent_settings': {'include_dirs': ['../..']}}]}
|
"""
Given an integer n. Each number from 1 to n is grouped according to the sum of its digits.
Return how many groups have the largest size.
"""
class Solution:
def countLargestGroup(self, n: int) -> int:
def sum_digits(integer):
tot = 0
while integer:
tot += integer % 10
integer = integer // 10
return tot
counter = dict()
for i in range(1, n + 1):
tot = sum_digits(i)
if tot in counter:
counter[tot] += 1
else:
counter[tot] = 1
largest_group = 1
count = 0
for key in counter.keys():
if counter[key] == largest_group:
count += 1
elif counter[key] > largest_group:
count = 1
largest_group = counter[key]
return count
|
"""
Given an integer n. Each number from 1 to n is grouped according to the sum of its digits.
Return how many groups have the largest size.
"""
class Solution:
def count_largest_group(self, n: int) -> int:
def sum_digits(integer):
tot = 0
while integer:
tot += integer % 10
integer = integer // 10
return tot
counter = dict()
for i in range(1, n + 1):
tot = sum_digits(i)
if tot in counter:
counter[tot] += 1
else:
counter[tot] = 1
largest_group = 1
count = 0
for key in counter.keys():
if counter[key] == largest_group:
count += 1
elif counter[key] > largest_group:
count = 1
largest_group = counter[key]
return count
|
# Create a sequence where each element is an individual base of DNA.
# Make the array 15 bases long.
bases = 'ATTCGGTCATGCTAA'
# Print the length of the sequence
print("DNA sequence length:", len(bases))
# Create a for loop to output every base of the sequence on a new line.
print("All bases:")
for base in bases:
print(base)
|
bases = 'ATTCGGTCATGCTAA'
print('DNA sequence length:', len(bases))
print('All bases:')
for base in bases:
print(base)
|
# Team 5
def save_to_json(datatables: list, directory=None):
pass
def open_json():
pass
|
def save_to_json(datatables: list, directory=None):
pass
def open_json():
pass
|
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Pbr_01_ape.py"
OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmPbr_SO/duck"
DATASETS = dict(TRAIN=("lm_pbr_duck_train",), TEST=("lm_real_duck_test",))
# bbnc6
# objects duck Avg(1)
# ad_2 4.23 4.23
# ad_5 26.01 26.01
# ad_10 61.88 61.88
# rete_2 54.37 54.37
# rete_5 97.28 97.28
# rete_10 100.00 100.00
# re_2 59.15 59.15
# re_5 97.28 97.28
# re_10 100.00 100.00
# te_2 89.67 89.67
# te_5 100.00 100.00
# te_10 100.00 100.00
# proj_2 85.63 85.63
# proj_5 98.22 98.22
# proj_10 99.91 99.91
# re 2.02 2.02
# te 0.01 0.01
|
_base_ = './FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Pbr_01_ape.py'
output_dir = 'output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmPbr_SO/duck'
datasets = dict(TRAIN=('lm_pbr_duck_train',), TEST=('lm_real_duck_test',))
|
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
temp = [0] * len(nums)
def mergeSort(start, end):
if start < end:
mid = (start + end) // 2
mergeSort(start, mid)
mergeSort(mid + 1, end)
i = k = start
j = mid + 1
while i <= mid:
while j <= end and nums[j] < nums[i]:
temp[k] = nums[j]
j += 1
k += 1
temp[k] = nums[i]
i += 1
k += 1
while j <= end:
temp[k] = nums[j]
j += 1
k += 1
nums[start: end + 1] = temp[start: end + 1]
mergeSort(0, len(nums) - 1)
return nums
|
class Solution:
def sort_array(self, nums: List[int]) -> List[int]:
temp = [0] * len(nums)
def merge_sort(start, end):
if start < end:
mid = (start + end) // 2
merge_sort(start, mid)
merge_sort(mid + 1, end)
i = k = start
j = mid + 1
while i <= mid:
while j <= end and nums[j] < nums[i]:
temp[k] = nums[j]
j += 1
k += 1
temp[k] = nums[i]
i += 1
k += 1
while j <= end:
temp[k] = nums[j]
j += 1
k += 1
nums[start:end + 1] = temp[start:end + 1]
merge_sort(0, len(nums) - 1)
return nums
|
class Foo0():
def __init__(self):
pass
foo1 = Foo0()
class Foo0(): ## error: redefined class
def __init__(self, a):
pass
foo2 = Foo0()
|
class Foo0:
def __init__(self):
pass
foo1 = foo0()
class Foo0:
def __init__(self, a):
pass
foo2 = foo0()
|
# List of possible Pokemon types
types = [
"Normal", "Fire", "Water", "Electric", "Grass", "Ice", "Fighting", "Poison", "Ground", "Flying", "Psychic", "Bug", "Rock", "Ghost", "Dragon", "Dark", "Steel", "Fairy"
]
# Chart of type weaknesses. type_dict["Water"]["Fire"] assumes water is attacking fire.
type_dict = {"Normal": {"Normal":1, "Fire":1, "Water":1, "Electric":1, "Grass":1, "Ice":1, "Fighting":1, "Poison":1, "Ground":1, "Flying":1, "Psychic":1, "Bug":1, "Rock":0.5, "Ghost":0, "Dragon":1, "Dark":1, "Steel":0.5, "Fairy":1},
"Fire": {"Normal":1, "Fire":0.5, "Water":0.5, "Electric":1, "Grass":2, "Ice":2, "Fighting":1, "Poison":1, "Ground":1, "Flying":1, "Psychic":1, "Bug":2, "Rock":0.5, "Ghost":1, "Dragon":0.5, "Dark":1, "Steel":2, "Fairy":1},
"Water": {"Normal":1, "Fire":2, "Water":0.5, "Electric":1, "Grass":0.5, "Ice":1, "Fighting":1, "Poison":1, "Ground":2, "Flying":1, "Psychic":1, "Bug":1, "Rock":2, "Ghost":1, "Dragon":0.5, "Dark":1, "Steel":1, "Fairy":1},
"Electric": {"Normal":1, "Fire":1, "Water":2, "Electric":0.5, "Grass":0.5, "Ice":1, "Fighting":1, "Poison":1, "Ground":0, "Flying":2, "Psychic":1, "Bug":1, "Rock":1, "Ghost":1, "Dragon":0.5, "Dark":1, "Steel":1, "Fairy":1},
"Grass": {"Normal":1, "Fire":0.5, "Water":2, "Electric":1, "Grass":0.5, "Ice":1, "Fighting":1, "Poison":0.5, "Ground":2, "Flying":0.5, "Psychic":1, "Bug":0.5, "Rock":2, "Ghost":1, "Dragon":0.5, "Dark":1, "Steel":0.5, "Fairy":1},
"Ice": {"Normal":1, "Fire":0.5, "Water":0.5, "Electric":1, "Grass":2, "Ice":0.5, "Fighting":1, "Poison":1, "Ground":2, "Flying":2, "Psychic":1, "Bug":1, "Rock":1, "Ghost":1, "Dragon":2, "Dark":1, "Steel":0.5, "Fairy":1},
"Fighting": {"Normal":2, "Fire":1, "Water":1, "Electric":1, "Grass":1, "Ice":2, "Fighting":1, "Poison":0.5, "Ground":2, "Flying":0.5, "Psychic":0.5, "Bug":0.5, "Rock":2, "Ghost":0, "Dragon":1, "Dark":2, "Steel":2, "Fairy":0.5},
"Poison": {"Normal":1, "Fire":1, "Water":1, "Electric":1, "Grass":2, "Ice":1, "Fighting":1, "Poison":0.5, "Ground":0.5, "Flying":1, "Psychic":1, "Bug":1, "Rock":0.5, "Ghost":0.5, "Dragon":1, "Dark":1, "Steel":0, "Fairy":2},
"Ground": {"Normal":1, "Fire":2, "Water":1, "Electric":2, "Grass":0.5, "Ice":1, "Fighting":1, "Poison":2, "Ground":1, "Flying":0, "Psychic":1, "Bug":0.5, "Rock":2, "Ghost":1, "Dragon":1, "Dark":1, "Steel":2, "Fairy":1},
"Flying": {"Normal":1, "Fire":1, "Water":1, "Electric":0.5, "Grass":2, "Ice":1, "Fighting":2, "Poison":1, "Ground":1, "Flying":1, "Psychic":1, "Bug":2, "Rock":0.5, "Ghost":1, "Dragon":1, "Dark":1, "Steel":0.5, "Fairy":1},
"Psychic": {"Normal":1, "Fire":1, "Water":1, "Electric":1, "Grass":1, "Ice":1, "Fighting":2, "Poison":2, "Ground":1, "Flying":1, "Psychic":0.5, "Bug":1, "Rock":1, "Ghost":1, "Dragon":1, "Dark":0, "Steel":0.5, "Fairy":1},
"Bug": {"Normal":1, "Fire":0.5, "Water":1, "Electric":1, "Grass":2, "Ice":1, "Fighting":0.5, "Poison":0.5, "Ground":1, "Flying":0.5, "Psychic":2, "Bug":1, "Rock":1, "Ghost":0.5, "Dragon":1, "Dark":2, "Steel":0.5, "Fairy":0.5},
"Rock": {"Normal":1, "Fire":2, "Water":1, "Electric":1, "Grass":1, "Ice":2, "Fighting":0.5, "Poison":1, "Ground":0.5, "Flying":2, "Psychic":1, "Bug":2, "Rock":1, "Ghost":1, "Dragon":1, "Dark":1, "Steel":0.5, "Fairy":1},
"Ghost": {"Normal":0, "Fire":1, "Water":1, "Electric":1, "Grass":1, "Ice":1, "Fighting":1, "Poison":1, "Ground":1, "Flying":1, "Psychic":2, "Bug":1, "Rock":1, "Ghost":2, "Dragon":1, "Dark":0.5, "Steel":1, "Fairy":1},
"Dragon": {"Normal":1, "Fire":1, "Water":1, "Electric":1, "Grass":1, "Ice":1, "Fighting":1, "Poison":1, "Ground":1, "Flying":1, "Psychic":1, "Bug":1, "Rock":1, "Ghost":1, "Dragon":2, "Dark":1, "Steel":0.5, "Fairy":0},
"Dark": {"Normal":1, "Fire":1, "Water":1, "Electric":1, "Grass":1, "Ice":1, "Fighting":0.5, "Poison":1, "Ground":1, "Flying":1, "Psychic":2, "Bug":1, "Rock":1, "Ghost":2, "Dragon":1, "Dark":0.5, "Steel":1, "Fairy":0.5},
"Steel": {"Normal":1, "Fire":0.5, "Water":0.5, "Electric":0.5, "Grass":1, "Ice":2, "Fighting":1, "Poison":1, "Ground":1, "Flying":1, "Psychic":1, "Bug":1, "Rock":2, "Ghost":1, "Dragon":1, "Dark":1, "Steel":0.5, "Fairy":1},
"Fairy": {"Normal":1, "Fire":0.5, "Water":1, "Electric":1, "Grass":1, "Ice":1, "Fighting":2, "Poison":0.5, "Ground":1, "Flying":1, "Psychic":1, "Bug":1, "Rock":1, "Ghost":1, "Dragon":2, "Dark":2, "Steel":0.5, "Fairy":1}
}
|
types = ['Normal', 'Fire', 'Water', 'Electric', 'Grass', 'Ice', 'Fighting', 'Poison', 'Ground', 'Flying', 'Psychic', 'Bug', 'Rock', 'Ghost', 'Dragon', 'Dark', 'Steel', 'Fairy']
type_dict = {'Normal': {'Normal': 1, 'Fire': 1, 'Water': 1, 'Electric': 1, 'Grass': 1, 'Ice': 1, 'Fighting': 1, 'Poison': 1, 'Ground': 1, 'Flying': 1, 'Psychic': 1, 'Bug': 1, 'Rock': 0.5, 'Ghost': 0, 'Dragon': 1, 'Dark': 1, 'Steel': 0.5, 'Fairy': 1}, 'Fire': {'Normal': 1, 'Fire': 0.5, 'Water': 0.5, 'Electric': 1, 'Grass': 2, 'Ice': 2, 'Fighting': 1, 'Poison': 1, 'Ground': 1, 'Flying': 1, 'Psychic': 1, 'Bug': 2, 'Rock': 0.5, 'Ghost': 1, 'Dragon': 0.5, 'Dark': 1, 'Steel': 2, 'Fairy': 1}, 'Water': {'Normal': 1, 'Fire': 2, 'Water': 0.5, 'Electric': 1, 'Grass': 0.5, 'Ice': 1, 'Fighting': 1, 'Poison': 1, 'Ground': 2, 'Flying': 1, 'Psychic': 1, 'Bug': 1, 'Rock': 2, 'Ghost': 1, 'Dragon': 0.5, 'Dark': 1, 'Steel': 1, 'Fairy': 1}, 'Electric': {'Normal': 1, 'Fire': 1, 'Water': 2, 'Electric': 0.5, 'Grass': 0.5, 'Ice': 1, 'Fighting': 1, 'Poison': 1, 'Ground': 0, 'Flying': 2, 'Psychic': 1, 'Bug': 1, 'Rock': 1, 'Ghost': 1, 'Dragon': 0.5, 'Dark': 1, 'Steel': 1, 'Fairy': 1}, 'Grass': {'Normal': 1, 'Fire': 0.5, 'Water': 2, 'Electric': 1, 'Grass': 0.5, 'Ice': 1, 'Fighting': 1, 'Poison': 0.5, 'Ground': 2, 'Flying': 0.5, 'Psychic': 1, 'Bug': 0.5, 'Rock': 2, 'Ghost': 1, 'Dragon': 0.5, 'Dark': 1, 'Steel': 0.5, 'Fairy': 1}, 'Ice': {'Normal': 1, 'Fire': 0.5, 'Water': 0.5, 'Electric': 1, 'Grass': 2, 'Ice': 0.5, 'Fighting': 1, 'Poison': 1, 'Ground': 2, 'Flying': 2, 'Psychic': 1, 'Bug': 1, 'Rock': 1, 'Ghost': 1, 'Dragon': 2, 'Dark': 1, 'Steel': 0.5, 'Fairy': 1}, 'Fighting': {'Normal': 2, 'Fire': 1, 'Water': 1, 'Electric': 1, 'Grass': 1, 'Ice': 2, 'Fighting': 1, 'Poison': 0.5, 'Ground': 2, 'Flying': 0.5, 'Psychic': 0.5, 'Bug': 0.5, 'Rock': 2, 'Ghost': 0, 'Dragon': 1, 'Dark': 2, 'Steel': 2, 'Fairy': 0.5}, 'Poison': {'Normal': 1, 'Fire': 1, 'Water': 1, 'Electric': 1, 'Grass': 2, 'Ice': 1, 'Fighting': 1, 'Poison': 0.5, 'Ground': 0.5, 'Flying': 1, 'Psychic': 1, 'Bug': 1, 'Rock': 0.5, 'Ghost': 0.5, 'Dragon': 1, 'Dark': 1, 'Steel': 0, 'Fairy': 2}, 'Ground': {'Normal': 1, 'Fire': 2, 'Water': 1, 'Electric': 2, 'Grass': 0.5, 'Ice': 1, 'Fighting': 1, 'Poison': 2, 'Ground': 1, 'Flying': 0, 'Psychic': 1, 'Bug': 0.5, 'Rock': 2, 'Ghost': 1, 'Dragon': 1, 'Dark': 1, 'Steel': 2, 'Fairy': 1}, 'Flying': {'Normal': 1, 'Fire': 1, 'Water': 1, 'Electric': 0.5, 'Grass': 2, 'Ice': 1, 'Fighting': 2, 'Poison': 1, 'Ground': 1, 'Flying': 1, 'Psychic': 1, 'Bug': 2, 'Rock': 0.5, 'Ghost': 1, 'Dragon': 1, 'Dark': 1, 'Steel': 0.5, 'Fairy': 1}, 'Psychic': {'Normal': 1, 'Fire': 1, 'Water': 1, 'Electric': 1, 'Grass': 1, 'Ice': 1, 'Fighting': 2, 'Poison': 2, 'Ground': 1, 'Flying': 1, 'Psychic': 0.5, 'Bug': 1, 'Rock': 1, 'Ghost': 1, 'Dragon': 1, 'Dark': 0, 'Steel': 0.5, 'Fairy': 1}, 'Bug': {'Normal': 1, 'Fire': 0.5, 'Water': 1, 'Electric': 1, 'Grass': 2, 'Ice': 1, 'Fighting': 0.5, 'Poison': 0.5, 'Ground': 1, 'Flying': 0.5, 'Psychic': 2, 'Bug': 1, 'Rock': 1, 'Ghost': 0.5, 'Dragon': 1, 'Dark': 2, 'Steel': 0.5, 'Fairy': 0.5}, 'Rock': {'Normal': 1, 'Fire': 2, 'Water': 1, 'Electric': 1, 'Grass': 1, 'Ice': 2, 'Fighting': 0.5, 'Poison': 1, 'Ground': 0.5, 'Flying': 2, 'Psychic': 1, 'Bug': 2, 'Rock': 1, 'Ghost': 1, 'Dragon': 1, 'Dark': 1, 'Steel': 0.5, 'Fairy': 1}, 'Ghost': {'Normal': 0, 'Fire': 1, 'Water': 1, 'Electric': 1, 'Grass': 1, 'Ice': 1, 'Fighting': 1, 'Poison': 1, 'Ground': 1, 'Flying': 1, 'Psychic': 2, 'Bug': 1, 'Rock': 1, 'Ghost': 2, 'Dragon': 1, 'Dark': 0.5, 'Steel': 1, 'Fairy': 1}, 'Dragon': {'Normal': 1, 'Fire': 1, 'Water': 1, 'Electric': 1, 'Grass': 1, 'Ice': 1, 'Fighting': 1, 'Poison': 1, 'Ground': 1, 'Flying': 1, 'Psychic': 1, 'Bug': 1, 'Rock': 1, 'Ghost': 1, 'Dragon': 2, 'Dark': 1, 'Steel': 0.5, 'Fairy': 0}, 'Dark': {'Normal': 1, 'Fire': 1, 'Water': 1, 'Electric': 1, 'Grass': 1, 'Ice': 1, 'Fighting': 0.5, 'Poison': 1, 'Ground': 1, 'Flying': 1, 'Psychic': 2, 'Bug': 1, 'Rock': 1, 'Ghost': 2, 'Dragon': 1, 'Dark': 0.5, 'Steel': 1, 'Fairy': 0.5}, 'Steel': {'Normal': 1, 'Fire': 0.5, 'Water': 0.5, 'Electric': 0.5, 'Grass': 1, 'Ice': 2, 'Fighting': 1, 'Poison': 1, 'Ground': 1, 'Flying': 1, 'Psychic': 1, 'Bug': 1, 'Rock': 2, 'Ghost': 1, 'Dragon': 1, 'Dark': 1, 'Steel': 0.5, 'Fairy': 1}, 'Fairy': {'Normal': 1, 'Fire': 0.5, 'Water': 1, 'Electric': 1, 'Grass': 1, 'Ice': 1, 'Fighting': 2, 'Poison': 0.5, 'Ground': 1, 'Flying': 1, 'Psychic': 1, 'Bug': 1, 'Rock': 1, 'Ghost': 1, 'Dragon': 2, 'Dark': 2, 'Steel': 0.5, 'Fairy': 1}}
|
class Solution:
def checkValidString(self, s: str) -> bool:
left_count = 0
star_count = 0
for char in s:
if char == '(':
left_count += 1
elif char == '*':
star_count += 1
else:
if left_count > 0:
left_count -= 1
elif star_count > 0:
star_count -= 1
else:
return False
if left_count == 0:
return True
right_count = 0
star_count = 0
for char in s[::-1]:
if char == ')':
right_count += 1
elif char == '*':
star_count += 1
else:
if right_count > 0:
right_count -= 1
elif star_count >0:
star_count -= 1
else:
return False
return True
|
class Solution:
def check_valid_string(self, s: str) -> bool:
left_count = 0
star_count = 0
for char in s:
if char == '(':
left_count += 1
elif char == '*':
star_count += 1
elif left_count > 0:
left_count -= 1
elif star_count > 0:
star_count -= 1
else:
return False
if left_count == 0:
return True
right_count = 0
star_count = 0
for char in s[::-1]:
if char == ')':
right_count += 1
elif char == '*':
star_count += 1
elif right_count > 0:
right_count -= 1
elif star_count > 0:
star_count -= 1
else:
return False
return True
|
class SanSize(int):
"""
Size in bytes
Range : [0..2^63-1].
"""
@staticmethod
def get_api_name():
return "san-size"
|
class Sansize(int):
"""
Size in bytes
Range : [0..2^63-1].
"""
@staticmethod
def get_api_name():
return 'san-size'
|
class FibonacciTable:
def __init__(self):
self.forward_look_up_table = {0: 0, 1: 1}
self.backward_look_up_table = {0: 0, 1: 1}
def _build_lookup_table(self, fib_index: int) -> None:
if fib_index in self.forward_look_up_table.keys():
return
current_highest_index = max(self.forward_look_up_table.keys())
next_value = self.forward_look_up_table[current_highest_index - 1] + self.forward_look_up_table[
current_highest_index]
self.forward_look_up_table[current_highest_index + 1] = next_value
self.backward_look_up_table[next_value] = current_highest_index + 1
self._build_lookup_table(fib_index)
def _build_non_fibonacci_lookup_table(self, fib_number: int) -> None:
current_index = self.backward_look_up_table[max(self.backward_look_up_table.keys())]
previous_index = current_index - 1
if abs(fib_number - self.forward_look_up_table[previous_index]) <= abs(
fib_number - self.forward_look_up_table[current_index]):
self.backward_look_up_table[fib_number] = previous_index
else:
self.backward_look_up_table[fib_number] = current_index
def _update_look_up_table_number(self, fib_index: int) -> None:
while fib_index > max(self.forward_look_up_table.keys()):
self._build_lookup_table(fib_index)
def _update_look_up_table_index(self, fib_number) -> None:
while fib_number >= max(self.backward_look_up_table.keys()):
current_index = self.backward_look_up_table[max(self.backward_look_up_table.keys())]
self._build_lookup_table(current_index + 1) # hier is het een fibonacci getal
if fib_number is not max(self.backward_look_up_table.keys()):
self._build_non_fibonacci_lookup_table(fib_number) # hier is het geen fibonacci getal
def new_fibonacci_number(self, fib_index: int) -> int:
self._update_look_up_table_number(fib_index)
return self.forward_look_up_table[fib_index]
def new_index_fibonacci_number(self, number: int) -> int:
"""Returns an index corresponding to the given fibonacci number."""
self._update_look_up_table_index(number)
return self.backward_look_up_table[number]
|
class Fibonaccitable:
def __init__(self):
self.forward_look_up_table = {0: 0, 1: 1}
self.backward_look_up_table = {0: 0, 1: 1}
def _build_lookup_table(self, fib_index: int) -> None:
if fib_index in self.forward_look_up_table.keys():
return
current_highest_index = max(self.forward_look_up_table.keys())
next_value = self.forward_look_up_table[current_highest_index - 1] + self.forward_look_up_table[current_highest_index]
self.forward_look_up_table[current_highest_index + 1] = next_value
self.backward_look_up_table[next_value] = current_highest_index + 1
self._build_lookup_table(fib_index)
def _build_non_fibonacci_lookup_table(self, fib_number: int) -> None:
current_index = self.backward_look_up_table[max(self.backward_look_up_table.keys())]
previous_index = current_index - 1
if abs(fib_number - self.forward_look_up_table[previous_index]) <= abs(fib_number - self.forward_look_up_table[current_index]):
self.backward_look_up_table[fib_number] = previous_index
else:
self.backward_look_up_table[fib_number] = current_index
def _update_look_up_table_number(self, fib_index: int) -> None:
while fib_index > max(self.forward_look_up_table.keys()):
self._build_lookup_table(fib_index)
def _update_look_up_table_index(self, fib_number) -> None:
while fib_number >= max(self.backward_look_up_table.keys()):
current_index = self.backward_look_up_table[max(self.backward_look_up_table.keys())]
self._build_lookup_table(current_index + 1)
if fib_number is not max(self.backward_look_up_table.keys()):
self._build_non_fibonacci_lookup_table(fib_number)
def new_fibonacci_number(self, fib_index: int) -> int:
self._update_look_up_table_number(fib_index)
return self.forward_look_up_table[fib_index]
def new_index_fibonacci_number(self, number: int) -> int:
"""Returns an index corresponding to the given fibonacci number."""
self._update_look_up_table_index(number)
return self.backward_look_up_table[number]
|
# Given an array of ints length 3, return an array with the elements "rotated
# left" so {1, 2, 3} yields {2, 3, 1}.
# rotate_left3([1, 2, 3]) --> [2, 3, 1]
# rotate_left3([5, 11, 9]) --> [11, 9, 5]
# rotate_left3([7, 0, 0]) --> [0, 0, 7]
def rotate_left3(nums):
nums.append(nums.pop(0))
return nums
print(rotate_left3([1, 2, 3]))
print(rotate_left3([5, 11, 9]))
print(rotate_left3([7, 0, 0]))
|
def rotate_left3(nums):
nums.append(nums.pop(0))
return nums
print(rotate_left3([1, 2, 3]))
print(rotate_left3([5, 11, 9]))
print(rotate_left3([7, 0, 0]))
|
""" This module provides procedures to check if an instance describes preferences that are single-crossing.
"""
def isSingleCrossing(instance):
""" Tests whether the instance describe a profile of single-crossed preferences.
:param instance: The instance to take the orders from.
:type instance: preflibtools.instance.preflibinstance.PreflibInstance
:return: A boolean indicating whether the instance is single-crossed or no.
:rtype: bool
"""
def prefers(a, b, o):
return o.index(a) < o.index(b)
def conflictSet(o1, o2):
res = set([])
for i in range(len(o1)):
for j in range(i + 1, len(o1)):
if ((prefers(o1[i], o1[j], o1) and prefers(o1[j], o1[i], o2)) or
(prefers(o1[j], o1[i], o1) and prefers(o1[i], o1[j], o2))):
res.add((min(o1[i][0], o1[j][0]), max(o1[i][0], o1[j][0])))
return res
def isSCwithFirst(i, profile):
for j in range(len(profile)):
for k in range(len(profile)):
conflictij = conflictSet(profile[i], profile[j])
conflictik = conflictSet(profile[i], profile[k])
if not (conflictij.issubset(conflictik) or conflictik.issubset(conflictij)):
return False
return True
for i in range(len(instance.orders)):
if isSCwithFirst(i, instance.orders):
return True
return False
|
""" This module provides procedures to check if an instance describes preferences that are single-crossing.
"""
def is_single_crossing(instance):
""" Tests whether the instance describe a profile of single-crossed preferences.
:param instance: The instance to take the orders from.
:type instance: preflibtools.instance.preflibinstance.PreflibInstance
:return: A boolean indicating whether the instance is single-crossed or no.
:rtype: bool
"""
def prefers(a, b, o):
return o.index(a) < o.index(b)
def conflict_set(o1, o2):
res = set([])
for i in range(len(o1)):
for j in range(i + 1, len(o1)):
if prefers(o1[i], o1[j], o1) and prefers(o1[j], o1[i], o2) or (prefers(o1[j], o1[i], o1) and prefers(o1[i], o1[j], o2)):
res.add((min(o1[i][0], o1[j][0]), max(o1[i][0], o1[j][0])))
return res
def is_s_cwith_first(i, profile):
for j in range(len(profile)):
for k in range(len(profile)):
conflictij = conflict_set(profile[i], profile[j])
conflictik = conflict_set(profile[i], profile[k])
if not (conflictij.issubset(conflictik) or conflictik.issubset(conflictij)):
return False
return True
for i in range(len(instance.orders)):
if is_s_cwith_first(i, instance.orders):
return True
return False
|
#!/usr/bin/env python3
# Parse input
lines = []
with open("10/input.txt", "r") as fd:
for line in fd:
lines.append(line.rstrip())
illegal = []
for line in lines:
stack = list()
for c in line:
if c == "(":
stack.append(")")
elif c == "[":
stack.append("]")
elif c == "{":
stack.append("}")
elif c == "<":
stack.append(">")
else:
# Closing
if len(stack) == 0:
illegal.append(c)
break
expected = stack.pop()
if c != expected:
illegal.append(c)
break
mapping = {
")": 3,
"]": 57,
"}": 1197,
">": 25137
}
print(sum([mapping[x] for x in illegal]))
|
lines = []
with open('10/input.txt', 'r') as fd:
for line in fd:
lines.append(line.rstrip())
illegal = []
for line in lines:
stack = list()
for c in line:
if c == '(':
stack.append(')')
elif c == '[':
stack.append(']')
elif c == '{':
stack.append('}')
elif c == '<':
stack.append('>')
else:
if len(stack) == 0:
illegal.append(c)
break
expected = stack.pop()
if c != expected:
illegal.append(c)
break
mapping = {')': 3, ']': 57, '}': 1197, '>': 25137}
print(sum([mapping[x] for x in illegal]))
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = self.back = None
def isEmpty(self):
return self.front == None
def EnQueue(self, item):
temp = Node(item)
if(self.back == None):
self.front = self.back = temp
return
self.back.next = temp
self.back = temp
def DeQueue(self):
if(self.isEmpty()):
return
temp = self.front
self.front = temp.next
if(self.front == None):
self.back = None
if __name__ == "__main__":
queue = Queue()
queue.EnQueue(20)
queue.EnQueue(30)
queue.DeQueue()
queue.DeQueue()
queue.EnQueue(40)
queue.EnQueue(50)
queue.EnQueue(60)
queue.DeQueue()
print("Queue Front " + str(queue.front.data))
print("Queue Back " + str(queue.back.data))
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = self.back = None
def is_empty(self):
return self.front == None
def en_queue(self, item):
temp = node(item)
if self.back == None:
self.front = self.back = temp
return
self.back.next = temp
self.back = temp
def de_queue(self):
if self.isEmpty():
return
temp = self.front
self.front = temp.next
if self.front == None:
self.back = None
if __name__ == '__main__':
queue = queue()
queue.EnQueue(20)
queue.EnQueue(30)
queue.DeQueue()
queue.DeQueue()
queue.EnQueue(40)
queue.EnQueue(50)
queue.EnQueue(60)
queue.DeQueue()
print('Queue Front ' + str(queue.front.data))
print('Queue Back ' + str(queue.back.data))
|
#/* *** ODSATag: RFact *** */
# Recursively compute and return n!
def rfact(n):
if n < 0: raise ValueError
if n <= 1: return 1 # Base case: return base solution
return n * rfact(n-1) # Recursive call for n > 1
#/* *** ODSAendTag: RFact *** */
#/* *** ODSATag: Sfact *** */
# Return n!
def sfact(n):
if n < 0: raise ValueError
# Make a stack just big enough
S = AStack(n)
while n > 1:
S.push(n)
n -= 1
result = 1
while S.length() > 0:
result = result * S.pop()
return result
#/* *** ODSAendTag: Sfact *** */
|
def rfact(n):
if n < 0:
raise ValueError
if n <= 1:
return 1
return n * rfact(n - 1)
def sfact(n):
if n < 0:
raise ValueError
s = a_stack(n)
while n > 1:
S.push(n)
n -= 1
result = 1
while S.length() > 0:
result = result * S.pop()
return result
|
"""
Range
range(stop)
range(start, stop)
range(start, stop, step)
start = 0
step = 1
- iterable object
- string is iterable
"""
r = range(5, 10, 2)
print(r.start)
print(r.stop)
print(r.step)
|
"""
Range
range(stop)
range(start, stop)
range(start, stop, step)
start = 0
step = 1
- iterable object
- string is iterable
"""
r = range(5, 10, 2)
print(r.start)
print(r.stop)
print(r.step)
|
# https://www.hackerrank.com/challenges/ctci-is-binary-search-tree
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
arr = []
inlen = 0
def checkBST(root):
global arr
if root is None:
return True
if checkBST(root.left):
arr.append(root.data)
if len(arr)>=2:
if arr[-1]>arr[-2]:
return True and checkBST(root.right)
else:
return False
else:
return checkBST(root.right)
else:
return False
# def checkBST(root):
# if root.left is None and root.right is None:
# return True
# elif root.left is None and root.data <= root.right.data:
# return checkBST(root.right)
# elif root.right is None and root.data >= root.left.data:
# return checkBST(root.left)
# elif root.left.data <= root.data <= root.right.data:
# return checkBST(root.left) and checkBST(root.right)
# else:
# return False
|
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
arr = []
inlen = 0
def check_bst(root):
global arr
if root is None:
return True
if check_bst(root.left):
arr.append(root.data)
if len(arr) >= 2:
if arr[-1] > arr[-2]:
return True and check_bst(root.right)
else:
return False
else:
return check_bst(root.right)
else:
return False
|
r1, c1 = map(int, input().split())
r2, c2 = map(int, input().split())
if abs(r1 - r2) + abs(c1 - c2) == 0:
print(0)
exit()
# Move
if abs(r1 - r2) + abs(c1 - c2) <= 3:
print(1)
exit()
r3 = r2
t = abs(r1 - r2)
if abs(c1 + t - c2) < abs(c1 - t - c2):
c3 = c1 + t
else:
c3 = c1 - t
# Bishop warp
if c3 == c2:
print(1)
exit()
# Move + Move
if abs(r1 - r2) + abs(c1 - c2) <= 6:
print(2)
exit()
# Bishop warp + Move
if abs(r3 - r2) + abs(c3 - c2) <= 3:
print(2)
exit()
# Bishop warp + Bishop warp
if (r1 + c1) % 2 == (r2 + c2) % 2:
print(2)
exit()
# Bishop warp + Bishop warp + Move
print(3)
|
(r1, c1) = map(int, input().split())
(r2, c2) = map(int, input().split())
if abs(r1 - r2) + abs(c1 - c2) == 0:
print(0)
exit()
if abs(r1 - r2) + abs(c1 - c2) <= 3:
print(1)
exit()
r3 = r2
t = abs(r1 - r2)
if abs(c1 + t - c2) < abs(c1 - t - c2):
c3 = c1 + t
else:
c3 = c1 - t
if c3 == c2:
print(1)
exit()
if abs(r1 - r2) + abs(c1 - c2) <= 6:
print(2)
exit()
if abs(r3 - r2) + abs(c3 - c2) <= 3:
print(2)
exit()
if (r1 + c1) % 2 == (r2 + c2) % 2:
print(2)
exit()
print(3)
|
age = 10
num = 0
while num < age:
if num == 0:
num += 1
continue
if num % 2 == 0:
print(num)
if num > 4:
break
num += 1
|
age = 10
num = 0
while num < age:
if num == 0:
num += 1
continue
if num % 2 == 0:
print(num)
if num > 4:
break
num += 1
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 25 19:01:56 2019
@author: joscelynec
"""
"""
Iterative Binary Search of a Sorted Array
Adapted from:
https://codereview.stackexchange.com/questions/117180/python-2-binary-search
"""
def binary_search(array, value):
start, stop = 0, len(array)
while start < stop:
offset = start + stop >> 1
sample = array[offset]
if sample < value:
start = offset + 1
elif sample > value:
stop = offset
else:
return offset
return -1
"""
Finds pivot index in sorted rotated list
for example, for [6, 7, 8, 9, 10, 1, 2, 3, 4]
pivot = 5
"""
def find_pivot(input_list):
start = 0
end = len(input_list) - 1
while start <= end:
mid = (start + end)//2
if input_list[start] <= input_list[end]: #check if list is not rotated
return start
elif input_list[start] <= input_list[mid]: #first to mid is sorted, pivot is in other half of list
start = mid +1
else: #pivot is in first half of list
end = mid
return start
"""
Modify/adapt binary search to search a rotated sorted input_list
in O(nlog n) time
Uses find_pivot(input_list) and then binary search on two sub lists
Find the index by searching in a rotated sorted input_list
Args:
input_list(input_list), number(int): Input input_list to search and the target
Returns:
int: Index or -1
"""
def rotated_input_list_search(input_list, number):
#Null input
if input_list == None or number == None:
return -1
#Empty List
if input_list == [] or number == None:
return -1
pivot_index = find_pivot(input_list)
#perform binary search on each list divided into at the pivot
temp = binary_search(input_list[0: pivot_index], number)
if temp != -1:
return temp
temp = binary_search(input_list[pivot_index: len(input_list)], number)
if temp != -1:
return temp + pivot_index
#number not found
return -1
#print(rotated_input_list_search([6, 7, 8, 1, 2, 3, 4], 6))
def linear_search(input_list, number):
#Null input
if input_list == None or number == None:
return -1
#Empty List
if input_list == [] or number == None:
return -1
for index, element in enumerate(input_list):
if element == number:
return index
return -1
#Udacity test function modified for None or Empty inputs
def test_function(test_case):
if test_case == None:
print("None")
return
input_list = test_case[0]
if input_list == [None]:
print("None")
return
number = test_case[1]
if number == None:
print("None")
return
if linear_search(input_list, number) == rotated_input_list_search(input_list, number):
print("Pass")
else:
print("Fail")
test_function(None)#Null Inputs
test_function([[None], None])#Null Input_lists
test_function([[None], 6])#Null Input_lists
test_function([[], None])#Empty List, None for number
test_function([[], 6])#Empty List
test_function([[8], 8])#Singleton List with value
test_function([[8], 7])#Singleton List without value
#More tests two element lists
test_function([[7,8], 8])
test_function([[8,5], 8])
test_function([[7,8], 9])
test_function([[8,5], 4])
#Full cycle of a sorted list, value present and not present
test_function([[1, 2, 3, 4, 5], 3])
test_function([[1, 2, 3, 4, 5], 6])
test_function([[2, 3, 4, 5, 1], 3])
test_function([[2, 3, 4, 5, 1], 6])
test_function([[3, 4, 5, 1, 2], 3])
test_function([[3, 4, 5, 1, 2], 6])
test_function([[4, 5, 1, 2, 3], 3])
test_function([[4, 5, 1, 2, 3], 6])
test_function([[5, 1, 2, 3, 4], 3])
test_function([[5, 1, 2, 3, 4], 6])
#Udacity supplied tests
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
"""
None
None
None
None
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
Pass
"""
|
"""
Created on Sat May 25 19:01:56 2019
@author: joscelynec
"""
'\nIterative Binary Search of a Sorted Array\nAdapted from:\nhttps://codereview.stackexchange.com/questions/117180/python-2-binary-search\n'
def binary_search(array, value):
(start, stop) = (0, len(array))
while start < stop:
offset = start + stop >> 1
sample = array[offset]
if sample < value:
start = offset + 1
elif sample > value:
stop = offset
else:
return offset
return -1
'\nFinds pivot index in sorted rotated list\nfor example, for [6, 7, 8, 9, 10, 1, 2, 3, 4]\npivot = 5\n'
def find_pivot(input_list):
start = 0
end = len(input_list) - 1
while start <= end:
mid = (start + end) // 2
if input_list[start] <= input_list[end]:
return start
elif input_list[start] <= input_list[mid]:
start = mid + 1
else:
end = mid
return start
'\nModify/adapt binary search to search a rotated sorted input_list\nin O(nlog n) time\nUses find_pivot(input_list) and then binary search on two sub lists\nFind the index by searching in a rotated sorted input_list\nArgs:\n input_list(input_list), number(int): Input input_list to search and the target\nReturns:\n int: Index or -1\n'
def rotated_input_list_search(input_list, number):
if input_list == None or number == None:
return -1
if input_list == [] or number == None:
return -1
pivot_index = find_pivot(input_list)
temp = binary_search(input_list[0:pivot_index], number)
if temp != -1:
return temp
temp = binary_search(input_list[pivot_index:len(input_list)], number)
if temp != -1:
return temp + pivot_index
return -1
def linear_search(input_list, number):
if input_list == None or number == None:
return -1
if input_list == [] or number == None:
return -1
for (index, element) in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
if test_case == None:
print('None')
return
input_list = test_case[0]
if input_list == [None]:
print('None')
return
number = test_case[1]
if number == None:
print('None')
return
if linear_search(input_list, number) == rotated_input_list_search(input_list, number):
print('Pass')
else:
print('Fail')
test_function(None)
test_function([[None], None])
test_function([[None], 6])
test_function([[], None])
test_function([[], 6])
test_function([[8], 8])
test_function([[8], 7])
test_function([[7, 8], 8])
test_function([[8, 5], 8])
test_function([[7, 8], 9])
test_function([[8, 5], 4])
test_function([[1, 2, 3, 4, 5], 3])
test_function([[1, 2, 3, 4, 5], 6])
test_function([[2, 3, 4, 5, 1], 3])
test_function([[2, 3, 4, 5, 1], 6])
test_function([[3, 4, 5, 1, 2], 3])
test_function([[3, 4, 5, 1, 2], 6])
test_function([[4, 5, 1, 2, 3], 3])
test_function([[4, 5, 1, 2, 3], 6])
test_function([[5, 1, 2, 3, 4], 3])
test_function([[5, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
'\nNone\nNone\nNone\nNone\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\nPass\n'
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 15:29:32 2019
@author: mwhitten
"""
def g2d1(Fy, Aw, Cv):
"""Nominal shear strength
The nominal shear strength, Vn, of unstiffened or stiffened webs, according
to the limit states of shear yielding and shear buckling, is
Vn = 0.6*Fy*Aw*Cv
Args:
Fy (float):
Aw (float):
Cv (float):
"""
Vn = 0.6*Fy*Aw*Cv
text = ()
return Vn, text
def g2d2(h, tw, E, Fy):
"""Web shear coefficient, Case (a)
For webs of rolled I-shaped member with
if h/tw <= 2.24*math.sqrt(E,Fy):
Cv = 1.0
else:
Cv = None
Args:
h (float):
web height
tw (float):
web thickness
E (float):
modulus of elasticity
Fy (float):
yield strength of web
Returns:
Cv (tuple(float, str)):
web shear coefficient
"""
if h/tw <= 2.24*math.sqrt(E/Fy):
Cv = 1.0
text = ()
else:
Cv = None
text = ()
return Cv, text
def g2d3(h, tw, kv, E, Fy):
"""Web shear coefficient, Case (b)(i)
For webs of all other doubly symmetric shapes and single symmetric shapes
and channels, excepts round HSS, the web shear coefficient, Cv, is
determined as follows
if h/tw <= 1.10*math.sqrt(kv*E/Fy):
Cv = 1.0
else:
Cv = None
Args:
h (float):
web height
tw (float):
web thickness
kv (float):
E (float):
modulus of elasticity
Fy (float):
yield strength of web
Returns:
Cv (tuple(float, str)):
web shear coefficient
"""
if h/tw <= 1.10*math.sqrt(kv*E/Fy):
Cv = 1.0
text = ()
else:
Cv = None
text = ()
return Cv, text
|
"""
Created on Tue Dec 24 15:29:32 2019
@author: mwhitten
"""
def g2d1(Fy, Aw, Cv):
"""Nominal shear strength
The nominal shear strength, Vn, of unstiffened or stiffened webs, according
to the limit states of shear yielding and shear buckling, is
Vn = 0.6*Fy*Aw*Cv
Args:
Fy (float):
Aw (float):
Cv (float):
"""
vn = 0.6 * Fy * Aw * Cv
text = ()
return (Vn, text)
def g2d2(h, tw, E, Fy):
"""Web shear coefficient, Case (a)
For webs of rolled I-shaped member with
if h/tw <= 2.24*math.sqrt(E,Fy):
Cv = 1.0
else:
Cv = None
Args:
h (float):
web height
tw (float):
web thickness
E (float):
modulus of elasticity
Fy (float):
yield strength of web
Returns:
Cv (tuple(float, str)):
web shear coefficient
"""
if h / tw <= 2.24 * math.sqrt(E / Fy):
cv = 1.0
text = ()
else:
cv = None
text = ()
return (Cv, text)
def g2d3(h, tw, kv, E, Fy):
"""Web shear coefficient, Case (b)(i)
For webs of all other doubly symmetric shapes and single symmetric shapes
and channels, excepts round HSS, the web shear coefficient, Cv, is
determined as follows
if h/tw <= 1.10*math.sqrt(kv*E/Fy):
Cv = 1.0
else:
Cv = None
Args:
h (float):
web height
tw (float):
web thickness
kv (float):
E (float):
modulus of elasticity
Fy (float):
yield strength of web
Returns:
Cv (tuple(float, str)):
web shear coefficient
"""
if h / tw <= 1.1 * math.sqrt(kv * E / Fy):
cv = 1.0
text = ()
else:
cv = None
text = ()
return (Cv, text)
|
# This is Stack build using Singly Linked List
class StackNode:
def __init__(self, value):
self.value = value
self._next = None
class Stack:
def __init__(self):
self.head = None # bottom
self.tail = None # top
self.size = 0
def __len__(self):
return self.size
def _size(self):
return self.size
def is_empty(self):
return self.size == 0
def __str__(self):
linked_list = ""
current_node = self.head
while current_node is not None:
linked_list += f"{current_node.value} -> "
current_node = current_node._next
linked_list += "None"
return linked_list
def __repr__(self):
return str(self)
def push(self, value):
node = StackNode(value)
if self.is_empty():
self.head = self.tail = node
else:
self.tail._next = node
self.tail = node
self.size += 1
def pop(self):
assert self.size != 0, 'Stack is empty'
tmp = self.head
self.size -= 1
if self.is_empty():
self.head = self.tail = None
else:
self.head = self.head._next
return tmp
s = Stack()
print(s.is_empty())
# print(s)
s.push(1)
print(s, s.head.value, s.tail.value)
s.push(2)
print(s, s.head.value, s.tail.value)
s.push(3)
print(s, s.head.value, s.tail.value)
s.push(4)
print(s, s.head.value, s.tail.value)
print(s.pop().value)
print(s, s.head.value, s.tail.value)
print(s.pop().value)
print(s, s.head.value, s.tail.value)
print(s.pop().value)
print(s, s.head.value, s.tail.value)
print(s.pop().value)
print(s)
|
class Stacknode:
def __init__(self, value):
self.value = value
self._next = None
class Stack:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def __len__(self):
return self.size
def _size(self):
return self.size
def is_empty(self):
return self.size == 0
def __str__(self):
linked_list = ''
current_node = self.head
while current_node is not None:
linked_list += f'{current_node.value} -> '
current_node = current_node._next
linked_list += 'None'
return linked_list
def __repr__(self):
return str(self)
def push(self, value):
node = stack_node(value)
if self.is_empty():
self.head = self.tail = node
else:
self.tail._next = node
self.tail = node
self.size += 1
def pop(self):
assert self.size != 0, 'Stack is empty'
tmp = self.head
self.size -= 1
if self.is_empty():
self.head = self.tail = None
else:
self.head = self.head._next
return tmp
s = stack()
print(s.is_empty())
s.push(1)
print(s, s.head.value, s.tail.value)
s.push(2)
print(s, s.head.value, s.tail.value)
s.push(3)
print(s, s.head.value, s.tail.value)
s.push(4)
print(s, s.head.value, s.tail.value)
print(s.pop().value)
print(s, s.head.value, s.tail.value)
print(s.pop().value)
print(s, s.head.value, s.tail.value)
print(s.pop().value)
print(s, s.head.value, s.tail.value)
print(s.pop().value)
print(s)
|
def create_data(n):
temp = [i for i in range(n)]
return temp
n = 100
target = n + 11
ma_list = create_data(n)
def binary_search(input_list,target):
found = False
low = 0
high = len(input_list) - 1
mid = int((high + low) / 2)
while (low <=high) and (not found):
curr = input_list[mid]
if curr == target:
found = True
return True
elif curr < target:
low = mid +1
elif curr > target:
high = mid - 1
mid = int((high + low) / 2)
print(mid)
return False
print(binary_search(ma_list,target))
|
def create_data(n):
temp = [i for i in range(n)]
return temp
n = 100
target = n + 11
ma_list = create_data(n)
def binary_search(input_list, target):
found = False
low = 0
high = len(input_list) - 1
mid = int((high + low) / 2)
while low <= high and (not found):
curr = input_list[mid]
if curr == target:
found = True
return True
elif curr < target:
low = mid + 1
elif curr > target:
high = mid - 1
mid = int((high + low) / 2)
print(mid)
return False
print(binary_search(ma_list, target))
|
# @Author: Ozan YILDIZ@2022
# Simple printing operation
val = 12
if __name__ == '__main__':
#print operation
print("Boolean True (True)", val)
|
val = 12
if __name__ == '__main__':
print('Boolean True (True)', val)
|
class FlightParsingConfig(object):
"""
Configuration for parsing an IGC file.
Defines a set of parameters used to validate a file, and to detect
thermals and flight mode. Details in comments.
"""
#
# Flight validation parameters.
#
# Minimum of fixes required before takeoff for file to be regarded valid
min_fixes_before_takeoff = 5
# Minimum number of fixes in a file.
min_fixes = 50
# Maximum time between fixes, seconds.
# Soft limit, some fixes are allowed to exceed.
max_seconds_between_fixes = 50.0
# Minimum time between fixes, seconds.
# Soft limit, some fixes are allowed to exceed.
min_seconds_between_fixes = 1.0
# Maximum number of fixes exceeding time between fix constraints.
max_time_violations = 10
# Maximum number of times a file can cross the 0:00 UTC time.
max_new_days_in_flight = 2
# Minimum average of absolute values of altitude changes in a file.
# This is needed to discover altitude sensors (either pressure or
# gps) that report either always constant altitude, or almost
# always constant altitude, and therefore are invalid. The unit
# is meters/fix.
min_avg_abs_alt_change = 0.01
# Maximum altitude change per second between fixes, meters per second.
# Soft limit, some fixes are allowed to exceed.
max_alt_change_rate = 50.0
# Maximum number of fixes that exceed the altitude change limit.
max_alt_change_violations = 3
# Absolute maximum altitude, meters.
max_alt = 10000.0
# Absolute minimum altitude, meters.
min_alt = -600.0
#
# Flight detection parameters.
#
# Minimum ground speed to switch to flight mode, km/h.
min_gsp_flight = 15.0
# Minimum idle time (i.e. time with speed below min_gsp_flight) to switch
# to landing, seconds. Exception: end of the file (tail fixes that
# do not trigger the above condition), no limit is applied there.
min_landing_time = 5.0 * 60.0
# In case there are multiple continuous segments with ground
# speed exceeding the limit, which one should be taken?
# Available options:
# - "first": take the first segment, ignore the part after
# the first detected landing.
# - "concat": concatenate all segments; will include the down
# periods between segments (legacy behavior)
# - "all": create seperate flight objects for all detected takeoffs
which_flight_to_pick = "first"
#
# Thermal detection parameters.
#
# Minimum bearing change to enter a thermal, deg/sec.
min_bearing_change_circling = 6.0
# Minimum time between fixes to calculate bearing change, seconds.
# See the usage for a more detailed comment on why this is useful.
min_time_for_bearing_change = 5.0
# Minimum time to consider circling a thermal, seconds.
min_time_for_thermal = 60.0
#
# Engine detection parameters.
#
# Which sensor to choose to detect engine run if available
sensors = ['RPM', 'ENL', 'MOP', 'CUR']
# minima of these sensor to detect raw engine emissions
min_sensor_level = {'RPM': 50, 'ENL': 500, 'MOP': 50, 'CUR': 5}
# minima of fixes above min_sensor_level
min_engine_running = 10
#
# Tow detection parameters.
#
# Minimum climbing rate on tow, used for raw emissions for tow detections
min_vario_on_tow = 0.0
# Maximum bearing change on tow, deg/sec.
max_bearing_change_on_tow = 10.0
# maybe also speed change after tow release?
#
# Scoring parameters.
#
# Maximum scoring speed - used to disregard windows based on time, km/h
max_scoring_speed = 300
|
class Flightparsingconfig(object):
"""
Configuration for parsing an IGC file.
Defines a set of parameters used to validate a file, and to detect
thermals and flight mode. Details in comments.
"""
min_fixes_before_takeoff = 5
min_fixes = 50
max_seconds_between_fixes = 50.0
min_seconds_between_fixes = 1.0
max_time_violations = 10
max_new_days_in_flight = 2
min_avg_abs_alt_change = 0.01
max_alt_change_rate = 50.0
max_alt_change_violations = 3
max_alt = 10000.0
min_alt = -600.0
min_gsp_flight = 15.0
min_landing_time = 5.0 * 60.0
which_flight_to_pick = 'first'
min_bearing_change_circling = 6.0
min_time_for_bearing_change = 5.0
min_time_for_thermal = 60.0
sensors = ['RPM', 'ENL', 'MOP', 'CUR']
min_sensor_level = {'RPM': 50, 'ENL': 500, 'MOP': 50, 'CUR': 5}
min_engine_running = 10
min_vario_on_tow = 0.0
max_bearing_change_on_tow = 10.0
max_scoring_speed = 300
|
"""URL creator for the evergreen API."""
class UrlCreator:
"""Class to create evergreen URLs."""
def __init__(self, api_server: str) -> None:
"""
Initialize a url creator.
:param api_server: Hostname API server to connect to.
"""
self.api_server = api_server
def rest_v2(self, endpoint: str) -> str:
"""
Create a REST V2 url.
:param endpoint: Endpoint to connect to.
:return: URL to access given endpoint.
"""
return f"{self.api_server}/rest/v2/{endpoint}"
|
"""URL creator for the evergreen API."""
class Urlcreator:
"""Class to create evergreen URLs."""
def __init__(self, api_server: str) -> None:
"""
Initialize a url creator.
:param api_server: Hostname API server to connect to.
"""
self.api_server = api_server
def rest_v2(self, endpoint: str) -> str:
"""
Create a REST V2 url.
:param endpoint: Endpoint to connect to.
:return: URL to access given endpoint.
"""
return f'{self.api_server}/rest/v2/{endpoint}'
|
#http://shell-storm.org/shellcode/files/shellcode-103.php
"""
\x7f\x45\x4c\x46\x01\x01\x01\x09\x00\x00\x00\x00\x00\x00\x00\x00
\x02\x00\x03\x00\x01\x00\x00\x00\x74\x80\x04\x08\x34\x00\x00\x00
\xa8\x00\x00\x00\x00\x00\x00\x00\x34\x00\x20\x00\x02\x00\x28\x00
\x05\x00\x04\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x80\x04\x08
\x00\x80\x04\x08\x8b\x00\x00\x00\x8b\x00\x00\x00\x05\x00\x00\x00
\x00\x10\x00\x00\x01\x00\x00\x00\x8c\x00\x00\x00\x8c\x90\x04\x08
\x8c\x90\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00
\x00\x10\x00\x00
"""
"""
\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69
\x6e\x89\xe3\x50\x54\x53\x50\xb0\x3b\xcd\x80\x44
"""
"""
"\x7f\x45\x4c\x46\x01\x01\x01\x09\x00\x00\x00\x00\x00\x00\x00\x00
\x02\x00\x03\x00\x01\x00\x00\x00\x74\x80\x04\x08\x34\x00\x00\x00
\xa8\x00\x00\x00\x00\x00\x00\x00\x34\x00\x20\x00\x02\x00\x28\x00
\x05\x00\x04\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x80\x04\x08
\x00\x80\x04\x08\x8b\x00\x00\x00\x8b\x00\x00\x00\x05\x00\x00\x00
\x00\x10\x00\x00\x01\x00\x00\x00\x8c\x00\x00\x00\x8c\x90\x04\x08
\x8c\x90\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00
\x00\x10\x00\x00
"""
"""
\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x54\x53\x50\xb0\x3b\xcd\x80\x44
"""
|
"""
\x7fELF\x01\x01\x01 \x00\x00\x00\x00\x00\x00\x00\x00
\x02\x00\x03\x00\x01\x00\x00\x00t\x80\x04\x084\x00\x00\x00
¨\x00\x00\x00\x00\x00\x00\x004\x00 \x00\x02\x00(\x00
\x05\x00\x04\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x80\x04\x08
\x00\x80\x04\x08\x8b\x00\x00\x00\x8b\x00\x00\x00\x05\x00\x00\x00
\x00\x10\x00\x00\x01\x00\x00\x00\x8c\x00\x00\x00\x8c\x90\x04\x08
\x8c\x90\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00
\x00\x10\x00\x00
"""
'\n1ÀPh//shh/bi\nn\x89ãPTSP°;Í\x80D\n'
'\n"\x7fELF\x01\x01\x01\t\x00\x00\x00\x00\x00\x00\x00\x00\n\x02\x00\x03\x00\x01\x00\x00\x00t\x80\x04\x084\x00\x00\x00\n¨\x00\x00\x00\x00\x00\x00\x004\x00 \x00\x02\x00(\x00\n\x05\x00\x04\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x80\x04\x08\n\x00\x80\x04\x08\x8b\x00\x00\x00\x8b\x00\x00\x00\x05\x00\x00\x00\n\x00\x10\x00\x00\x01\x00\x00\x00\x8c\x00\x00\x00\x8c\x90\x04\x08\n\x8c\x90\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\n\x00\x10\x00\x00\n'
'\n1ÀPh//shh/bin\x89ãPTSP°;Í\x80D\n'
|
#Finding least trial
def least_trial_num(n):
#making 1000001 size buffer
buffer = []
for i in range(1000001):
buffer += [0]
#Minimum calculation of 1 is 0 times.
buffer[1] = 0
#Minimum calculations of other values
for i in range(2, n + 1):
#Since calculations of (n - 1), (n / 2), (n / 3) is all minimum-guaranteed, n is also minimum.
#First, we set to calculations of n to 1 + calculations of (n - 1)
buffer[i] = buffer[i - 1] + 1
#Comparing two if n can be divided by 2
if i % 2 == 0:
buffer[i] = min2(buffer[i], buffer[i // 2] + 1)
#Comparing two if n can be divided by 3
if i % 3 == 0:
buffer[i] = min2(buffer[i], buffer[i // 3] + 1)
#Returning a value
return buffer[n]
#This is fumction which finds least value of two
def min2(a, b):
if a < b: return a
else: return b
#Input part
N = int(input())
#Output part
print(least_trial_num(N))
|
def least_trial_num(n):
buffer = []
for i in range(1000001):
buffer += [0]
buffer[1] = 0
for i in range(2, n + 1):
buffer[i] = buffer[i - 1] + 1
if i % 2 == 0:
buffer[i] = min2(buffer[i], buffer[i // 2] + 1)
if i % 3 == 0:
buffer[i] = min2(buffer[i], buffer[i // 3] + 1)
return buffer[n]
def min2(a, b):
if a < b:
return a
else:
return b
n = int(input())
print(least_trial_num(N))
|
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
"""
Date: 2019/11/27
Author: Xiao-Le Deng
Email: xiaoledeng at gmail.com
Function: get a list of each line in the file
"""
def read_file_to_list(file):
"""Return a list of each line in the file"""
result=[]
with open(file,'rt',encoding='utf-8') as f:
for line in f:
result.append(list(line.strip('\n').split(','))[0])
return result
# # example
# a = read_file_to_list("example.txt")
# print('The len of the list is:',len(a))
# print(a)
|
"""
Date: 2019/11/27
Author: Xiao-Le Deng
Email: xiaoledeng at gmail.com
Function: get a list of each line in the file
"""
def read_file_to_list(file):
"""Return a list of each line in the file"""
result = []
with open(file, 'rt', encoding='utf-8') as f:
for line in f:
result.append(list(line.strip('\n').split(','))[0])
return result
|
# environment variables
ATOM_PROGRAM = '/home/physics/bin/atm'
ATOM_UTILS_DIR ='/home/physics/bin/pseudo'
element = "Al"
equil_volume = 16.4796
# general calculation parameters
calc = {"element": element,
"lattice": "FCC",
"xc": "pb",
"n_core": 3,
"n_val": 2,
"is_spin_pol": False,
"core": True,
}
# pseudopotential parameters
electrons = [2, 1]
radii = [2.4, 2.8, 2.3, 2.3, 0.7]
# SIESTA calculation parameters
siesta_calc = {"element": element,
"title": element + " SIESTA calc",
"xc_f": "GGA",
"xc": "PBE"
}
# electronic configurations
configs = [[1.5, 1.5],
[1, 2],
[0.5, 2.5],
[0, 3]]
# number of atoms in cubic cell
_nat_cell = {"SC": 1,
"BCC": 2,
"FCC": 4}
nat = _nat_cell[calc["lattice"]]
|
atom_program = '/home/physics/bin/atm'
atom_utils_dir = '/home/physics/bin/pseudo'
element = 'Al'
equil_volume = 16.4796
calc = {'element': element, 'lattice': 'FCC', 'xc': 'pb', 'n_core': 3, 'n_val': 2, 'is_spin_pol': False, 'core': True}
electrons = [2, 1]
radii = [2.4, 2.8, 2.3, 2.3, 0.7]
siesta_calc = {'element': element, 'title': element + ' SIESTA calc', 'xc_f': 'GGA', 'xc': 'PBE'}
configs = [[1.5, 1.5], [1, 2], [0.5, 2.5], [0, 3]]
_nat_cell = {'SC': 1, 'BCC': 2, 'FCC': 4}
nat = _nat_cell[calc['lattice']]
|
idir="<path to public/template database>/";
odir=idir+"output/";
public_dir='DPA_contest2_public_base_diff_vcc_a128_2009_12_23/'
template_dir='DPA_contest2_template_base_diff_vcc_a128_2009_12_23/'
template_index_file=idir+'DPA_contest2_template_base_index_file'
public_index_file=idir+'DPA_contest2_public_base_index_file'
template_keymsg_file=idir+'keymsg_template_base_dpacontest2'
public_keymsg_file=idir+'keymsg_public_base_dpacontest2'
template_idir=idir+template_dir
public_idir=idir+public_dir
|
idir = '<path to public/template database>/'
odir = idir + 'output/'
public_dir = 'DPA_contest2_public_base_diff_vcc_a128_2009_12_23/'
template_dir = 'DPA_contest2_template_base_diff_vcc_a128_2009_12_23/'
template_index_file = idir + 'DPA_contest2_template_base_index_file'
public_index_file = idir + 'DPA_contest2_public_base_index_file'
template_keymsg_file = idir + 'keymsg_template_base_dpacontest2'
public_keymsg_file = idir + 'keymsg_public_base_dpacontest2'
template_idir = idir + template_dir
public_idir = idir + public_dir
|
def getNoZeroIntegers(self, n: int) -> List[int]:
for i in range(1, n):
a = i
b = n - i
if "0" in str(a) or "0" in str(b):
continue
return [a, b]
|
def get_no_zero_integers(self, n: int) -> List[int]:
for i in range(1, n):
a = i
b = n - i
if '0' in str(a) or '0' in str(b):
continue
return [a, b]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.