content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 08:54:01 2019
@author: balam
"""
|
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2
leftHalf = arr[:mid] # 56,24,93,17
rightHalf = arr[mid:] # 77,31,44,55,20
mergeSort(leftHalf)
mergeSort(rightHalf)
i = j = k = 0
while i < len(leftHalf) and j < len(rightHalf):
if leftHalf[i] < rightHalf[j]:
arr[k] = leftHalf[i]
i += 1
else:
arr[k] = rightHalf[j]
j += 1
k += 1
while i < len(leftHalf):
arr[k] = leftHalf[i]
i += 1
k += 1
while j < len(rightHalf):
arr[k] = rightHalf[j]
j += 1
k += 1
arr = [56,24,93,17,77,31,44,55,20]
mergeSort(arr)
print(arr) |
# for循环是一种遍历列表的有效方式, 但在for循环中不应修改列表, 否则将导致Python难以跟踪其中的元素.
# 要在遍历列表的同时对其进行修改, 可使用while循环.
# 在列表之间移动元素
unconfirmed_users = ['alice', 'brian', 'candace'] # 待验证用户列表
confirmed_users = [] # 已验证用户列表
# 遍历列表对用户进行验证
while unconfirmed_users: # 当列表不为空时返回True, 当列表为空时, 返回False
current_user = unconfirmed_users.pop() # 取出需要验证的用户
print('验证用户: ' + current_user.title())
confirmed_users.append(current_user) # 将已验证的移到已验证用户列表
print('\n以下用户已经经过验证: ')
for user in confirmed_users:
print('\t' + user)
print('\n未完成验证的用户为: ')
print(unconfirmed_users)
# 为什么不能用for代替while
print('\n')
print('采用for循环的方式来实现上述操作: ')
unconfirmed_users = ['alice', 'brian', 'candace'] # 待验证用户列表
confirmed_users = [] # 已验证用户列表
for unconfirmed_user in unconfirmed_users:
# current_user = unconfirmed_users.pop() # for循环中, 不能采用pop来删除元素, 会出现遍历问题
print('验证用户: ' + unconfirmed_user.title())
confirmed_users.append(unconfirmed_user) # 将已验证的移到已验证用户列表
# unconfirmed_users.remove(unconfirmed_user) # for循环中, 不能采用remove来删除元素, 会出现遍历问题
print('\n以下用户已经经过验证: ')
for user in confirmed_users:
print('\t' + user)
print('\n未完成验证的用户为: ')
print(unconfirmed_users)
# 删除包含特定值的所有列表元素
# 通过while循环不断判断列表中是否存在特定元素, 存在就将它删除
print('\n')
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print('初始化的数据为: ')
print(pets)
cat_name = 'cat'
while cat_name in pets:
pets.remove(cat_name)
print('删除名称为' + cat_name + '的宠物后, 宠物列表为: ')
print(pets)
# 使用用户输入来填充字典
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ") # 获取用户输入的姓名
response = input("Which mountain would you like to climb someday? ") # 获取用户想要爬的山
responses[name] = response # 将用户的数据存入字典
repeat = input('Would you like to let another person respond? (yes/ no) ')
if repeat == 'no': # 判断调查是否结束
polling_active = False
print('\n---Poll Result---') # 打印调查结果
for name, response in responses.items():
print(name + ' would like to climb ' + response + '.') |
# ask for int, report runnig total / version 1
num = 0
total = 0
while num != -1:
total = total + num
print("total so far = " + str(total))
num = int(input("next int: "))
# ask for int, report runnig total / version 2
total = 0
while True:
num = int(input("next int: "))
if num == -1:
break
total += num
print("total so far = " + str(total))
# check if number is prime
num = int(input("int: "))
total = 0
for x in range(2, num):
if num % x == 0:
print(str(num) + " is NOT prime")
break # we don't need to continue checking
else:
print(str(num) + " is PRIME")
# check multiple numbers
while True:
num = int(input("int: "))
if num == -1:
break
if num < 3:
print("int must be greater than 2")
continue
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(str(num) + " is PRIME")
else:
print(str(num) + " is NOT prime")
# print out primes up to 100
for i in range(3, 101):
is_prime = True
for j in range(2, i-1):
if i % j == 0:
is_prime = False
break
if is_prime:
print(str(i) + " is PRIME")
else:
print(str(i) + " is NOT prime")
# print multilication table
for i in range(1, 11):
for j in range(1, 11):
print("%3d" % (i * j), end=' ')
print()
print()
|
# Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images.
#
# Example 1:
#
#
#
#
# Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
# Output: [1,4,2,7,5,3,8,6,9]
#
#
# Example 2:
#
#
#
#
# Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
# Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
#
#
# Example 3:
#
#
# Input: nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]]
# Output: [1,4,2,5,3,8,6,9,7,10,11]
#
#
# Example 4:
#
#
# Input: nums = [[1,2,3,4,5,6]]
# Output: [1,2,3,4,5,6]
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 10^5
# 1 <= nums[i].length <= 10^5
# 1 <= nums[i][j] <= 10^9
# There at most 10^5 elements in nums.
#
#
class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
m = []
for i, row in enumerate(nums):
for j, v in enumerate(row):
if i + j >= len(m): m.append([])
m[i + j].append(v)
return [v for d in m for v in reversed(d)]
|
#!/usr/bin/env python3
#################################################################################
# #
# Program purpose: Generate message based on user input. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : September 10, 2019 #
# #
#################################################################################
def get_message(info: {}):
basic_info = f"Hi there {info['name']}!, nice knowing you!"
if int(info['age']) < 18:
basic_info += f" You're relatively young at {info['age']}."
if 18 < int(info['age']) < 30:
if info['gender'] == "male":
basic_info += f" Becoming a man, huh!"
else:
basic_info += f" Becoming a woman, hun!"
elif int(info['age']) < 18:
basic_info += " Enjoy your teens"
else:
basic_info += " You're getting old, you know!"
basic_info += f" Living in {info['location']} should be pretty fun!"
return basic_info
if __name__ == "__main__":
name = str(input("Enter your name: "))
gender = str(input("Enter your gender: "))
age = 0
cont = True
while cont:
try:
age = int(input("Enter your age: "))
cont = False
except ValueError as ve:
print(f"[ERROR]: {ve}")
location = str(input("Where do you live: "))
print(get_message({'name': name, 'gender': gender, 'age': age, 'location': location}))
|
class Tree:
def __init__(self):
self.left = None
self.right = None
self.data = None
def init_left_child(self):
self.left = Tree()
def init_right_child(self):
self.right = Tree()
def init_both_childs(self):
self.init_left_child()
self.init_right_child()
def init_data(self, data):
self.data = data
def init_both_childs_and_data(self, data):
self.init_both_childs()
self.init_data(data)
def main():
root = Tree()
root.init_both_childs()
|
'''
Title : Loops
Subdomain : Introduction
Domain : Python
Author : Kalpak Seal
Created : 28 September 2016
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(raw_input())
for i in range(0, n):
print (i ** 2) |
local_val = 'magical creature'
def square(x):
return x * x
class User:
def __init__(self, name):
self.name = name
def say_hello(self):
return 'Hello'
# This conditional allows us to run certain blocks of code depending on which file they're in
if __name__ == "__main__":
print('the file is being executed directly')
else:
print('the file is being executed because it is imported by another file, this file is called', __name__)
pass
# print(square(5))
# user = User("Luigi")
# print(user.name)
# print(user.say_hello())
# print(__name__)
|
t = int(input())
for _ in range(t):
a, b = [int(x) for x in input().split()]
print(a * b)
|
"""
アドオンのデフォルト設定を定義する。
この定義は `addons/アドオン名/settings/local.py` に記述された設定により上書きされる。
"""
# NodeSettingsモデル `models.py` の `param_1` のデフォルト値
DEFAULT_PARAM_1 = 'This is test!'
|
"""Rules to work with protoc plugins in a language agnostic manner.
"""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@rules_proto//proto:defs.bzl", "ProtoInfo")
load("//protoc:providers.bzl", "ProtocPluginInfo")
_DEFAULT_PROTOC = "@com_google_protobuf//:protoc"
def run_protoc(
ctx,
protos,
protoc,
plugin,
options,
outputs,
plugin_out = ".",
data = []):
"""Run protoc with a plugin.
Args:
ctx: The Bazel context used to create actions.
protos (list of ProtoInfo): The proto libraries to generate code for.
protoc (executable): The protoc executable.
plugin (executable): The plugin executable.
options (list of str): List of options passed to the plugin.
outputs (list of File): List of files that are going to be generated by
the plugin.
plugin_out (str): The output root to generate the files to. This will be
passed as --<plugin-name>_out=<plugin_out> to the protoc executable.
data (depset of File): Additional files added to the action as inputs.
"""
# Merge proto root paths of all protos. Each proto root path will be passed
# with the --proto_path (-I) option to protoc.
proto_roots = depset(transitive = [p.transitive_proto_path for p in protos])
args = ctx.actions.args()
for root in proto_roots.to_list():
args.add("--proto_path=" + root)
# actually name does not matter
name = plugin.basename.replace(".exe", "")
args.add("--plugin=protoc-gen-" + name + "=" + plugin.path)
# Add the output prefix. Protoc will put all files that the plugin returns
# other this folder. E.g. a retuned file `a/b/c.pb.go` will then be placed
# and thus be generated under `<plugin_out>/a/b/c.pb.go`.
# The user provided plugin_out is relative to the workspace directory. Join
# with the Bazel bin directory to generate the output where it is expected
# by Bazel (bazel-out/{arch}/bin/<plugin_out>).
plugin_out = paths.join(ctx.bin_dir.path, plugin_out)
args.add("--" + name + "_out=" + plugin_out)
# Add option arguments.
for opt in options:
args.add("--" + name + "_opt=" + opt)
# Direct sources that are requested on command line. For these corresponding
# files will be generated.
for proto in protos:
args.add_all(proto.direct_sources)
# Collect inputs.
direct_sources = [] # list of File
for proto in protos:
direct_sources.extend(proto.direct_sources)
transitive_sources = [p.transitive_sources for p in protos] # list of depsets
inputs = depset(direct_sources, transitive = transitive_sources + [data]) # data is a depset
ctx.actions.run_shell(
inputs = inputs,
outputs = outputs,
command = "mkdir -p {} && {} $@".format(plugin_out, protoc.path),
arguments = [args],
mnemonic = "ProtocPlugins",
tools = [protoc, plugin],
progress_message = "Generating plugin output in {}".format(plugin_out),
)
def _protoc_output_impl(ctx):
protos = [p[ProtoInfo] for p in ctx.attr.protos]
# Default the plugin_out parameter to <rule_dir>/<target_name> if not specified.
plugin_out = ctx.attr.plugin_out
if plugin_out == "":
plugin_out = paths.join(ctx.label.package, ctx.label.name)
# Call the plugin provided output function to obtain the filenames that the plugin
# is going to generated. See the documentation of ProtocPluginInfo for more information
# how that works.
plugin_info = ctx.attr.plugin[ProtocPluginInfo]
filenames = plugin_info.outputs(protos, ctx.attr.outputs, **plugin_info.outputs_kwargs)
outputs = []
for file in filenames:
out_full_name = paths.join(plugin_out, file)
if not out_full_name.startswith(ctx.label.package):
fail("""Trying to generate an output file named \"{}\" that is not under the current package \"{}/\".
Bazel requires files to be generated in/below the package of their corresponging rule.""".format(out_name, ctx.label.package))
# Make the output path relative to ctx.label.package. When declaring files
# with ctx.actions.declare_file the file is always assumed to be relative
# to the current package.
out_name = paths.relativize(out_full_name, ctx.label.package)
out = ctx.actions.declare_file(out_name)
outputs.append(out)
expanded_options = []
for opt in ctx.attr.options:
# TODO: $(locations ...) produces a space-separated list of output paths,
# this must somewhat be handeled since it is passed directly to the
# command line via "key=value value value".
expanded_options.append(ctx.expand_location(opt, ctx.attr.data))
run_protoc(
ctx = ctx,
protos = protos,
protoc = ctx.executable.protoc,
plugin = plugin_info.executable,
outputs = outputs,
options = expanded_options + plugin_info.default_options,
plugin_out = plugin_out,
data = depset(ctx.files.data, transitive = [plugin_info.runfiles.files]),
)
return DefaultInfo(files = depset(outputs))
protoc_output = rule(
implementation = _protoc_output_impl,
doc = """Runs a protoc plugin.""",
attrs = {
"protos": attr.label_list(
doc = "The proto libraries to generate code for.",
providers = [ProtoInfo],
allow_empty = False,
),
"plugin": attr.label(
doc = "The plugin to run.",
providers = [ProtocPluginInfo],
mandatory = True,
),
"outputs": attr.string_list(
doc = """Optional output attributes passed to the plugins.
For plugin that define the their outputs using predeclared outputs,
this is the list of predeclared outputs.
See ProtocPluginInfo.output for more information.""",
),
"options": attr.string_list(
doc = """Options passed to the plugin.
For example: `["x=3", "y=5"]` will be passed as
```
--<plugin-name>_opt=x=3 --<plugin-name>_opt=y=5
```
to the command line line when running protoc with the plugin (`<plugin-name>`).
The `options` are subject to ctx.expanded_locations: For example, use
```
"config=$(location :my_data_file)"
```
to obtain the runfile location of `:my_data_file` and passed it as `config` option to the plugin.
`:my_data_file` must be passed in the `data` attribute for the expansion to work.
Do not use the `locations` (note the `s`) directive.
""",
),
"data": attr.label_list(
doc = "Files added to the actions execution environment such that the plugin can access them.",
allow_files = True,
),
"plugin_out": attr.string(
default = "",
doc = """The output root to generate the files to. This will be passed as --<plugin-name>_out=<plugin_out> to the protoc executable.
Defaults to `<bazel_package>/<target_name>/`.
When using a different value, this will affect where to plugin generates its outputs files to.
Each file that the plugin returns will be placed under `<plugin_out>/<generated_filename>`.
Bazel requires that all files must be generated under the current Bazel package,
so when setting `plugin_out` set it in a way that the resulting outputs are generated accordingly.""",
),
"protoc": attr.label(
executable = True,
doc = "The protoc executable.",
cfg = "exec",
allow_files = True,
default = Label(_DEFAULT_PROTOC),
),
},
)
|
# coding: utf-8
class LNode:
""" 单链表节点 """
def __init__(self, value, next_=None):
self.value = value
self.next_ = next_
def reverse_link_list(link_list):
""" 翻转单链表 """
if not link_list:
return
current = link_list.next_
link_list.next_ = None
pre = link_list
while current:
_next = current.next_
current.next_ = pre
pre = current
current = _next
return pre
if __name__ == '__main__':
link_list = LNode('a', LNode('b', LNode('c', LNode('d', LNode('e')))))
print("before reverse".center(80, '-'))
cursor = link_list
while cursor:
print(cursor.value)
cursor = cursor.next_
print("after reverse".center(80, '-'))
ret = reverse_link_list(link_list)
cursor = ret
while cursor:
print(cursor.value)
cursor = cursor.next_
|
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
def backtrack(pos,cur,target):
if target == 0 :
res.append(cur.copy())
if target <= 0 :
return
prev = -1
for i in range(pos,len(candidates)):
if candidates[i] == prev :
continue
cur.append(candidates[i])
backtrack(i+1,cur,target - candidates[i] )
cur.pop()
prev = candidates[i]
backtrack(0,[],target)
return res
|
class NumString:
def __init__(self, value):
self.value = str(value)
def __str__(self):
return self.value
def __int__(self):
return int(self.value)
def __float__(self):
return float(self.value)
#EXAMPLE: NumString(5) + 5 = 10
def __add__(self, other):
if '.' in self.value:
return float(self) + other
return int(self) + other
#If you reflect your addition, this method will reflect it again so the __add__ method can be used
#EXAMPLE: 2 + NumString(5) becomes NumString(5) + 2
def __radd__(self, other):
return self + other
#will store a calculated self.value and therefore change the instance of NumString
#EXAMPLE: NumString(25) += 5 will change Numstring(25) into Numstring(30)
def __iadd__(self, other):
self.value = self + other
return self.value
|
# import time
def slowprint(string):
for letter in string:
print(letter, end='')
# time.sleep(.05)
|
def prob1():
sum = 0
i = 1
for i in range(1000):
if (((i % 3) == 0) or ((i % 5) == 0)):
sum = sum +i
print(sum)
print(i)
if __name__ == "__main__":
print("Project Euler Problem 1")
prob1() |
# String Formation
'''
Given an array of strings, each of the same length and a target string construct the target string using characters from the strings in the given array such that the indices of the characters in the order in which they are used to form a strictly increasing sequence. Here the index of character is the position at which it appears in the string. Note that it is acceptable to use multiple characters from the same string.
Determine the number of ways to construct the target string. One construction is different from another if either the sequences of indices they use are different, or the sequences are same but there exists a character at some index such that it is chosen from a different string in these constructions. Since the answer can be very large, return the value modulo (10^9 + 7).
'''
# mod = 1000000007
mod = 10 ** 9 + 7
dp = [[-1 for i in range(1000)] for j in range(1000)]
def calculate(pos, prev, s, index):
if pos == len(s):
return 1
if dp[pos][prev] != -1:
return dp[pos][prev]
c = ord(s[pos]) - ord('a');
answer = 0
for i in range(len(index[c])):
if index[c][i] > prev:
answer = (answer % mod + calculate(pos + 1, index[c][i], s, index) % mod) % mod
dp[pos][prev] = answer
# Store and return the solution for this subproblem
return dp[pos][prev]
def countWays(a, s):
n = len(a)
index = [[] for i in range(26)]
for i in range(n):
for j in range(len(a[i])):
index[ord(a[i][j]) - ord('a')].append(j + 1)
return calculate(0, 0, s, index)
# Driver Code
if __name__ == '__main__':
A = []
A.append("adc")
A.append("aec")
A.append("erg")
S = "ac"
# A = ["valya", "lyglb", "vldoh"]
# S = "val"
# A = ["xzu", "dfw", "eor", "mat", "jyc"]
# S = "cf"
# A = ["afsdc", "aeeeedc", "ddegerg"]
# S = "ae"
print(countWays(A, S))
|
# colors.py
#
# GameGenerator is free to use, modify, and redistribute for any purpose
# that is both educational and non-commercial, as long as this paragraph
# remains unmodified and in its entirety in a prominent place in all
# significant portions of the final code. No warranty, express or
# implied, is made regarding the merchantability, fitness for a
# particular purpose, or any other aspect of the software contained in
# this module.
"""This file contains some basic colors for you to use in your game if
you so choose. Or you can use colors from the huge list included with
Pygame, or type your own. Up to you.
"""
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (127, 127, 127)
DARK_GRAY = (31, 31, 31)
MEDIUM_DARK_GRAY = (63, 63, 63)
MEDIUM_LIGHT_GRAY = (180, 180, 180)
LIGHT_GRAY = (236, 236, 236)
RED = (255, 0, 0)
MAROON = (102, 0, 0)
PINK = (255, 204, 204)
GREEN = (0, 255, 0)
DARK_GREEN = (51, 102, 0)
LIGHT_GREEN = (204, 255, 153)
BLUE = (0, 0, 255)
DARK_BLUE = (0, 51, 102)
LIGHT_BLUE = (153, 204, 255)
CYAN = (0, 255, 255)
TEAL = (0, 153, 153)
MAGENTA = (255, 0, 255)
FUCSIA = (255, 0, 127)
YELLOW = (255, 255, 0)
ORANGE = (255, 128, 0)
BROWN = (153, 76, 0)
PURPLE = (102, 0, 204)
|
#!/usr/bin/env python
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
#grid[0][0] grid[1][0] grid[2][0]
#grid[0][1] grid[1][1] grid[2][1]
for i in range(len(grid[0])):
for j in range(len(grid)):
print(grid[j][i], end='')
print('')
|
# Python code to reverse a string
# using loop
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using loops) is : ",end="")
print (reverse(s))
|
def has_line(game_result):
for l in game_result:
if l == tuple("XXX"):
return "X"
elif l == tuple("OOO"):
return "O"
return None
def has_col(game_result):
return has_line(zip(*[list(e) for e in game_result]))
def has_diag(game_result):
def check_diag(c, reverse=False) :
for i in range(len(game_result)):
if (not reverse and game_result[i][i] != c) or \
(reverse and game_result[i][len(game_result) - 1 - i] != c):
return False
return True
return "X" if check_diag("X") or check_diag("X", reverse=True) else "O" if check_diag("O") or check_diag("O", reverse=True) else None
def checkio(game_result):
line = has_line([tuple(e) for e in game_result])
col = has_col(game_result)
diag = has_diag(game_result)
return line if line is not None else col if col is not None else diag if diag is not None else "D"
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for
#auto-testing
assert checkio(["X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio(["OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio(["OOX",
"XXO",
"OXX"]) == "D", "Draw"
assert checkio(["O.X",
"XX.",
"XOO"]) == "X", "Xs wins again"
|
#!/usr/bin/env python3
def validate_no_repeated(passphrase):
words = passphrase.strip().split()
return len(set(words)) == len(words)
def validate_no_anagrams(passphrase):
words = [''.join(sorted(word)) for word in passphrase.strip().split()]
return len(set(words)) == len(words)
assert validate_no_repeated("aa bb cc dd ee")
assert validate_no_repeated("aa bb cc dd aaa")
assert not validate_no_repeated("aa bb cc dd aa")
assert validate_no_anagrams("aa bb cc dd ee")
assert validate_no_anagrams("aa bb cc dd aaa")
assert validate_no_anagrams("abcde fghij")
assert validate_no_anagrams("a ab abc abd abf abj")
assert validate_no_anagrams("iiii oiii ooii oooi oooo")
assert not validate_no_anagrams("aa bb cc dd aa")
assert not validate_no_anagrams("abcde xyz ecdab")
assert not validate_no_anagrams("oiii ioii iioi iiio")
if __name__ == '__main__':
with open('input') as f:
lines = f.readlines()
print(sum(validate_no_repeated(passphrase) for passphrase in lines))
print(sum(validate_no_anagrams(passphrase) for passphrase in lines))
|
def clean_number_list(numbers_to_add):
"""
Input: a List of numbers to be added together
Function will clean the list and then return the new list.
Cleaning involves conversion of string to numbers
Function will return False if an invalid value has been found
"""
# Verify that the input is a list
if not isinstance(numbers_to_add, list):
return False
# Build a new list with cleaned values
numbers_to_add_list = []
for item in numbers_to_add:
if isinstance(item, str):
if item.isdigit():
numbers_to_add_list.append(int(item))
else:
try:
float_value = float(item)
numbers_to_add_list.append(float_value)
except Exception as e:
# print(type(e))
# TODO # Print to log file
return False
if isinstance(item, (int, float)):
numbers_to_add_list.append(item)
return (numbers_to_add_list)
|
linha = '-' * 30
totMais18 = 0
totHomens = 0
totMulherMenos20 = 0
while True:
print(linha)
print('{:^30}'.format('CADASTRE UMA PESSOA'))
print(linha)
idadeTXT = ' '
while not idadeTXT.isnumeric():
idadeTXT = str(input('Idade: '))
idade = int(idadeTXT)
sexo = ' '
while sexo not in 'MF':
sexo = str(input('Sexo: [M/F] ')).strip().upper()[0]
if idade > 18:
totMais18 += 1
if sexo == 'M':
totHomens += 1
if (sexo == 'F' and idade < 20):
totMulherMenos20 += 1
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Deseja continuar? [S/N?] ')).strip().upper()[0]
if continuar == 'N':
break
print(linha)
print('Total de pessoas com mais de 18:', totMais18)
print('Ao todo, temos {} homens cadastrados'.format(totHomens))
print(f'E temos {totMulherMenos20} mulheres com menos de 20 anos')
|
"""
A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
Example 1:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Example 2:
Input: sentence = "leetcode"
Output: false
Constraints:
1 <= sentence.length <= 1000
sentence consists of lowercase English letters.
# algorithm:
iterate through string
if char has been seen do nothing
else add char to result string
if string.length == 26 return true : false
"""
def pan_gram(string):
result = ''
for char in string:
if char not in result:
result += char
if len(result) == 26:
return True
else:
return False
def another(string):
return len(set(string)) == 26 |
GRAPH = {
"A": ["B","D","E"],
"B": ["A","C","D"],
"C": ["B","G"],
"D": ["A","B","E","F"],
"E": ["A","D"],
"F": ["D"],
"G": ["C"]
}
def bfs(graph, current_vertex):
queue = [] # an empty queue
visited = [] # an empty list of visited nodes
queue.append(current_vertex) # enqueue
while len(queue) > 0: # while queue not empty
current_vertex = queue.pop(0) # dequeue
visited.append(current_vertex)
for neighbour in graph[current_vertex]:
if neighbour not in visited and \
neighbour not in queue:
queue.append(neighbour)
return visited
# main program
traversal = bfs(GRAPH, 'A')
print('Nodes visited in this order:', traversal)
|
# use an increment and assign operator
count = 0
while count != 5:
count += 1
print(count)
# increment count by 3
count = 0
while count <= 20:
count += 3
print(count)
# decrements count by 3
count = 20
while count >= 0:
count -= 3
print(count)
|
class Solution:
def solve(self, s):
lCount = 0
rCount = 0
choiceCount = 0
for i in s:
if i == 'L':
lCount += 1
elif i == 'R':
rCount += 1
else:
choiceCount += 1
if lCount > rCount:
return (lCount + choiceCount) - rCount
else:
return (rCount + choiceCount) - lCount
|
class Vertice:
def __init__(self, n):
self.nombre = n
class Grafo:
vertices = {}
bordes = []
indices_bordes = {}
def agregar_vertice(self, vertex):
if isinstance(vertex, Vertice) and vertex.nombre not in self.vertices:
self.vertices[vertex.nombre] = vertex
for fila in self.bordes:
fila.append(0)
self.bordes.append([0] * (len(self.bordes) + 1))
self.indices_bordes[vertex.nombre] = len(self.indices_bordes)
return True
else:
return False
def agregar_borde(self, u, v, weight=1):
if u in self.vertices and v in self.vertices:
self.bordes[self.indices_bordes[u]][self.indices_bordes[v]] = weight
self.bordes[self.indices_bordes[v]][self.indices_bordes[u]] = weight
return True
else:
return False
def imprimir_grafo(self):
for v, x in sorted(self.indices_bordes.items()):
print(v + ' ', end='')
for j in range(len(self.bordes)):
print(self.bordes[x][j], end='')
print(' ')
g = Grafo()
a = Vertice('1')
g.agregar_vertice(a)
g.agregar_vertice(Vertice('2'))
for i in range(ord('1'), ord('8')):
g.agregar_vertice(Vertice(chr(i)))
bordes = ['12', '24', '26', '43', '32', '45', '52', '65', '67', '75', '74']
for borde in bordes:
g.agregar_borde(borde[:1], borde[1:])
g.imprimir_grafo()
|
#Single line concat
"Hello " "World"
#Multi line concat with line continuation
"Goodbye " \
"World"
#Single line concat in list
[ "a" "b" ]
#Single line, looks like tuple, but is just parenthesized
("c" "d" )
#Multi line in list
[
'e'
'f'
]
#Simple String
"string"
#String with escapes
"\n\n\n\n"
#String with unicode escapes
'\u0123\u1234'
#Concat with empty String
'word' ''
#String with escapes and concatenation :
'\n\n\n\n' '0'
#Multiline string
'''
line 0
line 1
'''
#Multiline impicitly concatenated string
'''
line 2
line 3
''' '''
line 4
line 5
'''
#Implicitly concatenated
|
class WalletError(Exception):
"""Base Exception raised for all wallet errors."""
pass
class InsufficientFunds(WalletError):
"""Error raised when address has insufficient funds to make a transaction.
Attributes:
address: input address for which the error occurred
balance: current balance for the address
message: explanation of the error
"""
def __init__(self, address, balance=0):
super().__init__()
self.address = address
self.balance = balance
self.message = f"Insufficient funds for address {address} (balance = {balance})"
@classmethod
def forAmount(cls, address, balance, out_amount, fee):
ex = cls(address, balance)
total = out_amount + fee
ex.message = f"Balance {balance} is less than {total} (including {fee} fee)"
return ex
def __str__(self):
return self.message
class EmptyUnspentTransactionOutputSet(InsufficientFunds):
"""Error raised when address has an empty UTXO set.
Attributes:
address: input address for which the error occurred
balance: current balance for the address
message: explanation of the error
"""
def __init__(self, address):
super().__init__(address)
self.message = f"No unspent transactions were found for address {address})"
class NoConfirmedTransactionsFound(InsufficientFunds):
"""Error raised when address has no confirmed unspent transactions to use.
Attributes:
address: input address for which the error occurred
balance: current balance for the address
message: explanation of the error
"""
def __init__(self, address, min_confirmations):
super().__init__(address)
self.message = f"No confirmed unspent transactions were found for address {address} (asking for min: {min_confirmations})"
|
num1 = 111
num2 = 222
num3 = 333333
num3 = 333
num4 = 444
num6 = 666
num5 = 555
num7 = 777
|
# True & False
limit = 5000
limit == 4000 # returns False
limit == 5000 # returns True
5 == 4 # returns False
5 == 5 # returns True
# if & else & elif
gain = 50000
limit = 50000
if gain > limit:
print("gain is greater than the limit")
elif gain == limit:
print("gain equally limit")
else:
print("limit is greater than the gain")
|
#!/usr/bin/env python
''' THIS IS DOUBLY LINKED LIST IMPLEMENTATION '''
class Node:
def __init__(self, prev=None, next=None, data=None):
self.prev = prev
self.next = next
self.data = data
def __str__(self):
return str(self.data)
class DoublyLinkedList:
def __init__(self):
self.head = None
self.count = int(0)
def display(self):
temp = self.head
print("\nDLL Content: "),
while (temp):
print(str(temp.data)),
temp = temp.next
print(" #")
def show_count(self):
print(self.count)
def get_count(self):
return self.count
def push(self, new_data):
new_node = Node(data=new_data)
new_node.prev = None
new_node.next = self.head
if self.head is not None:
self.head.prev = new_node
self.head = new_node
self.count = self.count + 1
def insertBefore(self, cursor, new_data):
if cursor is None:
print("Error: Node doesn't exist")
return
new_node = Node(data=new_data)
new_node.prev = cursor.prev
new_node.next = cursor
if cursor.prev is not None:
cursor.prev.next = new_node
cursor.prev = new_node
self.count = self.count + 1
def insertAfter(self, cursor, new_data):
if cursor is None:
print("Error: Node doesn't exist")
return
new_node = Node(data=new_data)
new_node.prev = cursor
new_node.next = cursor.next
cursor.next = new_node
if new_node.next is not None:
new_node.next.prev = new_node
self.count = self.count + 1
def append(self, new_data):
new_node = Node(data=new_data)
new_node.next = None
if self.head is None:
new_node.prev = None
self.head = new_node
self.count = self.count + 1
return
last = self.head
while (last.next is not None):
last = last.next
new_node.prev = last
last.next = new_node
self.count = self.count + 1
def menu():
print("Doubly Linked List\n")
print("1. Show List")
print("2. Insert at Start")
print("3. Insert Before")
print("4. Insert After")
print("5. Insert at End")
print("9. # of Element")
print("0. Exit")
print(">> "),
def main():
dll = DoublyLinkedList()
while(True):
menu()
choice = int(raw_input())
if choice == int('1'):
dll.display()
elif choice == int('2'):
print("Enter data to insert: "),
data = raw_input()
dll.push(data)
elif choice == int('3'):
print("Enter data to insert: "),
data = raw_input()
print("Enter position of cursor (before): "),
pos = int(raw_input())
if pos == int('1'):
dll.push(data)
continue
cursor = dll.head
for i in range(1, pos):
cursor = cursor.next
print(cursor)
dll.insertBefore(cursor, data)
# print("3")
elif choice == int('4'):
print("Enter data to insert: "),
data = raw_input()
print("Enter position of cursor (after): "),
pos = int(raw_input())
cursor = dll.head
for i in range(pos - 1):
cursor = cursor.next
print(cursor)
dll.insertAfter(cursor, data)
# print("4")
elif choice == int('5'):
print("Enter data to insert: "),
data = raw_input()
dll.append(data)
# print("5")
elif choice == int('9'):
print("No of element: "),
dll.show_count()
elif choice == int('0'):
break
else:
print("Invalid Selection")
print('\n\nEND\n\n')
if __name__ == '__main__':
main()
|
"""
Created on Wed Aug 25 12:52:52 2021
AI and deep learnin with Python
Data types and operators
Quiz Data types and Operators
"""
# The current volume of a water reservoir is ( in cubic meters)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic meters)
rainfall = 5e6
# Decrease the rainfall variable by 10% to account for runoff
rainfall *= 0.9
# add the rainfall variable to the reservoir_volume variable
reservoir_volume += rainfall
print(reservoir_volume) |
'''input
2
9
3 6
12
5
20
11 12 9 17 12
74
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem B
if __name__ == '__main__':
ball_count = int(input())
robotB_position = int(input())
positions = list(map(int, input().split()))
total_length = 0
for i in range(ball_count):
if positions[i] < abs(robotB_position - positions[i]):
total_length += 2 * positions[i]
else:
total_length += 2 * abs(robotB_position - positions[i])
print(total_length)
|
S = input()
K = int(input())
for i, s in enumerate(S):
if s == "1":
if i + 1 == K:
print(1)
exit()
else:
print(s)
exit()
|
# PASSED
_ = input()
lst = sorted(list(map(int, input().split())))
output = []
if len(lst) % 2:
output.append(lst.pop(0))
while lst:
output.append(lst[-1])
output.append(lst[0])
lst = lst[1:-1]
print(*reversed(output)) |
'''
Read numbers and put in a list
one list will have the EVEN numbers
the other will have the ODD ones
SHow the result
'''
odd_list = []
even_list = []
num = int(input('Type a number: '))
if num%2 == 0:
even_list.append(num)
elif num%2 != 0:
odd_list.append(num)
while True:
opt = str(input('Do you want to keep adding numbers? [Y/N]: ')).lower()
if 'y' in opt:
num = int(input('Type a number: '))
if num%2 == 0:
even_list.append(num)
elif num%2 != 0:
odd_list.append(num)
elif 'n' in opt:
print(f'The list is: {sorted(even_list + odd_list)}')
print(f'The EVEN list: {sorted(even_list)}')
print(f'The ODD list: {sorted(odd_list)}')
break
else:
print('Sorry, the options are Y - yes or N - no.') |
__version__ = "1.0.8"
def get_version():
return __version__
|
#14
def sumDigits(num):
sum = 0
for digit in str(num):
sum += int(digit)
return sum
num = int(input('Enter a 4-digit number:'))
print('Sum of the digits:', sumDigits(num))
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
hashset = set()
return self.inorder(root, k, hashset)
def inorder(self, root, k, hashset):
if root:
left = self.inorder(root.left, k, hashset)
if left or k - root.val in hashset:
return True
hashset.add(root.val)
right = self.inorder(root.right, k, hashset)
return right
return False |
class BinaryChunkHeader:
LUA_SIGNATURE = bytes(b'\x1bLua')
LUAC_VERSION = 0x53
LUAC_FORMAT = 0x0
LUAC_DATA = bytes(b'\x19\x93\r\n\x1a\n')
CINT_SIZE = 4
CSIZET_SIZE = 8
INST_SIZE = 4
LUA_INT_SIZE = 8
LUA_NUMBER_SIZE = 8
LUAC_INT = 0x5678
LUAC_NUM = 370.5
def __init__(self, br):
self.signature = br.read_bytes(4)
self.version = br.read_uint8()
self.format = br.read_uint8()
self.luac_data = br.read_bytes(6)
self.cint_size = br.read_uint8()
self.csizet_size = br.read_uint8()
self.inst_size = br.read_uint8()
self.lua_int_size = br.read_uint8()
self.lua_number_size = br.read_uint8()
self.luac_int = br.read_uint64()
self.luac_num = br.read_double()
def check(self):
assert(self.signature == BinaryChunkHeader.LUA_SIGNATURE)
assert(self.version == BinaryChunkHeader.LUAC_VERSION)
assert(self.format == BinaryChunkHeader.LUAC_FORMAT)
assert(self.luac_data == BinaryChunkHeader.LUAC_DATA)
assert(self.cint_size == BinaryChunkHeader.CINT_SIZE)
assert(self.csizet_size == BinaryChunkHeader.CSIZET_SIZE)
assert(self.inst_size == BinaryChunkHeader.INST_SIZE)
assert(self.lua_int_size == BinaryChunkHeader.LUA_INT_SIZE)
assert(self.lua_number_size == BinaryChunkHeader.LUA_NUMBER_SIZE)
assert(self.luac_int == BinaryChunkHeader.LUAC_INT)
assert(self.luac_num == BinaryChunkHeader.LUAC_NUM)
def dump(self):
print('signature: ', self.signature)
print('version: ', self.version)
print('format: ', self.format)
print('luac_data: ', self.luac_data)
print('cint_size: ', self.cint_size)
print('csizet_size: ', self.csizet_size)
print('inst_size: ', self.inst_size)
print('lua_int_size: ', self.lua_int_size)
print('lua_number_size: ', self.lua_number_size)
print('luac_int: ', hex(self.luac_int))
print('luac_num: ', self.luac_num)
print()
|
data = [
'I live in a house near the mountains. I have two brothers and one sister, and I was born last. My father teaches mathematics, and my mother is a nurse at a big hospital. My brothers are very smart and work hard in school. My sister is a nervous girl, but she is very kind. My grandmother also lives with us. She came from Italy when I was two years old. She has grown old, but she is still very strong. She cooks the best food!',
'Hi! Nice to meet you! My name is John Smith. I am 19 and a student in college. I go to college in New York. My favorite courses are Geometry, French, and History. English is my hardest course. My professors are very friendly and smart. It’s my second year in college now. I love it! I live in a big house on Ivy Street. It’s near the college campus. I share the house with three other students. Their names are Bill, Tony, and Paul.',
'My favorite beach is called Emerson Beach. It is very long, with soft sand and palm trees. It is very beautiful. I like to make sandcastles and watch the sailboats go by. Sometimes there are dolphins and whales in the water! Every morning we look for shells in the sand. I found fifteen big shells last year. I put them in a special place in my room. This year I want to learn to surf. It is hard to surf, but so much fun!',
'Wednesday is the third day of the week, and serves as the "middle" of the work week; some individuals refer to Wednesday as "hump day," as once its workday is complete, employees will have passed the work-week "hump," and will be on the downturn, as only two days on the job will remain in the week. Thursday is the fourth day of the week, and is viewed favorably by many, as it\'s rather close to the end of the work week.',
'Saturday is perhaps the most highly regarded day of the week. Because Sunday follows it (and there is presumably no work or school to attend, for most individuals), everyone is free to stay out (or awake) until late at night, having fun with plans or other leisure-related activities. To be sure, Saturday is generally thought of as a day to partake in hobbies that couldn\'t otherwise be enjoyed during the regular week.',
]
|
# FUNCTIONS
# Positional-Only Arguments
def pos_only(arg1, arg2, /):
print(f'{arg1}, {arg2}')
pos_only('One', 2)
# Cannot pass keyword arguments to a function of positional-only arguments
# pos_only(arg1='One', arg2=2)
# Keyword-Only Arguments
def kw_only(*, arg1, arg2):
print(f'{arg1}, {arg2}')
kw_only(arg1='First', arg2='Second')
kw_only(arg2=2, arg1=1)
# Cannot pass arguments without their name being specified specifically
# kw_only(1, arg1=2)
# No Restriction On Positional-Only Or Keyword-Only Arguments
def no_res(arg1, arg2):
print(f'{arg1}, {arg2}')
# Positional arguments will always need to be placed in front of keyword arguments
no_res('Firstly', arg2='Secondly')
# Combine Both Positional-Only, Positional-Or-Keyword and Keyword-Only Arguments
def fn(pos1, pos2, /, pos_or_kw1, pos_or_kw2, *, kw1, kw2):
print(f'{pos1}, {pos2}, {pos_or_kw1}, {pos_or_kw2}, {kw1}, {kw2}')
fn(1, 'Two', 3, pos_or_kw2='Four', kw1=5, kw2='Six')
# Arbitrary Argument Lists
def hyper_link(protocol, domain, *routes, separator='/'):
return f'{protocol}://{domain}/' + separator.join(routes)
print(hyper_link('https', 'python.org', 'downloads',
'release', 'python-385', separator='/'))
# Unpacking List/Tuple Argument Lists with * and Dictionary Arguments with **
def server(host, port, separator=':'):
return f'{host}{separator}{port}'
print(server(*['localhost', 8080])) # call with arguments unpacked from a list
def url(routes, params):
r = '/'.join(routes)
p = '&'.join([f'{name}={value}' for name, value in params.items()])
return f'{r}?{p}'
route_config = {
'routes': ['download', 'latest'],
'params': {
'ver': 3,
'os': 'windows'
}
}
print(url(**route_config)) # call with arguments unpacked from a dictionary
# Lambda Expressions
week_days = ['Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat', 'Sun']
day_codes = [3, 5, 2, 6, 1, 7]
def convert_days(converter_fn, day_codes):
return [converter_fn(day_code) for day_code in day_codes]
converted_days = convert_days(
lambda day_code: week_days[day_code % 7], day_codes)
print(converted_days)
|
"""
bigrange - big ranges. Really.
Only one cool iterator in Python that supports big integers.
"""
def bigrange(a,b,step=1):
"""
A replacement for the xrange iterator; the builtin class
doesn't handle arbitrarely large numbers.
Input:
a First numeric output
b Lower (or upper) bound, never yield
step Defaults to 1
"""
i=a
while cmp(i,b)==cmp(0,step):
yield i
i+=step |
class PM:
def __init__(self):
pass
def get_possible_state(self, filled=True):
if filled:
state = self.user_info['state']
possible_states = self.state_info[state].get('possible_states', [])
self.user_info['possible_states'] = possible_states
else:
state = self.user_info['state']
possible_states = [state]
self.user_info['possible_states'] = possible_states
def take_action(self, action):
if action == 'CLEAN_SLOT':
for slot in self.slot_templet_info:
if slot in self.user_info:
del self.user_info[slot]
print('系统指令:', action)
def get_actions(self):
state = self.user_info['state']
actions = self.state_info[state].get("actions", [])
for action in actions:
self.take_action(action)
def policy_making(self, user_info, state_info, slot_templet_info):
self.user_info = user_info
self.state_info = state_info
self.slot_templet_info = slot_templet_info
needed_slots = self.user_info["needed_slots"]
# 如果槽位已经足够了可以直接回应
if not needed_slots:
self.user_info['policy'] = 'response'
self.get_possible_state()
self.get_actions()
# 不然就可能的状态还是当前状态,接着填槽
else:
slot = needed_slots[0]
self.get_possible_state(False)
self.user_info['policy'] = 'need:%s' % slot
def pm(user_info, state_info, slot_templet_info):
po = PM()
po.policy_making(user_info, state_info, slot_templet_info)
return po.user_info
if __name__ == '__main__':
user_info = {'possible_states': ['重填挂号信息'],
'query': '错了',
'state': '重填挂号信息',
'next_score': 1.0,
'#性别#': '男',
'#年龄#': '22',
'needed_slots': [],
'needed_slots_state': '重填挂号信息',
'policy': 'response'}
state_info = {'填入挂号信息': {'state': '填入挂号信息',
'intents': ['我想要来医院挂号'],
'slot': ['#性别#', '#年龄#'],
'response': '系统消息:\n好的,请确认您的性别年龄:性别:#性别#;年龄:#年龄#',
'possible_states': ['支付挂号费', '重填挂号信息']},
'重填挂号信息': {'state': '重填挂号信息',
'intents': ['性别年龄信息有误', '重新输入', '错了有问题'],
'actions': ['CLEAN_SLOT'],
'response': '系统消息:\n好的,为您清楚当前信息,请重新输入挂号信息',
'possible_states': ['填入挂号信息']},
'确认挂号信息': {'state': '确认挂号信息',
'intents': ['确认'],
'response': '系统消息:\n好的',
'possible_states': ['支付挂号费']},
'支付挂号费': {'state': '支付挂号费',
'intents': ['确认'],
'actions': ['假装返回一个支付二维码链接:https://www.pleasepayyourbill.com/your_info'],
'response': '系统消息:\n请支付5元挂号费,支付后请刷新',
'possible_states': ['挂号成功']},
'挂号成功': {'state': '挂号成功',
'intents': ['刷新'],
'actions': ['假装将号码信息录入挂号系统:https://www.guahao.com/your_info'],
'response': '系统消息:\n您的排队号码为xx,祝您身体健康,万事如意',
'possible_states': []}}
slot_templet_info = {'#性别#': ['请问您的性别为', '男|女'], '#年龄#': ['请问您的年龄为', '(\\d+)']}
user_info = pm(user_info, state_info, slot_templet_info)
print(user_info)
|
class Solution(object):
def reorderLogFiles(self, logs):
letter_log = {}
letter_logs = []
res = []
for idx, log in enumerate(logs):
if log.split(' ')[-1].isdigit():
res.append(log)
else:
letters = tuple(log.split(' ')[1:])
letter_log[letters] = idx
letter_logs.append(letters)
letter_logs.sort(reverse=True)
for letters in letter_logs:
res.insert(0, logs[letter_log[letters]])
return res
if __name__ == '__main__':
print(Solution().reorderLogFiles(["a1 9 2 3 1", "g1 act car", "zo4 4 7", "ab1 off key dog", "a8 act zoo"]))
|
class FiniteStateMachine:
def __init__(self, states, starting):
self.states = states
self.current = starting
self.entry_words = {} # Dictionary of states, {state.name : word}, words where words are the words used to enter the state
self.stay_words = {} # Dictionary of states, {states.name: [words]}, words is list with words which lead to staying in state
def process(self, sentence):
for word in sentence.split():
word = word.lower()
next_state = self.current.get_next_state(word)
if next_state is not None: # Change state
self.entry_words[next_state.name] = word
self.current = next_state
else: # Stay in same state
if self.current.name in self.stay_words: # State already in dict => more than 1 word for staying in this state
self.stay_words[self.current.name].append(word)
else: # state not in dict
word_list = [word]
self.stay_words[self.current.name] = word_list
return self.current # return final state
|
# 1η θέση = 20€ , 2η θέση = 15€ και 3η θέση = 10€
def ektelesi():
ticket_issues = 'Y'
income = 0
pos_1 = 0 # Θα χρησιμοποιηθεί για την καταμέτρηση των εισιτηρίων, 1ηςΘΕΣΗΣ
pos_2 = 0 # Θα χρησιμοποιηθεί για την καταμέτρηση των εισιτηρίων, 2ηςΘΕΣΗΣ
pos_3 = 0 # Θα χρησιμοποιηθεί για την καταμέτρηση των εισιτηρίων, 3ηςΘΕΣΗΣ
# Εδώ το πρόγραμμα θα επαναλαμβάνετε για οσο η τιμή είναι διάφορη του 'Ν'
while ticket_issues != 'N':
emfanisi_katigorion()
categorie_position = katigoria_thesis()
# Εδώ παίρνει τις τιμές από την εντολή return, της συνάρτησης της
# timi thesis και τις μεταφέρει στις μεταβλητές παρακάτω
position_price, p1, p2, p3 = timi_thesis(categorie_position)
pos_1 = int(pos_1 + p1) # Εδώ κάνει την καταμέτρηση 1ης ΘΕΣΗΣ
pos_2 = int(pos_2 + p2) # Εδώ κάνει την καταμέτρηση 2ης ΘΕΣΗΣ
pos_3 = int(pos_3 + p3) # Εδώ κάνει την καταμέτρηση 3ης ΘΕΣΗΣ
# Σε αυτό το σημείο υπολογίζει το εισ΄΄οδημα.
income = float(income + position_price)
# Σε αυτό το σημείο εμφανίζει τα αποτελέσματα.
print('Εισιτήρια που πουλήθηκαν:\n1η ΘΕΣΗ = ', pos_1, '\n2η ΘΕΣΗ = ',
pos_2, '\n3η ΘΕΣΗ = ', pos_3, sep='')
print()
print('Το εισόδημα που προέκυψε από την πώληση των εισιτηρίων '
'είναι: €', format(income, ',.2f'), sep='')
print()
ticket_issues = ekdosi_eisitirion() # Σε αυτο το σημείο κάνει loop
def katigoria_thesis():
# Η συνάρτηση αυτή θα χρησιμοποιηθεί για την εισαγωγή της θέσης στην οποία
# θα κοπεί το εισιτήριο, αλλά και για την επαλήθευση σε περίπτωση
# λανθασμένης απάντησης από τον χρήστη.
thesi = int(input('Δώσε την κατηγορία της θέσης στην οποία θα κοπεί το '
'εισιτήριο: '))
print()
# Εδώ γ΄΄ινεται η επαλήθευση σε περίπτωση λανθασμένης απάντησης
while thesi != 1 and thesi != 2 and thesi != 3:
print('Έχεις δώσει λανθασμένη κατηγορία θέσης. Οι κατηγορίες θέσεων '
'είναι 1, 2 και 3.')
thesi = int(input('Παρακαλώ ξανά προσπάθησε: '))
print()
return thesi
def ekdosi_eisitirion():
# Η συνάρτηση αυτή θα χρησιμοποιηθεί για την επαναληπτική εκτέλεση του
# προγράμματος, αλλά και για την επαλήθευση σε περίπτωση λανθασμένης
# απάντησης από τον χρήστη.
ekdosi = input('ΠΡΟΣΟΧΗ!!!\n(Τα γράμματα πρέπει να είναι σε '
'λατινικούς χαρακτήρες και κεφαλαία για να συνεχίσει το '
'πρόγραμμα.)'
'\nΘέλεις να κόψεις άλλο εισιτήριο;\nΔώσε "Y" για ΝΑΙ και '
'"N" για ΟΧΙ. : ')
print()
# Εδώ γ΄΄ινεται η επαλήθευση σε περίπτωση λανθασμένης απάντησης
while ekdosi != 'Y' and ekdosi != 'N':
print('Έχεις δώσει λανθασμένη απάντηση.')
ekdosi = input('Παρακαλώ ξανά προσπάθησε: ')
print()
return ekdosi
def emfanisi_katigorion():
# Εμφανίζει τις κατηγορίες στην αρχή αλλά και στην επανάληψη του
# προγράμματος.
print('\t3 ΚΑΤΗΓΟΡΙΕΣ ΘΕΣΕΩΝ', '\n-------------------------------------')
print('1η ΘΕΣΗ\t| 2η ΘΕΣΗ\t| 3η ΘΕΣΗ')
print('20€', '\t| ', '15€', '\t', '\t| 10€')
print()
def timi_thesis(categorie_position): # Εδώ βρίσκει την τιμή της θέσης
# Τις μεταβλητές αυτές τις βάζω, διότι η if-elif-else θα δώσει μια
# τιμή στην εκάστοτε μεταβλητή και άρα η εντολή return, θa πρέπει να πάρει
# από κάπου τις τιμές για τις άλλες δύο μεταβλητές, αλλιώς θα βγάλει σφάλμα
# το πρόγραμμα.
t1 = 0
t2 = 0
t3 = 0
if categorie_position == 1:
timi = 20
t1 = 1
elif categorie_position == 2:
timi = 15
t2 = 1
else:
timi = 10
t3 = 1
return timi, t1, t2, t3
ektelesi()
|
# Faça um programa que leia o valor de um produto e imprima o valor com desconto,
# tendo em vista que o desconto foi de 12%
produto = float(input("Digite o valor do produto: "))
desconto = produto - (0.12 * 100)
print(f"O valor final do produto é: {desconto}")
|
class _ReadOnlyWidgetProxy(object):
def __init__(self, widget):
self.widget = widget
def __getattr__(self, name):
return getattr(self.widget, name)
def __call__(self, field, **kwargs):
kwargs.setdefault('readonly', True)
return self.widget(field, **kwargs)
def readonly_field(field):
def _do_nothing(*args, **kwargs):
pass
field.widget = _ReadOnlyWidgetProxy(field.widget)
field.process = _do_nothing
field.populate_obj = _do_nothing
return field
|
def reverse(s):
return " ".join((s.split())[::-1])
s = input("Enter a sentence: ")
print(reverse(s)) |
fenceMap = hero.findNearest(hero.findFriends()).getMap()
def convertCoor(row, col):
return {"x": 34 + col * 4, "y": 26 + row * 4}
for i in range(len(fenceMap)):
for j in range(len(fenceMap[i])):
if fenceMap[i][j] == 1:
pos = convertCoor(i, j)
hero.buildXY("fence", pos["x"], pos["y"])
hero.moveXY(30, 18)
|
class Student:
pass
Jiggu = Student()
Himanshu = Student()
Jiggu.name = "Jiggu"
Jiggu.std = 12
Jiggu.section = 1
Himanshu.std = 11
Himanshu.subjects = ["Hindi","English"]
print(Jiggu.section, Himanshu.subjects)
|
#
# PySNMP MIB module NETSCREEN-VPN-PHASEONE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSCREEN-VPN-PHASEONE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:10:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint")
netscreenVpn, netscreenVpnMibModule = mibBuilder.importSymbols("NETSCREEN-SMI", "netscreenVpn", "netscreenVpnMibModule")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter64, ObjectIdentity, MibIdentifier, Gauge32, Bits, iso, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, ModuleIdentity, TimeTicks, Counter32, IpAddress, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "ObjectIdentity", "MibIdentifier", "Gauge32", "Bits", "iso", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "ModuleIdentity", "TimeTicks", "Counter32", "IpAddress", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
netscreenVpnPhaseoneMibModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 3224, 4, 0, 5))
netscreenVpnPhaseoneMibModule.setRevisions(('2004-05-03 00:00', '2004-03-03 00:00', '2003-11-13 00:00', '2001-09-28 00:00', '2001-05-14 00:00',))
if mibBuilder.loadTexts: netscreenVpnPhaseoneMibModule.setLastUpdated('200405032022Z')
if mibBuilder.loadTexts: netscreenVpnPhaseoneMibModule.setOrganization('Juniper Networks, Inc.')
nsVpnPhaseOneCfg = MibIdentifier((1, 3, 6, 1, 4, 1, 3224, 4, 5))
nsVpnPhOneTable = MibTable((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1), )
if mibBuilder.loadTexts: nsVpnPhOneTable.setStatus('current')
nsVpnPhOneEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1), ).setIndexNames((0, "NETSCREEN-VPN-PHASEONE-MIB", "nsVpnPhOneIndex"))
if mibBuilder.loadTexts: nsVpnPhOneEntry.setStatus('current')
nsVpnPhOneIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneIndex.setStatus('current')
nsVpnPhOneName = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneName.setStatus('current')
nsVpnPhOneAuthMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("preshare", 0), ("rsa-sig", 1), ("dsa-sig", 2), ("rsa-enc", 3), ("rsa-rev", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneAuthMethod.setStatus('current')
nsVpnPhOneDhGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneDhGroup.setStatus('current')
nsVpnPhOneEncryp = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("null", 0), ("des", 1), ("des3", 2), ("aes", 3), ("aes-192", 4), ("aes-256", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneEncryp.setStatus('current')
nsVpnPhOneHash = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("null", 0), ("md5", 1), ("sha", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneHash.setStatus('current')
nsVpnPhOneLifetime = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneLifetime.setStatus('current')
nsVpnPhOneLifetimeMeasure = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("second", 0), ("minute", 1), ("hours", 2), ("days", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneLifetimeMeasure.setStatus('current')
nsVpnPhOneVsys = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsVpnPhOneVsys.setStatus('current')
mibBuilder.exportSymbols("NETSCREEN-VPN-PHASEONE-MIB", nsVpnPhaseOneCfg=nsVpnPhaseOneCfg, nsVpnPhOneVsys=nsVpnPhOneVsys, nsVpnPhOneIndex=nsVpnPhOneIndex, nsVpnPhOneEntry=nsVpnPhOneEntry, PYSNMP_MODULE_ID=netscreenVpnPhaseoneMibModule, netscreenVpnPhaseoneMibModule=netscreenVpnPhaseoneMibModule, nsVpnPhOneLifetime=nsVpnPhOneLifetime, nsVpnPhOneName=nsVpnPhOneName, nsVpnPhOneAuthMethod=nsVpnPhOneAuthMethod, nsVpnPhOneLifetimeMeasure=nsVpnPhOneLifetimeMeasure, nsVpnPhOneHash=nsVpnPhOneHash, nsVpnPhOneDhGroup=nsVpnPhOneDhGroup, nsVpnPhOneTable=nsVpnPhOneTable, nsVpnPhOneEncryp=nsVpnPhOneEncryp)
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
class Solution:
def xorOperation(self, n: int, start: int) -> int:
#Defining the nums array
nums=[int(start+2*i) for i in range (n)]
#Initializing the xor
xor=nums[0]
for i in range(1,len(nums)):
xor^=nums[i] #Taking bitwise xor of each element
return xor
|
# 定义文件夹
train_dir = 'flowers/train'
valid_dir = 'flowers/valid'
test_dir = 'flowers/test'
# 训练集
data_transforms_train = transforms.Compose([
transforms.RandomResizedCrop(244), # 此处224是图片尺寸
transforms.RandomRotation(45),
transforms.RandomHorizontalFlip(), # RandomResizedCrop
transforms.ToTensor(), # 转换成Torch张量
transforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225]) # 标准化张量图片
])
# 测试数据集
data_transforms_test = transforms.Compose([
transforms.RandomResizedCrop(244), # 此处224是图片尺寸
transforms.ToTensor(), # 转换成Torch张量
transforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225]), # 标准化张量图片
])
# TODO: Load the datasets with ImageFolder
image_datasets_train = datasets.ImageFolder(train_dir, transform = data_transforms_train)
image_datasets_valid = datasets.ImageFolder(valid_dir, transform = data_transforms_test)
image_datasets_test = datasets.ImageFolder(test_dir, transform = data_transforms_test)
# TODO: Using the image datasets and the trainforms, define the dataloaders
dataloaders_train = DataLoader(image_datasets_train, batch_size=64, shuffle=True)
dataloaders_valid = DataLoader(image_datasets_valid, batch_size=64)
dataloaders_test = DataLoader(image_datasets_test, batch_size=64)
# 标签映射
with open('cat_to_name.json', 'r') as f:
cat_to_name = json.load(f)
# 构建和训练分类器
# 初始化 requires_grad 为 False 冻结参数
for param in model.parameters():
# print(param)
param.requires_grad = False
model.classifier = nn.Sequential(OrderedDict([
('fcl', nn.Linear(1024, 500)),
('relu', nn.ReLU()),
('drop', nn.Dropout(p=0.5)),
('fc2', nn.Linear(500, len(cat_to_name))),
('output', nn.LogSoftmax(dim=1))]))
# 迁移到GPU
model.cuda()
criterion = nn.NLLLoss().cuda()
# 定义优化器
# optimizer = optim.Adam(model.parameters(), lr = 0.001)
optimizer = optim.Adam(model.classifier.parameters(), lr = 0.001)
# 定义训练方法
def train(model, dataloaders_train, criterion, optimizer):
model.train()
n_batches = len(dataloaders_train)
all_loss = 0.0
all_acc = 0
for inputs, labels in dataloaders_train:
inputs = Variable(inputs.cuda())
labels = Variable(labels.cuda())
optimizer.zero_grad() # 权重初始化
outputs = model(inputs)
loss = criterion(outputs, labels)
all_loss += loss.data[0]
loss.backward() # 反向传播
optimizer.step()
pre = torch.exp(outputs).data
equlity = (labels.data == pre.max(1)[1])
all_acc += equlity.type_as(torch.FloatTensor()).mean()
average = all_loss / n_batches
accuracy = all_acc / n_batches
print('Average loss: {: .3f}, Accuracy: ({:.3f})\n'.format(average, accuracy)) |
'''
Body mass index is a measure to assess body fat. It is widely use because it is easy to calculate and can
apply to everyone. The Body Mass Index (BMI) can calculate using the following equation.
Body Mass Index (BMI) = weight / height2 (Height in meters)
If BMI is 40 or greater, the program should print Fattest.
If BMI is 35.0 or above but less than 40 , the program should print Fat level II.
If BMI is 28.5 or above, but less than 35, the program should print Fat level I.
If BMI is 23.5 or above but less than 28.5, the program should print Overweight.
If BMI is 18.5 or above but less than 23.5, the program should print Normally.
If BMI is less than 18.5, the program should print Underweight.
Input
The first line is height (cm)
The second line is weight (kg)
Output
The first line shows BMI (2 decimal places).
The second line shows the interpretation of BMI level.
'''
h = float(input()) / 100
w = float(input())
bmi = w / (h * h)
print(f'{bmi:.2f}')
if bmi >= 40:
print('Fattest')
elif 40 > bmi >= 35:
print('Fat level II')
elif 35 > bmi >= 28.5:
print('Fat level I')
elif 28.5 > bmi >= 23.5:
print('Overweight')
elif 23.5 > bmi >= 18.5:
print('Normally')
else:
print('Underweight')
|
"""
Problem:
3.2 Stack Min: How would you design a stack which, in addition to push and pop, has a function min
which returns the minimum element? Push, pop and min should all operate in 0(1) time.
Hints:#27, #59, #78
--
Algorithm
The default implementation of a Stack already has Push and Pop as operations in O(1) time.
Thus, the goal here is to implement the Min operation. How can we do this?
We have to somehow keep a list of the minimum values so that we can reach them really fast.
A Hashmap would not work because it won't be ordered with the same order the elements were added
to the stack.
A MinHeap would help, but the operations to remove the elements would be O(logn) time.
Another option is to use another stack to keep the minimum elements.
Let's look at an example:
Input: [5,2,3,6,1]
OriginalStack
[5,2,3,6,1] - the last element is on top
MinStack
[5,2,1]
Every time we push a new element, if it is less than or equal to the top
of the MinStack, we added there too. When MinStack is empty, we just add the element.
Also, when we pop an element, we check if the element is in the top of the MinStack,
if it is, we pop it there.
Now, when we want to check the minimum element, we just look at the top of the
MinStack.
--
How to test it?
Let's assume our input is a list of operations in a stack:
- Push
- Pop
- Min
Our return will be the minimum values we asked for. So we will check
if they are correct.
"""
class StackWithMin:
def __init__(self) -> None:
self.__stack = []
self.__min_stack = []
def push(self, val):
self.__stack.append(val)
if not self.__min_stack:
self.__min_stack.append(val)
elif val <= self.__min_stack[-1]:
self.__min_stack.append(val)
def pop(self):
if not self.__stack:
raise Exception("Stack is empty")
if self.__stack[-1] == self.__min_stack[-1]:
self.__min_stack.pop()
return self.__stack.pop()
def min(self):
if not self.__stack:
raise Exception("Stack is empty")
return self.__min_stack[-1]
def query_stack(commands):
stack = StackWithMin()
result = []
for command in commands:
query = command.split()
if query[0] == "push":
stack.push(int(query[1]))
elif query[0] == "pop":
stack.pop()
elif query[0] == "min":
min_value = stack.min()
result.append(min_value)
return result
def test(commands, expected_answer):
answer = query_stack(commands)
if answer != expected_answer:
raise Exception(
f"Answer {answer} is wrong. Expected answer is {expected_answer}"
)
if __name__ == "__main__":
test(["push 5", "push 1", "push 2", "min", "pop", "min", "pop", "min"], [1, 1, 5])
test(["push 5", "min", "push 6", "min", "push 2", "min"], [5, 5, 2])
test(["push 5", "push 1", "push 3", "push 1", "min", "pop", "min"], [1, 1])
test(["push -5", "min", "push 6", "push -6", "min"], [-5, -6])
print("All tests passed!")
|
#!/usr/bin/env python3
# Write a program that computes the GC% of a DNA sequence
# Format the output for 2 decimal places
# Use all three formatting methods
dna = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change
s_count = 0
for nt in dna:
if nt == "G" or nt == "C":
s_count += 1
s_frac = s_count / len(dna)
# Method 1: %
print('%.2f' %(s_frac))
# Method 2:{}.format
print('{:.2f}'.format(s_frac))
#Method 3:f{}
print(f'{s_frac:.2f}')
"""
0.42
0.42
0.42
"""
|
#[playbook(say_hi)]
def say_hi(ctx):
with open('/scratch/output.txt', 'w') as f:
print("{message}".format(**ctx), file=f)
|
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
s=pattern
t=str.split()
return map(s.index, s) == map(t.index, t)
|
{
"targets": [
{
"target_name": "sypexgeo",
"sources": [
"src/xyz/vyvid/sypexgeo/bindings/nodejs/sypexgeo_node.cc",
"src/xyz/vyvid/sypexgeo/bindings/nodejs/sypexgeo_node.h",
"src/xyz/vyvid/sypexgeo/util/string_builder.h",
"src/xyz/vyvid/sypexgeo/uint24_t.h",
"src/xyz/vyvid/sypexgeo/db.cc",
"src/xyz/vyvid/sypexgeo/db.h",
"src/xyz/vyvid/sypexgeo/errors.h",
"src/xyz/vyvid/sypexgeo/header.h",
"src/xyz/vyvid/sypexgeo/location.cc",
"src/xyz/vyvid/sypexgeo/location.h",
"src/xyz/vyvid/sypexgeo/raw_city_access.h",
"src/xyz/vyvid/sypexgeo/raw_country_access.h",
"src/xyz/vyvid/sypexgeo/raw_region_access.h"
],
"include_dirs": [
"<!(node -e \"require('nan')\")",
"./src"
],
"cflags": [
"-std=gnu++11",
"-fno-rtti",
"-Wall",
"-fexceptions"
],
"cflags_cc": [
"-std=gnu++11",
"-fno-rtti",
"-Wall",
"-fexceptions"
],
"conditions": [
[
"OS=='mac'",
{
"xcode_settings": {
"GCC_ENABLE_CPP_EXCEPTIONS": "YES",
"GCC_ENABLE_CPP_RTTI": "NO",
"CLANG_CXX_LANGUAGE_STANDARD": "gnu++11",
"CLANG_CXX_LIBRARY": "libc++",
"MACOSX_DEPLOYMENT_TARGET": "10.7"
}
}
]
]
}
]
} |
#
# PySNMP MIB module Unisphere-Data-AUTOCONFIGURE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-AUTOCONFIGURE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:23:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
Unsigned32, Integer32, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Counter64, Counter32, NotificationType, TimeTicks, Gauge32, ModuleIdentity, ObjectIdentity, Bits, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Integer32", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Counter64", "Counter32", "NotificationType", "TimeTicks", "Gauge32", "ModuleIdentity", "ObjectIdentity", "Bits", "MibIdentifier")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
usDataMibs, = mibBuilder.importSymbols("Unisphere-Data-MIBs", "usDataMibs")
UsdEnable, = mibBuilder.importSymbols("Unisphere-Data-TC", "UsdEnable")
usdAutoConfMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48))
usdAutoConfMIB.setRevisions(('2002-11-18 00:00', '2000-11-16 00:00',))
if mibBuilder.loadTexts: usdAutoConfMIB.setLastUpdated('200211190000Z')
if mibBuilder.loadTexts: usdAutoConfMIB.setOrganization('Unisphere Networks Inc.')
class UsdAutoConfEncaps(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 17, 19))
namedValues = NamedValues(("ip", 0), ("ppp", 1), ("pppoe", 17), ("bridgedEthernet", 19))
usdAutoConfObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1))
usdAutoConf = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1))
usdAutoConfTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1), )
if mibBuilder.loadTexts: usdAutoConfTable.setStatus('current')
usdAutoConfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1), ).setIndexNames((0, "Unisphere-Data-AUTOCONFIGURE-MIB", "usdAutoConfIfIndex"), (0, "Unisphere-Data-AUTOCONFIGURE-MIB", "usdAutoConfEncaps"))
if mibBuilder.loadTexts: usdAutoConfEntry.setStatus('current')
usdAutoConfIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: usdAutoConfIfIndex.setStatus('current')
usdAutoConfEncaps = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 2), UsdAutoConfEncaps())
if mibBuilder.loadTexts: usdAutoConfEncaps.setStatus('current')
usdAutoConfEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 3), UsdEnable()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: usdAutoConfEnable.setStatus('current')
usdAutoConfMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4))
usdAutoConfMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 1))
usdAutoConfMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 2))
usdAutoConfCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 1, 1)).setObjects(("Unisphere-Data-AUTOCONFIGURE-MIB", "usdAutoConfGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdAutoConfCompliance = usdAutoConfCompliance.setStatus('current')
usdAutoConfGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 2, 1)).setObjects(("Unisphere-Data-AUTOCONFIGURE-MIB", "usdAutoConfEnable"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdAutoConfGroup = usdAutoConfGroup.setStatus('current')
mibBuilder.exportSymbols("Unisphere-Data-AUTOCONFIGURE-MIB", usdAutoConfIfIndex=usdAutoConfIfIndex, usdAutoConfGroup=usdAutoConfGroup, usdAutoConfMIBConformance=usdAutoConfMIBConformance, usdAutoConfMIB=usdAutoConfMIB, usdAutoConfCompliance=usdAutoConfCompliance, UsdAutoConfEncaps=UsdAutoConfEncaps, usdAutoConfEncaps=usdAutoConfEncaps, usdAutoConfTable=usdAutoConfTable, usdAutoConfEntry=usdAutoConfEntry, usdAutoConfMIBCompliances=usdAutoConfMIBCompliances, usdAutoConf=usdAutoConf, usdAutoConfObjects=usdAutoConfObjects, usdAutoConfEnable=usdAutoConfEnable, usdAutoConfMIBGroups=usdAutoConfMIBGroups, PYSNMP_MODULE_ID=usdAutoConfMIB)
|
# http://flask-sqlalchemy.pocoo.org/2.1/config/
SQLALCHEMY_DATABASE_URI = 'sqlite:////commandment/commandment.db'
# FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.
SQLALCHEMY_TRACK_MODIFICATIONS = False
PORT = 5443
# PLEASE! Do not take this key and use it for another product/project. It's
# only for Commandment's use. If you'd like to get your own (free!) key
# contact the mdmcert.download administrators and get your own key for your
# own project/product. We're trying to keep statistics on which products are
# requesting certs (per Apple T&C). Don't force Apple's hand and
# ruin it for everyone!
MDMCERT_API_KEY = 'b742461ff981756ca3f924f02db5a12e1f6639a9109db047ead1814aafc058dd'
PLISTIFY_MIMETYPE = 'application/xml'
|
def combine_words(word, **kwargs):
if 'prefix' in kwargs:
return kwargs['prefix'] + word
elif 'suffix' in kwargs:
return word + kwargs['suffix']
return word
print(combine_words('child', prefix='man'))
print(combine_words('child', suffix='ish'))
print(combine_words('child')) |
# -*- coding: utf-8 -*-
print('!'*30)
print(' Loja SUPER BARATÃO ')
print('!'*30)
lisProdutos = []
lisPrecos = []
precMil = 0
while True:
print('='*30)
lisProdutos.append(str(input('Nome do produto: ').strip() ).title())
precos = float(input('Preço: R$ '))
if precos >= 1000:
precMil += 1
lisPrecos.append(precos)
else:
lisPrecos.append(precos)
print('='*30)
sn = str(input('Quer continuar? [S/N] ').strip() ).upper()
while sn != 'N' and sn != 'S':
print('Opção inválida.')
sn = str(input('Quer continuar? [S/N] ').strip() ).upper()
if sn == 'N':
break
print(f'TOTAL DA COMPRA: {sum(lisPrecos):.2f}')
print(f'{precMil} produtos custam mais do que R$ 1000.00')
print(f'O produto mais barato foi "{lisProdutos[lisPrecos.index(min(lisPrecos))]}" que custa R$ {min(lisPrecos):.2f}')
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 09:03:49 2020
@author: Okuda
"""
|
#Tuple
#ordered
#indexed
#Immutable
#Faster than list
t = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
print(t)
print(type(t))
#t.append(20) AttributeError: 'tuple' object has no attribute 'append'
print(t[2])
print(t[-1])
print(t[1:3])
print(len(t))
print(t.count("Monday"))
print(t.index("Friday"))
#Problem:
"""
Given a tuple A , find if all elements of tuple are different or not.
Example 1:
Input:
A = (1, 2, 3, 4, 5, 4)
Output:
Not Distinct
Example 2:
Input:
A = (1, 2, 3, 4, 5)
Output:
Distinct
"""
A = (1, 2, 3, 4)
s = set(A)
if len(A) != len(s):
output = "Not Distinct"
elif len(A) == len(s):
output = "Distinct"
print(output)
print("#######################################################")
#Problem:
"""
Given a tuple A with distinct elements and an integer X, find the index position of X. Assume to have X in the tuple always.
Example 1:
Input:
A = (1, 2, 3, 4, 5)
X = 3
Output:
2
Example 2:
Input:
A = (3, 2, 1, 5, 4)
X = 5
Output:
3
"""
A = (1, 2, 3, 4, 5)
X = 3
for i in range(len(A)):
if A[i] == X:
print(i)
|
# -*- coding: utf-8 -*-
PI = 3.14159
def main():
r = float(input())
area = PI * r * r
print('A=%.4f' % area)
if __name__ == '__main__':
main() |
def get_action(self, states, epsilon):
if np.random.random() < epsilon:
return np.random.choice(self.num_actions)
else:
return np.argmax(self.predict(np.atleast_2d(states))[0]) |
'-----------------------------------------------------------------------------'
#================================___ФУНКЦІЇ___================================
#Функція із рекурсією
def golden_pyramid(triangle, row=0, column=0, total=0):
if row == len(triangle) - 1:
return total + triangle[row][column]
return max(golden_pyramid(triangle, row + 1, column,\
total + triangle[row][column]),\
golden_pyramid(triangle, row + 1, column + 1,\
total + triangle[row][column]))
#Функція без рекурсії
def golden_pyramid_d(triangle):
sums = [row[:] for row in triangle]
for i in range(len(sums) - 2, -1, -1):
for j in range(i + 1):
sums[i][j] += max(sums[i + 1][j],\
sums[i + 1][j + 1])
return sums[0][0]
#=============================================================================
'-----------------------------------------------------------------------------'
'*****************************************************************************'
#=======================___ОСНОВНА_ЧАСТИНА_ПРОГРАМИ___========================
n = int(input('input n = '))
lst = []
for i in range(n):
lst.append([])
lst[i] = list(map(int,input('Уведіть %d'%(i+1)+'-й рядок: ').split()))
golden_pyramid_main = [row[:] for row in lst]
for i in range(len(golden_pyramid_main) - 2, -1, -1):
for j in range(i + 1):
golden_pyramid_main [i][j] += \
max(golden_pyramid_main[i + 1][j],golden_pyramid_main[i + 1][j + 1])
#=============================================================================
'*****************************************************************************'
'-----------------------------------------------------------------------------'
#===============================___ВИВЕДЕННЯ___===============================
#---СУМИ---
print('\nСума = ', golden_pyramid(lst,row=0,column=0,total=0)) #Через рекурсивну функцію
print('Сума = ', golden_pyramid_d(lst)) #Через нерекурсивну функцію
print('Сума = ', golden_pyramid_main[0][0]) #Без використання надбудов
#---ПІРАМІДА---
print('\nПіраміда: ')
for i in range(n):
s = (n-i)*' ' + ' '*6 #Для оформлення
for j in range(i+1):
s += str(lst[i][j])+' '
print(s)
print('========END=========')
#=============================================================================
'-----------------------------------------------------------------------------'
|
'''Crie um programa que leia o nome e o preço de vários produtos
O programa deverá perguntar se o usuário quer continuar
No final mostre
A) Qual é o total gasto na compra.
B) Quantos produtos custam mais de 1k.
C) Qual é o nome do produto mais barato.'''
print('\033[36m{:=^37}\033[m'.format('Code-Save'))
print('\033[31m{:=^37}\033[m'.format('Eletro-Tex'))
total = tot1k = menor = cont = 0
barato = ' '
while True:
produto = str(input('\033[36mNome do produto:\033[m '))
preço = float(input('Preço do produto R$: '))
cont += 1
total += preço
if preço > 1000:
tot1k += 1
if cont == 1 or preço < menor:
menor = preço
barato = produto
resp = ' '
while resp not in 'SN':
resp = str(input('\033[36mContinuar compra [S/N]?\033[m ')).strip().upper()[0]
if resp == 'N':
break
print('\033[36m{:=^37}\033[m'.format('Obrigado, Volte sempre'))
print(f'O total da compra foi R$:{total:.2f} ')
print(f'\033[36m{tot1k} produtos custaram mais de 1k!\033[m ')
print(f'O produto mais barato foi o(a):{barato}, que custou R$:{menor:.2f}! ')
|
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2019/9/17 15:01
@Author : Jay Chen
@FileName: response_code.py
@GitHub : https://github.com/cRiii
"""
class RET:
OK = 200
PARAMS_MISSING_ERROR = 2001
IMAGE_CODE_OVERDUE_ERROR = 2002
IMAGE_CODE_INPUT_ERROR = 2003
USER_LOGIN_ERROR = 3001
USER_LOGOUT_ERROR = 3002
USER_NOT_EXIST = 3003
USER_PASSWORD_ERROR = 3004
USER_LOCK_ERROR = 3005
USER_REGISTER_ERROR = 3006
USER_OAUTH_ERROR = 3007
DATABASE_COMMIT_ERROR = 4001
DATABASE_SELECT_ERROR = 4002
REDIS_SAVE_ERROR = 4011
REDIS_GET_ERROR = 4012
error_map = {
RET.OK: u"成功",
RET.PARAMS_MISSING_ERROR: u"参数缺失错误",
RET.IMAGE_CODE_OVERDUE_ERROR: u"图片验证码过期错误",
RET.IMAGE_CODE_INPUT_ERROR: u"图片验证码输入错误",
RET.USER_LOGIN_ERROR: u"用户登陆失败",
RET.USER_LOGOUT_ERROR: u"用户退出失败",
RET.USER_NOT_EXIST: u"用户不存在",
RET.USER_PASSWORD_ERROR: u"用户密码错误",
RET.USER_LOCK_ERROR: u"锁定用户",
RET.USER_REGISTER_ERROR: u"用户注册错误",
RET.USER_OAUTH_ERROR: u"用户第三方认证错误",
RET.DATABASE_SELECT_ERROR: u"数据库查询失败",
RET.DATABASE_COMMIT_ERROR: u"数据库提交失败",
RET.REDIS_SAVE_ERROR: u'REDIS保存数据失败',
RET.REDIS_GET_ERROR: u'REDIS获取数据失败',
}
|
class TogaLayout(extends=android.view.ViewGroup):
@super({context: android.content.Context})
def __init__(self, context, interface):
self.interface = interface
def shouldDelayChildPressedState(self) -> bool:
return False
def onMeasure(self, width: int, height: int) -> void:
# print("ON MEASURE %sx%s" % (width, height))
self.measureChildren(width, height)
self.interface.rehint()
self.setMeasuredDimension(width, height)
def onLayout(self, changed: bool, left: int, top: int, right: int, bottom: int) -> void:
# print("ON LAYOUT %s %sx%s -> %sx%s" % (changed, left, top, right, bottom))
device_scale = self.interface.app._impl.device_scale
self.interface._update_layout(
width=(right - left) / device_scale,
height=(bottom - top) / device_scale,
)
self.interface.style.apply()
count = self.getChildCount()
# print("LAYOUT: There are %d children" % count)
for i in range(0, count):
child = self.getChildAt(i)
# print(" child: %s" % child, child.getMeasuredHeight(), child.getMeasuredWidth(), child.getWidth(), child.getHeight())
# print(" layout: ", child.interface.layout)
child.layout(
child.interface.layout.absolute.left * device_scale,
child.interface.layout.absolute.top * device_scale,
(child.interface.layout.absolute.left + child.interface.layout.width) * device_scale,
(child.interface.layout.absolute.top + child.interface.layout.height) * device_scale,
)
# def onSizeChanged(self, left: int, top: int, right: int, bottom: int) -> void:
# print("ON SIZE CHANGE %sx%s -> %sx%s" % (left, top, right, bottom))
# count = self.getChildCount()
# print("CHANGE: There are %d children" % count)
# for i in range(0, count):
# child = self.getChildAt(i)
# print(" child: %s" % child)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
# Functions & classes =========================================================
def _by_attr(xdom, attr):
"""
From `xdom` pick element with attributes defined by `attr`.
Args:
xdom (obj): DOM parsed by :mod:`xmltodict`.
attr (dict): Dictionary defining all the arguments.
Returns:
obj: List in case that multiple records were returned, or OrderedDict \
instance in case that there was only one. Blank array in case of \
no matching tag.
"""
out = []
for tag in xdom:
for attr_name, val in attr.iteritems():
if attr_name not in tag:
break
if val is not None and tag[attr_name] != val:
break
out.append(tag)
return out[0] if len(out) == 1 else out
class Modes(object):
"""
Container holding informations about modes which may be used by registrar
to register documents.
Attributes:
by_resolver (bool): True if the mode can be used.
by_registrar (bool): True if the mode can be used.
by_reservation (bool): True if the mode can be used.
"""
def __init__(self, by_resolver=False, by_registrar=False,
by_reservation=False):
self.by_resolver = by_resolver
self.by_registrar = by_registrar
self.by_reservation = by_reservation
def __eq__(self, other):
return all([
self.by_resolver == other.by_resolver,
self.by_registrar == other.by_registrar,
self.by_reservation == other.by_reservation,
])
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return "Modes(%r%r%r)" % (
self.by_resolver,
self.by_registrar,
self.by_reservation
)
@staticmethod
def from_xmldict(modes_tag):
"""
Parse Modes information from XML.
Args:
modes_tags (obj): OrderedDict ``<modes>`` tag returned from
:mod:`xmltodict`.
Returns:
obj: :class:`.Modes` instance.
"""
by_resolver = _by_attr(modes_tag, attr={"@name": "BY_RESOLVER"})
by_registrar = _by_attr(modes_tag, attr={"@name": "BY_REGISTRAR"})
by_reservation = _by_attr(modes_tag, attr={"@name": "BY_RESERVATION"})
return Modes(
by_resolver=by_resolver["@enabled"].lower() == "true",
by_registrar=by_registrar["@enabled"].lower() == "true",
by_reservation=by_reservation["@enabled"].lower() == "true",
)
|
L = list(map(int,list(input())))
i = 0
k = 1
while i < len(L):
L2 = list(map(int,list(str(k))))
j = 0
while i<len(L) and j <len(L2):
if L[i] == L2[j]:
i+=1
j+=1
k+=1
print(k-1) |
#
# PySNMP MIB module CENTILLION-ROOT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CENTILLION-ROOT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:15:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibIdentifier, iso, Counter32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Bits, TimeTicks, Counter64, Integer32, ModuleIdentity, NotificationType, enterprises, IpAddress, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "iso", "Counter32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Bits", "TimeTicks", "Counter64", "Integer32", "ModuleIdentity", "NotificationType", "enterprises", "IpAddress", "ObjectIdentity")
Counter32, = mibBuilder.importSymbols("SNMPv2-SMI-v1", "Counter32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
class StatusIndicator(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("valid", 1), ("invalid", 2))
class SsBackplaneType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("other", 1), ("atmBus", 2))
class SsChassisType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))
namedValues = NamedValues(("other", 1), ("six-slot", 2), ("twelve-slot", 3), ("workgroup", 4), ("three-slotC50N", 5), ("three-slotC50T", 6), ("six-slotBH5005", 7))
class SsModuleType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50))
namedValues = NamedValues(("empty", 1), ("other", 2), ("mTR4PC", 3), ("mTRMCP4PC", 4), ("mATM", 5), ("mTRFiber", 6), ("mTRMCPFiber", 7), ("mEther16PC10BT", 8), ("mEtherMCP8PC10BT", 9), ("mATM2PSMFiber", 10), ("mATM2PCopper", 11), ("mATM4PMMFiber", 12), ("mATM4PSMFiber", 13), ("mATM4PCopper", 14), ("mATMMCP2PSMFiber", 15), ("mATMMCP2PMMFiber", 16), ("mATMMCP2PCopper", 17), ("mATMMCP4PSMFiber", 18), ("mATMMCP4PMMFiber", 19), ("mATMMCP4PCopper", 20), ("mATM2PC", 21), ("mATM4PC", 22), ("mATMMCP2PC", 23), ("mATMMCP4PC", 24), ("mEther16P10BT100BTCopper", 25), ("mEther14P10BT100BF", 26), ("mEther8P10BF", 27), ("mEther10P10BT100BT", 28), ("mEther16P10BT100BTMixed", 29), ("mEther10P10BT100BTMIX", 30), ("mEther12PBFL", 32), ("mEther16P4x4", 33), ("mTRMCP8PC", 34), ("mTR8PC", 35), ("mEther24PC", 36), ("mEther24P10BT100BT", 37), ("mEther24P100BFx", 38), ("mTR8PFiber", 39), ("mATM4PMDA", 40), ("mATMMCP4PMDA", 41), ("mEther4P100BT", 42), ("mTR24PC", 43), ("mTR16PC", 44), ("mATMMCP1PSMFiber", 45), ("mATMMCP1PMMFiber", 46), ("mATM1PMMFiber", 47), ("mATM1PVNR", 48), ("mEther24P10BT100BTx", 49), ("mEther24P100BFX", 50))
class SsMediaType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))
namedValues = NamedValues(("mediaUnkown", 1), ("mediaTokenRing", 2), ("mediaFDDI", 3), ("mediaEthernet", 4), ("mediaATM", 5))
class MacAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6)
fixedLength = 6
class Boolean(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("true", 1), ("false", 2))
class BitField(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("clear", 1), ("set", 2))
class PortId(Integer32):
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 65535)
class CardId(Integer32):
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 16)
class FailIndicator(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("on", 1), ("off", 2))
class EnableIndicator(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("disabled", 1), ("enabled", 2))
centillion = MibIdentifier((1, 3, 6, 1, 4, 1, 930))
cnProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1))
proprietary = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2))
extensions = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 3))
cnTemporary = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 4))
cnSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1))
cnATM = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2))
sysChassis = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 1))
sysConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 2))
sysMonitor = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 3))
sysTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4))
sysEvtLogMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 5))
atmConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 1))
atmMonitor = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 2))
atmLane = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 3))
atmSonet = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 4))
sysMcpRedundTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4, 1))
cnPvcTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4, 2))
cnCentillion100 = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 1))
cnIBM8251 = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 2))
cnBayStack301 = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 3))
cn5000BH_MCP = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 4)).setLabel("cn5000BH-MCP")
cnCentillion50N = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 5))
cnCentillion50T = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 6))
cn5005BH_MCP = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 7)).setLabel("cn5005BH-MCP")
chassisType = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 1), SsChassisType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisType.setStatus('mandatory')
chassisBkplType = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 2), SsBackplaneType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisBkplType.setStatus('mandatory')
chassisPs1FailStatus = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 3), FailIndicator()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPs1FailStatus.setStatus('mandatory')
chassisPs2FailStatus = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 4), FailIndicator()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPs2FailStatus.setStatus('mandatory')
chassisFanFailStatus = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 5), FailIndicator()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisFanFailStatus.setStatus('mandatory')
chassisSerialNumber = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(3, 3)).setFixedLength(3)).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisSerialNumber.setStatus('mandatory')
chassisPartNumber = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(6, 6)).setFixedLength(6)).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPartNumber.setStatus('mandatory')
slotConfigTable = MibTable((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9), )
if mibBuilder.loadTexts: slotConfigTable.setStatus('mandatory')
slotConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1), ).setIndexNames((0, "CENTILLION-ROOT-MIB", "slotNumber"))
if mibBuilder.loadTexts: slotConfigEntry.setStatus('mandatory')
slotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotNumber.setStatus('mandatory')
slotModuleType = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 2), SsModuleType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleType.setStatus('deprecated')
slotModuleHwVer = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(6, 6)).setFixedLength(6)).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleHwVer.setStatus('mandatory')
slotModuleSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(3, 3)).setFixedLength(3)).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleSerialNumber.setStatus('mandatory')
slotModuleSwVer = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleSwVer.setStatus('mandatory')
slotModuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ok", 1), ("fail", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleStatus.setStatus('mandatory')
slotModuleLeds = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 7), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleLeds.setStatus('mandatory')
slotModuleReset = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("noReset", 1), ("reset", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: slotModuleReset.setStatus('mandatory')
slotConfigDelete = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 9), Boolean()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: slotConfigDelete.setStatus('mandatory')
slotConfigMediaType = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 10), SsMediaType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotConfigMediaType.setStatus('mandatory')
slotModuleMaxRAM = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleMaxRAM.setStatus('mandatory')
slotModuleInstalledRAM = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 12), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleInstalledRAM.setStatus('mandatory')
slotModuleFlashSize = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleFlashSize.setStatus('mandatory')
slotModuleProductImageId = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("notApplicable", 1), ("noAtmLanEmulation", 2), ("minAtmLanEmulation", 3), ("fullAtmLanEmulation", 4), ("pnnifullAtmLanEmulation", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleProductImageId.setStatus('mandatory')
slotModuleBaseMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 15), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotModuleBaseMacAddress.setStatus('mandatory')
slotLastResetEPC = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotLastResetEPC.setStatus('mandatory')
slotLastResetVirtualAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotLastResetVirtualAddress.setStatus('mandatory')
slotLastResetCause = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotLastResetCause.setStatus('mandatory')
slotLastResetTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: slotLastResetTimeStamp.setStatus('mandatory')
slotConfigAdd = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 20), Boolean()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: slotConfigAdd.setStatus('mandatory')
slotConfigExtClockSource = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 21), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: slotConfigExtClockSource.setStatus('mandatory')
slotConfigTrafficShapingRate = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 22), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: slotConfigTrafficShapingRate.setStatus('mandatory')
mibBuilder.exportSymbols("CENTILLION-ROOT-MIB", EnableIndicator=EnableIndicator, slotNumber=slotNumber, SsChassisType=SsChassisType, SsModuleType=SsModuleType, slotLastResetEPC=slotLastResetEPC, cnPvcTraps=cnPvcTraps, slotLastResetVirtualAddress=slotLastResetVirtualAddress, sysMcpRedundTrap=sysMcpRedundTrap, sysEvtLogMgmt=sysEvtLogMgmt, CardId=CardId, chassisPs1FailStatus=chassisPs1FailStatus, cnATM=cnATM, SsMediaType=SsMediaType, slotConfigTable=slotConfigTable, slotModuleHwVer=slotModuleHwVer, slotConfigMediaType=slotConfigMediaType, cnBayStack301=cnBayStack301, SsBackplaneType=SsBackplaneType, sysConfig=sysConfig, chassisPartNumber=chassisPartNumber, slotModuleLeds=slotModuleLeds, slotConfigExtClockSource=slotConfigExtClockSource, FailIndicator=FailIndicator, proprietary=proprietary, slotModuleReset=slotModuleReset, sysChassis=sysChassis, cnIBM8251=cnIBM8251, chassisBkplType=chassisBkplType, extensions=extensions, cnCentillion50N=cnCentillion50N, slotModuleType=slotModuleType, slotModuleProductImageId=slotModuleProductImageId, atmLane=atmLane, StatusIndicator=StatusIndicator, cnSystem=cnSystem, slotConfigEntry=slotConfigEntry, BitField=BitField, cnTemporary=cnTemporary, centillion=centillion, slotModuleStatus=slotModuleStatus, cnCentillion50T=cnCentillion50T, chassisSerialNumber=chassisSerialNumber, slotModuleSerialNumber=slotModuleSerialNumber, slotModuleFlashSize=slotModuleFlashSize, slotModuleBaseMacAddress=slotModuleBaseMacAddress, slotConfigAdd=slotConfigAdd, slotConfigDelete=slotConfigDelete, Boolean=Boolean, slotLastResetTimeStamp=slotLastResetTimeStamp, chassisFanFailStatus=chassisFanFailStatus, cn5000BH_MCP=cn5000BH_MCP, slotModuleInstalledRAM=slotModuleInstalledRAM, cnProducts=cnProducts, cn5005BH_MCP=cn5005BH_MCP, PortId=PortId, slotModuleSwVer=slotModuleSwVer, slotLastResetCause=slotLastResetCause, atmConfig=atmConfig, slotModuleMaxRAM=slotModuleMaxRAM, slotConfigTrafficShapingRate=slotConfigTrafficShapingRate, cnCentillion100=cnCentillion100, sysMonitor=sysMonitor, atmMonitor=atmMonitor, chassisPs2FailStatus=chassisPs2FailStatus, sysTrap=sysTrap, atmSonet=atmSonet, chassisType=chassisType, MacAddress=MacAddress)
|
l = 2
if(l == 1):
print(l)
elif(l == 2):
print(l+5)
else:
print(l+1)
|
n1, n2, n3 = map(int, input().split())
total = n1 * n2 * n3
print(total) |
class Atom:
def __init__(self, name, children):
self.name = name
self.children = children
if None in children:
raise Exception("none in lisp atom")
def __str__(self):
child_string = " ".join(
[str(e) if type(e) != str else f'"{e}"' for e in self.children]
)
return f"({self.name} {child_string})"
class Literal:
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
def __repr__(self):
return self.value
def __eq__(self, other):
return self.value == other
|
#This algoritm was copied at 16/Nov/2018 from https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python and applied to activity sequences
delimter = "@"
def length(s):
return s.count(delimter) + 1
def enumerateSequence(s):
list = s.split(delimter)
return enumerate(list,0)
def levenshtein(s1, s2):
if length(s1) < length(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if length(s2) == 0:
return length(s1)
previous_row = range(length(s2) + 1)
for i, c1 in enumerateSequence(s1):
current_row = [i + 1]
for j, c2 in enumerateSequence(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1] |
# -*- Mode: Python; coding: utf-8; indent-tabs-mpythoode: nil; tab-width: 4 -*-
# CODEWARS
# https://www.codewars.com/kata/5583090cbe83f4fd8c000051
#
# "Convert number to reversed array of digits"
def digitize(n):
if n == 0:
return [0]
if n < 0:
n *= -1
arr = []
while n > 0:
arr += [n % 10]
n /= 10
return arr
def testEqual(test, str1, str2):
print(test, str1 == str2)
def main():
testEqual(1, digitize(35231),[1,3,2,5,3])
testEqual(2, digitize(348597),[7,9,5,8,4,3])
testEqual(3, digitize(0),[0])
testEqual(4, digitize(1),[1])
testEqual(5, digitize(10),[0,1])
testEqual(6, digitize(100),[0,0,1])
testEqual(7, digitize(-1000),[0,0,0,1])
if __name__ == '__main__':
main() |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
end = len(s) -1
c = 0
while s[end] == " ":
end -= 1
while s[end] != " " and end >= 0:
c += 1
end -= 1
return c |
class Phoneme:
def __init__(self, ptype: str):
self.ptype = ptype
class Cons(Phoneme):
def __init__(self, voice: int, ctype: str):
super().__init__("Cons")
self.voice = voice
self.ctype = ctype
class PulmCons(Cons):
def __init__(self, voice: int, pcmanner: int, pcplace: int):
super().__init__(voice, "PulmCons")
self.pcmanner = pcmanner
self.pcplace = pcplace
class NonPulmCons(Cons):
def __init__(self, voice: int, npctype: str):
super().__init__(voice, "NonPulmCons")
self.npctype = npctype
class Ejective(NonPulmCons):
def __init__(self, voice: int, ejmanner: int, ejplace: int):
super().__init__(voice, "Ejective")
self.ejmanner = ejmanner
self.ejplace = ejplace
class Click(NonPulmCons):
def __init__(self, voice: int, clmanner: int, clplace: int):
super().__init__(voice, "Click")
self.clmanner = clmanner
self.clplace = clplace
class Implosive(NonPulmCons):
def __init__(self, voice: int, implace: int):
super().__init__(voice, "Implosive")
self.implace = implace
class Multi(Cons):
def __init__(self, voice: int, catype: str):
super().__init__(voice, "Multi")
self.catype = catype
self.sequence = []
def append(self, cons: Cons):
self.sequence.append(cons) |
log_table = []
alpha_table = []
def multiplie(x, y, P):
if x == 0 or y == 0:
return 0
P_deg = len(bin(P)) - 3
i, j = log_table[x], log_table[y]
return alpha_table[(i + j) % ((1 << P_deg)-1)]
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class DescribePackRes(object):
def __init__(self, packType=None, packMode=None, flowLimit=None, availableZoneNum=None, cdnSpeedTraffic=None, ddosBaseProtect=None, ddosElasticProtect=None, freeCert=None, botManage=None, waf=None, customUploadCert=None, ccAttackQpsSingle=None, ccAttackQpsTotal=None, dedicatedIp=None, availableNodeNum=None, specialCertNum=None, trueClientIp=None, originErrorPagePass=None, staticContentCache=None, customClearByUrl=None, advanceCustomClear=None, minCacheTtl=None, clientUploadFileLimit=None, maxCacheFileLimit=None, urlPrefetch=None, pageRuleNum=None, imageOptimize=None, http2=None, developMode=None, queryStringSort=None, customNameServer=None, generalCert=None, customCertNum=None, websiteAnalyseTimeSpecs=None, dnsAnalyseTime=None, attackAnalyseTime=None, auditLog=None, requestLog=None, owaspCoreRule=None, builtInPredefinedRule=None, firewallRuleNum=None, firewalRegularRule=None):
"""
:param packType: (Optional) 套餐类型
:param packMode: (Optional) 套餐模型(BASE->基础版 FLOW->流量版)
:param flowLimit: (Optional) 套餐流量
:param availableZoneNum: (Optional) 可用域名数
:param cdnSpeedTraffic: (Optional) cdn加速流量
:param ddosBaseProtect: (Optional) DDoS保底防护
:param ddosElasticProtect: (Optional) 是否支持DDoS弹性防护
:param freeCert: (Optional) 是否提供免费证书
:param botManage: (Optional) 是否支持BOT功能
:param waf: (Optional) 是否支持WAF
:param customUploadCert: (Optional) 自定义上传证书数量
:param ccAttackQpsSingle: (Optional) 单节点CC攻击QPS
:param ccAttackQpsTotal: (Optional) CC攻击QPS总量
:param dedicatedIp: (Optional) 独享IP数量
:param availableNodeNum: (Optional) 可用节点数量
:param specialCertNum: (Optional) 域名专用证书数
:param trueClientIp: (Optional) 是否支持TrueCLientIp
:param originErrorPagePass: (Optional) 是否支持RriginErrorPagePass
:param staticContentCache: (Optional) 是否支持静态内容缓存
:param customClearByUrl: (Optional) 基于URL自定义清除
:param advanceCustomClear: (Optional) 高级自定义清除(主机名、Tag、前缀目录)
:param minCacheTtl: (Optional) 最小缓存TTL时间
:param clientUploadFileLimit: (Optional) 客户端上传文件限制
:param maxCacheFileLimit: (Optional) 最大缓存文件限制
:param urlPrefetch: (Optional) 是否支持基于URL预取
:param pageRuleNum: (Optional) 页面规则数量
:param imageOptimize: (Optional) 是否支持页面优化
:param http2: (Optional) 是否支持HTTP2
:param developMode: (Optional) 是否支持开发模式
:param queryStringSort: (Optional) 是否支持查询字符串排序
:param customNameServer: (Optional) 是否支持自定义名称服务器(忽略)
:param generalCert: (Optional) 是否支持通用证书
:param customCertNum: (Optional) 自定义证书数量
:param websiteAnalyseTimeSpecs: (Optional) 网站分析时间规格
:param dnsAnalyseTime: (Optional) DNS分析时间(历史时间)
:param attackAnalyseTime: (Optional) 攻击分析时间(历史时间)
:param auditLog: (Optional) 是否支持审计日志
:param requestLog: (Optional) 是否支持请求日志
:param owaspCoreRule: (Optional) 是否支持OWASP核心规则
:param builtInPredefinedRule: (Optional) 是否支持内置预定义规则
:param firewallRuleNum: (Optional) 防火墙规则数量
:param firewalRegularRule: (Optional) 是否支持防火墙正则表达式规则
"""
self.packType = packType
self.packMode = packMode
self.flowLimit = flowLimit
self.availableZoneNum = availableZoneNum
self.cdnSpeedTraffic = cdnSpeedTraffic
self.ddosBaseProtect = ddosBaseProtect
self.ddosElasticProtect = ddosElasticProtect
self.freeCert = freeCert
self.botManage = botManage
self.waf = waf
self.customUploadCert = customUploadCert
self.ccAttackQpsSingle = ccAttackQpsSingle
self.ccAttackQpsTotal = ccAttackQpsTotal
self.dedicatedIp = dedicatedIp
self.availableNodeNum = availableNodeNum
self.specialCertNum = specialCertNum
self.trueClientIp = trueClientIp
self.originErrorPagePass = originErrorPagePass
self.staticContentCache = staticContentCache
self.customClearByUrl = customClearByUrl
self.advanceCustomClear = advanceCustomClear
self.minCacheTtl = minCacheTtl
self.clientUploadFileLimit = clientUploadFileLimit
self.maxCacheFileLimit = maxCacheFileLimit
self.urlPrefetch = urlPrefetch
self.pageRuleNum = pageRuleNum
self.imageOptimize = imageOptimize
self.http2 = http2
self.developMode = developMode
self.queryStringSort = queryStringSort
self.customNameServer = customNameServer
self.generalCert = generalCert
self.customCertNum = customCertNum
self.websiteAnalyseTimeSpecs = websiteAnalyseTimeSpecs
self.dnsAnalyseTime = dnsAnalyseTime
self.attackAnalyseTime = attackAnalyseTime
self.auditLog = auditLog
self.requestLog = requestLog
self.owaspCoreRule = owaspCoreRule
self.builtInPredefinedRule = builtInPredefinedRule
self.firewallRuleNum = firewallRuleNum
self.firewalRegularRule = firewalRegularRule
|
"""
auto generated test file
"""
# Create your tests here.
|
# https://leetcode.com/problems/delete-columns-to-make-sorted/
# You are given an array of n strings strs, all of the same length.
# The strings can be arranged such that there is one on each line, making a grid.
# For example, strs = ["abc", "bce", "cae"] can be arranged as:
# You want to delete the columns that are not sorted lexicographically. In the
# above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are
# sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1.
# Return the number of columns that you will delete.
################################################################################
class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
ans = 0
for col in zip(*strs):
for i in range(len(col) - 1):
if col[i] > col[i+1]:
ans += 1
break
return ans
|
def full_query(okta_id, video_string, fan_string, limit=5000):
query = f'''
WITH
-- FIRST CTE
all_comments (
comment_id,
parent_youtube_comment_id,
youtube_fan_id,
by_creator,
content,
archived,
timestamp,
up_vote,
down_vote,
video_title,
video_id,
video_thumbnail,
classification
)
AS (
SELECT
comments.id as comment_id,
comments.parent_youtube_comment_id as parent_youtube_comment_id,
comments.youtube_fan_id as youtube_fan_id,
comments.by_creator as by_creator,
comments.content as content,
comments.archived as archived,
comments.timestamp as timestamp,
comments.up_vote as up_vote,
comments.down_vote as down_vote,
video.video_title as video_title,
video.video_id as video_id,
video.thumbnail_url as video_thumbnail,
comments.classification as classification
FROM
(
SELECT
id as video_id,
video_title,
thumbnail_url
FROM
(
SELECT
id as creator_id
FROM
creators
WHERE
okta_platform_account_id = '{okta_id}'
)
creator
JOIN
youtube_videos
ON youtube_videos.creator_id = creator.creator_id
)
video
JOIN
youtube_comments comments
ON video.video_id = comments.youtube_video_id
),
-- SECOND CTE
top_comments (
comment_id,
parent_youtube_comment_id,
youtube_fan_id,
by_creator,
content,
archived,
timestamp,
up_vote,
down_vote,
video_title,
video_id,
video_thumbnail,
classification
)
AS
(
SELECT
*
FROM
all_comments
WHERE
parent_youtube_comment_id is NULL{video_string}{fan_string}
AND
by_creator is false
ORDER BY timestamp desc
LIMIT {limit}
),
-- THIRD CTE
top_fan_comments (
comment_id,
parent_youtube_comment_id,
youtube_fan_id,
timestamp
)
AS (
SELECT
all_comments.comment_id as comment_id,
all_comments.parent_youtube_comment_id as parent_youtube_comment_id,
all_comments.youtube_fan_id as youtube_fan_id,
all_comments.timestamp as timestamp
FROM
(
SELECT
DISTINCT youtube_fan_id as id
FROM top_comments
)
top_fans
JOIN all_comments
ON top_fans.id = all_comments.youtube_fan_id
),
-- FOURTH CTE
top_comments_with_replies (
comment_id,
parent_youtube_comment_id,
youtube_fan_id,
by_creator,
content,
archived,
timestamp,
up_vote,
down_vote,
video_title,
video_id,
video_thumbnail,
classification
)
AS (
SELECT
*
FROM
top_comments
UNION
SELECT
replies.comment_id as comment_id,
parent_youtube_comment_id,
youtube_fan_id,
by_creator,
content,
archived,
timestamp,
up_vote,
down_vote,
video_title,
video_id,
video_thumbnail,
classification
FROM
(
SELECT
comment_id
FROM
top_comments
) roots
JOIN
all_comments replies
ON roots.comment_id = replies.parent_youtube_comment_id
)
-- MAIN QUERY
SELECT
top_comments_with_replies.comment_id,
top_comments_with_replies.parent_youtube_comment_id,
top_comments_with_replies.youtube_fan_id,
top_comments_with_replies.content,
top_comments_with_replies.archived,
top_comments_with_replies.timestamp,
top_comments_with_replies.up_vote,
top_comments_with_replies.down_vote,
top_comments_with_replies.video_title,
top_comments_with_replies.video_id,
top_comments_with_replies.video_thumbnail,
fan_aggregations.total_comments,
fan_aggregations.total_replies,
fan_aggregations.responses,
fan_aggregations.sec_comment,
youtube_fans.account_title,
youtube_fans.thumbnail_url,
top_comments_with_replies.classification,
youtube_fans.note
FROM
top_comments_with_replies
LEFT JOIN
( -- AGGREGATION
SELECT
top_fan_comments.youtube_fan_id as youtube_fan_id,
COUNT(top_fan_comments.comment_id) as total_comments,
COUNT(top_fan_comments.parent_youtube_comment_id) as total_replies,
COUNT(responses.creator_response) as responses,
MAX(second_comment.sec_timestamp) as sec_comment
FROM
top_fan_comments
JOIN -- Second Comment timestamp
(
SELECT
comment_id,
youtube_fan_id,
nth_value(timestamp,2) OVER (PARTITION BY youtube_fan_id
ORDER BY timestamp DESC) AS sec_timestamp
FROM top_fan_comments
)
second_comment
ON top_fan_comments.comment_id = second_comment.comment_id
LEFT JOIN -- Creator Responses
(
SELECT
distinct parent_youtube_comment_id as creator_response
FROM all_comments
WHERE by_creator = TRUE
)
responses
ON top_fan_comments.comment_id = responses.creator_response
GROUP BY top_fan_comments.youtube_fan_id
)
fan_aggregations
ON top_comments_with_replies.youtube_fan_id = fan_aggregations.youtube_fan_id
LEFT JOIN
(
SELECT
id,
account_title,
thumbnail_url,
note
FROM
youtube_fans
)
youtube_fans
ON top_comments_with_replies.youtube_fan_id = youtube_fans.id
'''
return query |
n = int(input())
for j in range(1,n+1):
led = 0
x = input()
for i in range(0,len(x)):
if x[i] == '1':
led = led + 2
if x[i] == '2':
led = led + 5
if x[i] == '3':
led = led + 5
if x[i] == '4':
led = led + 4
if x[i] == '5':
led = led + 5
if x[i] == '6':
led = led + 6
if x[i] == '7':
led = led + 3
if x[i] == '8':
led = led + 7
if x[i] == '9':
led = led + 6
if x[i] == '0':
led = led + 6
print('{} leds'.format(led))
|
#Write a Python program to sum of three given integers. However, if two values are equal sum will be zero
def sumif(a,b,c):
if a != b != c and c !=a:
return a+b+c
else:
return 0
print(sumif(42,5,9))
print(sumif(8,8,12))
print(sumif(9,54,9))
print(sumif(87,4,9)) |
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, Charles Paul <cpaul@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Parameters for VCA modules
DOCUMENTATION = r'''
options:
username:
description:
- The vca username or email address, if not set the environment variable C(VCA_USER) is checked for the username.
type: str
aliases: [ user ]
password:
description:
- The vca password, if not set the environment variable C(VCA_PASS) is checked for the password.
type: str
aliases: [ pass, passwd]
org:
description:
- The org to login to for creating vapp.
- This option is required when the C(service_type) is I(vdc).
type: str
instance_id:
description:
- The instance ID in a vchs environment to be used for creating the vapp.
type: str
host:
description:
- The authentication host to be used when service type is vcd.
type: str
api_version:
description:
- The API version to be used with the vca.
type: str
default: "5.7"
service_type:
description:
- The type of service we are authenticating against.
type: str
choices: [ vca, vcd, vchs ]
default: vca
state:
description:
- Whether the object should be added or removed.
type: str
choices: [ absent, present ]
default: present
validate_certs:
description:
- If the certificates of the authentication is to be verified.
type: bool
default: yes
aliases: [ verify_certs ]
vdc_name:
description:
- The name of the vdc where the gateway is located.
type: str
gateway_name:
description:
- The name of the gateway of the vdc where the rule should be added.
type: str
default: gateway
'''
|
'''
Array Sum
You are given an array of integers of size . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large.
Input Format
The first line of the input consists of an integer . The next line contains space-separated integers contained in the array.
Output Format
Print a single value equal to the sum of the elements in the array.
Constraints
1<=N<=10 0<=a[i]<=10^10
SAMPLE INPUT
5
1000000001 1000000002 1000000003 1000000004 1000000005
SAMPLE OUTPUT
5000000015
'''
n=int(input())
x=map(int,input().split())
print(sum(x))
#List comprehension
n=int(input())
print(sum([int(x) for x in input().split()]))
|
DEFAULT_FPGA='VC709'
def addClock(file, FPGA=DEFAULT_FPGA):
file.write("#Clock Source\r\n")
if(FPGA=='VC709'):
file.write("set_property IOSTANDARD DIFF_SSTL15 [get_ports clk_p]\r\n")
file.write("set_property PACKAGE_PIN H19 [get_ports clk_p]\r\n")
file.write("set_property PACKAGE_PIN G18 [get_ports clk_n]\r\n")
file.write("set_property IOSTANDARD DIFF_SSTL15 [get_ports clk_n]\r\n")
elif(FPGA=='A735'):
file.write("set_property -dict {PACKAGE_PIN E3 IOSTANDARD LVCMOS33} [get_ports CLK]\r\n")
file.write("create_clock -period 10.000 -name sys_clk_pin -waveform {0.000 5.000} -add [get_ports CLK]\r\n")
elif(FPGA=='A7100'):
file.write("set_property -dict {PACKAGE_PIN E3 IOSTANDARD LVCMOS33} [get_ports CLK]\r\n")
file.write("create_clock -period 10.000 -name sys_clk_pin -waveform {0.000 5.000} -add [get_ports CLK]\r\n")
file.write("\r\n")
def addLED(file, FPGA=DEFAULT_FPGA):
file.write("#LEDs\r\n")
if(FPGA=='VC709'):
file.write("set_property -dict { PACKAGE_PIN AM39 IOSTANDARD LVCMOS18 } [get_ports { LED[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AN39 IOSTANDARD LVCMOS18 } [get_ports { LED[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AR37 IOSTANDARD LVCMOS18 } [get_ports { LED[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AT37 IOSTANDARD LVCMOS18 } [get_ports { LED[3] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AR35 IOSTANDARD LVCMOS18 } [get_ports { LED[4] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AP41 IOSTANDARD LVCMOS18 } [get_ports { LED[5] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AP42 IOSTANDARD LVCMOS18 } [get_ports { LED[6] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AU39 IOSTANDARD LVCMOS18 } [get_ports { LED[7] }];\r\n")
elif(FPGA=='A735'):
file.write("set_property -dict { PACKAGE_PIN H5 IOSTANDARD LVCMOS33 } [get_ports { LED[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN J5 IOSTANDARD LVCMOS33 } [get_ports { LED[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN T9 IOSTANDARD LVCMOS33 } [get_ports { LED[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN T10 IOSTANDARD LVCMOS33 } [get_ports { LED[3] }];\r\n")
elif(FPGA=='A7100'):
file.write("set_property -dict { PACKAGE_PIN H5 IOSTANDARD LVCMOS33 } [get_ports { LED[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN J5 IOSTANDARD LVCMOS33 } [get_ports { LED[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN T9 IOSTANDARD LVCMOS33 } [get_ports { LED[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN T10 IOSTANDARD LVCMOS33 } [get_ports { LED[3] }];\r\n")
file.write("\r\n")
def addSwitches(file, FPGA=DEFAULT_FPGA):
file.write("#Switches\r\n")
if(FPGA=='VC709'):
file.write("set_property -dict { PACKAGE_PIN AV30 IOSTANDARD LVCMOS18 } [get_ports { SW[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AY33 IOSTANDARD LVCMOS18 } [get_ports { SW[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN BA31 IOSTANDARD LVCMOS18 } [get_ports { SW[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN BA32 IOSTANDARD LVCMOS18 } [get_ports { SW[3] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AW30 IOSTANDARD LVCMOS18 } [get_ports { SW[4] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AY30 IOSTANDARD LVCMOS33 } [get_ports { SW[5] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN BA30 IOSTANDARD LVCMOS18 } [get_ports { SW[6] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN BB31 IOSTANDARD LVCMOS18 } [get_ports { SW[7] }];\r\n")
elif(FPGA=='A735'):
file.write("set_property -dict { PACKAGE_PIN A8 IOSTANDARD LVCMOS33 } [get_ports { SW[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN C11 IOSTANDARD LVCMOS33 } [get_ports { SW[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN C10 IOSTANDARD LVCMOS33 } [get_ports { SW[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN A10 IOSTANDARD LVCMOS33 } [get_ports { SW[3] }];\r\n")
elif(FPGA=='A7100'):
file.write("set_property -dict { PACKAGE_PIN A8 IOSTANDARD LVCMOS33 } [get_ports { SW[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN C11 IOSTANDARD LVCMOS33 } [get_ports { SW[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN C10 IOSTANDARD LVCMOS33 } [get_ports { SW[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN A10 IOSTANDARD LVCMOS33 } [get_ports { SW[3] }];\r\n")
file.write("\r\n")
def addUART(file, FPGA=DEFAULT_FPGA):
file.write("#Uart\r\n")
if(FPGA=='VC709'):
file.write("set_property -dict { PACKAGE_PIN AU36 IOSTANDARD LVCMOS18 } [get_ports { TX }];\r\n")
elif(FPGA=='A735'):
file.write("set_property -dict { PACKAGE_PIN D10 IOSTANDARD LVCMOS33 } [get_ports { TX }];\r\n")
file.write("#set_property -dict {PACKAGE_PIN A9 IOSTANDARD LVCMOS33 } [get_ports RX];\r\n")
elif(FPGA=='A7100'):
file.write("set_property -dict { PACKAGE_PIN D10 IOSTANDARD LVCMOS33 } [get_ports { TX }];\r\n")
file.write("#set_property -dict {PACKAGE_PIN A9 IOSTANDARD LVCMOS33 } [get_ports RX];\r\n")
file.write("\r\n")
def addButtons(file, FPGA=DEFAULT_FPGA):
file.write("#Buttons\r\n")
if(FPGA=='VC709'):
file.write("set_property -dict { PACKAGE_PIN AV39 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AW40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AP40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AU38 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[3] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN AR40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[4] }];\r\n")
elif(FPGA=='A735'):
file.write("set_property -dict { PACKAGE_PIN D9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN C9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN B9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN B8 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[3] }];\r\n")
elif(FPGA=='A7100'):
file.write("set_property -dict { PACKAGE_PIN D9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[0] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN C9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[1] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN B9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[2] }];\r\n")
file.write("set_property -dict { PACKAGE_PIN B8 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[3] }];\r\n")
file.write("\r\n")
def addClockBlock(file, FPGA=DEFAULT_FPGA):
file.write("create_pblock pblock_clk_div\r\n")
file.write("add_cells_to_pblock [get_pblocks pblock_clk_div] [get_cells -quiet [list clk_div]]\r\n")
if(FPGA=='VC709'):
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X196Y475:SLICE_X221Y499}\r\n")
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X13Y190:RAMB18_X14Y199}\r\n")
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X13Y95:RAMB36_X14Y99}\r\n")
elif(FPGA=='A735'):
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X36Y134:SLICE_X57Y149}\r\n")
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X1Y54:RAMB18_X1Y59}\r\n")
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X1Y27:RAMB36_X1Y29}\r\n")
file.write("set_property BEL MMCME2_ADV [get_cells clk_div/MMCME2_ADV_inst]\r\n")
file.write("set_property LOC MMCME2_ADV_X1Y1 [get_cells clk_div/MMCME2_ADV_inst]\r\n")
elif(FPGA=='A7100'):
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X66Y134:SLICE_X79Y149}\r\n")
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X2Y54:RAMB18_X2Y59}\r\n")
file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X2Y27:RAMB36_X2Y29}\r\n")
file.write("set_property BEL MMCME2_ADV [get_cells clk_div/MMCME2_ADV_inst]\r\n")
file.write("set_property LOC MMCME2_ADV_X1Y1 [get_cells clk_div/MMCME2_ADV_inst]\r\n")
file.write("set_property SNAPPING_MODE ON [get_pblocks pblock_clk_div]\r\n")
file.write("\r\n")
def addUARTCtrlBlock(file, FPGA=DEFAULT_FPGA):
file.write("create_pblock pblock_uart_ctrl\r\n")
file.write("add_cells_to_pblock [get_pblocks pblock_uart_ctrl] [get_cells -quiet [list uart_ctrl]]\r\n")
if(FPGA=='VC709'):
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X170Y475:SLICE_X195Y499}\r\n")
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X11Y190:RAMB18_X12Y199}\r\n")
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X11Y95:RAMB36_X12Y99}\r\n")
elif(FPGA=='A735'):
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X36Y118:SLICE_X57Y133}\r\n")
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X1Y50:RAMB18_X1Y51}\r\n")
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X1Y25:RAMB36_X1Y25}\r\n")
elif(FPGA=='A7100'):
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X52Y134:SLICE_X65Y149}\r\n")
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X1Y54:RAMB18_X1Y59}\r\n")
file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X1Y27:RAMB36_X1Y29}\r\n")
file.write("set_property SNAPPING_MODE ON [get_pblocks pblock_uart_ctrl]\r\n")
file.write("\r\n")
def addRRAMCtrlBlock(file, FPGA=DEFAULT_FPGA):
file.write("create_pblock pblock_rram_ctrl\r\n")
file.write("add_cells_to_pblock [get_pblocks pblock_rram_ctrl] [get_cells -quiet [list rram_ctrl instdb]]\r\n")
if(FPGA=='VC709'):
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X170Y0:SLICE_X221Y474}\r\n")
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X11Y0:RAMB18_X14Y189}\r\n")
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X11Y0:RAMB36_X14Y94}\r\n")
elif(FPGA=='A735'):
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X36Y0:SLICE_X65Y99}\r\n")
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X1Y0:RAMB18_X2Y39}\r\n")
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X1Y0:RAMB36_X2Y19}\r\n")
elif(FPGA=='A7100'):
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X52Y0:SLICE_X79Y133}\r\n")
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X1Y0:RAMB18_X2Y51}\r\n")
file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X1Y0:RAMB36_X2Y25}\r\n")
file.write("set_property SNAPPING_MODE ON [get_pblocks pblock_rram_ctrl]\r\n")
file.write("\r\n")
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 30 22:11:59 2022
@author: Akshatha
"""
# recursive data structure
class TreeNode():
def __init__(self, data):
self.parent = None
self.data = data
self.children = []
def add_child(self, child):
self.children.append(child)
child.parent = self
def print_tree(self,level=0):
print(self.data)
level += 1
for child in self.children:
print('\t'*level,end=' ')
child.print_tree(level)
def build_tree():
root = TreeNode('Books')
category_1 = TreeNode('Mystery')
category_1.add_child(TreeNode('Behind her eyes'))
category_1.add_child(TreeNode('Black water lilies'))
category_2 = TreeNode('Adventure')
category_2.add_child(TreeNode('Secret seven series'))
category_2.add_child(TreeNode('Famous five series'))
category_3 = TreeNode('Science Fiction')
category_3.add_child(TreeNode('Project Hail Mary'))
category_3.add_child(TreeNode('Deception Point'))
root.add_child(category_1)
root.add_child(category_2)
root.add_child(category_3)
return root
if __name__ == '__main__':
root = build_tree()
root.print_tree()
|
# Bucles For Each - Bucle "Para cada X"
# repite un conjunto de sentencias un determinado numero de veces. Es muy util para "recorer" listas de valores como listas, cadenas, diccionarios, rangos, etc.
# Una sentencia for comienza con la palabra clave for, seguida por una variable, seguido por la palabra clave in, seguido por un valor iterable, y terminando con dos puntos.
# En cada ejecución, a la variable en la sentencia for se le asigna el valor del siguiente elemento de la lista.
# for <item> in <iterable>:
# pass
# la variable que se usa despues de la palabra for, es la que tendrá el valor actual en la iteración/vuelta
for contador in range(5):
print('En esta iteración, el CONTADOR vale ' + str(contador))
for un_item in "En este conjunto de letras":
print(un_item)
# Recorriendo una Lista de forma simple.
amigos = ["Juan", "Caren", "Brayan"]
for nombre_amigo in amigos:
print(nombre_amigo)
print("fin lista \n")
# la función range() devuelve una secuencia de numeros iniciando en 0, hasta el valor máximo introducido.
# range(5) devuelve range(0, 5)
# es equivalente a la lista [0, 1, 2, 3, 4]
# print(list(range(5)))
# de 0 a 9, no incluye a 10.
for indice in range(10):
print(indice)
print("fin del for \n")
# de 3 a 9, no incluye a 10.
for indice in range(3, 10):
print(indice)
print("fin del for \n")
# Recorriendo una Lista de forma manual
amigos = ["Juan", "Caren", "Brayan"]
for index in range(len(amigos)):
print(amigos[index])
# condiciones simples para un elemento dentro del bucle
amigos = ["Juan", "Caren", "Brayan"]
for index in range(len(amigos)):
if index == 0:
print("\n")
print("=== Lista Amigos ===")
# else:
# print("")
print(amigos[index])
print("=== * ===")
|
class Calculator:
def __init__(self, a: int, b: int) -> None:
self.a = a
self.b = b
def suma(self):
return self.a + self.b
def resta(self):
return self.a - self.b
def multiplicacion(self):
return self.a * self.b
def division(self):
try:
return self.a / self.b
except ZeroDivisionError:
return('No se puede dividir entre cero')
def potencia(self):
return self.a ** self.b
def raiz(self):
if(self.a < 0):
return('No se puede sacar raiz a un numero negativo')
else:
return self.a ** 1/self.b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.