content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class FourCal:
def setdata(self, first, second):
self.first = first
self.second = second
def sum(self):
result = self.first + self.second
return result
def sub(self):
result = self.first - self.second
return result
def mul(self):
result = self.first * self.second
return result
def div(self):
result = self.first / self.second
return result
| class Fourcal:
def setdata(self, first, second):
self.first = first
self.second = second
def sum(self):
result = self.first + self.second
return result
def sub(self):
result = self.first - self.second
return result
def mul(self):
result = self.first * self.second
return result
def div(self):
result = self.first / self.second
return result |
# 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': 'files_icon_button',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_metadata_box',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_metadata_entry',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_quick_view',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_ripple',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_safe_img',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_safe_img_webview_content',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_toast',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_toggle_ripple',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_tooltip',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'files_tooltip_unittest',
# 'includes': ['../../../compile_js2.gypi'],
# },
],
}
| {'targets': []} |
"""
[issue2]
$ echo TEST1
. # doctest: +ELLIPSIS
T...ST1
$ echo TEST2
. # doctest: +ELLIPSIS
...EST2
"""
| """
[issue2]
$ echo TEST1
. # doctest: +ELLIPSIS
T...ST1
$ echo TEST2
. # doctest: +ELLIPSIS
...EST2
""" |
# sample function to get a prediction from the model
def getPrediction(text):
if type(text) is str:
return len(text)
else:
return -1
| def get_prediction(text):
if type(text) is str:
return len(text)
else:
return -1 |
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
"""
"""
dp: opt(n) = max{opt(n - 1) + f(n), f(n)}
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
>>> Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4])
6
"""
use_dp = True
if len(nums) == 0:
return 0
maxSum = nums[0]
currentMax = nums[0]
if use_dp:
for i in range(1, len(nums)):
if currentMax > 0:
currentMax += nums[i]
else:
currentMax = nums[i]
maxSum = max(currentMax, maxSum)
return maxSum
else:
pass
| """
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
"""
'\ndp: opt(n) = max{opt(n - 1) + f(n), f(n)}\n'
class Solution(object):
def max_sub_array(self, nums):
"""
:type nums: List[int]
:rtype: int
>>> Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4])
6
"""
use_dp = True
if len(nums) == 0:
return 0
max_sum = nums[0]
current_max = nums[0]
if use_dp:
for i in range(1, len(nums)):
if currentMax > 0:
current_max += nums[i]
else:
current_max = nums[i]
max_sum = max(currentMax, maxSum)
return maxSum
else:
pass |
# -*- coding: utf-8 -*-
"""
559. Maximum Depth of N-ary Tree
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal,
each group of children is separated by the null value (See examples).
Constraints:
The depth of the n-ary tree is less than or equal to 1000.
The total number of nodes is between [0, 10^4].
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
def maxDepth(self, root) -> int:
if root is None:
return 0
elif not root.children:
return 1
else:
return max([self.maxDepth(child) for child in root.children]) + 1
| """
559. Maximum Depth of N-ary Tree
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal,
each group of children is separated by the null value (See examples).
Constraints:
The depth of the n-ary tree is less than or equal to 1000.
The total number of nodes is between [0, 10^4].
"""
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
def max_depth(self, root) -> int:
if root is None:
return 0
elif not root.children:
return 1
else:
return max([self.maxDepth(child) for child in root.children]) + 1 |
notas = [[['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'], 1],
[['D', 'G'], 2],
[['B', 'C', 'M', 'P'], 3],
[['F', 'H', 'V', 'W', 'Y'], 4],
[['K'], 5],
[['J', 'X'], 8],
[['Q', 'Z'], 10]]
def score(word):
total = 0
word = word.upper()
for letra in word:
for n in notas:
if letra in n[0]:
total += n[1]
return total | notas = [[['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'], 1], [['D', 'G'], 2], [['B', 'C', 'M', 'P'], 3], [['F', 'H', 'V', 'W', 'Y'], 4], [['K'], 5], [['J', 'X'], 8], [['Q', 'Z'], 10]]
def score(word):
total = 0
word = word.upper()
for letra in word:
for n in notas:
if letra in n[0]:
total += n[1]
return total |
"""Commands for chooks.py."""
__all__ = [
'add',
'disable',
'execute',
'install',
'list',
'remove',
]
| """Commands for chooks.py."""
__all__ = ['add', 'disable', 'execute', 'install', 'list', 'remove'] |
def splitDate(date):
splitup = date.split('.')
return splitup[1], splitup[0], splitup[2]
| def split_date(date):
splitup = date.split('.')
return (splitup[1], splitup[0], splitup[2]) |
class StyleSelector(object):
"""
Provides a way to apply styles based on custom logic.
StyleSelector()
"""
def SelectStyle(self,item,container):
"""
SelectStyle(self: StyleSelector,item: object,container: DependencyObject) -> Style
When overridden in a derived class,returns a System.Windows.Style based on custom logic.
item: The content.
container: The element to which the style will be applied.
Returns: Returns an application-specific style to apply; otherwise,null.
"""
pass
| class Styleselector(object):
"""
Provides a way to apply styles based on custom logic.
StyleSelector()
"""
def select_style(self, item, container):
"""
SelectStyle(self: StyleSelector,item: object,container: DependencyObject) -> Style
When overridden in a derived class,returns a System.Windows.Style based on custom logic.
item: The content.
container: The element to which the style will be applied.
Returns: Returns an application-specific style to apply; otherwise,null.
"""
pass |
# 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.
INCLUDES = """
#include <openssl/bn.h>
"""
TYPES = """
typedef ... BIGNUM;
/*
* TODO: This typedef is wrong.
*
* This is due to limitations of cffi.
* See https://bitbucket.org/cffi/cffi/issue/69
*
* For another possible work-around (not used here because it involves more
* complicated use of the cffi API which falls outside the general pattern used
* by this package), see
* http://paste.pound-python.org/show/iJcTUMkKeBeS6yXpZWUU/
*
* The work-around used here is to just be sure to declare a type that is at
* least as large as the real type. Maciej explains:
*
* <fijal> I think you want to declare your value too large (e.g. long)
* <fijal> that way you'll never pass garbage
*/
typedef uintptr_t BN_ULONG;
"""
FUNCTIONS = """
BIGNUM *BN_new(void);
void BN_free(BIGNUM *);
int BN_set_word(BIGNUM *, BN_ULONG);
char *BN_bn2hex(const BIGNUM *);
int BN_hex2bn(BIGNUM **, const char *);
int BN_dec2bn(BIGNUM **, const char *);
int BN_num_bits(const BIGNUM *);
"""
MACROS = """
"""
CUSTOMIZATIONS = """
"""
CONDITIONAL_NAMES = {}
| includes = '\n#include <openssl/bn.h>\n'
types = "\ntypedef ... BIGNUM;\n/*\n * TODO: This typedef is wrong.\n *\n * This is due to limitations of cffi.\n * See https://bitbucket.org/cffi/cffi/issue/69\n *\n * For another possible work-around (not used here because it involves more\n * complicated use of the cffi API which falls outside the general pattern used\n * by this package), see\n * http://paste.pound-python.org/show/iJcTUMkKeBeS6yXpZWUU/\n *\n * The work-around used here is to just be sure to declare a type that is at\n * least as large as the real type. Maciej explains:\n *\n * <fijal> I think you want to declare your value too large (e.g. long)\n * <fijal> that way you'll never pass garbage\n */\ntypedef uintptr_t BN_ULONG;\n"
functions = '\nBIGNUM *BN_new(void);\nvoid BN_free(BIGNUM *);\n\nint BN_set_word(BIGNUM *, BN_ULONG);\n\nchar *BN_bn2hex(const BIGNUM *);\nint BN_hex2bn(BIGNUM **, const char *);\nint BN_dec2bn(BIGNUM **, const char *);\n\nint BN_num_bits(const BIGNUM *);\n'
macros = '\n'
customizations = '\n'
conditional_names = {} |
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for x in range(len(nums)):
if nums[x] >= target:
return x
return (len(nums)) | class Solution:
def search_insert(self, nums: List[int], target: int) -> int:
for x in range(len(nums)):
if nums[x] >= target:
return x
return len(nums) |
#!/usr/bin/python
class TOSSerialReceptionError:
def __init__(self, chaine = "Vide"):
self.ch = chaine;
def __str__(self):
return self.ch;
class TOSSerialPacket:
"""Data structure that defines the content of a serial packet"""
def __init__(self):
messageType = 0;
dest = 0;
src = 0;
len = 0;
group = 0;
handler = 0;
payload = [];
class TOSSerialParser:
# Allowed parser states:
# 0: Init
# 1: Start or end flag read
# 2: Start flag read
# 3: Protocol byte read
# 4: Message type byte read
# 5: Address MSB read
# 6: Address LSB read
# 7: Destination byte
# 8: Source byte
# 9: Length byte read
# 10: Group byte read
# 11: Handler byte read
# 12: Payload byte read
# 13: CRC MSB read
# 14: CRC LSB read
# 15: End flag read
def __init__(self):
self.state = 0; # Init state
self.currentLength = 0;
self.currentPacket = TOSSerialPacket();
self.currentCRC = 0;
self.escapeChar = False;
def readByte(self, b):
if self.state == 0:
# Init state
if ord(b) == 0x7E:
# We have read a start or end packet flag
self.state = 1;
elif self.state == 1:
# "Start of end flag read" state
if ord(b) == 0x7E:
# We have read a start flag
self.state = 2;
else:
if ord(b) in [67, 68, 69, 255]:
# We have read the protocol byte
self.state = 3;
else:
# The protocol byte is not allowed
self.state = 1;
raise TOSSerialReceptionError("Protocol not allowed");
elif self.state == 2:
# "Start flag read" state
if ord(b) in [67, 68, 69, 255]:
# We have read the protocol byte
self.state = 3;
else:
# The protocol byte is not allowed
self.state = 1;
raise TOSSerialReceptionError("Protocol not allowed");
elif self.state == 3:
# "Protocol byte read" state
if ord(b) in [0, 1, 2, 255]:
# We have read the message type byte
self.currentPacket.messageType = ord(b);
self.state = 4;
else:
# The message type is not allowed
self.state = 1;
raise TOSSerialReceptionError("Message type not allowed");
elif self.state == 4:
# "Message type read" state
# We have read the MSB of address
self.state = 5;
elif self.state == 5:
# "Address MSB read" state
# We have read the LSB of address
self.state = 6;
elif self.state == 6:
# "Address LSB read" state
# We have read the destination byte
self.currentPacket.dest = ord(b);
self.state = 7;
elif self.state == 7:
self.currentPacket.src = ord(b);
self.state = 8;
elif self.state == 8:
self.currentPacket.len = ord(b);
self.state = 9;
elif self.state == 9:
self.currentPacket.group = ord(b);
self.state = 10;
elif self.state == 10:
self.currentPacket.handler = ord(b);
self.currentPacket.payload = [];
self.state = 11;
elif self.state == 11:
if ord(b) == 0x7E:
self.state = 1;
raise TOSSerialReceptionError("Byte 0x7E not allowed in payload")
elif ord(b) == 0x7D:
self.escapeChar = True;
self.currentLength = 0;
else:
self.currentPacket.payload.append(b);
self.escapeChar = False;
self.currentLength = 1;
self.state = 12;
elif self.state == 12:
if ord(b) == 0x7E:
self.state = 1;
if self.currentLength == self.currentPacket.len:
raise TOSSerialReceptionError("Byte 0x7E not allowed in CRC")
else:
raise TOSSerialReceptionError("Byte 0x7E not allowed in payload")
elif ord(b) == 0x7D:
self.escapeChar = True;
else:
if self.escapeChar:
self.escapeChar = False;
if ord(b) == 0x5E:
b = chr(0x7E);
elif ord(b) == 0x5D:
b = chr(0x7D);
else:
self.state = 1;
if self.currentLength == self.currentPacket.len:
raise TOSSerialReceptionError("Wrong escape sequence in CRC")
else:
raise TOSSerialReceptionError("Wrong escape sequence in payload")
if self.currentLength == self.currentPacket.len:
self.currentCRC = ord(b) << 8;
self.state = 13;
else:
self.currentPacket.payload.append(b);
self.currentLength += 1;
elif self.state == 13:
if ord(b) == 0x7E:
self.state = 1;
raise TOSSerialReceptionError("Byte 0x7E not allowed in CRC")
elif ord(b) == 0x7D:
self.escapeChar = True;
else:
if self.escapeChar:
self.escapeChar = False;
if ord(b) == 0x5E:
b = chr(0x7E);
elif ord(b) == 0x5D:
b = chr(0x7D);
else:
self.state = 1;
raise TOSSerialReceptionError("Wrong escape sequence in CRC")
self.currentCRC += ord(b);
# TODO: compute the real CRC and match with the read one
self.state = 14;
elif self.state == 14:
if ord(b) == 0x7E:
self.state = 15;
raise self.currentPacket;
else:
self.state = 1;
raise TOSSerialReceptionError("Byte should be 0x7E at end of message");
elif self.state == 15:
if ord(b) == 0x7E:
self.state = 2;
else:
self.state = 1;
raise TOSSerialReceptionError("Byte should be 0x7E at beginning of message");
| class Tosserialreceptionerror:
def __init__(self, chaine='Vide'):
self.ch = chaine
def __str__(self):
return self.ch
class Tosserialpacket:
"""Data structure that defines the content of a serial packet"""
def __init__(self):
message_type = 0
dest = 0
src = 0
len = 0
group = 0
handler = 0
payload = []
class Tosserialparser:
def __init__(self):
self.state = 0
self.currentLength = 0
self.currentPacket = tos_serial_packet()
self.currentCRC = 0
self.escapeChar = False
def read_byte(self, b):
if self.state == 0:
if ord(b) == 126:
self.state = 1
elif self.state == 1:
if ord(b) == 126:
self.state = 2
elif ord(b) in [67, 68, 69, 255]:
self.state = 3
else:
self.state = 1
raise tos_serial_reception_error('Protocol not allowed')
elif self.state == 2:
if ord(b) in [67, 68, 69, 255]:
self.state = 3
else:
self.state = 1
raise tos_serial_reception_error('Protocol not allowed')
elif self.state == 3:
if ord(b) in [0, 1, 2, 255]:
self.currentPacket.messageType = ord(b)
self.state = 4
else:
self.state = 1
raise tos_serial_reception_error('Message type not allowed')
elif self.state == 4:
self.state = 5
elif self.state == 5:
self.state = 6
elif self.state == 6:
self.currentPacket.dest = ord(b)
self.state = 7
elif self.state == 7:
self.currentPacket.src = ord(b)
self.state = 8
elif self.state == 8:
self.currentPacket.len = ord(b)
self.state = 9
elif self.state == 9:
self.currentPacket.group = ord(b)
self.state = 10
elif self.state == 10:
self.currentPacket.handler = ord(b)
self.currentPacket.payload = []
self.state = 11
elif self.state == 11:
if ord(b) == 126:
self.state = 1
raise tos_serial_reception_error('Byte 0x7E not allowed in payload')
elif ord(b) == 125:
self.escapeChar = True
self.currentLength = 0
else:
self.currentPacket.payload.append(b)
self.escapeChar = False
self.currentLength = 1
self.state = 12
elif self.state == 12:
if ord(b) == 126:
self.state = 1
if self.currentLength == self.currentPacket.len:
raise tos_serial_reception_error('Byte 0x7E not allowed in CRC')
else:
raise tos_serial_reception_error('Byte 0x7E not allowed in payload')
elif ord(b) == 125:
self.escapeChar = True
else:
if self.escapeChar:
self.escapeChar = False
if ord(b) == 94:
b = chr(126)
elif ord(b) == 93:
b = chr(125)
else:
self.state = 1
if self.currentLength == self.currentPacket.len:
raise tos_serial_reception_error('Wrong escape sequence in CRC')
else:
raise tos_serial_reception_error('Wrong escape sequence in payload')
if self.currentLength == self.currentPacket.len:
self.currentCRC = ord(b) << 8
self.state = 13
else:
self.currentPacket.payload.append(b)
self.currentLength += 1
elif self.state == 13:
if ord(b) == 126:
self.state = 1
raise tos_serial_reception_error('Byte 0x7E not allowed in CRC')
elif ord(b) == 125:
self.escapeChar = True
else:
if self.escapeChar:
self.escapeChar = False
if ord(b) == 94:
b = chr(126)
elif ord(b) == 93:
b = chr(125)
else:
self.state = 1
raise tos_serial_reception_error('Wrong escape sequence in CRC')
self.currentCRC += ord(b)
self.state = 14
elif self.state == 14:
if ord(b) == 126:
self.state = 15
raise self.currentPacket
else:
self.state = 1
raise tos_serial_reception_error('Byte should be 0x7E at end of message')
elif self.state == 15:
if ord(b) == 126:
self.state = 2
else:
self.state = 1
raise tos_serial_reception_error('Byte should be 0x7E at beginning of message') |
# -*- coding: utf-8 -*-
__author__ = "venkat"
__author_email__ = "venkatram0273@gmail.com"
# def comments_and_doc_strings() -> None:
# """
# These are multi-line comments.
# Used to document specific information about the function.
# These are called docstrings as well and can be accessed through func.__doc__
# Arguments:
# None: None
# Return:
# None
# """
# # This is single line comment used to highlight that is important logic to understand
# a: int = 23 # This is inline comment used to elaborate more about this specific line
# print(a)
# print(comments_and_doc_strings.__doc__)
# def google_style_guide(name: str, language: str = "en") -> int:
# """Say hello to a person
# Args:
# name: Name of the person to say hello
# language: Language in which the person wants greeting to be printed
# Returns:
# A number
# """
# print(" ".join(["Hello", name]))
# return 4
# google_style_guide(name="venkat")
# print(google_style_guide.__doc__)
| __author__ = 'venkat'
__author_email__ = 'venkatram0273@gmail.com' |
"""
List of 3rd party test dependencies. Generated by bazel-deps.
"""
def list_dependencies():
return [
{
"bind_args": {
"actual": "@com_typesafe_play_twirl_api_2_11",
"name": "jar/com/typesafe/play/twirl_api_2_11"
},
"import_args": {
"default_visibility": [ "//visibility:public" ],
"exports": [
"@org_scala_lang_modules_scala_xml_2_11",
"@scala_scala_library//jar"
],
"jar_sha256": "c42a3ca5866b783409998d90738ced7ae33506ed20022dae7f26438ded7d6dc5",
"jar_urls": [
"http://central.maven.org/maven2/com/typesafe/play/twirl-api_2.11/1.2.1/twirl-api_2.11-1.2.1.jar"
],
"licenses": [ "notice" ],
"name": "com_typesafe_play_twirl_api_2_11",
"srcjar_sha256": "c933aea8dec927643b112a7ef29e31b071b077d2d473abcc14317bc5685f139e",
"srcjar_urls": [
"http://central.maven.org/maven2/com/typesafe/play/twirl-api_2.11/1.2.1/twirl-api_2.11-1.2.1-sources.jar"
]
},
"lang": "scala"
},
{
"bind_args": {
"actual": "@org_scala_lang_modules_scala_parser_combinators_2_11",
"name": "jar/org/scala_lang/modules/scala_parser_combinators_2_11"
},
"import_args": {
"default_visibility": [ "//visibility:public" ],
"jar_sha256": "e8d15ebde0ccad54b5c9c82501afef8f7506a12f9500f2526d9c7e76a6ec3618",
"jar_urls": [
"http://central.maven.org/maven2/org/scala-lang/modules/scala-parser-combinators_2.11/1.0.6/scala-parser-combinators_2.11-1.0.6.jar"
],
"licenses": [ "notice" ],
"name": "org_scala_lang_modules_scala_parser_combinators_2_11",
"srcjar_sha256": "63e29b5fb131f2c6e5bf1bd8e40181fb7fdc96a7481f033a69b18734313eeb09",
"srcjar_urls": [
"http://central.maven.org/maven2/org/scala-lang/modules/scala-parser-combinators_2.11/1.0.6/scala-parser-combinators_2.11-1.0.6-sources.jar"
]
},
"lang": "java"
},
# duplicates in org.scala-lang.modules:scala-xml_2.11 promoted to 1.0.6
# - com.typesafe.play:twirl-api_2.11:1.2.1 wanted version 1.0.5
# - org.specs2:specs2-common_2.11:3.9.5 wanted version 1.0.6
{
"bind_args": {
"actual": "@org_scala_lang_modules_scala_xml_2_11",
"name": "jar/org/scala_lang/modules/scala_xml_2_11"
},
"import_args": {
"default_visibility": [ "//visibility:public" ],
"jar_sha256": "a3ec190294a15a26706123f140a087a8c0a5db8980e86755e5b8e8fc33ac8d3d",
"jar_urls": [
"http://central.maven.org/maven2/org/scala-lang/modules/scala-xml_2.11/1.0.6/scala-xml_2.11-1.0.6.jar"
],
"licenses": [ "notice" ],
"name": "org_scala_lang_modules_scala_xml_2_11",
"srcjar_sha256": "02a63308c374fd82db89fba59739bd1f30ec160cf8e422f9d26fde07274da8b0",
"srcjar_urls": [
"http://central.maven.org/maven2/org/scala-lang/modules/scala-xml_2.11/1.0.6/scala-xml_2.11-1.0.6-sources.jar"
]
},
"lang": "java"
},
{
"bind_args": {
"actual": "@org_scalaz_scalaz_core_2_11",
"name": "jar/org/scalaz/scalaz_core_2_11"
},
"import_args": {
"default_visibility": [ "//visibility:public" ],
"jar_sha256": "4d30a7d41cacbec7bf926be1745b6b5bb76712af3f220fe8461942dfa626c924",
"jar_urls": [
"http://central.maven.org/maven2/org/scalaz/scalaz-core_2.11/7.2.12/scalaz-core_2.11-7.2.12.jar"
],
"licenses": [ "notice" ],
"name": "org_scalaz_scalaz_core_2_11",
"srcjar_sha256": "b8e321c0a2f22cb121bf2d55f364c8404d5b221ad2bff54800d04e091c2f8e98",
"srcjar_urls": [
"http://central.maven.org/maven2/org/scalaz/scalaz-core_2.11/7.2.12/scalaz-core_2.11-7.2.12-sources.jar"
]
},
"lang": "java"
},
{
"bind_args": {
"actual": "@org_scalaz_scalaz_effect_2_11",
"name": "jar/org/scalaz/scalaz_effect_2_11"
},
"import_args": {
"default_visibility": [ "//visibility:public" ],
"jar_sha256": "70fa494665f44a0af53b89cbe739739a76ddebcc4c9c49637d86c022de2ab3bf",
"jar_urls": [
"http://central.maven.org/maven2/org/scalaz/scalaz-effect_2.11/7.2.12/scalaz-effect_2.11-7.2.12.jar"
],
"licenses": [ "notice" ],
"name": "org_scalaz_scalaz_effect_2_11",
"srcjar_sha256": "7a7ad93f4f36c6bd46ac246eb42feef09665186a5f1296723aa826da7ddb7ca0",
"srcjar_urls": [
"http://central.maven.org/maven2/org/scalaz/scalaz-effect_2.11/7.2.12/scalaz-effect_2.11-7.2.12-sources.jar"
]
},
"lang": "java"
},
{
"bind_args": {
"actual": "@org_specs2_specs2_common_2_11",
"name": "jar/org/specs2/specs2_common_2_11"
},
"import_args": {
"default_visibility": [ "//visibility:public" ],
"exports": [
"@org_scala_lang_modules_scala_parser_combinators_2_11",
"@org_scala_lang_modules_scala_xml_2_11",
"@org_scalaz_scalaz_core_2_11",
"@org_scalaz_scalaz_effect_2_11",
"@scala_scala_reflect//jar"
],
"jar_sha256": "6c09027d91b464130df54716c0c144e14ae4c8507f857e409e2d0980a388b157",
"jar_urls": [
"http://central.maven.org/maven2/org/specs2/specs2-common_2.11/3.9.5/specs2-common_2.11-3.9.5.jar"
],
"licenses": [ "notice" ],
"name": "org_specs2_specs2_common_2_11",
"srcjar_sha256": "2f75c93722f049235de6e5e3fa5b77c1c10a93aff7f25ddd5e6d5839c6913152",
"srcjar_urls": [
"http://central.maven.org/maven2/org/specs2/specs2-common_2.11/3.9.5/specs2-common_2.11-3.9.5-sources.jar"
]
},
"lang": "java"
},
{
"bind_args": {
"actual": "@org_specs2_specs2_core_2_11",
"name": "jar/org/specs2/specs2_core_2_11"
},
"import_args": {
"default_visibility": [ "//visibility:public" ],
"exports": [
"@org_specs2_specs2_matcher_2_11",
"@scala_scala_library//jar"
],
"jar_sha256": "f5c9e5f77cb43925cbc06692bf2e88351de439bcafc354a80d1b93410ab34c46",
"jar_urls": [
"http://central.maven.org/maven2/org/specs2/specs2-core_2.11/3.9.5/specs2-core_2.11-3.9.5.jar"
],
"licenses": [ "notice" ],
"name": "org_specs2_specs2_core_2_11",
"srcjar_sha256": "e2bf3ebe229ae835fb42706d94180c163186b54b8aa2a01a69f94c48b91347c4",
"srcjar_urls": [
"http://central.maven.org/maven2/org/specs2/specs2-core_2.11/3.9.5/specs2-core_2.11-3.9.5-sources.jar"
]
},
"lang": "scala"
},
{
"bind_args": {
"actual": "@org_specs2_specs2_matcher_2_11",
"name": "jar/org/specs2/specs2_matcher_2_11"
},
"import_args": {
"default_visibility": [ "//visibility:public" ],
"exports": [ "@org_specs2_specs2_common_2_11" ],
"jar_sha256": "071cba2168a621d2355aceacdf6b59dd2cb83e41591864d1f3d827abf96c13a5",
"jar_urls": [
"http://central.maven.org/maven2/org/specs2/specs2-matcher_2.11/3.9.5/specs2-matcher_2.11-3.9.5.jar"
],
"licenses": [ "notice" ],
"name": "org_specs2_specs2_matcher_2_11",
"srcjar_sha256": "526d5b0cfd941a67eebf83b436bc2dda5f85e11a7274ea0d89a8bedd7bf67959",
"srcjar_urls": [
"http://central.maven.org/maven2/org/specs2/specs2-matcher_2.11/3.9.5/specs2-matcher_2.11-3.9.5-sources.jar"
]
},
"lang": "java"
}
]
| """
List of 3rd party test dependencies. Generated by bazel-deps.
"""
def list_dependencies():
return [{'bind_args': {'actual': '@com_typesafe_play_twirl_api_2_11', 'name': 'jar/com/typesafe/play/twirl_api_2_11'}, 'import_args': {'default_visibility': ['//visibility:public'], 'exports': ['@org_scala_lang_modules_scala_xml_2_11', '@scala_scala_library//jar'], 'jar_sha256': 'c42a3ca5866b783409998d90738ced7ae33506ed20022dae7f26438ded7d6dc5', 'jar_urls': ['http://central.maven.org/maven2/com/typesafe/play/twirl-api_2.11/1.2.1/twirl-api_2.11-1.2.1.jar'], 'licenses': ['notice'], 'name': 'com_typesafe_play_twirl_api_2_11', 'srcjar_sha256': 'c933aea8dec927643b112a7ef29e31b071b077d2d473abcc14317bc5685f139e', 'srcjar_urls': ['http://central.maven.org/maven2/com/typesafe/play/twirl-api_2.11/1.2.1/twirl-api_2.11-1.2.1-sources.jar']}, 'lang': 'scala'}, {'bind_args': {'actual': '@org_scala_lang_modules_scala_parser_combinators_2_11', 'name': 'jar/org/scala_lang/modules/scala_parser_combinators_2_11'}, 'import_args': {'default_visibility': ['//visibility:public'], 'jar_sha256': 'e8d15ebde0ccad54b5c9c82501afef8f7506a12f9500f2526d9c7e76a6ec3618', 'jar_urls': ['http://central.maven.org/maven2/org/scala-lang/modules/scala-parser-combinators_2.11/1.0.6/scala-parser-combinators_2.11-1.0.6.jar'], 'licenses': ['notice'], 'name': 'org_scala_lang_modules_scala_parser_combinators_2_11', 'srcjar_sha256': '63e29b5fb131f2c6e5bf1bd8e40181fb7fdc96a7481f033a69b18734313eeb09', 'srcjar_urls': ['http://central.maven.org/maven2/org/scala-lang/modules/scala-parser-combinators_2.11/1.0.6/scala-parser-combinators_2.11-1.0.6-sources.jar']}, 'lang': 'java'}, {'bind_args': {'actual': '@org_scala_lang_modules_scala_xml_2_11', 'name': 'jar/org/scala_lang/modules/scala_xml_2_11'}, 'import_args': {'default_visibility': ['//visibility:public'], 'jar_sha256': 'a3ec190294a15a26706123f140a087a8c0a5db8980e86755e5b8e8fc33ac8d3d', 'jar_urls': ['http://central.maven.org/maven2/org/scala-lang/modules/scala-xml_2.11/1.0.6/scala-xml_2.11-1.0.6.jar'], 'licenses': ['notice'], 'name': 'org_scala_lang_modules_scala_xml_2_11', 'srcjar_sha256': '02a63308c374fd82db89fba59739bd1f30ec160cf8e422f9d26fde07274da8b0', 'srcjar_urls': ['http://central.maven.org/maven2/org/scala-lang/modules/scala-xml_2.11/1.0.6/scala-xml_2.11-1.0.6-sources.jar']}, 'lang': 'java'}, {'bind_args': {'actual': '@org_scalaz_scalaz_core_2_11', 'name': 'jar/org/scalaz/scalaz_core_2_11'}, 'import_args': {'default_visibility': ['//visibility:public'], 'jar_sha256': '4d30a7d41cacbec7bf926be1745b6b5bb76712af3f220fe8461942dfa626c924', 'jar_urls': ['http://central.maven.org/maven2/org/scalaz/scalaz-core_2.11/7.2.12/scalaz-core_2.11-7.2.12.jar'], 'licenses': ['notice'], 'name': 'org_scalaz_scalaz_core_2_11', 'srcjar_sha256': 'b8e321c0a2f22cb121bf2d55f364c8404d5b221ad2bff54800d04e091c2f8e98', 'srcjar_urls': ['http://central.maven.org/maven2/org/scalaz/scalaz-core_2.11/7.2.12/scalaz-core_2.11-7.2.12-sources.jar']}, 'lang': 'java'}, {'bind_args': {'actual': '@org_scalaz_scalaz_effect_2_11', 'name': 'jar/org/scalaz/scalaz_effect_2_11'}, 'import_args': {'default_visibility': ['//visibility:public'], 'jar_sha256': '70fa494665f44a0af53b89cbe739739a76ddebcc4c9c49637d86c022de2ab3bf', 'jar_urls': ['http://central.maven.org/maven2/org/scalaz/scalaz-effect_2.11/7.2.12/scalaz-effect_2.11-7.2.12.jar'], 'licenses': ['notice'], 'name': 'org_scalaz_scalaz_effect_2_11', 'srcjar_sha256': '7a7ad93f4f36c6bd46ac246eb42feef09665186a5f1296723aa826da7ddb7ca0', 'srcjar_urls': ['http://central.maven.org/maven2/org/scalaz/scalaz-effect_2.11/7.2.12/scalaz-effect_2.11-7.2.12-sources.jar']}, 'lang': 'java'}, {'bind_args': {'actual': '@org_specs2_specs2_common_2_11', 'name': 'jar/org/specs2/specs2_common_2_11'}, 'import_args': {'default_visibility': ['//visibility:public'], 'exports': ['@org_scala_lang_modules_scala_parser_combinators_2_11', '@org_scala_lang_modules_scala_xml_2_11', '@org_scalaz_scalaz_core_2_11', '@org_scalaz_scalaz_effect_2_11', '@scala_scala_reflect//jar'], 'jar_sha256': '6c09027d91b464130df54716c0c144e14ae4c8507f857e409e2d0980a388b157', 'jar_urls': ['http://central.maven.org/maven2/org/specs2/specs2-common_2.11/3.9.5/specs2-common_2.11-3.9.5.jar'], 'licenses': ['notice'], 'name': 'org_specs2_specs2_common_2_11', 'srcjar_sha256': '2f75c93722f049235de6e5e3fa5b77c1c10a93aff7f25ddd5e6d5839c6913152', 'srcjar_urls': ['http://central.maven.org/maven2/org/specs2/specs2-common_2.11/3.9.5/specs2-common_2.11-3.9.5-sources.jar']}, 'lang': 'java'}, {'bind_args': {'actual': '@org_specs2_specs2_core_2_11', 'name': 'jar/org/specs2/specs2_core_2_11'}, 'import_args': {'default_visibility': ['//visibility:public'], 'exports': ['@org_specs2_specs2_matcher_2_11', '@scala_scala_library//jar'], 'jar_sha256': 'f5c9e5f77cb43925cbc06692bf2e88351de439bcafc354a80d1b93410ab34c46', 'jar_urls': ['http://central.maven.org/maven2/org/specs2/specs2-core_2.11/3.9.5/specs2-core_2.11-3.9.5.jar'], 'licenses': ['notice'], 'name': 'org_specs2_specs2_core_2_11', 'srcjar_sha256': 'e2bf3ebe229ae835fb42706d94180c163186b54b8aa2a01a69f94c48b91347c4', 'srcjar_urls': ['http://central.maven.org/maven2/org/specs2/specs2-core_2.11/3.9.5/specs2-core_2.11-3.9.5-sources.jar']}, 'lang': 'scala'}, {'bind_args': {'actual': '@org_specs2_specs2_matcher_2_11', 'name': 'jar/org/specs2/specs2_matcher_2_11'}, 'import_args': {'default_visibility': ['//visibility:public'], 'exports': ['@org_specs2_specs2_common_2_11'], 'jar_sha256': '071cba2168a621d2355aceacdf6b59dd2cb83e41591864d1f3d827abf96c13a5', 'jar_urls': ['http://central.maven.org/maven2/org/specs2/specs2-matcher_2.11/3.9.5/specs2-matcher_2.11-3.9.5.jar'], 'licenses': ['notice'], 'name': 'org_specs2_specs2_matcher_2_11', 'srcjar_sha256': '526d5b0cfd941a67eebf83b436bc2dda5f85e11a7274ea0d89a8bedd7bf67959', 'srcjar_urls': ['http://central.maven.org/maven2/org/specs2/specs2-matcher_2.11/3.9.5/specs2-matcher_2.11-3.9.5-sources.jar']}, 'lang': 'java'}] |
# -*- coding: utf-8 -*-
'''
File name: code\nontransitive_sets_of_dice\sol_376.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #376 :: Nontransitive sets of dice
#
# For more information see:
# https://projecteuler.net/problem=376
# Problem Statement
'''
Consider the following set of dice with nonstandard pips:
Die A: 1 4 4 4 4 4
Die B: 2 2 2 5 5 5
Die C: 3 3 3 3 3 6
A game is played by two players picking a die in turn and rolling it. The player who rolls the highest value wins.
If the first player picks die A and the second player picks die B we get
P(second player wins) = 7/12 > 1/2
If the first player picks die B and the second player picks die C we get
P(second player wins) = 7/12 > 1/2
If the first player picks die C and the second player picks die A we get
P(second player wins) = 25/36 > 1/2
So whatever die the first player picks, the second player can pick another die and have a larger than 50% chance of winning.
A set of dice having this property is called a nontransitive set of dice.
We wish to investigate how many sets of nontransitive dice exist. We will assume the following conditions:There are three six-sided dice with each side having between 1 and N pips, inclusive.
Dice with the same set of pips are equal, regardless of which side on the die the pips are located.
The same pip value may appear on multiple dice; if both players roll the same value neither player wins.
The sets of dice {A,B,C}, {B,C,A} and {C,A,B} are the same set.
For N = 7 we find there are 9780 such sets.
How many are there for N = 30 ?
'''
# Solution
# Solution Approach
'''
'''
| """
File name: code
ontransitive_sets_of_dice\\sol_376.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
"""
'\nConsider the following set of dice with nonstandard pips:\n\n\n\nDie A: 1 4 4 4 4 4\nDie B: 2 2 2 5 5 5\nDie C: 3 3 3 3 3 6\n\n\nA game is played by two players picking a die in turn and rolling it. The player who rolls the highest value wins.\n\n\n\nIf the first player picks die A and the second player picks die B we get\nP(second player wins) = 7/12 > 1/2\n\n\nIf the first player picks die B and the second player picks die C we get\nP(second player wins) = 7/12 > 1/2\n\n\nIf the first player picks die C and the second player picks die A we get\nP(second player wins) = 25/36 > 1/2\n\n\nSo whatever die the first player picks, the second player can pick another die and have a larger than 50% chance of winning.\nA set of dice having this property is called a nontransitive set of dice.\n\n\n\nWe wish to investigate how many sets of nontransitive dice exist. We will assume the following conditions:There are three six-sided dice with each side having between 1 and N pips, inclusive.\nDice with the same set of pips are equal, regardless of which side on the die the pips are located.\nThe same pip value may appear on multiple dice; if both players roll the same value neither player wins.\nThe sets of dice {A,B,C}, {B,C,A} and {C,A,B} are the same set.\n\nFor N = 7 we find there are 9780 such sets.\nHow many are there for N = 30 ?\n'
'\n' |
def gcd(m,n):
while n>0:
t=m%n
m=n
n=t
return m
input();A=list(map(int,input().split()))
input();B=list(map(int,input().split()))
AA=1; BB=1
for i in A: AA*=i
for i in B: BB*=i
result=gcd(AA,BB)
if result >= 10**9: print("%09d" % (result%(10**9)))
else: print(result) | def gcd(m, n):
while n > 0:
t = m % n
m = n
n = t
return m
input()
a = list(map(int, input().split()))
input()
b = list(map(int, input().split()))
aa = 1
bb = 1
for i in A:
aa *= i
for i in B:
bb *= i
result = gcd(AA, BB)
if result >= 10 ** 9:
print('%09d' % (result % 10 ** 9))
else:
print(result) |
"""
Scenarios:
Parameters (some/all/None) -> reduce
Result (1, 2) -> reduce
Combinations of above -> reduce
Filter[parameter],Filter[result],Filter[parameter+result],None
= (3 + 2 + 6) * 4 = 44 tests
test: data recovered (shape,dtype, values), description recovered, tasks marked as complete, locations in index, subsets stored in index
test: running again does not do any work
""" | """
Scenarios:
Parameters (some/all/None) -> reduce
Result (1, 2) -> reduce
Combinations of above -> reduce
Filter[parameter],Filter[result],Filter[parameter+result],None
= (3 + 2 + 6) * 4 = 44 tests
test: data recovered (shape,dtype, values), description recovered, tasks marked as complete, locations in index, subsets stored in index
test: running again does not do any work
""" |
def title_card(code_name):
print('\n~~~~~~~~~~~~~~~~~~~~~~~')
print(code_name)
print('~~~~~~~~~~~~~~~~~~~~~~~ \n')
| def title_card(code_name):
print('\n~~~~~~~~~~~~~~~~~~~~~~~')
print(code_name)
print('~~~~~~~~~~~~~~~~~~~~~~~ \n') |
# 155. Min Stack
# ttungl@gmail.com
class MinStack(object):
# using list array
# runtime: 72 ms
def __init__(self):
self.stack = []
def push(self, x):
if not self.stack:
self.stack.append((x, x))
else:
self.stack.append((x, min(x, self.stack[-1][1]))) # keep track on x and min.
def pop(self):
if self.stack:
self.stack.pop()
def top(self):
if self.stack:
return self.stack[-1][0]
return None
def getMin(self):
if self.stack:
return self.stack[-1][1]
return None
#################################################
# sol 2:
# keep stack and min in the separate lists.
# runtime: 79ms
def __init__(self):
self.stack = list()
self.minlist = list()
def push(self, x):
self.stack.append(x)
if not self.minlist:
self.minlist.append(x)
else:
self.minlist.append(min(x, self.minlist[-1]))
def pop(self):
if self.stack:
del self.stack[-1]
del self.minlist[-1]
def top(self):
return self.stack[-1]
def getMin(self):
return self.minlist[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
| class Minstack(object):
def __init__(self):
self.stack = []
def push(self, x):
if not self.stack:
self.stack.append((x, x))
else:
self.stack.append((x, min(x, self.stack[-1][1])))
def pop(self):
if self.stack:
self.stack.pop()
def top(self):
if self.stack:
return self.stack[-1][0]
return None
def get_min(self):
if self.stack:
return self.stack[-1][1]
return None
def __init__(self):
self.stack = list()
self.minlist = list()
def push(self, x):
self.stack.append(x)
if not self.minlist:
self.minlist.append(x)
else:
self.minlist.append(min(x, self.minlist[-1]))
def pop(self):
if self.stack:
del self.stack[-1]
del self.minlist[-1]
def top(self):
return self.stack[-1]
def get_min(self):
return self.minlist[-1] |
def check_similar_sequences(sequences):
"""
takes a dictionary of sequences, removes the gaps and checks which sequences are similar
return a dictionary of a group number as key and the similar sequence id as a list as vlaue
:param sequences: a dictionary of sequences
:return groups: a dictionary of a group number as key and members as a list as value
"""
# I am doing it in probably a hacky way
# However, this tool won't be dealing with huge amount of sequences in general
# so having the sequences as keys (hashes) should be fine for use case of this tool
seq_to_id = dict()
for seq_name, seq in sequences.items():
if seq not in seq_to_id:
seq_to_id[seq] = [seq_name]
else:
seq_to_id[seq].append(seq_name)
group = dict()
idx = 0
for seq, group_list in seq_to_id.items():
group['group_' + str(idx)] = group_list
idx += 1
return group
| def check_similar_sequences(sequences):
"""
takes a dictionary of sequences, removes the gaps and checks which sequences are similar
return a dictionary of a group number as key and the similar sequence id as a list as vlaue
:param sequences: a dictionary of sequences
:return groups: a dictionary of a group number as key and members as a list as value
"""
seq_to_id = dict()
for (seq_name, seq) in sequences.items():
if seq not in seq_to_id:
seq_to_id[seq] = [seq_name]
else:
seq_to_id[seq].append(seq_name)
group = dict()
idx = 0
for (seq, group_list) in seq_to_id.items():
group['group_' + str(idx)] = group_list
idx += 1
return group |
# -*- coding: utf-8 -*-
# Copyright 2013 Lyft
#
# 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.
"""General information about Amazon Web Services, such as region-to-endpoint
mappings.
"""
### EC2 Instances ###
# map from instance type to number of compute units
# from http://aws.amazon.com/ec2/instance-types/
# and http://aws.amazon.com/ec2/previous-generation/
EC2_INSTANCE_TYPE_TO_COMPUTE_UNITS = {
'c1.medium': 5,
'c1.xlarge': 20,
'c3.2xlarge': 28,
'c3.4xlarge': 55,
'c3.8xlarge': 108,
'c3.large': 7,
'c3.xlarge': 14,
'c4.2xlarge': 31,
'c4.4xlarge': 62,
'c4.8xlarge': 132,
'c4.large': 8,
'c4.xlarge': 16,
'cc1.4xlarge': 33.5,
'cc2.8xlarge': 32,
'cg1.4xlarge': 33.5,
'cr1.8xlarge': 32,
'd2.2xlarge': 28,
'd2.4xlarge': 56,
'd2.8xlarge': 116,
'd2.xlarge': 14,
'g2.2xlarge': 26,
'hi1.4xlarge': 16,
'hs2.8xlarge': 17,
'i2.2xlarge': 27,
'i2.4xlarge': 53,
'i2.8xlarge': 104,
'i2.xlarge': 14,
'm1.large': 4,
'm1.medium': 1,
'm1.small': 1,
'm1.xlarge': 8,
'm2.2xlarge': 13,
'm2.4xlarge': 26,
'm2.xlarge': 6.5,
'm3.2xlarge': 26,
'm3.large': 6.5,
'm3.medium': 3,
'm3.xlarge': 13,
'r3.2xlarge': 26,
'r3.4xlarge': 52,
'r3.8xlarge': 104,
'r3.large': 6.5,
'r3.xlarge': 13,
't1.micro': 1,
# t2 units are "burstable", and receive a certain number of "credits"
# (CPU-minutes) per hour. MapReduce usage is pretty much continuous, so
# just rating them by how much they can use in one hour.
't2.medium': 0.4,
't2.micro': 0.1,
't2.small': 0.2,
}
# map from instance type to GB of memory
# from http://aws.amazon.com/ec2/instance-types/
# and http://aws.amazon.com/ec2/previous-generation/
EC2_INSTANCE_TYPE_TO_MEMORY = {
'c1.medium': 1.7,
'c1.xlarge': 7,
'c3.2xlarge': 15,
'c3.4xlarge': 30,
'c3.8xlarge': 60,
'c3.large': 3.75,
'c3.xlarge': 7.5,
'c4.2xlarge': 15,
'c4.4xlarge': 30,
'c4.8xlarge': 60,
'c4.large': 3.75,
'c4.xlarge': 7.5,
'cc1.4xlarge': 23,
'cc2.8xlarge': 60.5,
'cg1.4xlarge': 22,
'cr1.8xlarge': 244,
'd2.2xlarge': 61,
'd2.4xlarge': 122,
'd2.8xlarge': 244,
'd2.xlarge': 30.5,
'g2.2xlarge': 15,
'hi1.4xlarge': 60.5,
'hs1.8xlarge': 117,
'i2.2xlarge': 61,
'i2.4xlarge': 122,
'i2.8xlarge': 244,
'i2.xlarge': 30.5,
'm1.large': 7.5,
'm1.medium': 3.75,
'm1.small': 1.7,
'm1.xlarge': 15,
'm2.2xlarge': 34.2,
'm2.4xlarge': 68.4,
'm2.xlarge': 17.5,
'm3.2xlarge': 30,
'm3.large': 7.5,
'm3.medium': 3.75,
'm3.xlarge': 15,
'r3.2xlarge': 61,
'r3.4xlarge': 122,
'r3.8xlarge': 244,
'r3.large': 15,
'r3.xlarge': 30.5,
't1.micro': 0.615,
't2.medium': 4,
't2.micro': 1,
't2.small': 2,
}
### EMR ###
# EMR's hard limit on number of steps in a job flow
MAX_STEPS_PER_JOB_FLOW = 256
### Regions ###
# Based on http://docs.aws.amazon.com/general/latest/gr/rande.html
# See Issue #658 for why we don't just let boto handle this.
# where to connect to EMR. The docs say
# elasticmapreduce.<region>.amazonaws.com, but the SSL certificates,
# they tell a different story. See Issue #621.
# where the AWS docs say to connect to EMR
_EMR_REGION_ENDPOINT = 'elasticmapreduce.%(region)s.amazonaws.com'
# the host that currently works with EMR's SSL certificate
_EMR_REGION_SSL_HOST = '%(region)s.elasticmapreduce.amazonaws.com'
# the regionless endpoint doesn't have SSL issues
_EMR_REGIONLESS_ENDPOINT = 'elasticmapreduce.amazonaws.com'
# where to connect to S3
_S3_REGION_ENDPOINT = 's3-%(region)s.amazonaws.com'
_S3_REGIONLESS_ENDPOINT = 's3.amazonaws.com'
# us-east-1 doesn't have its own endpoint or need bucket location constraints
_S3_REGION_WITH_NO_LOCATION_CONSTRAINT = 'us-east-1'
# "EU" is an alias for the eu-west-1 region
_ALIAS_TO_REGION = {
'eu': 'eu-west-1',
}
# The region to assume if none is specified
_DEFAULT_REGION = 'us-east-1'
def _fix_region(region):
"""Convert "EU" to "eu-west-1", None to '', and convert to lowercase."""
region = (region or '').lower()
return _ALIAS_TO_REGION.get(region) or region
def emr_endpoint_for_region(region):
"""Get the host for Elastic MapReduce in the given AWS region."""
region = _fix_region(region)
if not region:
return _EMR_REGIONLESS_ENDPOINT
else:
return _EMR_REGION_ENDPOINT % {'region': region}
def emr_ssl_host_for_region(region):
"""Get the host for Elastic MapReduce that matches their SSL cert
for the given region. (See Issue #621.)"""
region = _fix_region(region)
if not region:
return _EMR_REGIONLESS_ENDPOINT
else:
return _EMR_REGION_SSL_HOST % {'region': region}
def s3_endpoint_for_region(region):
"""Get the host for S3 in the given AWS region.
This will accept ``''`` for region as well, so it's fine to
use location constraint in place of region.
"""
region = _fix_region(region)
if not region or region == _S3_REGION_WITH_NO_LOCATION_CONSTRAINT:
return _S3_REGIONLESS_ENDPOINT
else:
return _S3_REGION_ENDPOINT % {'region': region}
def s3_location_constraint_for_region(region):
"""Get the location constraint an S3 bucket needs so that other AWS
services can connect to it in the given region."""
region = _fix_region(region)
if not region or region == _S3_REGION_WITH_NO_LOCATION_CONSTRAINT:
return ''
else:
return region
| """General information about Amazon Web Services, such as region-to-endpoint
mappings.
"""
ec2_instance_type_to_compute_units = {'c1.medium': 5, 'c1.xlarge': 20, 'c3.2xlarge': 28, 'c3.4xlarge': 55, 'c3.8xlarge': 108, 'c3.large': 7, 'c3.xlarge': 14, 'c4.2xlarge': 31, 'c4.4xlarge': 62, 'c4.8xlarge': 132, 'c4.large': 8, 'c4.xlarge': 16, 'cc1.4xlarge': 33.5, 'cc2.8xlarge': 32, 'cg1.4xlarge': 33.5, 'cr1.8xlarge': 32, 'd2.2xlarge': 28, 'd2.4xlarge': 56, 'd2.8xlarge': 116, 'd2.xlarge': 14, 'g2.2xlarge': 26, 'hi1.4xlarge': 16, 'hs2.8xlarge': 17, 'i2.2xlarge': 27, 'i2.4xlarge': 53, 'i2.8xlarge': 104, 'i2.xlarge': 14, 'm1.large': 4, 'm1.medium': 1, 'm1.small': 1, 'm1.xlarge': 8, 'm2.2xlarge': 13, 'm2.4xlarge': 26, 'm2.xlarge': 6.5, 'm3.2xlarge': 26, 'm3.large': 6.5, 'm3.medium': 3, 'm3.xlarge': 13, 'r3.2xlarge': 26, 'r3.4xlarge': 52, 'r3.8xlarge': 104, 'r3.large': 6.5, 'r3.xlarge': 13, 't1.micro': 1, 't2.medium': 0.4, 't2.micro': 0.1, 't2.small': 0.2}
ec2_instance_type_to_memory = {'c1.medium': 1.7, 'c1.xlarge': 7, 'c3.2xlarge': 15, 'c3.4xlarge': 30, 'c3.8xlarge': 60, 'c3.large': 3.75, 'c3.xlarge': 7.5, 'c4.2xlarge': 15, 'c4.4xlarge': 30, 'c4.8xlarge': 60, 'c4.large': 3.75, 'c4.xlarge': 7.5, 'cc1.4xlarge': 23, 'cc2.8xlarge': 60.5, 'cg1.4xlarge': 22, 'cr1.8xlarge': 244, 'd2.2xlarge': 61, 'd2.4xlarge': 122, 'd2.8xlarge': 244, 'd2.xlarge': 30.5, 'g2.2xlarge': 15, 'hi1.4xlarge': 60.5, 'hs1.8xlarge': 117, 'i2.2xlarge': 61, 'i2.4xlarge': 122, 'i2.8xlarge': 244, 'i2.xlarge': 30.5, 'm1.large': 7.5, 'm1.medium': 3.75, 'm1.small': 1.7, 'm1.xlarge': 15, 'm2.2xlarge': 34.2, 'm2.4xlarge': 68.4, 'm2.xlarge': 17.5, 'm3.2xlarge': 30, 'm3.large': 7.5, 'm3.medium': 3.75, 'm3.xlarge': 15, 'r3.2xlarge': 61, 'r3.4xlarge': 122, 'r3.8xlarge': 244, 'r3.large': 15, 'r3.xlarge': 30.5, 't1.micro': 0.615, 't2.medium': 4, 't2.micro': 1, 't2.small': 2}
max_steps_per_job_flow = 256
_emr_region_endpoint = 'elasticmapreduce.%(region)s.amazonaws.com'
_emr_region_ssl_host = '%(region)s.elasticmapreduce.amazonaws.com'
_emr_regionless_endpoint = 'elasticmapreduce.amazonaws.com'
_s3_region_endpoint = 's3-%(region)s.amazonaws.com'
_s3_regionless_endpoint = 's3.amazonaws.com'
_s3_region_with_no_location_constraint = 'us-east-1'
_alias_to_region = {'eu': 'eu-west-1'}
_default_region = 'us-east-1'
def _fix_region(region):
"""Convert "EU" to "eu-west-1", None to '', and convert to lowercase."""
region = (region or '').lower()
return _ALIAS_TO_REGION.get(region) or region
def emr_endpoint_for_region(region):
"""Get the host for Elastic MapReduce in the given AWS region."""
region = _fix_region(region)
if not region:
return _EMR_REGIONLESS_ENDPOINT
else:
return _EMR_REGION_ENDPOINT % {'region': region}
def emr_ssl_host_for_region(region):
"""Get the host for Elastic MapReduce that matches their SSL cert
for the given region. (See Issue #621.)"""
region = _fix_region(region)
if not region:
return _EMR_REGIONLESS_ENDPOINT
else:
return _EMR_REGION_SSL_HOST % {'region': region}
def s3_endpoint_for_region(region):
"""Get the host for S3 in the given AWS region.
This will accept ``''`` for region as well, so it's fine to
use location constraint in place of region.
"""
region = _fix_region(region)
if not region or region == _S3_REGION_WITH_NO_LOCATION_CONSTRAINT:
return _S3_REGIONLESS_ENDPOINT
else:
return _S3_REGION_ENDPOINT % {'region': region}
def s3_location_constraint_for_region(region):
"""Get the location constraint an S3 bucket needs so that other AWS
services can connect to it in the given region."""
region = _fix_region(region)
if not region or region == _S3_REGION_WITH_NO_LOCATION_CONSTRAINT:
return ''
else:
return region |
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return -1
N = len(nums)
sums = [0] * (N + 1)
for i in range(N):
sums[i + 1] = sums[i] + nums[i]
for i in range(N):
if sums[i] == sums[-1] - sums[i + 1]:
return i
return -1
| class Solution(object):
def pivot_index(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return -1
n = len(nums)
sums = [0] * (N + 1)
for i in range(N):
sums[i + 1] = sums[i] + nums[i]
for i in range(N):
if sums[i] == sums[-1] - sums[i + 1]:
return i
return -1 |
# This file contains defaults that this module uses
# Max allowed for assumed safe request, any higher than this
# Will raise a RateLimitReached Exception
# If the rate limiter cant assume a safe request
# Due to the assumption being to risky at this point
max_safe_requests = 40
# quater of safe requests
max_ongoing_requests = 10
# This module prefers safety over max efficiency
# This allows safe multi-script usage additionally
# Should never be over 50
ratelimit_max = 40
ratelimit_within = 30
# To be safe the module overshoots
# The actual max time of around 30
# by 20 seconds by default
ratelimit_maxsleeps = 90
# Amount of time to sleep before retrying rate limit check
ratelimit_sleep_time = 0.5 | max_safe_requests = 40
max_ongoing_requests = 10
ratelimit_max = 40
ratelimit_within = 30
ratelimit_maxsleeps = 90
ratelimit_sleep_time = 0.5 |
x = 10
def foo(x):
y = x * 2
return bar(y)
def bar(y):
y = x / 2
return y
z = foo(x)
| x = 10
def foo(x):
y = x * 2
return bar(y)
def bar(y):
y = x / 2
return y
z = foo(x) |
# Copyright (c) 2020 Vishnu J. Seesahai
# Use of this source code is governed by an MIT
# license that can be found in the LICENSE file.
MIN_CONF = '6'
MAX_CONF = '9999999'
| min_conf = '6'
max_conf = '9999999' |
class Solution(object):
def generatePalindromes(self, s):
"""
:type s: str
:rtype: List[str]
"""
dic = {}
half = []
res = []
for c in s:
dic[c] = dic.get(c, 0) + 1
odd, even = 0, 0
for c in dic:
if dic[c] % 2 == 0:
even += 1
else:
odd += 1
if odd > 1:
return []
# generate half
seed = []
mid = ''
for c in dic:
if dic[c] % 2 == 1:
mid = c
seed.extend([c] * (dic[c] / 2))
self.permute(half, seed, 0)
# merge half to get res
for r in half:
res.append(''.join(r) + mid + ''.join(reversed(r)))
return res
def permute(self, res, num, index):
if index == len(num):
res.append(list(num))
return
appeared = set()
for i in range(index, len(num)):
if num[i] in appeared:
continue
appeared.add(num[i])
num[i], num[index] = num[index], num[i]
self.permute(res, num, index + 1)
num[i], num[index] = num[index], num[i]
| class Solution(object):
def generate_palindromes(self, s):
"""
:type s: str
:rtype: List[str]
"""
dic = {}
half = []
res = []
for c in s:
dic[c] = dic.get(c, 0) + 1
(odd, even) = (0, 0)
for c in dic:
if dic[c] % 2 == 0:
even += 1
else:
odd += 1
if odd > 1:
return []
seed = []
mid = ''
for c in dic:
if dic[c] % 2 == 1:
mid = c
seed.extend([c] * (dic[c] / 2))
self.permute(half, seed, 0)
for r in half:
res.append(''.join(r) + mid + ''.join(reversed(r)))
return res
def permute(self, res, num, index):
if index == len(num):
res.append(list(num))
return
appeared = set()
for i in range(index, len(num)):
if num[i] in appeared:
continue
appeared.add(num[i])
(num[i], num[index]) = (num[index], num[i])
self.permute(res, num, index + 1)
(num[i], num[index]) = (num[index], num[i]) |
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class Stack:
def __init__(self):
self.last = None
def push(self, item):
self.last = Node(item, self.last)
def pop(self):
item = self.last.item
self.last = self.last.next
return item
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
| class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class Stack:
def __init__(self):
self.last = None
def push(self, item):
self.last = node(item, self.last)
def pop(self):
item = self.last.item
self.last = self.last.next
return item
stack = stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5) |
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
# dfs solution to solve this problem
nums = [-float('inf')] + nums + [-float('inf')]
lo, hi = 0, len(nums)-1
while lo < hi:
mid = (lo+hi)//2
if nums[mid] > nums[mid-1] and nums[mid] > nums[mid+1]:
return mid-1
if nums[mid-1] > nums[mid]:
hi = mid
else:
lo = mid+1
return lo-1 | class Solution:
def find_peak_element(self, nums: List[int]) -> int:
nums = [-float('inf')] + nums + [-float('inf')]
(lo, hi) = (0, len(nums) - 1)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > nums[mid - 1] and nums[mid] > nums[mid + 1]:
return mid - 1
if nums[mid - 1] > nums[mid]:
hi = mid
else:
lo = mid + 1
return lo - 1 |
"""
Unit Tests for lfs library
"""
__author__ = 'Stephen Brown (Little Fish Solutions LTD)'
| """
Unit Tests for lfs library
"""
__author__ = 'Stephen Brown (Little Fish Solutions LTD)' |
# __init__.py
# Copyright 2011 Roger Marsh
# Licence: See LICENCE (BSD licence)
"""results berkelelydb interface.
"""
| """results berkelelydb interface.
""" |
a = 2 < 3
b = 2 + 4
c = (1 <= 2 ) and (1 <= 3)
x = 1 + 2 * 3
y = 1 * 2 + 3
x = 2+3 < 2+1 or 2 < 3 and not not True
y = not True and False | a = 2 < 3
b = 2 + 4
c = 1 <= 2 and 1 <= 3
x = 1 + 2 * 3
y = 1 * 2 + 3
x = 2 + 3 < 2 + 1 or (2 < 3 and (not not True))
y = not True and False |
class deque:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.item==[]
def addRear(self,item):
self.items.append(item)
def addFront(self,item):
self.items.insert(0,item)
def removeFront(self):
return self.pop()
def removeRear(self):
return self.pop(0)
def size(self):
return len(self.items)
d=deque()
d.addFront(10)
d.addRear(20)
print(d.size())
| class Deque:
def __init__(self):
self.items = []
def is_empty(self):
return self.item == []
def add_rear(self, item):
self.items.append(item)
def add_front(self, item):
self.items.insert(0, item)
def remove_front(self):
return self.pop()
def remove_rear(self):
return self.pop(0)
def size(self):
return len(self.items)
d = deque()
d.addFront(10)
d.addRear(20)
print(d.size()) |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
x=[]
for i in nums:
x.append(sum([1 for y in nums if y<i]))
return x
| class Solution:
def smaller_numbers_than_current(self, nums: List[int]) -> List[int]:
x = []
for i in nums:
x.append(sum([1 for y in nums if y < i]))
return x |
def score_submission(submission):
# first remove existing leaderboard entries
# read in scores dictionary, ex:
# scoring_program_output = {
# "RESULTS": [
# ("Score", 1),
# ],
# "ALTERNATE_RESULTS": [
# ("Score", 2),
# ("Misc", 10),
# ]
# }
pass
| def score_submission(submission):
pass |
'''
Write a function, gooseFilter / goose-filter / goose_filter / GooseFilter, that
takes an array of strings as an argument and returns a filtered array
containing the same elements but with the 'geese' removed.
The geese are any strings in the following array, which is pre-populated in
your solution:
geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]
For example, if this array were passed as an argument:
["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]
Your function would return the following array:
["Mallard", "Hook Bill", "Crested", "Blue Swedish"]
The elements in the returned array should be in the same order as in the
initial array passed to your function, albeit with the 'geese' removed. Note
that all of the strings will be in the same case as those provided, and some
elements may be repeated.
'''
geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]
def goose_filter(birds):
result = []
for bird in birds:
if not bird in geese:
result.append(bird)
return result
# Should return ["Mallard", "Hook Bill", "Crested", "Blue Swedish"]
print(goose_filter(["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]))
# Should return ["Mallard", "Barbary", "Hook Bill", "Blue Swedish", "Crested"]
print(goose_filter(["Mallard", "Barbary", "Hook Bill", "Blue Swedish", "Crested"]))
# Should return []
print(goose_filter(["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]))
| """
Write a function, gooseFilter / goose-filter / goose_filter / GooseFilter, that
takes an array of strings as an argument and returns a filtered array
containing the same elements but with the 'geese' removed.
The geese are any strings in the following array, which is pre-populated in
your solution:
geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]
For example, if this array were passed as an argument:
["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]
Your function would return the following array:
["Mallard", "Hook Bill", "Crested", "Blue Swedish"]
The elements in the returned array should be in the same order as in the
initial array passed to your function, albeit with the 'geese' removed. Note
that all of the strings will be in the same case as those provided, and some
elements may be repeated.
"""
geese = ['African', 'Roman Tufted', 'Toulouse', 'Pilgrim', 'Steinbacher']
def goose_filter(birds):
result = []
for bird in birds:
if not bird in geese:
result.append(bird)
return result
print(goose_filter(['Mallard', 'Hook Bill', 'African', 'Crested', 'Pilgrim', 'Toulouse', 'Blue Swedish']))
print(goose_filter(['Mallard', 'Barbary', 'Hook Bill', 'Blue Swedish', 'Crested']))
print(goose_filter(['African', 'Roman Tufted', 'Toulouse', 'Pilgrim', 'Steinbacher'])) |
# -*- coding: utf-8 -*-
"""Top-level package for deploy_ova."""
__author__ = """Michael Palmer"""
__email__ = 'palmertime@gmail.com'
__version__ = '0.1.0'
| """Top-level package for deploy_ova."""
__author__ = 'Michael Palmer'
__email__ = 'palmertime@gmail.com'
__version__ = '0.1.0' |
# Copyright 2018 Google LLC
#
# 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.
def genBox(image_width, image_height, size, step, zoom_step, skip=1):
# generates boxes that scan the image
# image_width, image_height: input image size
# size: smallest tile size (real tile size is size*zoom)
# step: smallest step (real step is step*zoom)
# zoom_step: reapeatedly applied zoom factor
# skip: return 1 out of skip results only
zoom = 1.0
cnt = 0
boxes = []
while zoom <= min(image_width, image_height):
s = size*zoom
x = 0.0
while x+s <= image_width:
y = 0.0
while y+s <= image_height:
if (cnt % skip) == 0:
yield [x, y, x+s, y+s]
cnt += 1
y += step*zoom
x += step*zoom
zoom *= zoom_step | def gen_box(image_width, image_height, size, step, zoom_step, skip=1):
zoom = 1.0
cnt = 0
boxes = []
while zoom <= min(image_width, image_height):
s = size * zoom
x = 0.0
while x + s <= image_width:
y = 0.0
while y + s <= image_height:
if cnt % skip == 0:
yield [x, y, x + s, y + s]
cnt += 1
y += step * zoom
x += step * zoom
zoom *= zoom_step |
# Variables can be used to hold information.
# Integer-type
initial_amount = 100
# Float-type
interest_rate = 5.0
# Integer-type
num_of_years = 7
# The type of "final_amount" must be deduced from the number-types in the expression.
# The type of "final_amount" will be the least precise type that's involved in the calculation.
# Thus, the type will be a float in this scenario.
# I.e: if you were to multiply two integers, the result would be an integer.
final_amount = initial_amount * (1+interest_rate/100)**num_of_years
print(f"After {num_of_years} years, {initial_amount} has grown to {final_amount:.2f}.") | initial_amount = 100
interest_rate = 5.0
num_of_years = 7
final_amount = initial_amount * (1 + interest_rate / 100) ** num_of_years
print(f'After {num_of_years} years, {initial_amount} has grown to {final_amount:.2f}.') |
#
# Author VinhLH <vinh.le@zalora.com>
# Copyright Mar 2016
#
# Configs
host = ''
port = 8888
workDir = '/Users/vinhlh/Works/test'
log = 'server.log' | host = ''
port = 8888
work_dir = '/Users/vinhlh/Works/test'
log = 'server.log' |
def register(mf):
mf.register_defaults({
"fuzzy": __file__,
"fuzzychild_nonunique": __file__
})
| def register(mf):
mf.register_defaults({'fuzzy': __file__, 'fuzzychild_nonunique': __file__}) |
"""Integration tests for the pyWriter project.
Test helper module.
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
def read_file(inputFile):
try:
with open(inputFile, 'r', encoding='utf-8') as f:
return f.read()
except:
# HTML files exported by a word processor may be ANSI encoded.
with open(inputFile, 'r') as f:
return f.read()
| """Integration tests for the pyWriter project.
Test helper module.
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
def read_file(inputFile):
try:
with open(inputFile, 'r', encoding='utf-8') as f:
return f.read()
except:
with open(inputFile, 'r') as f:
return f.read() |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-09-14 21:20:08
# Description:
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator % denominator == 0:
return str(numerator // denominator)
sign = '' if numerator * denominator >= 0 else '-'
numerator, denominator = abs(numerator), abs(denominator)
res = sign + str(numerator // denominator) + '.'
numerator %= denominator
i, part = 0, ''
m = {numerator: i}
while numerator % denominator:
numerator *= 10
i += 1
rem = numerator % denominator
part += str(numerator // denominator)
if rem in m:
part = part[:m[rem]] + '(' + part[m[rem]:] + ')'
return res + part
m[rem] = i
numerator = rem
return res + part
if __name__ == "__main__":
pass
| class Solution:
def fraction_to_decimal(self, numerator: int, denominator: int) -> str:
if numerator % denominator == 0:
return str(numerator // denominator)
sign = '' if numerator * denominator >= 0 else '-'
(numerator, denominator) = (abs(numerator), abs(denominator))
res = sign + str(numerator // denominator) + '.'
numerator %= denominator
(i, part) = (0, '')
m = {numerator: i}
while numerator % denominator:
numerator *= 10
i += 1
rem = numerator % denominator
part += str(numerator // denominator)
if rem in m:
part = part[:m[rem]] + '(' + part[m[rem]:] + ')'
return res + part
m[rem] = i
numerator = rem
return res + part
if __name__ == '__main__':
pass |
valor = int(input())
print('{}'.format(valor))
numero100 = valor//100
print('{} nota(s) de R$ 100,00'.format(numero100))
valor -= numero100*100 #valor - valor (menos ele mesmo)
numero50 = valor//50
print('{} nota(s) de R$ 50,00'.format(numero50))
valor -= numero50*50
numero20 = valor//20
print('{} nota(s) de R$ 20,00'.format(numero20))
valor -= numero20*20
numero10 = valor//10
print('{} nota(s) de R$ 10,00'.format(numero10))
valor -= numero10*10
numero5 = valor//5
print('{} nota(s) de R$ 5,00'.format(numero5))
valor -= numero5*5
numero2 = valor//2
print('{} nota(s) de R$ 2,00'.format(numero2))
valor -= numero2*2
numero1 = valor//1
print('{} nota(s) de R$ 1,00'.format(numero1))
| valor = int(input())
print('{}'.format(valor))
numero100 = valor // 100
print('{} nota(s) de R$ 100,00'.format(numero100))
valor -= numero100 * 100
numero50 = valor // 50
print('{} nota(s) de R$ 50,00'.format(numero50))
valor -= numero50 * 50
numero20 = valor // 20
print('{} nota(s) de R$ 20,00'.format(numero20))
valor -= numero20 * 20
numero10 = valor // 10
print('{} nota(s) de R$ 10,00'.format(numero10))
valor -= numero10 * 10
numero5 = valor // 5
print('{} nota(s) de R$ 5,00'.format(numero5))
valor -= numero5 * 5
numero2 = valor // 2
print('{} nota(s) de R$ 2,00'.format(numero2))
valor -= numero2 * 2
numero1 = valor // 1
print('{} nota(s) de R$ 1,00'.format(numero1)) |
def func_read_in_pattern_file(pattern_file_path):
pattern_dict = {}
with open(pattern_file_path, 'r') as file:
for line in file:
line_lst = line.strip().split(",")
pattern_dict[line_lst[0]] = [line_lst[1], line_lst[2], line_lst[3], line_lst[4]]
return pattern_dict | def func_read_in_pattern_file(pattern_file_path):
pattern_dict = {}
with open(pattern_file_path, 'r') as file:
for line in file:
line_lst = line.strip().split(',')
pattern_dict[line_lst[0]] = [line_lst[1], line_lst[2], line_lst[3], line_lst[4]]
return pattern_dict |
# Copyright (c) 2015 Google Inc. 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': 'test_default',
'type': 'executable',
'sources': ['hello.cc'],
},
{
'target_name': 'test_set_reserved_size',
'type': 'executable',
'sources': ['hello.cc'],
'msvs_settings': {
'VCLinkerTool': {
'StackReserveSize': 2097152, # 2MB
}
},
},
{
'target_name': 'test_set_commit_size',
'type': 'executable',
'sources': ['hello.cc'],
'msvs_settings': {
'VCLinkerTool': {
'StackCommitSize': 8192, # 8KB
}
},
},
{
'target_name': 'test_set_both',
'type': 'executable',
'sources': ['hello.cc'],
'msvs_settings': {
'VCLinkerTool': {
'StackReserveSize': 2097152, # 2MB
'StackCommitSize': 8192, # 8KB
}
},
},
]
}
| {'targets': [{'target_name': 'test_default', 'type': 'executable', 'sources': ['hello.cc']}, {'target_name': 'test_set_reserved_size', 'type': 'executable', 'sources': ['hello.cc'], 'msvs_settings': {'VCLinkerTool': {'StackReserveSize': 2097152}}}, {'target_name': 'test_set_commit_size', 'type': 'executable', 'sources': ['hello.cc'], 'msvs_settings': {'VCLinkerTool': {'StackCommitSize': 8192}}}, {'target_name': 'test_set_both', 'type': 'executable', 'sources': ['hello.cc'], 'msvs_settings': {'VCLinkerTool': {'StackReserveSize': 2097152, 'StackCommitSize': 8192}}}]} |
test_input_1 = """\
8 8
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBBBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
"""
test_input_2 = """\
10 13
BBBBBBBBWBWBW
BBBBBBBBBWBWB
BBBBBBBBWBWBW
BBBBBBBBBWBWB
BBBBBBBBWBWBW
BBBBBBBBBWBWB
BBBBBBBBWBWBW
BBBBBBBBBWBWB
WWWWWWWWWWBWB
WWWWWWWWWWBWB
"""
test_input_3 = """\
8 8
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
"""
test_input_4 = """\
9 23
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBW
"""
# ERROR CASE
test_input_7 = """\
11 12
BWWBWWBWWBWW
BWWBWBBWWBWW
WBWWBWBBWWBW
BWWBWBBWWBWW
WBWWBWBBWWBW
BWWBWBBWWBWW
WBWWBWBBWWBW
BWWBWBWWWBWW
WBWWBWBBWWBW
BWWBWBBWWBWW
WBWWBWBBWWBW
"""
START_WITH_B = "BWBWBWBW"
START_WITH_W = "WBWBWBWB"
def get_count_diff_two_length8_string(str1, str2):
count = 0
for i in range(0,8):
if str1[i] != str2[i]:
count += 1
return count
M, N = input().split()
M, N = map(int, (M, N))
input_array = []
for i in range(0, M):
input_array.append(input())
number_of_possible_case = (M-7) * (N-7)
MAX = 100000000000
min_upperleft_black_counter = MAX
min_upperleft_white_counter = MAX
flag = True
for i in range(0, M-7):
test_board = input_array[i:i+8]
for j in range(0, N-7):
upperleft_black_counter = 0
upperleft_white_counter = 0
for row in range(0, 8):
if flag == True:
upperleft_black_counter += get_count_diff_two_length8_string(START_WITH_B, test_board[row][j:j+8])
upperleft_white_counter += get_count_diff_two_length8_string(START_WITH_W, test_board[row][j:j+8])
else:
upperleft_white_counter += get_count_diff_two_length8_string(START_WITH_B, test_board[row][j:j+8])
upperleft_black_counter += get_count_diff_two_length8_string(START_WITH_W, test_board[row][j:j+8])
flag = not(flag)
if min_upperleft_black_counter > upperleft_black_counter:
min_upperleft_black_counter = upperleft_black_counter
if min_upperleft_white_counter > upperleft_white_counter:
min_upperleft_white_counter = upperleft_white_counter
if min_upperleft_black_counter > min_upperleft_white_counter:
print(min_upperleft_white_counter)
else:
print(min_upperleft_black_counter) | test_input_1 = '8 8\nWBWBWBWB\nBWBWBWBW\nWBWBWBWB\nBWBBBWBW\nWBWBWBWB\nBWBWBWBW\nWBWBWBWB\nBWBWBWBW\n'
test_input_2 = '10 13\nBBBBBBBBWBWBW\nBBBBBBBBBWBWB\nBBBBBBBBWBWBW\nBBBBBBBBBWBWB\nBBBBBBBBWBWBW\nBBBBBBBBBWBWB\nBBBBBBBBWBWBW\nBBBBBBBBBWBWB\nWWWWWWWWWWBWB\nWWWWWWWWWWBWB\n'
test_input_3 = '8 8\nBWBWBWBW\nWBWBWBWB\nBWBWBWBW\nWBWBWBWB\nBWBWBWBW\nWBWBWBWB\nBWBWBWBW\nWBWBWBWB\n'
test_input_4 = '9 23\nBBBBBBBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBBBBBBW\n'
test_input_7 = '11 12\nBWWBWWBWWBWW\nBWWBWBBWWBWW\nWBWWBWBBWWBW\nBWWBWBBWWBWW\nWBWWBWBBWWBW\nBWWBWBBWWBWW\nWBWWBWBBWWBW\nBWWBWBWWWBWW\nWBWWBWBBWWBW\nBWWBWBBWWBWW\nWBWWBWBBWWBW\n'
start_with_b = 'BWBWBWBW'
start_with_w = 'WBWBWBWB'
def get_count_diff_two_length8_string(str1, str2):
count = 0
for i in range(0, 8):
if str1[i] != str2[i]:
count += 1
return count
(m, n) = input().split()
(m, n) = map(int, (M, N))
input_array = []
for i in range(0, M):
input_array.append(input())
number_of_possible_case = (M - 7) * (N - 7)
max = 100000000000
min_upperleft_black_counter = MAX
min_upperleft_white_counter = MAX
flag = True
for i in range(0, M - 7):
test_board = input_array[i:i + 8]
for j in range(0, N - 7):
upperleft_black_counter = 0
upperleft_white_counter = 0
for row in range(0, 8):
if flag == True:
upperleft_black_counter += get_count_diff_two_length8_string(START_WITH_B, test_board[row][j:j + 8])
upperleft_white_counter += get_count_diff_two_length8_string(START_WITH_W, test_board[row][j:j + 8])
else:
upperleft_white_counter += get_count_diff_two_length8_string(START_WITH_B, test_board[row][j:j + 8])
upperleft_black_counter += get_count_diff_two_length8_string(START_WITH_W, test_board[row][j:j + 8])
flag = not flag
if min_upperleft_black_counter > upperleft_black_counter:
min_upperleft_black_counter = upperleft_black_counter
if min_upperleft_white_counter > upperleft_white_counter:
min_upperleft_white_counter = upperleft_white_counter
if min_upperleft_black_counter > min_upperleft_white_counter:
print(min_upperleft_white_counter)
else:
print(min_upperleft_black_counter) |
# Write a small program to ask for a name and an age.
# When both values have been entered, check if the person
# is the right age to go on an 18-30 holiday (they must be
# over 18 and under 31).
# If they are, welcome them to the holiday, otherwise print
# a (polite) message refusing them entry.
name = input("Please enter your name: ")
age = int(input("How old are you, {0}? ".format(name)))
# if 18 <= age < 31:
if age >=18 and age <31:
print("Welcome to club 18-30 holidays, {0}".format(name))
else:
print("I'm sorry, our holidays are only for seriously cool people") | name = input('Please enter your name: ')
age = int(input('How old are you, {0}? '.format(name)))
if age >= 18 and age < 31:
print('Welcome to club 18-30 holidays, {0}'.format(name))
else:
print("I'm sorry, our holidays are only for seriously cool people") |
class Phone:
def __init__(self, str):
str = ''.join([x for x in str if x in '0123456789'])
if len(str) == 10:
self.number = str
elif len(str) == 11 and str[0] == '1':
self.number = str[1:]
else:
raise ValueError('bad format')
self.area_code = self.number[:3]
if self.area_code[:1] in '01':
raise ValueError('bad area code')
self.exchange_code = self.number[3:6]
if self.exchange_code[:1] in '01':
raise ValueError('bad exchange code')
def pretty(self):
return '({}) {}-{}'.format(self.area_code,
self.exchange_code,
self.number[-4:])
| class Phone:
def __init__(self, str):
str = ''.join([x for x in str if x in '0123456789'])
if len(str) == 10:
self.number = str
elif len(str) == 11 and str[0] == '1':
self.number = str[1:]
else:
raise value_error('bad format')
self.area_code = self.number[:3]
if self.area_code[:1] in '01':
raise value_error('bad area code')
self.exchange_code = self.number[3:6]
if self.exchange_code[:1] in '01':
raise value_error('bad exchange code')
def pretty(self):
return '({}) {}-{}'.format(self.area_code, self.exchange_code, self.number[-4:]) |
ABI_ENDPOINT = "https://api.etherscan.io/api?module=contract&action=getabi&address="
POLYGON_ABI_ENDPOINT = (
"https://api.polygonscan.com/api?module=contract&action=getabi&address="
)
ENDPOINT = ""
POLYGON_ENDPOINT = ""
ATTRIBUTES_FOLDER = "raw_attributes"
IMPLEMENTATION_SLOT = (
"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
)
IPFS_GATEWAY = ""
| abi_endpoint = 'https://api.etherscan.io/api?module=contract&action=getabi&address='
polygon_abi_endpoint = 'https://api.polygonscan.com/api?module=contract&action=getabi&address='
endpoint = ''
polygon_endpoint = ''
attributes_folder = 'raw_attributes'
implementation_slot = '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc'
ipfs_gateway = '' |
studentdata = {}
alldata = []
studentdata['Name'] = str(input("Type the Student's name: "))
studentdata['AVGRADE'] = float(input("Type the Average Grade of the Student: "))
if studentdata['AVGRADE'] < 5:
studentdata['Situation'] = ("Reproved")
elif studentdata['AVGRADE'] > 5 and studentdata['AVGRADE'] < 7:
studentdata['Situation'] = ("Recuperation")
else:
studentdata['Situation'] = ("Aproved")
alldata.append(studentdata.copy())
for x in alldata:
for k,v in x.items():
print(f"The {k} is equal to: {v}")
| studentdata = {}
alldata = []
studentdata['Name'] = str(input("Type the Student's name: "))
studentdata['AVGRADE'] = float(input('Type the Average Grade of the Student: '))
if studentdata['AVGRADE'] < 5:
studentdata['Situation'] = 'Reproved'
elif studentdata['AVGRADE'] > 5 and studentdata['AVGRADE'] < 7:
studentdata['Situation'] = 'Recuperation'
else:
studentdata['Situation'] = 'Aproved'
alldata.append(studentdata.copy())
for x in alldata:
for (k, v) in x.items():
print(f'The {k} is equal to: {v}') |
# -*- coding: utf-8 -*-
f = open(filename)
char = f.read(1)
while char:
process(char)
char = f.read(1)
f.close()
| f = open(filename)
char = f.read(1)
while char:
process(char)
char = f.read(1)
f.close() |
b = str(input()).split()
d = int(b[0])
c= int(b[1])
e = '.|.'
for i in range(1,d,2):
print((e*i).center(c,'-'))
print(('WELCOME').center(c,'-'))
for i in range(d-2,-1,-2):
print((e * i).center(c, '-'))
| b = str(input()).split()
d = int(b[0])
c = int(b[1])
e = '.|.'
for i in range(1, d, 2):
print((e * i).center(c, '-'))
print('WELCOME'.center(c, '-'))
for i in range(d - 2, -1, -2):
print((e * i).center(c, '-')) |
LANGUAGE_CODE = 'ru-RU'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
| language_code = 'ru-RU'
time_zone = 'UTC'
use_i18_n = True
use_l10_n = True
use_tz = True |
fila1="abcdefghi"
fila2="jklmnopqr"
fila3="stuvwxyz"
n=int(input())
for i in range(0,n):
flag=True
palabras=input()
palabras=palabras.strip().split()
if (len(palabras[0])==len(palabras[1])):
if (palabras[0]==palabras[1]):
print("1")
pass
else:
for j in range(0,len(palabras[0])):
if palabras[0][j] in fila1:
temp=fila1.find(palabras[0][j])
if temp==0:
if palabras[1][j]==fila1[temp] or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1]:
pass
else:
flag=False
break
elif temp==8:
if palabras[1][j]==fila1[temp] or palabras[1][j]==fila1[temp-1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp-1]:
pass
else:
flag=False
break
else:
if palabras[1][j]==fila1[temp] or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1] or palabras[1][j]==fila1[temp-1] or palabras[1][j]==fila2[temp-1]:
pass
else:
flag=False
break
elif palabras[0][j] in fila2:
temp=fila2.find(palabras[0][j])
if temp==0:
if palabras[1][j]==fila2[temp] or palabras[1][j]==fila1[temp] or palabras[1][j]==fila3[temp] or palabras[1][j]==fila2[temp+1]or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila3[temp+1]:
pass
else:
flag=False
break
elif temp==8:
if palabras[1][j]==fila2[temp] or palabras[1][j]==fila1[temp] or palabras[1][j]==fila2[temp-1]or palabras[1][j]==fila1[temp-1] or palabras[1][j]==fila3[temp-1]:
pass
else:
flag=False
break
elif temp==7:
if palabras[1][j]==fila2[temp] or palabras[1][j]==fila1[temp] or palabras[1][j]==fila3[temp] or palabras[1][j]==fila2[temp+1]or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila3[temp-1]or palabras[1][j]==fila2[temp-1]or palabras[1][j]==fila1[temp-1]:
pass
else:
flag=False
break
else:
if palabras[1][j]==fila2[temp] or palabras[1][j]==fila1[temp] or palabras[1][j]==fila3[temp] or palabras[1][j]==fila2[temp+1]or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila3[temp+1] or palabras[1][j]==fila3[temp-1]or palabras[1][j]==fila2[temp-1]or palabras[1][j]==fila1[temp-1]:
pass
else:
flag=False
break
elif palabras[0][j] in fila3:
temp=fila3.find(palabras[0][j])
if temp==0:
if palabras[1][j]==fila3[temp] or palabras[1][j]==fila3[temp+1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1]:
pass
else:
flag=False
break
if temp==7:
if palabras[1][j]==fila3[temp] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1] or palabras[1][j]==fila3[temp-1] or palabras[1][j]==fila2[temp-1]:
pass
else:
flag=False
break
else:
if palabras[1][j]==fila3[temp] or palabras[1][j]==fila3[temp+1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1] or palabras[1][j]==fila3[temp-1] or palabras[1][j]==fila2[temp-1]:
pass
else:
flag=False
break
if flag:
print("2")
pass
else:
print("3")
pass
else:
print("3")
pass | fila1 = 'abcdefghi'
fila2 = 'jklmnopqr'
fila3 = 'stuvwxyz'
n = int(input())
for i in range(0, n):
flag = True
palabras = input()
palabras = palabras.strip().split()
if len(palabras[0]) == len(palabras[1]):
if palabras[0] == palabras[1]:
print('1')
pass
else:
for j in range(0, len(palabras[0])):
if palabras[0][j] in fila1:
temp = fila1.find(palabras[0][j])
if temp == 0:
if palabras[1][j] == fila1[temp] or palabras[1][j] == fila1[temp + 1] or palabras[1][j] == fila2[temp] or (palabras[1][j] == fila2[temp + 1]):
pass
else:
flag = False
break
elif temp == 8:
if palabras[1][j] == fila1[temp] or palabras[1][j] == fila1[temp - 1] or palabras[1][j] == fila2[temp] or (palabras[1][j] == fila2[temp - 1]):
pass
else:
flag = False
break
elif palabras[1][j] == fila1[temp] or palabras[1][j] == fila1[temp + 1] or palabras[1][j] == fila2[temp] or (palabras[1][j] == fila2[temp + 1]) or (palabras[1][j] == fila1[temp - 1]) or (palabras[1][j] == fila2[temp - 1]):
pass
else:
flag = False
break
elif palabras[0][j] in fila2:
temp = fila2.find(palabras[0][j])
if temp == 0:
if palabras[1][j] == fila2[temp] or palabras[1][j] == fila1[temp] or palabras[1][j] == fila3[temp] or (palabras[1][j] == fila2[temp + 1]) or (palabras[1][j] == fila1[temp + 1]) or (palabras[1][j] == fila3[temp + 1]):
pass
else:
flag = False
break
elif temp == 8:
if palabras[1][j] == fila2[temp] or palabras[1][j] == fila1[temp] or palabras[1][j] == fila2[temp - 1] or (palabras[1][j] == fila1[temp - 1]) or (palabras[1][j] == fila3[temp - 1]):
pass
else:
flag = False
break
elif temp == 7:
if palabras[1][j] == fila2[temp] or palabras[1][j] == fila1[temp] or palabras[1][j] == fila3[temp] or (palabras[1][j] == fila2[temp + 1]) or (palabras[1][j] == fila1[temp + 1]) or (palabras[1][j] == fila3[temp - 1]) or (palabras[1][j] == fila2[temp - 1]) or (palabras[1][j] == fila1[temp - 1]):
pass
else:
flag = False
break
elif palabras[1][j] == fila2[temp] or palabras[1][j] == fila1[temp] or palabras[1][j] == fila3[temp] or (palabras[1][j] == fila2[temp + 1]) or (palabras[1][j] == fila1[temp + 1]) or (palabras[1][j] == fila3[temp + 1]) or (palabras[1][j] == fila3[temp - 1]) or (palabras[1][j] == fila2[temp - 1]) or (palabras[1][j] == fila1[temp - 1]):
pass
else:
flag = False
break
elif palabras[0][j] in fila3:
temp = fila3.find(palabras[0][j])
if temp == 0:
if palabras[1][j] == fila3[temp] or palabras[1][j] == fila3[temp + 1] or palabras[1][j] == fila2[temp] or (palabras[1][j] == fila2[temp + 1]):
pass
else:
flag = False
break
if temp == 7:
if palabras[1][j] == fila3[temp] or palabras[1][j] == fila2[temp] or palabras[1][j] == fila2[temp + 1] or (palabras[1][j] == fila3[temp - 1]) or (palabras[1][j] == fila2[temp - 1]):
pass
else:
flag = False
break
elif palabras[1][j] == fila3[temp] or palabras[1][j] == fila3[temp + 1] or palabras[1][j] == fila2[temp] or (palabras[1][j] == fila2[temp + 1]) or (palabras[1][j] == fila3[temp - 1]) or (palabras[1][j] == fila2[temp - 1]):
pass
else:
flag = False
break
if flag:
print('2')
pass
else:
print('3')
pass
else:
print('3')
pass |
# Which of the following expressions return the infinity values?
# Suppose, the variables inf and nan have been defined.
nan = float("nan")
inf = float("inf")
print(0.0 / inf) # nan
print(inf / 2 - inf) # inf
print(100 * inf + nan) # inf
print(inf - 10 ** 300) # nan
print(-inf * inf) # inf
# print(inf % 0.0) | nan = float('nan')
inf = float('inf')
print(0.0 / inf)
print(inf / 2 - inf)
print(100 * inf + nan)
print(inf - 10 ** 300)
print(-inf * inf) |
lines = open('input.txt', 'r').readlines()
# create graph
node_hash_list = dict()
node_hash_list["start"] = set()
for line in lines:
p1, p2 = line.strip().split("-")
if p2 not in node_hash_list:
node_hash_list[p2] = set()
if p1 not in node_hash_list:
node_hash_list[p1] = set()
if not p1 == "end" and not p2 == "start":
node_hash_list[p1].add(p2)
if not p2 == "end" and not p1 == "start":
node_hash_list[p2].add(p1)
# traverse graph PART ONE
possible_paths = list()
path1 = ["start"]
possible_paths.append(path1)
flag_paths_updated = True
while flag_paths_updated:
flag_paths_updated = False
for path in possible_paths.copy():
if path[-1] == "end":
continue # ignore
# try to find next move
for nextStep in node_hash_list[path[-1]]:
copyPath = [p for p in path]
if nextStep not in path or nextStep.isupper():
# append path
copyPath.append(nextStep)
flag_paths_updated = True
possible_paths.append(copyPath)
possible_paths.remove(path)
print("Part 1: ", len(possible_paths))
# PART TWO
def small_cave_one_more_visit_allowed(path, nextStep):
if nextStep == "end":
return True
small_caves = set()
for name in path:
if name.isupper():
continue
if name in small_caves:
return nextStep not in path
small_caves.add(name)
return True
# traverse graph PART Two
possible_paths = list()
possible_paths.append(["start"])
possible_path_counter = 0
flag_paths_updated = True
while flag_paths_updated:
flag_paths_updated = False
for path in possible_paths.copy():
if path[-1] == "end":
possible_path_counter += 1
possible_paths.remove(path)
continue # ignore
# try to find next move
for nextStep in node_hash_list[path[-1]]:
copyPath = [p for p in path]
if nextStep.isupper() or small_cave_one_more_visit_allowed(copyPath, nextStep):
# append path
copyPath.append(nextStep)
flag_paths_updated = True
possible_paths.append(copyPath)
possible_paths.remove(path)
print("Paths: ", possible_path_counter)
| lines = open('input.txt', 'r').readlines()
node_hash_list = dict()
node_hash_list['start'] = set()
for line in lines:
(p1, p2) = line.strip().split('-')
if p2 not in node_hash_list:
node_hash_list[p2] = set()
if p1 not in node_hash_list:
node_hash_list[p1] = set()
if not p1 == 'end' and (not p2 == 'start'):
node_hash_list[p1].add(p2)
if not p2 == 'end' and (not p1 == 'start'):
node_hash_list[p2].add(p1)
possible_paths = list()
path1 = ['start']
possible_paths.append(path1)
flag_paths_updated = True
while flag_paths_updated:
flag_paths_updated = False
for path in possible_paths.copy():
if path[-1] == 'end':
continue
for next_step in node_hash_list[path[-1]]:
copy_path = [p for p in path]
if nextStep not in path or nextStep.isupper():
copyPath.append(nextStep)
flag_paths_updated = True
possible_paths.append(copyPath)
possible_paths.remove(path)
print('Part 1: ', len(possible_paths))
def small_cave_one_more_visit_allowed(path, nextStep):
if nextStep == 'end':
return True
small_caves = set()
for name in path:
if name.isupper():
continue
if name in small_caves:
return nextStep not in path
small_caves.add(name)
return True
possible_paths = list()
possible_paths.append(['start'])
possible_path_counter = 0
flag_paths_updated = True
while flag_paths_updated:
flag_paths_updated = False
for path in possible_paths.copy():
if path[-1] == 'end':
possible_path_counter += 1
possible_paths.remove(path)
continue
for next_step in node_hash_list[path[-1]]:
copy_path = [p for p in path]
if nextStep.isupper() or small_cave_one_more_visit_allowed(copyPath, nextStep):
copyPath.append(nextStep)
flag_paths_updated = True
possible_paths.append(copyPath)
possible_paths.remove(path)
print('Paths: ', possible_path_counter) |
KEY_TO_SYM = {
"ArrowLeft": "Left",
"ArrowRight": "Right",
"ArrowUp": "Up",
"ArrowDown": "Down",
"BackSpace": "BackSpace",
"Tab": "Tab",
"Enter": "Return",
# 'Shift': 'Shift_L',
# 'Control': 'Control_L',
# 'Alt': 'Alt_L',
"CapsLock": "Caps_Lock",
"Escape": "Escape",
" ": "space",
"PageUp": "Prior",
"PageDown": "Next",
"Home": "Home",
"End": "End",
"Delete": "Delete",
"Insert": "Insert",
"*": "asterisk",
"+": "plus",
"|": "bar",
"-": "minus",
".": "period",
"/": "slash",
"F1": "F1",
"F2": "F2",
"F3": "F3",
"F4": "F4",
"F5": "F5",
"F6": "F6",
"F7": "F7",
"F8": "F8",
"F9": "F9",
"F10": "F10",
"F11": "F11",
"F12": "F12",
}
INTERACTION_THROTTLE = 100
| key_to_sym = {'ArrowLeft': 'Left', 'ArrowRight': 'Right', 'ArrowUp': 'Up', 'ArrowDown': 'Down', 'BackSpace': 'BackSpace', 'Tab': 'Tab', 'Enter': 'Return', 'CapsLock': 'Caps_Lock', 'Escape': 'Escape', ' ': 'space', 'PageUp': 'Prior', 'PageDown': 'Next', 'Home': 'Home', 'End': 'End', 'Delete': 'Delete', 'Insert': 'Insert', '*': 'asterisk', '+': 'plus', '|': 'bar', '-': 'minus', '.': 'period', '/': 'slash', 'F1': 'F1', 'F2': 'F2', 'F3': 'F3', 'F4': 'F4', 'F5': 'F5', 'F6': 'F6', 'F7': 'F7', 'F8': 'F8', 'F9': 'F9', 'F10': 'F10', 'F11': 'F11', 'F12': 'F12'}
interaction_throttle = 100 |
#!/usr/bin/env python
#coding: utf-8
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def postorderTraversal(self, root):
if not root: return []
leftL = self.postorderTraversal(root.left)
rightL = self.postorderTraversal(root.right)
return leftL + rightL + [root.val]
| class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def postorder_traversal(self, root):
if not root:
return []
left_l = self.postorderTraversal(root.left)
right_l = self.postorderTraversal(root.right)
return leftL + rightL + [root.val] |
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"append: 0.09872150200000007\n",
"concat: 0.10876064500000027\n",
"unpack: 0.14667600099999945\n"
]
}
],
"source": [
"from timeit import timeit\n",
"\n",
"append = \"\"\"\n",
"array1 = [0, 1, 2]\n",
"array1.append(3)\n",
"\"\"\"\n",
"concat = \"\"\"\n",
"array2 = [0, 1, 2]\n",
"array2 += [3]\n",
"\"\"\"\n",
"unpack = \"\"\"\n",
"array3 = [0, 1, 2]\n",
"array3 = [*array3, 3]\n",
"\"\"\"\n",
"\n",
"print(f\"append: {timeit(append)}\")\n",
"print(f\"concat: {timeit(concat)}\")\n",
"print(f\"unpack: {timeit(unpack)}\")"
]
}
],
"metadata": {
"interpreter": {
"hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
},
"kernelspec": {
"display_name": "Python 3.8.2 64-bit",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.12"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| {'cells': [{'cell_type': 'code', 'execution_count': 2, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['append: 0.09872150200000007\n', 'concat: 0.10876064500000027\n', 'unpack: 0.14667600099999945\n']}], 'source': ['from timeit import timeit\n', '\n', 'append = """\n', 'array1 = [0, 1, 2]\n', 'array1.append(3)\n', '"""\n', 'concat = """\n', 'array2 = [0, 1, 2]\n', 'array2 += [3]\n', '"""\n', 'unpack = """\n', 'array3 = [0, 1, 2]\n', 'array3 = [*array3, 3]\n', '"""\n', '\n', 'print(f"append: {timeit(append)}")\n', 'print(f"concat: {timeit(concat)}")\n', 'print(f"unpack: {timeit(unpack)}")']}], 'metadata': {'interpreter': {'hash': '31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6'}, 'kernelspec': {'display_name': 'Python 3.8.2 64-bit', 'language': 'python', 'name': 'python3'}, 'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3}, 'file_extension': '.py', 'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python', 'pygments_lexer': 'ipython3', 'version': '3.8.12'}, 'orig_nbformat': 4}, 'nbformat': 4, 'nbformat_minor': 2} |
"""
CM, your case/content management system for the internet.
Copyright Alex Li 2003.
Package structure:
cm/
html/ (UI subpackages...)
htmllib/ (HTML frontend shared library)
model/ (Business Domain subpackages)
... (framework modules...such as database access,
security/permission checking, session management)
config.py (the configuration file of this web application...
Currently it is application-specific AND
client-specific)
"""
__copyright__=""
__version__="0.8.4"
__date__="2003-08-27"
| """
CM, your case/content management system for the internet.
Copyright Alex Li 2003.
Package structure:
cm/
html/ (UI subpackages...)
htmllib/ (HTML frontend shared library)
model/ (Business Domain subpackages)
... (framework modules...such as database access,
security/permission checking, session management)
config.py (the configuration file of this web application...
Currently it is application-specific AND
client-specific)
"""
__copyright__ = ''
__version__ = '0.8.4'
__date__ = '2003-08-27' |
def method1():
a = [1, 2, 3, 4, 5]
for _ in range(1):
f = a[0]
for j in range(0, len(a) - 1):
a[j] = a[j + 1]
a[len(a) - 1] = f
return a
if __name__ == "__main__":
"""
from timeit import timeit
print(timeit(lambda: method1(), number=10000)) 0.008410404003370786
"""
| def method1():
a = [1, 2, 3, 4, 5]
for _ in range(1):
f = a[0]
for j in range(0, len(a) - 1):
a[j] = a[j + 1]
a[len(a) - 1] = f
return a
if __name__ == '__main__':
'\n from timeit import timeit\n print(timeit(lambda: method1(), number=10000)) 0.008410404003370786\n ' |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:
# init
if head:
p1 = head
p2 = p1.next
else: return [-1, -1]
if p2: p3 = p2.next
else: return [-1, -1]
if not p3: return [-1, -1]
ind = 1
criticalPoints = []
# loop all nodes
while p3:
if p1.val > p2.val and p3.val > p2.val:
criticalPoints.append(ind)
if p1.val < p2.val and p3.val < p2.val:
criticalPoints.append(ind)
# update nodes
tmp3 = p3
tmp2 = p2
p3 = tmp3.next
p2 = tmp3
p1 = tmp2
ind += 1
# check criticalPoints to return
if len(criticalPoints) < 2: return [-1, -1]
else:
maxD = criticalPoints[-1] - criticalPoints[0]
minD = maxD
for i in range(1, len(criticalPoints)):
if criticalPoints[i] - criticalPoints[i-1] < minD:
minD = criticalPoints[i] - criticalPoints[i-1]
return [minD, maxD]
| class Solution:
def nodes_between_critical_points(self, head: Optional[ListNode]) -> List[int]:
if head:
p1 = head
p2 = p1.next
else:
return [-1, -1]
if p2:
p3 = p2.next
else:
return [-1, -1]
if not p3:
return [-1, -1]
ind = 1
critical_points = []
while p3:
if p1.val > p2.val and p3.val > p2.val:
criticalPoints.append(ind)
if p1.val < p2.val and p3.val < p2.val:
criticalPoints.append(ind)
tmp3 = p3
tmp2 = p2
p3 = tmp3.next
p2 = tmp3
p1 = tmp2
ind += 1
if len(criticalPoints) < 2:
return [-1, -1]
else:
max_d = criticalPoints[-1] - criticalPoints[0]
min_d = maxD
for i in range(1, len(criticalPoints)):
if criticalPoints[i] - criticalPoints[i - 1] < minD:
min_d = criticalPoints[i] - criticalPoints[i - 1]
return [minD, maxD] |
def maak_fizzbuzz(n):
"""Zie ook: https://en.wikipedia.org/wiki/Fizz_buzz"""
for getal in range(1, n+1):
if getal % 3 == 0 and getal % 5 == 0:
print("FizzBuzz")
elif getal % 3 == 0:
print("Fizz")
elif getal % 5 == 0:
print("Buzz")
else:
print(getal)
maak_fizzbuzz(20)
| def maak_fizzbuzz(n):
"""Zie ook: https://en.wikipedia.org/wiki/Fizz_buzz"""
for getal in range(1, n + 1):
if getal % 3 == 0 and getal % 5 == 0:
print('FizzBuzz')
elif getal % 3 == 0:
print('Fizz')
elif getal % 5 == 0:
print('Buzz')
else:
print(getal)
maak_fizzbuzz(20) |
# posts model
# create an empty list
posts=[]
def posts_db():
return posts | posts = []
def posts_db():
return posts |
while True:
try:
n, inSeq = int(input()), input().split()
inSeq = ''.join(inSeq)
stack = ''
def outSeq(inSeq, stack):
if len(inSeq) == 0:
return [''.join(reversed(stack))]
if len(stack) == 0:
outLater = outSeq(inSeq[1: ], stack + inSeq[0])
return outLater
else:
head = stack[-1]
outNow = [head+x for x in outSeq(inSeq, stack[ :-1]) if len(x)!=0]
outLater = outSeq(inSeq[1: ], stack + inSeq[0])
return outNow + outLater
r = outSeq(inSeq, stack)
# print(len(r))
r = [' '.join(list(x)) for x in r]
print('\n'.join(r))
except:
break | while True:
try:
(n, in_seq) = (int(input()), input().split())
in_seq = ''.join(inSeq)
stack = ''
def out_seq(inSeq, stack):
if len(inSeq) == 0:
return [''.join(reversed(stack))]
if len(stack) == 0:
out_later = out_seq(inSeq[1:], stack + inSeq[0])
return outLater
else:
head = stack[-1]
out_now = [head + x for x in out_seq(inSeq, stack[:-1]) if len(x) != 0]
out_later = out_seq(inSeq[1:], stack + inSeq[0])
return outNow + outLater
r = out_seq(inSeq, stack)
r = [' '.join(list(x)) for x in r]
print('\n'.join(r))
except:
break |
GET_USERS = "SELECT users FROM all_users WHERE user_id = '{}'"
CREATE_MAIN_TABLE = "CREATE TABLE all_users(user_id text NOT NULL, users text NOT NULL);"
ADD_USER = "UPDATE all_users SET users = '{}' WHERE user_id = '{}'"
CREATE_USER = "INSERT INTO all_users (user_id, users) VALUES ('{}', ' ')"
GET_ALL_IDS = "SELECT user_id from all_users" | get_users = "SELECT users FROM all_users WHERE user_id = '{}'"
create_main_table = 'CREATE TABLE all_users(user_id text NOT NULL, users text NOT NULL);'
add_user = "UPDATE all_users SET users = '{}' WHERE user_id = '{}'"
create_user = "INSERT INTO all_users (user_id, users) VALUES ('{}', ' ')"
get_all_ids = 'SELECT user_id from all_users' |
class Extractor:
def __str__(self):
return self.__class__.__name__
class ExtractByCommand(Extractor):
def feed(self, command):
if not hasattr(self, command['type']):
return
getattr(self, command['type'])(command)
| class Extractor:
def __str__(self):
return self.__class__.__name__
class Extractbycommand(Extractor):
def feed(self, command):
if not hasattr(self, command['type']):
return
getattr(self, command['type'])(command) |
REGISTERED_METHODS = [
"ACL",
"BASELINE-CONTROL",
"BIND",
"CHECKIN",
"CHECKOUT",
"CONNECT",
"COPY",
"DELETE",
"GET",
"HEAD",
"LABEL",
"LINK",
"LOCK",
"MERGE",
"MKACTIVITY",
"MKCALENDAR",
"MKREDIRECTREF",
"MKWORKSPACE",
"MOVE",
"OPTIONS",
"ORDERPATCH",
"PATCH",
"POST",
"PRI",
"PROPFIND",
"PUT",
"QUERY",
"REBIND",
"REPORT",
"SEARCH",
"TRACE",
"UNBIND",
"UNCHECKOUT",
"UNLINK",
"UNLOCK",
"UPDATE",
"UPDATEREDIRECTREF",
"VERSION-CONTROL",
]
| registered_methods = ['ACL', 'BASELINE-CONTROL', 'BIND', 'CHECKIN', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LABEL', 'LINK', 'LOCK', 'MERGE', 'MKACTIVITY', 'MKCALENDAR', 'MKREDIRECTREF', 'MKWORKSPACE', 'MOVE', 'OPTIONS', 'ORDERPATCH', 'PATCH', 'POST', 'PRI', 'PROPFIND', 'PUT', 'QUERY', 'REBIND', 'REPORT', 'SEARCH', 'TRACE', 'UNBIND', 'UNCHECKOUT', 'UNLINK', 'UNLOCK', 'UPDATE', 'UPDATEREDIRECTREF', 'VERSION-CONTROL'] |
"""Linked list module."""
class Node:
"""Node of a linked list."""
def __init__(self, value, next = None):
self.value = value
self.next = next
class LinkedList:
"""Linked List data structure."""
def __init__(self, head = None):
self.head = head
def __iter__(self):
"""Make this class iterable implementing the "__next__" method."""
self.iter_current = self.head
return self
def __next__(self):
"""Get next element while iterating. Must raise "StopIteration" after the last element."""
if self.iter_current is not None:
node = self.iter_current
self.iter_current = self.iter_current.next
return node
else:
raise StopIteration
# def __iter__(self):
# """Make this class iterable using a generator."""
# current = self.head
# while current is not None:
# yield current
# current = current.next
def insert(self, value):
"""Insert a new value to the linked list."""
self.head = Node(value, self.head)
def size(self):
"""Get the number of elements in the linked list at the head."""
count = 0
current = self.head
while current is not None:
count += 1
current = current.next
return count
def get_head(self):
"""Get the head node."""
return self.head
def get_tail(self):
"""Get the tail node."""
if self.head is None:
return None
current = self.head
while current.next is not None:
current = current.next
return current
def clear(self):
"""Empty the linked list."""
self.head = None
def remove_head(self):
"""Remove the head node."""
if self.head is not None:
self.head = self.head.next
def remove_tail(self):
"""Remove the tail node."""
if self.head is None:
return
if self.head.next is None:
self.head = None
return
previous = self.head
current = self.head.next
while current.next is not None:
previous = current
current = current.next
previous.next = None
def insert_tail(self, value):
"""Insert a new value to the linked list at the tail."""
node = Node(value)
tail = self.get_tail()
if tail is None:
self.head = node
else:
tail.next = node
def get_at(self, index):
"""Get the element at the specified index."""
count = 0
current = self.head
while current is not None:
if count == index:
return current
current = current.next
count += 1
return None
def remove_at(self, index):
"""Remove the element at the specified index."""
if self.head is None:
return
if index == 0:
self.head = self.head.next
previous = self.get_at(index - 1)
if previous is None or previous.next is None:
return
previous.next = previous.next.next
def insert_at(self, index, value):
"""Insert a new value to the linked list at the specified index."""
if self.head is None or index == 0:
self.head = Node(value, self.head)
return
# Get the node before the specified index or, if it not exists, at the tail.
previous = self.get_at(index - 1) or self.get_tail()
previous.next = Node(value, previous.next) | """Linked list module."""
class Node:
"""Node of a linked list."""
def __init__(self, value, next=None):
self.value = value
self.next = next
class Linkedlist:
"""Linked List data structure."""
def __init__(self, head=None):
self.head = head
def __iter__(self):
"""Make this class iterable implementing the "__next__" method."""
self.iter_current = self.head
return self
def __next__(self):
"""Get next element while iterating. Must raise "StopIteration" after the last element."""
if self.iter_current is not None:
node = self.iter_current
self.iter_current = self.iter_current.next
return node
else:
raise StopIteration
def insert(self, value):
"""Insert a new value to the linked list."""
self.head = node(value, self.head)
def size(self):
"""Get the number of elements in the linked list at the head."""
count = 0
current = self.head
while current is not None:
count += 1
current = current.next
return count
def get_head(self):
"""Get the head node."""
return self.head
def get_tail(self):
"""Get the tail node."""
if self.head is None:
return None
current = self.head
while current.next is not None:
current = current.next
return current
def clear(self):
"""Empty the linked list."""
self.head = None
def remove_head(self):
"""Remove the head node."""
if self.head is not None:
self.head = self.head.next
def remove_tail(self):
"""Remove the tail node."""
if self.head is None:
return
if self.head.next is None:
self.head = None
return
previous = self.head
current = self.head.next
while current.next is not None:
previous = current
current = current.next
previous.next = None
def insert_tail(self, value):
"""Insert a new value to the linked list at the tail."""
node = node(value)
tail = self.get_tail()
if tail is None:
self.head = node
else:
tail.next = node
def get_at(self, index):
"""Get the element at the specified index."""
count = 0
current = self.head
while current is not None:
if count == index:
return current
current = current.next
count += 1
return None
def remove_at(self, index):
"""Remove the element at the specified index."""
if self.head is None:
return
if index == 0:
self.head = self.head.next
previous = self.get_at(index - 1)
if previous is None or previous.next is None:
return
previous.next = previous.next.next
def insert_at(self, index, value):
"""Insert a new value to the linked list at the specified index."""
if self.head is None or index == 0:
self.head = node(value, self.head)
return
previous = self.get_at(index - 1) or self.get_tail()
previous.next = node(value, previous.next) |
# coding=utf-8
"""Self organizing list (transpose method) Python implementation."""
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
class SelfOrganizingList:
def __init__(self):
self.first = None
def add_node(self, key, val):
if self.first:
prev = None
current = self.first
while current:
prev = current
current = current.next
prev.next = Node(key, val)
else:
self.first = Node(key, val)
def get_node(self, key):
prev = None
prevprev = None
current = self.first
while current.key != key:
prevprev = prev
prev = current
current = current.next
if prevprev:
prevprev.next = current
prev.next = current.next
current.next = prev
return current.val
def get_items(self):
current = self.first
items = []
while current:
items.append(current.val)
current = current.next
return items
if __name__ == "__main__":
sol = SelfOrganizingList()
for x in range(100):
sol.add_node(x, x)
print(sol.get_items())
for x in range(100):
sol.get_node(x % 15)
print(sol.get_items())
for x in range(100):
sol.get_node(12)
print(sol.get_items())
| """Self organizing list (transpose method) Python implementation."""
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
class Selforganizinglist:
def __init__(self):
self.first = None
def add_node(self, key, val):
if self.first:
prev = None
current = self.first
while current:
prev = current
current = current.next
prev.next = node(key, val)
else:
self.first = node(key, val)
def get_node(self, key):
prev = None
prevprev = None
current = self.first
while current.key != key:
prevprev = prev
prev = current
current = current.next
if prevprev:
prevprev.next = current
prev.next = current.next
current.next = prev
return current.val
def get_items(self):
current = self.first
items = []
while current:
items.append(current.val)
current = current.next
return items
if __name__ == '__main__':
sol = self_organizing_list()
for x in range(100):
sol.add_node(x, x)
print(sol.get_items())
for x in range(100):
sol.get_node(x % 15)
print(sol.get_items())
for x in range(100):
sol.get_node(12)
print(sol.get_items()) |
def open_file():
'''Remember to put a docstring here'''
while True:
file_name = input("Input a file name: ")
try:
fp = open(file_name)
break
except FileNotFoundError:
print("Unable to open file. Please try again.")
continue
return fp
def main():
count = [0 for i in range(9)]
percentages = [0 for i in range(9)]
expected_percentages = ['30.1','17.6','12.5','9.7','7.9','6.7','5.8','5.1','4.6']
fp = open_file()
for line in fp:
line = line.strip()
try:
number = int(line)
except (TypeError, ValueError):
pass
try:
number = int(str(line[0]))
except ValueError:
pass
index = number - 1
count[index]+= 1
line_count = sum(count)
print("Digit Percent Benford")
for x in range(len(count)):
percentages[x] = (count[x]/line_count)*100
print("{:3s} {:>10.1f}% ({:>5s}%) ".format(str(x+1)+":",percentages[x],expected_percentages[x]))
main() | def open_file():
"""Remember to put a docstring here"""
while True:
file_name = input('Input a file name: ')
try:
fp = open(file_name)
break
except FileNotFoundError:
print('Unable to open file. Please try again.')
continue
return fp
def main():
count = [0 for i in range(9)]
percentages = [0 for i in range(9)]
expected_percentages = ['30.1', '17.6', '12.5', '9.7', '7.9', '6.7', '5.8', '5.1', '4.6']
fp = open_file()
for line in fp:
line = line.strip()
try:
number = int(line)
except (TypeError, ValueError):
pass
try:
number = int(str(line[0]))
except ValueError:
pass
index = number - 1
count[index] += 1
line_count = sum(count)
print('Digit Percent Benford')
for x in range(len(count)):
percentages[x] = count[x] / line_count * 100
print('{:3s} {:>10.1f}% ({:>5s}%) '.format(str(x + 1) + ':', percentages[x], expected_percentages[x]))
main() |
class C(object):
"""Silly example!!!"""
def __init__(self):
"""XXXX"""
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
# class property([fget[, fset[, fdel[, doc]]]])
c = C()
c.x = 10 # setx
print(C.x.__doc__)
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
c = C()
# c.x = 10 # setx
print(c.x) # getx
# del c.x # delx
c.x = 'HELEN'
print(C.x.__doc__) # no need instance | class C(object):
"""Silly example!!!"""
def __init__(self):
"""XXXX"""
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
c = c()
c.x = 10
print(C.x.__doc__)
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
c = c()
print(c.x)
c.x = 'HELEN'
print(C.x.__doc__) |
#
# https://projecteuler.net/problem=4
#
# Largest palindrome product
# Problem 4
#
# A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digits numers is 9009 = 91 x 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
# Solution
def reverse(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
def isPalindrome(value):
s = str(value)
# return s == s[::-1] #It is not valid in Micro Python
return s == reverse(s)
def problem(limit):
maxPalindrome = 0
for x in range(limit):
for y in range(limit):
value = x * y
if isPalindrome(value):
if (value > maxPalindrome):
# print(value)
maxPalindrome = value
return maxPalindrome
# Asserts
print(reverse("demo") == "omed")
print(isPalindrome(9008) == False)
print(isPalindrome(9009) == True)
print(problem(100) == 9009)
# print(problem(1000) == 906609) #Computational issues for TI-84
| def reverse(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1
new_string += a_string[index]
return new_string
def is_palindrome(value):
s = str(value)
return s == reverse(s)
def problem(limit):
max_palindrome = 0
for x in range(limit):
for y in range(limit):
value = x * y
if is_palindrome(value):
if value > maxPalindrome:
max_palindrome = value
return maxPalindrome
print(reverse('demo') == 'omed')
print(is_palindrome(9008) == False)
print(is_palindrome(9009) == True)
print(problem(100) == 9009) |
class Player:
"""
Defines all character related attributes. Used by scripts.py.
"""
day = 0
timeofday = 6
stats = {
'name': 'Player',
'health': 100,
'speed': 1,
'intelligence': 1,
'rads': 0,
}
inventory = {
'money': 0,
'food': 10,
'water': 10
}
skills = {}
buildings = {'shelter': 0,
'shed': 0,
'corral': 0,
'workshop': 0,
'outpost': 0,
'barricade': 0,
'turret': 0,
'farm': 0,
}
| class Player:
"""
Defines all character related attributes. Used by scripts.py.
"""
day = 0
timeofday = 6
stats = {'name': 'Player', 'health': 100, 'speed': 1, 'intelligence': 1, 'rads': 0}
inventory = {'money': 0, 'food': 10, 'water': 10}
skills = {}
buildings = {'shelter': 0, 'shed': 0, 'corral': 0, 'workshop': 0, 'outpost': 0, 'barricade': 0, 'turret': 0, 'farm': 0} |
class ItemModel:
def __init__(self):
self.vowels = ['A', 'E', 'I', 'O', 'U']
self.rare_letters = ['X', 'J']
self.other_letters = ['B', 'C', 'D', 'F', 'G', 'H',
'K', 'L', 'M', 'N', 'P', 'Q',
'R', 'S', 'T', 'V', 'W', 'Y', 'Z']
self.items = [
{"id": 1, "name": "A", 'costs': {'amount': 1}, "affects": {}},
{"id": 2, "name": "B", 'costs': {'amount': 1}, "affects": {}},
{"id": 3, "name": "C", 'costs': {'amount': 1}, "affects": {}},
{"id": 4, "name": "D", 'costs': {'amount': 1}, "affects": {}},
{"id": 5, "name": "E", 'costs': {'amount': 1}, "affects": {}},
{"id": 6, "name": "F", 'costs': {'amount': 1}, "affects": {}},
{"id": 7, "name": "G", 'costs': {'amount': 1}, "affects": {}},
{"id": 8, "name": "H", 'costs': {'amount': 1}, "affects": {}},
{"id": 9, "name": "I", 'costs': {'amount': 1}, "affects": {}},
{"id": 10, "name": "J", 'costs': {'amount': 1}, "affects": {}},
{"id": 11, "name": "K", 'costs': {'amount': 1}, "affects": {}},
{"id": 12, "name": "L", 'costs': {'amount': 1}, "affects": {}},
{"id": 13, "name": "M", 'costs': {'amount': 1}, "affects": {}},
{"id": 14, "name": "N", 'costs': {'amount': 1}, "affects": {}},
{"id": 15, "name": "O", 'costs': {'amount': 1}, "affects": {}},
{"id": 16, "name": "P", 'costs': {'amount': 1}, "affects": {}},
{"id": 17, "name": "Q", 'costs': {'amount': 1}, "affects": {}},
{"id": 18, "name": "R", 'costs': {'amount': 1}, "affects": {}},
{"id": 19, "name": "S", 'costs': {'amount': 1}, "affects": {}},
{"id": 20, "name": "T", 'costs': {'amount': 1}, "affects": {}},
{"id": 21, "name": "U", 'costs': {'amount': 1}, "affects": {}},
{"id": 22, "name": "V", 'costs': {'amount': 1}, "affects": {}},
{"id": 23, "name": "W", 'costs': {'amount': 1}, "affects": {}},
{"id": 24, "name": "X", 'costs': {'amount': 1}, "affects": {}},
{"id": 25, "name": "Y", 'costs': {'amount': 1}, "affects": {}},
{"id": 26, "name": "Z", 'costs': {'amount': 1}, "affects": {}}
]
| class Itemmodel:
def __init__(self):
self.vowels = ['A', 'E', 'I', 'O', 'U']
self.rare_letters = ['X', 'J']
self.other_letters = ['B', 'C', 'D', 'F', 'G', 'H', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y', 'Z']
self.items = [{'id': 1, 'name': 'A', 'costs': {'amount': 1}, 'affects': {}}, {'id': 2, 'name': 'B', 'costs': {'amount': 1}, 'affects': {}}, {'id': 3, 'name': 'C', 'costs': {'amount': 1}, 'affects': {}}, {'id': 4, 'name': 'D', 'costs': {'amount': 1}, 'affects': {}}, {'id': 5, 'name': 'E', 'costs': {'amount': 1}, 'affects': {}}, {'id': 6, 'name': 'F', 'costs': {'amount': 1}, 'affects': {}}, {'id': 7, 'name': 'G', 'costs': {'amount': 1}, 'affects': {}}, {'id': 8, 'name': 'H', 'costs': {'amount': 1}, 'affects': {}}, {'id': 9, 'name': 'I', 'costs': {'amount': 1}, 'affects': {}}, {'id': 10, 'name': 'J', 'costs': {'amount': 1}, 'affects': {}}, {'id': 11, 'name': 'K', 'costs': {'amount': 1}, 'affects': {}}, {'id': 12, 'name': 'L', 'costs': {'amount': 1}, 'affects': {}}, {'id': 13, 'name': 'M', 'costs': {'amount': 1}, 'affects': {}}, {'id': 14, 'name': 'N', 'costs': {'amount': 1}, 'affects': {}}, {'id': 15, 'name': 'O', 'costs': {'amount': 1}, 'affects': {}}, {'id': 16, 'name': 'P', 'costs': {'amount': 1}, 'affects': {}}, {'id': 17, 'name': 'Q', 'costs': {'amount': 1}, 'affects': {}}, {'id': 18, 'name': 'R', 'costs': {'amount': 1}, 'affects': {}}, {'id': 19, 'name': 'S', 'costs': {'amount': 1}, 'affects': {}}, {'id': 20, 'name': 'T', 'costs': {'amount': 1}, 'affects': {}}, {'id': 21, 'name': 'U', 'costs': {'amount': 1}, 'affects': {}}, {'id': 22, 'name': 'V', 'costs': {'amount': 1}, 'affects': {}}, {'id': 23, 'name': 'W', 'costs': {'amount': 1}, 'affects': {}}, {'id': 24, 'name': 'X', 'costs': {'amount': 1}, 'affects': {}}, {'id': 25, 'name': 'Y', 'costs': {'amount': 1}, 'affects': {}}, {'id': 26, 'name': 'Z', 'costs': {'amount': 1}, 'affects': {}}] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Python for AHDA.
Part 4, Example 1.
Please rename:
'sample_thomas_moore_download.txt'
to:
'Moore.txt'
"""
# Cut a subset of a file
F_IN = 'Moore.txt'
F_106 = 'Moore_106.txt'
F_4170 = 'Moore_4170.txt'
# by slicing a string
with open(F_IN, 'r', encoding='utf-8', newline='\n') as f_in:
raw_text = f_in.read()
with open(F_4170, 'w', encoding='utf-8', newline='\n') as f_out:
f_out.write(raw_text[:4170])
# alternative by looping through lines
with open(F_IN, 'r', encoding='utf-8', newline='\n') as f_in:
lines = f_in.readlines()
with open(F_106, 'w', encoding='utf-8', newline='\n') as f_out:
for i, line in enumerate(lines, start=1):
f_out.write(line)
if i == 106:
break
| """Python for AHDA.
Part 4, Example 1.
Please rename:
'sample_thomas_moore_download.txt'
to:
'Moore.txt'
"""
f_in = 'Moore.txt'
f_106 = 'Moore_106.txt'
f_4170 = 'Moore_4170.txt'
with open(F_IN, 'r', encoding='utf-8', newline='\n') as f_in:
raw_text = f_in.read()
with open(F_4170, 'w', encoding='utf-8', newline='\n') as f_out:
f_out.write(raw_text[:4170])
with open(F_IN, 'r', encoding='utf-8', newline='\n') as f_in:
lines = f_in.readlines()
with open(F_106, 'w', encoding='utf-8', newline='\n') as f_out:
for (i, line) in enumerate(lines, start=1):
f_out.write(line)
if i == 106:
break |
#-*-coding:utf-8-*-
def bmi(w, h):
bmi = (w/(h**2))*10000.0
if bmi<15.0 :
str = "VSU"
elif bmi<16.0:
str = "SUN"
elif bmi<18.5:
str = "UND"
elif bmi<25.0:
str = "NOR"
elif bmi<30.0:
str = "OVE"
elif bmi<35.0:
str = "MOV"
elif bmi<40.0:
str = "SOV"
else:
str = "VSO"
return str
def main():
weight = float(input())
height = float(input())
print(bmi(weight, height))
if __name__ == '__main__':
main() | def bmi(w, h):
bmi = w / h ** 2 * 10000.0
if bmi < 15.0:
str = 'VSU'
elif bmi < 16.0:
str = 'SUN'
elif bmi < 18.5:
str = 'UND'
elif bmi < 25.0:
str = 'NOR'
elif bmi < 30.0:
str = 'OVE'
elif bmi < 35.0:
str = 'MOV'
elif bmi < 40.0:
str = 'SOV'
else:
str = 'VSO'
return str
def main():
weight = float(input())
height = float(input())
print(bmi(weight, height))
if __name__ == '__main__':
main() |
"""
Add riverwalls to the domain
Gareth Davies, Geoscience Australia 2014+
"""
def setup_riverwalls(domain, project):
# #########################################################################
#
# Add Riverwalls [ must happen after distribute(domain) in parallel ]
#
# #########################################################################
if not project.riverwalls == {}:
domain.riverwallData.create_riverwalls(project.riverwalls,
project.riverwall_par)
domain.riverwallData.export_riverwalls_to_text(
output_dir=project.output_dir + '/' +
project.spatial_text_output_dir)
return
| """
Add riverwalls to the domain
Gareth Davies, Geoscience Australia 2014+
"""
def setup_riverwalls(domain, project):
if not project.riverwalls == {}:
domain.riverwallData.create_riverwalls(project.riverwalls, project.riverwall_par)
domain.riverwallData.export_riverwalls_to_text(output_dir=project.output_dir + '/' + project.spatial_text_output_dir)
return |
class Block:
"""Minecraft PI block description. Can be sent to Minecraft.setBlock/s"""
def __init__(self, id, data=0):
self.id = id
self.data = data
def __cmp__(self, rhs):
return hash(self) - hash(rhs)
def __eq__(self, rhs):
return self.id == rhs.id and self.data == rhs.data
def __hash__(self):
return (self.id << 8) + self.data
def withData(self, data):
return Block(self.id, data)
def __iter__(self):
"""Allows a Block to be sent whenever id [and data] is needed"""
return iter((self.id, self.data))
def __repr__(self):
return "Block(%d, %d)"%(self.id, self.data)
AIR = Block(0)
STONE = Block(1)
GRASS = Block(2)
DIRT = Block(3)
COBBLESTONE = Block(4)
WOOD_PLANKS = Block(5)
SAPLING = Block(6)
BEDROCK = Block(7)
WATER_FLOWING = Block(8)
WATER = WATER_FLOWING
WATER_STATIONARY = Block(9)
LAVA_FLOWING = Block(10)
LAVA = LAVA_FLOWING
LAVA_STATIONARY = Block(11)
SAND = Block(12)
GRAVEL = Block(13)
GOLD_ORE = Block(14)
IRON_ORE = Block(15)
COAL_ORE = Block(16)
WOOD = Block(17)
LEAVES = Block(18)
GLASS = Block(20)
LAPIS_LAZULI_ORE = Block(21)
LAPIS_LAZULI_BLOCK = Block(22)
SANDSTONE = Block(24)
BED = Block(26)
RAIL_POWERED = Block(27)
RAIL_DETECTOR = Block(28)
COBWEB = Block(30)
GRASS_TALL = Block(31)
DEAD_BUSH = Block(32)
WOOL = Block(35)
FLOWER_YELLOW = Block(37)
FLOWER_CYAN = Block(38)
MUSHROOM_BROWN = Block(39)
MUSHROOM_RED = Block(40)
GOLD_BLOCK = Block(41)
IRON_BLOCK = Block(42)
STONE_SLAB_DOUBLE = Block(43)
STONE_SLAB = Block(44)
BRICK_BLOCK = Block(45)
TNT = Block(46)
BOOKSHELF = Block(47)
MOSS_STONE = Block(48)
OBSIDIAN = Block(49)
TORCH = Block(50)
FIRE = Block(51)
STAIRS_WOOD = Block(53)
CHEST = Block(54)
DIAMOND_ORE = Block(56)
DIAMOND_BLOCK = Block(57)
CRAFTING_TABLE = Block(58)
FARMLAND = Block(60)
FURNACE_INACTIVE = Block(61)
FURNACE_ACTIVE = Block(62)
SIGN_STANDING = Block(63)
DOOR_WOOD = Block(64)
LADDER = Block(65)
RAIL = Block(66)
STAIRS_COBBLESTONE = Block(67)
SIGN_WALL = Block(68)
DOOR_IRON = Block(71)
REDSTONE_ORE = Block(73)
TORCH_REDSTONE = Block(76)
SNOW = Block(78)
ICE = Block(79)
SNOW_BLOCK = Block(80)
CACTUS = Block(81)
CLAY = Block(82)
SUGAR_CANE = Block(83)
FENCE = Block(85)
PUMPKIN = Block(86)
NETHERRACK = Block(87)
SOUL_SAND = Block(88)
GLOWSTONE_BLOCK = Block(89)
LIT_PUMPKIN = Block(91)
STAINED_GLASS = Block(95)
BEDROCK_INVISIBLE = Block(95)
TRAPDOOR = Block(96)
STONE_BRICK = Block(98)
GLASS_PANE = Block(102)
MELON = Block(103)
FENCE_GATE = Block(107)
STAIRS_BRICK = Block(108)
STAIRS_STONE_BRICK = Block(109)
MYCELIUM = Block(110)
NETHER_BRICK = Block(112)
FENCE_NETHER_BRICK = Block(113)
STAIRS_NETHER_BRICK = Block(114)
END_STONE = Block(121)
WOODEN_SLAB = Block(126)
STAIRS_SANDSTONE = Block(128)
EMERALD_ORE = Block(129)
RAIL_ACTIVATOR = Block(157)
LEAVES2 = Block(161)
TRAPDOOR_IRON = Block(167)
FENCE_SPRUCE = Block(188)
FENCE_BIRCH = Block(189)
FENCE_JUNGLE = Block(190)
FENCE_DARK_OAK = Block(191)
FENCE_ACACIA = Block(192)
DOOR_SPRUCE = Block(193)
DOOR_BIRCH = Block(194)
DOOR_JUNGLE = Block(195)
DOOR_ACACIA = Block(196)
DOOR_DARK_OAK = Block(197)
GLOWING_OBSIDIAN = Block(246)
NETHER_REACTOR_CORE = Block(247)
| class Block:
"""Minecraft PI block description. Can be sent to Minecraft.setBlock/s"""
def __init__(self, id, data=0):
self.id = id
self.data = data
def __cmp__(self, rhs):
return hash(self) - hash(rhs)
def __eq__(self, rhs):
return self.id == rhs.id and self.data == rhs.data
def __hash__(self):
return (self.id << 8) + self.data
def with_data(self, data):
return block(self.id, data)
def __iter__(self):
"""Allows a Block to be sent whenever id [and data] is needed"""
return iter((self.id, self.data))
def __repr__(self):
return 'Block(%d, %d)' % (self.id, self.data)
air = block(0)
stone = block(1)
grass = block(2)
dirt = block(3)
cobblestone = block(4)
wood_planks = block(5)
sapling = block(6)
bedrock = block(7)
water_flowing = block(8)
water = WATER_FLOWING
water_stationary = block(9)
lava_flowing = block(10)
lava = LAVA_FLOWING
lava_stationary = block(11)
sand = block(12)
gravel = block(13)
gold_ore = block(14)
iron_ore = block(15)
coal_ore = block(16)
wood = block(17)
leaves = block(18)
glass = block(20)
lapis_lazuli_ore = block(21)
lapis_lazuli_block = block(22)
sandstone = block(24)
bed = block(26)
rail_powered = block(27)
rail_detector = block(28)
cobweb = block(30)
grass_tall = block(31)
dead_bush = block(32)
wool = block(35)
flower_yellow = block(37)
flower_cyan = block(38)
mushroom_brown = block(39)
mushroom_red = block(40)
gold_block = block(41)
iron_block = block(42)
stone_slab_double = block(43)
stone_slab = block(44)
brick_block = block(45)
tnt = block(46)
bookshelf = block(47)
moss_stone = block(48)
obsidian = block(49)
torch = block(50)
fire = block(51)
stairs_wood = block(53)
chest = block(54)
diamond_ore = block(56)
diamond_block = block(57)
crafting_table = block(58)
farmland = block(60)
furnace_inactive = block(61)
furnace_active = block(62)
sign_standing = block(63)
door_wood = block(64)
ladder = block(65)
rail = block(66)
stairs_cobblestone = block(67)
sign_wall = block(68)
door_iron = block(71)
redstone_ore = block(73)
torch_redstone = block(76)
snow = block(78)
ice = block(79)
snow_block = block(80)
cactus = block(81)
clay = block(82)
sugar_cane = block(83)
fence = block(85)
pumpkin = block(86)
netherrack = block(87)
soul_sand = block(88)
glowstone_block = block(89)
lit_pumpkin = block(91)
stained_glass = block(95)
bedrock_invisible = block(95)
trapdoor = block(96)
stone_brick = block(98)
glass_pane = block(102)
melon = block(103)
fence_gate = block(107)
stairs_brick = block(108)
stairs_stone_brick = block(109)
mycelium = block(110)
nether_brick = block(112)
fence_nether_brick = block(113)
stairs_nether_brick = block(114)
end_stone = block(121)
wooden_slab = block(126)
stairs_sandstone = block(128)
emerald_ore = block(129)
rail_activator = block(157)
leaves2 = block(161)
trapdoor_iron = block(167)
fence_spruce = block(188)
fence_birch = block(189)
fence_jungle = block(190)
fence_dark_oak = block(191)
fence_acacia = block(192)
door_spruce = block(193)
door_birch = block(194)
door_jungle = block(195)
door_acacia = block(196)
door_dark_oak = block(197)
glowing_obsidian = block(246)
nether_reactor_core = block(247) |
"""depsgen.bzl
"""
load("@build_stack_rules_proto//rules:providers.bzl", "ProtoDependencyInfo")
def _depsgen_impl(ctx):
config_json = ctx.outputs.json
output_deps = ctx.outputs.deps
config = struct(
out = output_deps.path,
name = ctx.label.name,
deps = [dep[ProtoDependencyInfo] for dep in ctx.attr.deps],
)
ctx.actions.write(
output = config_json,
content = config.to_json(),
)
ctx.actions.run(
mnemonic = "DepsGenerate",
progress_message = "Generating %s deps" % ctx.attr.name,
executable = ctx.file._depsgen,
arguments = ["--config_json=%s" % config_json.path],
inputs = [config_json],
outputs = [output_deps],
)
return [DefaultInfo(
files = depset([config_json, output_deps]),
)]
depsgen = rule(
implementation = _depsgen_impl,
attrs = {
"deps": attr.label_list(
doc = "Top level dependencies to compute",
providers = [ProtoDependencyInfo],
),
"_depsgen": attr.label(
doc = "The depsgen tool",
default = "//cmd/depsgen",
allow_single_file = True,
executable = True,
cfg = "host",
),
},
outputs = {
"json": "%{name}.json",
"deps": "%{name}_deps.bzl",
},
)
| """depsgen.bzl
"""
load('@build_stack_rules_proto//rules:providers.bzl', 'ProtoDependencyInfo')
def _depsgen_impl(ctx):
config_json = ctx.outputs.json
output_deps = ctx.outputs.deps
config = struct(out=output_deps.path, name=ctx.label.name, deps=[dep[ProtoDependencyInfo] for dep in ctx.attr.deps])
ctx.actions.write(output=config_json, content=config.to_json())
ctx.actions.run(mnemonic='DepsGenerate', progress_message='Generating %s deps' % ctx.attr.name, executable=ctx.file._depsgen, arguments=['--config_json=%s' % config_json.path], inputs=[config_json], outputs=[output_deps])
return [default_info(files=depset([config_json, output_deps]))]
depsgen = rule(implementation=_depsgen_impl, attrs={'deps': attr.label_list(doc='Top level dependencies to compute', providers=[ProtoDependencyInfo]), '_depsgen': attr.label(doc='The depsgen tool', default='//cmd/depsgen', allow_single_file=True, executable=True, cfg='host')}, outputs={'json': '%{name}.json', 'deps': '%{name}_deps.bzl'}) |
class P:
def __init__( self, name, alias ):
self.name = name # public
self.__alias = alias # private
def who(self):
print('name : ', self.name)
print('alias : ', self.__alias)
class X:
def __init__( self, x ):
self.set_x( x )
def get_x( self ):
return self.__x
def set_x( self, x ):
if x > 1000:
self.__x = 1000
elif x < 0:
self.__x = 0
else:
self.__x = x
class Y:
def __init__( self, x ):
self.x = x # self.x is now the @x.setter
@property
def x( self ):
return self.__x # this is a private variable
@x.setter
def x( self, x ):
if x > 1000:
self.__x = 1000
elif x < 0:
self.__x = 0
else:
self.__x = x
class S:
def __init__( self, name ):
self.name = name
def __repr__( self ):
return f'{self.__dict__}'
def __str__( self ):
return f'Name: {self.name}'
def __add__( self, other ):
return S(f'{self.name} {other.name}')
class Deck:
def __init__( self, cards ):
self.cards = list( cards )
def __getitem__( self, key ):
return self.cards[key]
def __repr__( self ):
return f'{self.__dict__}'
p = P('Claus', 'clbo')
p.who()
print( p.__dict__ )
print( p._P__alias )
p._P__alias = 'wow'
print ( p._P__alias )
x1 = X( 3 )
x2 = X( 50 )
x1.set_x( x1.get_x() + x2.get_x() )
print ( x1.get_x() )
y1 = Y( 10 )
y2 = Y( 15 )
print( y1.__dict__ )
print ( y1.x )
y1.x = y1.x + y2.x
print ( y1.x )
y1._Y__x = -10
print( y1.x )
s1 = S( "Cristian" )
s2 = S( "Valentin" )
s3 = s1.__add__( s2 )
print( s3 )
d1 = Deck( ["K", "A", 2, 3] )
print( d1 )
print ( d1[0] ) | class P:
def __init__(self, name, alias):
self.name = name
self.__alias = alias
def who(self):
print('name : ', self.name)
print('alias : ', self.__alias)
class X:
def __init__(self, x):
self.set_x(x)
def get_x(self):
return self.__x
def set_x(self, x):
if x > 1000:
self.__x = 1000
elif x < 0:
self.__x = 0
else:
self.__x = x
class Y:
def __init__(self, x):
self.x = x
@property
def x(self):
return self.__x
@x.setter
def x(self, x):
if x > 1000:
self.__x = 1000
elif x < 0:
self.__x = 0
else:
self.__x = x
class S:
def __init__(self, name):
self.name = name
def __repr__(self):
return f'{self.__dict__}'
def __str__(self):
return f'Name: {self.name}'
def __add__(self, other):
return s(f'{self.name} {other.name}')
class Deck:
def __init__(self, cards):
self.cards = list(cards)
def __getitem__(self, key):
return self.cards[key]
def __repr__(self):
return f'{self.__dict__}'
p = p('Claus', 'clbo')
p.who()
print(p.__dict__)
print(p._P__alias)
p._P__alias = 'wow'
print(p._P__alias)
x1 = x(3)
x2 = x(50)
x1.set_x(x1.get_x() + x2.get_x())
print(x1.get_x())
y1 = y(10)
y2 = y(15)
print(y1.__dict__)
print(y1.x)
y1.x = y1.x + y2.x
print(y1.x)
y1._Y__x = -10
print(y1.x)
s1 = s('Cristian')
s2 = s('Valentin')
s3 = s1.__add__(s2)
print(s3)
d1 = deck(['K', 'A', 2, 3])
print(d1)
print(d1[0]) |
class search:
def __init__():
pass
def ParseSearch(request):
tab = {}
if request.len > 0:
pass
pass
def search(request):
pass
| class Search:
def __init__():
pass
def parse_search(request):
tab = {}
if request.len > 0:
pass
pass
def search(request):
pass |
a = int(input())
b = int(input())
c = int(input())
mul = str(a * b * c)
for i in range(0, 10):
count = 0
for j in mul:
if i == int(j):
count += 1
print(count)
| a = int(input())
b = int(input())
c = int(input())
mul = str(a * b * c)
for i in range(0, 10):
count = 0
for j in mul:
if i == int(j):
count += 1
print(count) |
#User function Template for python3
# https://gitlab.com/pranav/my-sprints/-/snippets/2215721
'''
Input:
a = 5, b = 5, x = 11, # dest = (5, 5), x = 11
Output:
0
|
- R -
|
(-1) * x1 + 1 * x2 = a
(-1) * y1 + 1 * y2 = b
x1 + x2 + y1 + y2 = x
TC: O(1)
SC: O(1)
---
Exponential TC algorithm: O(1 + 4 + 4^2 + ... + 4^x), SC: O(4^x)
1. Start from 0, 0
2. For each direction posibility:
2.1. Do BFS
2.2. If we touch a,b at any leaf node(after x moves), return 1 else return 0
to_visit.push([0, 0])
step = 0
while(step < x):
queue_len = len(to_visit) # number of nodes at this level to be visited
id = 0
while(id < queue_len):
start = to_visit.pop(0)
next_1 = [start[0], start[1] + 1]
next_2 = [start[0], start[1] - 1]
next_3 = [start[0] + 1, start[1]]
next_4 = [start[0] - 1, start[1]]
to_visit.push(next_1)
to_visit.push(next_2)
to_visit.push(next_3)
to_visit.push(next_4)
id += 1
step += 1
while to_visit:
element = to_visit.pop()
if (element[0] == a and element[1] == b):
return 1
else:
continue
return 0
---
(a + b) mod x == 0
---
try solving this in 1D: given x units, and 0 starting point, each movement is +1 or -1
given (a, x) return true or false: if a % 2 == 0 and x > a, check x % a == 0, return true else false
if a % 2 == 1 and x > a, check x % a == 1 return true
'''
class Solution:
def canReachBFS(self, a, b, x):
to_visit = []
to_visit.append([0, 0])
step = 0
while(step < x):
queue_len = len(to_visit) # number of nodes at this level to be visited
id = 0
while(id < queue_len):
start = to_visit.pop(0)
next_1 = [start[0], start[1] + 1]
next_2 = [start[0], start[1] - 1]
next_3 = [start[0] + 1, start[1]]
next_4 = [start[0] - 1, start[1]]
to_visit.append(next_1)
to_visit.append(next_2)
to_visit.append(next_3)
to_visit.append(next_4)
id += 1
step += 1
while to_visit:
element = to_visit.pop()
if (element[0] == a and element[1] == b):
return 1
else:
continue
return 0
def canReach(self, a, b, x): # Final solution, TC: O(1), SC: O(1)
# code here
sum_ab = abs(a) + abs(b)
if x < sum_ab: # sanity check
return 0
if sum_ab % 2 == x % 2: # (0,0, 8)->1, (0, 0, 7)-> 0
return 1
else:
return 0
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int (input ())
for _ in range (t):
a,b,x=map(int,input().split())
ob = Solution()
print(ob.canReach(a,b,x))
# } Driver Code Ends
| """
Input:
a = 5, b = 5, x = 11, # dest = (5, 5), x = 11
Output:
0
|
- R -
|
(-1) * x1 + 1 * x2 = a
(-1) * y1 + 1 * y2 = b
x1 + x2 + y1 + y2 = x
TC: O(1)
SC: O(1)
---
Exponential TC algorithm: O(1 + 4 + 4^2 + ... + 4^x), SC: O(4^x)
1. Start from 0, 0
2. For each direction posibility:
2.1. Do BFS
2.2. If we touch a,b at any leaf node(after x moves), return 1 else return 0
to_visit.push([0, 0])
step = 0
while(step < x):
queue_len = len(to_visit) # number of nodes at this level to be visited
id = 0
while(id < queue_len):
start = to_visit.pop(0)
next_1 = [start[0], start[1] + 1]
next_2 = [start[0], start[1] - 1]
next_3 = [start[0] + 1, start[1]]
next_4 = [start[0] - 1, start[1]]
to_visit.push(next_1)
to_visit.push(next_2)
to_visit.push(next_3)
to_visit.push(next_4)
id += 1
step += 1
while to_visit:
element = to_visit.pop()
if (element[0] == a and element[1] == b):
return 1
else:
continue
return 0
---
(a + b) mod x == 0
---
try solving this in 1D: given x units, and 0 starting point, each movement is +1 or -1
given (a, x) return true or false: if a % 2 == 0 and x > a, check x % a == 0, return true else false
if a % 2 == 1 and x > a, check x % a == 1 return true
"""
class Solution:
def can_reach_bfs(self, a, b, x):
to_visit = []
to_visit.append([0, 0])
step = 0
while step < x:
queue_len = len(to_visit)
id = 0
while id < queue_len:
start = to_visit.pop(0)
next_1 = [start[0], start[1] + 1]
next_2 = [start[0], start[1] - 1]
next_3 = [start[0] + 1, start[1]]
next_4 = [start[0] - 1, start[1]]
to_visit.append(next_1)
to_visit.append(next_2)
to_visit.append(next_3)
to_visit.append(next_4)
id += 1
step += 1
while to_visit:
element = to_visit.pop()
if element[0] == a and element[1] == b:
return 1
else:
continue
return 0
def can_reach(self, a, b, x):
sum_ab = abs(a) + abs(b)
if x < sum_ab:
return 0
if sum_ab % 2 == x % 2:
return 1
else:
return 0
if __name__ == '__main__':
t = int(input())
for _ in range(t):
(a, b, x) = map(int, input().split())
ob = solution()
print(ob.canReach(a, b, x)) |
#!/usr/bin/python3
n = int(input())
_ = input()
for i in range(n):
a = int(input())
print(a*(i+1))
| n = int(input())
_ = input()
for i in range(n):
a = int(input())
print(a * (i + 1)) |
class NanometerPixelConverter:
def __init__(self, pitch_nm: float):
self._pitch_nm = pitch_nm
def to_pixel(self, value_nm: float) -> int:
return int(value_nm / self._pitch_nm)
def to_nm(self, value_pixel: int) -> float:
return value_pixel * self._pitch_nm
| class Nanometerpixelconverter:
def __init__(self, pitch_nm: float):
self._pitch_nm = pitch_nm
def to_pixel(self, value_nm: float) -> int:
return int(value_nm / self._pitch_nm)
def to_nm(self, value_pixel: int) -> float:
return value_pixel * self._pitch_nm |
#!/usr/bin/env python
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
__author__ = 'kjellander@webrtc.org (Henrik Kjellander)'
class DataHelper(object):
"""
Helper class for managing table data.
This class does not verify the consistency of the data tables sent into it.
"""
def __init__(self, data_list, table_description, names_list, messages):
""" Initializes the DataHelper with data.
Args:
data_list: List of one or more data lists in the format that the
Google Visualization Python API expects (list of dictionaries, one
per row of data). See the gviz_api.DataTable documentation for more
info.
table_description: dictionary describing the data types of all
columns in the data lists, as defined in the gviz_api.DataTable
documentation.
names_list: List of strings of what we're going to name the data
columns after. Usually different runs of data collection.
messages: List of strings we might append error messages to.
"""
self.data_list = data_list
self.table_description = table_description
self.names_list = names_list
self.messages = messages
self.number_of_datasets = len(data_list)
self.number_of_frames = len(data_list[0])
def CreateData(self, field_name, start_frame=0, end_frame=0):
""" Creates a data structure for a specified data field.
Creates a data structure (data type description dictionary and a list
of data dictionaries) to be used with the Google Visualization Python
API. The frame_number column is always present and one column per data
set is added and its field name is suffixed by _N where N is the number
of the data set (0, 1, 2...)
Args:
field_name: String name of the field, must be present in the data
structure this DataHelper was created with.
start_frame: Frame number to start at (zero indexed). Default: 0.
end_frame: Frame number to be the last frame. If zero all frames
will be included. Default: 0.
Returns:
A tuple containing:
- a dictionary describing the columns in the data result_data_table below.
This description uses the name for each data set specified by
names_list.
Example with two data sets named 'Foreman' and 'Crew':
{
'frame_number': ('number', 'Frame number'),
'ssim_0': ('number', 'Foreman'),
'ssim_1': ('number', 'Crew'),
}
- a list containing dictionaries (one per row) with the frame_number
column and one column of the specified field_name column per data
set.
Example with two data sets named 'Foreman' and 'Crew':
[
{'frame_number': 0, 'ssim_0': 0.98, 'ssim_1': 0.77 },
{'frame_number': 1, 'ssim_0': 0.81, 'ssim_1': 0.53 },
]
"""
# Build dictionary that describes the data types
result_table_description = {'frame_number': ('string', 'Frame number')}
for dataset_index in range(self.number_of_datasets):
column_name = '%s_%s' % (field_name, dataset_index)
column_type = self.table_description[field_name][0]
column_description = self.names_list[dataset_index]
result_table_description[column_name] = (column_type, column_description)
# Build data table of all the data
result_data_table = []
# We're going to have one dictionary per row.
# Create that and copy frame_number values from the first data set
for source_row in self.data_list[0]:
row_dict = { 'frame_number': source_row['frame_number'] }
result_data_table.append(row_dict)
# Pick target field data points from the all data tables
if end_frame == 0: # Default to all frames
end_frame = self.number_of_frames
for dataset_index in range(self.number_of_datasets):
for row_number in range(start_frame, end_frame):
column_name = '%s_%s' % (field_name, dataset_index)
# Stop if any of the data sets are missing the frame
try:
result_data_table[row_number][column_name] = \
self.data_list[dataset_index][row_number][field_name]
except IndexError:
self.messages.append("Couldn't find frame data for row %d "
"for %s" % (row_number, self.names_list[dataset_index]))
break
return result_table_description, result_data_table
def GetOrdering(self, table_description):
""" Creates a list of column names, ordered alphabetically except for the
frame_number column which always will be the first column.
Args:
table_description: A dictionary of column definitions as defined by the
gviz_api.DataTable documentation.
Returns:
A list of column names, where frame_number is the first and the
remaining columns are sorted alphabetically.
"""
# The JSON data representation generated from gviz_api.DataTable.ToJSon()
# must have frame_number as its first column in order for the chart to
# use it as it's X-axis value series.
# gviz_api.DataTable orders the columns by name by default, which will
# be incorrect if we have column names that are sorted before frame_number
# in our data table.
columns_ordering = ['frame_number']
# add all other columns:
for column in sorted(table_description.keys()):
if column != 'frame_number':
columns_ordering.append(column)
return columns_ordering
def CreateConfigurationTable(self, configurations):
""" Combines multiple test data configurations for display.
Args:
configurations: List of one ore more configurations. Each configuration
is required to be a list of dictionaries with two keys: 'name' and
'value'.
Example of a single configuration:
[
{'name': 'name', 'value': 'VP8 software'},
{'name': 'test_number', 'value': '0'},
{'name': 'input_filename', 'value': 'foreman_cif.yuv'},
]
Returns:
A tuple containing:
- a dictionary describing the columns in the configuration table to be
displayed. All columns will have string as data type.
Example:
{
'name': 'string',
'test_number': 'string',
'input_filename': 'string',
}
- a list containing dictionaries (one per configuration) with the
configuration column names mapped to the value for each test run:
Example matching the columns above:
[
{'name': 'VP8 software',
'test_number': '12',
'input_filename': 'foreman_cif.yuv' },
{'name': 'VP8 hardware',
'test_number': '5',
'input_filename': 'foreman_cif.yuv' },
]
"""
result_description = {}
result_data = []
for configuration in configurations:
data = {}
result_data.append(data)
for dict in configuration:
name = dict['name']
value = dict['value']
result_description[name] = 'string'
data[name] = value
return result_description, result_data
| __author__ = 'kjellander@webrtc.org (Henrik Kjellander)'
class Datahelper(object):
"""
Helper class for managing table data.
This class does not verify the consistency of the data tables sent into it.
"""
def __init__(self, data_list, table_description, names_list, messages):
""" Initializes the DataHelper with data.
Args:
data_list: List of one or more data lists in the format that the
Google Visualization Python API expects (list of dictionaries, one
per row of data). See the gviz_api.DataTable documentation for more
info.
table_description: dictionary describing the data types of all
columns in the data lists, as defined in the gviz_api.DataTable
documentation.
names_list: List of strings of what we're going to name the data
columns after. Usually different runs of data collection.
messages: List of strings we might append error messages to.
"""
self.data_list = data_list
self.table_description = table_description
self.names_list = names_list
self.messages = messages
self.number_of_datasets = len(data_list)
self.number_of_frames = len(data_list[0])
def create_data(self, field_name, start_frame=0, end_frame=0):
""" Creates a data structure for a specified data field.
Creates a data structure (data type description dictionary and a list
of data dictionaries) to be used with the Google Visualization Python
API. The frame_number column is always present and one column per data
set is added and its field name is suffixed by _N where N is the number
of the data set (0, 1, 2...)
Args:
field_name: String name of the field, must be present in the data
structure this DataHelper was created with.
start_frame: Frame number to start at (zero indexed). Default: 0.
end_frame: Frame number to be the last frame. If zero all frames
will be included. Default: 0.
Returns:
A tuple containing:
- a dictionary describing the columns in the data result_data_table below.
This description uses the name for each data set specified by
names_list.
Example with two data sets named 'Foreman' and 'Crew':
{
'frame_number': ('number', 'Frame number'),
'ssim_0': ('number', 'Foreman'),
'ssim_1': ('number', 'Crew'),
}
- a list containing dictionaries (one per row) with the frame_number
column and one column of the specified field_name column per data
set.
Example with two data sets named 'Foreman' and 'Crew':
[
{'frame_number': 0, 'ssim_0': 0.98, 'ssim_1': 0.77 },
{'frame_number': 1, 'ssim_0': 0.81, 'ssim_1': 0.53 },
]
"""
result_table_description = {'frame_number': ('string', 'Frame number')}
for dataset_index in range(self.number_of_datasets):
column_name = '%s_%s' % (field_name, dataset_index)
column_type = self.table_description[field_name][0]
column_description = self.names_list[dataset_index]
result_table_description[column_name] = (column_type, column_description)
result_data_table = []
for source_row in self.data_list[0]:
row_dict = {'frame_number': source_row['frame_number']}
result_data_table.append(row_dict)
if end_frame == 0:
end_frame = self.number_of_frames
for dataset_index in range(self.number_of_datasets):
for row_number in range(start_frame, end_frame):
column_name = '%s_%s' % (field_name, dataset_index)
try:
result_data_table[row_number][column_name] = self.data_list[dataset_index][row_number][field_name]
except IndexError:
self.messages.append("Couldn't find frame data for row %d for %s" % (row_number, self.names_list[dataset_index]))
break
return (result_table_description, result_data_table)
def get_ordering(self, table_description):
""" Creates a list of column names, ordered alphabetically except for the
frame_number column which always will be the first column.
Args:
table_description: A dictionary of column definitions as defined by the
gviz_api.DataTable documentation.
Returns:
A list of column names, where frame_number is the first and the
remaining columns are sorted alphabetically.
"""
columns_ordering = ['frame_number']
for column in sorted(table_description.keys()):
if column != 'frame_number':
columns_ordering.append(column)
return columns_ordering
def create_configuration_table(self, configurations):
""" Combines multiple test data configurations for display.
Args:
configurations: List of one ore more configurations. Each configuration
is required to be a list of dictionaries with two keys: 'name' and
'value'.
Example of a single configuration:
[
{'name': 'name', 'value': 'VP8 software'},
{'name': 'test_number', 'value': '0'},
{'name': 'input_filename', 'value': 'foreman_cif.yuv'},
]
Returns:
A tuple containing:
- a dictionary describing the columns in the configuration table to be
displayed. All columns will have string as data type.
Example:
{
'name': 'string',
'test_number': 'string',
'input_filename': 'string',
}
- a list containing dictionaries (one per configuration) with the
configuration column names mapped to the value for each test run:
Example matching the columns above:
[
{'name': 'VP8 software',
'test_number': '12',
'input_filename': 'foreman_cif.yuv' },
{'name': 'VP8 hardware',
'test_number': '5',
'input_filename': 'foreman_cif.yuv' },
]
"""
result_description = {}
result_data = []
for configuration in configurations:
data = {}
result_data.append(data)
for dict in configuration:
name = dict['name']
value = dict['value']
result_description[name] = 'string'
data[name] = value
return (result_description, result_data) |
# 399-evaluate-division.py
#
# Copyright (C) 2019 Sang-Kil Park <likejazz@gmail.com>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
# Make bidirectional skeleton graph.
graph = {e[0]: [] for e in equations}
graph.update({e[1]: [] for e in equations})
for k, v in enumerate(equations):
graph[v[0]].append({v[1]: values[k]})
graph[v[1]].append({v[0]: 1 / values[k]})
answers = []
def dfs(fr, to, answer) -> bool:
if fr not in graph:
return False
if fr == to:
answers.append(answer)
return True
# Calculate multiplication via graph order.
while graph[fr]:
to_list = graph[fr].pop()
key = list(to_list.keys())[0]
answer *= to_list[key]
if dfs(key, to, answer):
return True
answer /= to_list[key]
return False
for q in queries:
graph_backup = copy.deepcopy(graph)
# Start dfs to find two variables given.
if not dfs(q[0], q[1], answer=1):
answers.append(-1)
graph = graph_backup
return answers
| class Solution:
def calc_equation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph = {e[0]: [] for e in equations}
graph.update({e[1]: [] for e in equations})
for (k, v) in enumerate(equations):
graph[v[0]].append({v[1]: values[k]})
graph[v[1]].append({v[0]: 1 / values[k]})
answers = []
def dfs(fr, to, answer) -> bool:
if fr not in graph:
return False
if fr == to:
answers.append(answer)
return True
while graph[fr]:
to_list = graph[fr].pop()
key = list(to_list.keys())[0]
answer *= to_list[key]
if dfs(key, to, answer):
return True
answer /= to_list[key]
return False
for q in queries:
graph_backup = copy.deepcopy(graph)
if not dfs(q[0], q[1], answer=1):
answers.append(-1)
graph = graph_backup
return answers |
def a_kv(n):
return n*n*(-1)**n
def sumkv(n):
return sum(map(a_kv, range(1, n+1)))
def mysum(n):
if (n % 2) == 0:
k = n / 2
print(2*k*k+k)
else:
k = (n+1) / 2
print(-2*k*k+k)
print(sumkv(1))
print(sumkv(2))
print(sumkv(3))
print(sumkv(4))
mysum(1)
mysum(2)
mysum(3)
mysum(4)
| def a_kv(n):
return n * n * (-1) ** n
def sumkv(n):
return sum(map(a_kv, range(1, n + 1)))
def mysum(n):
if n % 2 == 0:
k = n / 2
print(2 * k * k + k)
else:
k = (n + 1) / 2
print(-2 * k * k + k)
print(sumkv(1))
print(sumkv(2))
print(sumkv(3))
print(sumkv(4))
mysum(1)
mysum(2)
mysum(3)
mysum(4) |
"Utilities for generating starlark source code"
def _to_list_attr(list, indent_count = 0, indent_size = 4, quote_value = True):
if not list:
return "[]"
tab = " " * indent_size
indent = tab * indent_count
result = "["
for v in list:
val = "\"{}\"".format(v) if quote_value else v
result += "\n%s%s%s," % (indent, tab, val)
result += "\n%s]" % indent
return result
def _to_dict_attr(dict, indent_count = 0, indent_size = 4, quote_key = True, quote_value = True):
if not len(dict):
return "{}"
tab = " " * indent_size
indent = tab * indent_count
result = "{"
for k, v in dict.items():
key = "\"{}\"".format(k) if quote_key else k
val = "\"{}\"".format(v) if quote_value else v
result += "\n%s%s%s: %s," % (indent, tab, key, val)
result += "\n%s}" % indent
return result
def _to_dict_list_attr(dict, indent_count = 0, indent_size = 4, quote_key = True):
if not len(dict):
return "{}"
tab = " " * indent_size
indent = tab * indent_count
result = "{"
for k, v in dict.items():
key = "\"{}\"".format(k) if quote_key else k
result += "\n%s%s%s: %s," % (indent, tab, key, v)
result += "\n%s}" % indent
return result
starlark_codegen_utils = struct(
to_list_attr = _to_list_attr,
to_dict_attr = _to_dict_attr,
to_dict_list_attr = _to_dict_list_attr,
)
| """Utilities for generating starlark source code"""
def _to_list_attr(list, indent_count=0, indent_size=4, quote_value=True):
if not list:
return '[]'
tab = ' ' * indent_size
indent = tab * indent_count
result = '['
for v in list:
val = '"{}"'.format(v) if quote_value else v
result += '\n%s%s%s,' % (indent, tab, val)
result += '\n%s]' % indent
return result
def _to_dict_attr(dict, indent_count=0, indent_size=4, quote_key=True, quote_value=True):
if not len(dict):
return '{}'
tab = ' ' * indent_size
indent = tab * indent_count
result = '{'
for (k, v) in dict.items():
key = '"{}"'.format(k) if quote_key else k
val = '"{}"'.format(v) if quote_value else v
result += '\n%s%s%s: %s,' % (indent, tab, key, val)
result += '\n%s}' % indent
return result
def _to_dict_list_attr(dict, indent_count=0, indent_size=4, quote_key=True):
if not len(dict):
return '{}'
tab = ' ' * indent_size
indent = tab * indent_count
result = '{'
for (k, v) in dict.items():
key = '"{}"'.format(k) if quote_key else k
result += '\n%s%s%s: %s,' % (indent, tab, key, v)
result += '\n%s}' % indent
return result
starlark_codegen_utils = struct(to_list_attr=_to_list_attr, to_dict_attr=_to_dict_attr, to_dict_list_attr=_to_dict_list_attr) |
"""
File: largest_digit.py
Name: Sharlene Chen
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_largest_digit(281)) # 8
print(find_largest_digit(6)) # 6
print(find_largest_digit(-111)) # 1
print(find_largest_digit(-9453)) # 9
def find_largest_digit(n):
"""
:param n: the number to be processed and compared with
:return: the largest digit in the number
"""
num = abs(n)
initial_largest_digit = num % 10 # set largest digit to the last digit of the number
return helper(num, initial_largest_digit)
def helper(num,largest_digit):
"""
This is a helper function that helps find the largest digit with extra variables to assist
calculation. The calculation loops through the number by dividing it by 10 repeatedly to
separate out each digit, then compares recursively to find the largest digit.
:param num: the number to be checked
:param largest_digit: the current largest digit
:return: the most recent largest digit
"""
if num == 0:
return largest_digit
else:
last_digit = int(num % 10) #compare from the last digit
num = int((num - last_digit) / 10)
if last_digit >= largest_digit:
return helper(num,last_digit)
else:
return helper(num,largest_digit)
if __name__ == '__main__':
main()
| """
File: largest_digit.py
Name: Sharlene Chen
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345))
print(find_largest_digit(281))
print(find_largest_digit(6))
print(find_largest_digit(-111))
print(find_largest_digit(-9453))
def find_largest_digit(n):
"""
:param n: the number to be processed and compared with
:return: the largest digit in the number
"""
num = abs(n)
initial_largest_digit = num % 10
return helper(num, initial_largest_digit)
def helper(num, largest_digit):
"""
This is a helper function that helps find the largest digit with extra variables to assist
calculation. The calculation loops through the number by dividing it by 10 repeatedly to
separate out each digit, then compares recursively to find the largest digit.
:param num: the number to be checked
:param largest_digit: the current largest digit
:return: the most recent largest digit
"""
if num == 0:
return largest_digit
else:
last_digit = int(num % 10)
num = int((num - last_digit) / 10)
if last_digit >= largest_digit:
return helper(num, last_digit)
else:
return helper(num, largest_digit)
if __name__ == '__main__':
main() |
"""
Project:
Author:
"""
def is_object_has_method(obj, method_name):
assert isinstance(method_name, str)
maybe_method = getattr(obj, method_name, None)
return callable(maybe_method)
__all__ = ['is_object_has_method']
| """
Project:
Author:
"""
def is_object_has_method(obj, method_name):
assert isinstance(method_name, str)
maybe_method = getattr(obj, method_name, None)
return callable(maybe_method)
__all__ = ['is_object_has_method'] |
def init():
global originlist, ellipselist, adjmatrix, adjcoordinates, valcount,num,dim,iterate, primA
adjmatrix = [] # the adjmatrix is the list of edges that being created
adjcoordinates = []; # the adjval gives the dimension coordinates (for plotting for the nth point)
valcount = -1; # valcount keeps the number of the value of the point being added to the adjacency tree
primA = [] #primA stores the terms for the primary axis. The one to traverse along on the first iteration
iterate = 100 #Number of slices to cover the ellipsoid in nD space
num = 0;
dim = 0;
| def init():
global originlist, ellipselist, adjmatrix, adjcoordinates, valcount, num, dim, iterate, primA
adjmatrix = []
adjcoordinates = []
valcount = -1
prim_a = []
iterate = 100
num = 0
dim = 0 |
def add_numbers(numbers):
result = 0
for i in numbers:
result += i
#print("number =", i)
return result
result = add_numbers([1, 2, 30, 4, 5, 9])
print(result)
| def add_numbers(numbers):
result = 0
for i in numbers:
result += i
return result
result = add_numbers([1, 2, 30, 4, 5, 9])
print(result) |
target_number = 0
increment = 0
while target_number == 0:
sum1 = 0
increment += 1
for j in range(1, increment):
sum1 += j
factors = 0
for k in range(1, int(sum1**.5)+1):
if sum1 % k == 0:
factors += 1
factors = factors * 2
if factors > 500:
target_number = sum1
print(target_number) # 76576500 | target_number = 0
increment = 0
while target_number == 0:
sum1 = 0
increment += 1
for j in range(1, increment):
sum1 += j
factors = 0
for k in range(1, int(sum1 ** 0.5) + 1):
if sum1 % k == 0:
factors += 1
factors = factors * 2
if factors > 500:
target_number = sum1
print(target_number) |
# Jun - Dangerous Hide-and-Seek : Neglected Rocky Mountain (931000001)
if "exp1=1" not in sm.getQRValue(23007):
sm.sendNext("Eep! You found me.")
sm.sendSay("Eh, I wanted to go further into the wagon, but my head wouldn't fit.")
sm.sendSay("Did you find Ulrika and Von yet? Von is really, really good at hiding.\r\n\r\n\r\n\r\n#fUI/UIWindow2.img/QuestIcon/8/0# 5 exp")
sm.giveExp(5)
sm.addQRValue(23007, "exp1=1")
else:
sm.sendNext("Did you find Ulrika and Von yet? Von is really, really good at hiding.")
| if 'exp1=1' not in sm.getQRValue(23007):
sm.sendNext('Eep! You found me.')
sm.sendSay("Eh, I wanted to go further into the wagon, but my head wouldn't fit.")
sm.sendSay('Did you find Ulrika and Von yet? Von is really, really good at hiding.\r\n\r\n\r\n\r\n#fUI/UIWindow2.img/QuestIcon/8/0# 5 exp')
sm.giveExp(5)
sm.addQRValue(23007, 'exp1=1')
else:
sm.sendNext('Did you find Ulrika and Von yet? Von is really, really good at hiding.') |
# Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
print("Insert your name")
name = input()
print("Insert yor age")
age_str = input()
age_int = int(age_str)
print(f"{name}, you will be {age_int+100} years old in 100 years") | print('Insert your name')
name = input()
print('Insert yor age')
age_str = input()
age_int = int(age_str)
print(f'{name}, you will be {age_int + 100} years old in 100 years') |
""" Dependencies that are needed for jinja rules """
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("//tools:defs.bzl", "clean_dep")
def jinja_deps():
maybe(
http_archive,
name = "markupsafe_archive",
urls = [
"https://files.pythonhosted.org/packages/bf/10/ff66fea6d1788c458663a84d88787bae15d45daa16f6b3ef33322a51fc7e/MarkupSafe-2.0.1.tar.gz",
],
strip_prefix = "MarkupSafe-2.0.1",
build_file = clean_dep("//third_party:markupsafe.BUILD"),
sha256 = "594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a",
)
maybe(
http_archive,
name = "jinja_archive",
url = "https://files.pythonhosted.org/packages/39/11/8076571afd97303dfeb6e466f27187ca4970918d4b36d5326725514d3ed3/Jinja2-3.0.1.tar.gz",
sha256 = "703f484b47a6af502e743c9122595cc812b0271f661722403114f71a79d0f5a4",
build_file = clean_dep("//third_party:jinja.BUILD"),
strip_prefix = "Jinja2-3.0.1",
)
| """ Dependencies that are needed for jinja rules """
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('//tools:defs.bzl', 'clean_dep')
def jinja_deps():
maybe(http_archive, name='markupsafe_archive', urls=['https://files.pythonhosted.org/packages/bf/10/ff66fea6d1788c458663a84d88787bae15d45daa16f6b3ef33322a51fc7e/MarkupSafe-2.0.1.tar.gz'], strip_prefix='MarkupSafe-2.0.1', build_file=clean_dep('//third_party:markupsafe.BUILD'), sha256='594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a')
maybe(http_archive, name='jinja_archive', url='https://files.pythonhosted.org/packages/39/11/8076571afd97303dfeb6e466f27187ca4970918d4b36d5326725514d3ed3/Jinja2-3.0.1.tar.gz', sha256='703f484b47a6af502e743c9122595cc812b0271f661722403114f71a79d0f5a4', build_file=clean_dep('//third_party:jinja.BUILD'), strip_prefix='Jinja2-3.0.1') |
def find_player(matrix):
for r in range(len(matrix)):
for c in range(len(matrix)):
if matrix[r][c] == 'P':
return r, c
def check_valid_cell(size, r, c):
return 0 <= r < size and 0 <= c < size
string = input()
size = int(input())
field = [list(input()) for _ in range(size)]
m = int(input())
pr, pc = find_player(field)
deltas = {'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1)}
for _ in range(m):
command = input()
next_r, next_c = pr + deltas[command][0], pc + deltas[command][1]
if check_valid_cell(size, next_r, next_c):
if field[next_r][next_c] != '-':
string += field[next_r][next_c]
field[next_r][next_c] = 'P'
field[pr][pc] = '-'
pr, pc = next_r, next_c
else:
if len(string) > 0:
string = string[:-1]
print(string)
for row in field:
print(''.join(row))
| def find_player(matrix):
for r in range(len(matrix)):
for c in range(len(matrix)):
if matrix[r][c] == 'P':
return (r, c)
def check_valid_cell(size, r, c):
return 0 <= r < size and 0 <= c < size
string = input()
size = int(input())
field = [list(input()) for _ in range(size)]
m = int(input())
(pr, pc) = find_player(field)
deltas = {'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1)}
for _ in range(m):
command = input()
(next_r, next_c) = (pr + deltas[command][0], pc + deltas[command][1])
if check_valid_cell(size, next_r, next_c):
if field[next_r][next_c] != '-':
string += field[next_r][next_c]
field[next_r][next_c] = 'P'
field[pr][pc] = '-'
(pr, pc) = (next_r, next_c)
elif len(string) > 0:
string = string[:-1]
print(string)
for row in field:
print(''.join(row)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.