content
stringlengths 7
1.05M
|
---|
def add_native_methods(clazz):
def initProto____():
raise NotImplementedError()
def socketCreate__boolean__(a0, a1):
raise NotImplementedError()
def socketConnect__java_net_InetAddress__int__int__(a0, a1, a2, a3):
raise NotImplementedError()
def socketBind__java_net_InetAddress__int__boolean__(a0, a1, a2, a3):
raise NotImplementedError()
def socketListen__int__(a0, a1):
raise NotImplementedError()
def socketAccept__java_net_SocketImpl__(a0, a1):
raise NotImplementedError()
def socketAvailable____(a0):
raise NotImplementedError()
def socketClose0__boolean__(a0, a1):
raise NotImplementedError()
def socketShutdown__int__(a0, a1):
raise NotImplementedError()
def socketNativeSetOption__int__boolean__java_lang_Object__(a0, a1, a2, a3):
raise NotImplementedError()
def socketGetOption__int__java_lang_Object__(a0, a1, a2):
raise NotImplementedError()
def socketSendUrgentData__int__(a0, a1):
raise NotImplementedError()
clazz.initProto____ = staticmethod(initProto____)
clazz.socketCreate__boolean__ = socketCreate__boolean__
clazz.socketConnect__java_net_InetAddress__int__int__ = socketConnect__java_net_InetAddress__int__int__
clazz.socketBind__java_net_InetAddress__int__boolean__ = socketBind__java_net_InetAddress__int__boolean__
clazz.socketListen__int__ = socketListen__int__
clazz.socketAccept__java_net_SocketImpl__ = socketAccept__java_net_SocketImpl__
clazz.socketAvailable____ = socketAvailable____
clazz.socketClose0__boolean__ = socketClose0__boolean__
clazz.socketShutdown__int__ = socketShutdown__int__
clazz.socketNativeSetOption__int__boolean__java_lang_Object__ = socketNativeSetOption__int__boolean__java_lang_Object__
clazz.socketGetOption__int__java_lang_Object__ = socketGetOption__int__java_lang_Object__
clazz.socketSendUrgentData__int__ = socketSendUrgentData__int__
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 8 09:45:29 2018
@author: abaena
"""
DATATYPE_AGENT = 'agent'
DATATYPE_PATH_METRICS = 'pathmet'
DATATYPE_LOG_EVENTS = 'logeve'
DATATYPE_LOG_METRICS = 'logmet'
DATATYPE_MONITOR_HOST = 'host'
DATATYPE_MONITOR_MICROSERVICE = 'ms'
DATATYPE_MONITOR_TOMCAT = 'tomc'
DATATYPE_MONITOR_POSTGRES = 'psql'
SOURCE_TYPE_READER = "reader"
SOURCE_TYPE_HOST = "host"
SOURCE_TYPE_SPRINGMICROSERVICE = "spring_microservice"
SOURCE_TYPE_TOMCAT = "tomcat"
SOURCE_TYPE_POSTGRES = "postgres"
MEASURE_CAT_METRIC=0
MEASURE_CAT_EVENT=1
TRANSF_TYPE_NONE=0
TRANSF_TYPE_MINMAX=1
TRANSF_TYPE_STD=2
TRANSF_TYPE_PERCENTAGE=3
TRANSF_TYPE_FUZZY_1=4
|
''' This can be solved using the slicing method used in list. We have to modify the list by take moving the
last part of the array in reverse order and joining it with the remaining part of the list to its right'''
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k = k % len(nums) #To reduce the a full cycle rotation
nums[:] = nums[-k:] + nums[:-k] #nums[-k:] -> end part of the list in reverse order
#nums[:-k] -> front part of the list which is attached to the right of nums[-k:] |
'''Crie um programa que leia dois valores e mostre um menu na tela:
[1] somar
[2] multiplicar
[3] maior
[4] novos numeros
[5] sair do programa
Seu programa devera realizar a operação solicitada em cada caso'''
v1= int(input('Digite um numero: '))
v2 = int(input('Digite outro numero: '))
operacao = 0
print('''[1] somar
[2] multiplicar
[3] maior
[4] novos numeros
[5] sair do programa''')
operacao = int(input('Para realizar uma das operações anteriores, escolha uma das opções numericas: '))
while operacao!=0:
if operacao == 1:
v = v1+v2
operacao = int(input(f'O valor sera {v}. Qual a proxima operação a ser realizada? '))
if operacao == 2:
v = v1*v2
operacao = int(input(f'O valor sera {v}. Qual a proxima operação a ser realizada? '))
if operacao == 3:
if v1>v2:
operacao = int(input(f'O maior valor sera {v1}. Qual a proxima operação a ser realizada? '))
else:
operacao = int(input(f'O maior valor sera {v2}. Qual a proxima operação a ser realizada? '))
if operacao == 4:
v1 = int(input('Digite um novo numero: '))
v2 = int(input('Digite mais um novo numero: '))
operacao = int(input('Qual a proxima operação a ser realizada? '))
if operacao == 5:
operacao = 0
print('Fim')
|
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/viki/catkin_ws/src/beginner_tutorials/msg/Num.msg"
services_str = "/home/viki/catkin_ws/src/beginner_tutorials/srv/ResetCount.srv;/home/viki/catkin_ws/src/beginner_tutorials/srv/AddTwoInts.srv"
pkg_name = "beginner_tutorials"
dependencies_str = "std_msgs"
langs = "gencpp;genlisp;genpy"
dep_include_paths_str = "beginner_tutorials;/home/viki/catkin_ws/src/beginner_tutorials/msg;std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/indigo/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
|
x=int(input("no 1 "))
y=int(input("no 2 "))
def pow(x,y):
if y!=0:
return(x*pow(x,y-1))
else:
return 1
print(pow(x,y))
|
#!/usr/bin/python
hamming_threshold = [50, 60]
pattern_scale = [4.0, 6.0, 8.0, 10.0]
fp_runscript = open("/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_validation.sh", 'w')
fp_runscript.write("#!/bin/bash\n\n")
cnt = 0
for i in range(len(hamming_threshold)):
for j in range(len(pattern_scale)):
cnt += 1
filepath = "/home/kivan/Projects/cv-stereo/config_files/experiments/kitti/validation_freak/freak_tracker_validation_stage2_" + str(cnt) + ".txt"
print(filepath)
fp = open(filepath, 'w')
fp.write("odometry_method = VisualOdometryRansac\n")
fp.write("use_deformation_field = false\n")
fp.write("ransac_iters = 1000\n\n")
fp.write("tracker = StereoTracker\n")
fp.write("max_disparity = 160\n")
fp.write("stereo_wsz = 15\n")
fp.write("ncc_threshold_s = 0.7\n\n")
fp.write("tracker_mono = TrackerBFMcv\n")
fp.write("max_features = 5000\n")
fp.write("search_wsz = 230\n\n")
fp.write("hamming_threshold = " + str(hamming_threshold[i]) + "\n\n")
fp.write("detector = FeatureDetectorHarrisFREAK\n")
fp.write("harris_block_sz = 3\n")
fp.write("harris_filter_sz = 1\n")
fp.write("harris_k = 0.04\n")
fp.write("harris_thr = 1e-06\n")
fp.write("harris_margin = 15\n\n")
fp.write("freak_norm_scale = false\n")
fp.write("freak_norm_orient = false\n")
fp.write("freak_pattern_scale = " + str(pattern_scale[j]) + "\n")
fp.write("freak_num_octaves = 0\n")
fp.write("use_bundle_adjustment = false")
fp.close()
fp_runscript.write('./run_kitti_evaluation_dinodas.sh "' + filepath + '"\n')
fp_runscript.close()
|
# 2021.04.16 hard:
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
'''
dp 问题:
1. 子字符串应该一样长. 很简单已经保证了
子字符串一样,那么久直接返回 True
2. 子字符串中 存在的字母应该一样, 同一个字母的数量应该一样多 Count()
两种分割方式,交换 或者 不交换不断的迭代下去:
分割的两种方式要写对!
'''
@cache
def dfs(idx1, idx2, length):
if s1[idx1:length+idx1] == s2[idx2:idx2+length]:
return True
if Counter(s1[idx1:length+idx1]) != Counter(s2[idx2:idx2+length]):
return False
for i in range(1,length):
# no swarp
if dfs(idx1,idx2,i) and dfs(idx1+i, idx2+i, length-i): # 这两个的 位置 idx1, idx2 传入要注意:
return True
if dfs(idx1, idx2+length-i, i) and dfs(idx1+i, idx2, length-i):
return True
return False
res = dfs(0,0,len(s1))
dfs.cache_clear()
# print(res)
return res |
#!/usr/bin/env python
colors = ['white', 'black']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for size in sizes
for color in colors ]
print(tshirts)
tshirts = [(color, size) for color in colors
for size in sizes ]
print(tshirts)
|
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
max = -9999999
max2 = -9999999
for i in arr:
if(i>max):
max2=max
max=i
elif i>max2 and max>i:
max2=i
print(max2) |
class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use peek to look at the top of the stack
def peek(self):
return self.stack[-1] |
class KataResult:
def __init__(self, revenue, ipa, cost_of_kata, net_income, cost_of_goods, kata_penalty):
self.revenue = revenue
self.ipa = ipa
self.cost_of_kata = cost_of_kata
self.net_income = net_income
self.cost_of_goods = cost_of_goods
self.kata_penalty = kata_penalty
|
su = 0
a = [3,5,6,2,7,1]
print(sum(a))
x, y = input("Enter a two value: ").split()
x = int(x)
y = int(y)
su = a[y] + sum(a[:y])
print(su) |
def test_topic_regexp_matching(dequeuer):
msg = {'company_name': 'test_company'}
actions_1 = tuple(dequeuer.get_actions_for_topic('object__created', msg))
actions_2 = tuple(dequeuer.get_actions_for_topic('object__deleted', msg))
actions_3 = tuple(dequeuer.get_actions_for_topic('otherthing__created', msg))
assert actions_1 == actions_2
assert actions_1 != actions_3
def test_topic_regexp_matching_with_groups(dequeuer):
msg = {'company_name': 'test_company'}
actions_1 = tuple(dequeuer.get_actions_for_topic('step__alfa__started', msg))
payload = actions_1[0][1]['run'].args[2][0]
assert 'name' in payload
assert payload['name'] == 'alfa'
assert 'status' in payload
assert payload['status'] == 'started', payload
actions_2 = tuple(dequeuer.get_actions_for_topic('step__beta__finished', msg))
actions_3 = tuple(dequeuer.get_actions_for_topic('otherthing__created', msg))
assert actions_1 == actions_2
assert actions_1 != actions_3
|
# Find the closest number
# Difficulty: Basic Marks: 1
'''
Given an array of sorted integers. The task is to find the closest value to the given number in array. Array may contain duplicate values.
Note: If the difference is same for two values print the value which is greater than the given number.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. First line of each test case contains two integers N & K and the second line contains N space separated array elements.
Output:
For each test case, print the closest number in new line.
Constraints:
1<=T<=100
1<=N<=105
1<=K<=105
1<=A[i]<=105
Example:
Input:
2
4 4
1 3 6 7
7 4
1 2 3 5 6 8 9
Output:
3
5
'''
for _ in range(int(input())):
n1,n2=map(int,input().split())
a=list(map(int,input().split()))
a.append(n2)
a.sort()
for i in range(len(a)):
if a[-1]==n2:
print(a[-2])
break
else:
if a[i]==n2:
if a[i+1]==n2:
print(n2)
break
else:
if abs(n2-a[i+1])==abs(n2-a[i-1]):
print(a[i+1])
break
else:
if abs(n2-a[i+1])>abs(n2-a[i-1]):
print(a[i-1])
break
else:
print(a[i+1])
break
|
#!/usr/bin/env python3
"""sum_double
Given two int values, return their sum.
Unless the two values are the same, then return double their sum.
sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8
source: https://codingbat.com/prob/p141905
"""
def sum_double(a: int, b: int) -> int:
"""Sum Double.
Return the sum or if a == b return double the sum.
"""
multiply = 1
if a == b:
multiply += 1
return (a + b) * multiply
if __name__ == "__main__":
print(sum_double(1, 2))
print(sum_double(3, 2))
print(sum_double(2, 2))
|
# -*- coding: utf-8 -*-
VERSION = (1, 0, 4)
__version__ = "1.0.4"
__authors__ = ["Stefan Foulis <stefan.foulis@gmail.com>", ]
|
'''
This is the exceptions module:
'''
'''
Exception of when user do not have the access to certain pages.
'''
class CannotAccessPageException(Exception):
pass
'''
Exception of the first password and the second password does not match during registration.
'''
class PasswordsNotMatchingException(Exception):
pass
'''
Exception of when the user input format is wrong.
'''
class WrongFormatException(Exception):
def __init__(self, message=''):
super().__init__('{}, format is incorrect.'.format(message))
'''
Exception of when the ticket name is wrong.
'''
class WrongTicketNameException(Exception):
pass
'''
Exception of when the ticket quantity is wrong.
'''
class WrongTicketQuantityException(Exception):
pass
'''
Exception of when the ticket quantity is wrong.
'''
class WrongTicketPriceException(Exception):
pass
'''
Exception of when the email already exists in user data (already registered).
'''
class EmailAlreadyExistsException(Exception):
pass |
class TransportContext(object):
""" The System.Net.TransportContext class provides additional context about the underlying transport layer. """
def GetChannelBinding(self,kind):
"""
GetChannelBinding(self: TransportContext,kind: ChannelBindingKind) -> ChannelBinding
Retrieves the requested channel binding.
kind: The type of channel binding to retrieve.
Returns: The requested System.Security.Authentication.ExtendedProtection.ChannelBinding,or null if the
channel binding is not supported by the current transport or by the operating system.
"""
pass
def GetTlsTokenBindings(self):
""" GetTlsTokenBindings(self: TransportContext) -> IEnumerable[TokenBinding] """
pass
|
# encoding: utf-8
# input data constants
MARI_EL = 'Республика Марий Эл'
YOSHKAR_OLA = 'Республика Марий Эл, Йошкар-Ола'
VOLZHSK = 'Республика Марий Эл, Волжск'
VOLZHSK_ADM = 'Республика Марий Эл, Волжский район'
MOUNTIN = 'Республика Марий Эл, Горномарийский район'
ZVENIGOVO = 'Республика Марий Эл, Звениговский район'
KILEMARY = 'Республика Марий Эл, Килемарский район'
KUZHENER = 'Республика Марий Эл, Куженерский район'
TUREK = 'Республика Марий Эл, Мари-Турекский район'
MEDVEDEVO = 'Республика Марий Эл, Медведевский район'
MORKI = 'Республика Марий Эл, Моркинский район'
NEW_TORYAL = 'Республика Марий Эл, Новоторъяльский район'
ORSHANKA = 'Республика Марий Эл, Оршанский район'
PARANGA = 'Республика Марий Эл, Параньгинский район'
SERNUR = 'Республика Марий Эл, Сернурский район'
SOVETSKIY = 'Республика Марий Эл, Советский район'
YURINO = 'Республика Марий Эл, Юринский район'
ADMINISTRATIVE = [YOSHKAR_OLA, VOLZHSK, VOLZHSK_ADM, MOUNTIN, ZVENIGOVO, KILEMARY, KUZHENER, TUREK, MEDVEDEVO, MORKI, NEW_TORYAL, ORSHANKA, PARANGA, SERNUR, SOVETSKIY, YURINO]
# data indices
DATE = 0
TIME = 1
TYPE = 2
LOCATION = 3
STREET = 4
HOUSE_NUMBER = 5
ROAD = 6
KILOMETER = 7
METER = 8
LONGITUDE = 9
LATITUDE = 10
DEATH = 11
DEATH_CHILDREN = 12
INJURY = 13
INJURY_CHILDREN = 14
LONGITUDE_GEOCODE = 15
LATITUDE_GEOCODE = 16
VALID = 17
VALID_STRICT = 18
STREET_REPLACE_DICTIONARY = {
'Кырля': 'Кырли',
'Ленина пр-кт': 'Ленинский проспект',
'Ленина пл': 'Ленинский проспект',
'Л.Шевцовой': 'Шевцовой',
'Панфилова пер': 'Панфилова улица',
'Комсомольская пл': 'Комсомольская ул',
'Маркса пер': 'Маркса ул'
}
# coordinates grid borders
MARI_EL_WEST = 45.619745
MARI_EL_EAST = 50.200041
MARI_EL_SOUTH = 55.830512
MARI_EL_NORTH = 57.343631
YOSHKAR_OLA_WEST = 47.823484
YOSHKAR_OLA_EAST = 47.972560
YOSHKAR_OLA_SOUTH = 56.603073
YOSHKAR_OLA_NORTH = 56.669722
EARTH_MEAN_RADIUS = 6371000
MAX_DISTANCE = 150
# Yandex API constants
HOUSE_YANDEX = 'house' |
# Copyright 2016-2022 The FEAGI Authors. 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.
# ==============================================================================
def utf_detection_logic(detection_list):
# todo: Add a logic to account for cases were two top ranked items are too close
# Identifies the detected UTF character with highest activity
highest_ranked_item = '-'
second_highest_ranked_item = '-'
for item in detection_list:
if highest_ranked_item == '-':
highest_ranked_item = item
else:
if detection_list[item]['rank'] > detection_list[highest_ranked_item]['rank']:
second_highest_ranked_item = highest_ranked_item
highest_ranked_item = item
elif second_highest_ranked_item == '-':
second_highest_ranked_item = item
else:
if detection_list[item]['rank'] > detection_list[second_highest_ranked_item]['rank']:
second_highest_ranked_item = item
# todo: export detection factor to genome not parameters
detection_tolerance = 1.5
if highest_ranked_item != '-' and second_highest_ranked_item == '-':
print("Highest ranking number was chosen.")
print("1st and 2nd highest ranked numbers are: ", highest_ranked_item, second_highest_ranked_item)
return highest_ranked_item
elif highest_ranked_item != '-' and \
second_highest_ranked_item != '-' and \
detection_list[second_highest_ranked_item]['rank'] != 0:
if detection_list[highest_ranked_item]['rank'] / detection_list[second_highest_ranked_item]['rank'] > \
detection_tolerance:
print("Highest ranking number was chosen.")
print("1st and 2nd highest ranked numbers are: ", highest_ranked_item, second_highest_ranked_item)
return highest_ranked_item
else:
print(">>>> >>> >> >> >> >> > > Tolerance factor was not met!! !! !!")
print("Highest and 2nd highest ranked numbers are: ", highest_ranked_item, second_highest_ranked_item)
return '-'
else:
return '-'
# list_length = len(detection_list)
# if list_length == 1:
# for key in detection_list:
# return key
# elif list_length >= 2 or list_length == 0:
# return '-'
# else:
# temp = []
# counter = 0
# # print(">><<>><<>><<", detection_list)
# for key in detection_list:
# temp[counter] = (key, detection_list[key])
# if temp[0][1] > (3 * temp[1][1]):
# return temp[0][0]
# elif temp[1][1] > (3 * temp[0][1]):
# return temp[1][0]
# else:
# return '-'
# Load copy of all MNIST training images into mnist_data in form of an iterator. Each object has image label + image
|
def is_triangle(func):
def wrapped(sides):
if any(i <= 0 for i in sides):
return False
sum_ = sum(sides)
if any(sides[i] > sum_ - sides[i] for i in range(3)):
return False
return func(sides)
return wrapped
@is_triangle
def is_equilateral(sides):
return len(set(sides)) == 1
@is_triangle
def is_isosceles(sides):
return len(set(sides)) != 3
@is_triangle
def is_scalene(sides):
return len(set(sides)) == 3
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
BOT_NAME = 'book'
SPIDER_MODULES = ['book.spiders']
NEWSPIDER_MODULE = 'book.spiders'
IMAGES_STORE = '../storage/book/'
COOKIES_ENABLED = True
COOKIE_DEBUG = True
LOG_LEVEL = 'INFO'
# LOG_LEVEL = 'DEBUG'
CONCURRENT_REQUESTS = 100
CONCURRENT_REQUESTS_PER_DOMAIN = 1000
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, \
like Gecko) Chrome/49.0.2623.87 Safari/537.36"
DEFAULT_REQUEST_HEADERS = {
'Referer': 'https://m.douban.com/book/'
}
ITEM_PIPELINES = {
'book.pipelines.CoverPipeline': 0,
'book.pipelines.BookPipeline': 1,
}
|
AP = "AP"
BP = "BP"
ARRIVE = "ARRIVE"
NEUROMODULATORS = "NEUROMODULATORS"
TARGET = "TARGET"
OBSERVE = "OBSERVE"
SET_FREQUENCY = "SET_FREQUENCY"
DEACTIVATE = "DEACTIVATE"
ENCODE_INFORMATION = "ENCODE_INFORMATION"
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 9 00:00:43 2018
@author: joy
"""
print(5 + 3)
print(9 - 1)
print(2 * 4)
print(16//2) |
#! /usr/bin/python3
print("HELLO PYTHON")
|
try:
with open('proxies.txt', 'r') as file:
proxy = [ line.rstrip() for line in file.readlines()]
except FileNotFoundError:
raise Exception('Proxies.txt not found.') |
DILAMI_WEEKDAY_NAMES = {
0: "شمبه",
1: "یکشمبه",
2: "دۊشمبه",
3: "سۊشمبه",
4: "چارشمبه",
5: "پئنشمبه",
6: "جۊمه",
}
DILAMI_MONTH_NAMES = {
0: "پنجيک",
1: "نؤرۊز ما",
2: "کۊرچ ٚ ما",
3: "أرئه ما",
4: "تیر ما",
5: "مۊردال ما",
6: "شریرما",
7: "أمیر ما",
8: "آول ما",
9: "سیا ما",
10: "دیا ما",
11: "ورفن ٚ ما",
12: "اسفندار ما",
}
DILAMI_LEAP_YEARS = (
199,
203,
207,
211,
215,
220,
224,
228,
232,
236,
240,
244,
248,
253,
257,
261,
265,
269,
273,
277,
281,
286,
290,
294,
298,
302,
306,
310,
315,
319,
323,
327,
331,
335,
339,
343,
348,
352,
356,
360,
364,
368,
372,
376,
381,
385,
389,
393,
397,
401,
405,
409,
414,
418,
422,
426,
430,
434,
438,
443,
447,
451,
455,
459,
463,
467,
471,
476,
480,
484,
488,
492,
496,
500,
504,
509,
513,
517,
521,
525,
529,
533,
537,
542,
546,
550,
554,
558,
562,
566,
571,
575,
579,
583,
587,
591,
595,
599,
604,
608,
612,
616,
620,
624,
628,
632,
637,
641,
645,
649,
653,
657,
661,
665,
669,
674,
678,
682,
686,
690,
694,
698,
703,
707,
711,
715,
719,
723,
727,
731,
736,
740,
744,
748,
752,
756,
760,
764,
769,
773,
777,
781,
785,
789,
793,
797,
802,
806,
810,
814,
818,
822,
826,
831,
835,
839,
843,
847,
851,
855,
859,
864,
868,
872,
876,
880,
884,
888,
892,
897,
901,
905,
909,
913,
917,
921,
925,
930,
934,
938,
942,
946,
950,
954,
959,
963,
967,
971,
975,
979,
983,
987,
992,
996,
1000,
1004,
1008,
1012,
1016,
1020,
1025,
1029,
1033,
1037,
1041,
1045,
1049,
1053,
1058,
1062,
1066,
1070,
1074,
1078,
1082,
1087,
1091,
1095,
1099,
1103,
1107,
1111,
1115,
1120,
1124,
1128,
1132,
1136,
1140,
1144,
1148,
1153,
1157,
1161,
1165,
1169,
1173,
1177,
1181,
1186,
1190,
1194,
1198,
1202,
1206,
1210,
1215,
1219,
1223,
1227,
1231,
1235,
1239,
1243,
1248,
1252,
1256,
1260,
1264,
1268,
1272,
1276,
1281,
1285,
1289,
1293,
1297,
1301,
1305,
1309,
1314,
1318,
1322,
1326,
1330,
1334,
1338,
1343,
1347,
1351,
1355,
1359,
1363,
1367,
1371,
1376,
1380,
1384,
1388,
1392,
1396,
1400,
1404,
1409,
1413,
1417,
1421,
1425,
1429,
1433,
1437,
1442,
1446,
1450,
1454,
1458,
1462,
1466,
1471,
1475,
1479,
1483,
1487,
1491,
1495,
1499,
1504,
1508,
1512,
1516,
1520,
1524,
1528,
1532,
1537,
1541,
1545,
1549,
1553,
1557,
1561,
1565,
1570,
1574,
1578,
1582,
1586,
1590,
1594,
1599,
1603,
1607,
1611,
1615,
1619,
1623,
1627,
1632,
1636,
1640,
1644,
1648,
1652,
1656,
1660,
1665,
1669,
1673,
1677,
1681,
1685,
1689,
1693,
1698,
1702,
1706,
1710,
1714,
1718,
1722,
1727,
1731,
1735,
1739,
1743,
1747,
1751,
1755,
1760,
1764,
1768,
1772,
1776,
1780,
1784,
1788,
1793,
1797,
1801,
1805,
1809,
1813,
1817,
1821,
1826,
1830,
1834,
1838,
1842,
1846,
1850,
1855,
1859,
1863,
1867,
1871,
1875,
1879,
1883,
1888,
1892,
1896,
1900,
1904,
1908,
1912,
1916,
1921,
1925,
1929,
1933,
1937,
1941,
1945,
1949,
1954,
1958,
1962,
1966,
1970,
1974,
1978,
1983,
1987,
1991,
1995,
1999,
2003,
2007,
2011,
2016,
2020,
2024,
2028,
2032,
2036,
2040,
2044,
2049,
2053,
2057,
2061,
2065,
2069,
2073,
2077,
2082,
2086,
2090,
2094,
2098,
2102,
2106,
2111,
2115,
2119,
2123,
2127,
2131,
2135,
2139,
2144,
2148,
2152,
2156,
2160,
2164,
2168,
2172,
2177,
2181,
2185,
2189,
2193,
2197,
2201,
2205,
2210,
2214,
2218,
2222,
2226,
2230,
2234,
2239,
2243,
2247,
2251,
2255,
2259,
2263,
2267,
2272,
2276,
2280,
2284,
2288,
2292,
2296,
2300,
2305,
2309,
2313,
2317,
2321,
2325,
2329,
2333,
2338,
2342,
2346,
2350,
2354,
2358,
2362,
2367,
2371,
2375,
2379,
2383,
2387,
2391,
2395,
2400,
2404,
2408,
2412,
2416,
2420,
2424,
2428,
2433,
2437,
2441,
2445,
2449,
2453,
2457,
2461,
2466,
2470,
2474,
2478,
2482,
2486,
2490,
2495,
2499,
2503,
2507,
2511,
2515,
2519,
2523,
2528,
2532,
2536,
2540,
2544,
2548,
2552,
2556,
2561,
2565,
2569,
2573,
2577,
2581,
2585,
2589,
2594,
2598,
2602,
2606,
2610,
2614,
2618,
2623,
2627,
2631,
2635,
2639,
2643,
2647,
2651,
2656,
2660,
2664,
2668,
2672,
2676,
2680,
2684,
2689,
2693,
2697,
2701,
2705,
2709,
2713,
2717,
2722,
2726,
2730,
2734,
2738,
2742,
2746,
2751,
2755,
2759,
2763,
2767,
2771,
2775,
2779,
2784,
2788,
2792,
2796,
2800,
2804,
2808,
2812,
2817,
2821,
2825,
2829,
2833,
2837,
2841,
2845,
2850,
2854,
2858,
2862,
2866,
2870,
2874,
2879,
2883,
2887,
2891,
2895,
2899,
2903,
2907,
2912,
2916,
2920,
2924,
2928,
2932,
2936,
2940,
2945,
2949,
2953,
2957,
2961,
2965,
2969,
2973,
2978,
2982,
2986,
2990,
2994,
2998,
3002,
3007,
3011,
3015,
3019,
3023,
3027,
3031,
3035,
3040,
3044,
3048,
3052,
3056,
3060,
3064,
3068,
3073,
3077,
3081,
3085,
3089,
3093,
3097,
3101,
3106,
3110,
3114,
3118,
3122,
3126,
3130,
3135,
3139,
3143,
3147,
3151,
3155,
3159,
3163,
3168,
3172,
3176,
3180,
3184,
3188,
3192,
3196,
3201,
3205,
3209,
3213,
3217,
3221,
3225,
3229,
3234,
3238,
3242,
3246,
3250,
3254,
3258,
3263,
3267,
3271,
3275,
3279,
3283,
3287,
3291,
3296,
3300,
3304,
3308,
3312,
3316,
3320,
3324,
3329,
3333,
3337,
3341,
3345,
3349,
3353,
3357,
3362,
3366,
3370,
)
#: Minimum year supported by the library.
MINYEAR = 195
#: Maximum year supported by the library.
MAXYEAR = 3372
|
#Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário.
#O programa será interronpido quando o número solicitado for negativo.
c = 0
while True:
print(30*'-')
num = int(input('Quer ver a tabuada de qual valor ?'))
print(30*'-')
if num < 0:
break
for c in range(1,11):
print(f'{num} X {c} = {num*c}')
print('FIM') |
"""
Fragments of project version mutations
"""
PROJECT_VERSION_FRAGMENT = '''
content
id
name
projectId
'''
|
text = input()
punc_remove = [",", ".", "!", "?"]
for i in punc_remove:
text = text.replace(i, "")
print(text.lower()) |
'''
Student: Dan Grecoe
Assignment: Homework 1
Submission of the first homework assignment. The assignment
was to create a python file with 2 functions
multiply - Takes two parameters x and y and returns the product
of the values provided.
noop - Takes 0 parameters and returns None
'''
def multiply(x, y):
return x * y
def noop():
#raise Exception("Bad things happened")
print("Dumb student program")
return None
|
# `name` is the name of the package as used for `pip install package`
name = "package-name"
# `path` is the name of the package for `import package`
path = name.lower().replace("-", "_").replace(" ", "_")
version = "0.1.0"
author = "Author Name"
author_email = ""
description = "" # summary
license = "MIT"
|
class TestClient:
"""
Test before_request and after_request decorators in __init__.py.
"""
def test_1(self, client): # disallowed methods
res = client.put("/")
assert res.status_code == 405
assert b"Method Not Allowed" in res.content
res = client.options("/api/post/add")
assert res.status_code == 405
assert b"Method Not Allowed" in res.content
res = client.delete("/notifications")
assert res.status_code == 405
assert b"Method Not Allowed" in res.content
def test_2(self, client): # empty/fake user agent
res = client.get("/", headers={"User-Agent": ""})
assert res.status_code == 403
assert b"No Scrappers!" in res.content
res = client.get("/board/2", headers={"User-Agent": "python/3.8"})
assert res.status_code == 403
assert b"No Scrappers!" in res.content
|
x = 1 #x recebe 1
#print irá printar(mostrar) o valor desejado;
print(x) # resultado: 1
print(x + 4) # é possível somar uma variável com um número, desde que a variável tenha um valor definido - resultado: 5
print(2 * 2) #um asterisco é usado para multiplicar - resultado: 4
print(3 ** 3) #dois asterisco é usado para elevar a potência - resultado: 27
print(5 / 2) #divisão com uma barra é usado para retornar tipo flutuante - resultado = 2.5
print(5 // 2) #divisão com duas barras é usado para retorna tipo inteiro - resultado = 2;
print(5 % 2) #modulo é usado para retornar o resto da divisão - resultado = 1;
#OBS: o uso de '=' atribui um valor a uma variável, já o uso de '==' compara os valores;
y = 1 #1 é atribuído para y;
y == 1 #y é igual a 1?
|
"""
继承调用关系
"""
class A:
def a_say(self):
print('执行A:', self)
class B(A):
def b_say(self):
A.a_say(self) # 效果与下面的语句相同
super().a_say() # super()方法调用父类的定义,
# 默认传入当前对象的引用self
A().a_say() # 类对象的直接使用,先创建一个类对象A
print('执行B:', self)
a = A()
b = B()
a.a_say()
b.a_say()
print("*" * 50)
b.b_say() # 仍然引用子类实例化的对象
print("*" * 50)
B().b_say()
|
class Graph(object):
"""
A simple undirected, weighted graph
"""
def __init__(self):
self.nodes = set()
self.edges = {}
self.distances = {}
def add_node(self, value):
self.nodes.add(value)
def add_edge(self, from_node, to_node, distance):
self._add_edge(from_node, to_node, distance)
self._add_edge(to_node, from_node, distance)
def _add_edge(self, from_node, to_node, distance):
self.edges.setdefault(from_node, [])
self.edges[from_node].append(to_node)
self.distances[(from_node, to_node)] = distance
def dijkstra(graph, initial_node):
visited = {initial_node: 0}
nodes = set(graph.nodes)
while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
if min_node is None:
break
nodes.remove(min_node)
cur_wt = visited[min_node]
for edge in graph.edges[min_node]:
wt = cur_wt + graph.distances[(min_node, edge)]
if edge not in visited or wt < visited[edge]:
visited[edge] = wt
return visited
def dijkstra2(graph, initial_node):
visited = {initial_node: 0}
nodes = set(graph.nodes)
while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
if min_node is None:
break
nodes.remove(min_node)
cur_wt = visited[min_node]
for edge in graph.edges[min_node]:
wt = cur_wt + graph.distances[(min_node, edge)]
if edge not in visited or wt < visited[edge]:
visited[edge] = wt
return visited
|
class Config(object):
"""Configuration primitives.
Inherit from or instantiate this class and call configure() when you've got
a dictionary of configuration values you want to process and query.
Would be nice to have _expand_cidrlist() so blacklists can specify ranges.
"""
def __init__(self, config_dict=None, portlists=[]):
if config_dict is not None:
self.configure(config_dict, portlists)
def configure(self, config_dict, portlists=[], stringlists=[]):
"""Parse configuration.
Does three things:
1.) Turn dictionary keys to lowercase
2.) Turn string lists into arrays for quicker access
3.) Expand port range specifications
"""
self._dict = dict((k.lower(), v) for k, v in config_dict.items())
for entry in portlists:
portlist = self.getconfigval(entry)
if portlist:
expanded = self._expand_ports(portlist)
self.setconfigval(entry, expanded)
for entry in stringlists:
stringlist = self.getconfigval(entry)
if stringlist:
expanded = [s.strip() for s in stringlist.split(',')]
self.setconfigval(entry, expanded)
def reconfigure(self, portlists=[], stringlists=[]):
"""Same as configure(), but allows multiple callers to sequentially
apply parsing directives for port and string lists.
For instance, if a base class calls configure() specifying one set of
port lists and string lists, but a derived class knows about further
configuration items that will need to be accessed samewise, this
function can be used to leave the existing parsed data alone and only
re-parse the new port or string lists into arrays.
"""
self.configure(self._dict, portlists, stringlists)
def _expand_ports(self, ports_list):
ports = []
for i in ports_list.split(','):
if '-' not in i:
ports.append(int(i))
else:
l, h = list(map(int, i.split('-')))
ports += list(range(l, h + 1))
return ports
def _fuzzy_true(self, value):
return value.lower() in ['yes', 'on', 'true', 'enable', 'enabled']
def _fuzzy_false(self, value):
return value.lower() in ['no', 'off', 'false', 'disable', 'disabled']
def is_configured(self, opt):
return opt.lower() in list(self._dict.keys())
def is_unconfigured(self, opt):
return not self.is_configured(opt)
def is_set(self, opt):
return (self.is_configured(opt) and
self._fuzzy_true(self._dict[opt.lower()]))
def is_clear(self, opt):
return (self.is_configured(opt) and
self._fuzzy_false(self._dict[opt.lower()]))
def getconfigval(self, opt, default=None):
return self._dict[opt.lower()] if self.is_configured(opt) else default
def setconfigval(self, opt, obj):
self._dict[opt.lower()] = obj
|
__title__ = 'cisco_support'
__description__ = 'Cisco Support APIs'
__version__ = '0.1.0'
__author__ = 'Dennis Roth'
__license__ = 'MIT'
|
velocidade = float(input("Digite a sua velocidade em Km/h: "))
if velocidade > 80:
amais = velocidade - 80
amais = amais*7
print("Você foi multado, devera pagar uma multa de: R${:.2f}".format(amais))
print("FIM, não se mate")
|
elements = [int(x) for x in input().split(', ')]
even_numbers = [x for x in elements if x % 2 == 0]
odd_numbers = [x for x in elements if x % 2 != 0]
positive = [x for x in elements if x >= 0]
negative = [x for x in elements if x < 0]
print(f"Positive: {', '.join(str(x) for x in positive)}")
print(f"Negative: {', '.join(str(x) for x in negative)}")
print(f"Even: {', '.join(str(x) for x in even_numbers)}")
print(f"Odd: {', '.join(str(x) for x in odd_numbers)}")
|
vals = {
"yes" : 0,
"residential" : 1,
"service" : 2,
"unclassified" : 3,
"stream" : 4,
"track" : 5,
"water" : 6,
"footway" : 7,
"tertiary" : 8,
"private" : 9,
"tree" : 10,
"path" : 11,
"forest" : 12,
"secondary" : 13,
"house" : 14,
"no" : 15,
"asphalt" : 16,
"wood" : 17,
"grass" : 18,
"paved" : 19,
"primary" : 20,
"unpaved" : 21,
"bus_stop" : 22,
"parking" : 23,
"parking_aisle" : 24,
"rail" : 25,
"driveway" : 26,
"8" : 27,
"administrative" : 28,
"locality" : 29,
"turning_circle" : 30,
"crossing" : 31,
"village" : 32,
"fence" : 33,
"grade2" : 34,
"coastline" : 35,
"grade3" : 36,
"farmland" : 37,
"hamlet" : 38,
"hut" : 39,
"meadow" : 40,
"wetland" : 41,
"cycleway" : 42,
"river" : 43,
"school" : 44,
"trunk" : 45,
"gravel" : 46,
"place_of_worship" : 47,
"farm" : 48,
"grade1" : 49,
"traffic_signals" : 50,
"wall" : 51,
"garage" : 52,
"gate" : 53,
"motorway" : 54,
"living_street" : 55,
"pitch" : 56,
"grade4" : 57,
"industrial" : 58,
"road" : 59,
"ground" : 60,
"scrub" : 61,
"motorway_link" : 62,
"steps" : 63,
"ditch" : 64,
"swimming_pool" : 65,
"grade5" : 66,
"park" : 67,
"apartments" : 68,
"restaurant" : 69,
"designated" : 70,
"bench" : 71,
"survey_point" : 72,
"pedestrian" : 73,
"hedge" : 74,
"reservoir" : 75,
"riverbank" : 76,
"alley" : 77,
"farmyard" : 78,
"peak" : 79,
"level_crossing" : 80,
"roof" : 81,
"dirt" : 82,
"drain" : 83,
"garages" : 84,
"entrance" : 85,
"street_lamp" : 86,
"deciduous" : 87,
"fuel" : 88,
"trunk_link" : 89,
"information" : 90,
"playground" : 91,
"supermarket" : 92,
"primary_link" : 93,
"concrete" : 94,
"mixed" : 95,
"permissive" : 96,
"orchard" : 97,
"grave_yard" : 98,
"canal" : 99,
"garden" : 100,
"spur" : 101,
"paving_stones" : 102,
"rock" : 103,
"bollard" : 104,
"convenience" : 105,
"cemetery" : 106,
"post_box" : 107,
"commercial" : 108,
"pier" : 109,
"bank" : 110,
"hotel" : 111,
"cliff" : 112,
"retail" : 113,
"construction" : 114,
"-1" : 115,
"fast_food" : 116,
"coniferous" : 117,
"cafe" : 118,
"6" : 119,
"kindergarten" : 120,
"tower" : 121,
"hospital" : 122,
"yard" : 123,
"sand" : 124,
"public_building" : 125,
"cobblestone" : 126,
"destination" : 127,
"island" : 128,
"abandoned" : 129,
"vineyard" : 130,
"recycling" : 131,
"agricultural" : 132,
"isolated_dwelling" : 133,
"pharmacy" : 134,
"post_office" : 135,
"motorway_junction" : 136,
"pub" : 137,
"allotments" : 138,
"dam" : 139,
"secondary_link" : 140,
"lift_gate" : 141,
"siding" : 142,
"stop" : 143,
"main" : 144,
"farm_auxiliary" : 145,
"quarry" : 146,
"10" : 147,
"station" : 148,
"platform" : 149,
"taxiway" : 150,
"limited" : 151,
"sports_centre" : 152,
"cutline" : 153,
"detached" : 154,
"storage_tank" : 155,
"basin" : 156,
"bicycle_parking" : 157,
"telephone" : 158,
"terrace" : 159,
"town" : 160,
"suburb" : 161,
"bus" : 162,
"compacted" : 163,
"toilets" : 164,
"heath" : 165,
"works" : 166,
"tram" : 167,
"beach" : 168,
"culvert" : 169,
"fire_station" : 170,
"recreation_ground" : 171,
"bakery" : 172,
"police" : 173,
"atm" : 174,
"clothes" : 175,
"tertiary_link" : 176,
"waste_basket" : 177,
"attraction" : 178,
"viewpoint" : 179,
"bicycle" : 180,
"church" : 181,
"shelter" : 182,
"drinking_water" : 183,
"marsh" : 184,
"picnic_site" : 185,
"hairdresser" : 186,
"bridleway" : 187,
"retaining_wall" : 188,
"buffer_stop" : 189,
"nature_reserve" : 190,
"village_green" : 191,
"university" : 192,
"1" : 193,
"bar" : 194,
"townhall" : 195,
"mini_roundabout" : 196,
"camp_site" : 197,
"aerodrome" : 198,
"stile" : 199,
"9" : 200,
"car_repair" : 201,
"parking_space" : 202,
"library" : 203,
"pipeline" : 204,
"true" : 205,
"cycle_barrier" : 206,
"4" : 207,
"museum" : 208,
"spring" : 209,
"hunting_stand" : 210,
"disused" : 211,
"car" : 212,
"tram_stop" : 213,
"land" : 214,
"fountain" : 215,
"hiking" : 216,
"manufacture" : 217,
"vending_machine" : 218,
"kiosk" : 219,
"swamp" : 220,
"unknown" : 221,
"7" : 222,
"islet" : 223,
"shed" : 224,
"switch" : 225,
"rapids" : 226,
"office" : 227,
"bay" : 228,
"proposed" : 229,
"common" : 230,
"weir" : 231,
"grassland" : 232,
"customers" : 233,
"social_facility" : 234,
"hangar" : 235,
"doctors" : 236,
"stadium" : 237,
"give_way" : 238,
"greenhouse" : 239,
"guest_house" : 240,
"viaduct" : 241,
"doityourself" : 242,
"runway" : 243,
"bus_station" : 244,
"water_tower" : 245,
"golf_course" : 246,
"conservation" : 247,
"block" : 248,
"college" : 249,
"wastewater_plant" : 250,
"subway" : 251,
"halt" : 252,
"forestry" : 253,
"florist" : 254,
"butcher" : 255}
def getValues():
return vals
|
n1 = int(input('Digite um número e veja qual a sua tabuada: '))
n = 0
print('{} X {:2} = {:2}'.format(n1, 0, n1*n))
while n < 10:
n += 1
print('{} X {:2} = {:2}'.format(n1, n, n1*n))
|
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return binarySearch(nums,target,0,len(nums)-1)
def binarySearch(nums, target, low, high):
if (low > high):
return -1
middle = low + (high - low)/2
if nums[middle] == target:
return middle
if nums[low] <= nums[middle]:
if nums[low] < target and target < nums[middle]: # 在左边
return binarySearch(nums,target,low,middle-1)
else:
return binarySearch(nums,target,middle+1,high)
else:
if nums[middle] < target and target < nums[high]:
return binarySearch(nums,target,middle+1,high)
else:
return binarySearch(nums,target,low,middle-1)
|
def write_file(filess, T):
f = open(filess, "w")
for o in T:
f.write("[\n")
for l in o:
f.write(str(l)+"\n")
f.write("]\n")
f.close()
def save_hidden_weight(nb_hidden, hiddenw):
for i in range(nb_hidden):
write_file("save/base_nn_hid_" + str(i+1) + "w.nn", hiddenw[i])
def load_hiddenw(filess, hiddenw):
f = open(filess, "r")
s = f.read().splitlines()
h = 0
for o in s:
#print(o)
if o == "[":
h = []
elif o == "]":
hiddenw.append(h)
else:
h.append(float(o))
def load_hidden_weight(hiddenw, nb_hidden):
for i in range(nb_hidden):
hiddenw.append([])
load_hiddenw("save/base_nn_hid_" + str(i+1) + "w.nn", hiddenw[i])
def load_hidden_weight_v(hiddenw, nb_hidden):
for i in range(nb_hidden):
hiddenw.append([])
load_hiddenw("valid/NN/base_nn_hid_" + str(i+1) + "w.nn", hiddenw[i])
def display_hidden_weight(hiddenw, nb_hidden):
for i in range(nb_hidden):
for j in hiddenw[i]:
print("------------------------------------")
I = 0
for k in j:
print(k)
I+=1
if I > 3:
break
def write_fileb(filess, T):
f = open(filess, "w")
for o in T:
f.write(str(o)+"\n")
f.close()
def save_hidden_bias(nb_hidden, hiddenb):
for i in range(nb_hidden):
write_fileb("save/base_nn_hid_" + str(i+1) + "b.nn", hiddenb[i])
def load_hiddenb(filess, hiddenb):
f = open(filess, "r")
s = f.read().splitlines()
for o in s:
hiddenb.append(float(o))
def load_hidden_bias(hiddenb, nb_hidden):
for i in range(nb_hidden):
hiddenb.append([])
load_hiddenb("save/base_nn_hid_" + str(i+1) + "b.nn", hiddenb[i])
def load_hidden_bias_v(hiddenb, nb_hidden):
for i in range(nb_hidden):
hiddenb.append([])
load_hiddenb("valid/NN/base_nn_hid_" + str(i+1) + "b.nn", hiddenb[i])
def display_hidden_bias(hiddenb, nb_hidden):
for i in range(nb_hidden):
print("------------------------------------")
for j in hiddenb[i]:
print(j)
def save_output_weight(outputw):
write_file("save/base_nn_out_w.nn", outputw[0])
def load_output_weight(outputw):
outputw.append([])
load_hiddenw("save/base_nn_out_w.nn", outputw[0])
def load_output_weight_v(outputw):
outputw.append([])
load_hiddenw("valid/NN/base_nn_out_w.nn", outputw[0])
def save_output_bias(outputb):
write_fileb("save/base_nn_out_b.nn", outputb[0])
def load_output_bias(outputb):
outputb.append([])
load_hiddenb("save/base_nn_out_b.nn", outputb[0])
def load_output_bias_v(outputb):
outputb.append([])
load_hiddenb("valid/NN/base_nn_out_b.nn", outputb[0])
|
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:148 ms, 在所有 Python3 提交中击败了35.57% 的用户
内存消耗:13.7 MB, 在所有 Python3 提交中击败了36.81% 的用户
解题思路:
回溯
具体实现见代码注释
"""
class Solution:
def splitIntoFibonacci(self, S: str) -> List[int]:
def backtrack(S, current):
if S == '' and len(current) > 2: # 字符串均处理完,且当前序列长度大于2, 返回最终结果
return True
if S == '': # 当字符串处理完时,跳出
return
for i in range(1, len(S)+1): # 遍历当前字符串
if (S[0] == '0' and i == 1) or (S[0] != '0'): # 排除以0 开头的非0数, 如 01 02 等
if int(S[:i]) < (2**31-1) and (len(current) < 2 or int(S[:i]) == int(current[-1]) + int(current[-2])): # 数字限制;长度判断,如长度小于2,直接添加,如长度大于2,需判断和
current.append(S[:i])
if backtrack(S[i:], current):
return current
current.pop()
result = backtrack(S, [])
if result:
return result
else:
return [] |
class Config(object):
embedding_size = 300
n_layers = 1
hidden_size = 128
drop_prob = 0.2 |
begin_unit
comment|'#!/usr/bin/env python'
nl|'\n'
nl|'\n'
comment|'# Copyright 2013 OpenStack Foundation'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License");'
nl|'\n'
comment|'# you may not use this file except in compliance with the License.'
nl|'\n'
comment|'# You may obtain a copy of the License at'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# http://www.apache.org/licenses/LICENSE-2.0'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Unless required by applicable law or agreed to in writing, software'
nl|'\n'
comment|'# distributed under the License is distributed on an "AS IS" BASIS,'
nl|'\n'
comment|'# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.'
nl|'\n'
comment|'# See the License for the specific language governing permissions and'
nl|'\n'
comment|'# limitations under the License.'
nl|'\n'
string|'"""\nScript to cleanup old XenServer /var/lock/sm locks.\n\nXenServer 5.6 and 6.0 do not appear to always cleanup locks when using a\nFileSR. ext3 has a limit of 32K inode links, so when we have 32K-2 (31998)\nlocks laying around, builds will begin to fail because we can\'t create any\nadditional locks. This cleanup script is something we can run periodically as\na stop-gap measure until this is fixed upstream.\n\nThis script should be run on the dom0 of the affected machine.\n"""'
newline|'\n'
name|'import'
name|'errno'
newline|'\n'
name|'import'
name|'optparse'
newline|'\n'
name|'import'
name|'os'
newline|'\n'
name|'import'
name|'sys'
newline|'\n'
name|'import'
name|'time'
newline|'\n'
nl|'\n'
DECL|variable|BASE
name|'BASE'
op|'='
string|"'/var/lock/sm'"
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|_get_age_days
name|'def'
name|'_get_age_days'
op|'('
name|'secs'
op|')'
op|':'
newline|'\n'
indent|' '
name|'return'
name|'float'
op|'('
name|'time'
op|'.'
name|'time'
op|'('
op|')'
op|'-'
name|'secs'
op|')'
op|'/'
number|'86400'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|_parse_args
dedent|''
name|'def'
name|'_parse_args'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
name|'parser'
op|'='
name|'optparse'
op|'.'
name|'OptionParser'
op|'('
op|')'
newline|'\n'
name|'parser'
op|'.'
name|'add_option'
op|'('
string|'"-d"'
op|','
string|'"--dry-run"'
op|','
nl|'\n'
name|'action'
op|'='
string|'"store_true"'
op|','
name|'dest'
op|'='
string|'"dry_run"'
op|','
name|'default'
op|'='
name|'False'
op|','
nl|'\n'
name|'help'
op|'='
string|'"don\'t actually remove locks"'
op|')'
newline|'\n'
name|'parser'
op|'.'
name|'add_option'
op|'('
string|'"-l"'
op|','
string|'"--limit"'
op|','
nl|'\n'
name|'action'
op|'='
string|'"store"'
op|','
name|'type'
op|'='
string|"'int'"
op|','
name|'dest'
op|'='
string|'"limit"'
op|','
nl|'\n'
name|'default'
op|'='
name|'sys'
op|'.'
name|'maxint'
op|','
nl|'\n'
name|'help'
op|'='
string|'"max number of locks to delete (default: no limit)"'
op|')'
newline|'\n'
name|'parser'
op|'.'
name|'add_option'
op|'('
string|'"-v"'
op|','
string|'"--verbose"'
op|','
nl|'\n'
name|'action'
op|'='
string|'"store_true"'
op|','
name|'dest'
op|'='
string|'"verbose"'
op|','
name|'default'
op|'='
name|'False'
op|','
nl|'\n'
name|'help'
op|'='
string|'"don\'t print status messages to stdout"'
op|')'
newline|'\n'
nl|'\n'
name|'options'
op|','
name|'args'
op|'='
name|'parser'
op|'.'
name|'parse_args'
op|'('
op|')'
newline|'\n'
nl|'\n'
name|'try'
op|':'
newline|'\n'
indent|' '
name|'days_old'
op|'='
name|'int'
op|'('
name|'args'
op|'['
number|'0'
op|']'
op|')'
newline|'\n'
dedent|''
name|'except'
op|'('
name|'IndexError'
op|','
name|'ValueError'
op|')'
op|':'
newline|'\n'
indent|' '
name|'parser'
op|'.'
name|'print_help'
op|'('
op|')'
newline|'\n'
name|'sys'
op|'.'
name|'exit'
op|'('
number|'1'
op|')'
newline|'\n'
nl|'\n'
dedent|''
name|'return'
name|'options'
op|','
name|'days_old'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|main
dedent|''
name|'def'
name|'main'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
name|'options'
op|','
name|'days_old'
op|'='
name|'_parse_args'
op|'('
op|')'
newline|'\n'
nl|'\n'
name|'if'
name|'not'
name|'os'
op|'.'
name|'path'
op|'.'
name|'exists'
op|'('
name|'BASE'
op|')'
op|':'
newline|'\n'
indent|' '
name|'print'
op|'>>'
name|'sys'
op|'.'
name|'stderr'
op|','
string|'"error: \'%s\' doesn\'t exist. Make sure you\'re"'
string|'" running this on the dom0."'
op|'%'
name|'BASE'
newline|'\n'
name|'sys'
op|'.'
name|'exit'
op|'('
number|'1'
op|')'
newline|'\n'
nl|'\n'
dedent|''
name|'lockpaths_removed'
op|'='
number|'0'
newline|'\n'
name|'nspaths_removed'
op|'='
number|'0'
newline|'\n'
nl|'\n'
name|'for'
name|'nsname'
name|'in'
name|'os'
op|'.'
name|'listdir'
op|'('
name|'BASE'
op|')'
op|'['
op|':'
name|'options'
op|'.'
name|'limit'
op|']'
op|':'
newline|'\n'
indent|' '
name|'nspath'
op|'='
name|'os'
op|'.'
name|'path'
op|'.'
name|'join'
op|'('
name|'BASE'
op|','
name|'nsname'
op|')'
newline|'\n'
nl|'\n'
name|'if'
name|'not'
name|'os'
op|'.'
name|'path'
op|'.'
name|'isdir'
op|'('
name|'nspath'
op|')'
op|':'
newline|'\n'
indent|' '
name|'continue'
newline|'\n'
nl|'\n'
comment|'# Remove old lockfiles'
nl|'\n'
dedent|''
name|'removed'
op|'='
number|'0'
newline|'\n'
name|'locknames'
op|'='
name|'os'
op|'.'
name|'listdir'
op|'('
name|'nspath'
op|')'
newline|'\n'
name|'for'
name|'lockname'
name|'in'
name|'locknames'
op|':'
newline|'\n'
indent|' '
name|'lockpath'
op|'='
name|'os'
op|'.'
name|'path'
op|'.'
name|'join'
op|'('
name|'nspath'
op|','
name|'lockname'
op|')'
newline|'\n'
name|'lock_age_days'
op|'='
name|'_get_age_days'
op|'('
name|'os'
op|'.'
name|'path'
op|'.'
name|'getmtime'
op|'('
name|'lockpath'
op|')'
op|')'
newline|'\n'
name|'if'
name|'lock_age_days'
op|'>'
name|'days_old'
op|':'
newline|'\n'
indent|' '
name|'lockpaths_removed'
op|'+='
number|'1'
newline|'\n'
name|'removed'
op|'+='
number|'1'
newline|'\n'
nl|'\n'
name|'if'
name|'options'
op|'.'
name|'verbose'
op|':'
newline|'\n'
indent|' '
name|'print'
string|"'Removing old lock: %03d %s'"
op|'%'
op|'('
name|'lock_age_days'
op|','
nl|'\n'
name|'lockpath'
op|')'
newline|'\n'
nl|'\n'
dedent|''
name|'if'
name|'not'
name|'options'
op|'.'
name|'dry_run'
op|':'
newline|'\n'
indent|' '
name|'os'
op|'.'
name|'unlink'
op|'('
name|'lockpath'
op|')'
newline|'\n'
nl|'\n'
comment|'# Remove empty namespace paths'
nl|'\n'
dedent|''
dedent|''
dedent|''
name|'if'
name|'len'
op|'('
name|'locknames'
op|')'
op|'=='
name|'removed'
op|':'
newline|'\n'
indent|' '
name|'nspaths_removed'
op|'+='
number|'1'
newline|'\n'
nl|'\n'
name|'if'
name|'options'
op|'.'
name|'verbose'
op|':'
newline|'\n'
indent|' '
name|'print'
string|"'Removing empty namespace: %s'"
op|'%'
name|'nspath'
newline|'\n'
nl|'\n'
dedent|''
name|'if'
name|'not'
name|'options'
op|'.'
name|'dry_run'
op|':'
newline|'\n'
indent|' '
name|'try'
op|':'
newline|'\n'
indent|' '
name|'os'
op|'.'
name|'rmdir'
op|'('
name|'nspath'
op|')'
newline|'\n'
dedent|''
name|'except'
name|'OSError'
op|','
name|'e'
op|':'
newline|'\n'
indent|' '
name|'if'
name|'e'
op|'.'
name|'errno'
op|'=='
name|'errno'
op|'.'
name|'ENOTEMPTY'
op|':'
newline|'\n'
indent|' '
name|'print'
op|'>>'
name|'sys'
op|'.'
name|'stderr'
op|','
string|'"warning: directory \'%s\'"'
string|'" not empty"'
op|'%'
name|'nspath'
newline|'\n'
dedent|''
name|'else'
op|':'
newline|'\n'
indent|' '
name|'raise'
newline|'\n'
nl|'\n'
dedent|''
dedent|''
dedent|''
dedent|''
dedent|''
name|'if'
name|'options'
op|'.'
name|'dry_run'
op|':'
newline|'\n'
indent|' '
name|'print'
string|'"** Dry Run **"'
newline|'\n'
nl|'\n'
dedent|''
name|'print'
string|'"Total locks removed: "'
op|','
name|'lockpaths_removed'
newline|'\n'
name|'print'
string|'"Total namespaces removed: "'
op|','
name|'nspaths_removed'
newline|'\n'
nl|'\n'
nl|'\n'
dedent|''
name|'if'
name|'__name__'
op|'=='
string|"'__main__'"
op|':'
newline|'\n'
indent|' '
name|'main'
op|'('
op|')'
newline|'\n'
dedent|''
endmarker|''
end_unit
|
class BrainfuckException(Exception):
pass
class BLexer:
""" Static class encapsulating functionality for lexing Brainfuck programs. """
symbols = [
'>', '<', '+', '-',
'.', ',', '[', ']'
]
@staticmethod
def lex(code):
""" Return a generator for tokens in some Brainfuck code. """
# The syntax of Brainfuck is so simple that nothing is really gained from converting
# symbols to some sort of Token object. Just ignore everything that isn't in Brainfuck's
# syntax.
return (char for char in code if char in BLexer.symbols)
class BrainfuckMachine:
""" Class encapsulating the core operations of a brainfuck machine. Namely,
- Move pointer left,
- Move pointer right,
- Increment cell under pointer,
- Decrement cell under pointer,
- Output value of cell under pointer,
- Input value to cell under pointer.
"""
def __init__(self, cells=256, in_func=input, out_func=chr):
self.cells = [0] * cells
self.ptr = 0
self.in_func = in_func
self.out_func = out_func
self.looppos = []
self.out_buffer = []
def right(self):
if self.ptr < len(self.cells)-1:
self.ptr += 1
def left(self):
if self.ptr > 0:
self.ptr -= 1
def incr(self):
self.cells[self.ptr] += 1
def decr(self):
self.cells[self.ptr] -= 1
def value(self):
""" Return the value of the cell under the pointer. """
return self.cells[self.ptr]
def outf(self):
return self.out_func(self.cells[self.ptr])
def inf(self):
self.cells[self.ptr] = self.in_func()
class BInterpreter:
""" Class encapsulating interpretation functionality for brainfuck code. """
def __init__(self, machine=None):
if machine:
self.machine = machine
else:
self.machine = BrainfuckMachine()
def interpret_code(self, code):
""" Interpret each character in a list or string of brainfuck tokens. """
# Iterate through every character in the code. Use indexing so that we can
# jump as necessary for square bracket loops. To identify matching brackets for forward
# jumps, move forward a position at a time, keeping track of the nesting level (starts at 1). When a
# open bracket ([) is encountered, increment the nesting level, and when a close bracket
# (]) is found, decrement it. When nesting level reaches 0, the matching bracket has been found.
# For finding the correct bracket for a backwards jump, do the same thing but with
# backwards iteration and swap when you increment and decrement.
pos = 0
while pos < len(code):
if code[pos] == '[':
if self.machine.value() == 0:
nest = 1
while nest != 0:
pos += 1
if code[pos] == '[':
nest += 1
elif code[pos] == ']':
nest -= 1
pos += 1
else:
pos += 1
elif code[pos] == ']':
if self.machine.value() != 0:
nest = 1
while nest != 0:
pos -= 1
if code[pos] == ']':
nest += 1
elif code[pos] == '[':
nest -= 1
pos += 1
else:
pos += 1
else:
self.interpret_one(code[pos])
pos += 1
def interpret_one(self, char):
""" Perform the appropriate operation for a single brainfuck character. """
if char == '>':
self.machine.right()
elif char == '<':
self.machine.left()
elif char == '+':
self.machine.incr()
elif char == '-':
self.machine.decr()
elif char == '.':
# TODO output checks
print(self.machine.outf(), end='')
elif char == ',':
# TODO input checks
self.machine.inf()
if __name__ == '__main__':
bfm = BrainfuckMachine(cells=8, out_func=chr)
bi = BInterpreter(bfm)
f = open('helloworld', 'r').read()
code = list(BLexer.lex(f))
bi.interpret_code(code) |
load("@fbcode_macros//build_defs:config.bzl", "config")
load("@fbcode_macros//build_defs/config:read_configs.bzl", "read_int")
load("@fbcode_macros//build_defs:core_tools.bzl", "core_tools")
def _create_build_info(
build_mode,
buck_package,
name,
rule_type,
platform,
epochtime=0,
host="",
package_name="",
package_version="",
package_release="",
path="",
revision="",
revision_epochtime=0,
time="",
time_iso8601="",
upstream_revision="",
upstream_revision_epochtime=0,
user="",
):
return struct(
build_mode=build_mode,
rule="fbcode:" + buck_package + ":" + name,
platform=platform,
rule_type=rule_type,
epochtime=epochtime,
host=host,
package_name=package_name,
package_version=package_version,
package_release=package_release,
path=path,
revision=revision,
revision_epochtime=revision_epochtime,
time=time,
time_iso8601=time_iso8601,
upstream_revision=upstream_revision,
upstream_revision_epochtime=upstream_revision_epochtime,
user=user,
)
def _get_build_info(package_name, name, rule_type, platform):
"""
Gets a build_info struct from various configurations (or default values)
This struct has values passed in by the packaging system in order to
stamp things like the build epoch, platform, etc into the final binary.
This returns stable values by default so that non-release builds do not
affect rulekeys.
Args:
package_name: The name of the package that contains the build rule
that needs build info. No leading slashes
name: The name of the rule that needs build info
rule_type: The type of rule that is being built. This should be the
macro name, not the underlying rule type. (e.g. cpp_binary,
not cxx_binary)
platform: The platform that is being built for
"""
build_mode = config.get_build_mode()
if core_tools.is_core_tool(package_name,name):
return _create_build_info(
build_mode,
package_name,
name,
rule_type,
platform,
)
else:
return _create_build_info(
build_mode,
package_name,
name,
rule_type,
platform,
epochtime=read_int("build_info", "epochtime", 0),
host=native.read_config("build_info", "host", ""),
package_name=native.read_config("build_info", "package_name", ""),
package_version=native.read_config("build_info", "package_version", ""),
package_release=native.read_config("build_info", "package_release", ""),
path=native.read_config("build_info", "path", ""),
revision=native.read_config("build_info", "revision", ""),
revision_epochtime=read_int("build_info", "revision_epochtime", 0),
time=native.read_config("build_info", "time", ""),
time_iso8601=native.read_config("build_info", "time_iso8601", ""),
upstream_revision=native.read_config("build_info", "upstream_revision", ""),
upstream_revision_epochtime=read_int("build_info", "upstream_revision_epochtime", 0),
user=native.read_config("build_info", "user", ""),
)
build_info = struct(
get_build_info = _get_build_info,
)
|
sm.setSpeakerID(1013000)
sm.sendNext("Ugh. This isn't going to work. I need something else. No plants. No meat. What, you have no idea? But you're the master, and you're older than me, too. You must know what'd be good for me!")
sm.setPlayerAsSpeaker()
sm.sendSay("#bBut I don't. It's not like age has anything to do with this...")
sm.setSpeakerID(1013000)
if sm.sendAskAccept("Since you're older, you must be more experienced in the world, too. Makes sense that you'd know more than me. Oh, fine. I'll ask someone who's even older than you, master!"):
if not sm.hasQuest(parentID):
sm.startQuest(parentID)
sm.setPlayerAsSpeaker()
sm.sendSayOkay("#b#b(You already asked Dad once, but you don't have any better ideas. Time to ask him again!)")
else:
sm.sendNext("No use trying to find an answer to this on my own. I'd better look for #bsomeone older and wiser than master#k!")
sm.dispose() |
class Solution:
def chooseandswap (self, A):
opt = 'a'
fir = A[0]
arr = [0]*26
for s in A :
arr[ord(s)-97] += 1
i = 0
while i < len(A) :
if opt > 'z' :
break
while opt < fir :
if opt in A :
ans = ""
for s in A :
if s == opt :
ans += fir
elif s == fir :
ans += opt
else :
ans += s
return ans
opt = chr(ord(opt) + 1)
opt = chr(ord(opt) + 1)
while i < len(A) and A[i] <= fir :
i += 1
if i < len(A) :
fir = A[i]
return A
if __name__ == '__main__':
ob = Solution()
t = int (input ())
for _ in range (t):
A = input()
ans = ob.chooseandswap(A)
print(ans)
|
class AccountManager(object):
def __init__(self, balance = 0):
self.balance = balance
def getBalance(self):
return self.balance
def withdraw(self, value):
if self.balance >= value:
self.balance = self.balance - value
print('Successful Withdrawal.')
else:
print('Insufficient Funds')
def deposit(self, value):
self.balance = self.balance + value
print('Successful Deposit')
def income(self, rate):
self.balance = self.balance + self.balance*rate
class AccountCommon(AccountManager):
def __init__(self, balance = 0):
super(AccountCommon, self).__init__(balance=balance)
def getBalance(self):
return super().getBalance()
def deposit(self, value):
super().deposit(value)
def withdraw(self, value):
super().withdraw(value)
def income(self, rate):
super().income(rate)
def message(self):
print('Common account balance: %.2f' % self.getBalance())
class AccountSpetial(AccountManager):
def __init__(self, balance = 0):
super(AccountSpetial, self).__init__(balance=balance)
def getBalance(self):
return super().getBalance()
def deposit(self, value):
super().deposit(value)
def withdraw(self, value):
super().withdraw(value)
def message(self):
print('Common account balance: %.2f' % self.getBalance())
if __name__ == '__main__':
commonAccount = AccountCommon(500)
commonAccount.deposit(500)
commonAccount.withdraw(100)
commonAccount.income(0.005)
commonAccount.message()
print(' ------- ')
spetialAccount = AccountSpetial(1000)
spetialAccount.deposit(500)
spetialAccount.withdraw(200)
spetialAccount.message()
|
class Response(object):
"""
"""
def __init__(self, status_code, text):
self.content = text
self.cached = False
self.status_code = status_code
self.ok = self.status_code < 400
@property
def text(self):
return self.content
def __repr__(self):
return 'HTTP {} {}'.format(self.status_code, self.content)
|
# Exercicio 01 Tuplas
x = int(input('Digite o primeiro numero: '))
y = int(input('Digite o segundo numero: '))
cont = 1
soma = x
while cont < y:
soma = soma + x
cont = cont + 1
print('O resultado eh: {}' .format(soma))
|
'''
To have a error free way of accessing and updating private variables, we create specific methods for this.
Those methods which are meant to set a value to a private variable are called setter methods and methods
meant to access private variable values are called getter methods.
The below code is an example of getter and setter methods:
'''
class Customer:
def __init__(self, id, name, age, wallet_balance):
self.id = id
self.name = name
self.age = age
self.__wallet_balance = wallet_balance
def set_wallet_balance(self, amount):
if amount < 1000 and amount> 0:
self.__wallet_balance = amount
def get_wallet_balance(self):
return self.__wallet_balance
c1=Customer(100, "Gopal", 24, 1000)
c1.set_wallet_balance(120)
print(c1.get_wallet_balance())
|
class Solution:
def isMatch(self, s: str, p: str) -> bool:
# this is a dynamic programming solution fot this
matrix = [[False for x in range(len(p) + 1)] for x in range(len(s) + 1)]
matrix[0][0] = True
for i in range(1, len(matrix[0])):
if p[i - 1] == "*":
matrix[0][i] = matrix[0][i - 1]
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if s[i - 1] == p[j - 1] or p[j - 1] == "?":
matrix[i][j] = matrix[i - 1][j - 1]
elif p[j - 1] == "*":
matrix[i][j] = matrix[i][j - 1] or matrix[i - 1][j]
else:
matrix[i][j] = False
return matrix[len(s)][len(p)]
|
# https://open.kattis.com/problems/luhnchecksum
for _ in range(int(input())):
count = 0
for i, d in enumerate(reversed(input())):
if i % 2 == 0:
count += int(d)
continue
x = 2 * int(d)
if x < 10:
count += x
else:
x = str(x)
count += int(x[0]) + int(x[1])
print('PASS' if count % 10 == 0 else 'FAIL')
|
inputFile = "3-input"
outputFile = "3-output"
dir = {'L': [-1,0],'R': [1,0],'U': [0,1],'D': [0,-1]}
def readFile():
file = open(inputFile, "r")
A,B = file.readlines()
A,B = [line.split(",") for line in [A,B]]
file.close()
return A,B
def writeFile(a, b):
file = open(outputFile, "w+")
file.write("Part 1: " + a + "\n")
file.write("Part 2: " + b)
file.close()
def mapCommands(A):
cx, cy, step = 0, 0, 0
mapped = [[0]*20000 for _ in range(20000)]
for cmd in A:
ax,ay = dir[cmd[0]][0],dir[cmd[0]][1]
for _ in range(int(cmd[1:])):
cx += ax
cy += ay
step += 1
mapped[cx+10000][cy+10000] = step
return mapped
def findIntersects(A, B):
mapped = mapCommands(A);
cx, cy, step = 0, 0, 0
dist = 10000000
steps = 10000000
for cmd in B:
for _ in range(int(cmd[1:])):
cx += dir[cmd[0]][0]
cy += dir[cmd[0]][1]
step += 1
aStep = mapped[cx+10000][cy+10000]
aDist = abs(cx)+abs(cy)
if aStep != 0:
if (dist > aDist): dist = aDist
if (steps > aStep + step): steps = aStep + step
return dist, steps
def main():
A,B = readFile()
solA, solB = findIntersects(A, B)
print(solA, solB)
#writeFile(str(solA), str(solB))
if __name__ == '__main__': main() |
name = 'Urban Dictionary Therapy'
__all__ = ['UDTherapy',
'helper']
|
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 179 - Consecutive positive divisors
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
N = int(1e7)
n_factors = [1 for _ in range(N + 1)]
# can start at 2 because 1 is a divisor for all numbers and wont change the
# relative count.
# Factor counting loop
for i in range(2, N + 1):
n = i
while n < N:
n_factors[n] += 1
n += i
# Evaluate factor count array
count = 0
for i in range(N):
if n_factors[i] == n_factors[i + 1]:
count += 1
return count
if __name__ == "__main__":
print(run())
|
"""
Problem:
--------
Design a data structure that supports the following two operations:
- `void addNum(int num)`: Add a integer number from the data stream to the data structure.
- `double findMedian()`: Return the median of all elements so far.
"""
class MedianFinder:
def __init__(self):
"""
Initialize your data structure here.
"""
self.list = []
def addNum(self, num: int) -> None:
# Traverse through the list and check if `num` > ith element
# If yes, insert `num` in that index
# This keeps the list sorted at all times
for i in range(len(self.list)):
if num > self.list[i]:
self.list.insert(i, num)
return
# If `num` is the largest element or is the first one to be added
self.list.append(num)
def findMedian(self) -> float:
# Find index of the middle element (floor division by 2)
mid_index = len(self.list) // 2
if len(self.list) % 2 == 0:
# If number of elements = EVEN
# Return average of the middle 2 elements
return (self.list[mid_index - 1] + self.list[mid_index]) / 2
else:
# If number of elements = ODD
# Return the middle element
return self.list[mid_index]
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
|
class SimulateMode:
@staticmethod
def start_simulation(device, guide=None):
return
|
# Uses python3
n = int(input())
if n == 1:
print(1)
print(1)
quit()
W = n
prizes = []
for i in range(1, n):
if W>2*i:
prizes.append(i)
W -= i
else:
prizes.append(W)
break
print(len(prizes))
print(' '.join([str(i) for i in prizes])) |
# Question 8
# Print even numbers in a list, stop printing when the number is 237
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
print(numbers[i])
elif numbers[i] == 237:
break
# Alternative,
""" for x in numbers:
if x % 2 == 0:
print(x)
elif x == 237:
break """
|
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your first pizza!")
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your second pizza!") |
# markdownv2 python-telegram-bot specific
joined = '{} joined group `{}`'
not_joined = '{} is already in group `{}`'
left = '{} left group `{}`'
not_left = '{} did not join group `{}` before'
mention_failed = 'There are no users to mention'
no_groups = 'There are no groups for this chat'
# html python-telegram-bot specific
start_text = """
Hello!
@everyone_mention_bot here.
I am here to help you with multiple user mentions.
<b>Usage</b>:
Users that joined the group by <code>/join</code> command,
can be mentioned after typing one of those in your message:
<code>@all</code>, <code>@channel</code>, <code>@chat</code>, <code>@everyone</code>, <code>@group</code> or <code>@here</code>.
If you did create a group named <code>gaming</code>, simply use <code>@gaming</code> to call users from that group.
You can also use <code>/everyone</code> command.
<b>Commands</b>:
<pre>/join {group-name}</pre>
Joins (or creates if group did not exist before) group.
<pre>/leave {group-name}</pre>
Leaves (or deletes if no other users are left) the group
<pre>/everyone {group-name}</pre>
Mentions everyone that joined the group.
<pre>/groups</pre>
Show all created groups in this chat.
<pre>/start</pre>
Show start & help text
<b>Please note</b>
<code>{group-name}</code> is not required, <code>default</code> if not given.
"""
|
class A:
def fazer_algo(self):
print("Palmeiras")
def outro(self):
print("campeão")
class B:
def __init__(self):
self.a = A()
def fazer_algo(self):
#delega para self.a
return self.a.fazer_algo()
def outro(self):
#delegando novamente
return self.a.outro()
b = B()
print(b.fazer_algo())
print(b.outro())
|
"""Defines a rule for runsc test targets."""
load("@io_bazel_rules_go//go:def.bzl", _go_test = "go_test")
# runtime_test is a macro that will create targets to run the given test target
# with different runtime options.
def runtime_test(**kwargs):
"""Runs the given test target with different runtime options."""
name = kwargs["name"]
_go_test(**kwargs)
kwargs["name"] = name + "_hostnet"
kwargs["args"] = ["--runtime-type=hostnet"]
_go_test(**kwargs)
kwargs["name"] = name + "_kvm"
kwargs["args"] = ["--runtime-type=kvm"]
_go_test(**kwargs)
kwargs["name"] = name + "_overlay"
kwargs["args"] = ["--runtime-type=overlay"]
_go_test(**kwargs)
|
# Copyright 2019-2021 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.
"""utils"""
# input format begin
DEFAULT = "DefaultFormat"
NCHW = "NCHW"
NHWC = "NHWC"
HWCN = "HWCN"
NC1HWC0 = "NC1HWC0"
FRAC_Z = "FracZ"
# input format end
# fusion type begin
ELEMWISE = "ELEMWISE"
CONVLUTION = "CONVLUTION"
COMMREDUCE = "COMMREDUCE"
SEGMENT = "SEGMENT"
OPAQUE = "OPAQUE"
# fusion type end
BINDS = "binds" |
# -*- coding: utf-8 -*-
MNIST_DATASET_PATH = 'raw_data/mnist.pkl.gz'
TEST_FOLDER = 'test/'
TRAIN_FOLDER = 'train/'
MODEL_FILE_PATH = 'model/recognizer.pickle'
LABEL_ENCODER_FILE_PATH = 'model/label_encoder.pickle'
# Manual
DEMO_HELP_MSG = '\n' + \
'Input parameter is incorrect\n' + \
'Display help: \'python demo.py -h\''
TRAINER_HELP_MSG = '\n' + \
'Input parameter is incorrect\n' + \
'Display help: \'python extractor.py -h\''
|
#! /usr/bin/env python
def cut_the_sticks(a):
cuts = []
while len(a) > 0:
cutter = a.pop()
if cutter == 0:
continue
for i in range(len(a)):
a[i] -= cutter
cuts.append(len(a) + 1)
return cuts
if __name__ == '__main__':
_ = input()
value = map(int, input().split(' '))
res = cut_the_sticks(sorted(value, reverse=True))
for v in res:
print(v)
|
#pedir a altura e a largura de uma parede e dizer quantos litros de tinta vai gastar sabendo que cada litro de tinta pinta 2m2
altura = float(input('Qual a altura da parede? '))
largura = float(input('Qual a largura da parede? '))
area = altura * largura
tinta = (altura * largura) / 2
print('Voce tem a area de {}x{} e sua parede tem a area de: {}M² \n voce vai precisar de {:.2f} litros de tinta pra pintar a parede!!'.format(altura, largura, area, tinta))
|
nota1 = float(input('nota 1: '))
nota2 = float(input('nota 2: '))
media = (nota1 + nota2)/2
print('A media entre a nota 1 e a nota 2 é {}'.format(media))
|
num = int(input("Insira um numero para descobrir se este é par ou impar: "))
if num % 2 == 0:
print("Este numero é par")
else:
print("Este numero é impar")
|
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/pos_multie_print"
# docs_base_url = "https://[org_name].github.io/pos_multie_print"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "POS Multiple Print"
|
tanmuContent = '''
<style>
.barrage-input-tip {
z-index: 1999;
position: absolute;
left: 10px;
width: 179.883px;
height: 35.7422px;
line-height: 35.7422px;
border-radius: 35.7422px;
box-sizing: border-box;
color: rgb(255, 255, 255);
margin-left: 45.7031px;
background-color: {{ data.tanmuBtnColor }};
opacity: 0.65;
pointer-events: initial;
padding: 0px 16.9922px;
font-size: 14.0625px;
display: block;
}
.data-box{display:none}
.barrage_box_top{width:100%;height:160px;margin:0px auto;}
.barrage_box_top .barrage-row{margin-bottom:20px;}
.barrage_box_top .barrage-item{
background-color: {{ data.tanmuColor }};margin-bottom:10px; white-space:nowrap;color:{{ data.fontColor }}; font-size: 12px; transform: scale(1); opacity: 1; transition: all 0.65s ease-in 0s;padding: 6px 8px 0px 8px; height: 32px;display: inline-block;border-radius: 25px;
}
</style>
<div class="maka-barrage-dom" style="top: 0px; left: 0px; background-color: transparent; z-index: 1000;">
<div class="barrage-content" style="position: fixed; box-sizing: border-box; padding: 11.7188px; right: 0px; bottom: 0px; z-index: 1000; width: 100%; pointer-events: none; background: linear-gradient(rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.2) 100%);">
<div class="barrage-words row" style="margin-top: 11.7188px; height: 212.695px;"><div class="barrage-word" style="min-height: 32.2266px; line-height: 32.2266px; font-size: 12.8906px; padding: 4.10156px; border-radius: 22.8516px; bottom: 94.3359px; max-width: 310.547px; background-color: rgba(47, 50, 52, 0.6); transform: scale(1); opacity: 0; transition: bottom 2s ease-out 0s, opacity 0.75s linear 0.75s;">
</div>
</div>
<div class="barrage-bottom row" id="barrageBtn" style="padding-bottom: env(safe-area-inset-bottom); margin-top: 14.0625px; position: fixed; left: 11.7188px; bottom: 47px; pointer-events: initial;">
<div class="barrage-input-tip" data-toggle="modal" data-target="#myModal" style="background:{{ data.tanmuColor }}; width: 179.883px; height: 35.7422px; line-height: 35.7422px; border-radius: 35.7422px; box-sizing: border-box; color: rgb(255, 255, 255); margin-left: 45.7031px; background-color: rgb(47, 50, 52); opacity: 0.65; pointer-events: initial; padding: 0px 16.9922px; font-size: 14.0625px;">ฝากคำอวยพร...</div>
</div>
<div class="backdrop" style="position: fixed; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0); z-index: 999; display: none; top: 0px; left: 0px; pointer-events: initial;"></div>
<div class="barrage-btn tanBtn" style="padding-bottom: env(safe-area-inset-bottom); margin-top: 14.0625px; position: fixed; left: 11.7188px; bottom: 11.7188px; pointer-events: initial;">
<div class="correct-icon" id="tanmuOpen" style="background: url("https://i.ibb.co/1QmGHWV/danmu-open1.png") 0% 0% / contain no-repeat; border-radius: 100%; width: 35.7422px; height: 35.7422px;"></div>
<div class="close-icon" id="tanmuClose" style="background: url("https://i.ibb.co/QNwcxLx/danmu-close1.png") 0% 0% / contain no-repeat; border-radius: 100%; width: 35.7422px; height: 35.7422px; display: none;">
<b style="position: absolute; color: rgb(255, 255, 255); top: 2.92969px; left: 19.9219px; font-weight: 600; font-size: 8.78906px; transform: scale(0.8);">{{ data.greetings | length }}</b>
</div>
</div>
<div id="j-barrage-top" class="barrage_box barrage_box_top" style="position: fixed; box-sizing: border-box; padding: 0px; right: 0px; bottom: 0px; z-index: 1000; width: 100%; pointer-events: none;"></div>
</div>
<div class="barrage-input-wrap" id="modalShow" style="display: none; position: fixed; left: 0px; bottom: 0px;height: 0px; width: 100%; background-color:transparent; padding: 9.375px 11.7188px; box-sizing: border-box; z-index: 2000; pointer-events: initial;">
<!-- 模态框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div style="width:100%;" class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" style="cursor: pointer;" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">อวยพร</h4>
</div>
<div class="modal-body">
<form action="" id="form" class="form-horizontal">
<div class="form-group">
<div class="col-md-24" style="padding-left:10px;padding-right: 10px;">
<input type="text" class="form-control" style="width:100% !important;" name="name" placeholder="ชื่อ-นามสกุล" />
</div>
</div>
<div class="form-group">
<div class="col-md-24" style="padding-left:10px;padding-right: 10px;">
<input type="text" class="form-control" style="width:100% !important;" name="greetings" placeholder="คำอวยพร" />
</div>
</div>
<div class="form-group">
<div class="col-md-24 col-md-offset-2" style="padding-left:10px;padding-right: 10px;">
<button id="subBtn" type="submit" class="btn btn-primary" style="width:100%;">ส่ง</button>
</div>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</div>
</div>
<div class="alert alert-danger hide">ส่งคำอวยพรล้มเหลว!</div>
<div class="alert alert-success hide">ส่งคำอวยพรสำเร็จ!</div>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/bootstrapValidator.min.js"></script>
<script type="text/javascript" src="/static/js/index.js"></script>
<style type="text/css">
*{
padding:0;
margin:0;
}
a{
text-decoration: none;
}
.form-control{
display: inline-block;
width: auto;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
.btn{
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: 400;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.btn-primary {
color: #fff;
background-color: #337ab7;
border-color: #2e6da4;
}
/*组件主样式*/
.overflow-text{
display: block;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
opacity:0;
clear: both;
padding:0 10px;
border-radius: 10px;
box-sizing: border-box;
max-width: 100%;
color:#fff;
animation:colorchange 3s infinite alternate;
-webkit-animation:colorchange 3s infinite alternate; /*Safari and Chrome*/
}
@keyframes colorchange{
0%{
color:red;
}
50%{
color:green;
}
100%{
color:#6993f9;
}
}
/*组件主样式*/
.alert{
position: fixed;
width: 50%;
margin-left: 20%;
z-index: 2000;
}
</style>
<script type="text/javascript">
var Obj;
$.ajax({
//几个参数需要注意一下
type: "GET",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/api/v1/h5/greetings/"+{{ data.id }},//url
success: function (result) {
console.log(result);//打印服务端返回的数据(调试用)
if (result.code == 0) {
// 数据初始化
Obj = $('#j-barrage-top').barrage({
data : result.data, //数据列表
row : 1, //显示行数
time : 2500, //间隔时间
gap : 100, //每一个的间隙
position : 'fixed', //绝对定位
direction : 'bottom left', //方向
ismoseoverclose : true, //悬浮是否停止
height : 30, //设置单个div的高度
})
Obj.start();
} else {
alert("tanmu Error");
};
},
error : function() {
alert("tanmu Error");
}
});
</script>
<script>
$("#barrageBtn").click(function() {
var modalShowDiv = document.getElementById('modalShow');
modalShowDiv.style.display = 'block';
})
var kg = true; //给一个开关并赋值,用来进行后面的 if else 条件判断
$(".tanBtn").click(function() { //给button按钮一个点击事件
if (kg) { //进行判断
var tanmuOpenDiv= document.getElementById('tanmuOpen');
tanmuOpenDiv.style.display = 'block';
var tanmuCloseDiv= document.getElementById('tanmuClose');
tanmuCloseDiv.style.display='none';
Obj.start();
var barrageBtnDiv= document.getElementById('barrageBtn');
barrageBtnDiv.style.display = 'block';
} else {
var tanmuOpenDiv= document.getElementById('tanmuOpen');
tanmuOpenDiv.style.display = 'none';
var tanmuCloseDiv= document.getElementById('tanmuClose');
tanmuCloseDiv.style.display='block';
Obj.close();
var barrageBtnDiv= document.getElementById('barrageBtn');
barrageBtnDiv.style.display = 'none';
}
kg = !kg; //这里的感叹号是取反的意思,如果你没有写,当你点击切换回第一张图片时,就会不生效
})
$('#myModal').on('hidden.bs.modal', function (e) {
// 清空表单和验证
// Reset a form
document.getElementById("form").reset();
$('#form').bootstrapValidator("resetForm",true);
})
$('form').bootstrapValidator({
//默认提示
message: 'This value is not valid',
// 表单框里右侧的icon
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
excluded: [':disabled'],
submitHandler: function (validator, form, submitButton) {
// 表单提交成功时会调用此方法
// validator: 表单验证实例对象
// form jq对象 指定表单对象
// submitButton jq对象 指定提交按钮的对象
},
fields: {
name: {
message: 'ปรดกรอกชื่อ, ความยาวไม่เกิน 20 ตัวอักษร',
validators: {
notEmpty: { //不能为空
message: 'โปรดกรอกชื่อ'
},
stringLength: {
max: 20,
message: 'ความยาวไม่เกิน 20 ตัวอักษร'
},
}
},
greetings: {
message: 'โปรดกรอกคำอวยพร, ความยาวไม่เกิน 40 ตัวอักษร',
validators: {
notEmpty: {
message: 'โปรดกรอกคำอวยพร'
},
stringLength: {
max: 40,
message: 'ความยาวไม่เกิน 40 ตัวอักษร'
},
}
},
}
});
var that = this
$("#subBtn").click(function () { //非submit按钮点击后进行验证,如果是submit则无需此句直接验证
$("form").bootstrapValidator('validate'); //提交验证
if ($("form").data('bootstrapValidator').isValid()) { //获取验证结果,如果成功,执行下面代码
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/api/v1/h5/greetings/"+{{ data.id }},//url
data: $('#form').serialize(),
success: function (result) {
console.log(result);//打印服务端返回的数据(调试用)
if (result.code == 0) {
$("#myModal").modal('hide');
//添加评论
//此格式与dataa.js的数据格式必须一致
var addVal = {
text : result.data
}
//添加进数组
Obj.data.unshift(addVal);
$(".alert-success").addClass("show");
window.setTimeout(function(){
$(".alert-success").removeClass("show");
},1000);//显示的时间
} else {
$(".alert-danger").addClass("show");
window.setTimeout(function(){
$(".alert-danger").removeClass("show");
},1000);//显示的时间
};
},
error : function() {
{#alert("Error!");#}
$(".alert-danger").addClass("show");
window.setTimeout(function(){
$(".alert-danger").removeClass("show");
},1000);//显示的时间
}
});
}
});
</script>
''' |
# Moore Voting
# Majority Element
# Given an array of size n, find the majority element.
# The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# assume at leat one element
class Solution(object):
def majorityElement(self, nums):
count, major_num = 0, nums[0]
for num in nums:
if num == major_num:
count += 1
elif count == 0:
count, major_num = 1, num
else:
count -= 1
return major_num
# Majority Element II
class Solution(object):
def majorityElement(self, nums):
if not nums: return []
count1 = count2 = 0
major1 = major2 = nums[0]
for num in nums:
if num == major1:
count1 += 1
elif num == major2:
count2 += 1
elif count1 == 0:
count1, major1 = 1, num
elif count2 == 0:
count2, major2 = 1, num
else:
count1 -= 1
count2 -= 1
res = []
if nums.count(major1) > len(nums) / 3:
res.append(major1)
if major2 != major1 and nums.count(major2) > len(nums) / 3:
res.append(major2)
return res
|
n, k, v = int(input()), int(input()), []
for i in range(n): v.append(int(input()))
v = sorted(v, reverse=True)
print(k + v[k:].count(v[k-1]))
|
#! python3
# __author__ = "YangJiaHao"
# date: 2018/1/26
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
d = dict()
l, r = 0, 0
res = 0
while r < len(s):
if s[r] not in d:
d[s[r]] = None
r += 1
res = max(res, r - l)
else:
del d[s[l]]
l += 1
return res
class Solution2:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
lookup = {}
offset = -1
longest = 0
for idx, char in enumerate(s):
if char in lookup:
if offset < lookup[char]:
offset = lookup[char]
lookup[char] = idx
length = idx - offset
if length > longest:
longest = length
return longest
if __name__ == '__main__':
solution = Solution()
theMax = solution.lengthOfLongestSubstring("aaaabc")
print(theMax)
|
def get_field_name_from_line(line):
return line.split(':')[1].strip()
def remove_description(line):
if '-' in line:
return line.split('-')[0].strip()
else:
return line
def split_multiple_field_names(line):
if ',' in line:
field_names = line.split(',')
return map(lambda x: x.strip().upper(), field_names)
else:
return [line.upper()]
f = open('../data/8-20-17.nm2')
out = open('../data/8-20-17-field-names.txt', 'w')
for line in f:
if line.startswith('FieldName'):
field_name = get_field_name_from_line(line)
field_name = remove_description(field_name)
field_name_list = split_multiple_field_names(field_name)
for name in field_name_list:
out.writelines([name, '\n'])
f.close()
out.close() |
# -*- coding: utf-8 -*-#
'''
@Project : ClassicAlgorighthms
@File : HashTable.py
@USER : ZZZZZ
@TIME : 2021/4/25 18:25
'''
class Node():
'''
链地址法解决冲突的结点
'''
def __init__(self, value = None, next = None):
self.val = value
self.next = next
class HashTable():
'''
哈希表是根据 值 直接进行访问的数据结构。
具体来说,通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。
这个映射函数叫做 散列函数,存放记录的数组叫做 散列表。
其中有两个关键点:
1. 如何把值映射到一个位置?
(1) * 除余法: h(k) = k mod p
(2) 平方散列法: h(k) = (value^2) >> 28
(3) 斐波那契散列法: h(k) = (value * 2654435769(MAX_INT32) ) >> 28
2. 如果两个值映射到了同一个位置,该怎么办?
(1) 开放定址法:线性重散列 二次重散列
(2) * 链地址法:每个地址作为一个链来存储
(3) 再散列法:构造多个hash函数
Notice:
想想,如果在链地址法中,将每个表结点作为一颗平衡二叉树的根结点,那么每个位置都将成为一棵平衡二叉树
查找时间复杂度变成了log2N,并且由于经过了哈希,分散了结点数量,真实运行起来会更快一些
本例中用除余法取哈希值
用链地址法解决冲突
'''
def __init__(self):
# 哈希表的大小
self._table_size = 11
# 哈希表,每个元素是个表头,采用头插法放入元素
self._table = []
for i in range(self._table_size):
self._table.append(Node())
# 元素个数
self._count = 0
def init(self, values):
'''
通过一个列表构造哈希表
:param values: 待构造的列表
:return: None
'''
for value in values:
self.insert(value)
def insert(self, value):
'''
向哈希表中插入一个值
:param value: 待插入值
:return: None
'''
# 找到了它的位置
index = self._hash(value)
# 为这个值建立结点
node = Node(value = value)
# 头插法插入对应的位置
node.next = self._table[index].next
self._table[index].next = node
# 数量+1
self._count += 1
def delete(self, value):
'''
从哈希表中删除一个值
:param value: 待删除值
:return: None
'''
# 找到它的哈希位置
index = self._hash(value)
# 在链表中进行查询
pre_node = self._table[index]
node = self._table[index].next
if self.search(value) == False:
raise Exception("no this value!")
# 注意,这里按照链表的构造,只要查到这个值,是可以通过将它的下一个值赋给它,将下一个结点删掉的操作来进行的。
# 但是可能查到的这个值就是最后一个结点,那么上述方法行不通。
while node != None:
# 找到值了,停下来
if node.val == value:
break
else:
pre_node = pre_node.next
node = node.next
# 把node删除
pre_node.next = node.next
def search(self, value):
'''
从哈希表中查找一个值
:param value: 待查找的值
:return: 如果找到这个值,返回True;否则,返回False
'''
# 找到它的哈希位置
index = self._hash(value)
# 在链表中进行查询
node = self._table[index]
while node != None:
if node.val == value:
return True
node = node.next
# 如果走到这,肯定就没查找
return False
# ---------------------------- 私有方法 ----------------------------
def _hash(self, value):
'''
哈希函数,通过给定的值,计算出一个位置
:param value: 存入哈希表的值
:return: 散列表中的位置
'''
return value % self._table_size
# ---------------------------- 内部方法 ----------------------------
def __str__(self):
final_res = ""
for i in range(self._table_size):
res = []
node = self._table[i].next
while node != None:
res.append(str(node.val))
node = node.next
final_res += "索引为{}的位置的值为: {}\n".format(i, ",".join(res))
return final_res
if __name__ == "__main__":
ht = HashTable()
# 初始化
ht.init([2, 3, 5, 8, 9, 10, 2, 9, 1, 5, 2, 1, 7, 9, 11])
print("初始化后的哈希表为:\n{}".format(ht))
# 插入结点
ht.insert(9)
print("插入值后的哈希表为:\n{}".format(ht))
# 删除结点
ht.delete(11)
print("删除值后的哈希表为:\n{}".format(ht))
# 查找结点
res = ht.search(8)
print("查找值为8的结果为: {}".format(res))
|
class Circle:
def __init__(self, radius):
self.radius = radius
def compute_area(self):
return self.radius ** 2 * 3.14
circle = Circle(2)
print("Area of circuit: " + str(circle.compute_area()))
|
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
i, j, result, carry = len(num1) - 1, len(num2) - 1, '', 0
while i >= 0 or j >= 0:
if i >= 0:
carry += ord(num1[i]) - ord('0')
if j >= 0:
carry += ord(num2[j]) - ord('0')
result += chr(carry % 10 + ord('0'))
carry //= 10
i -= 1
j -= 1
if carry == 1:
result += '1'
return result[::-1]
|
word = input('Enter a word')
len = len(word)
for i in range(len-1, -1, -1):
print(word[i], end='')
|
ss = input('Please give me a string: ')
if ss == ss[::-1]:
print("Yes, %s is a palindrome." % ss)
else:
print('Nevermind, %s isn\'t a palindrome.' % ss)
|
class AbridgerError(Exception):
pass
class ConfigFileLoaderError(AbridgerError):
pass
class IncludeError(ConfigFileLoaderError):
pass
class DataError(ConfigFileLoaderError):
pass
class FileNotFoundError(ConfigFileLoaderError):
pass
class DatabaseUrlError(AbridgerError):
pass
class ExtractionModelError(AbridgerError):
pass
class UnknownTableError(AbridgerError):
pass
class UnknownColumnError(AbridgerError):
pass
class InvalidConfigError(ExtractionModelError):
pass
class RelationIntegrityError(ExtractionModelError):
pass
class GeneratorError(Exception):
pass
class CyclicDependencyError(GeneratorError):
pass
|
def aumentar(preco, taxa):
p = preco + (preco * taxa/100)
return p
def diminuir(preco, taxa):
p = preco - (preco * taxa/100)
return p
def dobro(preco):
p = preco * 2
return p
def metade(preco):
p = preco / 2
return p
|
DOMAIN = "fitx"
ICON = "mdi:weight-lifter"
CONF_LOCATIONS = 'locations'
CONF_ID = 'id'
ATTR_ADDRESS = "address"
ATTR_STUDIO_NAME = "studioName"
ATTR_ID = CONF_ID
ATTR_URL = "url"
DEFAULT_ENDPOINT = "https://www.fitx.de/fitnessstudios/{id}"
REQUEST_METHOD = "GET"
REQUEST_AUTH = None
REQUEST_HEADERS = None
REQUEST_PAYLOAD = None
REQUEST_VERIFY_SSL = True |
#!/usr/bin/env python3
# coding: UTF-8
'''!
module description
@author <A href="email:fulkgl@gmail.com">George L Fulk</A>
'''
__version__ = 0.01
def main():
'''!
main description
'''
print("Hello world")
return 0
if __name__ == "__main__":
# command line entry point
main()
# END #
|
# https://www.facebook.com/hackercup/problem/169401886867367/
__author__ = "Moonis Javed"
__email__ = "monis.javed@gmail.com"
def numberOfDays(arr):
arr = sorted(arr)
n = 0
while len(arr) > 0:
k = arr[-1]
w = k
del arr[-1]
while w <= 50:
try:
del arr[0]
w += k
except:
break
if w > 50:
n += 1
return n
if __name__ == "__main__":
f = open("input2.txt").read().split("\n")
writeF = open("output2.txt","w")
n = int(f[0])
del f[0]
for i in range(1,n+1):
t = int(f[0])
del f[0]
arr =[None]*t
for j in xrange(t):
arr[j] = int(f[0])
del f[0]
writeF.write("Case #%d: %d\n" % (i,numberOfDays(arr)))
# print i
|
class Robot:
def __init__(self, left="MOTOR4", right="MOTOR2", config=1):
print("init")
def forward(self):
print("forward")
def backward(self):
print("backward")
def left(self):
print("left")
def right(self):
print("right")
def stop(self):
print("stop")
|
"""Exceptions."""
class OandaError(Exception):
""" Generic error class, catches oanda response errors
"""
def __init__(self, error_response):
self.error_response = error_response
msg = f"OANDA API returned error code {error_response['code']} ({error_response['message']}) "
super(OandaError, self).__init__(msg)
class BadEnvironment(Exception):
"""environment should be: sandbox, practice or live."""
def __init__(self, environment):
msg = f"Environment '{environment}' does not exist"
super(BadEnvironment, self).__init__(msg)
|
"""
Entradas
monto de dinero presupuestal-->float-->a
Salidas
dinero correspondiente para ginecologia-->float-->b
dinero correspondiente para traumatologia-->float-->c
dinero correspondiente para pediatria-->float-->d
"""
a=float(input("Presupuesto anual al Hospital rural "))
b=a*0.40
c=a*0.30
d=a*0.30
print("El presupuesto del hospital rural para ginecología es: "+str(b))
print("El presupuesto del hospital rural para traumatología es: "+str(c))
print("El presupuesto del hospital rural para pediatría es: "+str(d)) |
'''
Created on 1.12.2016
@author: Darren
''''''
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
"
'''
|
#Represents an object
class Object:
def __init__(self,ID,name):
self.name = name
self.ID = ID
self.importance = 1
#keep track of the events in which this file was the object
self.modifiedIn = []
self.addedIn = []
self.deletedIn = []
def getName(self):
return self.name
def getID(self):
return self.ID
def getImportance(self):
return self.importance
#Add an event to the right list according to the modifier
#@param event : Event object
#@param modifier : "Added" "Deleted" or "Modified"
def addEvent(self, event, modifier):
if modifier == "Added":
if(not event in self.addedIn):
self.addedIn.append(event)
elif modifier == "Deleted":
if(not event in self.deletedIn):
self.deletedIn.append(event)
else:
if(not event in self.modifiedIn):
self.modifiedIn.append(event)
#Function that calculates the importance of a object based on a ratio:
#the number of months in which it was changed / the number of months is exists
#@param firstAndLastTimeStamp = tuple with the first timestamp of the log and the last
def calculateImportanceRatio(self,firstAndLastTimeStamp):
addedTimestamps = []
for event in self.addedIn:
addedTimestamps.append(event.getTimestamp())
addedTimestamps.sort()
deletedTimestamps = []
for event in self.deletedIn:
deletedTimestamps.append(event.getTimestamp())
deletedTimestamps.sort()
timestamps = []
for event in self.modifiedIn:
timestamps.append(event.getTimestamp())
for event in self.addedIn:
timestamps.append(event.getTimestamp())
numberOfMonthsExistence = 0
numberOfMonthsChanged = 0
iteratorAdded = 0
iteratorDeleted = 0
if(not addedTimestamps):
beginstamp = firstAndLastTimeStamp[0]
#only 2 scenarios possible : 0 or 1 deleted timestamp
if(not deletedTimestamps):
endstamp = firstAndLastTimeStamp[1]
else:
endstamp = deletedTimestamps[0]
numberOfMonthsExistence += self.calculateNumberOfMonthsExistence(beginstamp,endstamp)
numberOfMonthsChanged += self.calculateNumberOfMonthsChanged(beginstamp,endstamp,timestamps)
while(iteratorAdded < len(addedTimestamps)):
beginstamp = addedTimestamps[iteratorAdded]
iteratorAdded += 1
if(iteratorDeleted == len(deletedTimestamps)):
#all deleted stamps are done
endstamp = firstAndLastTimeStamp[1]
else:
endstamp = deletedTimestamps[iteratorDeleted]
iteratorDeleted += 1
if(endstamp < beginstamp):
beginstamp = firstAndLastTimeStamp[0]
iteratorAdded -= 1
numberOfMonthsExistence += self.calculateNumberOfMonthsExistence(beginstamp,endstamp)
numberOfMonthsChanged += self.calculateNumberOfMonthsChanged(beginstamp,endstamp,timestamps)
importance = numberOfMonthsChanged/numberOfMonthsExistence
#TO DO: what if importance = 0 ?
if importance == 0 :
importance = 0.00001
self.importance = importance
#calculate how many months this object exists between these 2 timestamps
def calculateNumberOfMonthsExistence(self,beginstamp, endstamp):
numberOfMonths = abs(endstamp.year - beginstamp.year) * 12 + abs(endstamp.month - beginstamp.month)
numberOfMonths += 1
return numberOfMonths
#calculate in how many months between begin and end the object was changed
#@param timestamps = list of timestamps when the file was committed
def calculateNumberOfMonthsChanged(self,beginstamp,endstamp,timestamps):
timestamps.sort()
numberOfMonths = 0
currentMonth = -1
currentYear = -1
for stamp in timestamps:
#only consider the timestamps between the timespan
if((stamp >= beginstamp)and(stamp <= endstamp)):
if((stamp.month != currentMonth) or (currentYear != stamp.year)):
currentMonth = stamp.month
currentYear = stamp.year
numberOfMonths += 1
return numberOfMonths
|
def uint(x):
# casts x to unsigned int (1 byte)
return x & 0xff
def chunkify(string, size):
# breaks up string into chunks of size
chunks = []
for i in range(0, len(string), size):
chunks.append(string[i:i + size])
return chunks
def gen_rcons(rounds):
# generates and returns round constants
# the round constants don't depend on the
# key so these constants could have been
# hard coded, but I wanted to build it anyway
rcons = []
for i in range(rounds):
value = 0
if i + 1 > 1:
if rcons[i - 1] >= 0x80:
value = uint((2 * rcons[i - 1]) ^ 0x11b)
else:
value = uint(2 * rcons[i - 1])
else:
value = 1
rcons.append(value)
return list(map(lambda x: x << 24, rcons))
def generate_round_keys(key, rounds, sbox):
# Generates round keys based on main key
# basic variables used for looping, etc.
key_size = len(key) * 8
R = rounds + 1
rcons = gen_rcons(rounds) # get round key constants
N = key_size // 32
# split key into 32 bit words and parse to int
K = [int(k.encode("utf-8").hex(), 16) for k in chunkify(key, 4)]
W = [0] * (4 * R)
# main loop to generate expanded round subkeys
for i in range(4 * R):
if i < N:
W[i] = K[i]
elif i >= N and i % N == 0:
word_str = hex(W[i - 1])[2:].zfill(8) # turn int to 8 digit hex
rot = word_str[2:] + word_str[:2] # rotate left 1 byte
hex_bytes = chunkify(rot, 2) # split into byte chunks
subvals = [sbox(hexb) for hexb in hex_bytes] # sub out hex bytes with s-box
sval = (subvals[0] << 24) \
+ (subvals[1] << 16) \
+ (subvals[2] << 8) \
+ subvals[3] # concat hex bytes and parse to 32 bit int
W[i] = W[i - N] ^ sval ^ rcons[(i // N) - 1]
elif i >= N and N > 6 and i % N == 4:
word_str = hex(W[i - 1])[2:].zfill(8) # turn int to 8 digit hex
hex_bytes = chunkify(word_str, 2) # split into byte chunks
subvals = [sbox(hexb) for hexb in hex_bytes] # sub out hex bytes with s-box
sval = (subvals[0] << 24) \
+ (subvals[1] << 16) \
+ (subvals[2] << 8) \
+ subvals[3] # concat hex bytes and parse to 32 bit int
W[i] = W[i - N] ^ sval
else:
W[i] = W[i - N] ^ W[i - 1]
# subkeys are all 128 bits, but each entry is 32 bits
# so combine all entries by groups of 4 for later use
return [tuple(W[i:i + 4]) for i in range(0, len(W), 4)]
def add_round_key(state, round_key):
# adds each byte of the round key to the
# respective byte of the state
key = []
# round key is a tuple of 4, 32 bit ints
for rk in round_key:
hx = hex(rk)[2:].zfill(8) # turn int to hex
# add each byte to the key list as an int
key += [int(hx[i:i + 2], 16) for i in range(0, len(hx), 2)]
for i in range(len(state)):
# run through the state and add each byte to the
# respective byte in the key
key_state = [key[j] for j in range(i, len(key), 4)]
state[i] = [sv ^ kv for sv, kv in zip(state[i], key_state)]
return state
|
def modulus_three(n):
r = n % 3
if r == 0:
print("Multiple of 3")
elif r == 1:
print("Remainder 1")
else:
assert r == 2, "Remainder is not 2"
print("Remainder 2")
def modulus_four(n):
r = n % 4
if r == 0:
print("Multiple of 4")
elif r == 1:
print("Remainder 1")
elif r == 2:
print("Remainder 2")
elif r == 3:
print("Remainder 3")
else:
assert False, "This should never happen"
if __name__ == '__main__':
print(modulus_four(5)) |
""" Contains classes to handle batch data components """
class ComponentDescriptor:
""" Class for handling one component item """
def __init__(self, component, default=None):
self._component = component
self._default = default
def __get__(self, instance, cls):
try:
if instance.data is None:
out = self._default
elif instance.pos is None:
out = instance.data[self._component]
else:
pos = instance.pos[self._component]
data = instance.data[self._component]
out = data[pos] if data is not None else self._default
except IndexError:
out = self._default
return out
def __set__(self, instance, value):
if instance.pos is None:
new_data = list(instance.data) if instance.data is not None else []
new_data = new_data + [None for _ in range(max(len(instance.components) - len(new_data), 0))]
new_data[self._component] = value
instance.data = tuple(new_data)
else:
pos = instance.pos[self._component]
instance.data[self._component][pos] = value
class BaseComponentsTuple:
""" Base class for a component tuple """
components = None
def __init__(self, data=None, pos=None):
if isinstance(data, BaseComponentsTuple):
self.data = data.data
else:
self.data = data
if pos is not None and not isinstance(pos, list):
pos = [pos for _ in self.components]
self.pos = pos
def __str__(self):
s = ''
for comp in self.components:
d = getattr(self, comp)
s += comp + '\n' + str(d) + '\n'
return s
def as_tuple(self, components=None):
""" Return components data as a tuple """
components = tuple(components or self.components)
return tuple(getattr(self, comp) for comp in components)
class MetaComponentsTuple(type):
""" Class factory for a component tuple """
def __init__(cls, *args, **kwargs):
_ = kwargs
super().__init__(*args, (BaseComponentsTuple,), {})
def __new__(mcs, name, components):
comp_class = super().__new__(mcs, name, (BaseComponentsTuple,), {})
comp_class.components = components
for i, comp in enumerate(components):
setattr(comp_class, comp, ComponentDescriptor(i))
globals()[comp_class.__name__] = comp_class
return comp_class
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 03:26:16 2019
@author: sodatab
MITx: 6.00.1x
"""
"""
03.6-Finger How Many
---------------------
Consider the following sequence of expressions:
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
We want to write some simple procedures that work on dictionaries to return information.
First, write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary.
"""
"""Answer Script:"""
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
sum = 0
for i in aDict.values():
sum += len(i)
return sum
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.