content
stringlengths 7
1.05M
|
---|
"""
Copyright 2020 Vadim Kholodilo <vadimkholodilo@gmail.com>, Iulia Durova <yulianna199820@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
# Class to represent a graph
# This class must have the following interface:
# Constructor creates an empty graph, no parameters.
# addVertex(value) adds vertex to the graph
# addEdge(v1, v2, weight) adds edge from v1 to v2 with a certain weight
# getWeight(v1, v2) returns weight of an edge between v1 and v2, if the edge does not exist returns -1
# Dijkstra algorithm will be added in future
|
"""
C 1.19
---------------------------------
Problem Statement : Demonstrate how to use Python’s list comprehension syntax to produce
the list [ a , b , c , ..., z ], but without having to type all 26 such
characters literally.
Author : Saurabh
"""
print([chr(x + 97) for x in range(26)])
|
"""lesson6/solution_simple_functions.py
Contains solutions for simple functions.
"""
# Exercise 1: Write a function that prints your name and try calling it.
# Work in this file and not in the Python shell. Defining functions in
# a Python shell is difficult. Remember to name your function something
# that indicates its purpose.
def print_my_name():
print("Vinay Mayar")
print_my_name()
# Exercise 2: Write a function that uses your function from Exercise 1
# to print your name 10 times.
def print_my_name_ten_times():
for ctr in range(10):
print_my_name()
print_my_name_ten_times()
|
# Link class
class Link:
## Constructor ##
def __init__(self, text = "None", url = "None", status_code = 000): # Not the keyword 'None' so it will still print something
# Dictionary of URL-related content
self.text = text
self.url = url
self.status_code = status_code
# Trims the inside of a string (removing extra whitespace between words)
def trim_inner(self, text):
return " ".join( [string.strip() for string in text.split()] ) # Separate the indiv. words and trim them individually
## OVERLOADS ##
# String representation of the 'Link' class
def __str__(self):
# Format: status code, hyperlinked text, then url (CSV)
text = self.trim_inner(self.text) # Trim internal whitespace;
if not text: # If the string is blank,
text = "N/A" # Give it some text
return f"{self.status_code}, {text}, {self.url}"
# Relational Operators, compared by status code for sorting
# > (less than)
def __lt__(self, other):
return self.status_code < other.status_code
# >= (less than or equal to)
def __le__(self, other):
return self.status_code <= other.status_code
# == (is equal to)
def __eq__(self, other):
return self.staus_code == other.status_code
# != (is not equal to)
def __ne__(self, other):
return self.status_code != other.status_code
# < (greater than)
def __gt__(self, other):
return self.status_code > other.status_code
# <= (greater than or equal to)
def __ge__(self, other):
return self.status_code >= other.status_code
# End of Link class
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class Subscription(object):
def __init__(self, consumerGroupId=None, endPoint=None, messageInvisibleTimeInSeconds=None, subscriptionType=None, tags=None, dlqEnable=None, maxRetryTimes=None, createTime=None, lastUpdateTime=None, consumerNumbers=None):
"""
:param consumerGroupId: (Optional) consumerGroupId
:param endPoint: (Optional) endPoint
:param messageInvisibleTimeInSeconds: (Optional) messageInvisibleTimeInSeconds
:param subscriptionType: (Optional) subscriptionType
:param tags: (Optional) tags
:param dlqEnable: (Optional) 是否开启死信队列
:param maxRetryTimes: (Optional) 最大重试次数
:param createTime: (Optional) 创建时间
:param lastUpdateTime: (Optional) 最后更新时间
:param consumerNumbers: (Optional) 在线consumer个数
"""
self.consumerGroupId = consumerGroupId
self.endPoint = endPoint
self.messageInvisibleTimeInSeconds = messageInvisibleTimeInSeconds
self.subscriptionType = subscriptionType
self.tags = tags
self.dlqEnable = dlqEnable
self.maxRetryTimes = maxRetryTimes
self.createTime = createTime
self.lastUpdateTime = lastUpdateTime
self.consumerNumbers = consumerNumbers
|
# -*- coding: utf-8 -*-
"""Manages custom event formatter helpers."""
class FormattersManager(object):
"""Custom event formatter helpers manager."""
_custom_formatter_helpers = {}
@classmethod
def GetEventFormatterHelper(cls, identifier):
"""Retrieves a custom event formatter helper.
Args:
identifier (str): identifier.
Returns:
CustomEventFormatterHelper: custom event formatter or None if not
available.
"""
identifier = identifier.lower()
return cls._custom_formatter_helpers.get(identifier)
@classmethod
def RegisterEventFormatterHelper(cls, formatter_helper_class):
"""Registers a custom event formatter helper.
The custom event formatter helpers are identified based on their lower
case identifier.
Args:
formatter_helper_class (type): class of the custom event formatter helper.
Raises:
KeyError: if a custom formatter helper is already set for the
corresponding identifier.
"""
identifier = formatter_helper_class.IDENTIFIER.lower()
if identifier in cls._custom_formatter_helpers:
raise KeyError((
'Custom event formatter helper already set for identifier: '
'{0:s}.').format(formatter_helper_class.IDENTIFIER))
cls._custom_formatter_helpers[identifier] = formatter_helper_class()
@classmethod
def RegisterEventFormatterHelpers(cls, formatter_helper_classes):
"""Registers custom event formatter helpers.
The formatter classes are identified based on their lower case data type.
Args:
formatter_helper_classes (list[type]): classes of the custom event
formatter helpers.
Raises:
KeyError: if a custom formatter helper is already set for the
corresponding data type.
"""
for formatter_helper_class in formatter_helper_classes:
cls.RegisterEventFormatterHelper(formatter_helper_class)
|
template_open = '{{#ctx.payload.aggregations.result.hits.hits.0._source}}'
template_close = template_open.replace('{{#','{{/')
kibana_url = (
"{{ctx.metadata.kibana_url}}/app/kibana#/discover?"
"_a=(columns:!(_source),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,"
"index:'metricbeat-*',key:query,negate:!f,type:custom,value:''),"
"query:(bool:(must:!((regexp:(kubernetes.pod.name:'{{ctx.metadata.regex}}')),"
"(match:(metricset.name:'state_pod')),"
"(match:(kubernetes.namespace:{{ctx.metadata.namespace}}))))))),"
"index:'metricbeat-*',"
"interval:auto,query:(language:lucene,query:''),"
"regexp:(language:lucene,query:'kubernetes.pod.name:test-nginx-%5B%5E-%5D%20-%5B%5E-%5D%20'),"
"sort:!('@timestamp',desc),time:(from:now%2FM,mode:quick,to:now%2FM))"
"&_g=(refreshInterval:(display:Off,pause:!f,value:0),"
"time:(from:now-15m,mode:quick,to:now))"
)
watch_url = "{{ctx.metadata.kibana_url}}/app/management/insightsAndAlerting/watcher/watches/watch/{{ctx.metadata.name}}/status"
slack_alert_template = "{template_open}*<{kibana_url}|{{{{ctx.metadata.name}}}}>* has `{{{{ctx.payload.aggregations.pods.value}}}}` not ready pod(s) <{watch_url}|[ack]>{{{{#ctx.metadata.docs}}}} <{{{{.}}}}|[docs]>{{{{/ctx.metadata.docs}}}}{template_close}".format(**locals())
email_alert_template = "{template_open}<a href=\"{kibana_url}\">{{{{ctx.metadata.name}}}}</a> has {{{{ctx.payload.aggregations.pods.value}}}} not ready pod(s) <a href=\"{watch_url}\">[ack]</a>{{{{#ctx.metadata.docs}}}} <a href=\"{{{{.}}}}\">[docs]</a>{{{{/ctx.metadata.docs}}}}{template_close}".format(**locals())
k8s_template = {
"metadata": {
"name": "",
"namespace": "",
"regex": "",
"kibana_url": "",
"kibana_dashboard": "",
"docs": "",
"xpack" : {
"type" : "json"
},
},
"trigger": {
"schedule": {
"interval": ""
}
},
"input": {
"search": {
"request": {
"search_type": "query_then_fetch",
"indices": [
"metricbeat-*"
],
"rest_total_hits_as_int": True,
"body": {
"aggs": {
"result": {
"top_hits": {
"size": 1
}
},
"pods": {
"cardinality": {
"field": "kubernetes.pod.name"
}
},
"not_ready": {
"terms": {
"field": "kubernetes.pod.name",
"min_doc_count": 12,
"size": 100
}
}
},
"query": {
"bool": {
"must_not": [],
"must": [],
"filter": [
{
"range": {
"@timestamp": {
"gte": "now-{{ctx.metadata.window}}"
}
}
}
]
}
}
}
}
}
},
"condition": {},
"actions": {
"email_admin": {
"throttle_period_in_millis": 300000,
"email": {
"profile": "standard",
"subject": "{{#ctx.payload.aggregations.result.hits.hits.0._source}}{{ctx.metadata.name}} has {{ctx.payload.aggregations.pods.value}} not ready pod(s){{/ctx.payload.aggregations.result.hits.hits.0._source}}",
"body": {
"html": email_alert_template
}
}
},
"notify-slack": {
"throttle_period_in_millis": 300000,
"slack": {
"message": {
"text": slack_alert_template
}
}
}
}
}
metricbeat_template = {
"metadata": {
"window": "300s",
"subject": "No metricbeat data has been recieved in the last 5 minutes!"
},
"trigger": {
"schedule": {
"interval": "60s"
}
},
"input": {
"search": {
"request": {
"search_type": "query_then_fetch",
"indices": [
"metricbeat-*"
],
"rest_total_hits_as_int": True,
"body": {
"query": {
"bool": {
"must": [
{
"match": {
"metricset.name": "state_pod"
}
}
],
"filter": [
{
"range": {
"@timestamp": {
"gte": "now-{{ctx.metadata.window}}"
}
}
}
]
}
}
}
}
}
},
"condition": {
"compare": {
"ctx.payload.hits.total": {
"eq": 0
}
}
},
"actions": {
"email_admin": {
"throttle_period_in_millis": 300000,
"email": {
"profile": "standard",
"subject": "{{ctx.metadata.subject}}",
"body": {
"text": "{{ctx.metadata.message}}"
}
}
},
"notify-slack": {
"throttle_period_in_millis": 300000,
"slack": {
"message": {
"text": "{{ctx.metadata.message}}"
}
}
}
}
}
|
c = get_config()
#Export all the notebooks in the current directory to the sphinx_howto format.
c.NbConvertApp.notebooks = ['*.ipynb']
c.NbConvertApp.export_format = 'latex'
c.NbConvertApp.postprocessor_class = 'PDF'
c.Exporter.template_file = 'custom_article.tplx'
|
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[List[int]]:
complement = {}
out = []
for i,n in enumerate(nums):
complement[target-n] = i
for i,n in enumerate(nums):
idx = complement.get(n, None)
if idx != None and idx != i:
out.append([nums[idx], nums[i]])
return out
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
nums.sort()
out = []
if set(nums) == {0}:
return [[0,0,0]]
i = 0
while len(nums) >= 3:
l_twosum = self.twoSum(nums[1:], -nums[0])
if l_twosum != None:
for l in l_twosum:
l.append(nums[0])
out.append(l)
nums.pop(0)
for i,l in enumerate(out):
out[i] = sorted(l)
out = list(map(list, set(map(tuple, out))))
return out
|
#To solve Rat in a maze problem using backtracking
#initializing the size of the maze and soution matrix
N = 4
solution_maze = [ [ 0 for j in range(N) ] for i in range(N) ]
def is_safe(maze, x, y ):
'''A utility function to check if x, y is valid
return true if it is valid move,
return false otherwise
'''
if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1:
return True
return False
def check_if_solution_exists(maze):
if solve_maze(maze) == False:
print("Solution doesn't exist");
return False
# recursive function to solve rat in a maze problem
def solve_maze(maze, x=0,y=0):
'''
This function will make several recursive calls
until we reach to some finding, if we reach to destination
following asafe path, then it prints the solution and return true,
will return false otherwise.
'''
# if (x, y is goal) return True
if x == N - 1 and y == N - 1:
solution_maze[x][y] = 1
print("solution:", solution_maze)
return True
# check if the move is valid
if is_safe(maze, x, y) == True:
# mark x, y as part of solution path
# for(0,0) it sets up 1 in solution maze
solution_maze[x][y] = 1
# Move forward in x direction (recursive call)
if solve_maze(maze, x + 1, y) == True:
return True
# Move down in y direction if moving in x direction is not fruitful
#(recursive call)
if solve_maze(maze, x, y + 1) == True:
return True
#no option for rat to move, backtrack
solution_maze[x][y] = 0
return False
# Driver program to test above function
if __name__ == "__main__":
maze = [ [1, 0, 0, 0],
[1, 1, 0, 1],
[1, 0, 0, 0],
[1, 1, 1, 1] ]
check_if_solution_exists(maze)
|
for i in range(2):
print(i) # print 0 then 1
for i in range(4,6):
print (i) # print 4 then 5
"""
Explanation:
If only single argument is passed to the range method,
Python considers this argument as the end of the range and the default start value of range is 0.
So, it will print all the numbers starting from 0 and before the supplied argument.
For the second for loop the starting value is explicitly supplied as 4 and ending is 5.
""" |
# called concatenation sometimes..
str1 = 'abra, '
str2 = 'cadabra. '
str3 = 'i wanna reach out and grab ya.'
combo = str1 + str1 + str2 + str3
# you probably don't remember the song.
print(combo)
# you can also do it this way
print('I heat up', '\n', "I can't cool down", '\n', 'my life is spinning', '\n', 'round and round')
# notice the change in single and double quotes. hopefully the change makes sense.
print('not sure why the space for lines 2,3,4 above.', '\n', "i guess there's more to learn... :)")
|
#!/usr/bin/env python3
"""Initialize.
Turn full names into initials.
Source:
https://edabit.com/challenge/ANsubgd5zPGxov3u8
"""
def __initialize(name: str, period: bool=False) -> str:
"""Turn full name string into a initials string.
Private function used by initialize.
Arguments:
name {[str]} -- Full name to be initialized.
Keyword Arguments:
period {bool} -- Include periods in initials (default: {False})
Returns:
[str] -- Initials string.
"""
if period:
return f"{'.'.join([n[0] for n in name.split(' ')])}."
return ''.join([n[0] for n in name.split(' ')])
def initialize(names: list, **kwargs) ->list:
"""Turn a list of full names into a list of initials.
Arguments:
names {list} -- List of full names, with a space between each name.
Raises:
TypeError -- Check for names is a list.
Returns:
list -- All names initialized.
"""
if isinstance(names, list):
return [__initialize(name.strip(), **kwargs) for name in names if len(name) > 2 and ' ' in name]
else:
raise TypeError('Parameter \'names\' is not a list.')
def main():
"""Run sample initialize function."""
print(initialize(['Peter Parker', 'Steve Rogers', 'Tony Stark']))
print(initialize(
['Bruce Wayne', 'Clark Kent', 'Diana Prince'], period=True))
if __name__ == "__main__":
main()
|
#Funções:__________________________________________________________________
def cadastro():
resp=input(print("Deseja cadastrar alguém?"))
if resp.upper()!= "N":
while resp.upper()!= "N":
arq=open("teste.txt","a")
nome=input(print("Digite seu nome"))
arq.write("Olá"+";"+nome+";")
arq.write("\n")
arq.close()
resp=input(print("Deseja continuar?"))
def pesquisa():
pesquisa="s"
while pesquisa!="n" and pesquisa!="N" and pesquisa!= "Não" and pesquisa!="não":
ler=open("teste.txt","r")
linha="a"
resultado= list(range(3))
pesquisa=input(print("Digite um nome"))
while linha!="":
linha=ler.readline()
if linha!="":
resultado=linha.split(';')
if resultado[1]==pesquisa:
print(resultado[0],",",resultado[1],resultado[2])
ler.close()
pesquisa=input(print("Deseja continuar? S/N"))
#Main:____________________________________________________________________
print("Hey")
o="s"
while o.upper()!="N":
cadastro()
pesquisa()
o=input(print("Continuar com o sistema S/N?"))
#[[0 for c in range(3)] for l in range(10)]
|
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
__version__ = "2.11.2"
version = __version__
|
def method1(X, Y):
m = len(X)
n = len(Y)
L = [[None] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
return L[m][n]
def method2(X, Y, m, n):
if m == 0 or n == 0:
return 0
elif X[m - 1] == Y[n - 1]:
return 1 + method2(X, Y, m - 1, n - 1)
else:
return max(method2(X, Y, m, n - 1), method2(X, Y, m - 1, n))
if __name__ == "__main__":
"""
from timeit import timeit
X = "AGGTAB"
Y = "GXTXAYB"
print(timeit(lambda: method1(X, Y), number=10000)) # 0.14817858800233807
print(
timeit(lambda: method2(X, Y, len(X), len(Y)), number=10000)
) # 0.5299446069984697
""" |
def combination(n, r):
r = min(n - r, r)
result = 1
for i in range(n, n - r, -1):
result *= i
for i in range(1, r + 1):
result //= i
return result
N, A, B = map(int, input().split())
v_list = list(map(int, input().split()))
v_list.sort(reverse=True)
mean_max = sum(v_list[:A]) / A
comb = 0
if v_list[0] != v_list[A - 1]:
x = v_list.count(v_list[A - 1])
y = v_list[:A].count(v_list[A - 1])
comb = combination(x, y)
else:
x = v_list.count(v_list[A - 1])
for i in range(A, B + 1):
if v_list[i - 1] == v_list[0]:
comb += combination(x, i)
print("{:.10f}".format(mean_max))
print(comb)
|
variable1 = input('Variable 1:')
variable2 = input('Variable 2:')
variable1, variable2 = variable2, variable1
print(f"Variable 1: {variable1}")
print(f"Variable 2: {variable2}") |
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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.
#
# Build configuration for ctmalloc. This is not a part of the original
# library.
{
'targets': [
{
'target_name': 'ctmalloc_lib',
'type': 'static_library',
'sources': [
'wtf/AsanHooks.cpp',
'wtf/AsanHooks.h',
'wtf/Assertions.h',
'wtf/Atomics.h',
'wtf/BitwiseOperations.h',
'wtf/ByteSwap.h',
'wtf/Compiler.h',
'wtf/config.h',
'wtf/CPU.h',
'wtf/malloc.cpp',
'wtf/PageAllocator.cpp',
'wtf/PageAllocator.h',
'wtf/PartitionAlloc.cpp',
'wtf/PartitionAlloc.h',
'wtf/ProcessID.h',
'wtf/SpinLock.h',
'wtf/WTFExport.h',
],
'defines': [
'CTMALLOC_NDEBUG',
],
'include_dirs': [
'<(src)/third_party/ctmalloc',
],
'all_dependent_settings': {
'defines': [
# We disable debug features of the CtMalloc heap as they are redundant
# given SyzyASan's extensive debug features.
'CTMALLOC_NDEBUG',
],
'include_dirs': [
'<(src)/third_party/ctmalloc',
],
},
},
],
}
|
def main():
# Manage input file
input = open(r"C:\Users\lawht\Desktop\Github\ROSALIND\Bioinformatics Stronghold\Complementing a Stand of DNA\Complementing a Stand of DNA\rosalind_revc.txt","r")
DNA_string = input.readline(); # take first line of input file for counting
# Take in input file of DNA string and print out its reverse complement
print(reverse_complement(DNA_string))
input.close()
# Given: A DNA string s of length at most 1000 bp.
# Return: The reverse complement sc of s.
def reverse_complement(s):
sc = "";
for n in reversed(s):
if n == "A":
sc = sc + "T"
elif n == "T":
sc = sc + "A"
elif n == "C":
sc = sc + "G"
elif n == "G":
sc = sc + "C"
else:
continue
return sc
# Manually call main() on the file load
if __name__ == "__main__":
main() |
"""
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
path = []
if root is None:
return path
stack1 = []
stack2 = []
stack1.append(root)
while stack1:
root = stack1.pop()
stack2.append(root.val)
if root.left is not None:
stack1.append(root.left)
if root.right is not None:
stack1.append(root.right)
while stack2:
path.append(stack2.pop())
return path
|
"""
Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre
todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele
quer ou não continuar a digitar valores.
"""
resposta = 'S'
cont = soma = maior = menor = media = 0
while resposta == 'S':
numero = int(input('Digite um número: '))
cont += 1
soma += numero
if cont == 1:
maior = menor = numero
else:
if numero > maior:
maior = numero
if numero < menor:
menor = numero
resposta = str(input('Quer continuar? [S/N]: ')).strip().upper()[0]
while resposta not in 'SN':
resposta = str(input('Quer continuar? [S/N]: ')).strip().upper()[0]
if resposta == 'N':
resposta = False
print('Finalizando...')
media = soma/cont
print(f'A média entre os valores lidos foi de {media:.2f}.')
print(f'O maior valor digitado foi {maior} e o menor {menor}.')
|
all_591_cities = [
{
"city": "台北市",
"id": "1"
},
{
"city": "新北市",
"id": "3"
},
{
"city": "桃園市",
"id": "6"
},
{
"city": "新竹市",
"id": "4"
},
{
"city": "新竹縣",
"id": "5"
},
{
"city": "基隆市",
"id": "2"
},
{
"city": "宜蘭縣",
"id": "21"
},
{
"city": "台中市",
"id": "8"
},
{
"city": "彰化縣",
"id": "10"
},
{
"city": "苗栗縣",
"id": "7"
},
{
"city": "雲林縣",
"id": "14"
},
{
"city": "南投縣",
"id": "11"
},
{
"city": "高雄市",
"id": "17"
},
{
"city": "台南市",
"id": "15"
},
{
"city": "嘉義市",
"id": "12"
},
{
"city": "屏東縣",
"id": "19"
},
{
"city": "嘉義縣",
"id": "13"
},
{
"city": "花蓮縣",
"id": "23"
},
{
"city": "台東縣",
"id": "22"
},
{
"city": "金門縣",
"id": "25"
},
{
"city": "澎湖縣",
"id": "24"
}
]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def part_1(program):
i = 0
while i < len(program):
opcode, a, b, dest = program[i:i+4]
i += 4
assert opcode in {1, 2, 99}, f'Unexpected opcode: {opcode}'
if opcode == 1:
val = program[a] + program[b]
elif opcode == 2:
val = program[a] * program[b]
elif opcode == 99:
return program
program[dest] = val
def part_2(program, goal):
for noun in range(99):
for verb in range(99):
p = program[:]
p[1] = noun
p[2] = verb
p = part_1(p)
if p[0] == goal:
return noun, verb
if __name__ == '__main__':
with open('input.txt') as f:
program = f.readline()
program = [int(i) for i in program.split(',')]
p_1 = program[:]
p_1[1] = 12
p_1[2] = 2
p = part_1(p_1)
print(f'part 1: {p[0]}')
noun, verb = part_2(program, 19690720)
print(f'part 2: noun={noun}\n\tverb={verb}')
|
# Copyright 2021 Duan-JM, Sun Aries
# 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.
# Note: passing both BUILD_SHARED_LIBS=ON and BUILD_STATIC_LIBS=ON to cmake
# still only builds the shared libraries, so we have to choose one or the
# other. We build shared libraries by default, but this variable can be used
# to switch to static libraries.
OPENCV_SHARED_LIBS = False
OPENCV_TAG = "4.5.0"
OPENCV_SO_VERSION = "4.5" # OPENCV_SO_VERSION need to match OPENCV_TAG
# Note: this determines the order in which the libraries are passed to the
# linker, so if library A depends on library B, library B must come _after_.
# Hence core is at the bottom.
OPENCV_MODULES = [
"calib3d",
"features2d",
"flann",
"highgui",
"video",
"videoio",
"imgcodecs",
"imgproc",
"core",
]
OPENCV_THIRD_PARTY_DEPS = [
"liblibjpeg-turbo.a",
"liblibpng.a",
"liblibprotobuf.a",
"libquirc.a",
"libtegra_hal.a",
"libzlib.a",
"libade.a",
"liblibopenjp2.a"
]
|
# Copyright (C) 2007-2012 Red Hat
# see file 'COPYING' for use and warranty information
#
# policygentool is a tool for the initial generation of SELinux policy
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# 02111-1307 USA
#
#
########################### tmp Template File #############################
te_types="""
type TEMPLATETYPE_rw_t;
files_type(TEMPLATETYPE_rw_t)
"""
te_rules="""
manage_dirs_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)
manage_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)
manage_lnk_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)
"""
########################### Interface File #############################
if_rules="""
########################################
## <summary>
## Search TEMPLATETYPE rw directories.
## </summary>
## <param name="domain">
## <summary>
## Domain allowed access.
## </summary>
## </param>
#
interface(`TEMPLATETYPE_search_rw_dir',`
gen_require(`
type TEMPLATETYPE_rw_t;
')
allow $1 TEMPLATETYPE_rw_t:dir search_dir_perms;
files_search_rw($1)
')
########################################
## <summary>
## Read TEMPLATETYPE rw files.
## </summary>
## <param name="domain">
## <summary>
## Domain allowed access.
## </summary>
## </param>
#
interface(`TEMPLATETYPE_read_rw_files',`
gen_require(`
type TEMPLATETYPE_rw_t;
')
read_files_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)
allow $1 TEMPLATETYPE_rw_t:dir list_dir_perms;
files_search_rw($1)
')
########################################
## <summary>
## Manage TEMPLATETYPE rw files.
## </summary>
## <param name="domain">
## <summary>
## Domain allowed access.
## </summary>
## </param>
#
interface(`TEMPLATETYPE_manage_rw_files',`
gen_require(`
type TEMPLATETYPE_rw_t;
')
manage_files_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)
')
########################################
## <summary>
## Create, read, write, and delete
## TEMPLATETYPE rw dirs.
## </summary>
## <param name="domain">
## <summary>
## Domain allowed access.
## </summary>
## </param>
#
interface(`TEMPLATETYPE_manage_rw_dirs',`
gen_require(`
type TEMPLATETYPE_rw_t;
')
manage_dirs_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)
')
"""
te_stream_rules="""
manage_sock_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)
"""
if_stream_rules="""\
########################################
## <summary>
## Connect to TEMPLATETYPE over a unix stream socket.
## </summary>
## <param name="domain">
## <summary>
## Domain allowed access.
## </summary>
## </param>
#
interface(`TEMPLATETYPE_stream_connect',`
gen_require(`
type TEMPLATETYPE_t, TEMPLATETYPE_rw_t;
')
stream_connect_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_t)
')
"""
if_admin_types="""
type TEMPLATETYPE_rw_t;"""
if_admin_rules="""
files_search_etc($1)
admin_pattern($1, TEMPLATETYPE_rw_t)
"""
########################### File Context ##################################
fc_file="""
FILENAME -- gen_context(system_u:object_r:TEMPLATETYPE_rw_t,s0)
"""
fc_sock_file="""\
FILENAME -s gen_context(system_u:object_r:TEMPLATETYPE_etc_rw_t,s0)
"""
fc_dir="""
FILENAME(/.*)? gen_context(system_u:object_r:TEMPLATETYPE_rw_t,s0)
"""
|
"""
Compartmentalize:
[ ascii art input ]
---------------
| maybe some |
| sort of auxillary |
| drawing program |
|
|
\ /
v
[ lex/parser ] --> [ translater ]
--------- ----------
| grammar | | notes literals|
| to numerical |
| patterns with |
| timestamps |
| and midi meta |
| data |
|
,------------------------'
|
`--> [ sequencer ]
-----------
| do the |
| sequencing |
| duh |
|
|
\ /
v
[ midi sender ]
----------
| communicate to |
| midi external |
"""
|
if __name__ == "__main__":
"""
Pobierz podstawe i wysokosc trojkata i wypisz pole.
"""
print("podaj podstawe i wysokosc trojkata:")
a = int(input())
h = int(input())
print(
"pole trojkata o podstawie ", a, " i wysokosci ", h, " jest rowne ", a * h / 2
)
"""
Pobierz dlugosci bokow prostokata i wypisz pole.
"""
print("podaj dlogosci bokow prostokata:")
a = int(input())
b = int(input())
print("pole prostokata o bokach ", a, " i ", b, " jest rowne ", a * b)
|
#
# 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.
"""Gabbi specific exceptions."""
class GabbiDataLoadError(ValueError):
"""An exception to alert when data streams cannot be loaded."""
pass
class GabbiFormatError(ValueError):
"""An exception to encapsulate poorly formed test data."""
pass
class GabbiSyntaxWarning(SyntaxWarning):
"""A warning about syntax that is not desirable."""
pass
|
logo = """
_____________________
| _________________ |
| | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------.
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
| ___ ___ ___ ___ | | | ______ | || | __ | || | _____ | || | ______ | |
| | 7 | 8 | 9 | | + | | | | .' ___ | | || | / \ | || | |_ _| | || | .' ___ | | |
| |___|___|___| |___| | | | / .' \_| | || | / /\ \ | || | | | | || | / .' \_| | |
| | 4 | 5 | 6 | | - | | | | | | | || | / ____ \ | || | | | _ | || | | | | |
| |___|___|___| |___| | | | \ `.___.'\ | || | _/ / \ \_ | || | _| |__/ | | || | \ `.___.'\ | |
| | 1 | 2 | 3 | | x | | | | `._____.' | || ||____| |____|| || | |________| | || | `._____.' | |
| |___|___|___| |___| | | | | || | | || | | || | | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| | '----------------' '----------------' '----------------' '----------------'
|_____________________|
"""
print(logo)
def add(x, y):
return x+y
def subtract(x, y):
return x-y
def division(x, y):
if(y == 0):
print("It can't divide per 0'")
else:
return x/y
def multiply(x, y):
return x*y
operators = {
"+": add,
"-": subtract,
"/": division,
"*": multiply
}
def calculator():
x = float(input("Please enter a number: "))
keep_going = "y"
while(keep_going == "y"):
operator_chosen = input("Please enter the desired operation: ")
y = float(input("Please enter a number: "))
calculation = operators[operator_chosen]
answer = calculation(x, y)
print(f"{x} {operator_chosen} {y} = {answer}")
keep_going = input(
f"Type 'y' to continue calculating with {answer} or type 'n' to exit: ").lower()
if(keep_going == "y"):
x = answer
"""Here we have a recursion when the user does not want to use the same answer before and it want to start a new iteration"""
else:
calculator()
calculator()
|
fd = open('f',"r")
buffer = fd.read(2)
print("first 2 chars in f:",buffer)
fd.close()
|
# from http://www.voidspace.org.uk/python/weblog/arch_d7_2007_03_17.shtml#e664
def ReadOnlyProxy(obj):
class _ReadOnlyProxy(object):
def __getattr__(self, name):
return getattr(obj, name)
def __setattr__(self, name, value):
raise AttributeError("Attributes can't be set on this object")
for name in dir(obj):
if not (name[:2] == '__' == name[-2:]):
continue
if name in ('__new__', '__init__', '__class__', '__bases__'):
continue
if not callable(getattr(obj, name)):
continue
def get_proxy_method(name):
def proxy_method(self, *args, **keywargs):
return getattr(obj, name)(*args, **keywargs)
return proxy_method
setattr(_ReadOnlyProxy, name, get_proxy_method(name))
return _ReadOnlyProxy() |
settings = {"velocity_min": 1,
"velocity_max": 3,
"x_boundary": 800,
"y_boundary": 800,
"small_particle_radius": 5,
"big_particle_radius": 10,
"number_of_particles": 500,
"density_min": 2,
"density_max": 20
} |
'''8. Write a Python program to count occurrences of a substring in a string.'''
def count_word_in_string(string1, substring2):
return string1.count(substring2)
print(count_word_in_string('The quick brown fox jumps over the lazy dog that is chasing the fox.', "fox")) |
test = {
"name": "q2",
"points": 1,
"hidden": True,
"suites": [
{
"cases": [
{
"code": r"""
>>> sample_population(test_results).num_rows
3000
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> "Test Result" in sample_population(test_results).labels
True
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> round(apply_statistic(test_results, "Village Number", np.average), 4)
8.1307
""",
"hidden": False,
"locked": False,
},
],
"scored": False,
"setup": "",
"teardown": "",
"type": "doctest"
},
]
} |
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
stack = []
for char in s:
if char == '{' or char == '[' or char == '(':
stack.append(char)
else:
try:
c = stack.pop()
if char == '}':
if c != '{':
return False
elif char == ']':
if c != '[':
return False
elif char == ')':
if c != '(':
return False
except IndexError:
return False
if len(stack) > 0:
return False
else:
return True
print(Solution().isValid('()')) |
def read_data():
rules = dict()
your_ticket = None
nearby_tickets = []
state = 0
with open('in') as f:
for line in map(lambda x: x.strip(), f.readlines()):
if line == '':
state += 1
continue
if line == 'your ticket:':
continue
if line == 'nearby tickets:':
continue
if state == 0:
parts = line.split(':')
ranges = parts[1].split('or')
rules[parts[0]] = []
for r in ranges:
nums = r.split('-')
rules[parts[0]].append((int(nums[0]), int(nums[1])))
if state == 1:
your_ticket = list(map(int, line.split(',')))
if state == 2:
nearby_tickets.append(list(map(int, line.split(','))))
return rules, your_ticket, nearby_tickets
def part_one(rules, tickets):
error_rate = 0
invalid_tickets = []
for i, ticket in enumerate(tickets):
for val in ticket:
valid_val = False
for rule in rules.keys():
valid = False
for m, M in rules[rule]:
if val >= m and val <= M:
valid = True
break
if valid:
valid_val = True
break
if not valid_val:
error_rate += val
invalid_tickets.append(i)
return invalid_tickets, error_rate
def part_two(rules, your_ticket, tickets):
possible_values = [set(rules.keys()) for i in range(len(rules.keys()))]
for ticket in tickets:
for i, val in enumerate(ticket):
for rule in rules.keys():
valid = False
for m, M in rules[rule]:
if val >= m and val <= M:
valid = True
break
if not valid and rule in possible_values[i]:
possible_values[i].remove(rule)
while True:
to_filter = False
for v in map(len, possible_values):
if v > 1:
to_filter = True
if not to_filter:
break
for i in range(len(possible_values)):
if len(possible_values[i]) == 1:
for j in range(len(possible_values)):
if i != j:
possible_values[j] -= possible_values[i]
res = 1
for i in range(len(possible_values)):
if 'departure' in list(possible_values[i])[0]:
res *= your_ticket[i]
return res
def main():
rules, your_ticket, nearby_tickets = read_data()
invalid_tickets, error_rate = part_one(rules, nearby_tickets)
p_two = part_two(rules, your_ticket, [t for i, t in enumerate(nearby_tickets) if i not in invalid_tickets])
print(f'Part One: {error_rate}')
print(f'Part Two: {p_two}')
if __name__ == '__main__':
main()
|
mapping = {
"settings": {
"index": {
"max_result_window": 15000,
"analysis": {
"analyzer": {
"default": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["english_stemmer", "lowercase"]
},
"autocomplete": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["lowercase", "autocomplete_filter"]
},
"symbols": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["lowercase"]
}
},
"filter": {
"english_stemmer": {
"type": "stemmer",
"language": "english"
},
"autocomplete_filter": {
"type": "edge_ngram",
"min_gram": "1",
"max_gram": "20"
}
}
},
"number_of_replicas": "1", #temporarily
"number_of_shards": "5"
}
},
"mappings": { # having a raw field means it can be a facet or sorted by
"searchable_item": {
"properties": {
"name": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
},
"autocomplete": {
"type": "string",
"analyzer": "autocomplete"
}
}
},
"category": {
"type": "string",
"analyzer": "symbols"
},
"href": {
"type": "string",
"analyzer": "symbols"
},
"description": {
"type": "string"
},
"first_name": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"last_name": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"institution": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"position": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"country": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"state": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"colleague_loci": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"number_annotations": {
"type": "integer"
},
"feature_type": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"name_description": {
"type": "string"
},
"summary": {
"type": "string"
},
"phenotypes": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"cellular_component": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"biological_process": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"molecular_function": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"ec_number": {
"type": "string",
"analyzer": "symbols"
},
"protein": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"tc_number": {
"type": "string",
"analyzer": "symbols"
},
"secondary_sgdid": {
"type": "string",
"analyzer": "symbols"
},
"sequence_history": {
"type": "string",
"analyzer": "symbols"
},
"gene_history": {
"type": "string",
"analyzer": "symbols"
},
"bioentity_id": {
"type": "string",
"analyzer": "symbols"
},
"keys": {
"type": "string",
"analyzer": "symbols"
},
"status": {
"type": "string",
"analyzer": "symbols",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"observable": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"qualifier": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"references": {
"type": "string",
"analyzer": "symbols",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"phenotype_loci": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"chemical": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"mutant_type": {
"type": "string",
"fields": {
"symbol": {
"type": "string",
"analyzer": "symbols"
},
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"synonyms": {
"type": "string"
},
"go_id": {
"type": "string",
"analyzer": "symbols"
},
"go_loci": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"author": {
"type": "string",
"analyzer": "symbols",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"journal": {
"type": "string",
"analyzer": "symbols",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"year": {
"type": "string",
"analyzer": "symbols",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"reference_loci": {
"type": "string",
"analyzer": "symbols",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"aliases": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"format": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"keyword": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"file_size": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"readme_url": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"topic": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"data": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
},
"is_quick_flag": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"symbol": {
"type": "string",
"analyzer": "symbols"
}
}
}
}
}
}
}
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 15:06:57 2021
@author: user24
"""
file = "./data/tsuretsuregusa.txt"
with open(file, "r", encoding="utf_8") as fileobj:
while True:
# set line as value of the file line
line = fileobj.readline()
# removes any white space at the end of string
aline = line.rstrip()
# if line exists, print line
if aline:
print(aline)
# if don't exist, break from loop
else:
break
|
'''
https://www.hackerrank.com/challenges/strings-xor/submissions/code/102872134
Given two strings consisting of digits 0 and 1 only, find the XOR of the two strings.
'''
def strings_xor(s, t):
res = ""
for i in range(len(s)):
if s[i] != t[i]:
res += '1'
else:
res += '0'
return res
s = input()
t = input()
print(strings_xor(s, t))
|
salario = float(input('Qual o seu salário? R$ '))
if salario <= 1250:
novo = salario + (salario * 15 / 100)
else:
novo = salario + (salario * 10 / 100)
print(f'Seu novo salário é R${novo :.2f}.') |
__description__ = "Gearman RPC broker"
__config__ = {
"gearmand.listen_address": dict(
description = "IP address to bind to",
default = "127.0.0.1",
),
"gearmand.user": dict(
display_name = "Gearmand user",
description = "User to run the gearmand procses as",
default = "nobody",
),
"gearmand.pidfile": dict(
display_name = "Gearmand pid file",
description = "Path to the PID file for gearmand",
default = "/var/run/gearmand/gearmand.pid",
),
}
|
bot_token = ''
waiting_timeout = 5 # Seconds
admin_id = ""
channel_id = ""
bitly_access_token = ""
vars_file = ""
|
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.5'
_lr_method = 'LALR'
_lr_signature = '5E2BB3531AA676A6BB1D06733251B2F3'
_lr_action_items = {'COS':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[1,1,1,1,1,1,1,1,1,1,-26,1,-32,1,1,1,1,1,-18,-19,1,-52,1,1,-27,-35,-24,1,-28,-37,1,-25,-34,-36,1,-30,-31,-39,1,1,1,-23,-38,-21,1,-29,1,1,-22,1,1,1,1,-47,-40,1,1,1,-7,-42,-49,1,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'COT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[5,5,5,5,5,5,5,5,5,5,-26,5,-32,5,5,5,5,5,-18,-19,5,-52,5,5,-27,-35,-24,5,-28,-37,5,-25,-34,-36,5,-30,-31,-39,5,5,5,-23,-38,-21,5,-29,5,5,-22,5,5,5,5,-47,-40,5,5,5,-7,-42,-49,5,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'DEGREE':([12,14,22,23,27,32,33,34,36,37,39,40,42,44,45,46,50,51,52,54,57,62,63,67,68,69,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[-26,-32,-18,-19,-52,-27,62,-24,-28,69,-25,72,75,-30,-31,78,-23,83,-21,-29,-22,-47,-40,-7,-42,-49,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-28,-33,]),'SUM':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[3,3,3,3,3,3,3,3,3,3,-26,3,-32,3,3,3,3,3,-18,-19,3,-52,3,3,-27,-35,-24,3,-28,-37,3,-25,-34,-36,3,-30,-31,-39,3,3,3,-23,-38,-21,3,-29,3,3,-22,3,3,3,3,-47,-40,3,3,3,-7,-42,-49,3,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'MINUS':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,21,22,23,26,27,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[4,4,4,4,4,4,4,4,4,4,-26,4,-32,4,4,4,4,4,-27,-18,-19,4,-52,4,4,61,-27,61,61,64,-28,61,4,61,61,61,61,64,61,61,61,64,64,4,61,61,61,4,-29,4,4,-22,4,4,4,4,-47,-40,4,4,4,61,-42,-49,64,-45,-46,-20,-41,-48,61,-44,-51,61,61,61,-43,-50,61,61,-14,61,-11,-13,-12,-12,61,-33,]),'LOG':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[2,2,2,2,2,2,2,2,2,2,-26,2,-32,2,2,2,2,2,-18,-19,2,-52,2,2,-27,-35,-24,2,-28,-37,2,-25,-34,-36,2,-30,-31,-39,2,2,2,-23,-38,-21,2,-29,2,2,-22,2,2,2,2,-47,-40,2,2,2,-7,-42,-49,2,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'RAD':([12,14,22,23,27,32,33,34,36,37,39,40,42,44,45,46,50,51,52,54,57,62,63,67,68,69,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[-26,-32,-18,-19,-52,-27,63,-24,-28,68,-25,71,74,-30,-31,77,-23,82,-21,-29,-22,-47,-40,-7,-42,-49,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-28,-33,]),'POWER':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[6,6,6,6,6,6,6,6,6,6,-26,6,-32,6,6,6,6,6,-18,-19,6,-52,6,6,-27,-35,-24,6,-28,-37,6,-25,-34,-36,6,-30,-31,-39,6,6,6,-23,-38,-21,6,-29,6,6,-22,6,6,6,6,-47,-40,6,6,6,-7,-42,-49,6,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'LN':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[7,7,7,7,7,7,7,7,7,7,-26,7,-32,7,7,7,7,7,-18,-19,7,-52,7,7,-27,-35,-24,7,-28,-37,7,-25,-34,-36,7,-30,-31,-39,7,7,7,-23,-38,-21,7,-29,7,7,-22,7,7,7,7,-47,-40,7,7,7,-7,-42,-49,7,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'SIN':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[8,8,8,8,8,8,8,8,8,8,-26,8,-32,8,8,8,8,8,-18,-19,8,-52,8,8,-27,-35,-24,8,-28,-37,8,-25,-34,-36,8,-30,-31,-39,8,8,8,-23,-38,-21,8,-29,8,8,-22,8,8,8,8,-47,-40,8,8,8,-7,-42,-49,8,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'OPAR':([0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[9,9,9,9,9,9,38,9,9,9,9,-26,9,-32,9,9,9,9,9,-18,-19,9,-52,9,9,-27,-35,-24,9,-28,-37,9,-25,-34,-36,9,-30,-31,-39,9,9,9,-23,-38,-21,9,-29,9,9,-22,9,9,9,9,-47,-40,9,9,9,-7,-42,-49,9,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'SEC':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[29,29,29,29,29,29,29,29,29,29,-26,29,-32,29,29,29,29,29,-18,-19,29,-52,29,29,-27,-35,-24,29,-28,-37,29,-25,-34,-36,29,-30,-31,-39,29,29,29,-23,-38,-21,29,-29,29,29,-22,29,29,29,29,-47,-40,29,29,29,-7,-42,-49,29,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'TAN':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[11,11,11,11,11,11,11,11,11,11,-26,11,-32,11,11,11,11,11,-18,-19,11,-52,11,11,-27,-35,-24,11,-28,-37,11,-25,-34,-36,11,-30,-31,-39,11,11,11,-23,-38,-21,11,-29,11,11,-22,11,11,11,11,-47,-40,11,11,11,-7,-42,-49,11,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'PI':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[12,12,12,12,12,12,12,12,12,12,-26,12,-32,12,12,12,12,12,-18,-19,12,-52,12,12,-27,-35,-24,12,-28,-37,12,-25,-34,-36,12,-30,-31,-39,12,12,12,-23,-38,-21,12,-29,12,12,-22,12,12,12,12,-47,-40,12,12,12,-7,-42,-49,12,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'QUOTIENT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[13,13,13,13,13,13,13,13,13,13,-26,13,-32,13,13,13,13,13,-18,-19,13,-52,13,13,-27,-35,-24,13,-28,-37,13,-25,-34,-36,13,-30,-31,-39,13,13,13,-23,-38,-21,13,-29,13,13,-22,13,13,13,13,-47,-40,13,13,13,-7,-42,-49,13,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'PLUS':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,59,-27,59,59,59,-28,59,59,59,59,59,59,59,59,59,59,59,59,59,59,-29,-22,-47,-40,-29,-22,59,-42,-49,59,-45,-46,-20,-41,-48,59,-44,-51,59,59,59,-43,-50,59,59,-14,59,-11,-13,-12,-12,59,-33,]),'SQUARE':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,21,22,23,26,27,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[15,15,15,15,15,15,15,15,15,15,-26,15,-32,15,15,15,15,15,-27,-18,-19,15,-52,15,15,54,-27,54,54,65,-28,54,15,54,54,54,54,65,54,54,54,65,65,15,54,54,54,15,-29,15,15,-22,15,15,15,15,-47,-40,15,15,15,54,-42,-49,65,-45,-46,-20,-41,-48,54,-44,-51,54,54,54,-43,-50,54,54,-14,54,-11,-13,-12,-12,54,-33,]),'XOR':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,55,-27,55,55,55,-28,55,55,55,55,55,55,55,55,55,55,55,55,55,55,-29,-22,-47,-40,-29,-22,55,-42,-49,55,-45,-46,-20,-41,-48,55,-44,-51,55,55,55,-43,-50,55,55,-14,55,-11,-13,-12,-12,55,-33,]),'DIVIDE':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,56,-27,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,-29,-22,-47,-40,-29,-22,56,-42,-49,56,-45,-46,-20,-41,-48,56,-44,-51,56,56,56,-43,-50,56,56,-14,56,56,-13,56,56,56,-33,]),'SQROOT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[16,16,16,16,16,16,16,16,16,16,-26,16,-32,16,16,16,16,16,-18,-19,16,-52,16,16,-27,-35,-24,16,-28,-37,16,-25,-34,-36,16,-30,-31,-39,16,16,16,-23,-38,-21,16,-29,16,16,-22,16,16,16,16,-47,-40,16,16,16,-7,-42,-49,16,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'CPAR':([12,14,22,23,27,32,33,34,36,37,39,40,41,42,44,45,46,50,51,52,54,57,62,63,67,68,69,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-18,-19,-52,-27,-35,-24,-28,-37,-25,-34,73,-36,-30,-31,-39,-23,-38,-21,-29,-22,-47,-40,-7,-42,-49,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-28,93,-33,]),'EQUALS':([21,],[49,]),'TIMES':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,60,-27,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,-29,-22,-47,-40,-29,-22,60,-42,-49,60,-45,-46,-20,-41,-48,60,-44,-51,60,60,60,-43,-50,60,60,-14,60,60,-13,60,60,60,-33,]),'COSEC':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[17,17,17,17,17,17,17,17,17,17,-26,17,-32,17,17,17,17,17,-18,-19,17,-52,17,17,-27,-35,-24,17,-28,-37,17,-25,-34,-36,17,-30,-31,-39,17,17,17,-23,-38,-21,17,-29,17,17,-22,17,17,17,17,-47,-40,17,17,17,-7,-42,-49,17,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'DIFFERENCE':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[18,18,18,18,18,18,18,18,18,18,-26,18,-32,18,18,18,18,18,-18,-19,18,-52,18,18,-27,-35,-24,18,-28,-37,18,-25,-34,-36,18,-30,-31,-39,18,18,18,-23,-38,-21,18,-29,18,18,-22,18,18,18,18,-47,-40,18,18,18,-7,-42,-49,18,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'AND':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,53,-27,53,53,53,-28,53,53,53,53,53,53,53,53,53,53,53,53,53,53,-29,-22,-47,-40,-29,-22,53,-42,-49,53,-45,-46,-20,-41,-48,53,-44,-51,53,53,53,-43,-50,53,53,-14,53,-11,-13,-12,-12,53,-33,]),'QUIT':([0,],[19,]),'PRODUCT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[20,20,20,20,20,20,20,20,20,20,-26,20,-32,20,20,20,20,20,-18,-19,20,-52,20,20,-27,-35,-24,20,-28,-37,20,-25,-34,-36,20,-30,-31,-39,20,20,20,-23,-38,-21,20,-29,20,20,-22,20,20,20,20,-47,-40,20,20,20,-7,-42,-49,20,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'NAME':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[21,32,32,32,32,32,32,32,32,32,-26,32,-32,32,32,32,32,32,-18,-19,32,-52,32,32,-27,-35,-24,32,-28,-37,32,-25,-34,-36,32,-30,-31,-39,32,32,32,-23,-38,-21,32,-29,32,32,-22,32,32,32,32,-47,-40,32,32,32,-7,-42,-49,32,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'INT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[22,22,22,22,22,22,22,22,22,22,-26,22,-32,22,22,22,22,22,-18,-19,22,-52,22,22,-27,-35,-24,22,-28,-37,22,-25,-34,-36,22,-30,-31,-39,22,22,22,-23,-38,-21,22,-29,22,22,-22,22,22,22,22,-47,-40,22,22,22,-7,-42,-49,22,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'FLOAT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[23,23,23,23,23,23,23,23,23,23,-26,23,-32,23,23,23,23,23,-18,-19,23,-52,23,23,-27,-35,-24,23,-28,-37,23,-25,-34,-36,23,-30,-31,-39,23,23,23,-23,-38,-21,23,-29,23,23,-22,23,23,23,23,-47,-40,23,23,23,-7,-42,-49,23,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'BREAK':([0,],[25,]),'FACTORIAL':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,21,22,23,26,27,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[26,26,26,26,26,26,26,26,26,26,-26,26,-32,26,26,26,26,26,-27,-18,-19,26,-52,26,26,57,-27,57,57,66,-28,57,26,57,57,57,57,66,57,57,57,66,66,26,57,57,57,26,-29,26,26,-22,26,26,26,26,-47,-40,26,26,26,57,-42,-49,66,-45,-46,-20,-41,-48,57,-44,-51,57,57,57,-43,-50,57,57,-14,57,-11,-13,-12,-12,57,-33,]),'REGISTERS':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[27,27,27,27,27,27,27,27,27,27,-26,27,-32,27,27,27,27,27,-18,-19,27,-52,27,27,-27,-35,-24,27,-28,-37,27,-25,-34,-36,27,-30,-31,-39,27,27,27,-23,-38,-21,27,-29,27,27,-22,27,27,27,27,-47,-40,27,27,27,-7,-42,-49,27,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'EXIT':([0,],[28,]),'NOT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[30,30,30,30,30,30,30,30,30,30,-26,30,-32,30,30,30,30,30,-18,-19,30,-52,30,30,-27,-35,-24,30,-28,-37,30,-25,-34,-36,30,-30,-31,-39,30,30,30,-23,-38,-21,30,-29,30,30,-22,30,30,30,30,-47,-40,30,30,30,-7,-42,-49,30,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'$end':([10,12,14,19,21,22,23,24,25,27,28,31,32,33,34,36,37,39,40,42,44,45,46,50,51,52,54,57,62,63,67,68,69,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,93,],[-2,-26,-32,-6,-27,-18,-19,0,-4,-52,-5,-3,-27,-35,-24,-28,-37,-25,-34,-36,-30,-31,-39,-23,-38,-21,-29,-22,-47,-40,-7,-42,-49,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-1,-43,-50,-16,-17,-14,-15,-11,-13,-12,-28,-33,]),'OR':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,58,-27,58,58,58,-28,58,58,58,58,58,58,58,58,58,58,58,58,58,58,-29,-22,-47,-40,-29,-22,58,-42,-49,58,-45,-46,-20,-41,-48,58,-44,-51,58,58,58,-43,-50,58,58,-14,58,-11,-13,-12,-12,58,-33,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'function1':([0,1,2,3,4,5,7,8,9,11,13,15,16,17,18,20,26,29,30,35,38,43,47,48,49,53,55,56,58,59,60,61,64,65,66,70,],[14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,]),'expression':([0,1,2,3,4,5,7,8,9,11,13,15,16,17,18,20,26,29,30,35,38,43,47,48,49,53,55,56,58,59,60,61,64,65,66,70,],[31,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,67,70,76,79,80,81,84,85,86,87,88,89,90,91,44,50,92,]),'assign':([0,],[24,]),'statement':([0,],[10,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> assign","S'",1,None,None,None),
('assign -> NAME EQUALS expression','assign',3,'p_statement_assign','calc1.py',13),
('assign -> statement','assign',1,'p_statement_assign','calc1.py',14),
('statement -> expression','statement',1,'p_statement_expr','calc1.py',22),
('statement -> BREAK','statement',1,'p_statement_expr','calc1.py',23),
('statement -> EXIT','statement',1,'p_statement_expr','calc1.py',24),
('statement -> QUIT','statement',1,'p_statement_expr','calc1.py',25),
('expression -> SUM expression expression','expression',3,'p_exprr','calc1.py',34),
('expression -> DIFFERENCE expression expression','expression',3,'p_exprr','calc1.py',35),
('expression -> PRODUCT expression expression','expression',3,'p_exprr','calc1.py',36),
('expression -> QUOTIENT expression expression','expression',3,'p_exprr','calc1.py',37),
('expression -> expression PLUS expression','expression',3,'p_expression_binop','calc1.py',50),
('expression -> expression MINUS expression','expression',3,'p_expression_binop','calc1.py',51),
('expression -> expression TIMES expression','expression',3,'p_expression_binop','calc1.py',52),
('expression -> expression DIVIDE expression','expression',3,'p_expression_binop','calc1.py',53),
('expression -> expression OR expression','expression',3,'p_expression_binop','calc1.py',54),
('expression -> expression AND expression','expression',3,'p_expression_binop','calc1.py',55),
('expression -> expression XOR expression','expression',3,'p_expression_binop','calc1.py',56),
('expression -> INT','expression',1,'p_factor','calc1.py',80),
('expression -> FLOAT','expression',1,'p_factor','calc1.py',81),
('expression -> OPAR expression CPAR','expression',3,'p_paran','calc1.py',85),
('expression -> NOT expression','expression',2,'p_logical_not','calc1.py',89),
('expression -> expression FACTORIAL','expression',2,'p_factorial_exp','calc1.py',93),
('expression -> FACTORIAL expression','expression',2,'p_factorial_exp','calc1.py',94),
('expression -> LOG expression','expression',2,'p_logarithms','calc1.py',108),
('expression -> LN expression','expression',2,'p_logarithms','calc1.py',109),
('expression -> PI','expression',1,'p_pival','calc1.py',126),
('expression -> NAME','expression',1,'p_pival','calc1.py',127),
('expression -> MINUS expression','expression',2,'p_uniminus','calc1.py',134),
('expression -> expression SQUARE','expression',2,'p_square_fun','calc1.py',138),
('expression -> SQUARE expression','expression',2,'p_square_fun','calc1.py',139),
('expression -> SQROOT expression','expression',2,'p_square_root','calc1.py',147),
('expression -> function1','expression',1,'p_math_fun','calc1.py',151),
('expression -> POWER OPAR expression expression CPAR','expression',5,'p_math_pow','calc1.py',155),
('function1 -> SIN expression','function1',2,'p_trig_func1','calc1.py',161),
('function1 -> COS expression','function1',2,'p_trig_func1','calc1.py',162),
('function1 -> TAN expression','function1',2,'p_trig_func1','calc1.py',163),
('function1 -> COT expression','function1',2,'p_trig_func1','calc1.py',164),
('function1 -> SEC expression','function1',2,'p_trig_func1','calc1.py',165),
('function1 -> COSEC expression','function1',2,'p_trig_func1','calc1.py',166),
('function1 -> COS expression RAD','function1',3,'p_trig_func1','calc1.py',167),
('function1 -> TAN expression RAD','function1',3,'p_trig_func1','calc1.py',168),
('function1 -> COT expression RAD','function1',3,'p_trig_func1','calc1.py',169),
('function1 -> SEC expression RAD','function1',3,'p_trig_func1','calc1.py',170),
('function1 -> COSEC expression RAD','function1',3,'p_trig_func1','calc1.py',171),
('function1 -> SIN expression RAD','function1',3,'p_trig_func1','calc1.py',172),
('function1 -> SIN expression DEGREE','function1',3,'p_func1','calc1.py',190),
('function1 -> COS expression DEGREE','function1',3,'p_func1','calc1.py',191),
('function1 -> TAN expression DEGREE','function1',3,'p_func1','calc1.py',192),
('function1 -> COT expression DEGREE','function1',3,'p_func1','calc1.py',193),
('function1 -> SEC expression DEGREE','function1',3,'p_func1','calc1.py',194),
('function1 -> COSEC expression DEGREE','function1',3,'p_func1','calc1.py',195),
('expression -> REGISTERS','expression',1,'p_registers','calc1.py',211),
]
|
# The following is a list of gene-plan combinations which should
# not be run
BLACKLIST = [
('8C58', 'performance'), # performance.xml make specific references to 52DC
('7DDA', 'performance') # performance.xml make specific references to 52DC
]
IGNORE = {
'history' : ['uuid', 'creationTool', 'creationDate'],
'genome' : ['uuid', 'creationTool', 'creationDate'],
# the following two ignored because they contain line numbers
'attempt' : ['description'],
'compared' : ['description']
}
|
#This exercise is Part 4 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 1, Part 2, and Part 3.
#
#In 3 previous exercises, we built up a few components needed to build a Tic Tac Toe game in Python:
#
# Draw the Tic Tac Toe game board
# Checking whether a game board has a winner
# Handle a player move from user input
#
#The next step is to put all these three components together to make a two-player Tic Tac Toe game! Your challenge in
# this exercise is to use the functions from those previous exercises all together in the same program to make a two-
# player game that you can play with a friend. There are a lot of choices you will have to make when completing this
# exercise, so you can go as far or as little as you want with it.
#
#Here are a few things to keep in mind:
#
# You should keep track of who won - if there is a winner, show a congratulatory message on the screen.
# If there are no more moves left, don’t ask for the next player’s move!
#
#As a bonus, you can ask the players if they want to play again and keep a running tally of who won more - Player 1
# or Player 2.
def printBoard(gameBoard):
board = ""
for i in range(0,3):
for _ in range(0,3):
board = board + " ---"
board = board + "\n"
for j in range(0,3):
board = board + "| {0} ".format(gameBoard[i][j] if gameBoard[i][j] != 0 else " ")
board = board + "|\n"
for _ in range(0,3):
board = board + " ---"
print(board)
def checkIfWin(board):
for i in range(0,len(board)):
if board[i][0] == board[i][1] and board[i][1] == board [i][2]:
return board[i][0]
elif board[0][i] == board[1][i] and board[1][i] == board [2][i]:
return board[i][0]
if board[0][0] == board[1][1] and board[1][1] == board [2][2]:
return board[0][0]
elif board[0][2] == board[1][1] and board[1][1] == board [2][0]:
return board[0][2]
else:
return 0
def placeMovement(board,x,y,playerSymbol):
if board[x][y] == 0:
board[x][y] = playerSymbol
return board
else:
raise NameError("Position Taken")
def getUserInput(playerNumber,playerSymbol,position):
while True:
try:
y = int(input("Player {0} ({1}), please input the {2} for your movement: ".format(playerNumber,playerSymbol,position)))
if y > 0 and y < 4:
y-=1
return y
else:
print("Value should be 1, 2 or 3.")
except ValueError:
print("Value is not a number.")
if __name__ == "__main__":
players = {
1: "X",
2: "O"
}
wins = {
1: 0,
2: 0
}
while True:
board = [[0,0,0],[0,0,0],[0,0,0]]
for i in range (0,9):
printBoard(board)
while True:
goesNext = 1 if i % 2 == 0 else 2
x = getUserInput(goesNext,players[goesNext],"row")
y = getUserInput(goesNext,players[goesNext],"column")
try:
board = placeMovement(board,x,y,players[goesNext])
break
except NameError:
print("Position is already taken. Try another one.")
if i >= 4:
if checkIfWin(board) != 0:
wins[goesNext]+=1
printBoard(board)
print("Player {0} won!".format(goesNext))
break
while True:
print("Player 1 won {0}, Player 2 won {1} times!".format(wins[1],wins[2]))
playAgain = input("Do you want to play again? (Yes/No): ")
if playAgain.lower() != 'yes' and playAgain.lower() != 'no':
print("Only valid options are 'Yes' and 'No'.")
else:
break
if playAgain.lower() == 'no':
print("Thanks for playing!")
break |
track = dict(
author_username='alexisbcook',
course_name='Data Cleaning',
course_url='https://www.kaggle.com/learn/data-cleaning',
course_forum_url='https://www.kaggle.com/learn-forum/172650'
)
lessons = [ {'topic': topic_name} for topic_name in
['Handling missing values', #1
'Scaling and normalization', #2
'Parsing dates', #3
'Character encodings', #4
'Inconsistent data entry'] #5
]
notebooks = [
dict(
filename='tut1.ipynb',
lesson_idx=0,
type='tutorial',
dataset_sources=['maxhorowitz/nflplaybyplay2009to2016'],
),
dict(
filename='ex1.ipynb',
lesson_idx=0,
type='exercise',
dataset_sources=['aparnashastry/building-permit-applications-data'],
scriptid=10824396
),
dict(
filename='tut2.ipynb',
lesson_idx=1,
type='tutorial',
),
dict(
filename='ex2.ipynb',
lesson_idx=1,
type='exercise',
dataset_sources=['kemical/kickstarter-projects'],
scriptid=10824404
),
dict(
filename='tut3.ipynb',
lesson_idx=2,
type='tutorial',
dataset_sources=['nasa/landslide-events']
),
dict(
filename='ex3.ipynb',
lesson_idx=2,
type='exercise',
dataset_sources=['usgs/earthquake-database', 'smithsonian/volcanic-eruptions'],
scriptid=10824403
),
dict(
filename='tut4.ipynb',
lesson_idx=3,
type='tutorial',
dataset_sources=['kemical/kickstarter-projects']
),
dict(
filename='ex4.ipynb',
lesson_idx=3,
type='exercise',
dataset_sources=['kwullum/fatal-police-shootings-in-the-us'],
scriptid=10824401
),
dict(
filename='tut5.ipynb',
lesson_idx=4,
type='tutorial',
dataset_sources=['alexisbcook/pakistan-intellectual-capital']
),
dict(
filename='ex5.ipynb',
lesson_idx=4,
type='exercise',
dataset_sources=['alexisbcook/pakistan-intellectual-capital'],
scriptid=10824407
),
] |
"""
https://leetcode.com/problems/3sum/
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
"""
class Solution(object):
def threeSum(self, nums):
"""
Strategy is to use sort first and then use three pointers:
1. One pointer is current value
2. One pointer is "left" index that starts from index after current value
3. One pointer is "right" index that starts from last index
Calculate sum of all three pointers.
If sum is greater than 0, need to make sum smaller, so decrease right index until next distinct integer
If sum is less than 0, need to make bigger, so increase left index until next distinct integer
If sum is 0, we found combination that works - when combination is found, need to increment left and right
indices until next distinct integers for both.
When left index surpasses right index, stop iterating and move on to next value.
Can only calculate sums when current value is not positive. This is because three positive values can't sum to 0.
:type nums: List[int]
:rtype: List[List[int]]
"""
triplets = []
nums.sort()
for index, target in enumerate(nums[:-2]):
if target <= 0 and (index == 0 or (index > 0 and nums[index] != nums[index - 1])):
left_index = index + 1
right_index = len(nums) - 1
while left_index < right_index:
triplet_sum = target + nums[left_index] + nums[right_index]
if triplet_sum > 0:
right_value = nums[right_index]
while left_index < right_index and right_value == nums[right_index]:
right_index -= 1
elif triplet_sum < 0:
left_value = nums[left_index]
while left_index < right_index and left_value == nums[left_index]:
left_index += 1
else:
triplets.append([
target,
nums[left_index],
nums[right_index],
])
right_value = nums[right_index]
while left_index < right_index and right_value == nums[right_index]:
right_index -= 1
left_value = nums[left_index]
while left_index < right_index and left_value == nums[left_index]:
left_index += 1
return triplets
|
# !usr/bin/python
# -*- coding: UTF-8 -*-
class Image:
def __init__(self, name, path, url):
self.name = name
self.path = path
self.url = url
@property
def full_path(self):
return self.path + self.name
def __str__(self):
return self.name
def __repr__(self):
return f' {{ Name: {self.name}, \nPath: {self.path}, \nURL:{self.url} }}'
|
def metade(preco,sit):
if sit==True:
return (f'R${preco/2}')
else:
return preco/2
def dobro(preco,sit):
if sit==True:
return (f'R${preco * 2}')
else:
return preco * 2
def aumentar(preco,r,sit):
if sit==True:
return (f'R${preco * (100 + r)/100}')
else:
return preco * (100 + r) / 100
def diminuir(preco,r,sit):
if sit==True:
return(f'R${preco * (100 - r)/100}')
else:
return preco * (100-r)/100
def moeda(preco):
return (f'R${preco}')
def resumo(p=0, r=10, q=5):
print('-'*30)
print('RESUMO DO VALOR'.center(30))
print('-' * 30)
print(f'Preco analisado: \t{moeda(p):>10}')
print(f'Dobro do preco: \t{dobro(p, True):>10}')
print(f'Metade do preco: \t{metade(p, True):>10}')
print(f'{r}% de aumento: \t{aumentar(p, r, True):>10}')
print(f'{q}% de reducao: \t{diminuir(p, q, True):>10}') |
""" Test filters used by test_toolbox_filters.py.
"""
def filter_tool( context, tool ):
"""Test Filter Tool"""
return False
def filter_section( context, section ):
"""Test Filter Section"""
return False
def filter_label_1( context, label ):
"""Test Filter Label 1"""
return False
def filter_label_2( context, label ):
"""Test Filter Label 2"""
return False
|
word=input("enter any word:")
d={}
for x in word:
d[x]=d.get(x,0)+1
for k,v in d.items():
print(k,"occured",v,"times") |
#!/usr/bin/env python3
average = 0
score = int(input('Enter first score: '))
score += int(input('Enter second score: '))
score += int(input('Enter third score: '))
average = score / 3.0
average = round(average, 2)
print(f'Total Score: {score}')
print(f'Average Score: {average}')
|
"""restrictive_growth_strings.py: Constructs the lexicographic
restrictive growth string representation of all the way to partition a set,
given the length of the set."""
__author__ = "Justin Overstreet"
__copyright__ = "oversj96.github.io"
def set_to_zero(working_set, index):
"""Given a set and an index, set all elements to 0 after the index."""
if index == len(working_set) - 1:
return working_set
else:
for i in range(index + 1, len(working_set)):
working_set[i] = 0
return working_set
def update_b_row(a_row, b_row):
"""Update b row to reflect the max value of a sequence range in row a"""
for i in range(1, len(a_row)):
b_row[i - 1] = max(a_row[:i]) + 1
return b_row
def restrictive_growth_strings(length):
"""Returns the set of all partitions of a set in a lexicographic integer format.
The algorithm is based on Donald Knuth's volume 4A on combinatoric algorithms.
Algorithm H."""
n = length - 1
a_string = [0 for i in range(0, length)]
b_string = [1 for i in range(0, n)]
lexico_string = [a_string.copy()]
incrementable = True
while incrementable:
incrementable = False
for index in range(n, 0, -1):
if a_string[index] < n and a_string[index] < b_string[index - 1]:
incrementable = True
a_string[index] += 1
a_string = set_to_zero(a_string, index)
b_string = update_b_row(a_string, b_string)
lexico_string.append(a_string.copy())
break
return lexico_string
if __name__ == "__main__":
"""A quick way to check if the module works correctly is to compare
the partition count to the bell number of the correct 'n' size.
For a set of 7 elements, the partition count should be 877 by Bell's numbers."""
strings = restrictive_growth_strings(7)
for string in strings:
print(string)
print(len(strings))
|
"""
Author: Sean Toll
Test simulation functionality
"""
print("Test")
|
def binary_tree(r):
"""
:param r: This is root node
:return: returns tree
"""
return [r, [], []]
def insert_left(root, new_branch):
"""
:param root: current root of the tree
:param new_branch: new branch for a tree
:return: updated root of the tree
"""
t = root.pop(1)
if len(t) > 1:
root.insert(1, [new_branch, t, []])
else:
root.insert(1, [new_branch, [], []])
return root
def insert_right(root, new_branch):
"""
:param root: current root of the tree
:param new_branch: new branch for a tree
:return: updated root of the tree
"""
t = root.pop(2)
if len(t) > 1:
root.insert(2, [new_branch, [], t])
else:
root.insert(2, [new_branch, [], []])
return root
def get_root_val(root):
"""
:param root: current tree root
:return: current tree root value
"""
return root[0]
def set_root_val(root, new_val):
"""
:param root: current tree root
:param new_val: new value for root to update it
:return: updated tree root
"""
root[0] = new_val
def get_left_child(root):
"""
:param root: current root
:return: Left child of selected root
"""
return root[1]
def get_right_child(root):
"""
:param root: current root
:return: Right child of selected root
"""
return root[2]
if __name__ == '__main__':
r = binary_tree(3)
print(insert_left(r, 5))
print(insert_left(r, 6))
print(insert_right(r, 7))
print(insert_right(r, 8))
l = get_left_child(r)
print(l)
rg = get_right_child(r)
print(rg)
|
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
'''
calculate AUC
'''
def calc_auc(raw_arr):
'''
calculate AUC
:param raw_arr:
:return:
'''
arr = sorted(raw_arr, key=lambda d: d[0], reverse=True)
pos, neg = 0., 0.
for record in arr:
if abs(record[1] - 1.) < 0.000001:
pos += 1
else:
neg += 1
fp, tp = 0., 0.
xy_arr = []
for record in arr:
if abs(record[1] - 1.) < 0.000001:
tp += 1
else:
fp += 1
xy_arr.append([fp / neg, tp / pos])
auc = 0.
prev_x = 0.
prev_y = 0.
for x, y in xy_arr:
if x != prev_x:
auc += ((x - prev_x) * (y + prev_y) / 2.)
prev_x = x
prev_y = y
return auc
|
def is_valid(r, c, size):
if 0 <= r < size and 0 <= c < size:
return True
return False
count_presents = int(input())
n = int(input())
matrix = []
nice_kids_count = 0
given_to_nice = 0
for _ in range(n):
data = input().split()
matrix.append(data)
nice_kids_count += data.count("V")
santa_row = int
santa_col = int
for row in range(n):
for col in range(n):
if matrix[row][col] == "S":
santa_row = row
santa_col = col
all_directions = {
"up": (-1, 0),
"down": (1, 0),
"left": (0, -1),
"right": (0, 1)
}
while True:
command = input()
if command == "Christmas morning":
break
next_row = santa_row + all_directions[command][0]
next_col = santa_col + all_directions[command][1]
if is_valid(next_row, next_col, n):
if matrix[next_row][next_col] == "V":
given_to_nice += 1
count_presents -= 1
elif matrix[next_row][next_col] == "C":
for direction in all_directions:
next_step_row = next_row + all_directions[direction][0]
next_step_col = next_col + all_directions[direction][1]
if is_valid(next_step_row, next_step_col, n):
if matrix[next_step_row][next_step_col] == "V":
given_to_nice += 1
count_presents -= 1
elif matrix[next_step_row][next_step_col] == "X":
count_presents -= 1
matrix[next_step_row][next_step_col] = "-"
if count_presents == 0:
break
matrix[santa_row][santa_col] = "-"
matrix[next_row][next_col] = "S"
santa_row = next_row
santa_col = next_col
if count_presents == 0:
break
if count_presents == 0 and nice_kids_count != given_to_nice:
print("Santa ran out of presents!")
for sublist in matrix:
print(" ".join(sublist))
if nice_kids_count == given_to_nice:
print(f"Good job, Santa! {given_to_nice} happy nice kid/s.")
else:
print(f"No presents for {nice_kids_count - given_to_nice} nice kid/s.") |
# Setup
opt = ["yes", "no"]
directions = ["left", "right", "forward", "backward"]
# Introduction
name = input("What is your name, HaCKaToOnEr ?\n")
print("Welcome to Toonslate island , " + name + " Let us go on a Minecraft quest!")
print("You find yourself in front of a abandoned mineshaft.")
print("Can you find your way to explore the shaft and find the treasure chest ?\n")
# Start of game
response = ""
while response not in opt:
response = input("Would you like to go inside the Mineshaft?\nyes/no\n")
if response == "yes":
print("You head into the Mineshaft. You hear grumbling sound of zombies,hissing sound of spidersand rattling of skeletons.\n")
elif response == "no":
print("You are not ready for this quest. Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")
# Next part of game
response = ""
while response not in directions:
print("To your left, you see a skeleton with a golden armor and a bow .")
print("To your right, there is a way to go more inside the shaft.")
print("There is a cobble stone wall directly in front of you.")
print("Behind you is the mineshaft exit.\n")
response = input("What direction would you like to move?\nleft/right/forward/backward\n")
if response == "left":
print(name+" was shot by an arrow. Farewell :( ")
quit()
elif response == "right":
print("You head deeper into the mineshaft and find the treasure chest ,Kudos!!!.\n")
elif response == "forward":
print("You broke the stone walls and find out it was a spider spawner, spiders slain you to deeath\n")
response = ""
elif response == "backward":
print("You leave the mineshaft un explored . Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")
|
#Julian Conneely, 21/03/18
#WhileIF loop with increment
#first 5 is printed
#then it is decreased to 4
#as it is not satisfying i<=2
#it moves on
#then 4 is printed
#then it is decreased to 3
#as it is not satisfying i<=2,it moves on
#then 3 is printed
#then it is decreased to 2
#as now i<=2 has completely satisfied, the loop breaks
i = 5
while True:
print(i)
i=i-1
if i<=2:
break
|
MIN_CONF = 0.3
NMS_THRESH = 0.3
USE_GPU = False
MIN_DISTANCE = 50
WEIGHT_PATH = "yolov3-tiny.weights"
CONFIG_PATH = "yolov3-tiny.cfg" |
def f(x, y):
"""
Args:
x (Foo
y (Bar : description
""" |
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 0
for n in nums:
k ^= n
return k |
expected_output = {
"address_family":{
"ipv4":{
"bfd_sessions_down":0,
"bfd_sessions_inactive":1,
"bfd_sessions_up":0,
"intf_down":1,
"intf_up":1,
"num_bfd_sessions":1,
"num_intf":2,
"state":{
"all":{
"sessions":2,
"slaves":0,
"total":2
},
"backup":{
"sessions":1,
"slaves":0,
"total":1
},
"init":{
"sessions":1,
"slaves":0,
"total":1
},
"master":{
"sessions":0,
"slaves":0,
"total":0
},
"master(owner)":{
"sessions":0,
"slaves":0,
"total":0
}
},
"virtual_addresses_active":0,
"virtual_addresses_inactive":2,
"vritual_addresses_total":2
},
"ipv6":{
"bfd_sessions_down":0,
"bfd_sessions_inactive":0,
"bfd_sessions_up":0,
"intf_down":0,
"intf_up":1,
"num_bfd_sessions":0,
"num_intf":1,
"state":{
"all":{
"sessions":1,
"slaves":0,
"total":1
},
"backup":{
"sessions":0,
"slaves":0,
"total":0
},
"init":{
"sessions":0,
"slaves":0,
"total":0
},
"master":{
"sessions":1,
"slaves":0,
"total":1
},
"master(owner)":{
"sessions":0,
"slaves":0,
"total":0
}
},
"virtual_addresses_active":1,
"virtual_addresses_inactive":0,
"vritual_addresses_total":1
},
"num_tracked_objects":2,
"tracked_objects_down":2,
"tracked_objects_up":0
}
}
|
n = int(input('Insira um número: '))
print('_' * 12)
print(f'{n} X 1 = {n*1}')
print(f'{n} X 2 = {n*2}')
print(f'{n} X 3 = {n*3}')
print(f'{n} X 4 = {n*4}')
print(f'{n} X 5 = {n*5}')
print(f'{n} x 6 = {n*6}')
print(f'{n} X 7 = {n*7}')
print(f'{n} X 8 = {n*8}')
print(f'{n} X 9 = {n*9}')
print(f'{n} X 10 = {n*10}')
print('_' * 12)
|
class Stack():
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
s=Stack()
s.isEmpty()
s.push(5)
s.push(56)
s.push('sdfg')
s.push(9)
print(s.peek())
print(s.pop())
print(s.peek())
print(s.size())
|
hola = True
adiosguillermomurielsanchezlafuente = True
if (adiosguillermomurielsanchezlafuente
and hola):
print("ok con nombre muy largo")
|
for i in range(1, int(input()) + 1):
quadrado = i ** 2
cubo = i ** 3
print(f'{i} {quadrado} {cubo}')
print(f'{i} {quadrado + 1} {cubo + 1}')
|
Scale.default = Scale.chromatic
Root.default = 0
Clock.bpm = 120
var.ch = var(P[1,5,0,3],8)
~p1 >> play('m', amp=.8, dur=PDur(3,8), rate=[1,(1,2)])
~p2 >> play('-', amp=.5, dur=2, hpf=2000, hpr=linvar([.1,1],16), sample=1).often('stutter', 4, dur=3).every(8, 'sample.offadd', 1)
~p3 >> play('{ ppP[pP][Pp]}', amp=.8, dur=.5, sample=PRand(7), rate=PRand([.5,1,2]))
~p4 >> play('V', amp=.8, dur=1)
~p5 >> play('#', amp=1.2, dur=16, drive=.1, chop=128, formant=1)
~s1 >> glass(var.ch+(0,5,12), amp=1, dur=8, coarse=8)
~s2 >> piano(var.ch+(0,[5,5,3,7],12), amp=1, dur=8, delay=(0,.25,.5))
Group(p1, p2, p3).stop()
p4.lpf = linvar([4000,10],[32,0])
p4.stop()
s2.stop()
~s3 >> saw(var.ch+PWalk(), amp=PRand([0,.8])[:24], dur=PDur(3,8), scale=Scale.minor, oct=PRand([4,5,6])[:32], drive=.05, room=1, mix=.5).spread()
~s3 >> saw(var.ch+PWalk(), amp=PRand([0,.8])[:20], dur=PDur(5,8), scale=Scale.minor, oct=PRand([4,5,6])[:32], drive=.05, room=1, mix=.5).spread()
~s3 >> saw(var.ch+PWalk(), amp=PRand([0,.8])[:64], dur=.25, scale=Scale.minor, oct=PRand([4,5,6])[:32], drive=.05, room=1, mix=.5).spread()
~p4 >> play('V', amp=.5, dur=1, room=1, lpf=1200).every(7, 'stutter', cycle=16)
~p6 >> play('n', amp=.5, dur=1, delay=.5, room=1, hpf=linvar([2000,4000],16), hpr=.1)
s1.oct = 4
s1.formant = 1
~p3 >> play('{ ppP[pP][Pp]}', amp=.5, dur=.5, sample=PRand(7), rate=PRand([.5,1,2]), room=1, mix=.25)
Group(p6, s3).stop()
~s2 >> piano(var.ch+([12,0],[5,5,3,7],[0,12]), amp=1, dur=8, delay=(0,.25,.5), room=1, mix=.5, drive=.05, chop=32, echo=[1,2,1,4])
Group(p3, s1).stop()
Clock.clear()
|
def namedArgumentFunction(a, b, c):
print("the values are a: {}, b: {}, c: {}".format(a,b,c))
namedArgumentFunction(100, 200, 300) # positional arguments
namedArgumentFunction(c=3, a=1, b=2) # named arguments
#namedArgumentFunction(181, a=102, b=103) # mix of position + name error
namedArgumentFunction(101, b=102, c=103) # mix of position + no error |
# Basic String Operations (Title)
# Reading
# Iterating over a String with the 'for' Loop (section)
# General Format:
# for variable in string:
# statement
# statement
# etc.
name = 'Juliet'
for ch in name:
print(ch)
# This program counts the number of times the letter T
# (uppercase or lowercase) appears in a string.
# (with 'for' loop)
def main():
count = 0
my_string = input('Enter a sentence: ')
for ch in my_string:
if ch == 'T' or ch == 't':
count += 1
print(f'The letter T appears {count} times.')
if __name__ == '__main__':
main()
# Indexing (section)
my_string = 'Roses are red'
ch = my_string[6]
my_string = 'Roses are red'
print(my_string[0], my_string[6], my_string[10])
# negative numbers
my_string = 'Roses are red'
print(my_string[-1], my_string[-2], my_string[-13])
# IndexError Exceptions (section)
# Occur if index out of range for a particular string
city = 'Boston'
print(city[6])
city = 'Boston'
index = 0
while index < 7:
print(city[index])
index += 1
# The 'len' Function (section)
# useful to prevent loops from iterating beyond the end
# of a string.
city = 'Boston'
size = len(city)
print(size)
city = 'Boston'
index = 0
while index < len(city):
print(city[index])
index += 1
# String Concatenation (section)
name = 'Kelly'
name += ' '
name += 'Yvonne'
name += ' '
name += 'Smith'
print(name)
# Strings are immutable (section)
# This program concatenates strings.
def main():
name = 'Carmen'
print(f'The name is: {name}')
name = name + ' Brown'
print(f'Now the name is: {name}')
if __name__ == '__main__':
main()
# no string[index] on left side of an assignment operator
# Error below
friend = 'Bill'
friend[0] = 'J'
# End
# Checkpoint
# 8.1 Assume the variable 'name' references a string. Write a
# 'for' loop that prints each character in the string.
name = 'name'
for letter in name:
print(letter)
# 8.2 What is the index of the first character in a string?
# A. 0
# 8.3 If a string has 10 characters, what is the index of the
# last character?
# A. 9
# 8.4 What happeneds if you try to use an invalid index to
# access a character in a string?
# A. An IndexError exception will occur if you try to use an
# index that is out of range for a particular string.
# 8.5 How do you find the length of a string?
# A. Use the built-in len function.
# 8.6 What is wrong with the following code?
animal = 'Tiger'
animal [0] = 'L'
# A. The second statement attempts to assign a value to an
# individual character in the string. Strings are immutable,
# however, so the expression animal [0] cannot appear on the
# left side of an assignment operator.
# End |
height = int(input())
apartments = int(input())
is_first = True
isit = 0
for f in range(height, 0, -1):
for s in range(0, apartments, 1):
if is_first == True:
isit += 1
print(f"L{f}{s}", end=" ")
if isit == apartments:
is_first = False
continue
if is_first == False:
if f % 2 == 0:
print(f"O{f}{s}", end=" ")
else:
print(f"A{f}{s}", end=" ")
print(end="\n")
|
"""
Dominator Problem
by Codility
Solution by B Hamilton
An array A consisting of N integers is given.
The dominator of array A is the value that occurs in more than half of the
elements of A.
Write a function that, given an array A consisting of N integers, returns
index of any element of array A in which the dominator of A occurs.
The function should return −1 if array A does not have a dominator.
(Given) Assume that:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range
[−2,147,483,648..2,147,483,647].
Target Complexity: Time O(N) oor O(NlogN) | Space O(1)
Task Score: 83% | Correctness: 75% | Performance 100%
"""
def solution(A):
# I think I cna use a hassh table here,
# but that will make a solution that is O(N) or worse
# I may not know how to do so, anyway...
# I will try a greedy math-based algorithm
# Key intuition is that the max will have
# as many coutns as all the others combined, except 1.
# and so every time we change to a number that isn't the max,
# decrease the count
# every time we repeat a number, increase the count
# In the end, the sum should be 1ish.
# a,b,c,a,a,d,a,a 1, -1, -1, -1, +1, +1, -1, -1, + 1 = -1
# may need to do a every time we change the number that is not the
# 'max', decrease by 1.
# If A[0], get Id (i.e. a) and Ct (+1)
# A[1], Id (!=a) so Ct 7483-1
# A[2] Id [!=a]
# Constraints
if len(A) < 0 or len(A) > 100000 or A == []:
return -1
#if any(A < -2147483648) or any(A > 2147483647):
# return -1
dominator = None
dominator_count = 0
dominator_indices = []
if len(A) == 0:
return -1
for i in range(len(A)): # an O(N) operation
#any time the count is 0...
#the incoming number becomes the dominator
#and increment the count by 1
if dominator_count == 0:
dominator = A[i]
#dominator_indices.append(i)
dominator_count += 1
# if the incoming number is the same as the dominator
# increment by 1
# appemd the index
elif A[i] == dominator:
dominator_count += 1
#dominator_indices.append(i)
# incoming number is the same as the dominator
# decrement by 1. If this reduces it to 0, the dominator
# will change on the next pass.
# pop the end of the stack
else:
dominator_count -= 1
#dominator_indices.pop()
# A second O(n) operation
dominator_indices= [idx for idx, num in enumerate(A) if num == dominator]
# What happens when we end with dominator_count = 0?
# edge cases where failed
# all different, non-dominator.
# need to double check the length is big enough!
if len(dominator_indices) == 0:
dominator_indices = [-1]
elif len(dominator_indices) < round(len(A)/2):
dominator_indices = [-1]
#print(dominator_indices)
# I can generate the indices, but it will not let me
# Maybe it allows me to return ANY of the indices
return dominator_indices[0]
# Test Cases that failed:
# any wher len(A) %2 == 0, split 50/50
# half elements the same, and half + 1 elements the same (got 10/20 for value 2,
# but 2 needed 11 to be the dominator
#
# N/2 values of 1, N even + [0,0,1,1,1] (for N = 4, not sure how this works)
#
#
|
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/twice-counter/0
def sol(words):
h = {}
res = 0
for word in words:
h[word] = h[word] + 1 if word in h else 1
for word in h:
if h[word] == 2:
res+=1
return res |
class Solution:
# Reverse Format String (Accepted), O(1) time and space
def reverseBits(self, n: int) -> int:
s = '{:032b}'.format(n)[::-1]
return int(s, 2)
# Bit Manipulation (Top Voted), O(1) time and space
def reverseBits(self, n: int) -> int:
ans = 0
for i in range(32):
ans = (ans << 1) + (n & 1)
n >>= 1
return ans
|
def count_frequency(a):
freq = dict()
for items in a:
freq[items] = a.count(items)
return freq
def solution(data, n):
frequency = count_frequency(data)
for key, value in frequency.items():
if value > n:
data = list(filter(lambda a: a != key, data))
return data
print(solution([1, 2, 3], 0))
print(solution([5, 10, 15, 10, 7], 1))
print(solution([1, 2, 2, 3, 3, 3, 4, 5, 5], 1))
|
# Copyright 2020 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.
# [START root_tag]
# [START nested_tag]
def nested_method():
return 'nested'
# [END nested_tag]
def root_method():
return 'root'
# [END root_tag]
# [START root_tag]
def another_root_method():
return 'another root'
# [END root_tag]
|
inventory = {'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1}
print(f'{inventory =}')
stock_list = inventory.copy()
print(f'{stock_list =}')
stock_list['hot cheetos'] = 25
stock_list.update({'cookie' : 18})
stock_list.pop('cake')
print(f'{stock_list =}') |
#Program to change a given string to a new string where the first and last chars have been exchanged.
string=str(input("Enter a string :"))
first=string[0] #store first index element of string in variable
last=string[-1] #store last index element of string in variable
new=last+string[1:-1]+first #concatenate last the middle part and first part
print(new)
|
"""
Class hierarchy for company management
"""
class Company:
def __init__(self, company_name, location):
self.company_name = company_name
self.location = location
def __str__(self):
return f"Company: {self.company_name}, {self.location}"
def __repr(self):
return f"Company: {self.company_name}, {self.location}"
class Management(Company):
def __init__(self, company_name, location, employee, position, management_type, **kwargs):
self.management_type = management_type
self.employee = employee
self.position = position
super().__init__(company_name, location)
def __str__(self):
return f"{self.employee}: {self.position} in {self.management_type} management at {self.company_name}"
def __repr__(self):
return f"{self.employee}: {self.position} in {self.management_type} management at {self.company_name}"
def type(self):
return f"{self.management_type}"
def position(self):
return f"{self.position}"
class TopLevelManagement(Management):
def __init__(self, company_name, location, employee, position, **kwargs):
super().__init__(company_name, location, employee, position, management_type='Top level', **kwargs)
@classmethod
def chairman(cls) -> 'TopLevelManagement':
return cls('Xamarin Ltd', 'John Doe', 'Chairman', 'United States')
@classmethod
def vice_president(cls) -> 'TopLevelManagement':
return cls('Xamarin Ltd', 'Jane Doe', 'Vice President', 'United States')
@classmethod
def ceo(cls) -> 'TopLevelManagement':
return cls('Xamarin Ltd', 'Jeanne Donne', 'CEO', 'United States')
class MiddleManagement(Management):
def __init__(self, company_name, location, employee, position, **kwargs):
super().__init__(company_name, location, employee, position, management_type='Middle', **kwargs)
@classmethod
def general_manager(cls) -> 'MiddleManagement':
return cls('Xamarin Ltd', 'Aran Diego', 'General Manager', 'United States')
@classmethod
def regional_manager(cls) -> 'MiddleManagement':
return cls('Xamarin Ltd', 'Antuan Doe', 'General Manager', 'United States')
class FirstLineManagement(Management):
def __init__(self, company_name, location, employee, position, **kwargs):
super().__init__(company_name, location, employee, position, management_type='First line', **kwargs)
@classmethod
def supervisor(cls) -> 'FirstLineManagement':
return cls('Xamarin Ltd', 'Sam Pauline', 'Supervisor', 'United States')
@classmethod
def office_manager(cls) -> 'FirstLineManagement':
return cls('Xamarin Ltd', 'Sarah Jones', 'Office Manager', 'United States')
@classmethod
def team_leader(cls) -> 'FirstLineManagement':
return cls('Xamarin Ltd', 'Amy Joe', 'Team Leader', 'United States')
def main():
company = Company('Xamarin Ltd', 'United States')
print(company)
chairman = TopLevelManagement.chairman()
print(chairman)
ceo = TopLevelManagement.ceo()
print(ceo)
general_manager = MiddleManagement.general_manager()
print(general_manager)
regional_manager = MiddleManagement.regional_manager()
print(regional_manager)
supervisor = FirstLineManagement.supervisor()
print(supervisor)
office_manager = FirstLineManagement.office_manager()
print(office_manager)
team_leader = FirstLineManagement.team_leader()
print(team_leader)
if __name__ == '__main__':
main()
|
# Make sure to rename this file as "config.py" before running the bot.
verbose=True
api_token='0000000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# Enter the user ID and a readable name for each user in your group.
# TODO make balaguer automatically collect user IDs.
# But that's only useful if the bot actually gathers widespread usage.
all_users={
000000000: 'Readable Name',
000000000: 'Readable Name',
000000000: 'Readable Name',
000000000: 'Readable Name',
}
# A list containing the user IDs of who can access the admin features of the bot.
admins = [000000000,
000000000,
000000000,
000000000]
# A list of the groups where the bot is allowed to operate (usually the main group and an admin test group)
approved_groups = [-000000000,
-000000000] |
# if语句
games = ['CS GO', 'wow', 'deathStranding']
for game in games:
if game == 'wow': # 判断是否相等用'=='
print(game.upper())
# 检查是否相等
sport = 'football'
if sport == 'FOOTBALL':
print('yes')
else:
print('No') # 此处输出结果为No说明大小写不同不被认同是同一string、转化为小写在进行对比
for game in games:
if game.lower() == 'cs go':
print('是cs go了')
# 检查是否不相等
for game in games:
if game != 'wow':
print('该游戏不是wow,该游戏是' + game)
else:
print('该游戏是wow')
# 比较数字
ages = [15, 31, 22, 18]
for age in ages:
if age >= 18:
print('已成年')
else:
print('未成年')
# 使用and检查多个条件
i = 17
j = 21
if i > 18 and j > 18:
print('\n两者都已成年')
else:
print('\n有未成年混入其中')
# 使用or也能检查多个条件 、只不过只要满足其中任意一个就会返回、两个选项都不满足时返回False
i = 17
j = 12
if i > 18 or j > 18:
print('\n两者里有成年人')
else:
print('\n都是未成年')
# 检查特定值是否存在可以选择用in
if 'wow' in games:
print('\nwow已经在游戏库中')
else:
games.append('OverWatch')
print('\nwow不在库中,现已经添加进去')
if 'OverWatch' in games:
print('\n守望先锋已经在游戏库中')
else:
games.append('OverWatch')
print('\nOverWatch不在库中,现已经添加进去')
# if-elif-else结构
age = 4
if age <= 4:
price = 0
elif 4 < age <= 18:
price = 25
else:
price = 50
print('您的票价为:' + str(price) + '元,谢谢参观!')
# 多个elif代码块
age = 31
if age <= 4:
price = 0
elif 4 < age <= 18:
price = 5
elif 18 < age < 65:
price = 10
elif 65 <= age:
price = 5
print('\n购买票价为:' + str(price) + '元 谢谢参观!')
ob = ['雕哥', '宝哥', '龙神', '胖头', '大狗', '大Mu', '核桃', '谢彬', '马甲', '566']
for player in ob:
if player == '谢彬':
print('谢彬是谁???')
elif player == '胖头':
print('法国士兵!!!')
else:
print(player + 'nb!!!')
# 检查列表是否为空
games = []
if games:
for game in games:
print('\n圣诞大折扣所要购买的游戏有:')
else:
print('\n购物车中没有任何游戏、快去添加吧!')
# 使用多个列表
my_games = ['Dota2', 'CS GO', 'WOW', 'Over Watch', 'Death Stranding', 'Cyberpunk2077', 'Dark Dungeon']
fri_games = ['Dota2', 'CS GO', 'WOW', 'lol']
for fri_game in fri_games:
if fri_game in my_games:
print('我们共同喜欢的游戏有:' + fri_game.upper())
else:
print('我不喜欢玩' + fri_game.upper() + '但是她好像蛮喜欢的')
|
print ("--------------------------------------------------------")
print ("-------------Bienvenido a la Temperatura----------------")
print ("--------------------------------------------------------\n")
x = 0
while x < 10000:
print ("Elige tus opciones:")
print ("(1) Convertir de °C a °F")
print ("(2) Convertir de °C a °K")
print ("(3) Convertir de °F a °C")
print ("(4) Convertir de °F a °K")
print ("(5) Convertir de °K a °C")
print ("(6) Convertir de °K a °F\n")
op = int(input("Elige una opcion de acuerdo a su numero: "))
if op ==1:
r11 = int(input("Escriba el numero que quiere convertir: "))
var11 = r11
var12 = var11 * 1.8
var13 = var12 + 32
print ("°F =", var11, "x 1.8 + 32\n°F =", var12,"+ 32\n°F =", var13,"\n")
elif op ==2:
r12 = int(input("Escriba el numero que quiere convertir: "))
var21 = r12
var22 = var21 + 273
print ("°K =", var21, "-273\n°K =", var22,"\n")
elif op ==3:
r13 = int(input("Escriba el numero que quiere convertir: "))
var31 = r13
var32 = var31 - 32
var33 = var32 / 1.8
print ("°C = (", var31,"- 32 ) / 1.8\n°C =", var32, "/ 1.8\n°C =", var33, "\n")
elif op ==4:
r14 = int(input("Escriba el numero que quiere convertir: "))
var41 = r14
var42 = var41 - 32
bla = 0.5 * var42
var43 = bla + 273
print ("°K = 5/9 (", var41,"- 32 ) + 273\n°K = 5/9", var42, "+ 273\n°K = 0.5 x", var42,"+ 273\n°K =",var43, "\n")
elif op ==5:
r15 = int(input("Escriba el numero que quiere convertir: "))
var51 = r15
var52 = var51 - 273
print ("El resultado es: ", var52)
elif op ==6:
r16 = int(input("Escriba el numero que quiere convertir: "))
var61 = r16
var62 = var61 - 273
num = 1.8 * var62
var63 = num + 32
print ("El resultado es: ", var63)
else:
print ("Esta opcion no existe, ingrese una nueva opcion...")
x = x + 1
|
class GameException(Exception):
pass
class GameFlowException(GameException):
pass
class EndProgram(GameFlowException):
pass
class InvalidPlayException(GameException):
pass
|
# Copyright 2018 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Partial response utilities for an Endpoints v1 over webapp2 service.
Grammar of a fields partial response string:
fields: selector [,selector]*
selector: path [(fields)]?
path: name [/name]*
name: [A-Za-z_][A-Za-z0-9_]* | \*
Examples:
fields=a
Response includes the value of the "a" field.
fields=a,b
Response includes the values of the "a" and "b" fields.
fields=a/b
Response includes the value of the "b" field of "a". If "a" is an array,
response includes the values of the "b" fields of every element in the array.
fields=a/*/c
For every element or field of "a", response includes the value of that element
or field's "c" field.
fields=a(b,c)
Equivalent to fields=a/b union fields=a/c.
"""
class ParsingError(Exception):
"""Indicates an error during parsing.
Fields:
index: The index the error occurred at.
message: The error message.
"""
def __init__(self, index, message):
super(ParsingError, self).__init__('%d: %s' % (index, message))
self.index = index
self.message = message
def _merge(source, destination):
"""Recursively merges the source dict into the destination dict.
Args:
source: A dict whose values are source dicts.
destination: A dict whose values are destination dicts.
"""
for key, value in source.iteritems():
if destination.get(key):
_merge(value, destination[key])
else:
destination[key] = value
class _ParsingContext(object):
"""Encapsulates parsing information.
Attributes:
accumulator: A list of field name characters accumulated so far.
expecting_name: Whether or not a field name is expected.
fields: A dict of accumulated fields.
"""
def __init__(self):
"""Initializes a new instance of ParsingContext."""
# Pointer to the subfield dict of the last added field.
self._last = None
self.accumulator = []
self.expecting_name = True
self.fields = {}
def accumulate(self, char):
"""Accumulates the given char.
Args:
char: The character to accumulate.
"""
# Accumulate all characters even if they aren't allowed by the grammar.
# In the worst case there will be extra keys in the fields dict which will
# be ignored when the mask is applied because they don't match any legal
# field name. It won't cause incorrect masks to be applied. The exception is
# / which has special meaning. See add_field below. Note that * has special
# meaning while applying the mask but not while parsing. See _apply below.
self.accumulator.append(char)
def add_field(self, i):
"""Records the field name in the accumulator then clears the accumulator.
Args:
i: The index the parser is at.
"""
# Reset the index to the start of the accumulated string.
i -= len(self.accumulator)
path = ''.join(self.accumulator).strip()
if not path:
raise ParsingError(i, 'expected name')
# Advance i to the first non-space char.
for char in self.accumulator:
if char != ' ':
break
i += 1
# / has special meaning; a/b/c is shorthand for a(b(c)). Add subfield dicts
# recursively. E.g. if the fields dict is empty then parsing a/b/c is like
# setting fields["a"] = {"b": {"c": {}} and pointing last to c's value.
pointer = self.fields
for part in path.split('/'):
if not part:
raise ParsingError(i, 'empty name in path')
pointer = pointer.setdefault(part, {})
# Increment the index by the length of this part as well as the /.
i += len(part) + 1
self._last = pointer
self.accumulator = []
def add_subfields(self, subfields):
"""Adds the given subfields to the last added field.
Args:
subfields: A dict of accumulated subfields.
Returns:
False if there was no last added field to add subfields to, else True.
"""
if self._last is None:
return False
_merge(subfields, self._last)
return True
def _parse(fields):
"""Parses the given partial response string into a partial response mask.
Args:
fields: A fields partial response string.
Returns:
A dict which can be used to mask another dict.
Raises:
ParsingError: If fields wasn't a valid partial response string.
"""
stack = [_ParsingContext()]
i = 0
while i < len(fields):
# Invariants maintained below.
# Stack invariant: The stack always has at least one context.
assert stack, fields
# Accumulator invariant: Non-empty accumulator implies expecting a name.
assert not stack[-1].accumulator or stack[-1].expecting_name, fields
if fields[i] == ',':
# If we just returned from a lower context, no name is expected.
if stack[-1].expecting_name:
stack[-1].add_field(i)
stack[-1].expecting_name = True
elif fields[i] == '(':
# Maintain accumulator invariant.
# A name must occur before any (.
stack[-1].add_field(i)
stack[-1].expecting_name = False
# Enter a new context. When we return from this context we don't expect to
# accumulate another name. There must be , or a return to a higher context
# (or the end of the string altogether).
stack.append(_ParsingContext())
elif fields[i] == ')':
# If we just returned from a lower context, no name is expected.
if stack[-1].expecting_name:
stack[-1].add_field(i)
# Return to a higher context. Maintain stack invariant.
subfields = stack.pop().fields
if not stack:
# Mismatched ().
raise ParsingError(i, 'unexpected )')
# See accumulator invariant maintenance above.
assert not stack[-1].expecting_name, fields
if not stack[-1].add_subfields(subfields):
# ) before any field.
raise ParsingError(i, 'unexpected (')
else:
# If we just returned from a lower context, no name is expected.
if not stack[-1].expecting_name:
raise ParsingError(i, 'unexpected name')
stack[-1].accumulate(fields[i])
i += 1
if len(stack) != 1:
# Mismatched ().
raise ParsingError(i, 'expected )')
# If we just returned from a lower context, no name is expected.
if stack[-1].expecting_name:
stack[-1].add_field(i)
return stack[0].fields
def _apply(response, partial):
"""Applies the given partial response dict to the given response.
Args:
response: A dict to be updated in place.
partial: A partial response dict as returned by _parse. May be modified,
but will not have its masking behavior changed.
Returns:
The masked response.
"""
for key, value in response.items():
pointer = None
if key in partial:
if partial[key]:
# If the subfield dict is non-empty, include all of *'s subfields.
_merge(partial.get('*', {}), partial[key])
pointer = partial[key]
elif '*' in partial:
pointer = partial['*']
if pointer is None:
response.pop(key)
elif pointer:
if isinstance(value, dict) and value:
_apply(value, pointer)
if not value:
# No subfields were kept, remove this field.
response.pop(key)
elif isinstance(value, list) and value:
new_values = []
for v in value:
# In a dict constructed from a protorpc.message.Message list elements
# always have the same type. Here we allow list elements to have mixed
# types and only recursively apply the mask to dicts.
if isinstance(v, dict):
_apply(v, pointer)
if v:
# Subfields were kept, include this element.
new_values.append(v)
else:
# Non-dict, include this element.
new_values.append(v)
response[key] = new_values
if not new_values:
# No elements were kept, remove this field.
response.pop(key)
return response
def mask(response, fields):
"""Applies the given fields partial response string to the given response.
Args:
response: A dict encoded using protorpc.protojson.ProtoJson.encode_message
to be updated in place.
fields: A fields partial response string.
Returns:
The masked response.
Raises:
ParsingError: If fields wasn't a valid partial response string.
"""
return _apply(response, _parse(fields))
|
def count_vowels(txt):
vs = "a, e, i, o, u".split(', ')
return sum([1 for t in txt if t in vs])
print(count_vowels('Hello world')) |
class GroupTransform:
"""
GroupTransform
"""
def __init__(self):
pass
def getTransform(self):
pass
def getTransforms(self):
pass
def setTransforms(self, transforms):
pass
def size(self):
pass
def push_back(self, transform):
pass
def clear(self):
pass
def empty(self):
pass
|
class KarmaCard(object):
info = {'type': ['number', 'wild'],
'trait': ['4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A', '2', '3', '10', 'draw'],
'order': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1',
'7:4', '7:3', '7:2', '7:1', '8:4', '8:3', '8:2', '8:1', '9:4', '9:3', '9:2', '9:1',
'J:4', 'J:3', 'J:2', 'J:1', 'Q:4', 'Q:3', 'Q:2', 'Q:1', 'K:1', 'K:2', 'K:3', 'K:4',
'A:1', 'A:2', 'A:3', 'A:4', '2:1', '2:2', '2:3', '2:4', '3:1', '3:2', '3:3', '3:4',
'10:1', '10:2', '10:3', '10:4', 'draw:1'],
'order_start': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1',
'7:4', '7:3', '7:2', '7:1', '8:4', '8:3', '8:2', '8:1', '9:4', '9:3', '9:2', '9:1',
'J:1', 'J:2', 'J:3', 'J:4', 'Q:1', 'Q:2', 'Q:3', 'Q:4', 'K:1', 'K:2', 'K:3', 'K:4',
'A:1', 'A:2', 'A:3', 'A:4', '2:1', '2:2', '2:3', '2:4', '3:1', '3:2', '3:3', '3:4',
'10:1', '10:2', '10:3', '10:4', 'draw:1']
}
def __init__(self, card_type, trait):
''' Initialize the class of UnoCard
Args:
card_type (str): The type of card
trait (str): The trait of card
'''
self.type = card_type
self.trait = trait
self.str = self.get_str()
def get_str(self):
''' Get the string representation of card
Return:
(str): The string of card's trait
'''
return self.trait
def get_index(self):
''' Get the index of trait
Return:
(int): The index of card's trait (value)
'''
return self.info['trait'].index(self.trait)
@staticmethod
def print_cards(cards):
''' Print out card in a nice form
Args:
card (str or list): The string form or a list of a Karma card
'''
if isinstance(cards, str):
cards = [cards]
for i, card in enumerate(cards):
print(card, end='')
if i < len(cards) - 1:
print(', ', end='')
|
#!/usr/bin/env python
# pylint: disable=too-few-public-methods
"""Reusable string literals."""
class DockerAuthentication:
"""
https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md
https://github.com/docker/distribution/blob/master/docs/spec/auth/scope.md
"""
DOCKERHUB_URL_PATTERN = (
"{0}?service={1}&scope={2}&client_id=docker-registry-client-async"
)
SCOPE_REGISTRY_CATALOG = "registry:catalog:*"
SCOPE_REPOSITORY_PULL_PATTERN = "repository:{0}:pull"
SCOPE_REPOSITORY_PUSH_PATTERN = "repository:{0}:push"
SCOPE_REPOSITORY_ALL_PATTERN = "repository:{0}:pull,push"
class DockerMediaTypes:
"""https://github.com/docker/distribution/blob/master/docs/spec/manifest-v2-2.md#manifest-list"""
CONTAINER_IMAGE_V1 = "application/vnd.docker.container.image.v1+json"
DISTRIBUTION_MANIFEST_LIST_V2 = (
"application/vnd.docker.distribution.manifest.list.v2+json"
)
DISTRIBUTION_MANIFEST_V1 = "application/vnd.docker.distribution.manifest.v1+json"
DISTRIBUTION_MANIFEST_V1_SIGNED = (
"application/vnd.docker.distribution.manifest.v1+prettyjws"
)
DISTRIBUTION_MANIFEST_V2 = "application/vnd.docker.distribution.manifest.v2+json"
IMAGE_ROOTFS_DIFF = "application/vnd.docker.image.rootfs.diff.tar.gzip"
IMAGE_ROOTFS_FOREIGN_DIFF = (
"application/vnd.docker.image.rootfs.foreign.diff.tar.gzip"
)
PLUGIN_V1 = "application/vnd.docker.plugin.v1+json"
class Indices:
"""Common registry indices."""
DOCKERHUB = "index.docker.io"
QUAY = "quay.io"
class QuayAuthentication:
"""
https://docs.quay.io/api/
"""
QUAY_URL_PATTERN = (
"{0}?service={1}&scope={2}&client_id=docker-registry-client-async"
)
SCOPE_REPOSITORY_PULL_PATTERN = "repo:{0}:read"
SCOPE_REPOSITORY_PUSH_PATTERN = "repo:{0}:write"
SCOPE_REPOSITORY_ALL_PATTERN = "repo:{0}:read,write"
class MediaTypes:
"""Generic mime types."""
APPLICATION_JSON = "application/json"
APPLICATION_OCTET_STREAM = "application/octet-stream"
APPLICATION_YAML = "application/yaml"
class OCIMediaTypes:
"""https://github.com/opencontainers/image-spec/blob/master/media-types.md"""
DESCRIPTOR_V1 = "application/vnd.oci.descriptor.v1+json"
IMAGE_CONFIG_V1 = "application/vnd.oci.image.config.v1+json"
IMAGE_INDEX_V1 = "application/vnd.oci.image.index.v1+json"
IMAGE_LAYER_V1 = "application/vnd.oci.image.layer.v1.tar"
IMAGE_LAYER_GZIP_V1 = "application/vnd.oci.image.layer.v1.tar+gzip"
IMAGE_LAYER_ZSTD_V1 = "application/vnd.oci.image.layer.v1.tar+zstd"
IMAGE_LAYER_NONDISTRIBUTABLE_V1 = (
"application/vnd.oci.image.layer.nondistributable.v1.tar"
)
IMAGE_LAYER_NONDISTRIBUTABLE_GZIP_V1 = (
"application/vnd.oci.image.layer.nondistributable.v1.tar+gzip"
)
IMAGE_LAYER_NONDISTRIBUTABLE_ZSTD_V1 = (
"application/vnd.oci.image.layer.nondistributable.v1.tar+zstd"
)
IMAGE_MANIFEST_V1 = "application/vnd.oci.image.manifest.v1+json"
LAYOUT_HEADER_V1 = "application/vnd.oci.layout.header.v1+json"
|
def test_see_for_top_level(result):
assert (
"usage: vantage [-a PATH] [-e NAME ...] [-v KEY=[VALUE] ...] [--verbose] [-h] COMMAND..."
in result.stdout_
)
|
"""
Given an array of numbers sorted in ascending order, find the range of a given number ‘key’.
The range of the ‘key’ will be the first and last position of the ‘key’ in the array.
Write a function to return the range of the ‘key’. If the ‘key’ is not present return [-1, -1].
Example 1:
Input: [4, 6, 6, 6, 9], key = 6
Output: [1, 3]
Example 2:
Input: [1, 3, 8, 10, 15], key = 10
Output: [3, 3]
Example 3:
Input: [1, 3, 8, 10, 15], key = 12
Output: [-1, -1]
"""
def number_range(nums, key):
start, end = -1, -1
left, right = 0, len(nums)-1
while left < right:
mid = (left + right) >> 1
if nums[mid] < key:
left = mid + 1
else:
right = mid
start = left
if nums[start] != key:
return [-1, -1]
left, right = 0, len(nums)-1
while left < right:
mid = (left + right + 1) >> 1
if nums[mid] > key:
right = mid - 1
else:
left = mid
end = right
return [start, end]
if __name__ == "__main__":
print(number_range([4, 6, 6, 6, 9], key = 6))
print(number_range([1, 3, 8, 10, 15], key = 10))
print(number_range([1, 3, 8, 10, 15], key = 12)) |
def wordBreakDP(word, dic):
n = len(word)
if word in dic:
return True
if len(dic) == 0:
return False
dp = [False for i in range(n + 1)]
dp[0] = True
for i in range(1, n + 1):
for j in range(i - 1, -1, -1):
if dp[j] == True:
substring = word[j:i]
if substring in dic:
dp[i] = True
break
return dp[-1]
def wordBreakRecursive(word, dic, startIndex=0):
if word in dic:
return True
if len(dic) == 0:
return false
if startIndex == len(word):
return True
for endIndex in range(startIndex + 1, len(word) + 1):
if word[startIndex: endIndex] in dic and wordBreakRecursive(word, dic, endIndex):
return True
return False
def wordBreakMemo(word, dic, startIndex=0, memo=None):
if word in dic:
return True
if len(dic) == 0:
return False
if memo == None:
memo = dict()
if startIndex in memo:
return memo[startIndex]
for endIndex in range(startIndex + 1, len(word) + 1):
if word[startIndex: endIndex] in dic and wordBreakRecursive(word, dic, endIndex):
memo[startIndex] = True
return memo[startIndex]
memo[startIndex] = False
return memo[startIndex]
word = "papapapokerface"
dic = {"pa", "poker", "face"}
print(wordBreakDP(word, dic))
print(wordBreakRecursive(word, dic))
print(wordBreakMemo(word, dic))
|
s = "Olá, mundo!";
print(s[::2]); # Imprime os caracteres nos índices pares.
print(s[1::2]) # Imprime os caracteres nos índices ímpares.
frase = "Mundo mundo vasto mundo"
print(frase[::-1]); #inverte a frase;
# Forma mais avançada de formatação de strings
frase_2 = "Um triângulo de base igual a {0} e altura igual a {1} possui área igual {2}.".format(3,4,12);
print(frase_2);
# Formatação de strongs com f-strings
linguagem = "Python";
frase_3 = f"Progamando em {linguagem}";
print(frase_3);
|
file1= "db_breakfast_menu.txt"
file2= "db_lunch_menu.txt"
file3= "db_dinner_menu.txt"
file4 = "db_label_text.txt"
retail = []
title = []
label = []
with open(file1, "r") as f:
data = f.readlines()
for line in data:
w = line.split(":")
title.append(w[1])
for line in data:
w = line.split("$")
price = w[1]
price.rstrip('\n')
conv = float(price)
retail.append(conv)
f.close()
with open (file4, "r") as f:
data = f.readlines()
for line in data:
i = 1
w = line.split(":")
string1 = w[i]
i+=1
string2 = w[i]
string = ("%s\n%s" %(string1,string2))
label.append(string)
f.close()
|
class Guesser:
def __init__(self, number, lives):
self.number = number
self.lives = lives
def guess(self,n):
if self.lives < 1:
raise Exception("Omae wa mo shindeiru")
match = n == self.number
if not match:
self.lives -= 1
return match |
def get_assign(user_input):
key, value = user_input.split("gets")
key = key.strip()
value = int(value.strip())
my_dict[key] = value
print(my_dict)
def add_values(num1, num2):
return num1 + num2
print("Welcome to the Adder REPL.")
my_dict = dict()
while True:
user_input = input("???")
if 'gets' in user_input:
get_assign(user_input)
if 'input' in user_input:
print("Enter a value for :")
input_assign()
if 'adds' in user_input:
a, b = user_input.split("adds")
if 'print' in user_input:
print_values()
if 'quit' in user_input:
print("GoodBye")
exit() |
"""
Solution for
Sort Integers by The Power Value: https://leetcode.com/problems/sort-integers-by-the-power-value/
"""
class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
# Can I calculate the power of an integer?
# if two ints have same power, sort by the ints
# power of 1 = 0 steps
# [1] -> 1
# no zeros for now
# assume no negatives
def calculate_steps(range_int: int) -> int: # i = range_int
# init a variable to count the number of steps at 0
steps = 0
# iterate while the number not equal to zero
while range_int != 1:
# transform it using the right eq, based on even or odd
if range_int % 2 == 0:
range_int /= 2
else: # should be odd
range_int = 3 * range_int + 1
steps += 1
# return the steps
return steps
"""
steps = 9
range_int = 1
"""
power_ints = dict()
# n = hi - lo + 1
# iterate over all the integers in the range
for num in range(lo, hi + 1): # n iterations
# calulate the power of the integer
power = calculate_steps(num)
# map each integer of the power -> range_int
if power in power_ints: # O(1)
power_ints[power].append(num)
else:
power_ints[power] = [num]
# sort the range ints into an seq, based on the powers
sorted_powers = sorted(power_ints) # O(n log n)
sorted_ints = list()
for power in sorted_powers: # n iterations
ints = power_ints[power]
ints.sort()
sorted_ints.extend(ints) #
# return the k - 1 element
return sorted_ints[k - 1]
# Time O(n * calculate_power + n log n)
# Space O(n)
"""
"""
"""
lo = 12
hi = 15
k = 2
power_ints = {
9: [12, 13]
17: [14, 15]
}
sorted_powers = [9, 17]
sorted_ints = [12, 13, 14, 15]
ints = [14, 15]
power = 17
num = 12
power = 9
"""
|
try:
for i in ['a', 'b', 'c']:
print(i ** 2)
except TypeError:
print("An error occured!")
x = 5
y = 0
try:
z = x /y
print(z)
except ZeroDivisionError:
print("Can't devide by zero")
finally:
print("All done")
def ask():
while True:
try:
val = int(input("Input an integer: "))
except:
print("An error occured! Please try again")
else:
break
print("Thank you, you number sqared is: ", val ** 2)
ask()
|
NR_CLASSES = 10
hyperparameters = {
"number-epochs" : 30,
"batch-size" : 100,
"learning-rate" : 0.005,
"weight-decay" : 1e-9,
"learning-decay" : 1e-3
}
|
class DoublyLinkedList:
""" Private Node Class """
class _Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return self.value
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def push_beginning(self, value):
node = self._Node(value)
if self.length == 0:
self.head = node
self.tail = node
else:
node.next = self.head
self.head.prev = node
self.head = node
self.length += 1
return True
def push_end(self, value):
node = self._Node(value)
if self.length == 0:
self.head = node
self.tail = node
else:
node.prev = self.tail
self.tail.next = node
self.tail = node
self.length += 1
return True
def push_at_index(self, value, index):
if self._is_empty():
raise IndexError("List is empty")
self._is_out_of_bounds(index)
if index == 0:
self.push_beginning(value)
if index >= self.length - 1:
self.push_end(value)
else:
node = self._Node(value)
i = 0
temp_node = self.head
while i < index - 1:
temp_node = temp_node.next
i += 1
node.next = temp_node.next
temp_node.next.prev = node
node.prev = temp_node
temp_node.next = node
self.length += 1
return True
def remove_beginning(self):
if self._is_empty():
raise IndexError("List is empty")
value = self.head.value
self.head = self.head.next
self.head.prev.next = None
self.head.prev = None
self.length -= 1
return value
def remove_end(self):
if self._is_empty():
raise IndexError("List is empty")
value = self.tail.value
self.tail = self.tail.prev
self.tail.next.prev = None
self.tail.next = None
self.length -= 1
return value
def remove_at_index(self, index):
if self._is_empty():
raise IndexError("List is empty")
self._is_out_of_bounds(index)
if index == 0:
self.remove_beginning()
if index >= self.length - 1:
self.remove_end()
else:
i = 0
temp_node = self.head
while i < index - 1:
temp_node = temp_node.next
i += 1
node_remove = temp_node.next
value = node_remove.value
temp_node.next = node_remove.next
node_remove.next = None
temp_node.next.prev = temp_node
node_remove.prev = None
return value
def get_value_at(self, index):
if self._is_empty():
raise IndexError("List is empty")
self._is_out_of_bounds(index)
i = 0
temp_node = self.head
while i < index:
temp_node = temp_node.next
i += 1
return temp_node.value
def set_value_at(self, value, index):
if self._is_empty():
raise IndexError("List is empty")
self._is_out_of_bounds(index)
i = 0
temp_node = self.head
while i < index:
temp_node = temp_node.next
i += 1
temp_node.value = value
return True
def reverse_list(self):
temp_node_head = self.head
temp_node_tail = self.tail
i = 0
while i < int(self.length / 2):
temp_value = temp_node_tail.value
temp_node_tail.value = temp_node_head.value
temp_node_head.value = temp_value
temp_node_tail = temp_node_tail.prev
temp_node_head = temp_node_head.next
i += 1
return True
""" Helper methods """
def size(self):
return self.length
def _is_empty(self):
return self.length == 0
def _is_out_of_bounds(self, idx):
if idx >= self.length:
raise IndexError('Index out of bounds')
def __str__(self):
temp_node = self.head
lst_str = "["
while temp_node is not None:
lst_str += str(temp_node.value)
if temp_node.next is not None:
lst_str += ","
temp_node = temp_node.next
lst_str += "]"
return lst_str
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.