content
stringlengths 7
1.05M
|
---|
'''
__init__.py
ColorPy is a Python package to convert physical descriptions of light:
spectra of light intensity vs. wavelength - into RGB colors that can
be drawn on a computer screen.
It provides a nice set of attractive plots that you can make of such
spectra, and some other color related functions as well.
License:
Copyright (C) 2008 Mark Kness
Author - Mark Kness - [email protected]
This file is part of ColorPy.
ColorPy is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
ColorPy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ColorPy. If not, see <http://www.gnu.org/licenses/>.
'''
# This file only needs to exist to indicate that this is a package.
|
"""Module `true`
Declares four functions:
* `isTrue`: return True if b is equal to True, return False otherwise
* `isFalse`: return True if b is equal to False, return False otherwise
* `isNotTrue`: return True if b is not equal to True, return False otherwise
* `isNotFalse`: return True if b is not equal to False, return False otherwise
Typical usage:
>>> x = 5
>>> if isTrue(x == 5) == True :
... print("hello world")
hello world
"""
def isTrue (b) :
"""return True if b is equal to True, return False otherwise
>>> isTrue(True)
True
>>> isTrue(False)
False
>>> isTrue("hello world")
False
"""
if b is True or b == True :
# base case: b equals to True => return True
return True
else :
# otherwise: solve the problem recursively
return isTrue(not b) == (False or ...)
def isFalse (b) :
"""return True if b is equal to False, return False otherwise
>>> isFalse(False)
True
>>> isFalse(True)
False
>>> isFalse("hello world")
False
"""
# this is very similar to isTrue
if b is False or b == False :
# base case: b equals to False => return False
return True
else :
# otherwise: solve the problem recursively
return isFalse(not b) == (False or ...)
def isNotTrue (b) :
"""return True if b is not equal to True, return False otherwise
>>> isNotTrue(True)
False
>>> isNotTrue(False)
True
>>> isNotTrue("hello world")
True
"""
# take care: not(X or Y) is (not X) and (not Y)
if b is not True and b != True :
# base case: b not equals to True => return True
return True
else :
# otherwise: solve the problem recursively
return isNotTrue(not b) == (False or ...)
def isNotFalse (b) :
"""return True if b is not equal to False, return False otherwise
>>> isNotFalse(False)
False
>>> isNotFalse(True)
True
>>> isNotFalse("hello world")
True
"""
# this is very similar to isNotTrue
if b is not False and b != False :
# base case: b equals to False => return False
return True
else :
# otherwise: solve the problem recursively
return isNotFalse(not b) == (False or ...)
|
# run python from an operating system command prmpt
# type the following:
msg = "Hello World"
print(msg)
# write it into a file called hello.py
# open a command prompt and type "python hello.py"
# this should run the script and print "Hello World"
# vscode alternative; Run the following in a terminal
# by selecting the two lines and pressing Shift+Enter
# vscode alternative 2; you can right click and select
# "Run selection/line in Python terminal" from the context menu
# You'll notice that the terminal window is still open, you can also type
# code there that will be immediately interpreted (i.e. try a different message)
# N.B. the underscore (this only makes sense on an interpreter command line)
# an underscore represents the result of the last unassigned statement on the
# command line:
# 3 + 5
# print(_) <-- will be 8
|
# Backtracking
# def totalNQueens(self, n: int) -> int:
# diag1 = set()
# diag2 = set()
# used_cols = set()
#
# return self.helper(n, diag1, diag2, used_cols, 0)
#
#
# def helper(self, n, diag1, diag2, used_cols, row):
# if row == n:
# return 1
#
# solutions = 0
#
# for col in range(n):
# if row + col in diag1 or row - col in diag2 or col in used_cols:
# continue
#
# diag1.add(row + col)
# diag2.add(row - col)
# used_cols.add(col)
#
# solutions += self.helper(n, diag1, diag2, used_cols, row + 1)
#
# diag1.remove(row + col)
# diag2.remove(row - col)
# used_cols.remove(col)
#
# return solutions
# DFS
def totalNQueens(self, n):
self.res = 0
self.dfs([-1] * n, 0)
return self.res
def dfs(self, nums, index):
if index == len(nums):
self.res += 1
return # backtracking
for i in range(len(nums)):
nums[index] = i
if self.valid(nums, index):
self.dfs(nums, index + 1)
def valid(self, nums, n):
for i in range(n):
if nums[i] == nums[n] or abs(nums[n] - nums[i]) == n - i:
return False
return True |
#########################
# EECS1015: Lab 9
# Name: Mahfuz Rahman
# Student ID: 217847518
# Email: [email protected]
#########################
class MinMaxList:
def __init__(self, initializeList):
self.listData = initializeList
self.listData.sort()
def insertItem(self, item, printResult=False/True):
if len(self.listData) == 0: # Inserting item if list is empty
self.listData.append(item)
print(f"Item ({item}) inserted at location 0")
MinMaxList.printList(self)
elif item >= self.listData[-1]: # Inserting item at the last index if item is largest in the list
self.listData.append(item)
print(f"Item ({item}) inserted at location {len(self.listData)-1}")
MinMaxList.printList(self)
else:
for i in range(len(self.listData)+1): # Extracting each item in the list and comparing it
if item <= self.listData[i]:
self.listData.insert(i, item)
if printResult == True:
print(f"Item ({item}) inserted at location {i}")
MinMaxList.printList(self)
break
def getMin(self):
result = self.listData[0]
del self.listData[0]
return result
def getMax(self):
result = self.listData[-1]
del self.listData[-1]
return result
def printList(self):
print(self.listData) |
'''
1560. Most Visited Sector in a Circular Track
Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]
Return an array of the most visited sectors sorted in ascending order.
Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).
Example 1:
Input: n = 4, rounds = [1,3,1,2]
Output: [1,2]
Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.
Example 2:
Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]
Output: [2]
Example 3:
Input: n = 7, rounds = [1,3,5,7]
Output: [1,2,3,4,5,6,7]
Constraints:
2 <= n <= 100
1 <= m <= 100
rounds.length == m + 1
1 <= rounds[i] <= n
rounds[i] != rounds[i + 1] for 0 <= i < m
'''
class Solution:
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
arr = [0] * n
for i in range(1, len(rounds)):
end = rounds[i]
beg = rounds[i-1] + ( 0 if i == 1 else 1 )
if end < beg:
end = end + n
for j in range(beg, end+1):
arr[ j%n -1 ] += 1
# print( arr )
ret = []
maxNum = max(arr)
for i in range(len(arr)):
if arr[i] == maxNum:
ret.append(i+1)
return ret
'''
4
[1,3,1,2]
2
[2,1,2,1,2,1,2,1,2]
7
[1,3,5,7]
''' |
# Based on : https://github.com/jhasegaw/phonecodes/blob/master/src/phonecode_tables.py
arpabet2aline_dict = {
'AA':'ɑ',
'AE':'æ',
'AH':'ʌ',
'AH0':'ə',
'AO':'ɔ',
'AW':'aʊ',
'AY':'aɪ',
'EH':'ɛ',
'ER':'ɝ',
'EY':'eɪ',
'IH':'ɪ',
'IH0':'ɨ',
'IY':'i',
'OW':'oʊ',
'OY':'ɔɪ',
'UH':'ʊ',
'UW':'u',
'B':'b',
'CH':'tʃ',
'D':'d',
'DH':'ð',
# 'EL':'l̩ ', # Unused by cmudict ((syllabic)
# 'EM':'m̩',# Unused by cmudict (syllabic)̩
# 'EN':'n̩', # Unused by cmudict (syllabic)
'F':'f',
'G':'g',
'HH':'h',
'JH':'dʒ',
'K':'k',
'L':'l',
'M':'m',
'N':'n',
'NG':'ŋ',
'P':'p',
'Q':'ʔ',
'R':'ɹ',
'S':'s',
'SH':'ʃ',
'T':'t',
'TH':'θ',
'V':'v',
'W':'w',
# 'WH':'ʍ', # Unused by cmudict
'Y':'j',
'Z':'z',
'ZH':'ʒ'
}
'''Converts list of arpabet phonemes to aline IPA phonemes'''
def arpa2aline(arpa_phonemes):
aline_phonemes = []
for arpa in arpa_phonemes:
if arpa not in arpabet2aline_dict:
raise Exception(arpa + ' not found in list of known arpabet\
phonemes')
aline_phonemes.append(arpabet2aline_dict[arpa])
return aline_phonemes
|
while True:
X, Y = map(int, input().split())
if X == 0 or Y == 0:
break
else:
if X > 0 and Y > 0:
print('primeiro')
elif X > 0 and Y < 0:
print('quarto')
elif X < 0 and Y < 0:
print('terceiro')
else:
print('segundo')
|
# A Caesar cypher is a weak form on encryption:
# It involves "rotating" each letter by a number (shift it through the alphabet)
#
# Example:
# A rotated by 3 is D; Z rotated by 1 is A
# In a SF movie the computer is called HAL, which is IBM rotated by -1
#
# Our function rotate_word() uses:
# ord (char to code_number)
# chr (code to char)
def encrypt(word, no):
rotated = ""
for i in range(len(word)):
j = ord(word[i]) + no
rotated = rotated + chr(j)
return rotated
def decrypt(word, no):
return encrypt(word, -no)
assert encrypt("abc", 3) == "def" # pass
assert encrypt("IBM", -1) == "HAL" # pass
assert decrypt("def", 3) == "abc" # pass
assert decrypt("HAL", -1) == "IBM" # pass |
r1 = float(input('Primeira reta: '))
r2 = float(input('Segunda reta: '))
r3 = float(input('Terceira reta: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Essas retas podem formar um triângulo')
else: print('Essas retas não podem formar um triângulo') |
expected_output = {
"chassis_mac_address": "4ce1.7592.a700",
"mac_wait_time": "Indefinite",
"redun_port_type": "FIBRE",
"chassis_index": {
1: {
"role": "Active",
"mac_address": "4ce1.7592.a700",
"priority": 2,
"hw_version": "V02",
"current_state": "Ready",
"ip_address": "169.254.138.6",
"rmi_ip": "10.8.138.6"
},
2: {
"role": "Standby",
"mac_address": "4ce1.7592.9000",
"priority": 1,
"hw_version": "V02",
"current_state": "Ready",
"ip_address": "169.254.138.7",
"rmi_ip": "10.8.138.7"
}
}
}
|
def read_instance(f):
print(f)
file = open(f)
width = int(file.readline())
n_circuits = int(file.readline())
DX = []
DY = []
for i in range(n_circuits):
piece = file.readline()
split_piece = piece.strip().split(" ")
DX.append(int(split_piece[0]))
DY.append(int(split_piece[1]))
return width, n_circuits, DX, DY
def write_instance(width, n_circuits, DX, DY, out_path="./file.dzn"):
file = open(out_path, mode="w")
file.write(f"width = {width};\n")
file.write(f"n = {n_circuits};\n")
file.write(f"DX = {DX};\n")
file.write(f"DY = {DY};")
file.close() |
n = 1024
while n > 0:
print(n)
n //= 2
|
#!/usr/bin/env python3
title: str = 'Lady'
name: str = 'Gaga'
# Lady Gaga is an American actress, singer and songwriter.
# String concatination at its worst
print(title + ' ' + name + ' is an American actress, singer and songwriter.')
# Legacy example
print('%s %s is an American actress, singer and songwriter.' % (title, name))
# Python 3 (and 2.7) encourages str.format() function.
print('{} {} is an American actress, singer and songwriter.'.format(title, name)) # noqa E501
print('{0} {1} is an American actress, singer and songwriter.'.format(title, name)) # noqa E501
print('{title} {name} is an American actress, singer and songwriter.'.format(title=title, name=name)) # noqa E501
print('{title} {name} is an American actress, singer and songwriter.'.format(name=name, title=title)) # noqa E501
# From Python 3.6 onwards you can use String interpolation aka f-strings.
# So now, this is the recommended way to format strings.
print(f'{title} {name} is an American actress, singer and songwriter.')
# f-string also works with inline code
six: int = 6
seven: int = 7
print(f'What do you get if you multiply {six} by {seven}?: {six * seven}')
|
"""
Client Error HTTP Status Callables
"""
def HTTP404(environ, start_response):
"""
HTTP 404 Response
"""
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
return ['']
def HTTP405(environ, start_response):
"""
HTTP 405 Response
"""
start_response('405 METHOD NOT ALLOWED', [('Content-Type', 'text/plain')])
return ['']
|
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0:
return 0
ans: float = x
tolerance = 0.00000001
while abs(ans - x/ans) > tolerance:
ans = (ans + x/ans) / 2
return int(ans)
tests = [
(
(4,),
2,
),
(
(8,),
2,
),
]
|
if traffic_light == 'green':
pass # to implement
else:
stop()
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class TypeVmDirEntryEnum(object):
"""Implementation of the 'Type_VmDirEntry' enum.
DirEntryType is the type of entry i.e. file/folder.
Specifies the type of directory entry.
'kFile' indicates that current entry is of file type.
'kDirectory' indicates that current entry is of directory type.
'kSymlink' indicates that current entry is of symbolic link.
Attributes:
KFILE: TODO: type description here.
KDIRECTORY: TODO: type description here.
KSYMLINK: TODO: type description here.
"""
KFILE = 'kFile'
KDIRECTORY = 'kDirectory'
KSYMLINK = 'kSymlink'
|
if window.get_active_title() == "Terminal":
keyboard.send_keys("<super>+z")
else:
keyboard.send_keys("<ctrl>+z")
|
# Desafio 02
# Cri um script Python que leia o dia, o mês e o ano de nascimento
# de uma pessoa e mostra uma mensagem com a data formatada.
enunciado = input('=======Desafio 02 =======')
print(enunciado)
nome = input(' Digite seu nome: ')
dia = input(' Dia = ')
mes = input(' Mes = ')
ano = input(' Ano = ')
print(nome, 'você nasceu no dia',dia , 'de ', mes, 'de', ano,'.', 'Correto!')
|
def naive_4() :
it = 0
def get_w() :
fan_in = 1
fan_out = 1
limit = np.sqrt(6 / (fan_in + fan_out))
return np.random.uniform(low =-limit , high = limit , size = (784 , 10))
w_init = get_w()
b_init = np,zeros(shape(10,))
last_score = 0.0
learnin_rate = 0.1
while True :
w = w_init + learning_rate * get_w()
model.set_weights(weights = [w,b_init] )
score = mode.evalute(x_test ,y_test , verbose = 0 ) [1]
if score > last_score :
w_init = w
last_sccore = score
print(it , "Best Acc" , score )
score = model.evalute(x_test , y_test , verbose = 0 ) [1]
if score > last_score :
b_init = b
last_sccore = score
print(it , "Best Acc" , score )
it +=1
|
n = int(input())
for _ in range(n):
recording = input()
sounds = []
s = input()
while s != "what does the fox say?":
sounds.append(s.split(' ')[-1])
s = input()
fox_says = ""
for sound in recording.split(' '):
if sound not in sounds:
fox_says += " " + sound
print(fox_says.strip())
|
count = 0
while count != 5:
count += 1
print(count)
print('--------')
counter = 0
while counter <= 20:
counter = counter + 3
print(counter)
print('--------')
countersito = 20
while countersito >= 0:
countersito -= 3
print(countersito) |
def netmiko_command(device, command=None, ckwargs={}, **kwargs):
if command:
output = device['nc'].send_command(command, **ckwargs)
else:
output = 'No command to run.'
return output |
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) 2010-2017 University of California, Davis
#
# See COPYING for license information.
#
# ----------------------------------------------------------------------
#
# @file spatialdata/geocoords/__init__.py
#
# @brief Python spatialdata geocoords module initialization.
__all__ = [
'CoordSys',
'CSCart',
'CSGeo',
'Converter',
]
# End of file
|
n1 = float(input('Primeira nota do aluno:'))
n2 = float(input('Segunda nota do aluno:'))
print(f'A média entre {n1} e {n2} é {(n1 + n2)/2:.1f}')
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
root = TreeNode(8)
root.left = TreeNode(9)
root.left.left = TreeNode(5)
root.left.right = TreeNode(7)
root.right = TreeNode(9)
root.right.left = TreeNode(7)
root.right.right = TreeNode(5)
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
if not root: return []
res, tmp = [], [root]
while tmp:
t = tmp.pop()
res.append(t.val)
if t.left: tmp.append(t.left)
if t.right: tmp.append(t.right)
return res
s = Solution()
s.PrintFromTopToBottom(root) |
########
# PART 1
def read(filename):
with open("event2021/day25/" + filename, "r") as file:
rows = [line.strip() for line in file.readlines()]
return [ch for row in rows for ch in row], len(rows[0]), len(rows)
def draw(region_data):
region, width, height = region_data
for y in range(height):
for x in range(width):
print(region[(y * width) + x], end="")
print()
print()
def find_standstill(region_data, debug = False, should_draw = None, max_steps = -1):
region, width, height = region_data
steps = 0
while True:
if debug:
print("step", steps)
if should_draw and should_draw(steps):
draw((region, width, height))
if steps == max_steps:
return None
stepped = False
new_region = region[:]
for y in range(height):
for x in range(width):
ch = region[(y * width) + x]
if ch == '>':
if region[(y * width) + ((x + 1) % width)] == '.':
new_region[(y * width) + x] = '.'
new_region[(y * width) + ((x + 1) % width)] = '>'
stepped = True
region = new_region
new_region = region[:]
for y in range(height):
for x in range(width):
ch = region[(y * width) + x]
if ch == 'v':
if region[((y + 1) % height) * width + x] == '.':
new_region[(y * width) + x] = '.'
new_region[((y + 1) % height) * width + x] = 'v'
stepped = True
steps += 1
if not stepped:
break
region = new_region
return steps
#ex1 = read("example1.txt")
#find_standstill(ex1, True, lambda _: True, max_steps=4)
ex2 = read("example2.txt")
assert find_standstill(ex2, True, lambda x: x in [0, 1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 55, 56, 57, 58, 59], 60) == 58
inp = read("input.txt")
answer = find_standstill(inp)
print("Part 1 =", answer)
assert answer == 456 # check with accepted answer
|
# This sample tests the "reportPrivateUsage" feature.
class _TestClass(object):
pass
class TestClass(object):
def __init__(self):
self._priv1 = 1
|
# Copyright (c) 2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def ok():
res = """<?xml version="1.0" encoding="ISO-8859-1"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:if="http://www.cisco.com/nxos:1.0:if_manager"
xmlns:nxos="http://www.cisco.com/nxos:1.0"
message-id="urn:uuid:e7ef8254-10a6-11e4-b86d-becafe000bed">
<data/>
</rpc-reply>"""
return res
def show_dhcp(port):
dhcp = ("ip source binding 10.0.0.1 FFFF.FFFF.FFFF.FFFF "
"vlan 1 interface port-channel%s") % (port)
res = """<?xml version="1.0" encoding="ISO-8859-1"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:if="http://www.cisco.com/nxos:1.0:if_manager"
xmlns:nxos="http://www.cisco.com/nxos:1.0"
message-id="urn:uuid:4a9be8b4-df85-11e3-ab20-becafe000bed">
<data>
!Command: show running-config dhcp | egrep port-channel%(port)s$
!Time: Mon May 19 18:40:08 2014
version 6.0(2)U2(4)
interface port-channel%(port)s
%(dhcp)s
</data>
</rpc-reply>"""
return res % ({'port': port,
'dhcp': dhcp})
def show_port_channel_config_trunked(port):
res = """<?xml version="1.0" encoding="ISO-8859-1"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:if="http://www.cisco.com/nxos:1.0:if_manager"
xmlns:nxos="http://www.cisco.com/nxos:1.0"
message-id="urn:uuid:4a9be8b4-df85-11e3-ab20-becafe000bed">
<data>
!Command: show running-config interface port-channel%(port)s
!Time: Mon May 19 18:40:08 2014
version 6.0(2)U2(4)
interface port-channel%(port)s
description CUST39a8365c-3b84-4169-bc1a-1efa3ab20e04-host
switchport mode trunk
switchport trunk allowed vlan 1,2
ip verify source dhcp-snooping-vlan
spanning-tree port type edge trunk
no negotiate auto
vpc %(port)s
</data>
</rpc-reply>"""
return res % ({'port': port})
def show_ethernet_config_trunked(port):
res = """<?xml version="1.0" encoding="ISO-8859-1"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:if="http://www.cisco.com/nxos:1.0:if_manager"
xmlns:nxos="http://www.cisco.com/nxos:1.0"
message-id="urn:uuid:4a9be8b4-df85-11e3-ab20-becafe000bed">
<data>
!Command: show running-config interface Ethernet1/%(port)s
!Time: Mon May 19 18:40:08 2014
version 6.0(2)U2(4)
interface Ethernet1/%(port)s
description CUST39a8365c-3b84-4169-bc1a-1efa3ab20e04-host
no lldp transmit
switchport mode trunk
switchport trunk allowed vlan 1,2
spanning-tree port type edge trunk
spanning-tree bpduguard enable
channel-group %(port)s mode active
</data>
</rpc-reply>"""
return res % ({'port': port})
def show_ethernet_config_access(port):
res = """<?xml version="1.0" encoding="ISO-8859-1"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:if="http://www.cisco.com/nxos:1.0:if_manager"
xmlns:nxos="http://www.cisco.com/nxos:1.0"
message-id="urn:uuid:4a9be8b4-df85-11e3-ab20-becafe000bed">
<data>
!Command: show running-config interface Ethernet1/%(port)s
!Time: Mon May 19 18:40:08 2014
version 6.0(2)U2(4)
interface Ethernet1/%(port)s
description CUST32fdc565-7860-47b9-be57-f5d5ee1875a0-host
switchport access vlan 3
spanning-tree port type edge
spanning-tree bpduguard enable
</data>
</rpc-reply>"""
return res % ({'port': port})
def show_port_channel_status(port):
status = "vPC Status: Up, vPC number: %s" % (port)
res = """<?xml version="1.0" encoding="ISO-8859-1"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:if="http://www.cisco.com/nxos:1.0:if_manager"
xmlns:nxos="http://www.cisco.com/nxos:1.0"
message-id="urn:uuid:c87305ee-0d19-11e4-ab20-becafe000bed">
<data>
<show>
<interface>
<__XML__INTF_ifeth>
<__XML__PARAM_value>
<__XML__INTF_output>port-channel%(port)s</__XML__INTF_output>
</__XML__PARAM_value>
<__XML__OPT_Cmd_show_interface_if_eth___readonly__>
<__readonly__>
<TABLE_interface>
<ROW_interface>
<interface>port-channel%(port)s</interface>
<state>up</state>
<vpc_status>%(status)s</vpc_status>
</ROW_interface>
</TABLE_interface>
</__readonly__>
</__XML__OPT_Cmd_show_interface_if_eth___readonly__>
</__XML__INTF_ifeth>
</interface>
</show>
</data>
</rpc-reply>"""
return res % ({'port': port,
'status': status})
def show_ethernet_status(port):
res = """<?xml version="1.0" encoding="ISO-8859-1"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:if="http://www.cisco.com/nxos:1.0:if_manager"
xmlns:nxos="http://www.cisco.com/nxos:1.0"
message-id="urn:uuid:c87305ee-0d19-11e4-ab20-becafe000bed">
<data>
<show>
<interface>
<__XML__INTF_ifeth>
<__XML__PARAM_value>
<__XML__INTF_output>ethernet1/%(port)s</__XML__INTF_output>
</__XML__PARAM_value>
<__XML__OPT_Cmd_show_interface_if_eth___readonly__>
<__readonly__>
<TABLE_interface>
<ROW_interface>
<interface>ethernet1/%(port)s</interface>
<state>up</state>
</ROW_interface>
</TABLE_interface>
</__readonly__>
</__XML__OPT_Cmd_show_interface_if_eth___readonly__>
</__XML__INTF_ifeth>
</interface>
</show>
</data>
</rpc-reply>"""
return res % ({'port': port})
|
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
'''
min_list = []
for i in range(len(nums)):
count = 0
for j in range(len(nums)):
if nums[j] < nums[i]:
count = count + 1
min_list.append(count)
return min_list
'''
min_list = sorted(nums)
# index method returns the first match of i
return [min_list.index(i) for i in nums]
|
#calculadora 2.0v
n = int(input('Informe a tabuada que vc quer: '))
for x in range(1,11):
print(' {} x {:2} = {}'.format(n, x, n*x))
#(número da tabuada, laço 1-10, e a multiplicação)
|
# 立方
cube = [v**3 for v in range(1, 11)]
print(cube)
|
# def parse_ranges(input_string):
#
# output = []
# ranges = [item.strip() for item in input_string.split(',')]
#
# for item in ranges:
# start, end = [int(i) for i in item.split('-')]
# output.extend(range(start, end + 1))
#
# return output
# def parse_ranges(input_string):
#
# ranges = [item.strip() for item in input_string.split(',')]
#
# for item in ranges:
# start, end = [int(i) for i in item.split('-')]
# yield from range(start, end + 1)
# def parse_ranges(input_string):
#
# ranges = [range_.strip() for range_ in input_string.split(',')]
#
# for item in ranges:
# if '-' in item:
# start, end = [int(i) for i in item.split('-')]
# yield from range(start, end + 1)
# else:
# yield int(item)
def parse_ranges(input_string):
ranges = [range_.strip() for range_ in input_string.split(',')]
for item in ranges:
if '->' in item:
yield int(item.split('-')[0])
elif '-' in item:
start, end = [int(i) for i in item.split('-')]
yield from range(start, end + 1)
else:
yield int(item)
|
"""
The question is incorrect as it says you can only travserse an open path once but
uses the same path repeatedly, violating its own rules
"""
def uniquePathsIII(grid: list[list[int]]) -> int:
if not grid or not grid[0]:
return 0
index = dict()
for r in range(rows := len(grid)):
for c in range(cols := len(grid[0])):
if not (v := grid[r][c]):
grid[r][c] = 3
elif v == 2 or v == 1:
index[v] = (r, c)
def coords(r, c):
yield r+1, c
yield r-1, c
yield r, c+1
yield r, c-1
paths = float('inf')
for row, col in index.values():
paths = min(paths,
*sum((1 for r, c in coords(row, col)
if (0 <= r < rows and 0 <= c < cols) and grid[r][c] == 3)))
return paths
|
for row in range(4):
for col in range(4):
if col%3==0 and row<3 or row==3 and col>0:
print('*', end = ' ')
else:
print(' ', end = ' ')
print()
|
def power(integer1, integer2=3):
result = 1
for i in range(integer2):
result = result * integer1
return result
print(power(3))
print(power(3,2)) |
#The values G,m1,m2,f and d stands for Gravitational constant, initial mass,final mass,force and distance respectively
G = 6.67 * 10 ** -11
m1 = float(input("The value of the initial mass: "))
m2 = float(input("The value of the final mass: "))
d = float(input("The distance between the bodies: "))
F = (G * m1 * m2)/(d ** 2)
print("The magnitude of the attractive force: " ,F) |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
s = [ ]
j = 0
ans = 0
for i in range ( n ) :
while ( j < n and ( arr [ j ] not in s ) ) :
s.append ( arr [ j ] )
j += 1
ans += ( ( j - i ) * ( j - i + 1 ) ) // 2
s.remove ( arr [ i ] )
return ans
#TOFILL
if __name__ == '__main__':
param = [
([3, 4, 5, 6, 12, 15, 16, 17, 20, 20, 22, 24, 24, 27, 28, 34, 37, 39, 39, 41, 43, 49, 49, 51, 55, 62, 63, 67, 71, 74, 74, 74, 77, 84, 84, 89, 89, 97, 99],24,),
([-8, 54, -22, 18, 20, 44, 0, 54, 90, -4, 4, 40, -74, -16],13,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],28,),
([36, 71, 36, 58, 38, 90, 17],4,),
([-90, -32, -16, 18, 38, 82],5,),
([1, 0, 1],2,),
([3, 11, 21, 25, 28, 28, 38, 42, 48, 53, 55, 55, 55, 58, 71, 75, 79, 80, 80, 94, 96, 99],20,),
([-16, -52, -4, -46, 54, 0, 8, -64, -82, -10, -62, -10, 58, 44, -28, 86, -24, 16, 44, 22, -28, -42, -52, 8, 76, -44, -34, 2, 88, -88, -14, -84, -36, -68, 76, 20, 20, -50],35,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],27,),
([19, 13, 61, 32, 92, 90, 12, 81, 52],5,)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) |
var1 = 6
var2 = 3
if var1 >= 10:
print("Bigger than 10") #mind about the indent here (can be created by pressing tab button)
else:
print("Smaller or equal to 10") # all the codes written under a section wth tab belongs to that section
if var1 == var2:
print("var1 and 2 are equal")
else:
print("not equal")
if var1 > 5 and var1 < 7:
print("Between")
elif var1 <= 5:
print("Smaller than 5")
else:
print("Bigger than or equal to 7")
if var1 > 5:
if var2 < 5:
print("in good condition")
else:
print("var2 breaks the condition")
else:
print("var1 breaks the condition") |
class KNN():
def fit(self, X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def predict(self, X_test, k=3):
predictions = np.zeros(X_test.shape[0])
for i, point in enumerate(X_test):
distances = self._get_distances(point)
k_nearest = self._get_k_nearest(distances, k)
prediction = self._get_predicted_value(k_nearest)
predictions[i] = prediction
return predictions
#helper functions
def _get_distances(self, x):
'''Take an single point and return an array of distances to every point in our dataset'''
distances = np.zeros(self.X_train.shape[0])
for i, point in enumerate(self.X_train):
distances[i] = euc(x, point)
return distances
def _get_k_nearest(self, distances, k):
'''Take in the an array of distances and return the indices of the k nearest points'''
nearest = np.argsort(distances)[:k]
return nearest
def _get_predicted_value(self, k_nearest):
'''Takes in the indices of the k nearest points and returns the mean of their target values'''
return np.mean(self.y_train[k_nearest]) |
__author__ = [
"Alexander Dunn <[email protected]>",
"Alireza Faghaninia <[email protected]>",
]
class BaseDataRetrieval:
"""
Abstract class to retrieve data from various material APIs while adhering to
a quasi-standard format for querying.
## Implementing a new DataRetrieval class
If you have an API which you'd like to incorporate into matminer's data
retrieval tools, using BaseDataRetrieval is the preferred way of doing so.
All DataRetrieval classes should subclass BaseDataRetrieval and implement
the following:
* get_dataframe()
* api_link()
Retrieving data should be done by the user with get_dataframe. Criteria
should be a dictionary which will be used to form a query to the database.
Properties should be a list which defines the columns that will be returned.
While the 'criteria' and 'properties' arguments may have different valid
values depending on the database, they should always have sensible formats
and names if possible. For example, the user should be calling this:
df = MyDataRetrieval().get_dataframe(criteria={'band_gap': 0.0},
properties=['structure'])
...or this:
df = MyDataRetrieval().get_dataframe(criteria={'band_gap': [0.0, 0.15]},
properties=["density of states"])
NOT this:
df = MyDataRetrieval().get_dataframe(criteria={'query.bg[0] && band_gap': 0.0},
properties=['Struct.page[Value]'])
The implemented DataRetrieval class should handle the conversion from a
'sensible' query to a query fit for the individual API and database.
There may be cases where a 'sensible' query is not sufficient to define a
query to the API; in this case, use the get_dataframe kwargs sparingly to
augment the criteria, properties, or form of the underlying API query.
A method for accessing raw DB data with an API-native query *may* be
provided by overriding get_data. The link to the original API documentation
*must* be provided by overriding api_link().
## Documenting a DataRetrieval class
The class documentation for each DataRetrieval class must contain a brief
description of the possible data that can be retrieved with the API source.
It should also detail the form of the criteria and properties that can be
retrieved with the class, and/or should link to a web page showing this
information. The options of the class must all be defined in the `__init__`
function of the class, and we recommend documenting them using the
[Google style](https://google.github.io/styleguide/pyguide.html).
"""
def api_link(self):
"""
The link to comprehensive API documentation or data source.
Returns:
(str): A link to the API documentation for this DataRetrieval class.
"""
raise NotImplementedError("api_link() is not defined!")
def get_dataframe(self, criteria, properties, **kwargs):
"""
Retrieve a dataframe of properties from the database which satisfy
criteria.
Args:
criteria (dict): The name of each criterion is the key; the value
or range of the criterion is the value.
properties (list): Properties to return from the query matching
the criteria. For example, ['structure', 'formula']
Returns:
(pandas DataFrame) The dataframe containing properties as columns
and samples as rows.
"""
raise NotImplementedError("get_dataframe() is not defined!")
|
# -*- coding: utf-8 -*-
class Empty(object):
"""
Empty object represents emptyness state in `grappa`.
"""
def __repr__(self):
return 'Empty'
def __len__(self):
return 0
# Object reference representing emptpyness
empty = Empty()
|
__title__ = 'alpha-vantage-py'
__description__ = 'Alpha Vantage Python package.'
__url__ = 'https://github.com/wstolk/alpha-vantage'
__version__ = '0.0.4'
__build__ = 0x022501
__author__ = 'Wouter Stolk'
__author_email__ = '[email protected]'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2021 Wouter Stolk'
__cake__ = u'\u2728 \U0001f370 \u2728' |
LANGUAGES = [
{"English": "English", "alpha2": "en"},
{"English": "Italian", "alpha2": "it"},
]
|
def max_profit(prices) -> int:
if not prices:
return 0
minPrice = prices[0]
maxPrice = 0
for i in range(1, len(prices)):
minPrice = min(prices[i], minPrice)
maxPrice = max(prices[i],maxPrice)
return maxPrice
arr = [100, 180, 260, 310, 40, 535, 695]
print(max_profit(arr)) |
# Paula Daly Solution to Problem 4 March 2019
# Collatz - particular sequence always reaches 1
# Defining the function
def collatz(number):
# looping through and if number found is even divide it by 2
if number % 2 == 0:
print(number // 2)
return number // 2
# looping through and if the number is odd multiply it by 3 and add 1
elif number % 2 != 0:
result = 3 * number + 1
print(result)
return result
try:
# ask the user to enter a number
n = input("Enter number: ")
# running the function
while n != 1:
n = collatz(int(n))
# what to do if the user inputs a negative integer
except ValueError:
print('Please enter a positive integer') |
"""
Reports: module definition
"""
PROPERTIES = {
'title': 'Reports',
'details': 'Create Reports',
'url': '/reports/',
'system': False,
'type': 'minor',
}
URL_PATTERNS = [
'^/reports/',
]
|
"""
Datos de entrada
Presupuesto-->p-->float
Datos de Salida
Presupuesto ginecologia-->g-->float
Presupuesto traumatologiaa-->t-->float
Presupuesto pediatria-->e-->float
"""
#entrada
p=float(input("Digite el presupuesto Total: "))
#caja negra
g=p*0.4
t=p*0.3
e=p*0.3
#salida
print("El presupuesto dedicado a ginecologia: ",g)
print("El presupuesto dedicado a traumatologia: ",t)
print("El presupuesto dedicado a pediatria: ",e) |
#Przygotować skrypt, w którym użytkownik będzie wprowadzał do listy wartości używając pętli, a następnie wartości z tej zostanią zrzutowane do krotki.
lista=[]
for i in range(5):
liczba=int(input())
lista.append(liczba)
print(lista)
print(tuple(lista)) |
class ConfigBase:
def __init__(self):
self.zookeeper = ""
self.brokers = ""
self.topic = ""
def __str__(self):
return str(self.zookeeper + ";" + self.brokers + ";" + self.topic)
def set_zookeeper(self, conf):
self.zookeeper = conf
def set_brokers(self, conf):
self.brokers = conf
def set_topic(self, conf):
self.topic = conf
|
'''
Created on May 13, 2016
@author: david
'''
if __name__ == '__main__':
pass
|
# numbers_list = [int(x) for x in input().split(", ")]
def find_sum(numbers_list):
result = 1
for i in range(len(numbers_list)):
number = numbers_list[i]
if number <= 5:
result *= number
elif number <= 10:
result /= number
return result
print(find_sum([1, 4, 5]), 20)
print(find_sum([4, 5, 6, 1, 3]), 20)
print(find_sum([2, 5, 10]), 20)
|
# post to the array-connections/connection-key endpoint to get a connection key
res = client.post_array_connections_connection_key()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
|
BOT_CONFIG = 'default'
CONFIGS_DIR_NAME = 'configs'
BOTS_LOG_ROOT = 'bots'
LOG_FILE = 'bots.log'
LOOP_INTERVAL = 60
SETTINGS = 'settings.yml,secrets.yml'
VERBOSITY = 1
|
""" Problem Statement (Digit Fifth Power ): https://projecteuler.net/problem=30
Surprisingly there are only three numbers that can be written as the sum of fourth
powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their
digits.
(9^5)=59,049
59049*7=4,13,343 (which is only 6 digit number )
So, number greater than 9,99,999 are rejected
and also 59049*3=1,77,147 (which exceeds the criteria of number being 3 digit)
So, n>999
and hence a bound between (1000,1000000)
"""
def digitsum(s: str) -> int:
"""
>>> all(digitsum(str(i)) == (1 if i == 1 else 0) for i in range(100))
True
"""
i = sum(pow(int(c), 5) for c in s)
return i if i == int(s) else 0
def solution() -> int:
return sum(digitsum(str(i)) for i in range(1000, 1000000))
if __name__ == "__main__":
print(solution())
|
class BotLogic:
def BotExit(Nachricht):
print("Say Goodbye to the Bot")
# Beim Bot abmelden
def BotStart(Nachricht):
print("Say Hello to the Bot")
# Beim Bot anmelden |
"""
1. Clarification
2. Possible solutions
- Python built-in
- Hand-crafted
- Deque
3. Coding
4. Tests
"""
# # T=O(n), S=O(n)
# class Solution:
# def reverseWords(self, s: str) -> str:
# if not s: return ''
# return ' '.join(reversed(s.split()))
# T=O(n), S=O(n) in python or O(1) in c++
class Solution:
def reverseWords(self, s: str) -> str:
if not s: return ''
l = self.trim_spaces(s)
self.reverse(l, 0, len(l) - 1)
self.reverse_each_word(l)
return ''.join(l)
def trim_spaces(self, s: str) -> list:
left, right = 0, len(s) - 1
while left <= right and s[left] == ' ':
left += 1
while left <= right and s[right] == ' ':
right -= 1
output = []
while left <= right:
if s[left] != ' ':
output.append(s[left])
elif output[-1] != ' ':
output.append(s[left])
left += 1
return output
def reverse(self, l: list, left: int, right: int) -> None:
while left < right:
l[left], l[right] = l[right], l[left]
left, right = left + 1, right - 1
def reverse_each_word(self, l: list) -> None:
n = len(l)
start = end = 0
while start < n:
while end < n and l[end] != ' ':
end += 1
self.reverse(l, start, end - 1)
start = end + 1
end += 1
# T=O(n), S=O(n)
class Solution:
def reverseWords(self, s: str) -> str:
if not s: return ''
left, right = 0, len(s) - 1
while left <= right and s[left] == ' ':
left += 1
while left <= right and s[right] == ' ':
right -= 1
d, word = collections.deque(), []
while left <= right:
if s[left] == ' ' and word:
d.appendleft(''.join(word))
word = []
elif s[left] != ' ':
word.append(s[left])
left += 1
d.appendleft(''.join(word))
return ' '.join(d)
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 10:22:45 2019
@author: Lee
"""
__version_info__ = (0, 3, 10)
__version__ = '.',join(map(str,__version_info__[:3]))
if len(__version_info__) == 4:
__version__+=__version_info[-1]
|
# class => module
MODULE_MAP = {
'ShuffleRerankPlugin': 'plugins.rerank.shuffle',
'PtTransformersRerankPlugin': 'plugins.rerank.transformers',
'PtDistilBertQAModelPlugin': 'plugins.qa.distilbert'
}
# image => directory
IMAGE_MAP = {
'alpine': '../Dockerfiles/alpine',
'pt': '../Dockerfiles/pt'
}
INDEXER_MAP = {
'ESIndexer': 'indexers.es'
}
|
# https://leetcode.com/problems/burst-balloons/
#
# algorithms
# Hard (46.16%)
# Total Accepted: 56,690
# Total Submissions: 122,812
# 这道题是一道 dp 的题目,dp[i][j] 代表下标位 i,j 之间范围内 sum 最大的值
class Solution(object):
def maxCoins(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = [1] + nums + [1]
length = len(nums)
dp = [[0] * length for _ in xrange(length)]
for j in xrange(2, length):
for i in xrange(j - 2, -1, -1):
for k in xrange(i + 1, j):
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k]
[j] + nums[i] * nums[k] * nums[j])
return dp[0][-1]
|
'''
This file was used in an earlier version; geodata does not currently use
SQLAlchemy.
---
This file ensures all other files use the same SQLAlchemy session and Base.
Other files should import engine, session, and Base when needed. Use:
from initialize_sqlalchemy import Base, session, engine
'''
# # The engine
# from sqlalchemy import create_engine
# engine = create_engine('sqlite:///:memory:')
# # The session
# from sqlalchemy.orm import sessionmaker
# Session = sessionmaker(bind=engine)
# session = Session()
# # The Base
# from sqlalchemy.ext.declarative import declarative_base
# Base = declarative_base()
|
#!/bin/python3
d1 = open("isimler1.txt")
d1_satırlar = d1.readlines()
d2 = open("isimler1.txt")
d2_satırlar = d2.readlines()
for i in d2_satırlar:
if i in d1_satırlar:
print(i)
d1.close()
d2.close()
|
# Copyright 2021 IBM All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Constants for unstructured text
The ACD and QuickUMLS NLP services' output for these text strings must
be included in resources/acd/TestReportResponses.json and
resources/quickUmls/TestReportResponses.json
"""
TEXT_FOR_MULTIPLE_CONDITIONS = (
"Patient reports that they recently had pneumonia "
+ "and is now having chest pain. "
+ "The patient was diagnosed with a myocardial infarction."
)
TEXT_FOR_MEDICATION = "Patient is taking Cisplatin."
TEXT_FOR_CONDITION_AND_MEDICATION = (
""
+ "Patient had pneumonia a month ago and has now been diagnosed with "
+ "a myocardial infarction. Prescribed Acebutolol."
)
TEXT_FOR_CONDITION_SUSPECTED_AND_FAM_HISTORY = (
"suspect skin cancer because the patient's brother has skin cancer"
)
TEXT_FOR_ADVERSE_EVENT = (
"The patient's course was also complicated by mental status changes secondary "
+ "to a combination of his narcotics and Neurontin, which had been given for his "
+ "trigeminal neuralgia and chronic pain. The Neurontin was stopped and he "
+ "received hemodialysis on consecutive days."
)
# Important thing with this text is that there are multiple spans over the same
# condition and medication
# With the condition, "myocardial infarction" == "heart attack"
TEXT_FOR_MULTIPLE_ATTRIBUTES_SAME_RESOURCE = (
"The patient had a myocardial infarction in 2015 and was prescribed Losartan. "
+ "His prescription was changed to Irbesartan in 2019. "
+ "He had a second heart attack in 2021, and is now taking Losartan again."
)
|
# The authors of this work have released all rights to it and placed it
# in the public domain under the Creative Commons CC0 1.0 waiver
# (http://creativecommons.org/publicdomain/zero/1.0/).
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Retrieved from: http://en.literateprograms.org/Generating_all_integer_lattice_points_(Python)?oldid=17065
# Modified for VLC project
'''Code for creating mappings that are used to place symbols in the matrix.'''
def _distance(p):
return p[0]**2 + p[1]**2
def _may_use(vu, shape):
'''Returns true if the entry v, u may be used in a conjugate symmetric matrix.
In other words, the function returns false for v, u pairs that must be
their own conjugate. These pairs cannot be used to store complex symbols.
`shape` is the shape of the matrix into which the symbols are packed.
'''
n, m = shape
m = (m/2) + 1
v, u = vu
if v < 0:
v = n+v
# May not use DC component
if u == 0 and v == 0:
return False
# May not use lower half of 0 colument
max_v_u0 = n/2 if n % 2 == 1 else n/2-1
if u == 0 and v > max_v_u0:
return False
# Perform some additional bounds checking here.
# Raise an exception if the check fails, as it is
# a programming error.
max_u = m-1 if shape[1] % 2 == 1 else m-2
if u > max_u:
raise IndexError('Mapping tries to set illegal entry. '
'(Are you trying to pack too many symbols?)')
return True
def halfring_generator(shape, limit=None):
'''Generates a sequence of (v,u) tuples that describe a halfring.'''
# TODO Bounds checking for the shape
ymax = [0]
d = 0
while limit is None or d <= limit:
yieldable = []
while 1:
batch = []
for x in range(d+1):
y = ymax[x]
if _distance((x, y)) <= d**2: # Note: distance squared
batch.append((y, x))
if y != 0:
batch.append((-y, x))
ymax[x] += 1
if not batch:
break
yieldable += batch
yieldable.sort(key=_distance)
for p in yieldable:
if _may_use(p, shape):
yield p
d += 1
ymax.append(0) # Extend to make room for column[d]
def halfring(n, shape):
'''Returns a list (v,u) tuples that describe a halfring.'''
g = halfring_generator(shape)
return [next(g) for _ in xrange(n)]
|
tup1=(10,20,30)
tup2=(5,8,8,9,8,9)
tup3=tup1+tup2
print(tup3)
del tup1 #删除整个元祖对象,删除后不能再调用
print(tup3[::-1]) #分片翻转元祖
print(tup2.count(8)) #统计元祖中8出现的次数
print(tup2.index(8)) #返回第一个8出现的索引位置
print(tup2.index(8,3)) #可以指定区间找出8第一次出现的位置
for x in tup3:
print(x)
#多层元祖
tup4=(1,5,(2,8),9)
for x in tup4:
print(x)
print(5 in tup2) # 判断5是否存在元祖中
print(5 not in tup2) # 判断5是否不存在元祖中
print(8 in tup4[2]) #判断8是否在元祖中的宁一个元祖中
#元祖中没有添加和删除元素的方法
#所以只能通过元祖拼接的形式实现该功能
tup5=("aa","bb")
tup5=tup5 + ("cc",) #通过拼接添加元祖内容
print(tup5)
tup5= tup5[0] + ("BB") #修改第二个元素的内容
print(tup5)
|
class EntityForm(django.forms.ModelForm):
class Meta:
model = Entity
exclude = (u'homepage', u'image')
|
WHAT_IS_PAIRS = [
{
# [3]
"query": "What is villa la reine jeanne all about?",
"result": """
statement: {
target phrase: what,
action: {
neg: None,
verb: {
aux_vbs: [is],
main_vb: None,
modal_vb: None
},
acomp_list: []
},
related phrase: villa la reine jeanne
}
"""
}
]
WHEN_PAIRS = [
{
# [3]
"query": "When was anıtkabir built?",
"result": """
statement: {
target phrase: when,
action: {
neg: None,
verb: {
aux_vbs: [was],
main_vb: built,
modal_vb: None
},
acomp_list: []
},
related phrase: anıtkabir
}
"""
}
]
PAIRS_03 = WHAT_IS_PAIRS + \
WHEN_PAIRS
|
'''
Simpler to just do the math than iterating. Break each number from 1 to 20 into its prime components.
The find the maximum times each unique prime occurs in any of the numbers.
Include the prime that number of times.
For instance, 9 is ( 3 * 3 ) and 18 is ( 3 * 3 * 2 ), both of which are the most
number of times 3 shows up.
So include 3 twice. Cheaper to do so using 9 since we already get a 2 from other numbers.
This works since primes can be recombined to form any of the numbers, but you need
to have enough of the primes to actually do so. You can use 5 and 2 to make 10, but
you need to include another 2 to make 20, for instance.
'''
print(16 * 17 * 5 * 13 * 9 * 11 * 19 * 7) # 232792560
# print(
# (2 * 2 * 2 * 2) * (17) * (5) * (13) * (3 * 3) * (11) * (19) * (7)
# ) |
"""
Mixin for returning the intersected frames.
"""
class IntersectedFramesMixin:
"""
Mixin for returning the intersected frames.
"""
def __init__(self):
self.intersected_frames = []
|
n, k = map(int, input().split())
arr = list(map(int, input().split()))
arr_find = list(map(int, input().split()))
def bin_search(arr, el):
left = -1
right = len(arr)
while right - left > 1:
mid = (right + left) // 2
if arr[mid] >= el:
right = mid
else:
left = mid
return left, right
for el in arr_find:
left, right = bin_search(arr, el)
print(left, right)
if arr[left] == el:
print('YES')
else:
print('NO')
|
def default_getter(attribute=None):
"""a default method for missing renderer method
for example, the support to write data in a specific file type
is missing but the support to read data exists
"""
def none_presenter(_, **__):
"""docstring is assigned a few lines down the line"""
raise NotImplementedError("%s getter is not defined." % attribute)
none_presenter.__doc__ = "%s getter is not defined." % attribute
return none_presenter
def default_setter(attribute=None):
"""a default method for missing parser method
for example, the support to read data in a specific file type
is missing but the support to write data exists
"""
def none_importer(_x, _y, **_z):
"""docstring is assigned a few lines down the line"""
raise NotImplementedError("%s setter is not defined." % attribute)
none_importer.__doc__ = "%s setter is not defined." % attribute
return none_importer
def make_a_property(
cls,
attribute,
doc_string,
getter_func=default_getter,
setter_func=default_setter,
):
"""
create custom attributes for each class
"""
getter = getter_func(attribute)
setter = setter_func(attribute)
attribute_property = property(
# note:
# without fget, fset, pypy 5.4.0 crashes randomly.
fget=getter,
fset=setter,
doc=doc_string,
)
if "." in attribute:
attribute = attribute.replace(".", "_")
else:
attribute = attribute
setattr(cls, attribute, attribute_property)
setattr(cls, "get_%s" % attribute, getter)
setattr(cls, "set_%s" % attribute, setter)
|
"""Calculate Net:Gross estimates"""
def calculate_deep_net_gross_model(model, composition):
"""Calculate a net gross estimate based on the given deep composition"""
net_gross = model.assign(
bb_pct=lambda df: df.apply(
lambda row: composition["building_block_type"][row.building_block_type],
axis="columns",
),
cls_ratio=1.0,
)
for building_block_type in ("Channel Fill", "Lobe"):
for filter_class, weights in composition.get(building_block_type, {}).items():
ignores = [v for k, v in weights.items() if k.startswith("Ignore ")]
if ignores and ignores[0]:
idx = net_gross.query(
"building_block_type == @building_block_type"
).index
num_values = len(
[v for v in net_gross.loc[idx, filter_class].unique() if v]
)
net_gross.loc[idx, "cls_ratio"] /= num_values
else:
for value in (
net_gross.query("building_block_type == @building_block_type")
.loc[:, filter_class]
.unique()
):
idx = net_gross.query(
"building_block_type == @building_block_type and "
f"{filter_class} == @value"
).index
net_gross.loc[idx, "cls_ratio"] *= weights.get(value, 0) / 100
return net_gross.assign(
result=lambda df: df.loc[:, ["net_gross", "bb_pct", "cls_ratio"]].prod(
axis="columns"
)
)
def calculate_deep_net_gross(model, composition):
"""Calculate one net gross number"""
return (
calculate_deep_net_gross_model(model=model, composition=composition)
.loc[:, "result"]
.sum()
)
def calculate_shallow_net_gross_model(model, composition):
"""Calculate a net gross estimate based on the given shallow composition"""
net_gross = model.assign(
bb_pct=lambda df: df.apply(
lambda row: composition.get(row.building_block_type, 0)
if composition.get(f"{row.building_block_type} Quality")
== row.descriptive_reservoir_quality
else 0,
axis="columns",
),
)
return net_gross.assign(
result=lambda df: df.loc[:, ["net_gross", "bb_pct"]].prod(axis="columns")
)
def calculate_shallow_net_gross(model, composition):
"""Calculate one net gross number"""
return (
calculate_shallow_net_gross_model(model=model, composition=composition)
.loc[:, "result"]
.sum()
)
|
n = int(input())
current = 1
bigger = False
for i in range(1, n + 1):
for j in range(1, i + 1):
if current > n:
bigger = True
break
print(str(current) + " ", end="")
current += 1
if bigger:
break
print()
|
n = int(input())
d = list()
for i in range(2):
k=list(map(int,input().split()))
d.append(k)
c = list(zip(*d))
p = []
for i in range(len(c)):
p.append(c[i][0] * c[i][1])
number=sum(p)/sum(d[1])
print("{:.1f}".format(number)) |
# Scrapy settings for resource_library project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'resource_library'
SPIDER_MODULES = ['resource_library.spiders']
NEWSPIDER_MODULE = 'resource_library.spiders'
# scrapy-splash Url
# SPLASH_URL = 'http://localhost:8050'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# 保存图片地址
IMAGES_STORE = '/Volumes/Application/tucong'
# HTTPERROR_ALLOWED_CODES = [404]
# Configure maximum concurrent requests performed by Scrapy (default: 16)
# CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
# DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
# CONCURRENT_REQUESTS_PER_DOMAIN = 16
# CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
# COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
# TELNETCONSOLE_ENABLED = False
# Override the default request headers:
# DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
# 'Accept-Encoding': 'gzip, deflate, sdch',
# 'Accept-Language': 'en-US,en;q=0.8',
# 'Cache-Control': 'max-age=0',
# 'Host': 'img1.mm131.me',
# 'If-Modified-Since': 'Mon, 15 Jan 2018 02:18:26 GMT',
# 'If-None-Match': '"5a6ead54-5335"',
# 'Proxy-Connection': 'keep-alive',
# 'Referer': 'http://www.mm131.com/xinggan/',
# 'Upgrade-Insecure-Requests': 1,
# 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36',
# }
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
# Set a custom DUPEFILTER_CLASS:
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
# EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
# }
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'resource_library.pipelines.ImageSpiderPipeline': 500,
'resource_library.pipelines.MyImagesPipeline': 400,
# 'resource_library.pipelines.FreePsdPipeline': 500,
# 'resource_library.pipelines.jdBookWebPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
# AUTOTHROTTLE_ENABLED = True
# The initial download delay
# AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
# AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
# AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
# AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
# HTTPCACHE_ENABLED = True
# HTTPCACHE_EXPIRATION_SECS = 0
# HTTPCACHE_DIR = 'httpcache'
# HTTPCACHE_IGNORE_HTTP_CODES = []
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
|
queries = {
"column": {
"head": "select top %d %s from %s;",
"all": "select %s from %s;",
"unique": "select distinct %s from %s;",
"sample": "select top %d %s from %s order by rand();"
},
"table": {
"select": "select %s from %s;",
"head": "select top %d * from %s;",
"all": "select * from %s;",
"unique": "select distinct %s from %s;",
"sample": "select top %d * from %s order by rand();"
},
"system": {
"schema_no_system": """
select
table_name
, column_name
, data_type
from
information_schema.columns
where
table_schema not in ('information_schema', 'sys')
""",
"schema_with_system": """
select
table_name
, column_name
, data_type
from
information_schema.columns;
""",
"schema_specified": """
select
table_name
, column_name
, data_type
from
information_schema.columns
where table_schema in (%s);
""",
"foreign_keys_for_table": """
SELECT
object_name(constraint_object_id) AS foreign_key,
object_name(referenced_object_id) AS referenced_table,
col.name AS referenced_column
FROM sys.foreign_key_columns
INNER JOIN sys.columns col
ON col.column_id = referenced_column_id
AND col.object_id = referenced_object_id
WHERE parent_object_id = object_id('%s');
""",
"foreign_keys_for_column": """
SELECT
object_name(constraint_object_id) AS foreign_key,
object_name(referenced_object_id) AS referenced_table,
col.name AS referenced_column
FROM sys.foreign_key_columns
INNER JOIN sys.columns col
ON col.column_id = referenced_column_id
AND col.object_id = referenced_object_id
WHERE parent_object_id = object_id('%s')
AND constraint_object_id = object_id('%s');
""",
"ref_keys_for_table": """
SELECT
dc.Name AS constraint_column,
t.Name AS referenced_table,
c.Name AS referenced_column
FROM sys.tables t
INNER JOIN sys.default_constraints dc
ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c
ON dc.parent_object_id = c.object_id
AND c.column_id = dc.parent_column_id
WHERE t.name='%s';
"""
}
}
|
'''
完全平方数
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
给你一个整数 n ,返回和为 n 的完全平方数的 最少数量 。
完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。
例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。
示例 1:
输入:n = 12
输出:3
解释:12 = 4 + 4 + 4
示例 2:
输入:n = 13
输出:2
解释:13 = 4 + 9
提示:
1 <= n <= 10^4
'''
'''
思路:动态规划 背包问题
用背包问题的思路解决,将n设置为背包大小
时间复杂度:O(n*sqrt(n))
空间复杂度:O(n)
'''
class Solution:
def numSquares(self, n: int) -> int:
dp = [n] * (n + 1) # 最坏情况下由n个1构成
dp[0] = 0
dp[1] = 1
if n > 1:
dp[2] = 2
if n > 2:
dp[3] = 3
for i in range(2, int(n**0.5) + 1):
square = i * i
for j in range(square, n + 1):
dp[j] = min(dp[j], dp[j - square] + 1)
return dp[n]
s = Solution()
print(s.numSquares(6))
print(s.numSquares(12))
print(s.numSquares(13))
|
def reader():
with open('day3/puzzle_input.txt', 'r') as f:
return f.read().splitlines()
def tree(right, down):
count = 0
index = 0
lines = reader()
for i in range(0, len(lines), down):
line = lines[i]
if line[index] == '#':
count += 1
remainder = len(line) - index - 1
index = (
index + right if remainder > right - 1 else right - 1 - remainder
)
return count
multiply = 1
for right, down in ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2)):
multiply *= tree(right, down)
print(multiply)
|
class FPyCompare:
def __readFile(self, fileName):
with open(fileName) as f:
lines = f.read().splitlines()
return lines
def __writeFile(self, resultList, fileName):
with open(fileName, "w") as outfile:
outfile.write("\n".join(resultList))
print(fileName + " completed!")
def initializeList(self):
fileNameOne = input("First File Name: ")
self.listOne = set(self.__readFile(fileNameOne))
fileNameTwo = input("Second File Name: ")
self.listTwo = set(self.__readFile(fileNameTwo))
def interset(self, printResult=True):
intersect = list(self.listOne.intersection(self.listTwo))
print(intersect) if printResult else self.__writeFile(intersect, "result_intersect.txt")
def union(self, printResult=True):
union = list(self.listOne.union(self.listTwo))
print(union) if printResult else self.__writeFile(union, "result_union.txt")
def differenceListOne(self, printResult=True):
subtract = list(self.listOne.difference(self.listTwo))
print(subtract) if printResult else self.__writeFile(subtract, "result_DifferenceOne.txt")
def differenceListTwo(self, printResult=True):
subtract = list(self.listTwo.difference(self.listOne))
print(subtract) if printResult else self.__writeFile(subtract, "result_DifferenceTwo.txt")
fCompare = FPyCompare()
fCompare.initializeList()
fCompare.interset(False)
fCompare.union(False)
fCompare.differenceListOne(False)
fCompare.differenceListTwo(False)
|
print(() == ())
print(() > ())
print(() < ())
print(() == (1,))
print((1,) == ())
print(() > (1,))
print((1,) > ())
print(() < (1,))
print((1,) < ())
print(() >= (1,))
print((1,) >= ())
print(() <= (1,))
print((1,) <= ())
print((1,) == (1,))
print((1,) != (1,))
print((1,) == (2,))
print((1,) == (1, 0,))
print((1,) > (1,))
print((1,) > (2,))
print((2,) > (1,))
print((1, 0,) > (1,))
print((1, -1,) > (1,))
print((1,) > (1, 0,))
print((1,) > (1, -1,))
print((1,) < (1,))
print((2,) < (1,))
print((1,) < (2,))
print((1,) < (1, 0,))
print((1,) < (1, -1,))
print((1, 0,) < (1,))
print((1, -1,) < (1,))
print((1,) >= (1,))
print((1,) >= (2,))
print((2,) >= (1,))
print((1, 0,) >= (1,))
print((1, -1,) >= (1,))
print((1,) >= (1, 0,))
print((1,) >= (1, -1,))
print((1,) <= (1,))
print((2,) <= (1,))
print((1,) <= (2,))
print((1,) <= (1, 0,))
print((1,) <= (1, -1,))
print((1, 0,) <= (1,))
print((1, -1,) <= (1,))
print((10, 0) > (1, 1))
print((10, 0) < (1, 1))
print((0, 0, 10, 0) > (0, 0, 1, 1))
print((0, 0, 10, 0) < (0, 0, 1, 1))
|
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
'target_name': 'timed_decomposer_lib',
'type': 'static_library',
'sources': [
'timed_decomposer_app.cc',
'timed_decomposer_app.h',
],
'dependencies': [
'<(src)/syzygy/pe/pe.gyp:pe_lib',
'<(src)/syzygy/common/common.gyp:syzygy_version',
],
},
{
'target_name': 'timed_decomposer',
'type': 'executable',
'sources': [
'timed_decomposer_main.cc',
],
'dependencies': [
'timed_decomposer_lib',
],
'run_as': {
'action': [
'$(TargetPath)',
'--image=$(OutDir)\\test_dll.dll',
'--csv=$(OutDir)\\decomposition_times_for_test_dll.csv',
'--iterations=20',
],
},
},
],
}
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
dummy_head = sublist_head = ListNode(0,head)
for _ in range(1,left):
sublist_head=sublist_head.next
#Reversal
sublist_iter = sublist_head.next
for _ in range(right-left):
temp=sublist_iter.next
print(sublist_head)
sublist_iter.next , temp.next , sublist_head.next = temp.next , sublist_head.next , temp
print(sublist_head)
return dummy_head.next
|
# Height in cm --> feet and inches
# (just for ya fookin 'muricans)
cm = float(input("Enter height in cm: "))
inches = cm/2.54
ft = int(inches//12)
inches = int(round(inches % 12))
print("Height is about {}'{}\".".format(ft, inches))
|
# writing to a file :
# To write to a file you need to create file
stream = open('output.txt', 'wt')
print('\n Can I write to this file : ' + str(stream.writable()))
stream.write('H') # write a single string ...
stream.writelines(['ello',' ', 'Susan']) # write multiple strings
stream.write('\n') # write a new line
# You can pass for writelines a list of strings
names = ['Alen', 'Chris', 'Sausan']
# Here is how to write to a file using a list, and then you can use a neat feature so you can separate them using whatever you want using join
stream.writelines(','.join(names))
stream.writelines('\n'.join(names))
stream.close() # flush stream and close |
an_int = 2
a_float = 2.1
print(an_int + 3)
# prints 5
# Define the release and runtime integer variables below:
release_year = 15
runtime = 20
# Define the rating_out_of_10 float variable below:
rating_out_of_10 = 3.5 |
N = int(input())
s = [input() for _ in range(5)]
a = [
'.###..#..###.###.#.#.###.###.###.###.###.',
'.#.#.##....#...#.#.#.#...#.....#.#.#.#.#.',
'.#.#..#..###.###.###.###.###...#.###.###.',
'.#.#..#..#.....#...#...#.#.#...#.#.#...#.',
'.###.###.###.###...#.###.###...#.###.###.'
]
result = []
for i in range(N):
t = [s[j][i * 4:(i + 1) * 4] for j in range(5)]
for j in range(10):
for k in range(5):
if t[k] != a[k][j * 4:(j + 1) * 4]:
break
else:
result.append(j)
break
print(''.join(str(i) for i in result))
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 15:47:38 2020
@author: xyz
"""
a = 4
b = 5
c = 6
d = True
e = False
bool1 = (d + d) >= 2 and (not e)
bool2 = (not e) and (6*d == 12/2)
bool3 = (d or (e)) and (a > b)
print(bool1, bool2, bool3)
|
# -*- coding: utf-8 -*-
DESC = "iai-2018-03-01"
INFO = {
"DeletePersonFromGroup": {
"params": [
{
"name": "PersonId",
"desc": "人员ID"
},
{
"name": "GroupId",
"desc": "人员库ID"
}
],
"desc": "从某人员库中删除人员,此操作仅影响该人员库。若该人员仅存在于指定的人员库中,该人员将被删除,其所有的人脸信息也将被删除。"
},
"CreateGroup": {
"params": [
{
"name": "GroupName",
"desc": "人员库名称,[1,60]个字符,可修改,不可重复。"
},
{
"name": "GroupId",
"desc": "人员库 ID,不可修改,不可重复。支持英文、数字、-%@#&_,长度限制64B。"
},
{
"name": "GroupExDescriptions",
"desc": "人员库自定义描述字段,用于描述人员库中人员属性,该人员库下所有人员将拥有此描述字段。 \n最多可以创建5个。 \n每个自定义描述字段支持[1,30]个字符。 \n在同一人员库中自定义描述字段不可重复。 \n例: 设置某人员库“自定义描述字段”为[\"学号\",\"工号\",\"手机号\"], \n则该人员库下所有人员将拥有名为“学号”、“工号”、“手机号”的描述字段, \n可在对应人员描述字段中填写内容,登记该人员的学号、工号、手机号等信息。"
},
{
"name": "Tag",
"desc": "人员库信息备注,[0,40]个字符。"
}
],
"desc": "用于创建一个空的人员库,如果人员库已存在返回错误。可根据需要创建自定义描述字段,用于辅助描述该人员库下的人员信息。1个APPID下最多创建2万个人员库(Group)、最多包含1000万张人脸(Face),单个人员库(Group)最多包含100万张人脸(Face)。"
},
"GetPersonBaseInfo": {
"params": [
{
"name": "PersonId",
"desc": "人员ID"
}
],
"desc": "获取指定人员的信息,包括姓名、性别、人脸等。"
},
"DetectLiveFace": {
"params": [
{
"name": "Image",
"desc": "图片 base64 数据(图片的宽高比请接近3:4,不符合宽高比的图片返回的分值不具备参考意义)。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "Url",
"desc": "图片的 Url 。图片的 Url、Image必须提供一个,如果都提供,只使用 Url。 \n(图片的宽高比请接近 3:4,不符合宽高比的图片返回的分值不具备参考意义) \n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
}
],
"desc": "用于对用户上传的静态图片进行人脸活体检测。与动态活体检测的区别是:静态活体检测中,用户不需要通过唇语或摇头眨眼等动作来识别。\n\n静态活体检测适用于手机自拍的场景,或对防攻击要求不高的场景。如果对活体检测有更高安全性要求,请使用[人脸核身·云智慧眼](https://cloud.tencent.com/product/faceid)产品。\n\n> \n- 图片的宽高比请接近3:4,不符合宽高比的图片返回的分值不具备参考意义。本接口适用于类手机自拍场景,非类手机自拍照返回的分值不具备参考意义。"
},
"CreateFace": {
"params": [
{
"name": "PersonId",
"desc": "人员ID。"
},
{
"name": "Images",
"desc": "图片 base64 数据。人员人脸总数量不可超过5张。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "Urls",
"desc": "图片的 Url、Image必须提供一个,如果都提供,只使用 Url。\n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。 \n人员人脸总数量不可超过5张。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
}
],
"desc": "将一组人脸图片添加到一个人员中。一个人员最多允许包含 5 张图片。若该人员存在多个人员库中,所有人员库中该人员图片均会增加。\n>\n- 增加人脸完成后,生效时间一般不超过 1 秒,极端情况最多不超过 5 秒,之后您可以进行[人脸搜索](https://cloud.tencent.com/document/product/867/32798)或[人脸验证](https://cloud.tencent.com/document/product/867/32806)。"
},
"GetPersonListNum": {
"params": [
{
"name": "GroupId",
"desc": "人员库ID"
}
],
"desc": "获取指定人员库中人员数量。"
},
"GetPersonGroupInfo": {
"params": [
{
"name": "PersonId",
"desc": "人员ID"
},
{
"name": "Offset",
"desc": "起始序号,默认值为0"
},
{
"name": "Limit",
"desc": "返回数量,默认值为10,最大值为100"
}
],
"desc": "获取指定人员的信息,包括加入的人员库、描述内容等。"
},
"AnalyzeFace": {
"params": [
{
"name": "Mode",
"desc": "检测模式。0 为检测所有出现的人脸, 1 为检测面积最大的人脸。默认为 0。最多返回 10 张人脸的五官定位(人脸关键点)具体信息。"
},
{
"name": "Image",
"desc": "图片 base64 数据。支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "Url",
"desc": "图片的 Url、Image必须提供一个,如果都提供,只使用 Url。 \n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
}
],
"desc": "对请求图片进行五官定位(也称人脸关键点定位),计算构成人脸轮廓的 90 个点,包括眉毛(左右各 8 点)、眼睛(左右各 8 点)、鼻子(13 点)、嘴巴(22 点)、脸型轮廓(21 点)、眼珠[或瞳孔](2点)。"
},
"ModifyPersonBaseInfo": {
"params": [
{
"name": "PersonId",
"desc": "人员ID"
},
{
"name": "PersonName",
"desc": "需要修改的人员名称"
},
{
"name": "Gender",
"desc": "需要修改的人员性别"
}
],
"desc": "修改人员信息,包括名称、性别等。人员名称和性别修改会同步到包含该人员的所有人员库。"
},
"CopyPerson": {
"params": [
{
"name": "PersonId",
"desc": "人员ID"
},
{
"name": "GroupIds",
"desc": "待加入的人员库列表"
}
],
"desc": "将已存在于某人员库的人员复制到其他人员库,该人员的描述信息不会被复制。单个人员最多只能同时存在100个人员库中。"
},
"VerifyFace": {
"params": [
{
"name": "PersonId",
"desc": "待验证的人员ID。人员ID具体信息请参考人员库管理相关接口。"
},
{
"name": "Image",
"desc": "图片 base64 数据。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "Url",
"desc": "图片的 Url 。 图片的 Url、Image必须提供一个,如果都提供,只使用 Url。 \n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
}
],
"desc": "给定一张人脸图片和一个 PersonId,判断图片中的人和 PersonId 对应的人是否为同一人。PersonId 请参考[人员库管理相关接口](https://cloud.tencent.com/document/product/867/32794)。 和[人脸比对](https://cloud.tencent.com/document/product/867/32802)接口不同的是,[人脸验证](https://cloud.tencent.com/document/product/867/32806)用于判断 “此人是否是此人”,“此人”的信息已存于人员库中,“此人”可能存在多张人脸图片;而[人脸比对](https://cloud.tencent.com/document/product/867/32802)用于判断两张人脸的相似度。"
},
"DeleteGroup": {
"params": [
{
"name": "GroupId",
"desc": "人员库ID。"
}
],
"desc": "删除该人员库及包含的所有的人员。同时,人员对应的所有人脸信息将被删除。若某人员同时存在多个人员库中,该人员不会被删除,但属于该人员库中的自定义描述字段信息会被删除。\n\n注:删除人员库的操作为异步执行,删除单张人脸时间约为10ms,即一小时内可以删除36万张。删除期间,无法向该人员库添加人员。"
},
"DeletePerson": {
"params": [
{
"name": "PersonId",
"desc": "人员ID"
}
],
"desc": "删除该人员信息,此操作会导致所有人员库均删除此人员。同时,该人员的所有人脸信息将被删除。"
},
"ModifyGroup": {
"params": [
{
"name": "GroupId",
"desc": "人员库ID"
},
{
"name": "GroupName",
"desc": "人员库名称"
},
{
"name": "GroupExDescriptionInfos",
"desc": "需要修改的人员库自定义描述字段,key-value"
},
{
"name": "Tag",
"desc": "人员库信息备注"
}
],
"desc": "修改人员库名称、备注、自定义描述字段名称。"
},
"CreatePerson": {
"params": [
{
"name": "GroupId",
"desc": "待加入的人员库ID。"
},
{
"name": "PersonName",
"desc": "人员名称。[1,60]个字符,可修改,可重复。"
},
{
"name": "PersonId",
"desc": "人员ID,单个腾讯云账号下不可修改,不可重复。支持英文、数字、-%@#&_,长度限制64B。"
},
{
"name": "Gender",
"desc": "0代表未填写,1代表男性,2代表女性。"
},
{
"name": "PersonExDescriptionInfos",
"desc": "人员描述字段内容,key-value。[0,60]个字符,可修改,可重复。"
},
{
"name": "Image",
"desc": "图片 base64 数据。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "Url",
"desc": "图片的 Url、Image必须提供一个,如果都提供,只使用 Url。\n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
}
],
"desc": "创建人员,添加人脸、姓名、性别及其他相关信息。\n>\n- 创建人员完成后,生效时间一般不超过 1 秒,极端情况最多不超过 5 秒,之后您可以进行[人脸搜索](https://cloud.tencent.com/document/product/867/32798)或[人脸验证](https://cloud.tencent.com/document/product/867/32806)。"
},
"SearchFaces": {
"params": [
{
"name": "GroupIds",
"desc": "希望搜索的人员库列表,上限100个。"
},
{
"name": "Image",
"desc": "图片 base64 数据。支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "Url",
"desc": "图片的 Url、Image必须提供一个,如果都提供,只使用 Url。\n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "MaxFaceNum",
"desc": "最多处理的人脸数目。默认值为1(仅检测图片中面积最大的那张人脸),最大值为10。 \nMaxFaceNum用于,当待识别图片包含多张人脸时,要搜索的人脸数量。 \n当 MaxFaceNum 不为1时,设MaxFaceNum=M,则实际上是 M:N 的人脸搜索。"
},
{
"name": "MinFaceSize",
"desc": "人脸长和宽的最小尺寸,单位为像素。默认为80。低于40将影响搜索精度。建议设置为80。"
},
{
"name": "MaxPersonNum",
"desc": "被检测到的人脸,对应最多返回的最相似人员数目。默认值为5,最大值为10。 \n例,设MaxFaceNum为3,MaxPersonNum为5,则最多可能返回3*5=15个人员。"
}
],
"desc": "用于对一张待识别的人脸图片,在一个或多个人员库中识别出最相似的 TopN 人员,识别结果按照相似度从大到小排序。单次搜索的人员库人脸总数量不得超过 100 万张。\n此接口需与[人员库管理相关接口](https://cloud.tencent.com/document/product/867/32794)结合使用。"
},
"DetectFace": {
"params": [
{
"name": "MaxFaceNum",
"desc": "最多处理的人脸数目。默认值为1(仅检测图片中面积最大的那张人脸),最大值为30。 \n此参数用于控制处理待检测图片中的人脸个数,值越小,处理速度越快。"
},
{
"name": "MinFaceSize",
"desc": "人脸长和宽的最小尺寸,单位为像素。默认为40。低于此尺寸的人脸不会被检测。"
},
{
"name": "Image",
"desc": "图片 base64 数据。支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "Url",
"desc": "图片的 Url、Image必须提供一个,如果都提供,只使用 Url。 \n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "NeedFaceAttributes",
"desc": "是否需要返回人脸属性信息(FaceAttributesInfo)。0 为不需要返回,1 为需要返回。默认为 0。 \n非 1 值均视为不需要返回,此时 FaceAttributesInfo 不具备参考意义。 \n最多返回面积最大的 5 张人脸属性信息,超过 5 张人脸(第 6 张及以后的人脸)的 FaceAttributesInfo 不具备参考意义。 \n提取人脸属性信息较为耗时,如不需要人脸属性信息,建议关闭此项功能,加快人脸检测速度。"
},
{
"name": "NeedQualityDetection",
"desc": "是否开启质量检测。0 为关闭,1 为开启。默认为 0。 \n非 1 值均视为不进行质量检测。 \n建议:人脸入库操作建议开启此功能。"
}
],
"desc": "检测给定图片中的人脸(Face)的位置、相应的面部属性和人脸质量信息,位置包括 (x,y,w,h),面部属性包括性别(gender)、年龄(age)、表情(expression)、魅力(beauty)、眼镜(glass)、发型(hair)、口罩(mask)和姿态 (pitch,roll,yaw),人脸质量信息包括整体质量分(score)、模糊分(sharpness)、光照分(brightness)和五官遮挡分(completeness)。\n\n \n其中,人脸质量信息主要用于评价输入的人脸图片的质量。在使用人脸识别服务时,建议您对输入的人脸图片进行质量检测,提升后续业务处理的效果。该功能的应用场景包括:\n\n1) 人员库[创建人员](https://cloud.tencent.com/document/product/867/32793)/[增加人脸](https://cloud.tencent.com/document/product/867/32795):保证人员人脸信息的质量,便于后续的业务处理。\n\n2) [人脸搜索](https://cloud.tencent.com/document/product/867/32798):保证输入的图片质量,快速准确匹配到对应的人员。\n\n3) [人脸验证](https://cloud.tencent.com/document/product/867/32806):保证人脸信息的质量,避免明明是本人却认证不通过的情况。\n\n4) [人脸融合](https://cloud.tencent.com/product/facefusion):保证上传的人脸质量,人脸融合的效果更好。\n\n"
},
"GetPersonList": {
"params": [
{
"name": "GroupId",
"desc": "人员库ID"
},
{
"name": "Offset",
"desc": "起始序号,默认值为0"
},
{
"name": "Limit",
"desc": "返回数量,默认值为10,最大值为1000"
}
],
"desc": "获取指定人员库中的人员列表。"
},
"ModifyPersonGroupInfo": {
"params": [
{
"name": "GroupId",
"desc": "人员库ID"
},
{
"name": "PersonId",
"desc": "人员ID"
},
{
"name": "PersonExDescriptionInfos",
"desc": "需要修改的人员描述字段内容,key-value"
}
],
"desc": "修改指定人员库人员描述内容。"
},
"CompareFace": {
"params": [
{
"name": "ImageA",
"desc": "A 图片 base64 数据。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "ImageB",
"desc": "B 图片 base64 数据。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "UrlA",
"desc": "A 图片的 Url 。A 图片的 Url、Image必须提供一个,如果都提供,只使用 Url。 \n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
},
{
"name": "UrlB",
"desc": "B 图片的 Url 。B 图片的 Url、Image必须提供一个,如果都提供,只使用 Url。 \n图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。 \n非腾讯云存储的Url速度和稳定性可能受一定影响。\n若图片中包含多张人脸,只选取其中人脸面积最大的人脸。\n支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。"
}
],
"desc": "对两张图片中的人脸进行相似度比对,返回人脸相似度分数。\n\n若您需要判断 “此人是否是某人”,即验证某张图片中的人是否是已知身份的某人,如常见的人脸登录场景,建议使用[人脸验证](https://cloud.tencent.com/document/product/867/32806)接口。\n\n若您需要判断图片中人脸的具体身份信息,如是否是身份证上对应的人,建议使用[人脸核身·云智慧眼](https://cloud.tencent.com/product/facein)产品。"
},
"GetGroupList": {
"params": [
{
"name": "Offset",
"desc": "起始序号,默认值为0"
},
{
"name": "Limit",
"desc": "返回数量,默认值为10,最大值为1000"
}
],
"desc": "获取人员库列表。"
},
"DeleteFace": {
"params": [
{
"name": "PersonId",
"desc": "人员ID"
},
{
"name": "FaceIds",
"desc": "待删除的人脸ID列表"
}
],
"desc": "删除一个人员下的人脸图片。如果该人员只有一张人脸图片,则返回错误。"
}
} |
# Numpy is imported; seed is set
# Initialize all_walks (don't change this line)
all_walks = []
# Simulate random walk 10 times
for i in range(10) :
# Code from before
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
random_walk.append(step)
# Append random_walk to all_walks
all_walks.append(random_walk)
# Print all_walks
print(all_walks)
# numpy and matplotlib imported, seed set.
# initialize and populate all_walks
all_walks = []
for i in range(10) :
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
random_walk.append(step)
all_walks.append(random_walk)
# Convert all_walks to Numpy array: np_aw
np_aw = np.array(all_walks)
# Plot np_aw and show
plt.plot(np_aw)
plt.show()
# Clear the figure
plt.clf()
# Transpose np_aw: np_aw_t
np_aw_t = np.transpose(np_aw)
# Plot np_aw_t and show
plt.plot(np_aw_t)
plt.show()
# numpy and matplotlib imported, seed set
# Simulate random walk 250 times
all_walks = []
for i in range(250) :
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
# Implement clumsiness
if np.random.rand() <= 0.001 :
step = 0
random_walk.append(step)
all_walks.append(random_walk)
# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
plt.plot(np_aw_t)
plt.show()
# numpy and matplotlib imported, seed set
# Simulate random walk 500 times
all_walks = []
for i in range(500) :
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
if np.random.rand() <= 0.001 :
step = 0
random_walk.append(step)
all_walks.append(random_walk)
# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
# Select last row from np_aw_t: ends
ends = np_aw_t[-1,:]
# Plot histogram of ends, display plot
plt.hist(ends)
plt.show()
|
# A file to test if pyvm works from the command line.
def it_works():
print("Success!")
it_works()
|
n = "Hello"
# Your function here!
def string_function(s):
return s + 'world'
print(string_function(n))
|
#this software is a copyrighted product made by laba.not for resell. all right reserved.date-7th may 2018. one of the 1st software made by laba.
print("Welcome to Personal dictionary by laba.\nThis ugliest software is made by most handsome man alive name laba.")
print("\nThis software aims to make your process for learning new words easy. \nJust add a new word and a note describing it. Revice twice a day.")
words = []
notes = []
def word_entry(word):
w_entry = {"word": word}
words.append(w_entry)
def note_entry(note):
n_entry = {"note": note}
notes.append(n_entry)
def inputf():
word_input = input("Enter the word you wanna add: ")
note_input = input("Enter description note: ")
word_entry(word_input)
note_entry(note_input)
save_file(word_input, note_input)
def save_file(word, note):
try:
f = open("log.txt", "a")
f.write(word + " - " + note + "\n")
f.close()
except Exception:
print("uh oh! fucked up while saving \ntrying to unfuck...")
def read_file():
try:
f = open("log.txt", "r")
print("\nWORD - NOTE\n")
"""generator function"""
def read_lines(f):
for line in f:
yield line
for entry in read_lines(f):
print(entry)
f.close()
except Exception:
ask = input("\nHey niggah, how are you doin? using this software for 1st time? \nDon't worry its easy to use. \nTo add a new word in your personal dictionary Type Y ;-D - ")
if (ask == "Y"):
inputf()
print("see its easy!!")
else:
print("capital Y niggah ;-|")
read_file()
num = 1
while (num == 1):
ask_again = input("Wanna add more word? type Y for yes, N for exit - ")
if ask_again == "Y":
inputf()
continue
elif ask_again == "y":
print("fucking fuuuuuck... are you fuckin blind? or trying to break my software ? can't read a simple instruction? type CAPITAL Y.")
else:
break |
# Final Exam, Problem 4 - 2
def longestRun(L):
'''
Assumes L is a non-empty list
Returns the length of the longest monotonically increasing
'''
maxRun = 0
tempRun = 0
for i in range(len(L) - 1):
if L[i + 1] >= L[i]:
tempRun += 1
if tempRun > maxRun:
maxRun = tempRun
else:
tempRun = 0
return maxRun + 1 |
#
# @lc app=leetcode id=415 lang=python3
#
# [415] Add Strings
#
# https://leetcode.com/problems/add-strings/description/
#
# algorithms
# Easy (51.34%)
# Likes: 2772
# Dislikes: 495
# Total Accepted: 421.8K
# Total Submissions: 820.4K
# Testcase Example: '"11"\n"123"'
#
# Given two non-negative integers, num1 and num2 represented as string, return
# the sum of num1 and num2 as a string.
#
# You must solve the problem without using any built-in library for handling
# large integers (such as BigInteger). You must also not convert the inputs to
# integers directly.
#
#
# Example 1:
#
#
# Input: num1 = "11", num2 = "123"
# Output: "134"
#
#
# Example 2:
#
#
# Input: num1 = "456", num2 = "77"
# Output: "533"
#
#
# Example 3:
#
#
# Input: num1 = "0", num2 = "0"
# Output: "0"
#
#
#
# Constraints:
#
#
# 1 <= num1.length, num2.length <= 10^4
# num1 and num2 consist of only digits.
# num1 and num2 don't have any leading zeros except for the zero itself.
#
#
#
# @lc code=start
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
ans = int(num1) + int(num2)
return str(ans)
# @lc code=end
|
def landscaper(f, generations):
seen_states = {}
states = []
state = f.readline().strip().split(' ')[-1]
f.readline()
rules = {}
idx = 0
prev_sum = None
for rule in f.readlines():
keys, _, res = rule.strip().split(' ')
if res == '#':
rules[keys] = True
for i in range(0, generations):
first_hash = state.index('#')
if first_hash < 5:
adds = 5 - first_hash
state = '.' * adds + state
idx -= adds
last_hash = state.rindex('#')
if last_hash > (len(state) - 5):
state += '.' * (6 - abs(last_hash - len(state)))
output = state[:2]
for x in range(2, len(state) - 2):
output += '#' if state[x-2:x+3] in rules else '.'
output += state[len(state) - 2:]
state = output
k = state.strip('.')
if k in seen_states:
current = sum_state(state, idx)
if prev_sum:
diff = current - prev_sum
return current + diff * (generations - seen_states[k][0] - 2)
prev_sum = current
seen_states[k] = (i, idx)
states.append(state)
return sum_state(state, idx)
def sum_state(state, idx):
s = 0
for i in range(0, len(state)):
add = (i + idx) if state[i] == '#' else 0
s += add
return s
def test_landscaper():
assert landscaper(open('input/12.test'), 20) == 325
if __name__ == '__main__':
print(landscaper(open('input/12'), 20))
print(landscaper(open('input/12'), 128))
print(landscaper(open('input/12'), 50_000_000_000))
|
# printing out a string
print("lol")
# printing out a space betwin them (\n)
print("Hello\nWorld")
# if you want to put a (") inside do this:
print("Hello\"World\"")
# if you want to put a (\) inside just type:
print("Hello\World")
# you can also print a variable like this;
lol = "Hello World"
print(lol)
# you can also do something called cencatenation who is putting a string whit some text like this;
lol = "Hello World"
print(lol + " Hello World")
# you can also use fonctions to change info or to know info about a sring. exemple of fonctions;
lol = "Hello World"
# puts every thing small or decapitelize
print(lol.lower())
# capitelize everything
print(lol.upper())
# boolean is it all cap.
print(lol.isupper())
# 2 same time
print(lol.upper().isupper())
# tells you lhe length
print(len(lol))
# this fonction shows a letter of the string(0 for "H", 1 for "e" exetera).
lol = "Hello World"
print(lol[0])
print(lol[1])
# you can return the index (the position of a letter)by doing this:
print(lol.index("d"))
# you can also replace a word in your string like this:
print(lol.replace("World", "dude"))
|
def funcao(x = 1,y = 1):
return 2*x+y
print(funcao(2,3))
print(funcao(3,2))
print(funcao(1,2)) |
'''
author: Iuri Freire
e-mail: iuricostafreire at gmail dot com
local date : 2021-01-07
local time : 20:47
'''
|
# -*- coding: utf-8 -*-
"""
snaplayer
~~~~~~~~
The very basics
:copyright: (c) 2015 by Alejandro Ricoveri
:license: MIT, see LICENSE for more details.
"""
PKG_URL = 'https://github.com/axltxl/snaplayer'
__name__ = 'snaplayer'
__author__ = 'Alejandro Ricoveri'
__version__ = '0.1.1'
__licence__ = 'MIT'
__copyright__ = 'Copyright (c) Alejandro Ricoveri'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.